@cyfsh/discovery 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -46,14 +46,40 @@ export function parseTimestampToIso(value, fallbackIso) {
46
46
  return fallbackIso;
47
47
  }
48
48
  /**
49
- * Safely parses JSONL content line by line, skipping malformed or partially-written lines.
49
+ * Safely parses JSONL content line by line without allocating a giant `.split()` array.
50
+ * When `skipHeavyToolOutputs` is enabled, multi-kilobyte `tool_result` / `function_call_output`
51
+ * stdout dump lines are bypassed in O(1) before `JSON.parse()`.
50
52
  */
51
- export function parseJsonlRecords(rawContent) {
53
+ export function parseJsonlRecords(rawContent, skipHeavyToolOutputs = false) {
52
54
  const records = [];
53
- const lines = rawContent.split(/\r?\n/);
54
- for (const rawLine of lines) {
55
- const line = rawLine.trim();
56
- if (!line || !line.startsWith("{")) {
55
+ const len = rawContent.length;
56
+ let pos = 0;
57
+ while (pos < len) {
58
+ let nl = rawContent.indexOf("\n", pos);
59
+ if (nl < 0) {
60
+ nl = len;
61
+ }
62
+ let start = pos;
63
+ let end = nl;
64
+ pos = nl + 1;
65
+ while (start < end && rawContent.charCodeAt(start) <= 32) {
66
+ start += 1;
67
+ }
68
+ while (end > start && rawContent.charCodeAt(end - 1) <= 32) {
69
+ end -= 1;
70
+ }
71
+ if (end <= start || rawContent.charCodeAt(start) !== 123 /* '{' */) {
72
+ continue;
73
+ }
74
+ const lineLen = end - start;
75
+ const line = rawContent.slice(start, end);
76
+ if (skipHeavyToolOutputs &&
77
+ lineLen > 2048 &&
78
+ (line.includes('"tool_result"') ||
79
+ line.includes('"function_call_output"') ||
80
+ line.includes('"custom_tool_call_output"')) &&
81
+ !line.includes('"tool_use"') &&
82
+ !line.includes('"output_text"')) {
57
83
  continue;
58
84
  }
59
85
  try {
@@ -80,7 +106,7 @@ function statToIsoDates(stat) {
80
106
  * Avoids reading multi-hundred-MB rollout files (which can even exceed V8's 512MB string limit)
81
107
  * when building the session explorer index.
82
108
  */
83
- export async function readJsonlSummarySlice(filePath, headBytes = 98_304, tailBytes = 24_576) {
109
+ export async function readJsonlSummarySlice(filePath, headBytes = 32_768, tailBytes = 12_288) {
84
110
  let fh;
85
111
  try {
86
112
  fh = await fsp.open(filePath, "r");
@@ -96,7 +122,7 @@ export async function readJsonlSummarySlice(filePath, headBytes = 98_304, tailBy
96
122
  const text = buf.subarray(0, bytesRead).toString("utf8");
97
123
  return {
98
124
  isComplete: true,
99
- records: parseJsonlRecords(text),
125
+ records: parseJsonlRecords(text, true),
100
126
  sampledBytes: bytesRead,
101
127
  size,
102
128
  mtimeMs: stat.mtimeMs,
@@ -104,7 +130,7 @@ export async function readJsonlSummarySlice(filePath, headBytes = 98_304, tailBy
104
130
  updatedAt,
105
131
  };
106
132
  }
107
- // Read head chunk (session_meta, workspace cwd, git branch, initial user prompt)
133
+ // Read compact 32KB head chunk (session_meta, workspace cwd, git branch, initial user prompt)
108
134
  const headBuf = Buffer.allocUnsafe(headBytes);
109
135
  const headRes = await fh.read(headBuf, 0, headBytes, 0);
110
136
  let headText = headBuf.subarray(0, headRes.bytesRead).toString("utf8");
@@ -112,11 +138,11 @@ export async function readJsonlSummarySlice(filePath, headBytes = 98_304, tailBy
112
138
  if (lastHeadNl > 0) {
113
139
  headText = headText.slice(0, lastHeadNl);
114
140
  }
115
- let headRecords = parseJsonlRecords(headText);
141
+ let headRecords = parseJsonlRecords(headText, true);
116
142
  let totalSampled = headRes.bytesRead;
117
- // If line 1/2 had a huge embedded blob/context and yielded <= 1 record, expand head once to 384KB
118
- if (headRecords.length <= 1 && size > headBytes) {
119
- const expandedLen = Math.min(size, 393_216);
143
+ // If line 1/2 had a huge embedded blob/context and yielded <= 2 records, expand head once to 192KB
144
+ if (headRecords.length <= 2 && size > headBytes) {
145
+ const expandedLen = Math.min(size, 196_608);
120
146
  const expBuf = Buffer.allocUnsafe(expandedLen);
121
147
  const expRes = await fh.read(expBuf, 0, expandedLen, 0);
122
148
  let expText = expBuf.subarray(0, expRes.bytesRead).toString("utf8");
@@ -124,10 +150,10 @@ export async function readJsonlSummarySlice(filePath, headBytes = 98_304, tailBy
124
150
  if (lastExpNl > 0) {
125
151
  expText = expText.slice(0, lastExpNl);
126
152
  }
127
- headRecords = parseJsonlRecords(expText);
153
+ headRecords = parseJsonlRecords(expText, true);
128
154
  totalSampled = expRes.bytesRead;
129
155
  }
130
- // Read tail chunk for latest turn timestamp & activity
156
+ // Read compact tail chunk for latest turn timestamp
131
157
  const tailOffset = Math.max(0, size - tailBytes);
132
158
  const tailBuf = Buffer.allocUnsafe(size - tailOffset);
133
159
  const tailRes = await fh.read(tailBuf, 0, tailBuf.length, tailOffset);
@@ -136,7 +162,7 @@ export async function readJsonlSummarySlice(filePath, headBytes = 98_304, tailBy
136
162
  if (firstTailNl >= 0) {
137
163
  tailText = tailText.slice(firstTailNl + 1);
138
164
  }
139
- const tailRecords = parseJsonlRecords(tailText);
165
+ const tailRecords = parseJsonlRecords(tailText, true);
140
166
  return {
141
167
  isComplete: false,
142
168
  records: [...headRecords, ...tailRecords],
@@ -156,10 +182,10 @@ export async function readJsonlSummarySlice(filePath, headBytes = 98_304, tailBy
156
182
  }
157
183
  /**
158
184
  * Bounded full-detail JSONL reader for `getSessionDetail`.
159
- * Reads files <= 6MB in full; for giant 50MB-600MB rollout logs, reads first 1.5MB + last 3.5MB
160
- * on clean newline boundaries so V8 never hits ERR_STRING_TOO_LONG and UI loads in <60ms.
185
+ * Reads files <= 2.5MB in full while bypassing giant `tool_result` stdout dumps before `JSON.parse`;
186
+ * for giant 50MB-600MB rollout logs, reads first 640KB + last 1.85MB on clean newline boundaries.
161
187
  */
162
- export async function readJsonlDetailBounded(filePath, maxFullBytes = 6 * 1024 * 1024) {
188
+ export async function readJsonlDetailBounded(filePath, maxFullBytes = Math.floor(2.5 * 1024 * 1024)) {
163
189
  let fh;
164
190
  try {
165
191
  fh = await fsp.open(filePath, "r");
@@ -172,9 +198,9 @@ export async function readJsonlDetailBounded(filePath, maxFullBytes = 6 * 1024 *
172
198
  const buf = Buffer.allocUnsafe(stat.size);
173
199
  const { bytesRead } = await fh.read(buf, 0, stat.size, 0);
174
200
  const raw = buf.subarray(0, bytesRead).toString("utf8");
175
- return { records: parseJsonlRecords(raw), createdAt, updatedAt };
201
+ return { records: parseJsonlRecords(raw, true), createdAt, updatedAt };
176
202
  }
177
- const headLen = Math.floor(maxFullBytes * 0.3);
203
+ const headLen = Math.floor(maxFullBytes * 0.25);
178
204
  const tailLen = maxFullBytes - headLen;
179
205
  const headBuf = Buffer.allocUnsafe(headLen);
180
206
  const headRes = await fh.read(headBuf, 0, headLen, 0);
@@ -193,7 +219,10 @@ export async function readJsonlDetailBounded(filePath, maxFullBytes = 6 * 1024 *
193
219
  tailText = tailText.slice(firstNl + 1);
194
220
  }
195
221
  return {
196
- records: [...parseJsonlRecords(headText), ...parseJsonlRecords(tailText)],
222
+ records: [
223
+ ...parseJsonlRecords(headText, true),
224
+ ...parseJsonlRecords(tailText, true),
225
+ ],
197
226
  createdAt,
198
227
  updatedAt,
199
228
  };
@@ -231,9 +260,48 @@ export async function runWithConcurrency(items, concurrency, worker) {
231
260
  };
232
261
  await Promise.all(Array.from({ length: laneCount }, () => runLane()));
233
262
  }
263
+ function resolveDashSegmentsOnDisk(rootPrefix, rawRest) {
264
+ const parts = rawRest.split("-").filter(Boolean);
265
+ if (parts.length === 0) {
266
+ return null;
267
+ }
268
+ try {
269
+ if (!fs.existsSync(rootPrefix)) {
270
+ return null;
271
+ }
272
+ let current = rootPrefix;
273
+ let i = 0;
274
+ while (i < parts.length) {
275
+ let matchedNext = null;
276
+ let matchedEnd = i;
277
+ // Greedily match hyphenated directory names (e.g., `do-yourself`, `code-everywhere`) when they exist on disk
278
+ for (let j = Math.min(parts.length, i + 6); j > i; j -= 1) {
279
+ const candidateSeg = parts.slice(i, j).join("-");
280
+ const candidateFull = path.join(current, candidateSeg);
281
+ if (fs.existsSync(candidateFull)) {
282
+ matchedNext = candidateFull;
283
+ matchedEnd = j;
284
+ break;
285
+ }
286
+ }
287
+ if (matchedNext) {
288
+ current = matchedNext;
289
+ i = matchedEnd;
290
+ }
291
+ else {
292
+ current = path.join(current, parts[i] ?? "");
293
+ i += 1;
294
+ }
295
+ }
296
+ return fs.existsSync(current) ? current.replace(/\\/g, "/") : null;
297
+ }
298
+ catch {
299
+ return null;
300
+ }
301
+ }
234
302
  /**
235
303
  * Decodes mangled workspace folder names used by Claude Code (`-Users-alice-app`)
236
- * and CodeBuddy (`C--Codes-app` or `%2FUsers%2Falice%2Fapp`) when JSONL lines omit `cwd`.
304
+ * and CodeBuddy (`C--Codes-app`, `c-Codes-ai-app`, or `%2FUsers%2Falice%2Fapp`) when JSONL lines omit `cwd`.
237
305
  */
238
306
  export function decodeEncodedCwd(encodedDirName) {
239
307
  const trimmed = encodedDirName.trim();
@@ -248,16 +316,29 @@ export function decodeEncodedCwd(encodedDirName) {
248
316
  // Ignore malformed URI sequence and fall through
249
317
  }
250
318
  }
251
- const winDriveMatch = /^([A-Za-z])--(.+)$/.exec(trimmed);
252
- if (winDriveMatch) {
253
- const drive = winDriveMatch[1];
254
- const rest = winDriveMatch[2];
319
+ const winDriveDoubleMatch = /^([A-Za-z])--(.+)$/.exec(trimmed);
320
+ if (winDriveDoubleMatch) {
321
+ const drive = winDriveDoubleMatch[1];
322
+ const rest = winDriveDoubleMatch[2];
255
323
  if (drive && rest) {
256
- return `${drive.toUpperCase()}:/${rest.replace(/-/g, "/")}`;
324
+ const prefix = `${drive.toUpperCase()}:/`;
325
+ return resolveDashSegmentsOnDisk(prefix, rest) ?? `${prefix}${rest.replace(/-/g, "/")}`;
326
+ }
327
+ }
328
+ const winDriveSingleMatch = /^([A-Za-z])-(.+)$/.exec(trimmed);
329
+ if (winDriveSingleMatch) {
330
+ const drive = winDriveSingleMatch[1];
331
+ const rest = winDriveSingleMatch[2];
332
+ if (drive && rest) {
333
+ const resolved = resolveDashSegmentsOnDisk(`${drive.toUpperCase()}:/`, rest);
334
+ if (resolved) {
335
+ return resolved;
336
+ }
257
337
  }
258
338
  }
259
339
  if (trimmed.startsWith("-")) {
260
- return `/${trimmed.slice(1).replace(/-/g, "/")}`;
340
+ const rest = trimmed.slice(1);
341
+ return resolveDashSegmentsOnDisk("/", rest) ?? `/${rest.replace(/-/g, "/")}`;
261
342
  }
262
343
  return trimmed;
263
344
  }
@@ -352,17 +433,251 @@ export function summarizeThinking(rawThinking) {
352
433
  if (!cleaned) {
353
434
  return undefined;
354
435
  }
355
- return cleaned.length > 260 ? `${cleaned.slice(0, 259).trimEnd()}…` : cleaned;
436
+ return cleaned.length > 480 ? `${cleaned.slice(0, 479).trimEnd()}…` : cleaned;
437
+ }
438
+ const SYNTHETIC_USER_PREFIXES = [
439
+ /^\[CE_BTW_SIDE_QUERY\]/i,
440
+ /^\[Request interrupted/i,
441
+ /^<command-name>/i,
442
+ /^<command-message>/i,
443
+ /^<local-command-/i,
444
+ /^#\s*AGENTS\.md instructions\b/i,
445
+ /^<INSTRUCTIONS>/i,
446
+ /^<permissions instructions>/i,
447
+ /^<environment_context>/i,
448
+ /^<collaboration_mode>/i,
449
+ /^<user_instructions>/i,
450
+ /^<subagent_notification>/i,
451
+ /^<agent-teams-message>/i,
452
+ /^#\s*Environment\s*\r?\nYou have been invoked/i,
453
+ ];
454
+ const PLACEHOLDER_TITLE_PATTERN = /^(?:New session\s*-\s*\d{4}-\d{2}-\d{2}|#\s*AGENTS\.md instructions|\[CE_BTW_SIDE_QUERY\]|\[调用工具:|<command-name>|<environment_context>|<permissions instructions>)/i;
455
+ export function isPlaceholderSessionTitle(title) {
456
+ if (!title)
457
+ return true;
458
+ const trimmed = title.trim();
459
+ if (!trimmed)
460
+ return true;
461
+ return PLACEHOLDER_TITLE_PATTERN.test(trimmed);
462
+ }
463
+ function unwrapKanbanMessage(raw) {
464
+ const match = /^<ce-kanban-message>\s*([\s\S]*?)<\/ce-kanban-message>/i.exec(raw.trim());
465
+ if (!match || !match[1])
466
+ return raw;
467
+ const inner = match[1];
468
+ const titleLine = /^Title:\s*(.+)$/m.exec(inner)?.[1]?.trim();
469
+ const contentIdx = inner.indexOf("Content:");
470
+ const contentBody = contentIdx >= 0 ? inner.slice(contentIdx + "Content:".length).trim() : "";
471
+ if (titleLine && contentBody) {
472
+ return `${titleLine}\n\n${contentBody}`;
473
+ }
474
+ return titleLine ?? (contentBody || inner.trim());
475
+ }
476
+ /**
477
+ * Cleans injected CLI system wrappers from user prompts and returns `null` when a record
478
+ * is purely an internal CLI meta/system injection (e.g. AGENTS.md, environment_context, /btw).
479
+ */
480
+ export function sanitizeAndFilterUserPrompt(rawText) {
481
+ let text = rawText.trim();
482
+ if (!text) {
483
+ return null;
484
+ }
485
+ for (const rx of SYNTHETIC_USER_PREFIXES) {
486
+ if (rx.test(text)) {
487
+ return null;
488
+ }
489
+ }
490
+ // 1. Fast-path: only run XML envelope stripping when '<' is actually present
491
+ if (text.includes("<")) {
492
+ text = text
493
+ .replace(/<system-reminder\b[^>]*>[\s\S]*?<\/system-reminder>/gi, "")
494
+ .replace(/<system-reminder\b[^>]*>[\s\S]*$/gi, "")
495
+ .replace(/<environment_context\b[^>]*>[\s\S]*?<\/environment_context>/gi, "")
496
+ .replace(/<permissions instructions>[\s\S]*?<\/permissions instructions>/gi, "")
497
+ .replace(/<collaboration_mode\b[^>]*>[\s\S]*?<\/collaboration_mode>/gi, "")
498
+ .replace(/<user_instructions\b[^>]*>[\s\S]*?<\/user_instructions>/gi, "")
499
+ .replace(/<INSTRUCTIONS\b[^>]*>[\s\S]*?<\/INSTRUCTIONS>/gi, "")
500
+ .replace(/<ADDITIONAL_METADATA\b[^>]*>[\s\S]*?<\/ADDITIONAL_METADATA>/gi, "")
501
+ .replace(/<subagent_notification\b[^>]*>[\s\S]*?<\/subagent_notification>/gi, "")
502
+ .trim();
503
+ }
504
+ if (text.includes("AGENTS.md")) {
505
+ text = text.replace(/^#\s*AGENTS\.md instructions for [^\r\n]+[\r\n]*/gim, "").trim();
506
+ }
507
+ // 2. Unwrap <USER_REQUEST>, <user_query>, and <ce-kanban-message> when '<' is present
508
+ if (text.includes("<")) {
509
+ const userReqMatch = /<USER_REQUEST>\s*([\s\S]*?)\s*<\/USER_REQUEST>/i.exec(text) ??
510
+ /<user_query>\s*([\s\S]*?)\s*<\/user_query>/i.exec(text);
511
+ if (userReqMatch?.[1]) {
512
+ text = userReqMatch[1].trim();
513
+ }
514
+ if (text.startsWith("<ce-kanban-message>")) {
515
+ text = unwrapKanbanMessage(text).trim();
516
+ }
517
+ if (text.startsWith("<user_query>") || text.endsWith("</user_query>")) {
518
+ text = text.replace(/^<user_query>\s*/i, "").replace(/\s*<\/user_query>$/i, "").trim();
519
+ }
520
+ }
521
+ for (const rx of SYNTHETIC_USER_PREFIXES) {
522
+ if (rx.test(text)) {
523
+ return null;
524
+ }
525
+ }
526
+ text = text.replace(/\n{3,}/g, "\n\n").trim();
527
+ return text.length > 0 ? text : null;
528
+ }
529
+ export function sanitizeAssistantMarkdown(rawText) {
530
+ if (!rawText)
531
+ return "";
532
+ let cleaned = rawText;
533
+ if (cleaned.includes("[调用工具:")) {
534
+ cleaned = cleaned.replace(/^\[调用工具:[^\]]*\]$/gm, "");
535
+ }
536
+ if (cleaned.includes("<system-reminder")) {
537
+ cleaned = cleaned.replace(/<system-reminder\b[^>]*>[\s\S]*?<\/system-reminder>/gi, "");
538
+ }
539
+ return cleaned.replace(/\n{3,}/g, "\n\n").trim();
540
+ }
541
+ function buildCanonicalBlocks(content, thinkingSummary, toolCalls) {
542
+ const blocks = [];
543
+ if (thinkingSummary) {
544
+ blocks.push({ type: "thinking", summary: thinkingSummary });
545
+ }
546
+ if (toolCalls && toolCalls.length > 0) {
547
+ for (const tc of toolCalls) {
548
+ blocks.push({
549
+ type: "tool_use",
550
+ name: tc.name,
551
+ summary: tc.summary,
552
+ ...(tc.isSensitive ? { isSensitive: true } : {}),
553
+ });
554
+ }
555
+ }
556
+ if (content.trim().length > 0) {
557
+ blocks.push({ type: "markdown", text: content });
558
+ }
559
+ return blocks;
560
+ }
561
+ /**
562
+ * Enforces the CYF Canonical Turn Protocol across all 5 engines:
563
+ * 1. Drops internal `system` environment dumps and synthetic CLI meta records;
564
+ * 2. Deduplicates consecutive identical user frames (e.g. Codex response_item + event_msg);
565
+ * 3. Coalesces multi-step consecutive `assistant` tool/thinking/text records into a single
566
+ * unified Assistant Turn so 50 tool calls never explode into 50 `[调用工具: ...]` bubbles.
567
+ */
568
+ export function coalesceCanonicalMessages(rawMessages, includeBlocks = true) {
569
+ const normalized = [];
570
+ // Strictly O(N) linear accumulators per coalesced assistant turn
571
+ let pendingThinkingChunks = [];
572
+ let pendingTextChunks = [];
573
+ const flushAssistantAt = (target) => {
574
+ if (!target || target.role !== "assistant")
575
+ return;
576
+ if (pendingTextChunks.length > 0) {
577
+ target.content = pendingTextChunks.join("\n\n");
578
+ pendingTextChunks = [];
579
+ }
580
+ if (pendingThinkingChunks.length > 0) {
581
+ const joined = pendingThinkingChunks.join(" ").slice(0, 1200);
582
+ const summary = summarizeThinking(joined);
583
+ if (summary) {
584
+ target.thinkingSummary = summary;
585
+ }
586
+ pendingThinkingChunks = [];
587
+ }
588
+ if (includeBlocks) {
589
+ target.blocks = buildCanonicalBlocks(target.content, target.thinkingSummary, target.toolCalls);
590
+ }
591
+ };
592
+ for (const msg of rawMessages) {
593
+ if (msg.role === "system") {
594
+ continue;
595
+ }
596
+ if (msg.role === "user") {
597
+ const cleanUser = sanitizeAndFilterUserPrompt(msg.content);
598
+ if (!cleanUser) {
599
+ continue;
600
+ }
601
+ const prev = normalized[normalized.length - 1];
602
+ if (prev && prev.role === "assistant") {
603
+ flushAssistantAt(prev);
604
+ }
605
+ else if (prev && prev.role === "user" && prev.content === cleanUser) {
606
+ continue;
607
+ }
608
+ normalized.push({
609
+ id: msg.id,
610
+ role: "user",
611
+ content: cleanUser,
612
+ timestamp: msg.timestamp,
613
+ ...(includeBlocks
614
+ ? { blocks: [{ type: "markdown", text: cleanUser }] }
615
+ : {}),
616
+ });
617
+ continue;
618
+ }
619
+ // Assistant step — O(1) amortized append without re-cloning arrays or re-running regexes
620
+ const cleanText = sanitizeAssistantMarkdown(msg.content);
621
+ const stepTools = msg.toolCalls ?? [];
622
+ const stepThinking = msg.thinkingSummary?.trim() || undefined;
623
+ if (!cleanText && !stepThinking && stepTools.length === 0) {
624
+ continue;
625
+ }
626
+ const prev = normalized[normalized.length - 1];
627
+ if (prev && prev.role === "assistant") {
628
+ if (cleanText) {
629
+ const lastTxt = pendingTextChunks[pendingTextChunks.length - 1];
630
+ if (lastTxt !== cleanText) {
631
+ pendingTextChunks.push(cleanText);
632
+ }
633
+ }
634
+ if (stepThinking && pendingThinkingChunks.length < 6) {
635
+ const lastTh = pendingThinkingChunks[pendingThinkingChunks.length - 1];
636
+ if (lastTh !== stepThinking) {
637
+ pendingThinkingChunks.push(stepThinking);
638
+ }
639
+ }
640
+ if (stepTools.length > 0) {
641
+ if (!prev.toolCalls) {
642
+ prev.toolCalls = [...stepTools];
643
+ }
644
+ else {
645
+ for (const tc of stepTools) {
646
+ prev.toolCalls.push(tc);
647
+ }
648
+ }
649
+ }
650
+ prev.timestamp = msg.timestamp || prev.timestamp;
651
+ continue;
652
+ }
653
+ pendingTextChunks = cleanText ? [cleanText] : [];
654
+ pendingThinkingChunks = stepThinking ? [stepThinking] : [];
655
+ const mergedMsg = {
656
+ id: msg.id,
657
+ role: "assistant",
658
+ content: cleanText,
659
+ timestamp: msg.timestamp,
660
+ ...(stepTools.length > 0 ? { toolCalls: [...stepTools] } : {}),
661
+ };
662
+ normalized.push(mergedMsg);
663
+ }
664
+ flushAssistantAt(normalized[normalized.length - 1]);
665
+ return normalized;
356
666
  }
357
667
  export function deriveSessionTitle(explicitTitle, messages, workspaceName, rawSessionId) {
358
- if (explicitTitle && explicitTitle.trim().length > 0) {
359
- const cleanExplicit = redactSecrets(explicitTitle).replace(/\s+/g, " ").trim();
360
- return cleanExplicit.length > 96
361
- ? `${cleanExplicit.slice(0, 95).trimEnd()}…`
362
- : cleanExplicit;
668
+ if (explicitTitle && !isPlaceholderSessionTitle(explicitTitle)) {
669
+ const cleanedPrompt = sanitizeAndFilterUserPrompt(explicitTitle) ?? explicitTitle.trim();
670
+ if (!isPlaceholderSessionTitle(cleanedPrompt)) {
671
+ const cleanExplicit = redactSecrets(cleanedPrompt).replace(/\s+/g, " ").trim();
672
+ if (cleanExplicit.length > 0) {
673
+ return cleanExplicit.length > 96
674
+ ? `${cleanExplicit.slice(0, 95).trimEnd()}…`
675
+ : cleanExplicit;
676
+ }
677
+ }
363
678
  }
364
679
  const firstUser = messages.find((m) => m.role === "user" && m.content.trim().length > 0);
365
- const candidate = firstUser ?? messages[0];
680
+ const candidate = firstUser ?? messages.find((m) => m.content.trim().length > 0);
366
681
  if (candidate) {
367
682
  const clean = redactSecrets(candidate.content).replace(/\s+/g, " ").trim();
368
683
  if (clean.length > 0) {
@@ -372,17 +687,32 @@ export function deriveSessionTitle(explicitTitle, messages, workspaceName, rawSe
372
687
  return `${workspaceName} (${rawSessionId.slice(0, 12)})`;
373
688
  }
374
689
  export function finalizeSessionSummary(params) {
375
- const msgCount = params.estimatedMessageCount ?? params.messages.length;
376
- if (msgCount === 0 && params.messages.length === 0) {
690
+ const canonicalMessages = params.alreadyCoalesced
691
+ ? params.messages
692
+ : coalesceCanonicalMessages(params.messages, false);
693
+ const hasExplicitValidTitle = Boolean(params.explicitTitle) && !isPlaceholderSessionTitle(params.explicitTitle);
694
+ // If messages were parsed, require at least 1 real user turn (or explicit non-placeholder title)
695
+ if (params.messages.length > 0 &&
696
+ canonicalMessages.length === 0 &&
697
+ !hasExplicitValidTitle) {
698
+ return null;
699
+ }
700
+ if (canonicalMessages.length > 0 &&
701
+ !canonicalMessages.some((m) => m.role === "user") &&
702
+ !hasExplicitValidTitle) {
703
+ return null;
704
+ }
705
+ const msgCount = params.estimatedMessageCount ?? canonicalMessages.length;
706
+ if (msgCount === 0 && canonicalMessages.length === 0) {
377
707
  return null;
378
708
  }
379
709
  const normalizedWorkspace = params.workspacePath.trim().length > 0 ? params.workspacePath.trim() : "/unknown-workspace";
380
710
  const workspaceName = extractWorkspaceName(normalizedWorkspace);
381
- const firstMsg = params.messages[0];
382
- const lastMsg = params.messages[params.messages.length - 1];
711
+ const firstMsg = canonicalMessages[0];
712
+ const lastMsg = canonicalMessages[canonicalMessages.length - 1];
383
713
  const createdAt = firstMsg?.timestamp ?? params.fallbackCreatedAt;
384
714
  const updatedAt = lastMsg?.timestamp ?? params.fallbackUpdatedAt;
385
- const title = deriveSessionTitle(params.explicitTitle, params.messages, workspaceName, params.rawSessionId);
715
+ const title = deriveSessionTitle(params.explicitTitle, canonicalMessages, workspaceName, params.rawSessionId);
386
716
  return {
387
717
  id: `${params.engine}:${params.rawSessionId}`,
388
718
  rawSessionId: params.rawSessionId,
@@ -391,7 +721,7 @@ export function finalizeSessionSummary(params) {
391
721
  workspacePath: normalizedWorkspace,
392
722
  workspaceName,
393
723
  sourcePath: params.sourcePath,
394
- messageCount: Math.max(msgCount, params.messages.length),
724
+ messageCount: Math.max(msgCount, canonicalMessages.length),
395
725
  createdAt,
396
726
  updatedAt,
397
727
  ...(params.gitBranch ? { gitBranch: params.gitBranch } : {}),
@@ -399,14 +729,20 @@ export function finalizeSessionSummary(params) {
399
729
  };
400
730
  }
401
731
  export function finalizeDiscoveredSession(params) {
402
- const summary = finalizeSessionSummary(params);
732
+ const canonicalMessages = coalesceCanonicalMessages(params.messages, true);
733
+ const summary = finalizeSessionSummary({
734
+ ...params,
735
+ messages: canonicalMessages,
736
+ alreadyCoalesced: true,
737
+ });
403
738
  if (!summary) {
404
739
  return null;
405
740
  }
406
741
  return {
407
742
  ...summary,
408
- messages: params.messages,
409
- suggestedCapsule: buildSanitizedCapsule(params.messages, summary.workspaceName),
743
+ messageCount: canonicalMessages.length,
744
+ messages: canonicalMessages,
745
+ suggestedCapsule: buildSanitizedCapsule(canonicalMessages, summary.workspaceName),
410
746
  };
411
747
  }
412
748
  export function toSessionSummary(detail) {
@@ -480,6 +816,17 @@ export async function isRegularFile(targetPath) {
480
816
  return false;
481
817
  }
482
818
  }
819
+ const IGNORED_SUBDIR_NAMES = new Set([
820
+ "subagents",
821
+ "memory",
822
+ "tool-results",
823
+ "artifacts",
824
+ "logs",
825
+ "cache",
826
+ "blobs",
827
+ "node_modules",
828
+ ".git",
829
+ ]);
483
830
  export async function walkFiles(rootDir, predicate, maxDepth = 6) {
484
831
  const collected = [];
485
832
  async function visit(currentDir, depth) {
@@ -493,15 +840,23 @@ export async function walkFiles(rootDir, predicate, maxDepth = 6) {
493
840
  catch {
494
841
  return;
495
842
  }
843
+ const childDirTasks = [];
496
844
  for (const entry of entries) {
497
- const fullPath = path.join(currentDir, entry.name);
498
845
  if (entry.isDirectory()) {
499
- await visit(fullPath, depth + 1);
846
+ if (depth < maxDepth && !IGNORED_SUBDIR_NAMES.has(entry.name.toLowerCase())) {
847
+ childDirTasks.push(visit(path.join(currentDir, entry.name), depth + 1));
848
+ }
500
849
  }
501
- else if (entry.isFile() && predicate(fullPath, entry.name)) {
502
- collected.push(fullPath);
850
+ else if (entry.isFile()) {
851
+ const fullPath = path.join(currentDir, entry.name);
852
+ if (predicate(fullPath, entry.name)) {
853
+ collected.push(fullPath);
854
+ }
503
855
  }
504
856
  }
857
+ if (childDirTasks.length > 0) {
858
+ await Promise.all(childDirTasks);
859
+ }
505
860
  }
506
861
  await visit(rootDir, 0);
507
862
  return collected;