@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/cli.js CHANGED
@@ -5,7 +5,7 @@ import { Command } from "commander";
5
5
  import pino2 from "pino";
6
6
 
7
7
  // package.json
8
- var version = "0.21.1";
8
+ var version = "0.23.0";
9
9
 
10
10
  // src/logger.ts
11
11
  import pino from "pino";
@@ -60,9 +60,9 @@ async function saveProfiles(profiles, configPath) {
60
60
 
61
61
  // src/scanner.ts
62
62
  import { EventEmitter } from "events";
63
- import { closeSync as closeSync2, openSync as openSync2, readSync as readSync2, statSync as statSync5 } from "fs";
63
+ import { closeSync as closeSync3, openSync as openSync3, readSync as readSync3, statSync as statSync6 } from "fs";
64
64
  import { homedir as homedir2 } from "os";
65
- import { join as join6 } from "path";
65
+ import { join as join7 } from "path";
66
66
 
67
67
  // src/cache.ts
68
68
  var LRUCache = class {
@@ -506,17 +506,317 @@ function toIndexDoc(meta, searchContent) {
506
506
  };
507
507
  }
508
508
 
509
+ // src/name-stores.ts
510
+ import Database from "better-sqlite3";
511
+ import { closeSync, existsSync, openSync, readdirSync, readFileSync as readFileSync2, readSync, statSync } from "fs";
512
+ import { basename, dirname as dirname2, join as join3 } from "path";
513
+
514
+ // src/tags.ts
515
+ var SYSTEM_TAGS = [
516
+ "system-reminder",
517
+ "command-name",
518
+ "command-message",
519
+ "command-args",
520
+ "ide_selection",
521
+ "ide_opened_file",
522
+ "local-command-stdout",
523
+ "local-command-caveat",
524
+ "retrieval_status",
525
+ "task_id",
526
+ "task_type",
527
+ "task-id",
528
+ "task-notification",
529
+ "fast_mode_info",
530
+ "persisted-output",
531
+ "tool_use_error",
532
+ "user-prompt-submit-hook",
533
+ "thinking",
534
+ "ask_user",
535
+ "teammate-message"
536
+ ];
537
+ var SYSTEM_TAG_RE = new RegExp(`<(${SYSTEM_TAGS.join("|")})[^>]*>[\\s\\S]*?<\\/\\1>`, "g");
538
+ var PASTED_CONTENT_RE = /<pasted_content id="[0-9a-f]{4}">([\s\S]*?)<\/pasted_content(?: id="[0-9a-f]{4}")?>/g;
539
+ function cleanSystemTags(text) {
540
+ return text.replace(SYSTEM_TAG_RE, "").replace(PASTED_CONTENT_RE, "$1").replace(/[^\S\n]+/g, " ").replace(/\n{3,}/g, "\n\n").trim();
541
+ }
542
+
543
+ // src/session-name.ts
544
+ var NAME_PRECEDENCE = [
545
+ "userTitle",
546
+ "toolTitle",
547
+ "lastPrompt",
548
+ "firstUserMessage",
549
+ "slug"
550
+ ];
551
+ var CLAUDE_SYSTEM_PREFIXES = [
552
+ "<command-name>",
553
+ "<command-message>",
554
+ "<command-args>",
555
+ "<local-command-stdout>",
556
+ "<local-command-stderr>",
557
+ "<local-command-caveat>",
558
+ "<bash-input>",
559
+ "<bash-stdout>",
560
+ "<bash-stderr>",
561
+ "<system-reminder>",
562
+ "<task-notification>",
563
+ "<teammate-message",
564
+ "Another Claude session sent a message:",
565
+ "[Request interrupted by user"
566
+ ];
567
+ var CODEX_SYSTEM_PREFIXES = [
568
+ "<environment_context>",
569
+ "# AGENTS.md instructions",
570
+ "<user_instructions>",
571
+ "<INSTRUCTIONS>",
572
+ "<external_codex_apps_open",
573
+ "<user_shell_command>",
574
+ "<turn_aborted>"
575
+ ];
576
+ function isCodexInjectedContext(text) {
577
+ if (text.startsWith("# AGENTS.md") || text.includes("<INSTRUCTIONS>")) return true;
578
+ return text.startsWith("<permissions instructions>") || text.includes("Filesystem sandboxing defines");
579
+ }
580
+ var CODEX_IMAGE_TAG_RE = /<\/?image\b[^>]*>/g;
581
+ function normalizeCandidate(text, provider) {
582
+ let t = text.trim();
583
+ if (provider === "codex-cli") t = t.replace(CODEX_IMAGE_TAG_RE, "").trim();
584
+ const prefixes = provider === "claude-code" ? CLAUDE_SYSTEM_PREFIXES : provider === "codex-cli" ? CODEX_SYSTEM_PREFIXES : [];
585
+ if (prefixes.some((p) => t.startsWith(p))) return null;
586
+ if (provider === "codex-cli" && isCodexInjectedContext(t)) return null;
587
+ return cleanSystemTags(t) || null;
588
+ }
589
+ function resolveSessionName(slots) {
590
+ for (const slot of NAME_PRECEDENCE) {
591
+ const value = slots[slot];
592
+ if (value?.trim()) return { name: value, source: slot };
593
+ }
594
+ return { name: null, source: null };
595
+ }
596
+ function applyNameCandidate(slots, slot, raw, provider) {
597
+ if (typeof raw !== "string") return slots;
598
+ if (slot === "firstUserMessage" && slots.firstUserMessage !== void 0) return slots;
599
+ const text = normalizeCandidate(raw, provider);
600
+ return text === null ? slots : { ...slots, [slot]: text };
601
+ }
602
+
603
+ // src/name-stores.ts
604
+ function slotsFrom(provider, candidates) {
605
+ return candidates.reduce(
606
+ (slots, [slot, raw]) => applyNameCandidate(slots, slot, typeof raw === "string" ? raw : void 0, provider),
607
+ {}
608
+ );
609
+ }
610
+ function readJson(path) {
611
+ try {
612
+ return JSON.parse(readFileSync2(path, "utf8"));
613
+ } catch {
614
+ return void 0;
615
+ }
616
+ }
617
+ function queryOne(dbPath, sql, ...params) {
618
+ let db;
619
+ try {
620
+ db = new Database(dbPath, { readonly: true, fileMustExist: true, timeout: 250 });
621
+ return db.prepare(sql).get(...params);
622
+ } catch (err) {
623
+ getLogger().debug({ dbPath, err }, "name store: query failed");
624
+ return void 0;
625
+ } finally {
626
+ db?.close();
627
+ }
628
+ }
629
+ var lastByIdCache = /* @__PURE__ */ new Map();
630
+ function lastValueById(path, idField, valueField) {
631
+ let sig;
632
+ try {
633
+ const s = statSync(path);
634
+ sig = `${s.mtimeMs}:${s.size}`;
635
+ } catch {
636
+ return /* @__PURE__ */ new Map();
637
+ }
638
+ const key = `${path}\0${idField}\0${valueField}`;
639
+ const cached = lastByIdCache.get(key);
640
+ if (cached?.sig === sig) return cached.map;
641
+ const map = /* @__PURE__ */ new Map();
642
+ try {
643
+ for (const line of readFileSync2(path, "utf8").split("\n")) {
644
+ if (!line.trim()) continue;
645
+ try {
646
+ const row = JSON.parse(line);
647
+ const id = row[idField];
648
+ const value = row[valueField];
649
+ if (typeof id === "string" && typeof value === "string") map.set(id, value);
650
+ } catch {
651
+ }
652
+ }
653
+ } catch {
654
+ }
655
+ lastByIdCache.set(key, { sig, map });
656
+ return map;
657
+ }
658
+ function readCodexNameSlots(codexHome, id) {
659
+ const index = lastValueById(join3(codexHome, "session_index.jsonl"), "id", "thread_name");
660
+ const history = lastValueById(join3(codexHome, "history.jsonl"), "session_id", "text");
661
+ let title = index.get(id);
662
+ if (!index.has(id)) {
663
+ title = queryOne(
664
+ join3(codexHome, "state_5.sqlite"),
665
+ "SELECT name FROM threads WHERE id = ?",
666
+ id
667
+ )?.name;
668
+ }
669
+ return slotsFrom("codex-cli", [
670
+ ["toolTitle", title],
671
+ ["lastPrompt", history.get(id)]
672
+ ]);
673
+ }
674
+ function readCursorCliNameSlots(chatsDir, id) {
675
+ let chat;
676
+ try {
677
+ chat = readdirSync(chatsDir).map((hash) => join3(chatsDir, hash, id)).find((p) => existsSync(p));
678
+ } catch {
679
+ }
680
+ if (!chat) return {};
681
+ const meta = readJson(join3(chat, "meta.json"));
682
+ const history = readJson(join3(chat, "prompt_history.json"));
683
+ let title = meta?.title;
684
+ if (typeof title !== "string" || !title.trim()) title = storeDbName(join3(chat, "store.db"));
685
+ return slotsFrom("cursor", [
686
+ ["toolTitle", title],
687
+ ["lastPrompt", Array.isArray(history) ? history[0] : void 0]
688
+ ]);
689
+ }
690
+ function storeDbName(dbPath) {
691
+ const row = queryOne(
692
+ dbPath,
693
+ "SELECT value FROM meta WHERE key = '0'"
694
+ );
695
+ if (!row) return void 0;
696
+ try {
697
+ const text = row.value.toString();
698
+ const json = /^(?:[0-9a-f]{2})+$/i.test(text) ? Buffer.from(text, "hex").toString("utf8") : text;
699
+ const name = JSON.parse(json).name;
700
+ return typeof name === "string" ? name : void 0;
701
+ } catch {
702
+ return void 0;
703
+ }
704
+ }
705
+ function readCursorIdeNameSlots(stateDbPath, id) {
706
+ const row = queryOne(
707
+ stateDbPath,
708
+ "SELECT json_extract(CAST(value AS TEXT), '$.name') AS name FROM cursorDiskKV WHERE key = ?",
709
+ `composerData:${id}`
710
+ );
711
+ return slotsFrom("cursor", [["toolTitle", row?.name]]);
712
+ }
713
+ function yamlScalar(text, key) {
714
+ const m = text.match(new RegExp(`^${key}:[ \\t]*(.*)$`, "m"));
715
+ const v = m?.[1].trim().replace(/^(["'])(.*)\1$/, "$2");
716
+ return v || void 0;
717
+ }
718
+ function readCopilotTitleSlots(sessionDir) {
719
+ const id = basename(sessionDir);
720
+ let yaml = "";
721
+ try {
722
+ yaml = readFileSync2(join3(sessionDir, "workspace.yaml"), "utf8");
723
+ } catch {
724
+ }
725
+ const name = yamlScalar(yaml, "name");
726
+ if (name) {
727
+ return slotsFrom("copilot", [
728
+ [yamlScalar(yaml, "user_named") === "true" ? "userTitle" : "toolTitle", name]
729
+ ]);
730
+ }
731
+ const row = queryOne(
732
+ join3(dirname2(dirname2(sessionDir)), "session-store.db"),
733
+ "SELECT summary FROM sessions WHERE id = ?",
734
+ id
735
+ );
736
+ return slotsFrom("copilot", [["toolTitle", row?.summary]]);
737
+ }
738
+ function findUp(start, hasStore, levels) {
739
+ let dir = start;
740
+ for (let i = 0; i < levels; i++) {
741
+ if (hasStore(dir)) return dir;
742
+ const parent = dirname2(dir);
743
+ if (parent === dir) break;
744
+ dir = parent;
745
+ }
746
+ return null;
747
+ }
748
+ function codexNameSlotsFor(rolloutPath, id) {
749
+ const home = findUp(
750
+ dirname2(rolloutPath),
751
+ (d) => ["session_index.jsonl", "history.jsonl", "state_5.sqlite"].some(
752
+ (f) => existsSync(join3(d, f))
753
+ ),
754
+ 6
755
+ );
756
+ return home ? readCodexNameSlots(home, id) : {};
757
+ }
758
+ var cursorStateDb;
759
+ function setCursorStateDb(path) {
760
+ cursorStateDb = path;
761
+ }
762
+ function cursorNameSlotsFor(transcriptPath, id) {
763
+ const home = findUp(dirname2(transcriptPath), (d) => existsSync(join3(d, "chats")), 6);
764
+ const cli = home ? readCursorCliNameSlots(join3(home, "chats"), id) : {};
765
+ if (cli.toolTitle || !cursorStateDb) return cli;
766
+ return { ...cli, ...readCursorIdeNameSlots(cursorStateDb, id) };
767
+ }
768
+ function copilotNameSlotsFor(eventsPath) {
769
+ return readCopilotTitleSlots(dirname2(eventsPath));
770
+ }
771
+ function nameStoreSlotsFor(provider, filePath, sessionId) {
772
+ switch (provider) {
773
+ case "codex-cli":
774
+ return codexNameSlotsFor(filePath, sessionId);
775
+ case "cursor":
776
+ return cursorNameSlotsFor(filePath, basename(filePath, ".jsonl"));
777
+ case "copilot":
778
+ return copilotNameSlotsFor(filePath);
779
+ default:
780
+ return {};
781
+ }
782
+ }
783
+
509
784
  // src/parser.ts
510
785
  import { createReadStream } from "fs";
511
- import { basename as basename2 } from "path";
786
+ import { basename as basename3 } from "path";
512
787
  import { createInterface } from "readline";
513
788
 
789
+ // src/persistent/claude-name-slots.ts
790
+ function userPromptText(entry) {
791
+ if (entry.isMeta || entry.isCompactSummary === true) return "";
792
+ const content = entry.message?.content;
793
+ if (typeof content === "string") return content;
794
+ if (!Array.isArray(content)) return "";
795
+ return content.map((b) => typeof b === "string" ? b : b?.type === "text" ? b.text : "").filter((t) => typeof t === "string" && t !== "").join(" ");
796
+ }
797
+ function applyClaudeNameEntry(slots, entry) {
798
+ const apply = (slot, raw) => applyNameCandidate(slots, slot, typeof raw === "string" ? raw : void 0, "claude-code");
799
+ if (entry.slug !== slots.slug) slots = apply("slug", entry.slug);
800
+ switch (entry.type) {
801
+ case "custom-title":
802
+ return apply("userTitle", entry.customTitle);
803
+ case "ai-title":
804
+ return apply("toolTitle", entry.aiTitle);
805
+ case "last-prompt":
806
+ return apply("lastPrompt", entry.lastPrompt);
807
+ case "user":
808
+ return slots.firstUserMessage === void 0 ? apply("firstUserMessage", userPromptText(entry)) : slots;
809
+ default:
810
+ return slots;
811
+ }
812
+ }
813
+
514
814
  // src/persistent/conversation-reducer.ts
515
815
  function initialConvState() {
516
816
  return {
517
817
  cwd: "",
518
818
  sessionId: "",
519
- sessionName: "",
819
+ nameSlots: {},
520
820
  latestTimestamp: "",
521
821
  lastPrompt: "",
522
822
  pendingToolUses: {},
@@ -526,7 +826,7 @@ function initialConvState() {
526
826
  function reduceConvLine(state, entry) {
527
827
  if (entry.cwd && !state.cwd) state.cwd = entry.cwd;
528
828
  if (entry.sessionId && !state.sessionId) state.sessionId = entry.sessionId;
529
- if (entry.slug && !state.sessionName) state.sessionName = entry.slug;
829
+ state.nameSlots = applyClaudeNameEntry(state.nameSlots, entry);
530
830
  if (entry.timestamp) {
531
831
  const ts = entry.timestamp;
532
832
  if (!state.latestTimestamp || ts > state.latestTimestamp) state.latestTimestamp = ts;
@@ -623,7 +923,7 @@ function applyTeamInfo(messages, state) {
623
923
  }
624
924
 
625
925
  // src/persistent/metadata-reducer.ts
626
- import { basename, dirname as dirname2, join as join3 } from "path";
926
+ import { basename as basename2, dirname as dirname3, join as join4 } from "path";
627
927
 
628
928
  // src/providers/provider.ts
629
929
  var CLAUDE_CODE_PROVIDER = "claude-code";
@@ -657,7 +957,7 @@ function providerMatches(stored, wanted) {
657
957
  function initialReducerState() {
658
958
  return {
659
959
  sessionId: "",
660
- sessionName: "",
960
+ nameSlots: {},
661
961
  latestTimestamp: "",
662
962
  cwd: "",
663
963
  teamName: "",
@@ -683,7 +983,7 @@ function initialReducerState() {
683
983
  function reduceLine(state, entry, tier) {
684
984
  if (entry.cwd && !state.cwd) state.cwd = entry.cwd;
685
985
  if (entry.sessionId && !state.sessionId) state.sessionId = entry.sessionId;
686
- if (entry.slug && !state.sessionName) state.sessionName = entry.slug;
986
+ state.nameSlots = applyClaudeNameEntry(state.nameSlots, entry);
687
987
  if (entry.teamName && !state.teamName) state.teamName = entry.teamName;
688
988
  if (entry.agentId && !state.agentId) state.agentId = entry.agentId;
689
989
  if (entry.isSidechain === true) state.isSidechain = true;
@@ -747,16 +1047,17 @@ function finalizeMeta(state, filePath, account, tier) {
747
1047
  const isSubagent = isSidechain || isSubagentPath;
748
1048
  let parentSessionId = null;
749
1049
  if (isSubagentPath) {
750
- const uuidDir = dirname2(dirname2(filePath));
751
- parentSessionId = join3(dirname2(uuidDir), `${basename(uuidDir)}.jsonl`);
1050
+ const uuidDir = dirname3(dirname3(filePath));
1051
+ parentSessionId = join4(dirname3(uuidDir), `${basename2(uuidDir)}.jsonl`);
752
1052
  }
753
1053
  const projectPath = state.cwd;
754
1054
  return {
755
1055
  id: filePath,
756
1056
  filePath,
757
1057
  provider: CLAUDE_CODE_PROVIDER,
758
- sessionId: state.sessionId || basename(filePath, ".jsonl"),
759
- sessionName: state.sessionName || deriveSessionNameFromFirstMessage(state.firstMessage),
1058
+ sessionId: state.sessionId || basename2(filePath, ".jsonl"),
1059
+ sessionName: resolveSessionName(state.nameSlots).name ?? "",
1060
+ nameSlots: state.nameSlots,
760
1061
  projectPath,
761
1062
  projectName: getShortProjectName(projectPath),
762
1063
  account,
@@ -782,44 +1083,11 @@ function finalizeMeta(state, filePath, account, tier) {
782
1083
  };
783
1084
  }
784
1085
  var SUBAGENT_PATH_RE = /[\\/]subagents[\\/]/;
785
- function deriveSessionNameFromFirstMessage(firstMessage) {
786
- const firstLine = firstMessage?.text.split("\n", 1)[0]?.trim() ?? "";
787
- return firstLine.slice(0, 80);
788
- }
789
1086
  function getShortProjectName(fullPath) {
790
1087
  const parts = fullPath.split("/").filter(Boolean);
791
1088
  return parts.slice(-3).join("/");
792
1089
  }
793
1090
 
794
- // src/tags.ts
795
- var SYSTEM_TAGS = [
796
- "system-reminder",
797
- "command-name",
798
- "command-message",
799
- "command-args",
800
- "ide_selection",
801
- "ide_opened_file",
802
- "local-command-stdout",
803
- "local-command-caveat",
804
- "retrieval_status",
805
- "task_id",
806
- "task_type",
807
- "task-id",
808
- "task-notification",
809
- "fast_mode_info",
810
- "persisted-output",
811
- "tool_use_error",
812
- "user-prompt-submit-hook",
813
- "thinking",
814
- "ask_user",
815
- "teammate-message"
816
- ];
817
- var SYSTEM_TAG_RE = new RegExp(`<(${SYSTEM_TAGS.join("|")})[^>]*>[\\s\\S]*?<\\/\\1>`, "g");
818
- var PASTED_CONTENT_RE = /<pasted_content id="[0-9a-f]{4}">([\s\S]*?)<\/pasted_content(?: id="[0-9a-f]{4}")?>/g;
819
- function cleanSystemTags(text) {
820
- return text.replace(SYSTEM_TAG_RE, "").replace(PASTED_CONTENT_RE, "$1").replace(/[^\S\n]+/g, " ").replace(/\n{3,}/g, "\n\n").trim();
821
- }
822
-
823
1091
  // src/parser.ts
824
1092
  async function parseMeta(filePath, account, tier, onEntry) {
825
1093
  const log = getLogger();
@@ -906,10 +1174,8 @@ async function parseConversation(filePath, account) {
906
1174
  filePath,
907
1175
  projectPath: state.cwd,
908
1176
  projectName: getShortProjectName2(state.cwd),
909
- sessionId: state.sessionId || basename2(filePath, ".jsonl"),
910
- sessionName: state.sessionName || deriveSessionNameFromFirstMessage(
911
- messages.find((m) => m.role === "user" && m.text && !m.isCompactSummary) ?? null
912
- ),
1177
+ sessionId: state.sessionId || basename3(filePath, ".jsonl"),
1178
+ sessionName: resolveSessionName(state.nameSlots).name ?? "",
913
1179
  messages,
914
1180
  fullText: textParts.join(" "),
915
1181
  timestamp: state.latestTimestamp || (/* @__PURE__ */ new Date()).toISOString(),
@@ -1015,7 +1281,7 @@ function getShortProjectName2(fullPath) {
1015
1281
  }
1016
1282
 
1017
1283
  // src/persistent/conversation-stream.ts
1018
- import { basename as basename3 } from "path";
1284
+ import { basename as basename4 } from "path";
1019
1285
 
1020
1286
  // src/persistent/paged-reader.ts
1021
1287
  import { createReadStream as createReadStream3 } from "fs";
@@ -1175,10 +1441,8 @@ function assemble(filePath, account, messages, fullText, turnDurations, state) {
1175
1441
  filePath,
1176
1442
  projectPath: state.cwd,
1177
1443
  projectName: getShortProjectName2(state.cwd),
1178
- sessionId: state.sessionId || basename3(filePath, ".jsonl"),
1179
- sessionName: state.sessionName || deriveSessionNameFromFirstMessage(
1180
- messages.find((m) => m.role === "user" && m.text && !m.isCompactSummary) ?? null
1181
- ),
1444
+ sessionId: state.sessionId || basename4(filePath, ".jsonl"),
1445
+ sessionName: resolveSessionName(state.nameSlots).name ?? "",
1182
1446
  messages,
1183
1447
  fullText,
1184
1448
  timestamp: state.latestTimestamp || (/* @__PURE__ */ new Date()).toISOString(),
@@ -1222,33 +1486,33 @@ async function extendConversation(previous, resume, filePath, account) {
1222
1486
 
1223
1487
  // src/persistent/cursor.ts
1224
1488
  import { createHash } from "crypto";
1225
- import { closeSync, openSync, readSync, statSync } from "fs";
1489
+ import { closeSync as closeSync2, openSync as openSync2, readSync as readSync2, statSync as statSync2 } from "fs";
1226
1490
  var FP_BYTES = 4096;
1227
1491
  function fingerprint(filePath, size) {
1228
1492
  const hash = createHash("sha1");
1229
1493
  hash.update(String(size));
1230
- const fd = openSync(filePath, "r");
1494
+ const fd = openSync2(filePath, "r");
1231
1495
  try {
1232
1496
  const head = Buffer.alloc(Math.min(FP_BYTES, size));
1233
1497
  if (head.length > 0) {
1234
- readSync(fd, head, 0, head.length, 0);
1498
+ readSync2(fd, head, 0, head.length, 0);
1235
1499
  hash.update(head);
1236
1500
  }
1237
1501
  if (size > FP_BYTES) {
1238
1502
  const tailLen = Math.min(FP_BYTES, size);
1239
1503
  const tail = Buffer.alloc(tailLen);
1240
- readSync(fd, tail, 0, tailLen, size - tailLen);
1504
+ readSync2(fd, tail, 0, tailLen, size - tailLen);
1241
1505
  hash.update(tail);
1242
1506
  }
1243
1507
  } finally {
1244
- closeSync(fd);
1508
+ closeSync2(fd);
1245
1509
  }
1246
1510
  return hash.digest("hex");
1247
1511
  }
1248
1512
  function classify(filePath, existing) {
1249
1513
  let stat6;
1250
1514
  try {
1251
- const s = statSync(filePath);
1515
+ const s = statSync2(filePath);
1252
1516
  stat6 = { size: s.size, mtimeMs: s.mtimeMs };
1253
1517
  } catch {
1254
1518
  return { change: "vanished" };
@@ -1276,13 +1540,13 @@ function classify(filePath, existing) {
1276
1540
  }
1277
1541
 
1278
1542
  // src/persistent/index-engine.ts
1279
- import { statSync as statSync4 } from "fs";
1543
+ import { statSync as statSync5 } from "fs";
1280
1544
 
1281
1545
  // src/providers/codex-cli.ts
1282
1546
  import fg2 from "fast-glob";
1283
1547
  import { createReadStream as createReadStream4 } from "fs";
1284
1548
  import { stat as stat2 } from "fs/promises";
1285
- import { basename as basename4 } from "path";
1549
+ import { basename as basename5 } from "path";
1286
1550
  import { createInterface as createInterface2 } from "readline";
1287
1551
  var CodexCliProvider = class {
1288
1552
  name = CODEX_CLI_PROVIDER;
@@ -1340,6 +1604,7 @@ var CodexCliProvider = class {
1340
1604
  isSubagent: false,
1341
1605
  parentSessionUuid: null,
1342
1606
  firstUser: null,
1607
+ nameSlots: {},
1343
1608
  lastUser: null,
1344
1609
  lastAssistant: null,
1345
1610
  toolNames: [],
@@ -1502,6 +1767,7 @@ function reduceCodexEntry(acc, entry, tier) {
1502
1767
  const snapshot = { text: text.slice(0, 200), timestamp: ts };
1503
1768
  if (sender === "user") {
1504
1769
  if (!acc.firstUser) acc.firstUser = snapshot;
1770
+ acc.nameSlots = applyNameCandidate(acc.nameSlots, "firstUserMessage", text, CODEX_CLI_PROVIDER);
1505
1771
  acc.lastUser = snapshot;
1506
1772
  } else {
1507
1773
  acc.lastAssistant = snapshot;
@@ -1519,7 +1785,8 @@ function reduceCodexEntry(acc, entry, tier) {
1519
1785
  }
1520
1786
  function finalizeCodexMeta(acc, filePath, account, tier) {
1521
1787
  if (acc.messageCount === 0) return null;
1522
- const sessionId = acc.sessionId || basename4(filePath, ".jsonl");
1788
+ const sessionId = acc.sessionId || basename5(filePath, ".jsonl");
1789
+ const nameSlots = { ...acc.nameSlots, ...codexNameSlotsFor(filePath, acc.sessionId) };
1523
1790
  const projectPath = acc.cwd;
1524
1791
  const kind = acc.lastAssistant === null && acc.toolNames.length > 0 ? "task" : "conversation";
1525
1792
  return {
@@ -1529,10 +1796,8 @@ function finalizeCodexMeta(acc, filePath, account, tier) {
1529
1796
  kind,
1530
1797
  externalSessionId: acc.sessionId || void 0,
1531
1798
  sessionId,
1532
- // Mirrors the Claude reducer: a rollout carries no slug, so the opening turn
1533
- // is the only human-readable name source. Only useful because the injected
1534
- // AGENTS.md turn is skipped above — otherwise every title would be that blob.
1535
- sessionName: deriveSessionNameFromFirstMessage(acc.firstUser),
1799
+ sessionName: resolveSessionName(nameSlots).name ?? "",
1800
+ nameSlots,
1536
1801
  projectPath,
1537
1802
  projectName: getShortProjectName3(projectPath),
1538
1803
  account,
@@ -1555,10 +1820,6 @@ function finalizeCodexMeta(acc, filePath, account, tier) {
1555
1820
  lastPrompt: acc.lastUser?.text || void 0
1556
1821
  };
1557
1822
  }
1558
- function isCodexInjectedContext(text) {
1559
- if (text.startsWith("# AGENTS.md") || text.includes("<INSTRUCTIONS>")) return true;
1560
- return text.startsWith("<permissions instructions>") || text.includes("Filesystem sandboxing defines");
1561
- }
1562
1823
  function getShortProjectName3(fullPath) {
1563
1824
  return fullPath.split("/").filter(Boolean).slice(-3).join("/");
1564
1825
  }
@@ -1581,6 +1842,7 @@ async function parseCodexConversation(filePath, account) {
1581
1842
  let cwd = "";
1582
1843
  let latestTimestamp = "";
1583
1844
  let lastUserText = "";
1845
+ let nameSlots = {};
1584
1846
  const rl = createInterface2({ input: createReadStream4(filePath), crlfDelay: Infinity });
1585
1847
  try {
1586
1848
  for await (const line of rl) {
@@ -1605,7 +1867,15 @@ async function parseCodexConversation(filePath, account) {
1605
1867
  messages.push(message);
1606
1868
  if (!message.text) continue;
1607
1869
  textParts.push(message.text);
1608
- if (message.role === "user") lastUserText = message.text;
1870
+ if (message.role === "user") {
1871
+ lastUserText = message.text;
1872
+ nameSlots = applyNameCandidate(
1873
+ nameSlots,
1874
+ "firstUserMessage",
1875
+ message.text,
1876
+ CODEX_CLI_PROVIDER
1877
+ );
1878
+ }
1609
1879
  }
1610
1880
  } catch (err) {
1611
1881
  log.warn({ filePath, err }, "parseCodexConversation: read failed");
@@ -1617,8 +1887,8 @@ async function parseCodexConversation(filePath, account) {
1617
1887
  filePath,
1618
1888
  projectPath: cwd,
1619
1889
  projectName: getShortProjectName3(cwd),
1620
- sessionId: sessionId || basename4(filePath, ".jsonl"),
1621
- sessionName: "",
1890
+ sessionId: sessionId || basename5(filePath, ".jsonl"),
1891
+ sessionName: resolveSessionName({ ...nameSlots, ...codexNameSlotsFor(filePath, sessionId) }).name ?? "",
1622
1892
  messages,
1623
1893
  fullText: textParts.join(" "),
1624
1894
  timestamp: latestTimestamp || (/* @__PURE__ */ new Date()).toISOString(),
@@ -1630,9 +1900,9 @@ async function parseCodexConversation(filePath, account) {
1630
1900
 
1631
1901
  // src/providers/copilot.ts
1632
1902
  import fg3 from "fast-glob";
1633
- import { createReadStream as createReadStream5, statSync as statSync2 } from "fs";
1903
+ import { createReadStream as createReadStream5, statSync as statSync3 } from "fs";
1634
1904
  import { stat as stat3 } from "fs/promises";
1635
- import { basename as basename5, dirname as dirname3 } from "path";
1905
+ import { basename as basename6, dirname as dirname4 } from "path";
1636
1906
  import { createInterface as createInterface3 } from "readline";
1637
1907
  var SESSION_START = "session.start";
1638
1908
  var USER_MESSAGE = "user.message";
@@ -1686,6 +1956,7 @@ var CopilotProvider = class {
1686
1956
  messageCount: 0,
1687
1957
  lastMessageSender: "user",
1688
1958
  firstUser: null,
1959
+ nameSlots: {},
1689
1960
  lastUser: null,
1690
1961
  lastAssistant: null,
1691
1962
  toolNames: [],
@@ -1793,6 +2064,7 @@ function reduceCopilotEntry(acc, entry, tier) {
1793
2064
  const snapshot = { text: text.slice(0, 200), timestamp };
1794
2065
  if (role === "user") {
1795
2066
  if (!acc.firstUser) acc.firstUser = snapshot;
2067
+ acc.nameSlots = applyNameCandidate(acc.nameSlots, "firstUserMessage", text, COPILOT_PROVIDER);
1796
2068
  acc.lastUser = snapshot;
1797
2069
  } else {
1798
2070
  acc.lastAssistant = snapshot;
@@ -1811,6 +2083,7 @@ function reduceCopilotEntry(acc, entry, tier) {
1811
2083
  function finalizeCopilotMeta(acc, filePath, account, tier) {
1812
2084
  if (acc.messageCount === 0) return null;
1813
2085
  const sessionId = acc.sessionId || sessionIdFromPath(filePath);
2086
+ const nameSlots = { ...acc.nameSlots, ...copilotNameSlotsFor(filePath) };
1814
2087
  const kind = acc.lastAssistant === null && acc.toolNames.length > 0 ? "task" : "conversation";
1815
2088
  return {
1816
2089
  id: filePath,
@@ -1819,7 +2092,8 @@ function finalizeCopilotMeta(acc, filePath, account, tier) {
1819
2092
  kind,
1820
2093
  externalSessionId: sessionId,
1821
2094
  sessionId,
1822
- sessionName: deriveSessionNameFromFirstMessage(acc.firstUser),
2095
+ sessionName: resolveSessionName(nameSlots).name ?? "",
2096
+ nameSlots,
1823
2097
  projectPath: acc.cwd,
1824
2098
  projectName: getShortProjectName4(acc.cwd),
1825
2099
  account,
@@ -1841,14 +2115,14 @@ function finalizeCopilotMeta(acc, filePath, account, tier) {
1841
2115
  };
1842
2116
  }
1843
2117
  function sessionIdFromPath(filePath) {
1844
- return basename5(dirname3(filePath));
2118
+ return basename6(dirname4(filePath));
1845
2119
  }
1846
2120
  function getShortProjectName4(fullPath) {
1847
2121
  return fullPath.split(/[/\\]/).filter(Boolean).slice(-3).join("/");
1848
2122
  }
1849
2123
  function fileMtimeIso(filePath) {
1850
2124
  try {
1851
- return new Date(statSync2(filePath).mtimeMs).toISOString();
2125
+ return new Date(statSync3(filePath).mtimeMs).toISOString();
1852
2126
  } catch {
1853
2127
  return (/* @__PURE__ */ new Date()).toISOString();
1854
2128
  }
@@ -1861,6 +2135,7 @@ async function parseCopilotConversation(filePath, account) {
1861
2135
  let cwd = "";
1862
2136
  let latestTimestamp = "";
1863
2137
  let lastUserText = "";
2138
+ let nameSlots = {};
1864
2139
  const rl = createInterface3({ input: createReadStream5(filePath), crlfDelay: Infinity });
1865
2140
  try {
1866
2141
  for await (const line of rl) {
@@ -1885,7 +2160,15 @@ async function parseCopilotConversation(filePath, account) {
1885
2160
  messages.push(message);
1886
2161
  if (!message.text) continue;
1887
2162
  textParts.push(message.text);
1888
- if (message.role === "user") lastUserText = message.text;
2163
+ if (message.role === "user") {
2164
+ lastUserText = message.text;
2165
+ nameSlots = applyNameCandidate(
2166
+ nameSlots,
2167
+ "firstUserMessage",
2168
+ message.text,
2169
+ COPILOT_PROVIDER
2170
+ );
2171
+ }
1889
2172
  }
1890
2173
  } catch (err) {
1891
2174
  log.warn({ filePath, err }, "parseCopilotConversation: read failed");
@@ -1898,7 +2181,7 @@ async function parseCopilotConversation(filePath, account) {
1898
2181
  projectPath: cwd,
1899
2182
  projectName: getShortProjectName4(cwd),
1900
2183
  sessionId: sessionId || sessionIdFromPath(filePath),
1901
- sessionName: "",
2184
+ sessionName: resolveSessionName({ ...nameSlots, ...copilotNameSlotsFor(filePath) }).name ?? "",
1902
2185
  messages,
1903
2186
  fullText: textParts.join(" "),
1904
2187
  timestamp: latestTimestamp || fileMtimeIso(filePath),
@@ -1911,9 +2194,9 @@ async function parseCopilotConversation(filePath, account) {
1911
2194
  // src/providers/cursor.ts
1912
2195
  import { createHash as createHash2 } from "crypto";
1913
2196
  import fg4 from "fast-glob";
1914
- import { createReadStream as createReadStream6, existsSync, statSync as statSync3 } from "fs";
2197
+ import { createReadStream as createReadStream6, existsSync as existsSync2, statSync as statSync4 } from "fs";
1915
2198
  import { stat as stat4 } from "fs/promises";
1916
- import { basename as basename6, dirname as dirname4, join as join4, sep as sep2 } from "path";
2199
+ import { basename as basename7, dirname as dirname5, join as join5, sep as sep2 } from "path";
1917
2200
  import { createInterface as createInterface4 } from "readline";
1918
2201
  var TIMESTAMP_RE = /<timestamp>\s*([\s\S]*?)\s*<\/timestamp>/;
1919
2202
  var USER_QUERY_RE = /<user_query>\s*([\s\S]*?)\s*<\/user_query>/;
@@ -1972,6 +2255,7 @@ var CursorProvider = class {
1972
2255
  parentSessionUuid: null,
1973
2256
  subagentId: null,
1974
2257
  firstUser: null,
2258
+ nameSlots: {},
1975
2259
  lastUser: null,
1976
2260
  lastAssistant: null,
1977
2261
  isImportedFromClaude: false,
@@ -2038,6 +2322,15 @@ function noteImportProvenance(acc, entry, text) {
2038
2322
  acc.isImportedFromCodex = true;
2039
2323
  }
2040
2324
  }
2325
+ function cursorUserQuery(content) {
2326
+ const texts = typeof content === "string" ? [content] : Array.isArray(content) ? content : [];
2327
+ for (const item of texts) {
2328
+ const text = typeof item === "string" ? item : item?.text;
2329
+ const query = typeof text === "string" ? text.match(USER_QUERY_RE) : null;
2330
+ if (query) return query[1];
2331
+ }
2332
+ return void 0;
2333
+ }
2041
2334
  function unwrapCursorUserText(text) {
2042
2335
  const query = text.match(USER_QUERY_RE);
2043
2336
  const body = query ? query[1] : text.replace(TIMESTAMP_RE, "");
@@ -2175,6 +2468,14 @@ function reduceCursorEntry(acc, entry, tier) {
2175
2468
  collectCursorToolNames(content, acc.toolNames);
2176
2469
  const text = textHint;
2177
2470
  if (!text) return;
2471
+ if (entry.role === "user") {
2472
+ acc.nameSlots = applyNameCandidate(
2473
+ acc.nameSlots,
2474
+ "firstUserMessage",
2475
+ cursorUserQuery(content),
2476
+ CURSOR_PROVIDER
2477
+ );
2478
+ }
2178
2479
  foldCursorMessage(acc, entry.role, text, firstTimestampHint(content), tier);
2179
2480
  return;
2180
2481
  }
@@ -2193,7 +2494,8 @@ function reduceCursorEntry(acc, entry, tier) {
2193
2494
  }
2194
2495
  function finalizeCursorMeta(acc, filePath, account, tier) {
2195
2496
  if (acc.messageCount === 0) return null;
2196
- const sessionId = basename6(filePath, ".jsonl");
2497
+ const sessionId = basename7(filePath, ".jsonl");
2498
+ const nameSlots = { ...acc.nameSlots, ...cursorNameSlotsFor(filePath, sessionId) };
2197
2499
  const isSubagent = SUBAGENT_PATH_RE2.test(filePath);
2198
2500
  const parent = isSubagent ? parentFromSubagentPath(filePath) : null;
2199
2501
  const { projectPath, projectName } = projectFromCursorPath(filePath);
@@ -2206,7 +2508,8 @@ function finalizeCursorMeta(acc, filePath, account, tier) {
2206
2508
  kind,
2207
2509
  externalSessionId: sessionId,
2208
2510
  sessionId,
2209
- sessionName: deriveSessionNameFromFirstMessage(acc.firstUser),
2511
+ sessionName: resolveSessionName(nameSlots).name ?? "",
2512
+ nameSlots,
2210
2513
  projectPath,
2211
2514
  projectName,
2212
2515
  account,
@@ -2232,20 +2535,20 @@ function finalizeCursorMeta(acc, filePath, account, tier) {
2232
2535
  };
2233
2536
  }
2234
2537
  function parentFromSubagentPath(filePath) {
2235
- const subagentsDir = dirname4(filePath);
2236
- const parentDir = dirname4(subagentsDir);
2237
- const parentSessionUuid = basename6(parentDir);
2538
+ const subagentsDir = dirname5(filePath);
2539
+ const parentDir = dirname5(subagentsDir);
2540
+ const parentSessionUuid = basename7(parentDir);
2238
2541
  if (!parentSessionUuid) return null;
2239
2542
  return {
2240
2543
  parentSessionUuid,
2241
- parentFilePath: canonicalPath(join4(parentDir, `${parentSessionUuid}.jsonl`))
2544
+ parentFilePath: canonicalPath(join5(parentDir, `${parentSessionUuid}.jsonl`))
2242
2545
  };
2243
2546
  }
2244
2547
  function projectFromCursorPath(filePath) {
2245
2548
  const parts = filePath.split(/[/\\]/);
2246
2549
  const idx = parts.lastIndexOf("agent-transcripts");
2247
- const cursorProjectDir = idx > 0 ? parts.slice(0, idx).join(sep2) : dirname4(dirname4(filePath));
2248
- const slug = basename6(cursorProjectDir);
2550
+ const cursorProjectDir = idx > 0 ? parts.slice(0, idx).join(sep2) : dirname5(dirname5(filePath));
2551
+ const slug = basename7(cursorProjectDir);
2249
2552
  const decoded = decodeCursorProjectSlug(slug);
2250
2553
  const projectPath = decoded ?? cursorProjectDir;
2251
2554
  return { projectPath, projectName: getShortProjectName5(projectPath) || slug };
@@ -2259,7 +2562,7 @@ function decodeCursorProjectSlug(slug) {
2259
2562
  let i = 0;
2260
2563
  if (rooted && segments[0] === "Users") {
2261
2564
  const users = `${sep2}Users`;
2262
- if (!existsSync(users)) return null;
2565
+ if (!existsSync2(users)) return null;
2263
2566
  acc = users;
2264
2567
  i = 1;
2265
2568
  }
@@ -2267,9 +2570,9 @@ function decodeCursorProjectSlug(slug) {
2267
2570
  let found = null;
2268
2571
  let next = i + 1;
2269
2572
  for (let j = segments.length; j > i; j--) {
2270
- const candidate = join4(acc, segments.slice(i, j).join("-"));
2573
+ const candidate = join5(acc, segments.slice(i, j).join("-"));
2271
2574
  try {
2272
- if (existsSync(candidate) && statSync3(candidate).isDirectory()) {
2575
+ if (existsSync2(candidate) && statSync4(candidate).isDirectory()) {
2273
2576
  found = candidate;
2274
2577
  next = j;
2275
2578
  break;
@@ -2288,17 +2591,26 @@ function getShortProjectName5(fullPath) {
2288
2591
  }
2289
2592
  function fileMtimeIso2(filePath) {
2290
2593
  try {
2291
- return new Date(statSync3(filePath).mtimeMs).toISOString();
2594
+ return new Date(statSync4(filePath).mtimeMs).toISOString();
2292
2595
  } catch {
2293
2596
  return (/* @__PURE__ */ new Date()).toISOString();
2294
2597
  }
2295
2598
  }
2599
+ function cursorLineContent(line) {
2600
+ try {
2601
+ const entry = JSON.parse(line);
2602
+ return entry.message?.content ?? entry.content;
2603
+ } catch {
2604
+ return void 0;
2605
+ }
2606
+ }
2296
2607
  async function parseCursorConversation(filePath, account) {
2297
2608
  const log = getLogger();
2298
2609
  const messages = [];
2299
2610
  const textParts = [];
2300
2611
  let latestTimestamp = "";
2301
2612
  let lastUserText = "";
2613
+ let nameSlots = {};
2302
2614
  const rl = createInterface4({ input: createReadStream6(filePath), crlfDelay: Infinity });
2303
2615
  try {
2304
2616
  for await (const line of rl) {
@@ -2310,7 +2622,17 @@ async function parseCursorConversation(filePath, account) {
2310
2622
  messages.push(message);
2311
2623
  if (!message.text) continue;
2312
2624
  textParts.push(message.text);
2313
- if (message.role === "user") lastUserText = message.text;
2625
+ if (message.role === "user") {
2626
+ lastUserText = message.text;
2627
+ if (nameSlots.firstUserMessage === void 0) {
2628
+ nameSlots = applyNameCandidate(
2629
+ nameSlots,
2630
+ "firstUserMessage",
2631
+ cursorUserQuery(cursorLineContent(line)),
2632
+ CURSOR_PROVIDER
2633
+ );
2634
+ }
2635
+ }
2314
2636
  }
2315
2637
  } catch (err) {
2316
2638
  log.warn({ filePath, err }, "parseCursorConversation: read failed");
@@ -2318,14 +2640,14 @@ async function parseCursorConversation(filePath, account) {
2318
2640
  }
2319
2641
  if (messages.length === 0) return null;
2320
2642
  const { projectPath, projectName } = projectFromCursorPath(filePath);
2321
- const sessionId = basename6(filePath, ".jsonl");
2643
+ const sessionId = basename7(filePath, ".jsonl");
2322
2644
  return {
2323
2645
  id: filePath,
2324
2646
  filePath,
2325
2647
  projectPath,
2326
2648
  projectName,
2327
2649
  sessionId,
2328
- sessionName: "",
2650
+ sessionName: resolveSessionName({ ...nameSlots, ...cursorNameSlotsFor(filePath, sessionId) }).name ?? "",
2329
2651
  messages,
2330
2652
  fullText: textParts.join(" "),
2331
2653
  timestamp: latestTimestamp || fileMtimeIso2(filePath),
@@ -2565,12 +2887,12 @@ function resolveTier(tierName, customTiers) {
2565
2887
  }
2566
2888
 
2567
2889
  // src/persistent/db.ts
2568
- import Database from "better-sqlite3";
2890
+ import Database2 from "better-sqlite3";
2569
2891
  import { mkdirSync } from "fs";
2570
- import { dirname as dirname5 } from "path";
2892
+ import { dirname as dirname6 } from "path";
2571
2893
 
2572
2894
  // src/persistent/schema.ts
2573
- var SCHEMA_VERSION = 10;
2895
+ var SCHEMA_VERSION = 11;
2574
2896
  var SCHEMA_SQL = `
2575
2897
  CREATE TABLE IF NOT EXISTS conversation_files (
2576
2898
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -2616,6 +2938,9 @@ CREATE TABLE IF NOT EXISTS conversations (
2616
2938
  external_session_id TEXT,
2617
2939
  session_id TEXT NOT NULL,
2618
2940
  session_name TEXT,
2941
+ -- JSON NameSlots the name was resolved from; lets a side-store change
2942
+ -- re-resolve the name without reparsing the transcript.
2943
+ name_slots TEXT,
2619
2944
 
2620
2945
  project_path TEXT,
2621
2946
  project_name TEXT,
@@ -2878,6 +3203,27 @@ function runMigrations(db) {
2878
3203
  db.exec(`UPDATE conversation_files SET ${assignments.join(", ")}`);
2879
3204
  }
2880
3205
  }
3206
+ if (current >= 1 && current < 11 && tableExists(db, "conversations")) {
3207
+ if (tableExists(db, "message_checkpoints")) db.exec("DELETE FROM message_checkpoints");
3208
+ if (!hasColumn(db, "conversations", "name_slots")) {
3209
+ db.exec("ALTER TABLE conversations ADD COLUMN name_slots TEXT");
3210
+ }
3211
+ if (tableExists(db, "conversation_files")) {
3212
+ const assignments = [];
3213
+ if (hasColumn(db, "conversation_files", "last_indexed_offset")) {
3214
+ assignments.push("last_indexed_offset = 0");
3215
+ }
3216
+ if (hasColumn(db, "conversation_files", "last_indexed_line")) {
3217
+ assignments.push("last_indexed_line = 0");
3218
+ }
3219
+ if (hasColumn(db, "conversation_files", "reducer_state")) {
3220
+ assignments.push("reducer_state = NULL");
3221
+ }
3222
+ if (assignments.length > 0) {
3223
+ db.exec(`UPDATE conversation_files SET ${assignments.join(", ")}`);
3224
+ }
3225
+ }
3226
+ }
2881
3227
  db.exec(SCHEMA_SQL);
2882
3228
  db.pragma(`user_version = ${SCHEMA_VERSION}`);
2883
3229
  }
@@ -2892,11 +3238,11 @@ function hasColumn(db, table, column) {
2892
3238
  // src/persistent/db.ts
2893
3239
  function openDatabase(dbPath) {
2894
3240
  if (dbPath !== ":memory:") {
2895
- mkdirSync(dirname5(dbPath), { recursive: true });
3241
+ mkdirSync(dirname6(dbPath), { recursive: true });
2896
3242
  }
2897
3243
  let db;
2898
3244
  try {
2899
- db = new Database(dbPath);
3245
+ db = new Database2(dbPath);
2900
3246
  } catch (err) {
2901
3247
  if (isNativeBindingFailure(err)) throw nativeBindingError(err, dbPath);
2902
3248
  throw err;
@@ -2937,7 +3283,7 @@ function nativeBindingError(err, dbPath) {
2937
3283
 
2938
3284
  // src/persistent/dir-watermark.ts
2939
3285
  import { readdir, stat as stat5 } from "fs/promises";
2940
- import { dirname as dirname6, join as join5 } from "path";
3286
+ import { dirname as dirname7, join as join6 } from "path";
2941
3287
  var FULL_RECONCILE_EVERY_N_SCANS = 20;
2942
3288
  async function discoverJsonlFilesGated(dirs, files, scannedDirs, options = {}) {
2943
3289
  const log = getLogger();
@@ -3008,10 +3354,10 @@ async function resolveProjectDirs(projectsDir, scannedDirs) {
3008
3354
  return { entries, commitRoot: { mtimeMs: rootStat.mtimeMs } };
3009
3355
  }
3010
3356
  function dirnameOf(filePath) {
3011
- return dirname6(filePath);
3357
+ return dirname7(filePath);
3012
3358
  }
3013
3359
  function joinPath(dir, name) {
3014
- return join5(dir, name);
3360
+ return join6(dir, name);
3015
3361
  }
3016
3362
 
3017
3363
  // src/persistent/repositories/checkpoints.repo.ts
@@ -3091,7 +3437,7 @@ function toCheckpoint(row) {
3091
3437
  }
3092
3438
 
3093
3439
  // src/persistent/repositories/conversation-files.repo.ts
3094
- import { basename as basename7, dirname as dirname7 } from "path";
3440
+ import { basename as basename8, dirname as dirname8 } from "path";
3095
3441
  var ConversationFilesRepo = class {
3096
3442
  constructor(db) {
3097
3443
  this.db = db;
@@ -3114,7 +3460,7 @@ var ConversationFilesRepo = class {
3114
3460
  const info = this.db.prepare(
3115
3461
  `INSERT INTO conversation_files (absolute_path, parent_dir, file_name, account)
3116
3462
  VALUES (?, ?, ?, ?)`
3117
- ).run(canonical, dirname7(canonical), basename7(canonical), account);
3463
+ ).run(canonical, dirname8(canonical), basename8(canonical), account);
3118
3464
  return Number(info.lastInsertRowid);
3119
3465
  }
3120
3466
  // Advance the cursor + persisted reducer state after a successful index pass.
@@ -3190,6 +3536,7 @@ function rowToMeta(row) {
3190
3536
  externalSessionId: row.external_session_id ?? void 0,
3191
3537
  sessionId: row.session_id,
3192
3538
  sessionName: row.session_name ?? "",
3539
+ nameSlots: row.name_slots ? JSON.parse(row.name_slots) : void 0,
3193
3540
  projectPath: row.project_path ?? "",
3194
3541
  projectName: row.project_name ?? "",
3195
3542
  account: row.account,
@@ -3233,7 +3580,7 @@ var ConversationsRepo = class {
3233
3580
  model, is_subagent, parent_session_id, subagent_id, parent_session_uuid,
3234
3581
  is_teammate, team_name, tool_names_json,
3235
3582
  last_prompt, is_imported_from_claude, is_imported_from_codex,
3236
- is_imported_from_cursor, status, updated_at
3583
+ is_imported_from_cursor, name_slots, status, updated_at
3237
3584
  ) VALUES (
3238
3585
  @file_id, @source_path, @provider, @kind, @external_session_id,
3239
3586
  @session_id, @session_name, @project_path, @project_name,
@@ -3245,7 +3592,7 @@ var ConversationsRepo = class {
3245
3592
  @model, @is_subagent, @parent_session_id, @subagent_id, @parent_session_uuid,
3246
3593
  @is_teammate, @team_name, @tool_names_json,
3247
3594
  @last_prompt, @is_imported_from_claude, @is_imported_from_codex,
3248
- @is_imported_from_cursor, 'active', CURRENT_TIMESTAMP
3595
+ @is_imported_from_cursor, @name_slots, 'active', CURRENT_TIMESTAMP
3249
3596
  )
3250
3597
  ON CONFLICT(file_id) DO UPDATE SET
3251
3598
  source_path = excluded.source_path,
@@ -3280,6 +3627,7 @@ var ConversationsRepo = class {
3280
3627
  is_imported_from_claude = excluded.is_imported_from_claude,
3281
3628
  is_imported_from_codex = excluded.is_imported_from_codex,
3282
3629
  is_imported_from_cursor = excluded.is_imported_from_cursor,
3630
+ name_slots = excluded.name_slots,
3283
3631
  status = 'active',
3284
3632
  index_seq = (SELECT COALESCE(MAX(index_seq), 0) + 1 FROM conversations),
3285
3633
  updated_at = CURRENT_TIMESTAMP`
@@ -3319,7 +3667,8 @@ var ConversationsRepo = class {
3319
3667
  last_prompt: meta.lastPrompt ?? null,
3320
3668
  is_imported_from_claude: meta.isImportedFromClaude ? 1 : 0,
3321
3669
  is_imported_from_codex: meta.isImportedFromCodex ? 1 : 0,
3322
- is_imported_from_cursor: meta.isImportedFromCursor ? 1 : 0
3670
+ is_imported_from_cursor: meta.isImportedFromCursor ? 1 : 0,
3671
+ name_slots: meta.nameSlots ? JSON.stringify(meta.nameSlots) : null
3323
3672
  });
3324
3673
  }
3325
3674
  getBySourcePath(sourcePath) {
@@ -3568,7 +3917,7 @@ var ScannedDirsRepo = class {
3568
3917
  };
3569
3918
 
3570
3919
  // src/persistent/sidecar.ts
3571
- import { readFileSync as readFileSync2, writeFileSync } from "fs";
3920
+ import { readFileSync as readFileSync3, writeFileSync } from "fs";
3572
3921
  var SIDECAR_VERSION = 1;
3573
3922
  function sidecarPath(jsonlPath) {
3574
3923
  return `${jsonlPath}.idx.json`;
@@ -3733,13 +4082,18 @@ var PersistentEngine = class {
3733
4082
  const tier = resolveTier(tierName, customTiers);
3734
4083
  const filePath = canonicalPath(rawFilePath);
3735
4084
  const existing = this.files.getByPath(filePath);
3736
- const { change, stat: stat6 } = classify(filePath, existing);
4085
+ const classified = classify(filePath, existing);
4086
+ const stat6 = classified.stat;
4087
+ let change = classified.change;
3737
4088
  if (change === "vanished" || !stat6) {
3738
4089
  this.markDeleted(filePath);
3739
4090
  return { meta: null, change: "vanished" };
3740
4091
  }
3741
4092
  if (change === "unchanged" && !force) {
3742
- return { meta: this.conversations.getBySourcePath(filePath), change };
4093
+ const meta2 = this.conversations.getBySourcePath(filePath);
4094
+ const sideStoresMoved = provider && provider.name !== CLAUDE_CODE_PROVIDER && meta2 && JSON.stringify(nameStoreSlotsFor(provider.name, filePath, meta2.sessionId)) !== existing?.reducer_state;
4095
+ if (!sideStoresMoved) return { meta: meta2, change };
4096
+ change = "reindex";
3743
4097
  }
3744
4098
  if (provider && provider.name !== CLAUDE_CODE_PROVIDER) {
3745
4099
  const meta2 = await this.indexFileWithProvider(
@@ -3821,7 +4175,7 @@ var PersistentEngine = class {
3821
4175
  // provider's reducer/finalize, then the same upsert + FTS write + cursor bump
3822
4176
  // the Threadbase path uses. The cursor records size/mtime (and offset = size)
3823
4177
  // so the next pass classifies an unchanged file as "unchanged" and skips it;
3824
- // any change reparses from 0 again. No reducer_state is persisted.
4178
+ // any change reparses from 0 again. reducer_state holds the side-store name slots, not a fold.
3825
4179
  async indexFileWithProvider(provider, filePath, account, tier, stat6, resolveGitBranch) {
3826
4180
  const log = getLogger();
3827
4181
  let searchDoc = emptySearchDocument();
@@ -3835,6 +4189,7 @@ var PersistentEngine = class {
3835
4189
  if (meta.gitBranch === null && meta.projectPath) {
3836
4190
  meta.gitBranch = resolveGitBranch(meta.projectPath);
3837
4191
  }
4192
+ const sideSlots = nameStoreSlotsFor(provider.name, filePath, meta.sessionId);
3838
4193
  const fp = stat6.size > 0 ? fingerprint(filePath, stat6.size) : null;
3839
4194
  const fileId = this.files.ensure(filePath, account);
3840
4195
  const upsert = this.db.transaction(() => {
@@ -3850,7 +4205,9 @@ var PersistentEngine = class {
3850
4205
  // can classify it "unchanged"); no resumable reducer state is kept.
3851
4206
  offset: stat6.size,
3852
4207
  line: 0,
3853
- reducerState: null,
4208
+ // Not resumable state: the side-store name slots this parse used, so the
4209
+ // next pass can tell when they moved (see indexFile).
4210
+ reducerState: JSON.stringify(sideSlots),
3854
4211
  fingerprint: fp,
3855
4212
  status: "active"
3856
4213
  });
@@ -3930,7 +4287,7 @@ var PersistentEngine = class {
3930
4287
  let floor = this.checkpoints.floor(filePath, fromIndex);
3931
4288
  if (floor) {
3932
4289
  try {
3933
- if (floor.byteOffset > statSync4(filePath).size) floor = null;
4290
+ if (floor.byteOffset > statSync5(filePath).size) floor = null;
3934
4291
  } catch {
3935
4292
  }
3936
4293
  }
@@ -4105,7 +4462,7 @@ function defaultDbPath() {
4105
4462
  "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."
4106
4463
  );
4107
4464
  }
4108
- return join6(homedir2(), ".config", "threadbase-scanner", "index.db");
4465
+ return join7(homedir2(), ".config", "threadbase-scanner", "index.db");
4109
4466
  }
4110
4467
  function capForMemory(doc, max) {
4111
4468
  const combined = combineSearchContent(doc);
@@ -4198,6 +4555,7 @@ var ConversationScanner = class {
4198
4555
  }
4199
4556
  }
4200
4557
  async runScan(options) {
4558
+ if (options.cursorStateDb !== void 0) setCursorStateDb(options.cursorStateDb);
4201
4559
  const profiles = await this.resolveProfiles(options.profiles);
4202
4560
  const activeProfiles = profiles.filter((p) => p.enabled && p.scanHistory !== false);
4203
4561
  this.lastTier = resolveTier(options.tier ?? "standard", options.tiers);
@@ -4284,7 +4642,7 @@ var ConversationScanner = class {
4284
4642
  const cached = statCache.get(filePath);
4285
4643
  if (cached) {
4286
4644
  try {
4287
- const s = statSync5(filePath);
4645
+ const s = statSync6(filePath);
4288
4646
  if (s.mtimeMs === cached.stat.mtimeMs && s.size === cached.stat.size) {
4289
4647
  return {
4290
4648
  meta: cached.meta,
@@ -4832,13 +5190,13 @@ var ConversationScanner = class {
4832
5190
  if (previous?.provider) return void 0;
4833
5191
  let sample = "";
4834
5192
  try {
4835
- const fd = openSync2(filePath, "r");
5193
+ const fd = openSync3(filePath, "r");
4836
5194
  try {
4837
5195
  const buf = Buffer.alloc(8192);
4838
- const n = readSync2(fd, buf, 0, buf.length, 0);
5196
+ const n = readSync3(fd, buf, 0, buf.length, 0);
4839
5197
  sample = buf.subarray(0, n).toString("utf8");
4840
5198
  } finally {
4841
- closeSync2(fd);
5199
+ closeSync3(fd);
4842
5200
  }
4843
5201
  } catch {
4844
5202
  return void 0;