@cyfsh/discovery 0.1.1 → 0.3.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.
- package/dist/index.d.ts +29 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +319 -49
- package/dist/index.js.map +1 -1
- package/dist/sanitizer.d.ts.map +1 -1
- package/dist/sanitizer.js +9 -4
- package/dist/sanitizer.js.map +1 -1
- package/dist/scanners/claude.d.ts +4 -1
- package/dist/scanners/claude.d.ts.map +1 -1
- package/dist/scanners/claude.js +90 -44
- package/dist/scanners/claude.js.map +1 -1
- package/dist/scanners/codebuddy.d.ts +4 -1
- package/dist/scanners/codebuddy.d.ts.map +1 -1
- package/dist/scanners/codebuddy.js +194 -52
- package/dist/scanners/codebuddy.js.map +1 -1
- package/dist/scanners/codex.d.ts +4 -1
- package/dist/scanners/codex.d.ts.map +1 -1
- package/dist/scanners/codex.js +112 -44
- package/dist/scanners/codex.js.map +1 -1
- package/dist/scanners/common.d.ts +79 -0
- package/dist/scanners/common.d.ts.map +1 -1
- package/dist/scanners/common.js +447 -20
- package/dist/scanners/common.js.map +1 -1
- package/dist/scanners/dsh.d.ts +5 -1
- package/dist/scanners/dsh.d.ts.map +1 -1
- package/dist/scanners/dsh.js +209 -85
- package/dist/scanners/dsh.js.map +1 -1
- package/dist/scanners/opencode.d.ts +10 -1
- package/dist/scanners/opencode.d.ts.map +1 -1
- package/dist/scanners/opencode.js +612 -293
- package/dist/scanners/opencode.js.map +1 -1
- package/package.json +2 -2
|
@@ -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, isPlaceholderSessionTitle, isRegularFile, parseTimestampToIso, runWithConcurrency, safeStatDates, sanitizeAndFilterUserPrompt, 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
|
|
70
|
+
export async function computeSqliteSignature(dbPath) {
|
|
71
71
|
try {
|
|
72
|
-
const
|
|
72
|
+
const mainStat = await fsp.stat(dbPath);
|
|
73
|
+
let walPart = "0:0";
|
|
73
74
|
try {
|
|
74
|
-
|
|
75
|
+
const walStat = await fsp.stat(`${dbPath}-wal`);
|
|
76
|
+
walPart = `${walStat.mtimeMs}:${walStat.size}`;
|
|
75
77
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
+
catch {
|
|
79
|
+
// No WAL sidecar present
|
|
78
80
|
}
|
|
81
|
+
return `${mainStat.mtimeMs}:${mainStat.size}:${walPart}`;
|
|
79
82
|
}
|
|
80
83
|
catch {
|
|
81
|
-
|
|
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:
|
|
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
|
|
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
|
-
|
|
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
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
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,628 @@ function extractSessionsFromOpenCodeDb(db, dbPath, fallbackIso) {
|
|
|
142
202
|
...(gitBranch ? { gitBranch } : {}),
|
|
143
203
|
});
|
|
144
204
|
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
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
|
-
|
|
165
|
-
const
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
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
|
-
|
|
176
|
-
|
|
177
|
-
|
|
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
|
-
|
|
180
|
-
|
|
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
|
|
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
|
|
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
|
|
278
|
+
const workspacePath = rawWorkspace.trim() || "/unknown-workspace";
|
|
279
|
+
const workspaceName = extractWorkspaceName(workspacePath);
|
|
280
|
+
let explicitTitle = sqlValToString(sRow.title) ?? asNonEmptyString(sData?.title);
|
|
281
|
+
if (explicitTitle && isPlaceholderSessionTitle(explicitTitle)) {
|
|
282
|
+
explicitTitle = undefined;
|
|
283
|
+
}
|
|
284
|
+
// Touch `part` with LIMIT 6 when session has no real explicit title (or had `New session - ...`)
|
|
285
|
+
if (!explicitTitle && partCols.has("session_id") && partCols.has("data")) {
|
|
286
|
+
const sampleParts = db
|
|
287
|
+
.prepare('SELECT "data" FROM "part" WHERE "session_id" = ? LIMIT 6')
|
|
288
|
+
.all(rawSessionId);
|
|
289
|
+
for (const sp of sampleParts) {
|
|
290
|
+
const pd = parseJsonColumn(sp.data);
|
|
291
|
+
if ((pd?.type === "text" || !pd?.type) && typeof pd?.text === "string" && pd.text.trim()) {
|
|
292
|
+
const cleaned = sanitizeAndFilterUserPrompt(pd.text);
|
|
293
|
+
if (cleaned) {
|
|
294
|
+
explicitTitle = cleaned;
|
|
295
|
+
break;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
if (explicitTitle && /^\[CE_BTW_SIDE_QUERY\]/i.test(explicitTitle.trim())) {
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
203
303
|
const gitBranch = sqlValToString(sRow.git_branch) ??
|
|
204
304
|
sqlValToString(sRow.branch) ??
|
|
205
305
|
asNonEmptyString(sData?.gitBranch) ??
|
|
206
306
|
projectInfo?.gitBranch;
|
|
207
|
-
|
|
307
|
+
const model = sqlValToString(sRow.model) ?? asNonEmptyString(sData?.modelID);
|
|
208
308
|
const sTimeObj = isJsonRecord(sData?.time) ? sData.time : undefined;
|
|
209
|
-
const
|
|
210
|
-
const
|
|
211
|
-
const
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
309
|
+
const createdAt = parseTimestampToIso(sRow.time_created ?? sRow.created_at ?? sTimeObj?.created, fallbackIso);
|
|
310
|
+
const updatedAt = parseTimestampToIso(sRow.time_updated ?? sRow.updated_at ?? sTimeObj?.updated, createdAt);
|
|
311
|
+
const title = deriveSessionTitle(explicitTitle, [], workspaceName, rawSessionId);
|
|
312
|
+
summaries.push({
|
|
313
|
+
id: `opencode:${rawSessionId}`,
|
|
314
|
+
rawSessionId,
|
|
315
|
+
engine: "opencode",
|
|
316
|
+
title,
|
|
317
|
+
workspacePath,
|
|
318
|
+
workspaceName,
|
|
319
|
+
sourcePath: dbPath,
|
|
320
|
+
messageCount: msgCount,
|
|
321
|
+
createdAt,
|
|
322
|
+
updatedAt,
|
|
323
|
+
...(gitBranch ? { gitBranch } : {}),
|
|
324
|
+
...(model ? { model } : {}),
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
return summaries;
|
|
328
|
+
}
|
|
329
|
+
function parseSingleSessionFromOpenCodeDb(db, dbPath, targetRawSessionId, fallbackIso) {
|
|
330
|
+
const sRows = selectProjectedColumns(db, "session", LIGHTWEIGHT_SESSION_COLS, 'WHERE "id" = ?', [targetRawSessionId]);
|
|
331
|
+
const sRow = sRows[0];
|
|
332
|
+
if (!sRow) {
|
|
333
|
+
return null;
|
|
334
|
+
}
|
|
335
|
+
const sData = parseJsonColumn(sRow.data);
|
|
336
|
+
const projectId = sqlValToString(sRow.project_id) ??
|
|
337
|
+
sqlValToString(sRow.projectID) ??
|
|
338
|
+
asNonEmptyString(sData?.projectID) ??
|
|
339
|
+
asNonEmptyString(sData?.project_id);
|
|
340
|
+
let projectInfo;
|
|
341
|
+
if (projectId) {
|
|
342
|
+
const pRows = selectProjectedColumns(db, "project", LIGHTWEIGHT_PROJECT_COLS, 'WHERE "id" = ?', [projectId]);
|
|
343
|
+
const pRow = pRows[0];
|
|
344
|
+
if (pRow) {
|
|
345
|
+
const pData = parseJsonColumn(pRow.data);
|
|
346
|
+
const worktree = sqlValToString(pRow.worktree) ??
|
|
347
|
+
sqlValToString(pRow.directory) ??
|
|
348
|
+
sqlValToString(pRow.cwd) ??
|
|
349
|
+
sqlValToString(pRow.path) ??
|
|
350
|
+
asNonEmptyString(pData?.worktree) ??
|
|
351
|
+
asNonEmptyString(pData?.directory) ??
|
|
352
|
+
"";
|
|
353
|
+
const gitBranch = sqlValToString(pRow.git_branch) ??
|
|
354
|
+
sqlValToString(pRow.branch) ??
|
|
355
|
+
asNonEmptyString(pData?.branch);
|
|
356
|
+
projectInfo = { worktree, ...(gitBranch ? { gitBranch } : {}) };
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
const workspacePath = sqlValToString(sRow.directory) ??
|
|
360
|
+
sqlValToString(sRow.cwd) ??
|
|
361
|
+
sqlValToString(sRow.workspace_path) ??
|
|
362
|
+
asNonEmptyString(sData?.directory) ??
|
|
363
|
+
asNonEmptyString(sData?.cwd) ??
|
|
364
|
+
projectInfo?.worktree ??
|
|
365
|
+
"/unknown-workspace";
|
|
366
|
+
const explicitTitle = sqlValToString(sRow.title) ?? asNonEmptyString(sData?.title);
|
|
367
|
+
const gitBranch = sqlValToString(sRow.git_branch) ??
|
|
368
|
+
sqlValToString(sRow.branch) ??
|
|
369
|
+
asNonEmptyString(sData?.gitBranch) ??
|
|
370
|
+
projectInfo?.gitBranch;
|
|
371
|
+
let sessionModel = sqlValToString(sRow.model) ?? asNonEmptyString(sData?.modelID);
|
|
372
|
+
const sTimeObj = isJsonRecord(sData?.time) ? sData.time : undefined;
|
|
373
|
+
const sessionCreatedIso = parseTimestampToIso(sRow.time_created ?? sRow.created_at ?? sTimeObj?.created, fallbackIso);
|
|
374
|
+
const sessionUpdatedIso = parseTimestampToIso(sRow.time_updated ?? sRow.updated_at ?? sTimeObj?.updated, sessionCreatedIso);
|
|
375
|
+
const msgCols = getTableColumns(db, "message");
|
|
376
|
+
let sMsgRows = [];
|
|
377
|
+
if (msgCols.has("session_id")) {
|
|
378
|
+
sMsgRows = db
|
|
379
|
+
.prepare('SELECT * FROM "message" WHERE "session_id" = ?')
|
|
380
|
+
.all(targetRawSessionId);
|
|
381
|
+
}
|
|
382
|
+
else if (msgCols.has("sessionID")) {
|
|
383
|
+
sMsgRows = db
|
|
384
|
+
.prepare('SELECT * FROM "message" WHERE "sessionID" = ?')
|
|
385
|
+
.all(targetRawSessionId);
|
|
386
|
+
}
|
|
387
|
+
else if (msgCols.size > 0) {
|
|
388
|
+
const allMsgs = db.prepare('SELECT * FROM "message"').all();
|
|
389
|
+
sMsgRows = allMsgs.filter((m) => {
|
|
390
|
+
const md = parseJsonColumn(m.data);
|
|
391
|
+
return (asNonEmptyString(md?.sessionID) ?? asNonEmptyString(md?.session_id)) === targetRawSessionId;
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
sMsgRows.sort((a, b) => {
|
|
395
|
+
const aTime = Number(a.time_created ?? a.created_at ?? 0);
|
|
396
|
+
const bTime = Number(b.time_created ?? b.created_at ?? 0);
|
|
397
|
+
if (Number.isFinite(aTime) && Number.isFinite(bTime) && aTime !== bTime) {
|
|
398
|
+
return aTime - bTime;
|
|
399
|
+
}
|
|
400
|
+
return 0;
|
|
401
|
+
});
|
|
402
|
+
const partCols = getTableColumns(db, "part");
|
|
403
|
+
let partRows = [];
|
|
404
|
+
if (partCols.has("session_id")) {
|
|
405
|
+
partRows = db
|
|
406
|
+
.prepare('SELECT * FROM "part" WHERE "session_id" = ?')
|
|
407
|
+
.all(targetRawSessionId);
|
|
408
|
+
}
|
|
409
|
+
else if (partCols.has("message_id") && sMsgRows.length > 0) {
|
|
410
|
+
const msgIds = sMsgRows
|
|
411
|
+
.map((m) => sqlValToString(m.id))
|
|
412
|
+
.filter((id) => Boolean(id));
|
|
413
|
+
if (msgIds.length > 0) {
|
|
414
|
+
const placeholders = msgIds.map(() => "?").join(", ");
|
|
415
|
+
partRows = db
|
|
416
|
+
.prepare(`SELECT * FROM "part" WHERE "message_id" IN (${placeholders})`)
|
|
417
|
+
.all(...msgIds);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
const partsByMessageId = new Map();
|
|
421
|
+
for (const partRow of partRows) {
|
|
422
|
+
const pData = parseJsonColumn(partRow.data);
|
|
423
|
+
const msgId = sqlValToString(partRow.message_id) ??
|
|
424
|
+
sqlValToString(partRow.messageID) ??
|
|
425
|
+
asNonEmptyString(pData?.messageID) ??
|
|
426
|
+
asNonEmptyString(pData?.message_id);
|
|
427
|
+
if (!msgId) {
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
430
|
+
const bucket = partsByMessageId.get(msgId);
|
|
431
|
+
if (bucket) {
|
|
432
|
+
bucket.push(partRow);
|
|
433
|
+
}
|
|
434
|
+
else {
|
|
435
|
+
partsByMessageId.set(msgId, [partRow]);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
const parsedMessages = [];
|
|
439
|
+
for (let mIdx = 0; mIdx < sMsgRows.length; mIdx += 1) {
|
|
440
|
+
const mRow = sMsgRows[mIdx];
|
|
441
|
+
if (!mRow) {
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
const msgId = sqlValToString(mRow.id) ?? `${targetRawSessionId}-msg-${mIdx + 1}`;
|
|
445
|
+
const mData = parseJsonColumn(mRow.data);
|
|
446
|
+
const roleStr = sqlValToString(mRow.role) ?? asNonEmptyString(mData?.role);
|
|
447
|
+
if (roleStr !== "user" && roleStr !== "assistant" && roleStr !== "system") {
|
|
448
|
+
continue;
|
|
449
|
+
}
|
|
450
|
+
const rowModel = sqlValToString(mRow.model) ??
|
|
451
|
+
asNonEmptyString(mData?.modelID) ??
|
|
452
|
+
(isJsonRecord(mData?.model)
|
|
453
|
+
? asNonEmptyString(mData.model.modelID)
|
|
454
|
+
: undefined);
|
|
455
|
+
if (rowModel) {
|
|
456
|
+
sessionModel = rowModel;
|
|
457
|
+
}
|
|
458
|
+
const mTimeObj = isJsonRecord(mData?.time) ? mData.time : undefined;
|
|
459
|
+
const msgTimestamp = parseTimestampToIso(mRow.time_created ?? mRow.created_at ?? mTimeObj?.created, sessionUpdatedIso);
|
|
460
|
+
const textChunks = [];
|
|
461
|
+
const thinkingChunks = [];
|
|
462
|
+
const toolCalls = [];
|
|
463
|
+
const directMsgContent = sqlValToString(mRow.content) ?? asNonEmptyString(mData?.content);
|
|
464
|
+
if (directMsgContent) {
|
|
465
|
+
textChunks.push(directMsgContent);
|
|
466
|
+
}
|
|
467
|
+
const directThinking = sqlValToString(mRow.thinking) ?? asNonEmptyString(mData?.thinking);
|
|
468
|
+
if (directThinking) {
|
|
469
|
+
thinkingChunks.push(directThinking);
|
|
470
|
+
}
|
|
471
|
+
const msgParts = partsByMessageId.get(msgId) ?? [];
|
|
472
|
+
msgParts.sort((a, b) => {
|
|
473
|
+
const aTime = Number(a.time_created ?? a.created_at ?? a.sort_order ?? 0);
|
|
474
|
+
const bTime = Number(b.time_created ?? b.created_at ?? b.sort_order ?? 0);
|
|
215
475
|
if (Number.isFinite(aTime) && Number.isFinite(bTime) && aTime !== bTime) {
|
|
216
476
|
return aTime - bTime;
|
|
217
477
|
}
|
|
218
478
|
return 0;
|
|
219
479
|
});
|
|
220
|
-
const
|
|
221
|
-
|
|
222
|
-
const
|
|
223
|
-
if (
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
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));
|
|
480
|
+
for (const partRow of msgParts) {
|
|
481
|
+
const pData = parseJsonColumn(partRow.data);
|
|
482
|
+
const partType = sqlValToString(partRow.type) ?? asNonEmptyString(pData?.type) ?? "text";
|
|
483
|
+
if (partType === "text") {
|
|
484
|
+
const txt = sqlValToString(partRow.text) ??
|
|
485
|
+
sqlValToString(partRow.content) ??
|
|
486
|
+
asNonEmptyString(pData?.text) ??
|
|
487
|
+
asNonEmptyString(pData?.content);
|
|
488
|
+
if (txt && !textChunks.includes(txt)) {
|
|
489
|
+
textChunks.push(txt);
|
|
299
490
|
}
|
|
300
491
|
}
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
492
|
+
else if (partType === "reasoning" || partType === "thinking") {
|
|
493
|
+
const thought = sqlValToString(partRow.text) ??
|
|
494
|
+
sqlValToString(partRow.content) ??
|
|
495
|
+
asNonEmptyString(pData?.text) ??
|
|
496
|
+
asNonEmptyString(pData?.thinking);
|
|
497
|
+
if (thought) {
|
|
498
|
+
thinkingChunks.push(thought);
|
|
499
|
+
}
|
|
304
500
|
}
|
|
305
|
-
if (
|
|
306
|
-
|
|
501
|
+
else if (partType === "tool" ||
|
|
502
|
+
partType === "tool_use" ||
|
|
503
|
+
partType === "tool-invocation" ||
|
|
504
|
+
partType === "tool_call") {
|
|
505
|
+
const toolName = sqlValToString(partRow.tool_name) ??
|
|
506
|
+
sqlValToString(partRow.name) ??
|
|
507
|
+
asNonEmptyString(pData?.tool) ??
|
|
508
|
+
asNonEmptyString(pData?.name) ??
|
|
509
|
+
"tool";
|
|
510
|
+
const stateRec = isJsonRecord(pData?.state) ? pData.state : undefined;
|
|
511
|
+
const toolInput = partRow.tool_input ??
|
|
512
|
+
partRow.input ??
|
|
513
|
+
stateRec?.input ??
|
|
514
|
+
pData?.input ??
|
|
515
|
+
pData?.args;
|
|
516
|
+
toolCalls.push(summarizeToolCall(toolName, toolInput));
|
|
307
517
|
}
|
|
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
518
|
}
|
|
318
|
-
const
|
|
319
|
-
|
|
320
|
-
|
|
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);
|
|
519
|
+
const finalContent = textChunks.join("\n").trim();
|
|
520
|
+
if (!finalContent && thinkingChunks.length === 0 && toolCalls.length === 0) {
|
|
521
|
+
continue;
|
|
332
522
|
}
|
|
523
|
+
const thinkingSummary = summarizeThinking(thinkingChunks.join("\n"));
|
|
524
|
+
parsedMessages.push({
|
|
525
|
+
id: msgId,
|
|
526
|
+
role: roleStr,
|
|
527
|
+
content: finalContent,
|
|
528
|
+
timestamp: msgTimestamp,
|
|
529
|
+
...(thinkingSummary ? { thinkingSummary } : {}),
|
|
530
|
+
...(toolCalls.length > 0 ? { toolCalls } : {}),
|
|
531
|
+
});
|
|
333
532
|
}
|
|
334
|
-
return
|
|
533
|
+
return finalizeDiscoveredSession({
|
|
534
|
+
engine: "opencode",
|
|
535
|
+
rawSessionId: targetRawSessionId,
|
|
536
|
+
explicitTitle,
|
|
537
|
+
workspacePath,
|
|
538
|
+
sourcePath: dbPath,
|
|
539
|
+
messages: parsedMessages,
|
|
540
|
+
fallbackCreatedAt: sessionCreatedIso,
|
|
541
|
+
fallbackUpdatedAt: sessionUpdatedIso,
|
|
542
|
+
gitBranch,
|
|
543
|
+
model: sessionModel,
|
|
544
|
+
});
|
|
335
545
|
}
|
|
336
|
-
async function
|
|
546
|
+
async function parseLegacyOpenCodeJsonFile(sFile, sessionDir, includeDetails) {
|
|
337
547
|
const storageRoot = path.dirname(sessionDir);
|
|
338
548
|
const messageRoot = path.join(storageRoot, "message");
|
|
339
549
|
const partRoot = path.join(storageRoot, "part");
|
|
340
|
-
const
|
|
341
|
-
const
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
550
|
+
const raw = await fsp.readFile(sFile, "utf8");
|
|
551
|
+
const parsed = JSON.parse(raw);
|
|
552
|
+
if (!isJsonRecord(parsed)) {
|
|
553
|
+
return { summary: null, detail: null };
|
|
554
|
+
}
|
|
555
|
+
const rawSessionId = asNonEmptyString(parsed.id) ?? path.basename(sFile, ".json");
|
|
556
|
+
const workspacePath = asNonEmptyString(parsed.directory) ??
|
|
557
|
+
asNonEmptyString(parsed.cwd) ??
|
|
558
|
+
asNonEmptyString(parsed.worktree) ??
|
|
559
|
+
"/unknown-workspace";
|
|
560
|
+
const explicitTitle = asNonEmptyString(parsed.title);
|
|
561
|
+
const gitBranch = asNonEmptyString(parsed.gitBranch) ?? asNonEmptyString(parsed.branch);
|
|
562
|
+
let model = asNonEmptyString(parsed.model) ?? asNonEmptyString(parsed.modelID);
|
|
563
|
+
const { createdAt, updatedAt } = await safeStatDates(sFile);
|
|
564
|
+
const messages = [];
|
|
565
|
+
if (Array.isArray(parsed.messages)) {
|
|
566
|
+
for (let idx = 0; idx < parsed.messages.length; idx += 1) {
|
|
567
|
+
const item = parsed.messages[idx];
|
|
568
|
+
if (!isJsonRecord(item)) {
|
|
347
569
|
continue;
|
|
348
570
|
}
|
|
349
|
-
const
|
|
350
|
-
const
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
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
|
-
}
|
|
571
|
+
const role = asNonEmptyString(item.role);
|
|
572
|
+
const content = asNonEmptyString(item.content) ?? asNonEmptyString(item.text);
|
|
573
|
+
if ((role === "user" || role === "assistant") && content) {
|
|
574
|
+
const ts = parseTimestampToIso(item.timestamp ?? item.createdAt, updatedAt);
|
|
575
|
+
const thinkingSummary = includeDetails
|
|
576
|
+
? summarizeThinking(asNonEmptyString(item.thinking) ?? "")
|
|
577
|
+
: undefined;
|
|
578
|
+
messages.push({
|
|
579
|
+
id: asNonEmptyString(item.id) ?? `${rawSessionId}-legacy-${idx + 1}`,
|
|
580
|
+
role,
|
|
581
|
+
content,
|
|
582
|
+
timestamp: ts,
|
|
583
|
+
...(thinkingSummary ? { thinkingSummary } : {}),
|
|
584
|
+
});
|
|
437
585
|
}
|
|
438
|
-
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
const perSessionMsgDir = path.join(messageRoot, rawSessionId);
|
|
589
|
+
if (messages.length === 0 && (await isDirectory(perSessionMsgDir))) {
|
|
590
|
+
const msgFiles = await walkFiles(perSessionMsgDir, (_f, name) => name.endsWith(".json"), 2);
|
|
591
|
+
if (!includeDetails && explicitTitle && msgFiles.length > 0) {
|
|
592
|
+
const summary = finalizeSessionSummary({
|
|
439
593
|
engine: "opencode",
|
|
440
594
|
rawSessionId,
|
|
441
595
|
explicitTitle,
|
|
442
596
|
workspacePath,
|
|
443
597
|
sourcePath: sFile,
|
|
444
|
-
messages,
|
|
598
|
+
messages: [],
|
|
599
|
+
estimatedMessageCount: msgFiles.length,
|
|
445
600
|
fallbackCreatedAt: createdAt,
|
|
446
601
|
fallbackUpdatedAt: updatedAt,
|
|
447
602
|
gitBranch,
|
|
448
603
|
model,
|
|
449
604
|
});
|
|
450
|
-
|
|
451
|
-
|
|
605
|
+
return { summary, detail: null };
|
|
606
|
+
}
|
|
607
|
+
msgFiles.sort();
|
|
608
|
+
for (let idx = 0; idx < msgFiles.length; idx += 1) {
|
|
609
|
+
const mf = msgFiles[idx];
|
|
610
|
+
if (!mf) {
|
|
611
|
+
continue;
|
|
612
|
+
}
|
|
613
|
+
const mRaw = await fsp.readFile(mf, "utf8");
|
|
614
|
+
const mObj = JSON.parse(mRaw);
|
|
615
|
+
if (!isJsonRecord(mObj)) {
|
|
616
|
+
continue;
|
|
617
|
+
}
|
|
618
|
+
const msgId = asNonEmptyString(mObj.id) ?? path.basename(mf, ".json");
|
|
619
|
+
const role = asNonEmptyString(mObj.role);
|
|
620
|
+
if (role !== "user" && role !== "assistant") {
|
|
621
|
+
continue;
|
|
622
|
+
}
|
|
623
|
+
const mModel = asNonEmptyString(mObj.modelID) ?? asNonEmptyString(mObj.model);
|
|
624
|
+
if (mModel) {
|
|
625
|
+
model = mModel;
|
|
626
|
+
}
|
|
627
|
+
const timeObj = isJsonRecord(mObj.time) ? mObj.time : undefined;
|
|
628
|
+
const ts = parseTimestampToIso(timeObj?.created ?? mObj.createdAt, updatedAt);
|
|
629
|
+
const textChunks = [];
|
|
630
|
+
const directContent = asNonEmptyString(mObj.content);
|
|
631
|
+
if (directContent) {
|
|
632
|
+
textChunks.push(directContent);
|
|
633
|
+
}
|
|
634
|
+
const perMsgPartDir = path.join(partRoot, msgId);
|
|
635
|
+
if (await isDirectory(perMsgPartDir)) {
|
|
636
|
+
const partFiles = await walkFiles(perMsgPartDir, (_f, name) => name.endsWith(".json"), 2);
|
|
637
|
+
partFiles.sort();
|
|
638
|
+
for (const pf of partFiles) {
|
|
639
|
+
const pRaw = await fsp.readFile(pf, "utf8");
|
|
640
|
+
const pObj = JSON.parse(pRaw);
|
|
641
|
+
if (isJsonRecord(pObj)) {
|
|
642
|
+
const txt = asNonEmptyString(pObj.text) ?? asNonEmptyString(pObj.content);
|
|
643
|
+
if (txt) {
|
|
644
|
+
textChunks.push(txt);
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
const joined = textChunks.join("\n").trim();
|
|
650
|
+
if (joined) {
|
|
651
|
+
messages.push({
|
|
652
|
+
id: msgId,
|
|
653
|
+
role,
|
|
654
|
+
content: joined,
|
|
655
|
+
timestamp: ts,
|
|
656
|
+
});
|
|
452
657
|
}
|
|
453
658
|
}
|
|
454
|
-
|
|
455
|
-
|
|
659
|
+
}
|
|
660
|
+
const baseParams = {
|
|
661
|
+
engine: "opencode",
|
|
662
|
+
rawSessionId,
|
|
663
|
+
explicitTitle,
|
|
664
|
+
workspacePath,
|
|
665
|
+
sourcePath: sFile,
|
|
666
|
+
messages,
|
|
667
|
+
fallbackCreatedAt: createdAt,
|
|
668
|
+
fallbackUpdatedAt: updatedAt,
|
|
669
|
+
gitBranch,
|
|
670
|
+
model,
|
|
671
|
+
};
|
|
672
|
+
if (includeDetails) {
|
|
673
|
+
const detail = finalizeDiscoveredSession(baseParams);
|
|
674
|
+
return { summary: detail, detail };
|
|
675
|
+
}
|
|
676
|
+
return { summary: finalizeSessionSummary(baseParams), detail: null };
|
|
677
|
+
}
|
|
678
|
+
export async function readOpenCodeSessionDetail(sourcePath, rawSessionId) {
|
|
679
|
+
if (sourcePath.endsWith(".json")) {
|
|
680
|
+
let sessionDir = path.dirname(sourcePath);
|
|
681
|
+
if (path.basename(path.dirname(sessionDir)) === "session") {
|
|
682
|
+
sessionDir = path.dirname(sessionDir);
|
|
456
683
|
}
|
|
684
|
+
const { detail } = await parseLegacyOpenCodeJsonFile(sourcePath, sessionDir, true).catch(() => ({ detail: null }));
|
|
685
|
+
return detail;
|
|
686
|
+
}
|
|
687
|
+
if (!(await isRegularFile(sourcePath))) {
|
|
688
|
+
return null;
|
|
457
689
|
}
|
|
458
|
-
|
|
690
|
+
const { updatedAt } = await safeStatDates(sourcePath);
|
|
691
|
+
return withReadOnlySqlite(sourcePath, (db) => parseSingleSessionFromOpenCodeDb(db, sourcePath, rawSessionId, updatedAt)).catch(() => null);
|
|
459
692
|
}
|
|
460
|
-
export async function
|
|
693
|
+
export async function prepareOpenCodeScan(customRoot, fileCache, sqliteCache) {
|
|
461
694
|
const { primaryRoot, dbCandidates, legacySessionDirs } = resolveOpenCodePaths(customRoot);
|
|
695
|
+
const activeDbs = [];
|
|
462
696
|
let detectedRoot = primaryRoot;
|
|
463
697
|
let storageDetected = false;
|
|
464
|
-
const sessionMap = new Map();
|
|
465
698
|
for (const candidateDb of dbCandidates) {
|
|
466
699
|
if (await isRegularFile(candidateDb)) {
|
|
467
700
|
if (!storageDetected) {
|
|
468
701
|
detectedRoot = candidateDb;
|
|
469
702
|
storageDetected = true;
|
|
470
703
|
}
|
|
471
|
-
|
|
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
|
-
}
|
|
704
|
+
activeDbs.push(candidateDb);
|
|
483
705
|
if (!customRoot) {
|
|
484
|
-
// Stop probing lower-priority default OS locations once primary active DB is found
|
|
485
706
|
break;
|
|
486
707
|
}
|
|
487
708
|
}
|
|
488
709
|
}
|
|
710
|
+
const legacyTasks = [];
|
|
489
711
|
for (const legacyDir of legacySessionDirs) {
|
|
490
712
|
if (await isDirectory(legacyDir)) {
|
|
491
713
|
if (!storageDetected) {
|
|
492
714
|
detectedRoot = legacyDir;
|
|
493
715
|
storageDetected = true;
|
|
494
716
|
}
|
|
495
|
-
const
|
|
496
|
-
for (const
|
|
497
|
-
|
|
498
|
-
sessionMap.set(s.rawSessionId, s);
|
|
499
|
-
}
|
|
717
|
+
const files = await walkFiles(legacyDir, (_full, name) => name.endsWith(".json"), 4);
|
|
718
|
+
for (const fp of files) {
|
|
719
|
+
legacyTasks.push({ sessionDir: legacyDir, filePath: fp });
|
|
500
720
|
}
|
|
501
721
|
}
|
|
502
722
|
}
|
|
723
|
+
const totalItems = activeDbs.length + legacyTasks.length;
|
|
724
|
+
if (!storageDetected) {
|
|
725
|
+
return {
|
|
726
|
+
engine: "opencode",
|
|
727
|
+
storageRoot: detectedRoot,
|
|
728
|
+
storageDetected: false,
|
|
729
|
+
totalItems: 0,
|
|
730
|
+
runScan: async () => ({ summaries: [], cacheHits: 0 }),
|
|
731
|
+
};
|
|
732
|
+
}
|
|
503
733
|
return {
|
|
504
734
|
engine: "opencode",
|
|
505
735
|
storageRoot: detectedRoot,
|
|
506
|
-
storageDetected,
|
|
507
|
-
|
|
736
|
+
storageDetected: true,
|
|
737
|
+
totalItems,
|
|
738
|
+
runScan: async (onItemDone) => {
|
|
739
|
+
const sessionMap = new Map();
|
|
740
|
+
let cacheHits = 0;
|
|
741
|
+
for (const dbPath of activeDbs) {
|
|
742
|
+
try {
|
|
743
|
+
const sig = await computeSqliteSignature(dbPath);
|
|
744
|
+
const cached = sig ? sqliteCache.get(dbPath) : undefined;
|
|
745
|
+
let dbSummaries;
|
|
746
|
+
if (cached && cached.signature === sig) {
|
|
747
|
+
dbSummaries = cached.summaries;
|
|
748
|
+
cacheHits += 1;
|
|
749
|
+
}
|
|
750
|
+
else {
|
|
751
|
+
const { updatedAt } = await safeStatDates(dbPath);
|
|
752
|
+
dbSummaries = await withReadOnlySqlite(dbPath, (db) => extractSessionSummariesFromOpenCodeDb(db, dbPath, updatedAt));
|
|
753
|
+
if (sig) {
|
|
754
|
+
sqliteCache.set(dbPath, { signature: sig, summaries: dbSummaries });
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
let newlyAdded = 0;
|
|
758
|
+
for (const s of dbSummaries) {
|
|
759
|
+
if (!sessionMap.has(s.rawSessionId)) {
|
|
760
|
+
sessionMap.set(s.rawSessionId, s);
|
|
761
|
+
newlyAdded += 1;
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
onItemDone(newlyAdded);
|
|
765
|
+
}
|
|
766
|
+
catch {
|
|
767
|
+
onItemDone(0);
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
await runWithConcurrency(legacyTasks, 16, async ({ sessionDir, filePath }) => {
|
|
771
|
+
try {
|
|
772
|
+
const stat = await fsp.stat(filePath);
|
|
773
|
+
const cached = fileCache.get(filePath);
|
|
774
|
+
let summary;
|
|
775
|
+
if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
|
|
776
|
+
summary = cached.summary;
|
|
777
|
+
cacheHits += 1;
|
|
778
|
+
}
|
|
779
|
+
else {
|
|
780
|
+
const res = await parseLegacyOpenCodeJsonFile(filePath, sessionDir, false);
|
|
781
|
+
summary = res.summary;
|
|
782
|
+
fileCache.set(filePath, {
|
|
783
|
+
mtimeMs: stat.mtimeMs,
|
|
784
|
+
size: stat.size,
|
|
785
|
+
summary,
|
|
786
|
+
});
|
|
787
|
+
}
|
|
788
|
+
if (summary && !sessionMap.has(summary.rawSessionId)) {
|
|
789
|
+
sessionMap.set(summary.rawSessionId, summary);
|
|
790
|
+
onItemDone(1);
|
|
791
|
+
}
|
|
792
|
+
else {
|
|
793
|
+
onItemDone(0);
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
catch {
|
|
797
|
+
onItemDone(0);
|
|
798
|
+
}
|
|
799
|
+
});
|
|
800
|
+
return { summaries: Array.from(sessionMap.values()), cacheHits };
|
|
801
|
+
},
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
export async function scanOpenCodeSessions(customRoot) {
|
|
805
|
+
const prepared = await prepareOpenCodeScan(customRoot, new Map(), new Map());
|
|
806
|
+
if (!prepared.storageDetected) {
|
|
807
|
+
return {
|
|
808
|
+
engine: "opencode",
|
|
809
|
+
storageRoot: prepared.storageRoot,
|
|
810
|
+
storageDetected: false,
|
|
811
|
+
sessions: [],
|
|
812
|
+
};
|
|
813
|
+
}
|
|
814
|
+
const { summaries } = await prepared.runScan(() => undefined);
|
|
815
|
+
const details = [];
|
|
816
|
+
for (const s of summaries) {
|
|
817
|
+
const detail = await readOpenCodeSessionDetail(s.sourcePath, s.rawSessionId);
|
|
818
|
+
if (detail) {
|
|
819
|
+
details.push(detail);
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
return {
|
|
823
|
+
engine: "opencode",
|
|
824
|
+
storageRoot: prepared.storageRoot,
|
|
825
|
+
storageDetected: true,
|
|
826
|
+
sessions: details,
|
|
508
827
|
};
|
|
509
828
|
}
|
|
510
829
|
//# sourceMappingURL=opencode.js.map
|