@cyfsh/discovery 0.3.6 → 0.3.7

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.
@@ -1,38 +1,386 @@
1
1
  import * as fsp from "node:fs/promises";
2
2
  import * as os from "node:os";
3
3
  import * as path from "node:path";
4
+ import * as zlib from "node:zlib";
4
5
  import { decompress } from "fzstd";
5
- import { asNonEmptyString, finalizeDiscoveredSession, finalizeSessionSummary, isDirectory, isJsonRecord, isRegularFile, parseJsonlRecords, parseTimestampToIso, readJsonlDetailBounded, runWithConcurrency, safeStatDates, sampleJsonlFileSummary, summarizeThinking, summarizeToolCall, toSessionSummary, walkFiles, } from "./common.js";
6
+ import { asNonEmptyString, decodeEncodedCwd, discoverWslDistroHomes, finalizeDiscoveredSession, finalizeSessionSummary, isDirectory, isJsonRecord, isRegularFile, normalizeSessionWorkspacePath, parseJsonlRecords, parseTimestampToIso, parseWslUncRoot, readJsonlDetailBounded, runWithConcurrency, safeStatDates, sampleJsonlFileSummary, summarizeThinking, summarizeToolCall, toSessionSummary, } from "./common.js";
6
7
  import { computeSqliteSignature, withReadOnlySqlite, } from "./opencode.js";
8
+ const ZSTD_FRAME_MAGIC = 0xfd2fb528;
9
+ const ZSTD_SKIPPABLE_MAGIC_MASK = 0xfffffff0;
10
+ const ZSTD_SKIPPABLE_MAGIC_BASE = 0x184d2a50;
11
+ /**
12
+ * Matches canonical DeepSeek Harness per-session generation filenames:
13
+ * `session.jsonl`, `session.jsonl.zstd`, `session.v1.jsonl.zstd` .. `session.v4.jsonl.zstd` (and `.zst`).
14
+ */
15
+ const CANONICAL_DSH_GEN_RE = /^session(?:\.v([1-9][0-9]*))?\.jsonl(?:\.(?:zstd|zst))?$/;
16
+ /**
17
+ * Non-session internal subdirectories inside `~/.dsh` (`$DSH_HOME`) that must never be walked as session logs.
18
+ */
19
+ const IGNORED_DSH_ROOT_SUBDIRS = new Set([
20
+ "profiles",
21
+ "storages",
22
+ "attachments",
23
+ "spill",
24
+ "credentials",
25
+ "cache",
26
+ "logs",
27
+ "blobs",
28
+ "skills",
29
+ "subagents",
30
+ "memory",
31
+ "tool-results",
32
+ "artifacts",
33
+ "node_modules",
34
+ ".git",
35
+ ]);
36
+ /**
37
+ * Synthetic `user/message` `source.kind` values emitted by `agent.inject()` in DeepSeek Harness
38
+ * (e.g. AGENTS.md instructions, skill catalogs, subagent internal reports).
39
+ */
40
+ const SYNTHETIC_DSH_USER_SOURCE_KINDS = new Set([
41
+ "agent-instructions",
42
+ "skill-catalog",
43
+ "skill-invocation",
44
+ "system-prompt",
45
+ "session-reference",
46
+ "subagent-report",
47
+ "subagent-settled",
48
+ "coordinator",
49
+ "agent-message",
50
+ "tool",
51
+ ]);
52
+ const SYNTHETIC_DSH_CONTEXT_FORMS = new Set([
53
+ "instructions",
54
+ "catalog",
55
+ "snapshot",
56
+ "notice",
57
+ "recall",
58
+ "relay",
59
+ ]);
60
+ function effectiveHomeDir() {
61
+ return process.env.CYF_HOME_OVERRIDE?.trim() || os.homedir();
62
+ }
63
+ function expandHomeTilde(rawPath, homeOverride) {
64
+ const home = homeOverride ?? effectiveHomeDir();
65
+ if (rawPath === "~") {
66
+ return home;
67
+ }
68
+ if (rawPath.startsWith("~/") || rawPath.startsWith("~\\")) {
69
+ return path.join(home, rawPath.slice(2));
70
+ }
71
+ return rawPath;
72
+ }
73
+ /**
74
+ * Adds Windows extended-length path prefix (`\\?\`) for deep DSH `--projectKey--/<sessionId>/session.v4.jsonl.zstd`
75
+ * paths exceeding `MAX_PATH` on hosts without `LongPathsEnabled`, while keeping public `sourcePath` clean.
76
+ */
77
+ function toWinLongFsPath(targetPath) {
78
+ if (process.platform !== "win32" ||
79
+ !targetPath ||
80
+ targetPath.startsWith("\\\\?\\") ||
81
+ targetPath.length < 220) {
82
+ return targetPath;
83
+ }
84
+ return path.toNamespacedPath(path.resolve(targetPath));
85
+ }
86
+ function stripWinLongFsPrefix(rawPath) {
87
+ if (rawPath.startsWith("\\\\?\\UNC\\")) {
88
+ return `\\\\${rawPath.slice("\\\\?\\UNC\\".length)}`;
89
+ }
90
+ if (rawPath.startsWith("\\\\?\\")) {
91
+ return rawPath.slice("\\\\?\\".length);
92
+ }
93
+ return rawPath;
94
+ }
7
95
  export function resolveDshStorageRoot(customRoot) {
8
96
  if (customRoot && customRoot.trim().length > 0) {
9
- return path.resolve(customRoot);
97
+ return path.resolve(expandHomeTilde(customRoot.trim()));
10
98
  }
11
- const dshHome = asNonEmptyString(process.env.DSH_HOME);
99
+ const dshHome = asNonEmptyString(process.env.DSH_HOME) ??
100
+ asNonEmptyString(process.env.DSH_DATA_DIR) ??
101
+ asNonEmptyString(process.env.DEEPSEEK_HOME);
12
102
  if (dshHome) {
13
- return path.resolve(dshHome);
103
+ return path.resolve(expandHomeTilde(dshHome));
14
104
  }
15
- return path.join(os.homedir(), ".dsh");
105
+ return path.join(effectiveHomeDir(), ".dsh");
16
106
  }
17
- function stripDshSessionExtensions(fileName) {
18
- if (fileName.endsWith(".jsonl.zst")) {
19
- return fileName.slice(0, -".jsonl.zst".length);
107
+ export function resolveDshStorageRoots(customRoot) {
108
+ if (customRoot && customRoot.trim().length > 0) {
109
+ return [resolveDshStorageRoot(customRoot)];
20
110
  }
21
- if (fileName.endsWith(".json.zst")) {
22
- return fileName.slice(0, -".json.zst".length);
111
+ const home = effectiveHomeDir();
112
+ const rawRoots = [];
113
+ for (const envVal of [
114
+ asNonEmptyString(process.env.DSH_HOME),
115
+ asNonEmptyString(process.env.DSH_DATA_DIR),
116
+ asNonEmptyString(process.env.DEEPSEEK_HOME),
117
+ ]) {
118
+ if (envVal) {
119
+ rawRoots.push(path.resolve(expandHomeTilde(envVal, home)));
120
+ }
121
+ }
122
+ rawRoots.push(path.join(home, ".dsh"));
123
+ const xdgData = asNonEmptyString(process.env.XDG_DATA_HOME);
124
+ if (xdgData) {
125
+ rawRoots.push(path.join(xdgData, "dsh"));
23
126
  }
24
- if (fileName.endsWith(".zst")) {
25
- return fileName.slice(0, -".zst".length);
127
+ const xdgConfig = asNonEmptyString(process.env.XDG_CONFIG_HOME);
128
+ if (xdgConfig) {
129
+ rawRoots.push(path.join(xdgConfig, "dsh"));
26
130
  }
27
- if (fileName.endsWith(".jsonl")) {
28
- return fileName.slice(0, -".jsonl".length);
131
+ rawRoots.push(path.join(home, ".config", "dsh"), path.join(home, "Library", "Application Support", "DeepSeek Harness"), path.join(home, "Library", "Application Support", "dsh"));
132
+ for (const wslHome of discoverWslDistroHomes()) {
133
+ rawRoots.push(path.join(wslHome.uncHome, ".dsh"), path.join(wslHome.uncHome, ".config", "dsh"));
29
134
  }
30
- if (fileName.endsWith(".json")) {
31
- return fileName.slice(0, -".json".length);
135
+ const deduped = [];
136
+ const seen = new Set();
137
+ for (const candidate of rawRoots) {
138
+ const key = process.platform === "win32" ? candidate.toLowerCase() : candidate;
139
+ if (!seen.has(key)) {
140
+ seen.add(key);
141
+ deduped.push(candidate);
142
+ }
143
+ }
144
+ return deduped;
145
+ }
146
+ function isZstdPath(filePath) {
147
+ const lower = filePath.toLowerCase();
148
+ return lower.endsWith(".zstd") || lower.endsWith(".zst");
149
+ }
150
+ function isSupportedDshSessionFileName(fileName) {
151
+ const lower = fileName.toLowerCase();
152
+ if (lower.endsWith(".tmp") ||
153
+ lower.endsWith(".lock") ||
154
+ lower.startsWith(".")) {
155
+ return false;
156
+ }
157
+ return (lower.endsWith(".jsonl.zstd") ||
158
+ lower.endsWith(".jsonl.zst") ||
159
+ lower.endsWith(".json.zstd") ||
160
+ lower.endsWith(".json.zst") ||
161
+ lower.endsWith(".zstd") ||
162
+ lower.endsWith(".zst") ||
163
+ lower.endsWith(".jsonl") ||
164
+ lower.endsWith(".json"));
165
+ }
166
+ function stripDshSessionExtensions(fileName) {
167
+ const suffixes = [
168
+ ".jsonl.zstd",
169
+ ".jsonl.zst",
170
+ ".json.zstd",
171
+ ".json.zst",
172
+ ".zstd",
173
+ ".zst",
174
+ ".jsonl",
175
+ ".json",
176
+ ];
177
+ const lower = fileName.toLowerCase();
178
+ for (const suffix of suffixes) {
179
+ if (lower.endsWith(suffix)) {
180
+ return fileName.slice(0, -suffix.length);
181
+ }
32
182
  }
33
183
  return fileName;
34
184
  }
35
- function extractDshToolCalls(rec, includeDetails) {
185
+ /**
186
+ * Decodes a path segment escaped via `@deepseek-ai/dsh-session-persistence-jsonl`'s `encodeSegment`
187
+ * (`~XXXX` uppercase 4-hex UTF-16 code units, e.g. `~002E` -> `.`).
188
+ */
189
+ export function decodeDshSegment(encoded) {
190
+ if (!encoded.includes("~")) {
191
+ return encoded;
192
+ }
193
+ return encoded.replace(/~([0-9A-Fa-f]{4})/g, (_match, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
194
+ }
195
+ /**
196
+ * Decodes DSH's `--project-slug--` directory name as a last-resort fallback when both
197
+ * `SessionHeader.cwd` and `session_projcache` omit `cwd`.
198
+ */
199
+ function decodeDshProjectDirFallback(dirName) {
200
+ const trimmed = dirName.trim();
201
+ if (!trimmed || trimmed === "_no-cwd" || trimmed === "sessions") {
202
+ return "";
203
+ }
204
+ if (trimmed.startsWith("--") && trimmed.endsWith("--") && trimmed.length > 4) {
205
+ const inner = decodeDshSegment(trimmed.slice(2, -2));
206
+ if (inner === "root") {
207
+ return "/";
208
+ }
209
+ return decodeEncodedCwd(/^[A-Za-z]-/.test(inner) ? inner : `-${inner}`);
210
+ }
211
+ return "";
212
+ }
213
+ function deriveFallbackDshSessionId(filePath) {
214
+ const cleanPath = stripWinLongFsPrefix(filePath);
215
+ const base = path.basename(cleanPath);
216
+ if (CANONICAL_DSH_GEN_RE.test(base)) {
217
+ const parentName = path.basename(path.dirname(cleanPath));
218
+ if (parentName && parentName !== "." && parentName !== "sessions") {
219
+ return decodeDshSegment(parentName);
220
+ }
221
+ }
222
+ const stripped = stripDshSessionExtensions(base);
223
+ if (/^session(?:\.v\d+)?$/i.test(stripped)) {
224
+ const parentName = path.basename(path.dirname(cleanPath));
225
+ if (parentName && parentName !== "." && parentName !== "sessions") {
226
+ return decodeDshSegment(parentName);
227
+ }
228
+ }
229
+ return stripped;
230
+ }
231
+ /**
232
+ * Scans concatenated Zstandard frame boundaries without decompressing blocks.
233
+ * Preserves all structurally complete frames when an active session or crash leaves
234
+ * a torn trailing frame at EOF, while rejecting genuinely corrupt frame headers.
235
+ */
236
+ function scanZstdFrames(buffer) {
237
+ const frames = [];
238
+ let offset = 0;
239
+ while (offset < buffer.length) {
240
+ const start = offset;
241
+ if (buffer.length - offset < 4) {
242
+ return { frames, tornStart: start };
243
+ }
244
+ const magic = buffer.readUInt32LE(offset);
245
+ if ((magic & ZSTD_SKIPPABLE_MAGIC_MASK) === ZSTD_SKIPPABLE_MAGIC_BASE) {
246
+ if (buffer.length - offset < 8) {
247
+ return { frames, tornStart: start };
248
+ }
249
+ const skipLen = buffer.readUInt32LE(offset + 4);
250
+ if (buffer.length - (offset + 8) < skipLen) {
251
+ return { frames, tornStart: start };
252
+ }
253
+ offset += 8 + skipLen;
254
+ continue;
255
+ }
256
+ if (magic !== ZSTD_FRAME_MAGIC) {
257
+ throw new Error(`Corrupt Zstandard session log: invalid frame magic at byte ${offset}`);
258
+ }
259
+ offset += 4;
260
+ if (offset === buffer.length) {
261
+ return { frames, tornStart: start };
262
+ }
263
+ const descriptor = buffer.readUInt8(offset);
264
+ offset += 1;
265
+ if ((descriptor & 0x18) !== 0) {
266
+ throw new Error(`Corrupt Zstandard session log: reserved frame-header bit at byte ${offset - 1}`);
267
+ }
268
+ const contentSizeFlag = descriptor >>> 6;
269
+ const singleSegment = (descriptor & 0x20) !== 0;
270
+ const checksum = (descriptor & 0x04) !== 0;
271
+ const dictionaryFlag = descriptor & 0x03;
272
+ const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag;
273
+ const contentSizeBytes = contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : 1 << contentSizeFlag;
274
+ const remainingHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes;
275
+ if (buffer.length - offset < remainingHeaderBytes) {
276
+ return { frames, tornStart: start };
277
+ }
278
+ offset += remainingHeaderBytes;
279
+ for (;;) {
280
+ if (buffer.length - offset < 3) {
281
+ return { frames, tornStart: start };
282
+ }
283
+ const blockHeader = buffer.readUIntLE(offset, 3);
284
+ offset += 3;
285
+ const lastBlock = (blockHeader & 1) !== 0;
286
+ const blockType = (blockHeader >>> 1) & 0x03;
287
+ const blockSize = blockHeader >>> 3;
288
+ if (blockType === 0x03) {
289
+ throw new Error(`Corrupt Zstandard session log: reserved block type at byte ${offset - 3}`);
290
+ }
291
+ const payloadBytes = blockType === 0x01 ? 1 : blockSize;
292
+ if (buffer.length - offset < payloadBytes) {
293
+ return { frames, tornStart: start };
294
+ }
295
+ offset += payloadBytes;
296
+ if (lastBlock) {
297
+ break;
298
+ }
299
+ }
300
+ if (checksum) {
301
+ if (buffer.length - offset < 4) {
302
+ return { frames, tornStart: start };
303
+ }
304
+ offset += 4;
305
+ }
306
+ frames.push({ start, end: offset });
307
+ }
308
+ return { frames };
309
+ }
310
+ function decompressCompleteZstdRange(source, frames) {
311
+ if (frames.length === 0) {
312
+ return Buffer.alloc(0);
313
+ }
314
+ // Node's `zlib.zstdDecompressSync` stops after the first Zstd frame when given a
315
+ // concatenated stream, so we MUST decode each scanned frame individually!
316
+ const hasNativeZstd = typeof zlib.zstdDecompressSync === "function";
317
+ const decodedChunks = [];
318
+ for (const frame of frames) {
319
+ const rawFrame = source.subarray(frame.start, frame.end);
320
+ if (hasNativeZstd) {
321
+ decodedChunks.push(zlib.zstdDecompressSync(rawFrame));
322
+ }
323
+ else {
324
+ decodedChunks.push(decompress(new Uint8Array(rawFrame)));
325
+ }
326
+ }
327
+ return Buffer.concat(decodedChunks);
328
+ }
329
+ function tryRecoverTornZstdPrefix(tornSlice) {
330
+ if (tornSlice.length === 0 || typeof zlib.zstdDecompressSync !== "function") {
331
+ return "";
332
+ }
333
+ try {
334
+ const zstdFlushConst = zlib.constants["ZSTD_e_flush"];
335
+ const partial = zlib.zstdDecompressSync(tornSlice, zstdFlushConst !== undefined ? { finishFlush: zstdFlushConst } : undefined);
336
+ const text = partial.toString("utf8");
337
+ const lastNl = text.lastIndexOf("\n");
338
+ return lastNl >= 0 ? text.slice(0, lastNl + 1) : "";
339
+ }
340
+ catch {
341
+ return "";
342
+ }
343
+ }
344
+ function decompressDshZstdBuffer(compressedBuf, summarySampleOnly) {
345
+ const { frames, tornStart } = scanZstdFrames(compressedBuf);
346
+ if (frames.length === 0) {
347
+ if (tornStart !== undefined) {
348
+ const recovered = tryRecoverTornZstdPrefix(compressedBuf.subarray(tornStart));
349
+ if (recovered.trim().length > 0) {
350
+ return { text: recovered, isPartialSample: false, sampledRatio: 1 };
351
+ }
352
+ }
353
+ throw new Error("Empty or incomplete Zstandard session log");
354
+ }
355
+ // Fast O(1) head+tail frame sampling when building list summaries over multi-MB compressed logs
356
+ if (summarySampleOnly && frames.length > 24 && compressedBuf.length > 512 * 1024) {
357
+ const headFrames = frames.slice(0, 12);
358
+ const tailFrames = frames.slice(-8);
359
+ const headBuf = decompressCompleteZstdRange(compressedBuf, headFrames);
360
+ const tailBuf = decompressCompleteZstdRange(compressedBuf, tailFrames);
361
+ const sampledBytes = (headFrames[headFrames.length - 1].end - headFrames[0].start) +
362
+ (tailFrames[tailFrames.length - 1].end - tailFrames[0].start);
363
+ return {
364
+ text: `${headBuf.toString("utf8")}\n${tailBuf.toString("utf8")}`,
365
+ isPartialSample: true,
366
+ sampledRatio: Math.min(1, sampledBytes / compressedBuf.length),
367
+ };
368
+ }
369
+ const mainText = decompressCompleteZstdRange(compressedBuf, frames).toString("utf8");
370
+ if (tornStart !== undefined && !summarySampleOnly) {
371
+ const recoveredTail = tryRecoverTornZstdPrefix(compressedBuf.subarray(tornStart));
372
+ if (recoveredTail) {
373
+ const joiner = mainText.endsWith("\n") ? "" : "\n";
374
+ return {
375
+ text: `${mainText}${joiner}${recoveredTail}`,
376
+ isPartialSample: false,
377
+ sampledRatio: 1,
378
+ };
379
+ }
380
+ }
381
+ return { text: mainText, isPartialSample: false, sampledRatio: 1 };
382
+ }
383
+ function extractDshToolCalls(rec, includeDetails, seenCallIds) {
36
384
  const calls = [];
37
385
  const rawList = (Array.isArray(rec.tool_calls) ? rec.tool_calls : undefined) ??
38
386
  (Array.isArray(rec.toolCalls) ? rec.toolCalls : undefined);
@@ -41,6 +389,12 @@ function extractDshToolCalls(rec, includeDetails) {
41
389
  if (!isJsonRecord(item)) {
42
390
  continue;
43
391
  }
392
+ const callId = asNonEmptyString(item.id) ?? asNonEmptyString(item.callId);
393
+ if (callId && seenCallIds) {
394
+ if (seenCallIds.has(callId))
395
+ continue;
396
+ seenCallIds.add(callId);
397
+ }
44
398
  if (isJsonRecord(item.function)) {
45
399
  const fnName = asNonEmptyString(item.function.name) ?? "tool";
46
400
  calls.push(includeDetails
@@ -57,9 +411,22 @@ function extractDshToolCalls(rec, includeDetails) {
57
411
  }
58
412
  if (Array.isArray(rec.content)) {
59
413
  for (const block of rec.content) {
60
- if (isJsonRecord(block) && asNonEmptyString(block.type) === "tool_use") {
414
+ if (!isJsonRecord(block)) {
415
+ continue;
416
+ }
417
+ const bType = asNonEmptyString(block.type);
418
+ // Real DSH uses `type: "tool-call"` with JSON `arguments`; legacy/Claude uses `tool_use` with `input`
419
+ if (bType === "tool-call" || bType === "tool_use") {
420
+ const callId = asNonEmptyString(block.id) ?? asNonEmptyString(block.callId);
421
+ if (callId && seenCallIds) {
422
+ if (seenCallIds.has(callId))
423
+ continue;
424
+ seenCallIds.add(callId);
425
+ }
61
426
  const name = asNonEmptyString(block.name) ?? "tool";
62
- calls.push(includeDetails ? summarizeToolCall(name, block.input) : { name, summary: name });
427
+ calls.push(includeDetails
428
+ ? summarizeToolCall(name, block.arguments ?? block.input)
429
+ : { name, summary: name });
63
430
  }
64
431
  }
65
432
  }
@@ -68,11 +435,14 @@ function extractDshToolCalls(rec, includeDetails) {
68
435
  function extractDshTextAndThinking(rec, includeDetails) {
69
436
  const textParts = [];
70
437
  const thinkingParts = [];
71
- if (includeDetails) {
72
- const directReasoning = asNonEmptyString(rec.reasoning_content) ??
73
- asNonEmptyString(rec.reasoningContent) ??
74
- asNonEmptyString(rec.thinking);
75
- if (directReasoning) {
438
+ const attachmentFallbackParts = [];
439
+ let hasReasoning = false;
440
+ const directReasoning = asNonEmptyString(rec.reasoning_content) ??
441
+ asNonEmptyString(rec.reasoningContent) ??
442
+ asNonEmptyString(rec.thinking);
443
+ if (directReasoning) {
444
+ hasReasoning = true;
445
+ if (includeDetails) {
76
446
  thinkingParts.push(directReasoning);
77
447
  }
78
448
  }
@@ -85,18 +455,28 @@ function extractDshTextAndThinking(rec, includeDetails) {
85
455
  continue;
86
456
  }
87
457
  const bType = asNonEmptyString(block.type);
88
- if (bType === "text" || !bType) {
458
+ if (bType === "text" || bType === "input_text" || bType === "output_text" || !bType) {
89
459
  const t = asNonEmptyString(block.text) ?? asNonEmptyString(block.content);
90
460
  if (t) {
91
461
  textParts.push(t);
92
462
  }
93
463
  }
94
- else if (includeDetails && (bType === "thinking" || bType === "reasoning")) {
464
+ else if (bType === "thinking" || bType === "reasoning") {
95
465
  const th = asNonEmptyString(block.thinking) ?? asNonEmptyString(block.text);
96
466
  if (th) {
97
- thinkingParts.push(th);
467
+ hasReasoning = true;
468
+ if (includeDetails) {
469
+ thinkingParts.push(th);
470
+ }
98
471
  }
99
472
  }
473
+ else if (bType === "file" || bType === "image") {
474
+ const att = isJsonRecord(block.attachment) ? block.attachment : undefined;
475
+ const attName = asNonEmptyString(att?.name) ??
476
+ asNonEmptyString(att?.attachmentId) ??
477
+ bType;
478
+ attachmentFallbackParts.push(`[${bType}: ${attName}]`);
479
+ }
100
480
  }
101
481
  }
102
482
  else {
@@ -105,23 +485,62 @@ function extractDshTextAndThinking(rec, includeDetails) {
105
485
  textParts.push(fallbackText);
106
486
  }
107
487
  }
488
+ const joinedText = textParts.length > 0
489
+ ? textParts.join("\n").trim()
490
+ : attachmentFallbackParts.join(" ").trim();
108
491
  return {
109
- text: textParts.join("\n").trim(),
492
+ text: joinedText,
110
493
  thinking: thinkingParts.join("\n").trim(),
494
+ hasReasoning,
111
495
  };
112
496
  }
113
- function extractDshSessionCore(records, filePath, fallbackCreatedAt, fallbackUpdatedAt, includeDetails) {
114
- let rawSessionId = stripDshSessionExtensions(path.basename(filePath));
497
+ function isSyntheticDshUserInjection(msgObj) {
498
+ if (!isJsonRecord(msgObj.source)) {
499
+ return false;
500
+ }
501
+ const kind = asNonEmptyString(msgObj.source.kind);
502
+ if (kind && SYNTHETIC_DSH_USER_SOURCE_KINDS.has(kind)) {
503
+ return true;
504
+ }
505
+ const form = asNonEmptyString(msgObj.source.form);
506
+ if (form && SYNTHETIC_DSH_CONTEXT_FORMS.has(form)) {
507
+ return true;
508
+ }
509
+ return false;
510
+ }
511
+ function isSubagentDshHeader(rec) {
512
+ if (asNonEmptyString(rec.origin) === "subagent") {
513
+ return true;
514
+ }
515
+ const depth = rec.delegationDepth;
516
+ return typeof depth === "number" && Number.isFinite(depth) && depth > 0;
517
+ }
518
+ function extractDshSessionCore(records, filePath, fallbackCreatedAt, fallbackUpdatedAt, includeDetails, projCache) {
519
+ const cleanFilePath = stripWinLongFsPrefix(filePath);
520
+ let rawSessionId = deriveFallbackDshSessionId(cleanFilePath);
115
521
  let workspacePath = "";
116
522
  let gitBranch;
117
523
  let model;
118
524
  let explicitTitle;
525
+ let sessionCreatedAt = fallbackCreatedAt;
526
+ let latestEventAt;
527
+ let isSubagent = false;
119
528
  const messages = [];
529
+ const seenToolCallIds = new Set();
120
530
  for (let idx = 0; idx < records.length; idx += 1) {
121
531
  const rec = records[idx];
122
532
  if (!rec) {
123
533
  continue;
124
534
  }
535
+ const recType = asNonEmptyString(rec.type);
536
+ const dataObj = isJsonRecord(rec.data)
537
+ ? rec.data
538
+ : isJsonRecord(rec.payload)
539
+ ? rec.payload
540
+ : undefined;
541
+ if (rec.time !== undefined || rec.timestamp !== undefined || rec.created_at !== undefined) {
542
+ latestEventAt = parseTimestampToIso(rec.time ?? rec.timestamp ?? rec.created_at, latestEventAt ?? fallbackUpdatedAt);
543
+ }
125
544
  const sId = asNonEmptyString(rec.sessionId) ??
126
545
  asNonEmptyString(rec.session_id);
127
546
  if (sId) {
@@ -145,60 +564,143 @@ function extractDshSessionCore(records, filePath, fallbackCreatedAt, fallbackUpd
145
564
  if (modelCandidate) {
146
565
  model = modelCandidate;
147
566
  }
148
- const recType = asNonEmptyString(rec.type);
149
- if (recType === "session_meta" ||
567
+ // 1. Canonical DSH `SessionHeader` (`type: "session"`) & legacy header records
568
+ if (recType === "session" ||
569
+ recType === "session_meta" ||
150
570
  recType === "session_start" ||
151
571
  recType === "meta" ||
152
572
  recType === "init") {
153
- const metaId = asNonEmptyString(rec.id) ?? asNonEmptyString(rec.sessionId);
573
+ if (recType === "session" && isSubagentDshHeader(rec)) {
574
+ isSubagent = true;
575
+ }
576
+ const metaId = asNonEmptyString(rec.id) ??
577
+ asNonEmptyString(rec.sessionId) ??
578
+ asNonEmptyString(rec.session_id);
154
579
  if (metaId) {
155
580
  rawSessionId = metaId;
156
581
  }
582
+ if (rec.createdAt !== undefined || rec.created_at !== undefined) {
583
+ sessionCreatedAt = parseTimestampToIso(rec.createdAt ?? rec.created_at, sessionCreatedAt);
584
+ }
157
585
  const metaTitle = asNonEmptyString(rec.title) ?? asNonEmptyString(rec.topic);
158
586
  if (metaTitle) {
159
587
  explicitTitle = metaTitle;
160
588
  }
161
- if (isJsonRecord(rec.payload)) {
162
- const p = rec.payload;
163
- rawSessionId = asNonEmptyString(p.id) ?? asNonEmptyString(p.sessionId) ?? rawSessionId;
589
+ if (dataObj) {
590
+ if (isSubagentDshHeader(dataObj)) {
591
+ isSubagent = true;
592
+ }
593
+ rawSessionId =
594
+ asNonEmptyString(dataObj.id) ??
595
+ asNonEmptyString(dataObj.sessionId) ??
596
+ rawSessionId;
164
597
  workspacePath =
165
598
  workspacePath ||
166
- asNonEmptyString(p.cwd) ||
167
- asNonEmptyString(p.workdir) ||
599
+ asNonEmptyString(dataObj.cwd) ||
600
+ asNonEmptyString(dataObj.workdir) ||
168
601
  "";
169
602
  gitBranch =
170
603
  gitBranch ??
171
- asNonEmptyString(p.gitBranch) ??
172
- (isJsonRecord(p.git) ? asNonEmptyString(p.git.branch) : undefined);
173
- model = model ?? asNonEmptyString(p.model);
174
- explicitTitle = explicitTitle ?? asNonEmptyString(p.title);
604
+ asNonEmptyString(dataObj.gitBranch) ??
605
+ (isJsonRecord(dataObj.git) ? asNonEmptyString(dataObj.git.branch) : undefined);
606
+ model = model ?? asNonEmptyString(dataObj.model);
607
+ explicitTitle = explicitTitle ?? asNonEmptyString(dataObj.title);
175
608
  }
176
609
  continue;
177
610
  }
611
+ // 2. Log-only DSH `session/title` event (last-wins)
612
+ if (recType === "session/title") {
613
+ const nextTitle = asNonEmptyString(dataObj?.title) ?? asNonEmptyString(rec.title);
614
+ if (nextTitle) {
615
+ explicitTitle = nextTitle;
616
+ }
617
+ continue;
618
+ }
619
+ // 3. Log-only DSH model/route metadata (`request/context`, `model/selection`, `request/header`)
620
+ if (recType === "request/context" || recType === "model/selection") {
621
+ const routeModel = asNonEmptyString(dataObj?.model);
622
+ if (routeModel) {
623
+ model = routeModel;
624
+ }
625
+ continue;
626
+ }
627
+ if (recType === "request/header" && dataObj && isJsonRecord(dataObj.header)) {
628
+ const cfg = isJsonRecord(dataObj.header.config)
629
+ ? dataObj.header.config
630
+ : undefined;
631
+ const hdrModel = asNonEmptyString(cfg?.model);
632
+ if (hdrModel) {
633
+ model = hdrModel;
634
+ }
635
+ continue;
636
+ }
637
+ // 4. Standalone `tool/call` event (deduplicated against `assistant/message` `tool-call` blocks by `callId`)
638
+ if (recType === "tool/call" && dataObj) {
639
+ const callId = asNonEmptyString(dataObj.callId) ?? asNonEmptyString(dataObj.id);
640
+ if (callId && seenToolCallIds.has(callId)) {
641
+ continue;
642
+ }
643
+ if (callId) {
644
+ seenToolCallIds.add(callId);
645
+ }
646
+ const toolName = asNonEmptyString(dataObj.name) ?? "tool";
647
+ const toolSummary = includeDetails
648
+ ? summarizeToolCall(toolName, dataObj.arguments ?? dataObj.input)
649
+ : { name: toolName, summary: toolName };
650
+ const timestamp = parseTimestampToIso(rec.time ?? rec.timestamp, latestEventAt ?? fallbackUpdatedAt);
651
+ messages.push({
652
+ id: callId ?? `${rawSessionId}-tc-${idx + 1}`,
653
+ role: "assistant",
654
+ content: "",
655
+ timestamp,
656
+ toolCalls: [toolSummary],
657
+ });
658
+ continue;
659
+ }
660
+ // 5. Surface message events:
661
+ // - DSH `user/message`: `rec.data` is `UserMessage` (`{ id, role: 'user', content, source }`)
662
+ // - DSH `assistant/message`: `rec.data` is `{ turn, step, message: AssistantMessage, stream, usage }`
663
+ // - Legacy/flat records: `rec.message`, `rec.payload`, or `rec`
178
664
  const sourceObj = isJsonRecord(rec.message)
179
665
  ? rec.message
180
- : isJsonRecord(rec.payload)
181
- ? rec.payload
182
- : rec;
666
+ : dataObj && isJsonRecord(dataObj.message)
667
+ ? dataObj.message
668
+ : (dataObj ?? rec);
669
+ if (isJsonRecord(sourceObj.source)) {
670
+ const msgSourceModel = asNonEmptyString(sourceObj.source.model);
671
+ if (msgSourceModel) {
672
+ model = msgSourceModel;
673
+ }
674
+ }
183
675
  const rawRole = asNonEmptyString(sourceObj.role) ??
184
- (recType === "user" || recType === "user_message"
676
+ (recType === "user" || recType === "user_message" || recType === "user/message"
185
677
  ? "user"
186
- : recType === "assistant" || recType === "assistant_message"
678
+ : recType === "assistant" ||
679
+ recType === "assistant_message" ||
680
+ recType === "assistant/message"
187
681
  ? "assistant"
188
682
  : undefined);
189
683
  if (rawRole !== "user" && rawRole !== "assistant" && rawRole !== "system") {
190
684
  continue;
191
685
  }
192
- const { text, thinking } = extractDshTextAndThinking(sourceObj, includeDetails);
193
- const toolCalls = extractDshToolCalls(sourceObj, includeDetails);
686
+ if (rawRole === "user" && isSyntheticDshUserInjection(sourceObj)) {
687
+ continue;
688
+ }
689
+ const { text, thinking, hasReasoning } = extractDshTextAndThinking(sourceObj, includeDetails);
690
+ const toolCalls = extractDshToolCalls(sourceObj, includeDetails, seenToolCallIds);
194
691
  const finalContent = text;
195
- if (!finalContent && !thinking && toolCalls.length === 0) {
692
+ if (!finalContent && !thinking && !hasReasoning && toolCalls.length === 0) {
196
693
  continue;
197
694
  }
198
- const timestamp = parseTimestampToIso(rec.timestamp ?? rec.created_at ?? sourceObj.timestamp, fallbackUpdatedAt);
199
- const thinkingSummary = includeDetails ? summarizeThinking(thinking) : undefined;
200
- const msgId = asNonEmptyString(rec.id) ??
201
- asNonEmptyString(sourceObj.id) ??
695
+ const timestamp = parseTimestampToIso(rec.time ?? rec.timestamp ?? rec.created_at ?? dataObj?.time ?? sourceObj.timestamp, latestEventAt ?? fallbackUpdatedAt);
696
+ const thinkingSummary = includeDetails
697
+ ? summarizeThinking(thinking)
698
+ : hasReasoning
699
+ ? "reasoning"
700
+ : undefined;
701
+ const msgId = asNonEmptyString(sourceObj.id) ??
702
+ asNonEmptyString(rec.id) ??
703
+ (typeof rec.seq === "number" ? `${rawSessionId}-seq-${rec.seq}` : undefined) ??
202
704
  `${rawSessionId}-ev-${idx + 1}`;
203
705
  messages.push({
204
706
  id: msgId,
@@ -206,18 +708,41 @@ function extractDshSessionCore(records, filePath, fallbackCreatedAt, fallbackUpd
206
708
  content: finalContent,
207
709
  timestamp,
208
710
  ...(thinkingSummary ? { thinkingSummary } : {}),
209
- ...(includeDetails && toolCalls.length > 0 ? { toolCalls } : {}),
711
+ ...(toolCalls.length > 0 ? { toolCalls } : {}),
210
712
  });
211
713
  }
714
+ // Enrich missing metadata from `~/.dsh/storages/session_projcache` when available
715
+ const cachedProj = projCache?.get(rawSessionId);
716
+ if (cachedProj) {
717
+ if (!explicitTitle && cachedProj.title) {
718
+ explicitTitle = cachedProj.title;
719
+ }
720
+ if (!workspacePath && cachedProj.cwd) {
721
+ workspacePath = cachedProj.cwd;
722
+ }
723
+ if (!latestEventAt && cachedProj.updatedAtIso) {
724
+ latestEventAt = cachedProj.updatedAtIso;
725
+ }
726
+ }
727
+ if (!workspacePath) {
728
+ const parentDir = path.dirname(cleanFilePath);
729
+ const grandParentName = path.basename(path.dirname(parentDir));
730
+ const parentName = path.basename(parentDir);
731
+ workspacePath =
732
+ decodeDshProjectDirFallback(grandParentName) ||
733
+ decodeDshProjectDirFallback(parentName) ||
734
+ "/unknown-workspace";
735
+ }
212
736
  return {
213
737
  engine: "dsh",
738
+ isSubagent,
214
739
  rawSessionId,
215
740
  explicitTitle,
216
- workspacePath: workspacePath || "/unknown-workspace",
217
- sourcePath: filePath,
741
+ workspacePath,
742
+ sourcePath: cleanFilePath,
218
743
  messages,
219
- fallbackCreatedAt,
220
- fallbackUpdatedAt,
744
+ fallbackCreatedAt: sessionCreatedAt,
745
+ fallbackUpdatedAt: latestEventAt ?? fallbackUpdatedAt,
221
746
  gitBranch,
222
747
  model,
223
748
  };
@@ -253,18 +778,30 @@ function sqlCellString(val) {
253
778
  }
254
779
  return undefined;
255
780
  }
256
- function extractSessionsFromDshSqlite(db, dbPath, fallbackIso, targetRawId) {
781
+ function extractSessionsFromDshSqlite(db, dbPath, fallbackIso, targetRawId, projCache) {
257
782
  const tableRows = db
258
783
  .prepare("SELECT name FROM sqlite_master WHERE type = 'table'")
259
784
  .all();
260
785
  const tableNames = new Set(tableRows
261
786
  .map((r) => sqlCellString(r.name))
262
787
  .filter((name) => Boolean(name)));
263
- const sessionTable = ["sessions", "session", "dsh_sessions"].find((t) => tableNames.has(t));
788
+ const sessionTable = [
789
+ "sessions",
790
+ "session",
791
+ "dsh_sessions",
792
+ "persisted_sessions",
793
+ ].find((t) => tableNames.has(t));
264
794
  if (!sessionTable) {
265
795
  return [];
266
796
  }
267
- const msgTable = ["messages", "message", "events", "dsh_events", "dsh_messages"].find((t) => tableNames.has(t));
797
+ const msgTable = [
798
+ "events",
799
+ "session_events",
800
+ "messages",
801
+ "message",
802
+ "dsh_events",
803
+ "dsh_messages",
804
+ ].find((t) => tableNames.has(t));
268
805
  const sRows = db.prepare(`SELECT * FROM "${sessionTable}"`).all();
269
806
  const filteredSRows = targetRawId
270
807
  ? sRows.filter((r) => (sqlCellString(r.id) ?? sqlCellString(r.session_id)) === targetRawId)
@@ -295,8 +832,18 @@ function extractSessionsFromDshSqlite(db, dbPath, fallbackIso, targetRawId) {
295
832
  if (!rawSessionId) {
296
833
  continue;
297
834
  }
835
+ const rowOrigin = sqlCellString(sRow.origin);
836
+ const rowDepthRaw = sRow.delegation_depth ?? sRow.delegationDepth;
837
+ const rowDepth = typeof rowDepthRaw === "number" || typeof rowDepthRaw === "bigint"
838
+ ? Number(rowDepthRaw)
839
+ : 0;
840
+ if (!targetRawId && (rowOrigin === "subagent" || rowDepth > 0)) {
841
+ continue;
842
+ }
298
843
  let parsedData;
299
- const rawDataStr = sqlCellString(sRow.data) ?? sqlCellString(sRow.payload);
844
+ const rawDataStr = sqlCellString(sRow.data) ??
845
+ sqlCellString(sRow.payload) ??
846
+ sqlCellString(sRow.header);
300
847
  if (rawDataStr && rawDataStr.startsWith("{")) {
301
848
  try {
302
849
  const parsed = JSON.parse(rawDataStr);
@@ -308,18 +855,24 @@ function extractSessionsFromDshSqlite(db, dbPath, fallbackIso, targetRawId) {
308
855
  // Ignore invalid JSON column
309
856
  }
310
857
  }
858
+ if (!targetRawId && parsedData && isSubagentDshHeader(parsedData)) {
859
+ continue;
860
+ }
311
861
  const workspacePath = sqlCellString(sRow.cwd) ??
312
862
  sqlCellString(sRow.workdir) ??
313
863
  sqlCellString(sRow.workspace_path) ??
314
864
  asNonEmptyString(parsedData?.cwd) ??
315
- "/unknown-workspace";
865
+ "";
316
866
  const explicitTitle = sqlCellString(sRow.title) ?? asNonEmptyString(parsedData?.title);
317
867
  const gitBranch = sqlCellString(sRow.git_branch) ??
318
868
  sqlCellString(sRow.branch) ??
319
869
  asNonEmptyString(parsedData?.gitBranch);
320
870
  const model = sqlCellString(sRow.model) ?? asNonEmptyString(parsedData?.model);
321
- const createdIso = parseTimestampToIso(sRow.created_at ?? sRow.time_created, fallbackIso);
322
- const updatedIso = parseTimestampToIso(sRow.updated_at ?? sRow.time_updated, createdIso);
871
+ const createdIso = parseTimestampToIso(sRow.createdAt ??
872
+ sRow.created_at ??
873
+ sRow.time_created ??
874
+ parsedData?.createdAt, fallbackIso);
875
+ const updatedIso = parseTimestampToIso(sRow.updatedAt ?? sRow.updated_at ?? sRow.time_updated, createdIso);
323
876
  const eventRecords = [];
324
877
  if (parsedData && Array.isArray(parsedData.messages)) {
325
878
  for (const item of parsedData.messages) {
@@ -330,12 +883,33 @@ function extractSessionsFromDshSqlite(db, dbPath, fallbackIso, targetRawId) {
330
883
  }
331
884
  const childRows = msgsBySession.get(rawSessionId) ?? [];
332
885
  for (const cRow of childRows) {
886
+ const rowType = sqlCellString(cRow.type);
887
+ const rowTime = cRow.time ?? cRow.created_at ?? cRow.timestamp;
888
+ const rowSeq = typeof cRow.seq === "number" || typeof cRow.seq === "bigint"
889
+ ? Number(cRow.seq)
890
+ : undefined;
333
891
  const cPayloadStr = sqlCellString(cRow.data) ?? sqlCellString(cRow.payload);
334
892
  if (cPayloadStr && cPayloadStr.startsWith("{")) {
335
893
  try {
336
894
  const cObj = JSON.parse(cPayloadStr);
337
895
  if (isJsonRecord(cObj)) {
338
- eventRecords.push(cObj);
896
+ // Preserve outer `SessionEvent` envelope (`type`, `seq`, `time`) from `dsh-session-persistence-sqlite`
897
+ if (rowType && cObj.type === undefined) {
898
+ eventRecords.push({
899
+ type: rowType,
900
+ ...(rowSeq !== undefined ? { seq: rowSeq } : {}),
901
+ ...(rowTime !== undefined ? { time: rowTime } : {}),
902
+ data: cObj,
903
+ });
904
+ }
905
+ else {
906
+ eventRecords.push({
907
+ ...(rowTime !== undefined && cObj.time === undefined && cObj.timestamp === undefined
908
+ ? { time: rowTime }
909
+ : {}),
910
+ ...cObj,
911
+ });
912
+ }
339
913
  continue;
340
914
  }
341
915
  }
@@ -345,140 +919,487 @@ function extractSessionsFromDshSqlite(db, dbPath, fallbackIso, targetRawId) {
345
919
  }
346
920
  eventRecords.push({
347
921
  id: sqlCellString(cRow.id),
348
- role: sqlCellString(cRow.role) ?? sqlCellString(cRow.type),
922
+ role: sqlCellString(cRow.role) ?? rowType,
349
923
  content: sqlCellString(cRow.content) ?? sqlCellString(cRow.text),
350
924
  reasoning_content: sqlCellString(cRow.reasoning_content) ?? sqlCellString(cRow.thinking),
351
- timestamp: cRow.created_at ?? cRow.timestamp,
925
+ timestamp: rowTime,
352
926
  });
353
927
  }
354
928
  const header = {
355
929
  type: "session_meta",
356
930
  id: rawSessionId,
357
- cwd: workspacePath,
931
+ cwd: workspacePath || undefined,
358
932
  gitBranch,
359
933
  model,
360
934
  title: explicitTitle,
361
935
  };
362
- const detail = finalizeDiscoveredSession(extractDshSessionCore([header, ...eventRecords], dbPath, createdIso, updatedIso, Boolean(targetRawId)));
936
+ const core = extractDshSessionCore([header, ...eventRecords], dbPath, createdIso, updatedIso, Boolean(targetRawId), projCache);
937
+ if (!targetRawId && core.isSubagent) {
938
+ continue;
939
+ }
940
+ const detail = finalizeDiscoveredSession(core);
363
941
  if (detail) {
364
942
  results.push(detail);
365
943
  }
366
944
  }
367
945
  return results;
368
946
  }
369
- async function parseDshNonPlainFile(filePath, includeDetails) {
370
- const { createdAt, updatedAt } = await safeStatDates(filePath);
371
- const textDecoder = new TextDecoder("utf-8");
947
+ function parseDshProjCacheRecord(raw) {
948
+ if (!isJsonRecord(raw)) {
949
+ return null;
950
+ }
951
+ const rec = isJsonRecord(raw.record) ? raw.record : raw;
952
+ const identity = isJsonRecord(rec.identity) ? rec.identity : undefined;
953
+ const rows = isJsonRecord(rec.rows) ? rec.rows : undefined;
954
+ if (!identity && !rows) {
955
+ return null;
956
+ }
957
+ const titleRow = rows && isJsonRecord(rows.title) ? rows.title : undefined;
958
+ const title = asNonEmptyString(titleRow?.val);
959
+ const cwd = asNonEmptyString(identity?.cwd);
960
+ const createdMs = identity?.createdAt;
961
+ const createdAtIso = typeof createdMs === "number" && createdMs > 0
962
+ ? new Date(createdMs).toISOString()
963
+ : undefined;
964
+ let maxUpdatedMs = typeof createdMs === "number" && createdMs > 0 ? createdMs : 0;
965
+ const timeCtx = rows && isJsonRecord(rows.timeContext) && isJsonRecord(rows.timeContext.val)
966
+ ? rows.timeContext.val
967
+ : undefined;
968
+ const listMeta = rows &&
969
+ isJsonRecord(rows.sessionListMetadata) &&
970
+ isJsonRecord(rows.sessionListMetadata.val)
971
+ ? rows.sessionListMetadata.val
972
+ : undefined;
973
+ for (const cand of [timeCtx?.lastMessageTime, listMeta?.lastPromptAt]) {
974
+ if (typeof cand === "number" && Number.isFinite(cand) && cand > maxUpdatedMs) {
975
+ maxUpdatedMs = cand;
976
+ }
977
+ }
978
+ return {
979
+ ...(title ? { title } : {}),
980
+ ...(cwd ? { cwd } : {}),
981
+ ...(createdAtIso ? { createdAtIso } : {}),
982
+ ...(maxUpdatedMs > 0 ? { updatedAtIso: new Date(maxUpdatedMs).toISOString() } : {}),
983
+ };
984
+ }
985
+ /**
986
+ * Loads best-effort metadata hints (`title`, `cwd`, `lastMessageTime`) from
987
+ * `~/.dsh/storages/session_projcache/sessions/*.json` and legacy `session_projcache.json`.
988
+ */
989
+ async function loadDshProjCacheMap(baseRoot) {
990
+ const out = new Map();
991
+ const legacyFile = path.join(baseRoot, "storages", "session_projcache.json");
992
+ try {
993
+ if (await isRegularFile(toWinLongFsPath(legacyFile))) {
994
+ const rawText = await fsp.readFile(toWinLongFsPath(legacyFile), "utf8");
995
+ const doc = JSON.parse(rawText);
996
+ if (isJsonRecord(doc) &&
997
+ isJsonRecord(doc.tables) &&
998
+ isJsonRecord(doc.tables.sessions)) {
999
+ for (const [sid, val] of Object.entries(doc.tables.sessions)) {
1000
+ const parsed = parseDshProjCacheRecord(val);
1001
+ if (parsed) {
1002
+ out.set(sid, parsed);
1003
+ }
1004
+ }
1005
+ }
1006
+ }
1007
+ }
1008
+ catch {
1009
+ // Ignore malformed legacy projcache
1010
+ }
1011
+ const perRecordDir = path.join(baseRoot, "storages", "session_projcache", "sessions");
1012
+ try {
1013
+ const fsDir = toWinLongFsPath(perRecordDir);
1014
+ if (await isDirectory(fsDir)) {
1015
+ const entries = await fsp.readdir(fsDir, { withFileTypes: true });
1016
+ await runWithConcurrency(entries, 16, async (entry) => {
1017
+ if (!entry.isFile() || !entry.name.endsWith(".json")) {
1018
+ return;
1019
+ }
1020
+ try {
1021
+ const rawText = await fsp.readFile(path.join(fsDir, entry.name), "utf8");
1022
+ const parsed = parseDshProjCacheRecord(JSON.parse(rawText));
1023
+ if (parsed) {
1024
+ const rawKey = entry.name.slice(0, -".json".length);
1025
+ out.set(decodeDshSegment(rawKey), parsed);
1026
+ out.set(rawKey, parsed);
1027
+ }
1028
+ }
1029
+ catch {
1030
+ // Ignore individual unreadable cache entries
1031
+ }
1032
+ });
1033
+ }
1034
+ }
1035
+ catch {
1036
+ // Ignore missing projcache directory
1037
+ }
1038
+ return out;
1039
+ }
1040
+ function resolvePatchTargetForBaseRoot(rawTarget, baseRoot) {
1041
+ const wslInfo = parseWslUncRoot(baseRoot);
1042
+ if (wslInfo) {
1043
+ const ownerHome = path.basename(baseRoot).toLowerCase() === ".dsh"
1044
+ ? path.dirname(baseRoot)
1045
+ : wslInfo.uncRoot;
1046
+ if (rawTarget === "~" || rawTarget.startsWith("~/") || rawTarget.startsWith("~\\")) {
1047
+ return expandHomeTilde(rawTarget, ownerHome);
1048
+ }
1049
+ if (rawTarget.startsWith("/")) {
1050
+ return normalizeSessionWorkspacePath(rawTarget, baseRoot);
1051
+ }
1052
+ }
1053
+ return path.resolve(expandHomeTilde(rawTarget));
1054
+ }
1055
+ /**
1056
+ * Discovers any custom static `root:` / `path:` configured for `dsh-session-persistence-*`
1057
+ * inside `<baseRoot>/profiles/<name>/cordis.patch.yml`.
1058
+ */
1059
+ async function discoverCustomPatchRoots(baseRoot) {
1060
+ const extraSessionDirs = [];
1061
+ const extraSqliteFiles = [];
1062
+ const profilesDir = path.join(baseRoot, "profiles");
1063
+ try {
1064
+ if (!(await isDirectory(profilesDir))) {
1065
+ return { extraSessionDirs, extraSqliteFiles };
1066
+ }
1067
+ const profileEntries = await fsp.readdir(profilesDir, { withFileTypes: true });
1068
+ for (const pEntry of profileEntries) {
1069
+ if (!pEntry.isDirectory())
1070
+ continue;
1071
+ for (const patchName of ["cordis.patch.yml", "cordis.patch.yaml"]) {
1072
+ const patchFile = path.join(profilesDir, pEntry.name, patchName);
1073
+ if (!(await isRegularFile(patchFile)))
1074
+ continue;
1075
+ const text = await fsp.readFile(patchFile, "utf8");
1076
+ if (!text.includes("session-persistence"))
1077
+ continue;
1078
+ const jsonlBlockMatch = /dsh-session-persistence-jsonl['"]?[\s\S]{0,240}?\broot\s*:\s*([^\r\n#]+)/.exec(text);
1079
+ const rawRoot = jsonlBlockMatch?.[1]?.trim().replace(/^['"]|['"]$/g, "");
1080
+ if (rawRoot && !rawRoot.startsWith("!!js") && !rawRoot.startsWith("!js")) {
1081
+ extraSessionDirs.push(resolvePatchTargetForBaseRoot(rawRoot, baseRoot));
1082
+ }
1083
+ const sqliteBlockMatch = /dsh-session-persistence-sqlite['"]?[\s\S]{0,240}?\bpath\s*:\s*([^\r\n#]+)/.exec(text);
1084
+ const rawDb = sqliteBlockMatch?.[1]?.trim().replace(/^['"]|['"]$/g, "");
1085
+ if (rawDb &&
1086
+ rawDb !== ":memory:" &&
1087
+ !rawDb.startsWith("!!js") &&
1088
+ !rawDb.startsWith("!js")) {
1089
+ extraSqliteFiles.push(resolvePatchTargetForBaseRoot(rawDb, baseRoot));
1090
+ }
1091
+ }
1092
+ }
1093
+ }
1094
+ catch {
1095
+ // Best-effort config inspection
1096
+ }
1097
+ return { extraSessionDirs, extraSqliteFiles };
1098
+ }
1099
+ /**
1100
+ * Walks DSH session directories (long-path safe on Windows) and selects only the highest
1101
+ * generation artifact (`session.v4.jsonl.zstd` > `session.v3` > ... > `session.jsonl`)
1102
+ * per session directory while preserving standalone `.jsonl` / `.zstd` / `.zst` / `.json` logs.
1103
+ */
1104
+ async function collectDshSessionFiles(rootDir, ignoreDshRootInternals, maxDepth = 5) {
1105
+ const standaloneFiles = [];
1106
+ const highestGenByDir = new Map();
1107
+ async function visit(currentCleanDir, depth) {
1108
+ if (depth > maxDepth) {
1109
+ return;
1110
+ }
1111
+ let entries;
1112
+ try {
1113
+ entries = await fsp.readdir(toWinLongFsPath(currentCleanDir), {
1114
+ withFileTypes: true,
1115
+ });
1116
+ }
1117
+ catch {
1118
+ return;
1119
+ }
1120
+ const childTasks = [];
1121
+ for (const entry of entries) {
1122
+ if (entry.isDirectory()) {
1123
+ if (depth >= maxDepth)
1124
+ continue;
1125
+ const lowerName = entry.name.toLowerCase();
1126
+ if (entry.name.startsWith(".") ||
1127
+ (ignoreDshRootInternals && depth === 0 && IGNORED_DSH_ROOT_SUBDIRS.has(lowerName)) ||
1128
+ lowerName === "node_modules" ||
1129
+ lowerName === "subagents" ||
1130
+ lowerName === "cache") {
1131
+ continue;
1132
+ }
1133
+ childTasks.push(visit(path.join(currentCleanDir, entry.name), depth + 1));
1134
+ }
1135
+ else if (entry.isFile() && isSupportedDshSessionFileName(entry.name)) {
1136
+ const cleanFullPath = path.join(currentCleanDir, entry.name);
1137
+ const genMatch = CANONICAL_DSH_GEN_RE.exec(entry.name);
1138
+ if (genMatch) {
1139
+ const version = genMatch[1] !== undefined ? Number(genMatch[1]) : 0;
1140
+ // If both plaintext and compressed exist for the same generation, prefer `.jsonl` for zero-decompress overhead
1141
+ const preferScore = entry.name.endsWith(".jsonl") ? 2 : 1;
1142
+ const prev = highestGenByDir.get(currentCleanDir);
1143
+ if (!prev ||
1144
+ version > prev.version ||
1145
+ (version === prev.version && preferScore > prev.preferScore)) {
1146
+ highestGenByDir.set(currentCleanDir, {
1147
+ version,
1148
+ preferScore,
1149
+ filePath: cleanFullPath,
1150
+ });
1151
+ }
1152
+ }
1153
+ else {
1154
+ standaloneFiles.push(cleanFullPath);
1155
+ }
1156
+ }
1157
+ }
1158
+ if (childTasks.length > 0) {
1159
+ await Promise.all(childTasks);
1160
+ }
1161
+ }
1162
+ await visit(stripWinLongFsPrefix(rootDir), 0);
1163
+ // Exclude non-canonical sibling files inside canonical per-session directories
1164
+ const filteredStandalone = standaloneFiles.filter((fp) => !highestGenByDir.has(path.dirname(fp)));
1165
+ return [
1166
+ ...Array.from(highestGenByDir.values(), (v) => v.filePath),
1167
+ ...filteredStandalone,
1168
+ ];
1169
+ }
1170
+ async function parseDshCompressedOrJsonFile(filePath, includeDetails, projCache) {
1171
+ const fsPath = toWinLongFsPath(filePath);
1172
+ const { createdAt, updatedAt } = await safeStatDates(fsPath);
372
1173
  let textContent;
373
- if (filePath.endsWith(".zst")) {
374
- const compressedBuf = await fsp.readFile(filePath);
375
- const decompressed = decompress(new Uint8Array(compressedBuf));
376
- textContent = textDecoder.decode(decompressed);
1174
+ let isPartialSample = false;
1175
+ let sampledRatio = 1;
1176
+ if (isZstdPath(filePath)) {
1177
+ const compressedBuf = await fsp.readFile(fsPath);
1178
+ const decoded = decompressDshZstdBuffer(compressedBuf, !includeDetails);
1179
+ textContent = decoded.text;
1180
+ isPartialSample = decoded.isPartialSample;
1181
+ sampledRatio = decoded.sampledRatio;
377
1182
  }
378
1183
  else {
379
- textContent = await fsp.readFile(filePath, "utf8");
1184
+ textContent = await fsp.readFile(fsPath, "utf8");
380
1185
  }
381
1186
  const trimmed = textContent.trim();
382
1187
  if (!trimmed) {
383
1188
  return null;
384
1189
  }
385
- if ((filePath.endsWith(".json") || filePath.endsWith(".json.zst")) &&
1190
+ const lower = filePath.toLowerCase();
1191
+ if ((lower.endsWith(".json") ||
1192
+ lower.endsWith(".json.zst") ||
1193
+ lower.endsWith(".json.zstd")) &&
386
1194
  !trimmed.includes("\n{")) {
387
1195
  const doc = JSON.parse(trimmed);
388
1196
  if (isJsonRecord(doc)) {
389
- return finalizeDiscoveredSession(extractDshSessionCore(buildDshRecordsFromJsonDoc(doc), filePath, createdAt, updatedAt, includeDetails));
1197
+ return {
1198
+ core: extractDshSessionCore(buildDshRecordsFromJsonDoc(doc), filePath, createdAt, updatedAt, includeDetails, projCache),
1199
+ isPartialSample: false,
1200
+ sampledRatio: 1,
1201
+ };
390
1202
  }
391
1203
  }
392
- const records = parseJsonlRecords(textContent);
393
- return finalizeDiscoveredSession(extractDshSessionCore(records, filePath, createdAt, updatedAt, includeDetails));
1204
+ const records = parseJsonlRecords(textContent, true);
1205
+ return {
1206
+ core: extractDshSessionCore(records, filePath, createdAt, updatedAt, includeDetails, projCache),
1207
+ isPartialSample,
1208
+ sampledRatio,
1209
+ };
1210
+ }
1211
+ function inferDshBaseRootFromSource(cleanSource) {
1212
+ let cursor = path.dirname(cleanSource);
1213
+ for (let depth = 0; depth < 6; depth += 1) {
1214
+ const base = path.basename(cursor).toLowerCase();
1215
+ if (base === ".dsh" || base === "dsh") {
1216
+ return cursor;
1217
+ }
1218
+ if (base === "sessions") {
1219
+ return path.dirname(cursor);
1220
+ }
1221
+ const parent = path.dirname(cursor);
1222
+ if (parent === cursor)
1223
+ break;
1224
+ cursor = parent;
1225
+ }
1226
+ return null;
394
1227
  }
395
1228
  export async function readDshSessionDetail(sourcePath, rawSessionId) {
396
- if (sourcePath.endsWith(".db") || sourcePath.endsWith(".sqlite")) {
397
- if (!(await isRegularFile(sourcePath))) {
1229
+ const cleanSource = stripWinLongFsPrefix(sourcePath);
1230
+ const fsSource = toWinLongFsPath(cleanSource);
1231
+ const inferredBaseRoot = inferDshBaseRootFromSource(cleanSource);
1232
+ const projCache = inferredBaseRoot
1233
+ ? await loadDshProjCacheMap(inferredBaseRoot).catch(() => undefined)
1234
+ : undefined;
1235
+ if (cleanSource.endsWith(".db") || cleanSource.endsWith(".sqlite")) {
1236
+ if (!(await isRegularFile(fsSource))) {
398
1237
  return null;
399
1238
  }
400
- const { updatedAt } = await safeStatDates(sourcePath);
401
- const rows = await withReadOnlySqlite(sourcePath, (db) => extractSessionsFromDshSqlite(db, sourcePath, updatedAt, rawSessionId)).catch(() => []);
1239
+ const { updatedAt } = await safeStatDates(fsSource);
1240
+ const rows = await withReadOnlySqlite(fsSource, (db) => extractSessionsFromDshSqlite(db, cleanSource, updatedAt, rawSessionId, projCache)).catch(() => []);
402
1241
  return rows[0] ?? null;
403
1242
  }
404
- if (sourcePath.endsWith(".jsonl")) {
405
- const bounded = await readJsonlDetailBounded(sourcePath);
1243
+ if (cleanSource.toLowerCase().endsWith(".jsonl")) {
1244
+ const bounded = await readJsonlDetailBounded(fsSource);
406
1245
  if (!bounded || bounded.records.length === 0) {
407
1246
  return null;
408
1247
  }
409
- return finalizeDiscoveredSession(extractDshSessionCore(bounded.records, sourcePath, bounded.createdAt, bounded.updatedAt, true));
1248
+ return finalizeDiscoveredSession(extractDshSessionCore(bounded.records, cleanSource, bounded.createdAt, bounded.updatedAt, true, projCache));
1249
+ }
1250
+ const parsed = await parseDshCompressedOrJsonFile(cleanSource, true, projCache).catch(() => null);
1251
+ if (!parsed) {
1252
+ return null;
410
1253
  }
411
- return parseDshNonPlainFile(sourcePath, true).catch(() => null);
1254
+ return finalizeDiscoveredSession(parsed.core);
412
1255
  }
413
1256
  export async function prepareDshScan(customRoot, fileCache, sqliteCache) {
414
- const baseRoot = resolveDshStorageRoot(customRoot);
415
- if ((baseRoot.endsWith(".db") || baseRoot.endsWith(".sqlite")) &&
416
- (await isRegularFile(baseRoot))) {
1257
+ const primaryRoot = resolveDshStorageRoot(customRoot);
1258
+ if ((primaryRoot.endsWith(".db") || primaryRoot.endsWith(".sqlite")) &&
1259
+ (await isRegularFile(toWinLongFsPath(primaryRoot)))) {
417
1260
  return {
418
1261
  engine: "dsh",
419
- storageRoot: baseRoot,
1262
+ storageRoot: primaryRoot,
420
1263
  storageDetected: true,
421
1264
  totalItems: 1,
422
1265
  runScan: async (onItemDone) => {
423
- const sig = await computeSqliteSignature(baseRoot);
424
- const cached = sig ? sqliteCache.get(baseRoot) : undefined;
1266
+ const sig = await computeSqliteSignature(toWinLongFsPath(primaryRoot));
1267
+ const cached = sig ? sqliteCache.get(primaryRoot) : undefined;
425
1268
  if (cached && cached.signature === sig) {
426
1269
  onItemDone(cached.summaries.length);
427
1270
  return { summaries: cached.summaries, cacheHits: 1 };
428
1271
  }
429
- const { updatedAt } = await safeStatDates(baseRoot);
430
- const details = await withReadOnlySqlite(baseRoot, (db) => extractSessionsFromDshSqlite(db, baseRoot, updatedAt)).catch(() => []);
1272
+ const { updatedAt } = await safeStatDates(toWinLongFsPath(primaryRoot));
1273
+ const details = await withReadOnlySqlite(toWinLongFsPath(primaryRoot), (db) => extractSessionsFromDshSqlite(db, primaryRoot, updatedAt)).catch(() => []);
431
1274
  const summaries = details.map((d) => toSessionSummary(d));
432
1275
  if (sig) {
433
- sqliteCache.set(baseRoot, { signature: sig, summaries });
1276
+ sqliteCache.set(primaryRoot, { signature: sig, summaries });
434
1277
  }
435
1278
  onItemDone(summaries.length);
436
1279
  return { summaries, cacheHits: 0 };
437
1280
  },
438
1281
  };
439
1282
  }
440
- const sessionsSubdir = path.join(baseRoot, "sessions");
441
- const hasSessionsSubdir = await isDirectory(sessionsSubdir);
442
- const hasBaseDir = await isDirectory(baseRoot);
443
- const dataDbPath = path.join(baseRoot, "data.db");
444
- const hasDataDb = await isRegularFile(dataDbPath);
445
- if (!hasBaseDir && !hasSessionsSubdir && !hasDataDb) {
1283
+ const baseRoots = resolveDshStorageRoots(customRoot);
1284
+ const existingBaseDirs = [];
1285
+ const existingSqliteFiles = [];
1286
+ const seenSqlite = new Set();
1287
+ const sessionDirsToWalk = [];
1288
+ const seenWalkDirs = new Set();
1289
+ let detectedStorageRoot;
1290
+ const normKey = (p) => process.platform === "win32" ? p.toLowerCase() : p;
1291
+ for (const baseRoot of baseRoots) {
1292
+ const sessionsSubdir = path.join(baseRoot, "sessions");
1293
+ const hasSessionsSubdir = await isDirectory(toWinLongFsPath(sessionsSubdir));
1294
+ const hasBaseDir = await isDirectory(toWinLongFsPath(baseRoot));
1295
+ if (hasBaseDir) {
1296
+ existingBaseDirs.push(baseRoot);
1297
+ }
1298
+ const sqliteCandidates = [
1299
+ path.join(baseRoot, "data.db"),
1300
+ path.join(baseRoot, "sessions.db"),
1301
+ path.join(sessionsSubdir, "sessions.db"),
1302
+ ];
1303
+ const patchExtras = customRoot
1304
+ ? { extraSessionDirs: [], extraSqliteFiles: [] }
1305
+ : await discoverCustomPatchRoots(baseRoot);
1306
+ for (const dbCand of [...sqliteCandidates, ...patchExtras.extraSqliteFiles]) {
1307
+ const k = normKey(dbCand);
1308
+ if (!seenSqlite.has(k) && (await isRegularFile(toWinLongFsPath(dbCand)))) {
1309
+ seenSqlite.add(k);
1310
+ existingSqliteFiles.push(dbCand);
1311
+ if (!detectedStorageRoot) {
1312
+ detectedStorageRoot = dbCand;
1313
+ }
1314
+ }
1315
+ }
1316
+ if (hasSessionsSubdir) {
1317
+ const k = normKey(sessionsSubdir);
1318
+ if (!seenWalkDirs.has(k)) {
1319
+ seenWalkDirs.add(k);
1320
+ sessionDirsToWalk.push({ dir: sessionsSubdir, ignoreRootInternals: false });
1321
+ }
1322
+ if (!detectedStorageRoot) {
1323
+ detectedStorageRoot = sessionsSubdir;
1324
+ }
1325
+ }
1326
+ else if (hasBaseDir) {
1327
+ const k = normKey(baseRoot);
1328
+ if (!seenWalkDirs.has(k)) {
1329
+ seenWalkDirs.add(k);
1330
+ sessionDirsToWalk.push({ dir: baseRoot, ignoreRootInternals: true });
1331
+ }
1332
+ if (!detectedStorageRoot) {
1333
+ detectedStorageRoot = baseRoot;
1334
+ }
1335
+ }
1336
+ for (const extraDir of patchExtras.extraSessionDirs) {
1337
+ const k = normKey(extraDir);
1338
+ if (!seenWalkDirs.has(k) && (await isDirectory(toWinLongFsPath(extraDir)))) {
1339
+ seenWalkDirs.add(k);
1340
+ sessionDirsToWalk.push({ dir: extraDir, ignoreRootInternals: false });
1341
+ if (!detectedStorageRoot) {
1342
+ detectedStorageRoot = extraDir;
1343
+ }
1344
+ }
1345
+ }
1346
+ }
1347
+ if (existingBaseDirs.length === 0 &&
1348
+ existingSqliteFiles.length === 0 &&
1349
+ sessionDirsToWalk.length === 0) {
446
1350
  return {
447
1351
  engine: "dsh",
448
- storageRoot: sessionsSubdir,
1352
+ storageRoot: path.join(primaryRoot, "sessions"),
449
1353
  storageDetected: false,
450
1354
  totalItems: 0,
451
1355
  runScan: async () => ({ summaries: [], cacheHits: 0 }),
452
1356
  };
453
1357
  }
454
- const scanDir = hasSessionsSubdir ? sessionsSubdir : baseRoot;
455
- const candidateFiles = (await isDirectory(scanDir))
456
- ? await walkFiles(scanDir, (_full, name) => name.endsWith(".jsonl") ||
457
- name.endsWith(".jsonl.zst") ||
458
- name.endsWith(".zst") ||
459
- name.endsWith(".json"), 4)
460
- : [];
461
- const totalItems = candidateFiles.length + (hasDataDb ? 1 : 0);
1358
+ const nestedLists = await Promise.all(sessionDirsToWalk.map(({ dir, ignoreRootInternals }) => collectDshSessionFiles(dir, ignoreRootInternals, 5)));
1359
+ const candidateFiles = Array.from(new Set(nestedLists.flat()));
1360
+ const totalItems = candidateFiles.length + existingSqliteFiles.length;
462
1361
  return {
463
1362
  engine: "dsh",
464
- storageRoot: hasSessionsSubdir ? sessionsSubdir : baseRoot,
1363
+ storageRoot: detectedStorageRoot ?? path.join(primaryRoot, "sessions"),
465
1364
  storageDetected: true,
466
1365
  totalItems,
467
1366
  runScan: async (onItemDone) => {
468
1367
  const sessionMap = new Map();
469
1368
  let cacheHits = 0;
1369
+ const projCache = new Map();
1370
+ if (existingBaseDirs.length > 0) {
1371
+ const maps = await Promise.all(existingBaseDirs.map((dir) => loadDshProjCacheMap(dir)));
1372
+ for (const m of maps) {
1373
+ for (const [k, v] of m) {
1374
+ if (!projCache.has(k)) {
1375
+ projCache.set(k, v);
1376
+ }
1377
+ }
1378
+ }
1379
+ }
470
1380
  await runWithConcurrency(candidateFiles, 16, async (filePath) => {
471
1381
  try {
472
- if (filePath.endsWith(".jsonl")) {
1382
+ const fsPath = toWinLongFsPath(filePath);
1383
+ if (filePath.toLowerCase().endsWith(".jsonl")) {
473
1384
  const { summary, fromCache } = await sampleJsonlFileSummary({
474
- filePath,
1385
+ filePath: fsPath,
475
1386
  cache: fileCache,
476
- parseSummaryFromRecords: (records, fp, createdAt, updatedAt) => finalizeSessionSummary(extractDshSessionCore(records, fp, createdAt, updatedAt, false)),
1387
+ parseSummaryFromRecords: (records, _fp, createdAt, updatedAt) => {
1388
+ const core = extractDshSessionCore(records, filePath, createdAt, updatedAt, false, projCache);
1389
+ if (core.isSubagent) {
1390
+ return null;
1391
+ }
1392
+ return finalizeSessionSummary(core);
1393
+ },
477
1394
  });
478
1395
  if (fromCache)
479
1396
  cacheHits += 1;
480
- if (summary && !sessionMap.has(summary.rawSessionId)) {
481
- sessionMap.set(summary.rawSessionId, summary);
1397
+ const normalizedSummary = summary
1398
+ ? { ...summary, sourcePath: stripWinLongFsPrefix(summary.sourcePath) }
1399
+ : null;
1400
+ if (normalizedSummary &&
1401
+ !sessionMap.has(normalizedSummary.rawSessionId)) {
1402
+ sessionMap.set(normalizedSummary.rawSessionId, normalizedSummary);
482
1403
  onItemDone(1);
483
1404
  }
484
1405
  else {
@@ -486,16 +1407,34 @@ export async function prepareDshScan(customRoot, fileCache, sqliteCache) {
486
1407
  }
487
1408
  return;
488
1409
  }
489
- const stat = await fsp.stat(filePath);
1410
+ const stat = await fsp.stat(fsPath);
490
1411
  const cached = fileCache.get(filePath);
491
1412
  let summary;
492
- if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
1413
+ if (cached &&
1414
+ cached.mtimeMs === stat.mtimeMs &&
1415
+ cached.size === stat.size) {
493
1416
  summary = cached.summary;
494
1417
  cacheHits += 1;
495
1418
  }
496
1419
  else {
497
- const detail = await parseDshNonPlainFile(filePath, false);
498
- summary = detail ? toSessionSummary(detail) : null;
1420
+ const parsed = await parseDshCompressedOrJsonFile(filePath, false, projCache);
1421
+ if (!parsed || parsed.core.isSubagent) {
1422
+ summary = null;
1423
+ }
1424
+ else {
1425
+ const rawSummary = finalizeSessionSummary(parsed.core);
1426
+ if (rawSummary &&
1427
+ parsed.isPartialSample &&
1428
+ parsed.sampledRatio > 0) {
1429
+ summary = {
1430
+ ...rawSummary,
1431
+ messageCount: Math.max(rawSummary.messageCount, Math.round(rawSummary.messageCount / parsed.sampledRatio)),
1432
+ };
1433
+ }
1434
+ else {
1435
+ summary = rawSummary;
1436
+ }
1437
+ }
499
1438
  fileCache.set(filePath, {
500
1439
  mtimeMs: stat.mtimeMs,
501
1440
  size: stat.size,
@@ -514,21 +1453,25 @@ export async function prepareDshScan(customRoot, fileCache, sqliteCache) {
514
1453
  onItemDone(0);
515
1454
  }
516
1455
  });
517
- if (hasDataDb) {
1456
+ for (const dbFilePath of existingSqliteFiles) {
518
1457
  try {
519
- const sig = await computeSqliteSignature(dataDbPath);
520
- const cached = sig ? sqliteCache.get(dataDbPath) : undefined;
1458
+ const fsDbPath = toWinLongFsPath(dbFilePath);
1459
+ const sig = await computeSqliteSignature(fsDbPath);
1460
+ const cached = sig ? sqliteCache.get(dbFilePath) : undefined;
521
1461
  let dbSummaries;
522
1462
  if (cached && cached.signature === sig) {
523
1463
  dbSummaries = cached.summaries;
524
1464
  cacheHits += 1;
525
1465
  }
526
1466
  else {
527
- const { updatedAt } = await safeStatDates(dataDbPath);
528
- const details = await withReadOnlySqlite(dataDbPath, (db) => extractSessionsFromDshSqlite(db, dataDbPath, updatedAt));
1467
+ const { updatedAt } = await safeStatDates(fsDbPath);
1468
+ const details = await withReadOnlySqlite(fsDbPath, (db) => extractSessionsFromDshSqlite(db, dbFilePath, updatedAt, undefined, projCache));
529
1469
  dbSummaries = details.map((d) => toSessionSummary(d));
530
1470
  if (sig) {
531
- sqliteCache.set(dataDbPath, { signature: sig, summaries: dbSummaries });
1471
+ sqliteCache.set(dbFilePath, {
1472
+ signature: sig,
1473
+ summaries: dbSummaries,
1474
+ });
532
1475
  }
533
1476
  }
534
1477
  let added = 0;