@threadbase-sh/scanner 0.21.1 → 0.23.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.
Files changed (37) hide show
  1. package/README.md +3 -1
  2. package/dist/cli.js +481 -123
  3. package/dist/cli.js.map +1 -1
  4. package/dist/index.cjs +564 -147
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.ts +3 -0
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +536 -128
  9. package/dist/index.js.map +1 -1
  10. package/dist/name-stores.d.ts +13 -0
  11. package/dist/name-stores.d.ts.map +1 -0
  12. package/dist/parser.d.ts.map +1 -1
  13. package/dist/persistent/claude-name-slots.d.ts +3 -0
  14. package/dist/persistent/claude-name-slots.d.ts.map +1 -0
  15. package/dist/persistent/conversation-reducer.d.ts +2 -1
  16. package/dist/persistent/conversation-reducer.d.ts.map +1 -1
  17. package/dist/persistent/conversation-stream.d.ts.map +1 -1
  18. package/dist/persistent/index-engine.d.ts.map +1 -1
  19. package/dist/persistent/metadata-reducer.d.ts +2 -4
  20. package/dist/persistent/metadata-reducer.d.ts.map +1 -1
  21. package/dist/persistent/migrations.d.ts.map +1 -1
  22. package/dist/persistent/repositories/conversations.repo.d.ts +1 -0
  23. package/dist/persistent/repositories/conversations.repo.d.ts.map +1 -1
  24. package/dist/persistent/schema.d.ts +2 -2
  25. package/dist/persistent/schema.d.ts.map +1 -1
  26. package/dist/providers/codex-cli.d.ts +3 -6
  27. package/dist/providers/codex-cli.d.ts.map +1 -1
  28. package/dist/providers/copilot.d.ts +2 -0
  29. package/dist/providers/copilot.d.ts.map +1 -1
  30. package/dist/providers/cursor.d.ts +2 -0
  31. package/dist/providers/cursor.d.ts.map +1 -1
  32. package/dist/scanner.d.ts.map +1 -1
  33. package/dist/session-name.d.ts +24 -0
  34. package/dist/session-name.d.ts.map +1 -0
  35. package/dist/types.d.ts +3 -0
  36. package/dist/types.d.ts.map +1 -1
  37. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -350,13 +350,329 @@ function toIndexDoc(meta, searchContent) {
350
350
  };
351
351
  }
352
352
 
353
+ // src/name-stores.ts
354
+ import Database from "better-sqlite3";
355
+ import { closeSync, existsSync, openSync, readdirSync, readFileSync as readFileSync2, readSync, statSync } from "fs";
356
+ import { basename, dirname as dirname2, join as join2 } from "path";
357
+
358
+ // src/tags.ts
359
+ var SYSTEM_TAGS = [
360
+ "system-reminder",
361
+ "command-name",
362
+ "command-message",
363
+ "command-args",
364
+ "ide_selection",
365
+ "ide_opened_file",
366
+ "local-command-stdout",
367
+ "local-command-caveat",
368
+ "retrieval_status",
369
+ "task_id",
370
+ "task_type",
371
+ "task-id",
372
+ "task-notification",
373
+ "fast_mode_info",
374
+ "persisted-output",
375
+ "tool_use_error",
376
+ "user-prompt-submit-hook",
377
+ "thinking",
378
+ "ask_user",
379
+ "teammate-message"
380
+ ];
381
+ var SYSTEM_TAG_RE = new RegExp(`<(${SYSTEM_TAGS.join("|")})[^>]*>[\\s\\S]*?<\\/\\1>`, "g");
382
+ var PASTED_CONTENT_RE = /<pasted_content id="[0-9a-f]{4}">([\s\S]*?)<\/pasted_content(?: id="[0-9a-f]{4}")?>/g;
383
+ function cleanSystemTags(text) {
384
+ return text.replace(SYSTEM_TAG_RE, "").replace(PASTED_CONTENT_RE, "$1").replace(/[^\S\n]+/g, " ").replace(/\n{3,}/g, "\n\n").trim();
385
+ }
386
+
387
+ // src/session-name.ts
388
+ var NAME_PRECEDENCE = [
389
+ "userTitle",
390
+ "toolTitle",
391
+ "lastPrompt",
392
+ "firstUserMessage",
393
+ "slug"
394
+ ];
395
+ var CLAUDE_SYSTEM_PREFIXES = [
396
+ "<command-name>",
397
+ "<command-message>",
398
+ "<command-args>",
399
+ "<local-command-stdout>",
400
+ "<local-command-stderr>",
401
+ "<local-command-caveat>",
402
+ "<bash-input>",
403
+ "<bash-stdout>",
404
+ "<bash-stderr>",
405
+ "<system-reminder>",
406
+ "<task-notification>",
407
+ "<teammate-message",
408
+ "Another Claude session sent a message:",
409
+ "[Request interrupted by user"
410
+ ];
411
+ var CODEX_SYSTEM_PREFIXES = [
412
+ "<environment_context>",
413
+ "# AGENTS.md instructions",
414
+ "<user_instructions>",
415
+ "<INSTRUCTIONS>",
416
+ "<external_codex_apps_open",
417
+ "<user_shell_command>",
418
+ "<turn_aborted>"
419
+ ];
420
+ function isCodexInjectedContext(text) {
421
+ if (text.startsWith("# AGENTS.md") || text.includes("<INSTRUCTIONS>")) return true;
422
+ return text.startsWith("<permissions instructions>") || text.includes("Filesystem sandboxing defines");
423
+ }
424
+ var CODEX_IMAGE_TAG_RE = /<\/?image\b[^>]*>/g;
425
+ function normalizeCandidate(text, provider) {
426
+ let t = text.trim();
427
+ if (provider === "codex-cli") t = t.replace(CODEX_IMAGE_TAG_RE, "").trim();
428
+ const prefixes = provider === "claude-code" ? CLAUDE_SYSTEM_PREFIXES : provider === "codex-cli" ? CODEX_SYSTEM_PREFIXES : [];
429
+ if (prefixes.some((p) => t.startsWith(p))) return null;
430
+ if (provider === "codex-cli" && isCodexInjectedContext(t)) return null;
431
+ return cleanSystemTags(t) || null;
432
+ }
433
+ function isValidNameCandidate(text, provider) {
434
+ return normalizeCandidate(text, provider) !== null;
435
+ }
436
+ function resolveSessionName(slots) {
437
+ for (const slot of NAME_PRECEDENCE) {
438
+ const value = slots[slot];
439
+ if (value?.trim()) return { name: value, source: slot };
440
+ }
441
+ return { name: null, source: null };
442
+ }
443
+ function applyNameCandidate(slots, slot, raw, provider) {
444
+ if (typeof raw !== "string") return slots;
445
+ if (slot === "firstUserMessage" && slots.firstUserMessage !== void 0) return slots;
446
+ const text = normalizeCandidate(raw, provider);
447
+ return text === null ? slots : { ...slots, [slot]: text };
448
+ }
449
+
450
+ // src/name-stores.ts
451
+ function slotsFrom(provider, candidates) {
452
+ return candidates.reduce(
453
+ (slots, [slot, raw]) => applyNameCandidate(slots, slot, typeof raw === "string" ? raw : void 0, provider),
454
+ {}
455
+ );
456
+ }
457
+ function readJson(path) {
458
+ try {
459
+ return JSON.parse(readFileSync2(path, "utf8"));
460
+ } catch {
461
+ return void 0;
462
+ }
463
+ }
464
+ function queryOne(dbPath, sql, ...params) {
465
+ let db;
466
+ try {
467
+ db = new Database(dbPath, { readonly: true, fileMustExist: true, timeout: 250 });
468
+ return db.prepare(sql).get(...params);
469
+ } catch (err) {
470
+ getLogger().debug({ dbPath, err }, "name store: query failed");
471
+ return void 0;
472
+ } finally {
473
+ db?.close();
474
+ }
475
+ }
476
+ var lastByIdCache = /* @__PURE__ */ new Map();
477
+ function lastValueById(path, idField, valueField) {
478
+ let sig;
479
+ try {
480
+ const s = statSync(path);
481
+ sig = `${s.mtimeMs}:${s.size}`;
482
+ } catch {
483
+ return /* @__PURE__ */ new Map();
484
+ }
485
+ const key = `${path}\0${idField}\0${valueField}`;
486
+ const cached = lastByIdCache.get(key);
487
+ if (cached?.sig === sig) return cached.map;
488
+ const map = /* @__PURE__ */ new Map();
489
+ try {
490
+ for (const line of readFileSync2(path, "utf8").split("\n")) {
491
+ if (!line.trim()) continue;
492
+ try {
493
+ const row = JSON.parse(line);
494
+ const id = row[idField];
495
+ const value = row[valueField];
496
+ if (typeof id === "string" && typeof value === "string") map.set(id, value);
497
+ } catch {
498
+ }
499
+ }
500
+ } catch {
501
+ }
502
+ lastByIdCache.set(key, { sig, map });
503
+ return map;
504
+ }
505
+ function readCodexNameSlots(codexHome, id) {
506
+ const index = lastValueById(join2(codexHome, "session_index.jsonl"), "id", "thread_name");
507
+ const history = lastValueById(join2(codexHome, "history.jsonl"), "session_id", "text");
508
+ let title = index.get(id);
509
+ if (!index.has(id)) {
510
+ title = queryOne(
511
+ join2(codexHome, "state_5.sqlite"),
512
+ "SELECT name FROM threads WHERE id = ?",
513
+ id
514
+ )?.name;
515
+ }
516
+ return slotsFrom("codex-cli", [
517
+ ["toolTitle", title],
518
+ ["lastPrompt", history.get(id)]
519
+ ]);
520
+ }
521
+ function readCursorCliNameSlots(chatsDir, id) {
522
+ let chat;
523
+ try {
524
+ chat = readdirSync(chatsDir).map((hash) => join2(chatsDir, hash, id)).find((p) => existsSync(p));
525
+ } catch {
526
+ }
527
+ if (!chat) return {};
528
+ const meta = readJson(join2(chat, "meta.json"));
529
+ const history = readJson(join2(chat, "prompt_history.json"));
530
+ let title = meta?.title;
531
+ if (typeof title !== "string" || !title.trim()) title = storeDbName(join2(chat, "store.db"));
532
+ return slotsFrom("cursor", [
533
+ ["toolTitle", title],
534
+ ["lastPrompt", Array.isArray(history) ? history[0] : void 0]
535
+ ]);
536
+ }
537
+ function storeDbName(dbPath) {
538
+ const row = queryOne(
539
+ dbPath,
540
+ "SELECT value FROM meta WHERE key = '0'"
541
+ );
542
+ if (!row) return void 0;
543
+ try {
544
+ const text = row.value.toString();
545
+ const json = /^(?:[0-9a-f]{2})+$/i.test(text) ? Buffer.from(text, "hex").toString("utf8") : text;
546
+ const name = JSON.parse(json).name;
547
+ return typeof name === "string" ? name : void 0;
548
+ } catch {
549
+ return void 0;
550
+ }
551
+ }
552
+ function readCursorIdeNameSlots(stateDbPath, id) {
553
+ const row = queryOne(
554
+ stateDbPath,
555
+ "SELECT json_extract(CAST(value AS TEXT), '$.name') AS name FROM cursorDiskKV WHERE key = ?",
556
+ `composerData:${id}`
557
+ );
558
+ return slotsFrom("cursor", [["toolTitle", row?.name]]);
559
+ }
560
+ function yamlScalar(text, key) {
561
+ const m = text.match(new RegExp(`^${key}:[ \\t]*(.*)$`, "m"));
562
+ const v = m?.[1].trim().replace(/^(["'])(.*)\1$/, "$2");
563
+ return v || void 0;
564
+ }
565
+ function readCopilotTitleSlots(sessionDir) {
566
+ const id = basename(sessionDir);
567
+ let yaml = "";
568
+ try {
569
+ yaml = readFileSync2(join2(sessionDir, "workspace.yaml"), "utf8");
570
+ } catch {
571
+ }
572
+ const name = yamlScalar(yaml, "name");
573
+ if (name) {
574
+ return slotsFrom("copilot", [
575
+ [yamlScalar(yaml, "user_named") === "true" ? "userTitle" : "toolTitle", name]
576
+ ]);
577
+ }
578
+ const row = queryOne(
579
+ join2(dirname2(dirname2(sessionDir)), "session-store.db"),
580
+ "SELECT summary FROM sessions WHERE id = ?",
581
+ id
582
+ );
583
+ return slotsFrom("copilot", [["toolTitle", row?.summary]]);
584
+ }
585
+ function readCopilotNameSlots(sessionDir) {
586
+ return {
587
+ ...readCopilotTitleSlots(sessionDir),
588
+ ...slotsFrom("copilot", [
589
+ ["firstUserMessage", firstCopilotUserMessage(join2(sessionDir, "events.jsonl"))]
590
+ ])
591
+ };
592
+ }
593
+ function firstCopilotUserMessage(path) {
594
+ let fd;
595
+ try {
596
+ fd = openSync(path, "r");
597
+ } catch {
598
+ return void 0;
599
+ }
600
+ try {
601
+ const buf = Buffer.alloc(64 * 1024);
602
+ let pending = "";
603
+ for (let n = readSync(fd, buf, 0, buf.length, null); n > 0; n = readSync(fd, buf, 0, buf.length, null)) {
604
+ pending += buf.toString("utf8", 0, n);
605
+ const lines = pending.split("\n");
606
+ pending = lines.pop() ?? "";
607
+ for (const line of lines) {
608
+ try {
609
+ const e = JSON.parse(line);
610
+ if (e.type === "user.message" && typeof e.data?.content === "string")
611
+ return e.data.content;
612
+ } catch {
613
+ }
614
+ }
615
+ }
616
+ return void 0;
617
+ } catch {
618
+ return void 0;
619
+ } finally {
620
+ closeSync(fd);
621
+ }
622
+ }
623
+ function findUp(start, hasStore, levels) {
624
+ let dir = start;
625
+ for (let i = 0; i < levels; i++) {
626
+ if (hasStore(dir)) return dir;
627
+ const parent = dirname2(dir);
628
+ if (parent === dir) break;
629
+ dir = parent;
630
+ }
631
+ return null;
632
+ }
633
+ function codexNameSlotsFor(rolloutPath, id) {
634
+ const home = findUp(
635
+ dirname2(rolloutPath),
636
+ (d) => ["session_index.jsonl", "history.jsonl", "state_5.sqlite"].some(
637
+ (f) => existsSync(join2(d, f))
638
+ ),
639
+ 6
640
+ );
641
+ return home ? readCodexNameSlots(home, id) : {};
642
+ }
643
+ var cursorStateDb;
644
+ function setCursorStateDb(path) {
645
+ cursorStateDb = path;
646
+ }
647
+ function cursorNameSlotsFor(transcriptPath, id) {
648
+ const home = findUp(dirname2(transcriptPath), (d) => existsSync(join2(d, "chats")), 6);
649
+ const cli = home ? readCursorCliNameSlots(join2(home, "chats"), id) : {};
650
+ if (cli.toolTitle || !cursorStateDb) return cli;
651
+ return { ...cli, ...readCursorIdeNameSlots(cursorStateDb, id) };
652
+ }
653
+ function copilotNameSlotsFor(eventsPath) {
654
+ return readCopilotTitleSlots(dirname2(eventsPath));
655
+ }
656
+ function nameStoreSlotsFor(provider, filePath, sessionId) {
657
+ switch (provider) {
658
+ case "codex-cli":
659
+ return codexNameSlotsFor(filePath, sessionId);
660
+ case "cursor":
661
+ return cursorNameSlotsFor(filePath, basename(filePath, ".jsonl"));
662
+ case "copilot":
663
+ return copilotNameSlotsFor(filePath);
664
+ default:
665
+ return {};
666
+ }
667
+ }
668
+
353
669
  // src/parser.ts
354
670
  import { createReadStream } from "fs";
355
- import { basename as basename2 } from "path";
671
+ import { basename as basename3 } from "path";
356
672
  import { createInterface } from "readline";
357
673
 
358
674
  // src/persistent/metadata-reducer.ts
359
- import { basename, dirname as dirname2, join as join2 } from "path";
675
+ import { basename as basename2, dirname as dirname3, join as join3 } from "path";
360
676
 
361
677
  // src/providers/provider.ts
362
678
  var CLAUDE_CODE_PROVIDER = "claude-code";
@@ -386,11 +702,36 @@ function providerMatches(stored, wanted) {
386
702
  return a === b;
387
703
  }
388
704
 
705
+ // src/persistent/claude-name-slots.ts
706
+ function userPromptText(entry) {
707
+ if (entry.isMeta || entry.isCompactSummary === true) return "";
708
+ const content = entry.message?.content;
709
+ if (typeof content === "string") return content;
710
+ if (!Array.isArray(content)) return "";
711
+ return content.map((b) => typeof b === "string" ? b : b?.type === "text" ? b.text : "").filter((t) => typeof t === "string" && t !== "").join(" ");
712
+ }
713
+ function applyClaudeNameEntry(slots, entry) {
714
+ const apply = (slot, raw) => applyNameCandidate(slots, slot, typeof raw === "string" ? raw : void 0, "claude-code");
715
+ if (entry.slug !== slots.slug) slots = apply("slug", entry.slug);
716
+ switch (entry.type) {
717
+ case "custom-title":
718
+ return apply("userTitle", entry.customTitle);
719
+ case "ai-title":
720
+ return apply("toolTitle", entry.aiTitle);
721
+ case "last-prompt":
722
+ return apply("lastPrompt", entry.lastPrompt);
723
+ case "user":
724
+ return slots.firstUserMessage === void 0 ? apply("firstUserMessage", userPromptText(entry)) : slots;
725
+ default:
726
+ return slots;
727
+ }
728
+ }
729
+
389
730
  // src/persistent/metadata-reducer.ts
390
731
  function initialReducerState() {
391
732
  return {
392
733
  sessionId: "",
393
- sessionName: "",
734
+ nameSlots: {},
394
735
  latestTimestamp: "",
395
736
  cwd: "",
396
737
  teamName: "",
@@ -416,7 +757,7 @@ function initialReducerState() {
416
757
  function reduceLine(state, entry, tier) {
417
758
  if (entry.cwd && !state.cwd) state.cwd = entry.cwd;
418
759
  if (entry.sessionId && !state.sessionId) state.sessionId = entry.sessionId;
419
- if (entry.slug && !state.sessionName) state.sessionName = entry.slug;
760
+ state.nameSlots = applyClaudeNameEntry(state.nameSlots, entry);
420
761
  if (entry.teamName && !state.teamName) state.teamName = entry.teamName;
421
762
  if (entry.agentId && !state.agentId) state.agentId = entry.agentId;
422
763
  if (entry.isSidechain === true) state.isSidechain = true;
@@ -480,16 +821,17 @@ function finalizeMeta(state, filePath, account, tier) {
480
821
  const isSubagent = isSidechain || isSubagentPath;
481
822
  let parentSessionId = null;
482
823
  if (isSubagentPath) {
483
- const uuidDir = dirname2(dirname2(filePath));
484
- parentSessionId = join2(dirname2(uuidDir), `${basename(uuidDir)}.jsonl`);
824
+ const uuidDir = dirname3(dirname3(filePath));
825
+ parentSessionId = join3(dirname3(uuidDir), `${basename2(uuidDir)}.jsonl`);
485
826
  }
486
827
  const projectPath = state.cwd;
487
828
  return {
488
829
  id: filePath,
489
830
  filePath,
490
831
  provider: CLAUDE_CODE_PROVIDER,
491
- sessionId: state.sessionId || basename(filePath, ".jsonl"),
492
- sessionName: state.sessionName || deriveSessionNameFromFirstMessage(state.firstMessage),
832
+ sessionId: state.sessionId || basename2(filePath, ".jsonl"),
833
+ sessionName: resolveSessionName(state.nameSlots).name ?? "",
834
+ nameSlots: state.nameSlots,
493
835
  projectPath,
494
836
  projectName: getShortProjectName(projectPath),
495
837
  account,
@@ -515,44 +857,11 @@ function finalizeMeta(state, filePath, account, tier) {
515
857
  };
516
858
  }
517
859
  var SUBAGENT_PATH_RE = /[\\/]subagents[\\/]/;
518
- function deriveSessionNameFromFirstMessage(firstMessage) {
519
- const firstLine = firstMessage?.text.split("\n", 1)[0]?.trim() ?? "";
520
- return firstLine.slice(0, 80);
521
- }
522
860
  function getShortProjectName(fullPath) {
523
861
  const parts = fullPath.split("/").filter(Boolean);
524
862
  return parts.slice(-3).join("/");
525
863
  }
526
864
 
527
- // src/tags.ts
528
- var SYSTEM_TAGS = [
529
- "system-reminder",
530
- "command-name",
531
- "command-message",
532
- "command-args",
533
- "ide_selection",
534
- "ide_opened_file",
535
- "local-command-stdout",
536
- "local-command-caveat",
537
- "retrieval_status",
538
- "task_id",
539
- "task_type",
540
- "task-id",
541
- "task-notification",
542
- "fast_mode_info",
543
- "persisted-output",
544
- "tool_use_error",
545
- "user-prompt-submit-hook",
546
- "thinking",
547
- "ask_user",
548
- "teammate-message"
549
- ];
550
- var SYSTEM_TAG_RE = new RegExp(`<(${SYSTEM_TAGS.join("|")})[^>]*>[\\s\\S]*?<\\/\\1>`, "g");
551
- var PASTED_CONTENT_RE = /<pasted_content id="[0-9a-f]{4}">([\s\S]*?)<\/pasted_content(?: id="[0-9a-f]{4}")?>/g;
552
- function cleanSystemTags(text) {
553
- return text.replace(SYSTEM_TAG_RE, "").replace(PASTED_CONTENT_RE, "$1").replace(/[^\S\n]+/g, " ").replace(/\n{3,}/g, "\n\n").trim();
554
- }
555
-
556
865
  // src/parser.ts
557
866
  async function parseMeta(filePath, account, tier, onEntry) {
558
867
  const log = getLogger();
@@ -639,10 +948,8 @@ async function parseConversation(filePath, account) {
639
948
  filePath,
640
949
  projectPath: state.cwd,
641
950
  projectName: getShortProjectName2(state.cwd),
642
- sessionId: state.sessionId || basename2(filePath, ".jsonl"),
643
- sessionName: state.sessionName || deriveSessionNameFromFirstMessage(
644
- messages.find((m) => m.role === "user" && m.text && !m.isCompactSummary) ?? null
645
- ),
951
+ sessionId: state.sessionId || basename3(filePath, ".jsonl"),
952
+ sessionName: resolveSessionName(state.nameSlots).name ?? "",
646
953
  messages,
647
954
  fullText: textParts.join(" "),
648
955
  timestamp: state.latestTimestamp || (/* @__PURE__ */ new Date()).toISOString(),
@@ -752,7 +1059,7 @@ function initialConvState() {
752
1059
  return {
753
1060
  cwd: "",
754
1061
  sessionId: "",
755
- sessionName: "",
1062
+ nameSlots: {},
756
1063
  latestTimestamp: "",
757
1064
  lastPrompt: "",
758
1065
  pendingToolUses: {},
@@ -762,7 +1069,7 @@ function initialConvState() {
762
1069
  function reduceConvLine(state, entry) {
763
1070
  if (entry.cwd && !state.cwd) state.cwd = entry.cwd;
764
1071
  if (entry.sessionId && !state.sessionId) state.sessionId = entry.sessionId;
765
- if (entry.slug && !state.sessionName) state.sessionName = entry.slug;
1072
+ state.nameSlots = applyClaudeNameEntry(state.nameSlots, entry);
766
1073
  if (entry.timestamp) {
767
1074
  const ts = entry.timestamp;
768
1075
  if (!state.latestTimestamp || ts > state.latestTimestamp) state.latestTimestamp = ts;
@@ -870,7 +1177,7 @@ function applyTeamInfo(messages, state) {
870
1177
  }
871
1178
 
872
1179
  // src/persistent/sidecar.ts
873
- import { readFileSync as readFileSync2, writeFileSync } from "fs";
1180
+ import { readFileSync as readFileSync3, writeFileSync } from "fs";
874
1181
  var SIDECAR_VERSION = 1;
875
1182
  function sidecarPath(jsonlPath) {
876
1183
  return `${jsonlPath}.idx.json`;
@@ -903,7 +1210,7 @@ function writeSidecar(jsonlPath, sidecar) {
903
1210
  }
904
1211
  function readSidecar(jsonlPath) {
905
1212
  try {
906
- return JSON.parse(readFileSync2(sidecarPath(jsonlPath), "utf-8"));
1213
+ return JSON.parse(readFileSync3(sidecarPath(jsonlPath), "utf-8"));
907
1214
  } catch {
908
1215
  return null;
909
1216
  }
@@ -912,19 +1219,19 @@ function readSidecar(jsonlPath) {
912
1219
  // src/profiles.ts
913
1220
  import { mkdir, readFile, writeFile } from "fs/promises";
914
1221
  import { homedir } from "os";
915
- import { join as join3 } from "path";
1222
+ import { join as join4 } from "path";
916
1223
  var PROFILES_FILE = "profiles.json";
917
1224
  function resolveConfigDir(configDir) {
918
1225
  return configDir.replace(/^~/, homedir());
919
1226
  }
920
1227
  function getProjectsDir(profile) {
921
- return join3(resolveConfigDir(profile.configDir), "projects");
1228
+ return join4(resolveConfigDir(profile.configDir), "projects");
922
1229
  }
923
1230
  async function detectDefaultProfile() {
924
1231
  return {
925
1232
  id: "default",
926
1233
  label: "Default",
927
- configDir: join3(homedir(), ".claude"),
1234
+ configDir: join4(homedir(), ".claude"),
928
1235
  enabled: true,
929
1236
  emoji: "\u{1F916}"
930
1237
  };
@@ -933,7 +1240,7 @@ async function loadProfiles(configPath) {
933
1240
  const log = getLogger();
934
1241
  try {
935
1242
  const resolved = resolveConfigDir(configPath);
936
- const data = await readFile(join3(resolved, PROFILES_FILE), "utf-8");
1243
+ const data = await readFile(join4(resolved, PROFILES_FILE), "utf-8");
937
1244
  const profiles = JSON.parse(data);
938
1245
  log.debug({ configPath, count: profiles.length }, "profiles: loaded");
939
1246
  return profiles;
@@ -946,7 +1253,7 @@ async function loadProfiles(configPath) {
946
1253
  async function saveProfiles(profiles, configPath) {
947
1254
  const resolved = resolveConfigDir(configPath);
948
1255
  await mkdir(resolved, { recursive: true });
949
- await writeFile(join3(resolved, PROFILES_FILE), JSON.stringify(profiles, null, 2));
1256
+ await writeFile(join4(resolved, PROFILES_FILE), JSON.stringify(profiles, null, 2));
950
1257
  getLogger().debug({ configPath, count: profiles.length }, "profiles: saved");
951
1258
  }
952
1259
 
@@ -954,7 +1261,7 @@ async function saveProfiles(profiles, configPath) {
954
1261
  import fg from "fast-glob";
955
1262
  import { createReadStream as createReadStream2 } from "fs";
956
1263
  import { stat } from "fs/promises";
957
- import { basename as basename3 } from "path";
1264
+ import { basename as basename4 } from "path";
958
1265
  import { createInterface as createInterface2 } from "readline";
959
1266
 
960
1267
  // src/canonical-path.ts
@@ -1020,6 +1327,7 @@ var CodexCliProvider = class {
1020
1327
  isSubagent: false,
1021
1328
  parentSessionUuid: null,
1022
1329
  firstUser: null,
1330
+ nameSlots: {},
1023
1331
  lastUser: null,
1024
1332
  lastAssistant: null,
1025
1333
  toolNames: [],
@@ -1182,6 +1490,7 @@ function reduceCodexEntry(acc, entry, tier) {
1182
1490
  const snapshot = { text: text.slice(0, 200), timestamp: ts };
1183
1491
  if (sender === "user") {
1184
1492
  if (!acc.firstUser) acc.firstUser = snapshot;
1493
+ acc.nameSlots = applyNameCandidate(acc.nameSlots, "firstUserMessage", text, CODEX_CLI_PROVIDER);
1185
1494
  acc.lastUser = snapshot;
1186
1495
  } else {
1187
1496
  acc.lastAssistant = snapshot;
@@ -1199,7 +1508,8 @@ function reduceCodexEntry(acc, entry, tier) {
1199
1508
  }
1200
1509
  function finalizeCodexMeta(acc, filePath, account, tier) {
1201
1510
  if (acc.messageCount === 0) return null;
1202
- const sessionId = acc.sessionId || basename3(filePath, ".jsonl");
1511
+ const sessionId = acc.sessionId || basename4(filePath, ".jsonl");
1512
+ const nameSlots = { ...acc.nameSlots, ...codexNameSlotsFor(filePath, acc.sessionId) };
1203
1513
  const projectPath = acc.cwd;
1204
1514
  const kind = acc.lastAssistant === null && acc.toolNames.length > 0 ? "task" : "conversation";
1205
1515
  return {
@@ -1209,10 +1519,8 @@ function finalizeCodexMeta(acc, filePath, account, tier) {
1209
1519
  kind,
1210
1520
  externalSessionId: acc.sessionId || void 0,
1211
1521
  sessionId,
1212
- // Mirrors the Claude reducer: a rollout carries no slug, so the opening turn
1213
- // is the only human-readable name source. Only useful because the injected
1214
- // AGENTS.md turn is skipped above — otherwise every title would be that blob.
1215
- sessionName: deriveSessionNameFromFirstMessage(acc.firstUser),
1522
+ sessionName: resolveSessionName(nameSlots).name ?? "",
1523
+ nameSlots,
1216
1524
  projectPath,
1217
1525
  projectName: getShortProjectName3(projectPath),
1218
1526
  account,
@@ -1235,10 +1543,6 @@ function finalizeCodexMeta(acc, filePath, account, tier) {
1235
1543
  lastPrompt: acc.lastUser?.text || void 0
1236
1544
  };
1237
1545
  }
1238
- function isCodexInjectedContext(text) {
1239
- if (text.startsWith("# AGENTS.md") || text.includes("<INSTRUCTIONS>")) return true;
1240
- return text.startsWith("<permissions instructions>") || text.includes("Filesystem sandboxing defines");
1241
- }
1242
1546
  function getShortProjectName3(fullPath) {
1243
1547
  return fullPath.split("/").filter(Boolean).slice(-3).join("/");
1244
1548
  }
@@ -1261,6 +1565,7 @@ async function parseCodexConversation(filePath, account) {
1261
1565
  let cwd = "";
1262
1566
  let latestTimestamp = "";
1263
1567
  let lastUserText = "";
1568
+ let nameSlots = {};
1264
1569
  const rl = createInterface2({ input: createReadStream2(filePath), crlfDelay: Infinity });
1265
1570
  try {
1266
1571
  for await (const line of rl) {
@@ -1285,7 +1590,15 @@ async function parseCodexConversation(filePath, account) {
1285
1590
  messages.push(message);
1286
1591
  if (!message.text) continue;
1287
1592
  textParts.push(message.text);
1288
- if (message.role === "user") lastUserText = message.text;
1593
+ if (message.role === "user") {
1594
+ lastUserText = message.text;
1595
+ nameSlots = applyNameCandidate(
1596
+ nameSlots,
1597
+ "firstUserMessage",
1598
+ message.text,
1599
+ CODEX_CLI_PROVIDER
1600
+ );
1601
+ }
1289
1602
  }
1290
1603
  } catch (err) {
1291
1604
  log.warn({ filePath, err }, "parseCodexConversation: read failed");
@@ -1297,8 +1610,8 @@ async function parseCodexConversation(filePath, account) {
1297
1610
  filePath,
1298
1611
  projectPath: cwd,
1299
1612
  projectName: getShortProjectName3(cwd),
1300
- sessionId: sessionId || basename3(filePath, ".jsonl"),
1301
- sessionName: "",
1613
+ sessionId: sessionId || basename4(filePath, ".jsonl"),
1614
+ sessionName: resolveSessionName({ ...nameSlots, ...codexNameSlotsFor(filePath, sessionId) }).name ?? "",
1302
1615
  messages,
1303
1616
  fullText: textParts.join(" "),
1304
1617
  timestamp: latestTimestamp || (/* @__PURE__ */ new Date()).toISOString(),
@@ -1310,9 +1623,9 @@ async function parseCodexConversation(filePath, account) {
1310
1623
 
1311
1624
  // src/providers/copilot.ts
1312
1625
  import fg2 from "fast-glob";
1313
- import { createReadStream as createReadStream3, statSync } from "fs";
1626
+ import { createReadStream as createReadStream3, statSync as statSync2 } from "fs";
1314
1627
  import { stat as stat2 } from "fs/promises";
1315
- import { basename as basename4, dirname as dirname3 } from "path";
1628
+ import { basename as basename5, dirname as dirname4 } from "path";
1316
1629
  import { createInterface as createInterface3 } from "readline";
1317
1630
  var SESSION_START = "session.start";
1318
1631
  var USER_MESSAGE = "user.message";
@@ -1366,6 +1679,7 @@ var CopilotProvider = class {
1366
1679
  messageCount: 0,
1367
1680
  lastMessageSender: "user",
1368
1681
  firstUser: null,
1682
+ nameSlots: {},
1369
1683
  lastUser: null,
1370
1684
  lastAssistant: null,
1371
1685
  toolNames: [],
@@ -1473,6 +1787,7 @@ function reduceCopilotEntry(acc, entry, tier) {
1473
1787
  const snapshot = { text: text.slice(0, 200), timestamp };
1474
1788
  if (role === "user") {
1475
1789
  if (!acc.firstUser) acc.firstUser = snapshot;
1790
+ acc.nameSlots = applyNameCandidate(acc.nameSlots, "firstUserMessage", text, COPILOT_PROVIDER);
1476
1791
  acc.lastUser = snapshot;
1477
1792
  } else {
1478
1793
  acc.lastAssistant = snapshot;
@@ -1491,6 +1806,7 @@ function reduceCopilotEntry(acc, entry, tier) {
1491
1806
  function finalizeCopilotMeta(acc, filePath, account, tier) {
1492
1807
  if (acc.messageCount === 0) return null;
1493
1808
  const sessionId = acc.sessionId || sessionIdFromPath(filePath);
1809
+ const nameSlots = { ...acc.nameSlots, ...copilotNameSlotsFor(filePath) };
1494
1810
  const kind = acc.lastAssistant === null && acc.toolNames.length > 0 ? "task" : "conversation";
1495
1811
  return {
1496
1812
  id: filePath,
@@ -1499,7 +1815,8 @@ function finalizeCopilotMeta(acc, filePath, account, tier) {
1499
1815
  kind,
1500
1816
  externalSessionId: sessionId,
1501
1817
  sessionId,
1502
- sessionName: deriveSessionNameFromFirstMessage(acc.firstUser),
1818
+ sessionName: resolveSessionName(nameSlots).name ?? "",
1819
+ nameSlots,
1503
1820
  projectPath: acc.cwd,
1504
1821
  projectName: getShortProjectName4(acc.cwd),
1505
1822
  account,
@@ -1521,14 +1838,14 @@ function finalizeCopilotMeta(acc, filePath, account, tier) {
1521
1838
  };
1522
1839
  }
1523
1840
  function sessionIdFromPath(filePath) {
1524
- return basename4(dirname3(filePath));
1841
+ return basename5(dirname4(filePath));
1525
1842
  }
1526
1843
  function getShortProjectName4(fullPath) {
1527
1844
  return fullPath.split(/[/\\]/).filter(Boolean).slice(-3).join("/");
1528
1845
  }
1529
1846
  function fileMtimeIso(filePath) {
1530
1847
  try {
1531
- return new Date(statSync(filePath).mtimeMs).toISOString();
1848
+ return new Date(statSync2(filePath).mtimeMs).toISOString();
1532
1849
  } catch {
1533
1850
  return (/* @__PURE__ */ new Date()).toISOString();
1534
1851
  }
@@ -1541,6 +1858,7 @@ async function parseCopilotConversation(filePath, account) {
1541
1858
  let cwd = "";
1542
1859
  let latestTimestamp = "";
1543
1860
  let lastUserText = "";
1861
+ let nameSlots = {};
1544
1862
  const rl = createInterface3({ input: createReadStream3(filePath), crlfDelay: Infinity });
1545
1863
  try {
1546
1864
  for await (const line of rl) {
@@ -1565,7 +1883,15 @@ async function parseCopilotConversation(filePath, account) {
1565
1883
  messages.push(message);
1566
1884
  if (!message.text) continue;
1567
1885
  textParts.push(message.text);
1568
- if (message.role === "user") lastUserText = message.text;
1886
+ if (message.role === "user") {
1887
+ lastUserText = message.text;
1888
+ nameSlots = applyNameCandidate(
1889
+ nameSlots,
1890
+ "firstUserMessage",
1891
+ message.text,
1892
+ COPILOT_PROVIDER
1893
+ );
1894
+ }
1569
1895
  }
1570
1896
  } catch (err) {
1571
1897
  log.warn({ filePath, err }, "parseCopilotConversation: read failed");
@@ -1578,7 +1904,7 @@ async function parseCopilotConversation(filePath, account) {
1578
1904
  projectPath: cwd,
1579
1905
  projectName: getShortProjectName4(cwd),
1580
1906
  sessionId: sessionId || sessionIdFromPath(filePath),
1581
- sessionName: "",
1907
+ sessionName: resolveSessionName({ ...nameSlots, ...copilotNameSlotsFor(filePath) }).name ?? "",
1582
1908
  messages,
1583
1909
  fullText: textParts.join(" "),
1584
1910
  timestamp: latestTimestamp || fileMtimeIso(filePath),
@@ -1591,9 +1917,9 @@ async function parseCopilotConversation(filePath, account) {
1591
1917
  // src/providers/cursor.ts
1592
1918
  import { createHash } from "crypto";
1593
1919
  import fg3 from "fast-glob";
1594
- import { createReadStream as createReadStream4, existsSync, statSync as statSync2 } from "fs";
1920
+ import { createReadStream as createReadStream4, existsSync as existsSync2, statSync as statSync3 } from "fs";
1595
1921
  import { stat as stat3 } from "fs/promises";
1596
- import { basename as basename5, dirname as dirname4, join as join4, sep as sep2 } from "path";
1922
+ import { basename as basename6, dirname as dirname5, join as join5, sep as sep2 } from "path";
1597
1923
  import { createInterface as createInterface4 } from "readline";
1598
1924
  var TIMESTAMP_RE = /<timestamp>\s*([\s\S]*?)\s*<\/timestamp>/;
1599
1925
  var USER_QUERY_RE = /<user_query>\s*([\s\S]*?)\s*<\/user_query>/;
@@ -1652,6 +1978,7 @@ var CursorProvider = class {
1652
1978
  parentSessionUuid: null,
1653
1979
  subagentId: null,
1654
1980
  firstUser: null,
1981
+ nameSlots: {},
1655
1982
  lastUser: null,
1656
1983
  lastAssistant: null,
1657
1984
  isImportedFromClaude: false,
@@ -1718,6 +2045,15 @@ function noteImportProvenance(acc, entry, text) {
1718
2045
  acc.isImportedFromCodex = true;
1719
2046
  }
1720
2047
  }
2048
+ function cursorUserQuery(content) {
2049
+ const texts = typeof content === "string" ? [content] : Array.isArray(content) ? content : [];
2050
+ for (const item of texts) {
2051
+ const text = typeof item === "string" ? item : item?.text;
2052
+ const query = typeof text === "string" ? text.match(USER_QUERY_RE) : null;
2053
+ if (query) return query[1];
2054
+ }
2055
+ return void 0;
2056
+ }
1721
2057
  function unwrapCursorUserText(text) {
1722
2058
  const query = text.match(USER_QUERY_RE);
1723
2059
  const body = query ? query[1] : text.replace(TIMESTAMP_RE, "");
@@ -1855,6 +2191,14 @@ function reduceCursorEntry(acc, entry, tier) {
1855
2191
  collectCursorToolNames(content, acc.toolNames);
1856
2192
  const text = textHint;
1857
2193
  if (!text) return;
2194
+ if (entry.role === "user") {
2195
+ acc.nameSlots = applyNameCandidate(
2196
+ acc.nameSlots,
2197
+ "firstUserMessage",
2198
+ cursorUserQuery(content),
2199
+ CURSOR_PROVIDER
2200
+ );
2201
+ }
1858
2202
  foldCursorMessage(acc, entry.role, text, firstTimestampHint(content), tier);
1859
2203
  return;
1860
2204
  }
@@ -1873,7 +2217,8 @@ function reduceCursorEntry(acc, entry, tier) {
1873
2217
  }
1874
2218
  function finalizeCursorMeta(acc, filePath, account, tier) {
1875
2219
  if (acc.messageCount === 0) return null;
1876
- const sessionId = basename5(filePath, ".jsonl");
2220
+ const sessionId = basename6(filePath, ".jsonl");
2221
+ const nameSlots = { ...acc.nameSlots, ...cursorNameSlotsFor(filePath, sessionId) };
1877
2222
  const isSubagent = SUBAGENT_PATH_RE2.test(filePath);
1878
2223
  const parent = isSubagent ? parentFromSubagentPath(filePath) : null;
1879
2224
  const { projectPath, projectName } = projectFromCursorPath(filePath);
@@ -1886,7 +2231,8 @@ function finalizeCursorMeta(acc, filePath, account, tier) {
1886
2231
  kind,
1887
2232
  externalSessionId: sessionId,
1888
2233
  sessionId,
1889
- sessionName: deriveSessionNameFromFirstMessage(acc.firstUser),
2234
+ sessionName: resolveSessionName(nameSlots).name ?? "",
2235
+ nameSlots,
1890
2236
  projectPath,
1891
2237
  projectName,
1892
2238
  account,
@@ -1912,20 +2258,20 @@ function finalizeCursorMeta(acc, filePath, account, tier) {
1912
2258
  };
1913
2259
  }
1914
2260
  function parentFromSubagentPath(filePath) {
1915
- const subagentsDir = dirname4(filePath);
1916
- const parentDir = dirname4(subagentsDir);
1917
- const parentSessionUuid = basename5(parentDir);
2261
+ const subagentsDir = dirname5(filePath);
2262
+ const parentDir = dirname5(subagentsDir);
2263
+ const parentSessionUuid = basename6(parentDir);
1918
2264
  if (!parentSessionUuid) return null;
1919
2265
  return {
1920
2266
  parentSessionUuid,
1921
- parentFilePath: canonicalPath(join4(parentDir, `${parentSessionUuid}.jsonl`))
2267
+ parentFilePath: canonicalPath(join5(parentDir, `${parentSessionUuid}.jsonl`))
1922
2268
  };
1923
2269
  }
1924
2270
  function projectFromCursorPath(filePath) {
1925
2271
  const parts = filePath.split(/[/\\]/);
1926
2272
  const idx = parts.lastIndexOf("agent-transcripts");
1927
- const cursorProjectDir = idx > 0 ? parts.slice(0, idx).join(sep2) : dirname4(dirname4(filePath));
1928
- const slug = basename5(cursorProjectDir);
2273
+ const cursorProjectDir = idx > 0 ? parts.slice(0, idx).join(sep2) : dirname5(dirname5(filePath));
2274
+ const slug = basename6(cursorProjectDir);
1929
2275
  const decoded = decodeCursorProjectSlug(slug);
1930
2276
  const projectPath = decoded ?? cursorProjectDir;
1931
2277
  return { projectPath, projectName: getShortProjectName5(projectPath) || slug };
@@ -1939,7 +2285,7 @@ function decodeCursorProjectSlug(slug) {
1939
2285
  let i = 0;
1940
2286
  if (rooted && segments[0] === "Users") {
1941
2287
  const users = `${sep2}Users`;
1942
- if (!existsSync(users)) return null;
2288
+ if (!existsSync2(users)) return null;
1943
2289
  acc = users;
1944
2290
  i = 1;
1945
2291
  }
@@ -1947,9 +2293,9 @@ function decodeCursorProjectSlug(slug) {
1947
2293
  let found = null;
1948
2294
  let next = i + 1;
1949
2295
  for (let j = segments.length; j > i; j--) {
1950
- const candidate = join4(acc, segments.slice(i, j).join("-"));
2296
+ const candidate = join5(acc, segments.slice(i, j).join("-"));
1951
2297
  try {
1952
- if (existsSync(candidate) && statSync2(candidate).isDirectory()) {
2298
+ if (existsSync2(candidate) && statSync3(candidate).isDirectory()) {
1953
2299
  found = candidate;
1954
2300
  next = j;
1955
2301
  break;
@@ -1968,17 +2314,26 @@ function getShortProjectName5(fullPath) {
1968
2314
  }
1969
2315
  function fileMtimeIso2(filePath) {
1970
2316
  try {
1971
- return new Date(statSync2(filePath).mtimeMs).toISOString();
2317
+ return new Date(statSync3(filePath).mtimeMs).toISOString();
1972
2318
  } catch {
1973
2319
  return (/* @__PURE__ */ new Date()).toISOString();
1974
2320
  }
1975
2321
  }
2322
+ function cursorLineContent(line) {
2323
+ try {
2324
+ const entry = JSON.parse(line);
2325
+ return entry.message?.content ?? entry.content;
2326
+ } catch {
2327
+ return void 0;
2328
+ }
2329
+ }
1976
2330
  async function parseCursorConversation(filePath, account) {
1977
2331
  const log = getLogger();
1978
2332
  const messages = [];
1979
2333
  const textParts = [];
1980
2334
  let latestTimestamp = "";
1981
2335
  let lastUserText = "";
2336
+ let nameSlots = {};
1982
2337
  const rl = createInterface4({ input: createReadStream4(filePath), crlfDelay: Infinity });
1983
2338
  try {
1984
2339
  for await (const line of rl) {
@@ -1990,7 +2345,17 @@ async function parseCursorConversation(filePath, account) {
1990
2345
  messages.push(message);
1991
2346
  if (!message.text) continue;
1992
2347
  textParts.push(message.text);
1993
- if (message.role === "user") lastUserText = message.text;
2348
+ if (message.role === "user") {
2349
+ lastUserText = message.text;
2350
+ if (nameSlots.firstUserMessage === void 0) {
2351
+ nameSlots = applyNameCandidate(
2352
+ nameSlots,
2353
+ "firstUserMessage",
2354
+ cursorUserQuery(cursorLineContent(line)),
2355
+ CURSOR_PROVIDER
2356
+ );
2357
+ }
2358
+ }
1994
2359
  }
1995
2360
  } catch (err) {
1996
2361
  log.warn({ filePath, err }, "parseCursorConversation: read failed");
@@ -1998,14 +2363,14 @@ async function parseCursorConversation(filePath, account) {
1998
2363
  }
1999
2364
  if (messages.length === 0) return null;
2000
2365
  const { projectPath, projectName } = projectFromCursorPath(filePath);
2001
- const sessionId = basename5(filePath, ".jsonl");
2366
+ const sessionId = basename6(filePath, ".jsonl");
2002
2367
  return {
2003
2368
  id: filePath,
2004
2369
  filePath,
2005
2370
  projectPath,
2006
2371
  projectName,
2007
2372
  sessionId,
2008
- sessionName: "",
2373
+ sessionName: resolveSessionName({ ...nameSlots, ...cursorNameSlotsFor(filePath, sessionId) }).name ?? "",
2009
2374
  messages,
2010
2375
  fullText: textParts.join(" "),
2011
2376
  timestamp: latestTimestamp || fileMtimeIso2(filePath),
@@ -2119,9 +2484,9 @@ var ThreadbaseProvider = class {
2119
2484
 
2120
2485
  // src/scanner.ts
2121
2486
  import { EventEmitter } from "events";
2122
- import { closeSync as closeSync2, openSync as openSync2, readSync as readSync2, statSync as statSync5 } from "fs";
2487
+ import { closeSync as closeSync3, openSync as openSync3, readSync as readSync3, statSync as statSync6 } from "fs";
2123
2488
  import { homedir as homedir2 } from "os";
2124
- import { join as join6 } from "path";
2489
+ import { join as join7 } from "path";
2125
2490
 
2126
2491
  // src/cache.ts
2127
2492
  var LRUCache = class {
@@ -2160,7 +2525,7 @@ var LRUCache = class {
2160
2525
  };
2161
2526
 
2162
2527
  // src/persistent/conversation-stream.ts
2163
- import { basename as basename6 } from "path";
2528
+ import { basename as basename7 } from "path";
2164
2529
 
2165
2530
  // src/persistent/paged-reader.ts
2166
2531
  import { createReadStream as createReadStream6 } from "fs";
@@ -2320,10 +2685,8 @@ function assemble(filePath, account, messages, fullText, turnDurations, state) {
2320
2685
  filePath,
2321
2686
  projectPath: state.cwd,
2322
2687
  projectName: getShortProjectName2(state.cwd),
2323
- sessionId: state.sessionId || basename6(filePath, ".jsonl"),
2324
- sessionName: state.sessionName || deriveSessionNameFromFirstMessage(
2325
- messages.find((m) => m.role === "user" && m.text && !m.isCompactSummary) ?? null
2326
- ),
2688
+ sessionId: state.sessionId || basename7(filePath, ".jsonl"),
2689
+ sessionName: resolveSessionName(state.nameSlots).name ?? "",
2327
2690
  messages,
2328
2691
  fullText,
2329
2692
  timestamp: state.latestTimestamp || (/* @__PURE__ */ new Date()).toISOString(),
@@ -2367,33 +2730,33 @@ async function extendConversation(previous, resume, filePath, account) {
2367
2730
 
2368
2731
  // src/persistent/cursor.ts
2369
2732
  import { createHash as createHash2 } from "crypto";
2370
- import { closeSync, openSync, readSync, statSync as statSync3 } from "fs";
2733
+ import { closeSync as closeSync2, openSync as openSync2, readSync as readSync2, statSync as statSync4 } from "fs";
2371
2734
  var FP_BYTES = 4096;
2372
2735
  function fingerprint(filePath, size) {
2373
2736
  const hash = createHash2("sha1");
2374
2737
  hash.update(String(size));
2375
- const fd = openSync(filePath, "r");
2738
+ const fd = openSync2(filePath, "r");
2376
2739
  try {
2377
2740
  const head = Buffer.alloc(Math.min(FP_BYTES, size));
2378
2741
  if (head.length > 0) {
2379
- readSync(fd, head, 0, head.length, 0);
2742
+ readSync2(fd, head, 0, head.length, 0);
2380
2743
  hash.update(head);
2381
2744
  }
2382
2745
  if (size > FP_BYTES) {
2383
2746
  const tailLen = Math.min(FP_BYTES, size);
2384
2747
  const tail = Buffer.alloc(tailLen);
2385
- readSync(fd, tail, 0, tailLen, size - tailLen);
2748
+ readSync2(fd, tail, 0, tailLen, size - tailLen);
2386
2749
  hash.update(tail);
2387
2750
  }
2388
2751
  } finally {
2389
- closeSync(fd);
2752
+ closeSync2(fd);
2390
2753
  }
2391
2754
  return hash.digest("hex");
2392
2755
  }
2393
2756
  function classify(filePath, existing) {
2394
2757
  let stat6;
2395
2758
  try {
2396
- const s = statSync3(filePath);
2759
+ const s = statSync4(filePath);
2397
2760
  stat6 = { size: s.size, mtimeMs: s.mtimeMs };
2398
2761
  } catch {
2399
2762
  return { change: "vanished" };
@@ -2421,7 +2784,7 @@ function classify(filePath, existing) {
2421
2784
  }
2422
2785
 
2423
2786
  // src/persistent/index-engine.ts
2424
- import { statSync as statSync4 } from "fs";
2787
+ import { statSync as statSync5 } from "fs";
2425
2788
 
2426
2789
  // src/providers/parse.ts
2427
2790
  import { createReadStream as createReadStream7 } from "fs";
@@ -2653,12 +3016,12 @@ function resolveTier(tierName, customTiers) {
2653
3016
  }
2654
3017
 
2655
3018
  // src/persistent/db.ts
2656
- import Database from "better-sqlite3";
3019
+ import Database2 from "better-sqlite3";
2657
3020
  import { mkdirSync } from "fs";
2658
- import { dirname as dirname5 } from "path";
3021
+ import { dirname as dirname6 } from "path";
2659
3022
 
2660
3023
  // src/persistent/schema.ts
2661
- var SCHEMA_VERSION = 10;
3024
+ var SCHEMA_VERSION = 11;
2662
3025
  var SCHEMA_SQL = `
2663
3026
  CREATE TABLE IF NOT EXISTS conversation_files (
2664
3027
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -2704,6 +3067,9 @@ CREATE TABLE IF NOT EXISTS conversations (
2704
3067
  external_session_id TEXT,
2705
3068
  session_id TEXT NOT NULL,
2706
3069
  session_name TEXT,
3070
+ -- JSON NameSlots the name was resolved from; lets a side-store change
3071
+ -- re-resolve the name without reparsing the transcript.
3072
+ name_slots TEXT,
2707
3073
 
2708
3074
  project_path TEXT,
2709
3075
  project_name TEXT,
@@ -2966,6 +3332,27 @@ function runMigrations(db) {
2966
3332
  db.exec(`UPDATE conversation_files SET ${assignments.join(", ")}`);
2967
3333
  }
2968
3334
  }
3335
+ if (current >= 1 && current < 11 && tableExists(db, "conversations")) {
3336
+ if (tableExists(db, "message_checkpoints")) db.exec("DELETE FROM message_checkpoints");
3337
+ if (!hasColumn(db, "conversations", "name_slots")) {
3338
+ db.exec("ALTER TABLE conversations ADD COLUMN name_slots TEXT");
3339
+ }
3340
+ if (tableExists(db, "conversation_files")) {
3341
+ const assignments = [];
3342
+ if (hasColumn(db, "conversation_files", "last_indexed_offset")) {
3343
+ assignments.push("last_indexed_offset = 0");
3344
+ }
3345
+ if (hasColumn(db, "conversation_files", "last_indexed_line")) {
3346
+ assignments.push("last_indexed_line = 0");
3347
+ }
3348
+ if (hasColumn(db, "conversation_files", "reducer_state")) {
3349
+ assignments.push("reducer_state = NULL");
3350
+ }
3351
+ if (assignments.length > 0) {
3352
+ db.exec(`UPDATE conversation_files SET ${assignments.join(", ")}`);
3353
+ }
3354
+ }
3355
+ }
2969
3356
  db.exec(SCHEMA_SQL);
2970
3357
  db.pragma(`user_version = ${SCHEMA_VERSION}`);
2971
3358
  }
@@ -2980,11 +3367,11 @@ function hasColumn(db, table, column) {
2980
3367
  // src/persistent/db.ts
2981
3368
  function openDatabase(dbPath) {
2982
3369
  if (dbPath !== ":memory:") {
2983
- mkdirSync(dirname5(dbPath), { recursive: true });
3370
+ mkdirSync(dirname6(dbPath), { recursive: true });
2984
3371
  }
2985
3372
  let db;
2986
3373
  try {
2987
- db = new Database(dbPath);
3374
+ db = new Database2(dbPath);
2988
3375
  } catch (err) {
2989
3376
  if (isNativeBindingFailure(err)) throw nativeBindingError(err, dbPath);
2990
3377
  throw err;
@@ -3025,7 +3412,7 @@ function nativeBindingError(err, dbPath) {
3025
3412
 
3026
3413
  // src/persistent/dir-watermark.ts
3027
3414
  import { readdir, stat as stat5 } from "fs/promises";
3028
- import { dirname as dirname6, join as join5 } from "path";
3415
+ import { dirname as dirname7, join as join6 } from "path";
3029
3416
  var FULL_RECONCILE_EVERY_N_SCANS = 20;
3030
3417
  async function discoverJsonlFilesGated(dirs, files, scannedDirs, options = {}) {
3031
3418
  const log = getLogger();
@@ -3096,10 +3483,10 @@ async function resolveProjectDirs(projectsDir, scannedDirs) {
3096
3483
  return { entries, commitRoot: { mtimeMs: rootStat.mtimeMs } };
3097
3484
  }
3098
3485
  function dirnameOf(filePath) {
3099
- return dirname6(filePath);
3486
+ return dirname7(filePath);
3100
3487
  }
3101
3488
  function joinPath(dir, name) {
3102
- return join5(dir, name);
3489
+ return join6(dir, name);
3103
3490
  }
3104
3491
 
3105
3492
  // src/persistent/repositories/checkpoints.repo.ts
@@ -3179,7 +3566,7 @@ function toCheckpoint(row) {
3179
3566
  }
3180
3567
 
3181
3568
  // src/persistent/repositories/conversation-files.repo.ts
3182
- import { basename as basename7, dirname as dirname7 } from "path";
3569
+ import { basename as basename8, dirname as dirname8 } from "path";
3183
3570
  var ConversationFilesRepo = class {
3184
3571
  constructor(db) {
3185
3572
  this.db = db;
@@ -3202,7 +3589,7 @@ var ConversationFilesRepo = class {
3202
3589
  const info = this.db.prepare(
3203
3590
  `INSERT INTO conversation_files (absolute_path, parent_dir, file_name, account)
3204
3591
  VALUES (?, ?, ?, ?)`
3205
- ).run(canonical, dirname7(canonical), basename7(canonical), account);
3592
+ ).run(canonical, dirname8(canonical), basename8(canonical), account);
3206
3593
  return Number(info.lastInsertRowid);
3207
3594
  }
3208
3595
  // Advance the cursor + persisted reducer state after a successful index pass.
@@ -3278,6 +3665,7 @@ function rowToMeta(row) {
3278
3665
  externalSessionId: row.external_session_id ?? void 0,
3279
3666
  sessionId: row.session_id,
3280
3667
  sessionName: row.session_name ?? "",
3668
+ nameSlots: row.name_slots ? JSON.parse(row.name_slots) : void 0,
3281
3669
  projectPath: row.project_path ?? "",
3282
3670
  projectName: row.project_name ?? "",
3283
3671
  account: row.account,
@@ -3321,7 +3709,7 @@ var ConversationsRepo = class {
3321
3709
  model, is_subagent, parent_session_id, subagent_id, parent_session_uuid,
3322
3710
  is_teammate, team_name, tool_names_json,
3323
3711
  last_prompt, is_imported_from_claude, is_imported_from_codex,
3324
- is_imported_from_cursor, status, updated_at
3712
+ is_imported_from_cursor, name_slots, status, updated_at
3325
3713
  ) VALUES (
3326
3714
  @file_id, @source_path, @provider, @kind, @external_session_id,
3327
3715
  @session_id, @session_name, @project_path, @project_name,
@@ -3333,7 +3721,7 @@ var ConversationsRepo = class {
3333
3721
  @model, @is_subagent, @parent_session_id, @subagent_id, @parent_session_uuid,
3334
3722
  @is_teammate, @team_name, @tool_names_json,
3335
3723
  @last_prompt, @is_imported_from_claude, @is_imported_from_codex,
3336
- @is_imported_from_cursor, 'active', CURRENT_TIMESTAMP
3724
+ @is_imported_from_cursor, @name_slots, 'active', CURRENT_TIMESTAMP
3337
3725
  )
3338
3726
  ON CONFLICT(file_id) DO UPDATE SET
3339
3727
  source_path = excluded.source_path,
@@ -3368,6 +3756,7 @@ var ConversationsRepo = class {
3368
3756
  is_imported_from_claude = excluded.is_imported_from_claude,
3369
3757
  is_imported_from_codex = excluded.is_imported_from_codex,
3370
3758
  is_imported_from_cursor = excluded.is_imported_from_cursor,
3759
+ name_slots = excluded.name_slots,
3371
3760
  status = 'active',
3372
3761
  index_seq = (SELECT COALESCE(MAX(index_seq), 0) + 1 FROM conversations),
3373
3762
  updated_at = CURRENT_TIMESTAMP`
@@ -3407,7 +3796,8 @@ var ConversationsRepo = class {
3407
3796
  last_prompt: meta.lastPrompt ?? null,
3408
3797
  is_imported_from_claude: meta.isImportedFromClaude ? 1 : 0,
3409
3798
  is_imported_from_codex: meta.isImportedFromCodex ? 1 : 0,
3410
- is_imported_from_cursor: meta.isImportedFromCursor ? 1 : 0
3799
+ is_imported_from_cursor: meta.isImportedFromCursor ? 1 : 0,
3800
+ name_slots: meta.nameSlots ? JSON.stringify(meta.nameSlots) : null
3411
3801
  });
3412
3802
  }
3413
3803
  getBySourcePath(sourcePath) {
@@ -3788,13 +4178,18 @@ var PersistentEngine = class {
3788
4178
  const tier = resolveTier(tierName, customTiers);
3789
4179
  const filePath = canonicalPath(rawFilePath);
3790
4180
  const existing = this.files.getByPath(filePath);
3791
- const { change, stat: stat6 } = classify(filePath, existing);
4181
+ const classified = classify(filePath, existing);
4182
+ const stat6 = classified.stat;
4183
+ let change = classified.change;
3792
4184
  if (change === "vanished" || !stat6) {
3793
4185
  this.markDeleted(filePath);
3794
4186
  return { meta: null, change: "vanished" };
3795
4187
  }
3796
4188
  if (change === "unchanged" && !force) {
3797
- return { meta: this.conversations.getBySourcePath(filePath), change };
4189
+ const meta2 = this.conversations.getBySourcePath(filePath);
4190
+ const sideStoresMoved = provider && provider.name !== CLAUDE_CODE_PROVIDER && meta2 && JSON.stringify(nameStoreSlotsFor(provider.name, filePath, meta2.sessionId)) !== existing?.reducer_state;
4191
+ if (!sideStoresMoved) return { meta: meta2, change };
4192
+ change = "reindex";
3798
4193
  }
3799
4194
  if (provider && provider.name !== CLAUDE_CODE_PROVIDER) {
3800
4195
  const meta2 = await this.indexFileWithProvider(
@@ -3876,7 +4271,7 @@ var PersistentEngine = class {
3876
4271
  // provider's reducer/finalize, then the same upsert + FTS write + cursor bump
3877
4272
  // the Threadbase path uses. The cursor records size/mtime (and offset = size)
3878
4273
  // so the next pass classifies an unchanged file as "unchanged" and skips it;
3879
- // any change reparses from 0 again. No reducer_state is persisted.
4274
+ // any change reparses from 0 again. reducer_state holds the side-store name slots, not a fold.
3880
4275
  async indexFileWithProvider(provider, filePath, account, tier, stat6, resolveGitBranch) {
3881
4276
  const log = getLogger();
3882
4277
  let searchDoc = emptySearchDocument();
@@ -3890,6 +4285,7 @@ var PersistentEngine = class {
3890
4285
  if (meta.gitBranch === null && meta.projectPath) {
3891
4286
  meta.gitBranch = resolveGitBranch(meta.projectPath);
3892
4287
  }
4288
+ const sideSlots = nameStoreSlotsFor(provider.name, filePath, meta.sessionId);
3893
4289
  const fp = stat6.size > 0 ? fingerprint(filePath, stat6.size) : null;
3894
4290
  const fileId = this.files.ensure(filePath, account);
3895
4291
  const upsert = this.db.transaction(() => {
@@ -3905,7 +4301,9 @@ var PersistentEngine = class {
3905
4301
  // can classify it "unchanged"); no resumable reducer state is kept.
3906
4302
  offset: stat6.size,
3907
4303
  line: 0,
3908
- reducerState: null,
4304
+ // Not resumable state: the side-store name slots this parse used, so the
4305
+ // next pass can tell when they moved (see indexFile).
4306
+ reducerState: JSON.stringify(sideSlots),
3909
4307
  fingerprint: fp,
3910
4308
  status: "active"
3911
4309
  });
@@ -3985,7 +4383,7 @@ var PersistentEngine = class {
3985
4383
  let floor = this.checkpoints.floor(filePath, fromIndex);
3986
4384
  if (floor) {
3987
4385
  try {
3988
- if (floor.byteOffset > statSync4(filePath).size) floor = null;
4386
+ if (floor.byteOffset > statSync5(filePath).size) floor = null;
3989
4387
  } catch {
3990
4388
  }
3991
4389
  }
@@ -4124,7 +4522,7 @@ function defaultDbPath() {
4124
4522
  "TB_SCANNER_DB must be set under a test runner. Refusing to open the default index at ~/.config/threadbase-scanner/index.db, because test fixtures written there are indistinguishable from real conversations and corrupt every measurement of the index. Point it at a temp directory in your test setup, or pass persistent.dbPath explicitly."
4125
4523
  );
4126
4524
  }
4127
- return join6(homedir2(), ".config", "threadbase-scanner", "index.db");
4525
+ return join7(homedir2(), ".config", "threadbase-scanner", "index.db");
4128
4526
  }
4129
4527
  function capForMemory(doc, max) {
4130
4528
  const combined = combineSearchContent(doc);
@@ -4217,6 +4615,7 @@ var ConversationScanner = class {
4217
4615
  }
4218
4616
  }
4219
4617
  async runScan(options) {
4618
+ if (options.cursorStateDb !== void 0) setCursorStateDb(options.cursorStateDb);
4220
4619
  const profiles = await this.resolveProfiles(options.profiles);
4221
4620
  const activeProfiles = profiles.filter((p) => p.enabled && p.scanHistory !== false);
4222
4621
  this.lastTier = resolveTier(options.tier ?? "standard", options.tiers);
@@ -4303,7 +4702,7 @@ var ConversationScanner = class {
4303
4702
  const cached = statCache.get(filePath);
4304
4703
  if (cached) {
4305
4704
  try {
4306
- const s = statSync5(filePath);
4705
+ const s = statSync6(filePath);
4307
4706
  if (s.mtimeMs === cached.stat.mtimeMs && s.size === cached.stat.size) {
4308
4707
  return {
4309
4708
  meta: cached.meta,
@@ -4851,13 +5250,13 @@ var ConversationScanner = class {
4851
5250
  if (previous?.provider) return void 0;
4852
5251
  let sample = "";
4853
5252
  try {
4854
- const fd = openSync2(filePath, "r");
5253
+ const fd = openSync3(filePath, "r");
4855
5254
  try {
4856
5255
  const buf = Buffer.alloc(8192);
4857
- const n = readSync2(fd, buf, 0, buf.length, 0);
5256
+ const n = readSync3(fd, buf, 0, buf.length, 0);
4858
5257
  sample = buf.subarray(0, n).toString("utf8");
4859
5258
  } finally {
4860
- closeSync2(fd);
5259
+ closeSync3(fd);
4861
5260
  }
4862
5261
  } catch {
4863
5262
  return void 0;
@@ -4984,11 +5383,13 @@ export {
4984
5383
  CursorProvider,
4985
5384
  DEFAULT_TIERS,
4986
5385
  LEGACY_CURSOR_PROVIDER,
5386
+ NAME_PRECEDENCE,
4987
5387
  SearchIndexer,
4988
5388
  ThreadbaseProvider,
4989
5389
  VALID_SORT_ORDERS,
4990
5390
  applyAccountFilter,
4991
5391
  applyIncludeFilter,
5392
+ applyNameCandidate,
4992
5393
  applyPagination,
4993
5394
  applyProjectFilter,
4994
5395
  applySinceFilter,
@@ -5003,20 +5404,27 @@ export {
5003
5404
  getLogger,
5004
5405
  getProjectsDir,
5005
5406
  isCodexInjectedContext,
5407
+ isValidNameCandidate,
5006
5408
  loadProfiles,
5007
5409
  parseCodexJsonlLine,
5008
5410
  parseCopilotJsonlLine,
5009
5411
  parseCursorJsonlLine,
5010
5412
  parseJsonlLine,
5011
5413
  providerMatches,
5414
+ readCodexNameSlots,
5415
+ readCopilotNameSlots,
5416
+ readCursorCliNameSlots,
5417
+ readCursorIdeNameSlots,
5012
5418
  readGitBranch,
5013
5419
  readSidecar,
5014
5420
  resetDefaultScanner,
5015
5421
  resolveConfigDir,
5422
+ resolveSessionName,
5016
5423
  resolveTier,
5017
5424
  saveProfiles,
5018
5425
  scan,
5019
5426
  search,
5427
+ setCursorStateDb,
5020
5428
  setLogger,
5021
5429
  sidecarPath,
5022
5430
  unwrapCursorUserText