sessiongraph 1.0.12 → 1.0.13

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.
@@ -2985,6 +2985,14 @@ function blockEvents(message2, content, transform = (v3) => v3) {
2985
2985
  return [eventFor(message2, id2, "event", `${part.type || "Unknown"} content`, "This content type is not represented as text.", { ...fields2, partial: true })];
2986
2986
  });
2987
2987
  }
2988
+ function userBlockEvents(message2, content, normalize) {
2989
+ const context = [];
2990
+ return blockEvents(message2, content, (value) => {
2991
+ const text2 = normalize(value);
2992
+ context.push(Boolean(value && !text2));
2993
+ return text2 || value;
2994
+ }).map((event) => event.kind === "message" && context.shift() ? { ...event, kind: "event", role: "system", name: "Session context", nativeType: "user-context" } : event);
2995
+ }
2988
2996
  function normalizedEvents(message2, sessionID) {
2989
2997
  let events = message2.events;
2990
2998
  if (!events) {
@@ -30994,6 +31002,8 @@ import { chmodSync, constants as constants4, copyFileSync, lstatSync as lstatSyn
30994
31002
  import { tmpdir } from "node:os";
30995
31003
  import { join as join7 } from "node:path";
30996
31004
  var copies = /* @__PURE__ */ new Map();
31005
+ var SqliteSnapshotChangedError = class extends Error {
31006
+ };
30997
31007
  var close = (path) => {
30998
31008
  const copy = copies.get(path);
30999
31009
  if (!copy) return;
@@ -31023,7 +31033,7 @@ function withSqliteSnapshot(path, read3, expected, pinned = false) {
31023
31033
  const retained = copies.get(path);
31024
31034
  if (pinned && expected && retained?.revision === expected) return read3(retained.db);
31025
31035
  const revision2 = sqliteRevision(path);
31026
- if (expected && revision2 !== expected) throw new Error("History database changed during import; import again.");
31036
+ if (expected && revision2 !== expected) throw new SqliteSnapshotChangedError("History database changed during import; import again.");
31027
31037
  let copy = copies.get(path);
31028
31038
  if (copy?.revision !== revision2) {
31029
31039
  close(path);
@@ -31042,7 +31052,7 @@ function withSqliteSnapshot(path, read3, expected, pinned = false) {
31042
31052
  throw error;
31043
31053
  }
31044
31054
  }
31045
- if (sqliteRevision(path) !== revision2) throw new Error("History database changed while copying; import again.");
31055
+ if (sqliteRevision(path) !== revision2) throw new SqliteSnapshotChangedError("History database changed while copying; import again.");
31046
31056
  db2 = new DatabaseSync(destination, { readOnly: true, enableDoubleQuotedStringLiterals: false, allowExtension: false });
31047
31057
  db2.exec("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; PRAGMA busy_timeout=1000; BEGIN;");
31048
31058
  copy = { revision: revision2, directory: directory2, db: db2 };
@@ -31057,7 +31067,7 @@ function withSqliteSnapshot(path, read3, expected, pinned = false) {
31057
31067
  }
31058
31068
  }
31059
31069
  const result = read3(copy.db);
31060
- if (!pinned && sqliteRevision(path) !== revision2) throw new Error("History database changed during reading; import again.");
31070
+ if (!pinned && sqliteRevision(path) !== revision2) throw new SqliteSnapshotChangedError("History database changed during reading; import again.");
31061
31071
  return result;
31062
31072
  }
31063
31073
  function hasTable(db2, name) {
@@ -31138,18 +31148,23 @@ function sqliteHistoryAdapter(source) {
31138
31148
  let unavailable = false;
31139
31149
  for (const path of await source.paths()) {
31140
31150
  try {
31141
- const snapshot2 = sqliteRevision(path), rev = digest([2, source.id, snapshot2]);
31151
+ const snapshot2 = sqliteRevision(path), rev = digest([source.version || 2, source.id, snapshot2]);
31142
31152
  let cached2 = metadata2.get(path);
31143
31153
  if (!cached2 || cached2.revision !== rev) {
31144
31154
  cached2 = withSqliteSnapshot(path, (db2) => {
31145
31155
  const table = typeof source.table === "string" ? source.table : source.table(db2);
31146
31156
  const values2 = rows(db2, table, source.fields, void 0, source.key, 2e4), found = [];
31147
31157
  const blocked2 = [], warnings2 = [];
31158
+ let empty = 0;
31148
31159
  for (const row of values2) {
31149
31160
  try {
31150
31161
  const h3 = parseHistory(source, db2, row, path);
31151
31162
  if (!h3) continue;
31152
- if (source.history !== false && !h3.messages.length) throw new Error("No readable conversation.");
31163
+ if (source.history !== false && !h3.messages.length) {
31164
+ blocked2.push(identity(source.id, String(row[source.key])));
31165
+ empty++;
31166
+ continue;
31167
+ }
31153
31168
  if (!h3.nativeID || h3.nativeID.length > 512) throw new Error("Missing native session identity.");
31154
31169
  const created = time(h3.session?.created) || h3.messages.map((m) => time(m.time)).find(Boolean);
31155
31170
  if (!created) throw new Error("Session has no recorded creation or message date.");
@@ -31169,7 +31184,8 @@ function sqliteHistoryAdapter(source) {
31169
31184
  blocked2.push(identity(source.id, String(row[source.key])));
31170
31185
  }
31171
31186
  }
31172
- if (blocked2.length) warnings2.push(`${blocked2.length} ${source.name} sessions had unsupported, undated, missing, or oversized history; saved imports are kept.`);
31187
+ if (blocked2.length > empty) warnings2.push(`${blocked2.length - empty} ${source.name} sessions had unsupported, undated, missing, or oversized history; saved imports are kept.`);
31188
+ if (empty) warnings2.push(`${empty} empty ${source.name} sessions had no saved messages; previous imports are kept.`);
31173
31189
  return { revision: rev, candidates: found, blocked: blocked2, warnings: warnings2 };
31174
31190
  }, snapshot2);
31175
31191
  metadata2.set(path, cached2);
@@ -31499,7 +31515,7 @@ async function transcriptFiles(root3, max = 2e4, match2 = (name) => name.endsWit
31499
31515
  var root2 = () => sourcePath("codex") || process.env.CODEX_HOME || join10(homedir5(), ".codex");
31500
31516
  var revision = async (path) => {
31501
31517
  const s = await stat2(path);
31502
- return digest([8, s.mtimeMs, s.size]);
31518
+ return digest([9, s.mtimeMs, s.size]);
31503
31519
  };
31504
31520
  function changedPaths(value) {
31505
31521
  if (!value || typeof value !== "object") return [];
@@ -31509,9 +31525,14 @@ function changedPaths(value) {
31509
31525
  function codexUserText(value) {
31510
31526
  if (typeof value !== "string") return "";
31511
31527
  let text2 = value.trim();
31528
+ for (; ; ) {
31529
+ const context = text2.match(/^<(environment_context|permissions|user_instructions|turn_aborted|system_instruction|recommended_plugins|external_codex_[\w-]+)(?:\s[^>]*)?>/i);
31530
+ if (!context) break;
31531
+ const end = text2.toLowerCase().indexOf(`</${context[1].toLowerCase()}>`, context[0].length);
31532
+ if (end < 0) return "";
31533
+ text2 = text2.slice(end + context[1].length + 3).trim();
31534
+ }
31512
31535
  if (/^# (?:AGENTS\.md|Instructions for)/i.test(text2)) return "";
31513
- text2 = text2.replace(/<(environment_context|permissions|user_instructions|turn_aborted|external_codex_[\w-]+)>[\s\S]*?<\/\1>/g, "").trim();
31514
- if (/^<(?:environment_context|permissions|user_instructions|turn_aborted|external_codex_[\w-]+)(?:>|\s)/.test(text2)) return "";
31515
31536
  return text2;
31516
31537
  }
31517
31538
  async function sessionNames() {
@@ -31564,8 +31585,7 @@ function codexRecord(raw, offset, candidate) {
31564
31585
  const role = p.role === "user" ? "user" : p.role === "assistant" ? "assistant" : p.type === "message" ? "system" : "tool";
31565
31586
  const msg = blankMessage(`item:${raw.ordinal ?? offset}`, Date.parse(raw.timestamp) || 0, role);
31566
31587
  const fields2 = { nativeID: p.id, nativeType: p.type, callID: p.call_id };
31567
- msg.events = p.type === "message" ? blockEvents(msg, p.content) : ["function_call", "custom_tool_call"].includes(p.type) ? [eventFor(msg, "call", "tool_call", p.name || "Tool call", "", { ...fields2, role: "assistant", input: eventText(p.arguments ?? p.input), status: "unknown" })] : ["function_call_output", "custom_tool_call_output"].includes(p.type) ? [eventFor(msg, "result", "tool_result", "Tool result", "", { ...fields2, output: eventText(p.output, 64e3), status: "unknown" })] : [eventFor(msg, "event", p.type === "reasoning" ? "reasoning" : "event", p.type === "reasoning" ? "Recorded reasoning summary" : p.type || "Unknown event", eventText(p.type === "reasoning" ? p.summary : p), { ...fields2, partial: p.type === "reasoning" })];
31568
- if (role === "user") msg.events = msg.events.map((event) => event.kind === "message" && event.text && !codexUserText(event.text) ? { ...event, kind: "event", role: "system", name: "Session context", nativeType: "user-context" } : event);
31588
+ msg.events = p.type === "message" ? role === "user" ? userBlockEvents(msg, p.content, codexUserText) : blockEvents(msg, p.content) : ["function_call", "custom_tool_call"].includes(p.type) ? [eventFor(msg, "call", "tool_call", p.name || "Tool call", "", { ...fields2, role: "assistant", input: eventText(p.arguments ?? p.input), status: "unknown" })] : ["function_call_output", "custom_tool_call_output"].includes(p.type) ? [eventFor(msg, "result", "tool_result", "Tool result", "", { ...fields2, output: eventText(p.output, 64e3), status: "unknown" })] : [eventFor(msg, "event", p.type === "reasoning" ? "reasoning" : "event", p.type === "reasoning" ? "Recorded reasoning summary" : p.type || "Unknown event", eventText(p.type === "reasoning" ? p.summary : p), { ...fields2, partial: p.type === "reasoning" })];
31569
31589
  if (p.type === "message") {
31570
31590
  for (const part of Array.isArray(p.content) ? p.content : []) if (["input_text", "output_text", "text"].includes(part.type)) addText(msg, role === "user" ? codexUserText(part.text) : part.text, role === "user" ? "You" : "Assistant");
31571
31591
  } else if (["function_call", "custom_tool_call"].includes(p.type)) {
@@ -31914,8 +31934,14 @@ var t3CodeAdapter = {
31914
31934
  async discover() {
31915
31935
  const path = await databasePath2();
31916
31936
  if (!path) return { sessions: [], projects: [], warnings: ["T3 Code database is unavailable. Saved history is retained."] };
31917
- const databaseRevision = sqliteRevision(path);
31918
- return withSqliteSnapshot(path, (db2) => hasTable(db2, "orchestration_v2_projection_threads") ? discoverV2(db2, path, databaseRevision) : discoverV1(db2, path, databaseRevision), databaseRevision);
31937
+ for (let attempt = 0; ; attempt++) {
31938
+ const databaseRevision = sqliteRevision(path);
31939
+ try {
31940
+ return withSqliteSnapshot(path, (db2) => hasTable(db2, "orchestration_v2_projection_threads") ? discoverV2(db2, path, databaseRevision) : discoverV1(db2, path, databaseRevision), databaseRevision);
31941
+ } catch (error) {
31942
+ if (!(error instanceof SqliteSnapshotChangedError) || attempt >= 2) throw error;
31943
+ }
31944
+ }
31919
31945
  },
31920
31946
  async read(candidate, cursor) {
31921
31947
  return withSqliteSnapshot(candidate.locator.path, (db2) => candidate.locator.format === "v2" ? readV2(db2, candidate, cursor) : readV1(db2, candidate, cursor), candidate.locator.databaseRevision, true);
@@ -31934,8 +31960,26 @@ function cursorTime(value) {
31934
31960
  const time4 = typeof value === "number" ? value : typeof value === "string" && /(?:Z|[+-]\d\d:\d\d)$/.test(value) ? Date.parse(value) : 0;
31935
31961
  return Number.isFinite(time4) && time4 > 0 && time4 <= 864e13 ? time4 : 0;
31936
31962
  }
31963
+ function cursorEnvelope(text2) {
31964
+ let value = text2.trim(), timestamp;
31965
+ for (; ; ) {
31966
+ value = value.replace(/^(?:\[Image\]\s*)+(?=<image_files>)/, "");
31967
+ const clock = value.match(/^<timestamp>([^<]+)<\/timestamp>\s*/);
31968
+ if (clock) {
31969
+ timestamp ??= clock[1];
31970
+ value = value.slice(clock[0].length);
31971
+ continue;
31972
+ }
31973
+ const context = value.match(/^<(user_info|environment_context|system_reminder|external_links|attached_files|image_files)(?:\s[^>]*)?>/);
31974
+ if (!context) break;
31975
+ const end = value.indexOf(`</${context[1]}>`, context[0].length);
31976
+ if (end < 0) return { text: "", timestamp };
31977
+ value = value.slice(end + context[1].length + 3).trim();
31978
+ }
31979
+ return { text: value, timestamp };
31980
+ }
31937
31981
  function cursorEnvelopeTime(text2) {
31938
- const value = text2.match(/^\s*<timestamp>([^<]+)<\/timestamp>/)?.[1];
31982
+ const value = cursorEnvelope(text2).timestamp;
31939
31983
  if (!value) return 0;
31940
31984
  const iso = cursorTime(value);
31941
31985
  if (iso) return iso;
@@ -31944,17 +31988,21 @@ function cursorEnvelopeTime(text2) {
31944
31988
  return cursorTime(Date.parse(`${match2[1]} ${match2[2]} GMT${match2[3]}${match2[4].padStart(2, "0")}${match2[5] || "00"}`));
31945
31989
  }
31946
31990
  function cursorUserText(text2) {
31947
- let value = text2.trim().replace(/^<timestamp>[^<]+<\/timestamp>\s*/, "");
31948
- for (; ; ) {
31949
- const stripped = value.replace(/^<(user_info|environment_context|system_reminder)>[\s\S]*?<\/\1>\s*/, "");
31950
- if (stripped === value) break;
31951
- value = stripped;
31952
- }
31991
+ const value = cursorEnvelope(text2).text;
31953
31992
  const query = value.match(/^<user_query>([\s\S]*?)<\/user_query>(?:\s*<system_reminder>[\s\S]*?<\/system_reminder>)*\s*$/);
31954
31993
  return (query ? query[1] : value).trim();
31955
31994
  }
31956
31995
  function cursorMessage(raw, fallbackID) {
31957
31996
  if (!raw || typeof raw !== "object") return;
31997
+ if (raw.type === "turn_ended") {
31998
+ const message2 = blankMessage(typeof raw.id === "string" && raw.id.length <= 512 ? raw.id : fallbackID, cursorTime(raw.timestamp), "system");
31999
+ const failed = raw.status === "error" || raw.status === "failed";
32000
+ message2.events = [eventFor(message2, "turn-ended", failed ? "error" : "event", failed ? "Cursor turn failed" : "Cursor turn ended", eventText(raw.error), {
32001
+ nativeType: "turn_ended",
32002
+ status: failed ? "failed" : raw.status === "completed" || raw.status === "success" ? "completed" : "unknown"
32003
+ })];
32004
+ return message2;
32005
+ }
31958
32006
  const body2 = raw.message && typeof raw.message === "object" ? raw.message : raw;
31959
32007
  const role = raw.role || body2.role;
31960
32008
  if (!["user", "assistant", "tool", "system"].includes(role)) return;
@@ -31963,7 +32011,7 @@ function cursorMessage(raw, fallbackID) {
31963
32011
  const time4 = cursorTime(raw.timestamp) || cursorTime(body2.timestamp) || cursorTime(body2.createdAt) || (role === "user" && typeof firstText === "string" ? cursorEnvelopeTime(firstText) : 0);
31964
32012
  const native = [raw.uuid, raw.id, body2.uuid, body2.id].find((id2) => typeof id2 === "string" && id2.length && id2.length <= 512);
31965
32013
  const msg = blankMessage(native || fallbackID, time4, role);
31966
- msg.events = role === "tool" ? [eventFor(msg, "result", "tool_result", body2.name || "Tool result", "", { callID: body2.tool_call_id, output: eventText(content, 64e3), status: "unknown" })] : blockEvents(msg, content);
32014
+ msg.events = role === "tool" ? [eventFor(msg, "result", "tool_result", body2.name || "Tool result", "", { callID: body2.tool_call_id, output: eventText(content, 64e3), status: "unknown" })] : role === "user" ? userBlockEvents(msg, content, cursorUserText) : blockEvents(msg, content);
31967
32015
  const kind = role === "user" ? "You" : role === "assistant" ? "Assistant" : "Tool";
31968
32016
  const text2 = (value) => addText(msg, role === "user" && typeof value === "string" ? cursorUserText(value) : value, kind);
31969
32017
  if (typeof content === "string") text2(content);
@@ -32186,7 +32234,7 @@ function discoverComposers(path, workspace = "") {
32186
32234
  for (const table of ["cursorDiskKV", "ItemTable"]) {
32187
32235
  if (!hasTable(db2, table)) continue;
32188
32236
  let failed = 0, count = 0;
32189
- const rows2 = db2.prepare(`SELECT key, CASE WHEN length(value)<=? THEN value END AS value FROM ${table} WHERE key LIKE 'composerData:%' ORDER BY key LIMIT 20001`).iterate(MAX_VALUE2);
32237
+ const rows2 = db2.prepare(`SELECT key, CASE WHEN length(value)<=? THEN value END AS value FROM ${table} WHERE key LIKE 'composerData:%' AND value IS NOT NULL ORDER BY key LIMIT 20001`).iterate(MAX_VALUE2);
32190
32238
  for (const row of rows2) {
32191
32239
  if (++count > 2e4) {
32192
32240
  warnings.push("Cursor Composer listing reached its 20,000-session limit.");
@@ -32207,7 +32255,7 @@ function discoverComposers(path, workspace = "") {
32207
32255
  session.model = text(data.modelConfig?.modelName) || "Unknown model";
32208
32256
  session.archived = data.isArchived === true;
32209
32257
  const children = Array.isArray(data.subagentComposerIds) ? data.subagentComposerIds.filter((id2) => typeof id2 === "string") : [];
32210
- sessions.push({ session, revision: digest([1, snapshot2, table, nativeID]), locator: { path, kind: "composer", table, snapshot: snapshot2, nativeID, children: JSON.stringify(children) } });
32258
+ sessions.push({ session, revision: digest([2, snapshot2, table, nativeID]), locator: { path, kind: "composer", table, snapshot: snapshot2, nativeID, children: JSON.stringify(children) } });
32211
32259
  } catch {
32212
32260
  failed++;
32213
32261
  }
@@ -32445,7 +32493,7 @@ function createCursorAdapter(options = {}) {
32445
32493
  session.projectID = project("cursor", session.directory).id;
32446
32494
  if (session.directory) delete locator.directoryNote;
32447
32495
  }
32448
- const candidate = { session, locator, revision: digest([4, kind, path, before, session.created, session.directory, session.parentID]) };
32496
+ const candidate = { session, locator, revision: digest([5, kind, path, before, session.created, session.directory, session.parentID]) };
32449
32497
  if (!previous || rank(candidate) > rank(previous) || rank(candidate) === rank(previous) && session.updated > previous.session.updated) found.set(session.id, candidate);
32450
32498
  } catch {
32451
32499
  unreadable++;
@@ -32525,7 +32573,7 @@ function createCursorAdapter(options = {}) {
32525
32573
  const messages = page.rows.flatMap((row) => {
32526
32574
  const message2 = cursorMessage(row.value, `offset:${row.offset}`);
32527
32575
  if (!message2) page.partial = true;
32528
- return message2 && message2.role !== "system" ? [message2] : [];
32576
+ return message2 && (message2.role !== "system" || row.value?.type === "turn_ended") ? [message2] : [];
32529
32577
  });
32530
32578
  await verify();
32531
32579
  if (!offset && page.cursor === void 0 && !messages.length) throw new Error("Cursor transcript has no readable conversation. Previous imports are retained.");
@@ -33205,7 +33253,14 @@ var fileHarnessAdapters = definitions.map((source) => localFileAdapter({
33205
33253
  // server/adapters/harness-databases.ts
33206
33254
  import { lstat as lstat6, readFile as readFile4 } from "node:fs/promises";
33207
33255
  import { isAbsolute as isAbsolute5, join as join22 } from "node:path";
33208
- var parsedContent = (v3) => typeof v3 === "string" && /^[\[{]/.test(v3.trim()) ? optionalJSON(v3) : v3;
33256
+ function hermesContent(value) {
33257
+ if (typeof value !== "string" || !value.startsWith("\0json:")) return value;
33258
+ try {
33259
+ return JSON.parse(value.slice(6));
33260
+ } catch {
33261
+ return value;
33262
+ }
33263
+ }
33209
33264
  var millisOrSeconds = (v3) => typeof v3 === "number" && v3 > 0 && v3 < 1e10 ? seconds(v3) : time(v3);
33210
33265
  function dbPaths(id2, defaults, match2) {
33211
33266
  return async () => {
@@ -33225,6 +33280,7 @@ function sessionHistory(r, messages, note) {
33225
33280
  var hermes = {
33226
33281
  id: "hermes",
33227
33282
  name: "Hermes Agent",
33283
+ version: 3,
33228
33284
  paths: async () => (await historyFiles(harnessRoots("hermes", () => [envHome("HERMES_HOME", ".hermes")])(), (p) => p === "state.db" || /^profiles\/[^/]+\/state\.db$/.test(p))).files,
33229
33285
  table: "sessions",
33230
33286
  key: "id",
@@ -33232,7 +33288,7 @@ var hermes = {
33232
33288
  parse(db2, r) {
33233
33289
  const messages = rows(db2, "messages", ["id", "message_uid", "role", "content", "timestamp", "tool_call_id", "tool_calls", "tool_name", "_compressed_summary"], ["session_id", r.id], "id").map((m) => {
33234
33290
  if (m._compressed_summary) return recordEvent(m, text(m.message_uid) || nativeText(m.id), "Context summary", seconds(m.timestamp), m.content);
33235
- return conversationMessage({ role: m.role, content: parsedContent(m.content), timestamp: seconds(m.timestamp), tool_call_id: m.tool_call_id, toolCalls: optionalJSON(m.tool_calls), toolName: m.tool_name }, text(m.message_uid) || nativeText(m.id));
33291
+ return conversationMessage({ role: m.role, content: hermesContent(m.content), timestamp: seconds(m.timestamp), tool_call_id: m.tool_call_id, toolCalls: optionalJSON(m.tool_calls), toolName: m.tool_name }, text(m.message_uid) || nativeText(m.id));
33236
33292
  });
33237
33293
  const h3 = sessionHistory({ ...r, created_at: seconds(r.started_at), updated_at: seconds(r.last_activity_at), provider: r.billing_provider }, messages, "Hermes saved message rows, including retained summaries. Compression/reset parent links are not subagent ancestry. Session usage aggregates are not used as message times.");
33238
33294
  if (r.source === "subagent") h3.parent = text(r.parent_session_id) || void 0;
@@ -33773,10 +33829,13 @@ function normalizeViewState(value) {
33773
33829
  function visibleSessions(sessions) {
33774
33830
  const owners = /* @__PURE__ */ new Map();
33775
33831
  for (const session of sessions) {
33776
- if (session.source !== "t3-code" || session.coverage?.history !== "complete" || !session.activity?.userMessages) continue;
33777
- for (const id2 of session.linkedSessionIDs || []) owners.set(id2, [...owners.get(id2) || [], session.id]);
33832
+ if (session.source !== "t3-code") continue;
33833
+ for (const id2 of new Set(session.linkedSessionIDs || [])) owners.set(id2, [...owners.get(id2) || [], session]);
33778
33834
  }
33779
- const unique = new Map([...owners].flatMap(([native, ids]) => ids.length === 1 ? [[native, ids[0]]] : []));
33835
+ const unique = new Map([...owners].flatMap(([native, claims]) => {
33836
+ const owner = claims[0];
33837
+ return claims.length === 1 && ["complete", "partial"].includes(owner.coverage?.history || "") && owner.activity?.userMessages ? [[native, owner.id]] : [];
33838
+ }));
33780
33839
  return sessions.filter((session) => !unique.has(session.id)).map((session) => ({
33781
33840
  ...session,
33782
33841
  parentID: session.parentID ? unique.get(session.parentID) || session.parentID : void 0,
@@ -34292,6 +34351,7 @@ var Importer = class {
34292
34351
  } while (cursor);
34293
34352
  const values = [...messages.values()];
34294
34353
  if (adapter.id === "opencode") values.reverse();
34354
+ if (saved?.activity?.userMessages && values.every((message2) => message2.role === "system")) throw new Error("Source has no readable conversation. Previous imports are retained.");
34295
34355
  this.store.replace(candidate, values, partial, note);
34296
34356
  this.status.imported++;
34297
34357
  } catch (error) {
package/docs/guide.md CHANGED
@@ -86,7 +86,7 @@ Onboarding closes automatically after a successful import and library refresh. I
86
86
  | OpenCode | Official authenticated local service discovery and V2 GET API | Explicit forks and child IDs; authoritative snapshot paths where available. OpenCode must be running for an import, but not to browse saved data. Remote endpoints are rejected. |
87
87
  | Claude Code | SDK conversation-chain parsing with read-only local transcript discovery; legacy `~/.claude/transcripts/` envelopes | CLI and VS Code extension sessions, including IDE-prefixed prompts omitted by the SDK listing. Project transcripts take precedence over overlapping legacy exports. Preserves recorded message times and explicit subagent metadata. SDK-visible history can omit pre-compaction text. No inferred fork ancestry. File evidence requires a successful matching edit-tool result. |
88
88
  | Codex | Bounded streaming reads of active/archived JSONL, zstd/gzip archives, and suffixed rollout copies | Native session IDs deduplicate copies; active uncompressed rollouts take precedence. Explicit recorded fork/parent fields; completed file-change events. Mirrored event text is not imported twice. Store-only/cloud-only history and ordinary ChatGPT desktop/web chats are not imported. |
89
- | T3 Code | Private read-only snapshot of the local server's `~/.t3/userdata/statev2.sqlite`; legacy `state.sqlite` fallback | T3 app threads retain their own titles, messages, ordered activity, recorded forks/children, and worktree paths. Strong recorded provider-thread IDs link overlapping Codex, Claude Code, and OpenCode imports; when the T3 conversation is complete, a uniquely linked provider session is shown through its T3 thread instead of appearing twice. Legacy V1 provides partial text history. Attachments and checkpoint file snapshots are omitted. |
89
+ | T3 Code | Private read-only snapshot of the local server's `~/.t3/userdata/statev2.sqlite`; legacy `state.sqlite` fallback | T3 app threads retain their own titles, messages, ordered activity, recorded forks/children, and worktree paths. Strong recorded provider-thread IDs group uniquely linked Codex, Claude Code, and OpenCode histories under one T3 map entry once user messages are imported, including partial histories. The inspector opens each linked provider's saved messages separately. Empty, pending, or ambiguous bindings retain separate entries. Legacy V1 provides partial text history. Attachments and checkpoint file snapshots are omitted. |
90
90
  | Cursor | IDE JSONL transcripts, CLI/ACP stores, and legacy Composer `state.vscdb` databases in application `User/globalStorage` and `User/workspaceStorage` | Inline conversations, conversation maps, and separate bubble records preserve native creation dates. Modern representations take precedence while retaining Composer's original start date. Missing bubble times stay unknown. Older `.txt` transcripts, cloud-only and SDK-only history are excluded. |
91
91
  | Gemini CLI | `~/.gemini/tmp/*/chats/` JSON/JSONL; sandbox cache equivalent | Reconstructs append-only patches and rewinds. Explicit subagent directories form parent links. Workspace identity comes from `.project_root`; unknown directories stay unknown. |
92
92
  | Qwen Code | `~/.qwen/projects/*/chats/*.jsonl` | Recorded forks and parent sessions remain distinct. Tool results retain call IDs and recorded execution status. Daemon-only histories are excluded. |
@@ -122,6 +122,7 @@ These file adapters read stable snapshots bounded to 32 MB combined, 50,000 reco
122
122
 
123
123
  - Select **Cursor** in **Manage sources**, then import. Cursor need not be running. This is a local-format adapter, not a supported Cursor history-export API; the [Cursor SDK](https://cursor.com/docs/sdk/typescript) documents its own local agent store.
124
124
  - IDE exports are marked partial because tool results and pre-compaction context may be absent. Recorded message IDs are preserved; otherwise stable byte offsets or ordered blob occurrences retain repeated identical turns. Images and unsupported content are disclosed as omitted. A broken primary store never downgrades saved history to a shorter transcript export.
125
+ - Titles and human message text skip known leading context envelopes, including attached files, web results, and image scaffolding. Literal markup inside a user query is preserved. Native turn-end/error records remain source events even when no conversation started; lifecycle-only exports never erase a previously saved conversation. NULL Composer marker rows are ignored; genuinely oversized payloads still respect import bounds.
125
126
  - Only recorded message timestamps and Cursor's leading timezone-qualified timestamp envelope place message dots. Missing timestamps remain unknown. When session creation is unavailable, placement uses the first recorded message or the file timestamp, with a coverage note.
126
127
  - Working directories come from recorded metadata or an unambiguous forward match against Cursor's workspace folder metadata. Encoded project names are never reverse-decoded into guessed paths. Choose a folder in the launcher when the original directory is unknown.
127
128
  - Store reads copy the database and its WAL into a temporary private directory, verify that the source stayed stable, and open only the copy with read-only SQLite. CLI/ACP limits: 20,000 histories, 256 MB per database/WAL, 2 MB per blob, and 64 MB / 50,000 nodes / 16 million text characters per conversation. Legacy Composer permits an 8 GB database/WAL, 32 MB Composer record, 8 MB bubble, and 64 MB / 50,000 bubbles per conversation. At most two legacy/database snapshots are cached; copies are removed on eviction or process exit. Changing or unsupported stores preserve previously saved history.
@@ -16,7 +16,7 @@ Paths below use `~` for the user's home. XDG data/config locations respect their
16
16
  | `kimchi` / Kimchi | `~/.config/kimchi/harness/sessions/` | Pi-format entries. |
17
17
  | `gajae` / Gajae-Code | `~/.gjc/agent/sessions/`, XDG `gjc/sessions/` | Pi-format entries. |
18
18
  | `openclaw` / OpenClaw | `~/.openclaw/agents/*/{sessions/,agent/openclaw-agent.sqlite}`; `.clawdbot`, `.moltbot`, `.moldbot` equivalents | SQLite transcript events take precedence over overlapping JSONL/zstd exports. Rollover and event-parent links do not imply ancestry. Non-message SQLite events are currently omitted. |
19
- | `hermes` / Hermes Agent | `~/.hermes/state.db`, `profiles/*/state.db` | Native messages and retained summaries. Only `source=subagent` establishes a child link; `_branched_from` establishes a fork. Compression/reset parents are not ancestry. |
19
+ | `hermes` / Hermes Agent | `~/.hermes/state.db`, `profiles/*/state.db` | Native messages and retained summaries. Structured content uses Hermes's explicit NUL + `json:` marker; ordinary JSON-looking text stays text. Only `source=subagent` establishes a child link; `_branched_from` establishes a fork. Compression/reset parents are not ancestry. |
20
20
  | `amp` / Amp | XDG `amp/threads/`, Tokscale `amp-cache/threads/` | Local/exported thread messages. No sync is invoked. Usage-ledger times are not assigned to prompts. |
21
21
  | `droid` / Factory Droid | `~/.factory/sessions/` | Saved conversation envelopes; excludes usage apportionment. |
22
22
  | `codebuff`, `freebuff` / Codebuff, Freebuff | XDG config `manicode`, `manicode-dev`, `manicode-staging` chat messages | A positive `base2-free` root-agent marker assigns Freebuff; shared storage is not imported into both sources. No text-based token estimates. |
@@ -71,4 +71,4 @@ File imports are bounded to 32 MB combined expanded data and 50,000 messages. SQ
71
71
 
72
72
  Missing message timestamps remain unknown. Native dates place database sessions; undated database histories are skipped with a warning. File histories can fall back to file dates and disclose this. Unsupported message blocks, binary attachments, missing tools, and absent snapshots remain partial. Token counts are never estimated from text; usage aggregates are not converted into conversations. No new harness is enabled automatically, and continuing a session remains an explicit user action through supported launch destinations.
73
73
 
74
- Fixture tests cover each parser family, registry/display-name consistency, duplicate representations, compressed archives, legacy Cursor bubbles, immutable DB/WAL reads, source changes, partial events, metadata-only sources, and saved-history retention. Native writers inspected in addition to Tokscale include Hermes, Goose, Zed, Octofriend, Mux, and Unsloth.
74
+ Fixture tests cover each parser family, registry/display-name consistency, duplicate representations, compressed archives, legacy Cursor bubbles, immutable DB/WAL reads, source changes, partial events, metadata-only sources, and saved-history retention. Native writers inspected in addition to Tokscale include Hermes, Goose, Zed, Octofriend, Mux, and Unsloth. See [the importer comparison](importer-comparison.md) for the title, content-decoding, and cross-source identity decisions informed by CASS and Agent Sessions.
@@ -0,0 +1,48 @@
1
+ # History importer comparison
2
+
3
+ Reviewed November 6, 2026. These are source-code comparisons, not claims that another project's entire importer is correct. References are pinned so later upstream changes do not alter the evidence.
4
+
5
+ ## CASS / Franken Agent Detection
6
+
7
+ [CASS](https://github.com/Dicklesworthstone/coding_agent_session_search/tree/298f51895585ab086d8b129b9a475a3b26609407) delegates its core connectors to [Franken Agent Detection at `6b337ba`](https://github.com/Dicklesworthstone/franken_agent_detection/tree/6b337ba434b72c65c6c5a748b7ec47885f840ac0), pinned in CASS's Cargo manifest.
8
+
9
+ - Its [Codex connector](https://github.com/Dicklesworthstone/franken_agent_detection/blob/6b337ba434b72c65c6c5a748b7ec47885f840ac0/src/connectors/codex.rs#L987-L1004) skips injected-context user records when deriving a title. It also tests mirrored `event_msg` / `response_item` prompts so they do not become duplicate messages.
10
+ - Its [Cursor connector](https://github.com/Dicklesworthstone/franken_agent_detection/blob/6b337ba434b72c65c6c5a748b7ec47885f840ac0/src/connectors/cursor.rs#L495-L504) excludes NULL-valued Composer marker rows explicitly. A marker is not a corrupt conversation. It deduplicates native session IDs across database representations.
11
+ - Its [Hermes connector](https://github.com/Dicklesworthstone/franken_agent_detection/blob/6b337ba434b72c65c6c5a748b7ec47885f840ac0/src/connectors/hermes.rs#L246-L284) reads message content as text rather than guessing JSON from punctuation.
12
+
13
+ **Applied here:** source-specific title normalization, NULL-marker filtering, and native-identity deduplication. Our raw histories remain separate from the map's grouping, and unchanged parser revisions are invalidated when decoding changes.
14
+
15
+ ## Agent Sessions
16
+
17
+ [Agent Sessions at `555fbfd`](https://github.com/jazzyalex/agent-sessions/tree/555fbfddaa286b63cdef2ef13db88cb9cf320d87) is a comparable local history browser.
18
+
19
+ - Its [title selection](https://github.com/jazzyalex/agent-sessions/blob/555fbfddaa286b63cdef2ef13db88cb9cf320d87/AgentSessions/Model/Session.swift#L666-L740) prioritizes custom titles and filters harness preambles before falling back to other text.
20
+ - Its [Cursor parser](https://github.com/jazzyalex/agent-sessions/blob/555fbfddaa286b63cdef2ef13db88cb9cf320d87/AgentSessions/Services/CursorSessionParser.swift#L48-L58) recognizes error-only `turn_ended` records. Its user-query tag removal does not cover every attachment/web-context envelope encountered in our audit.
21
+ - Some of its preamble checks search for phrases anywhere in a message. Those heuristics can also match a legitimate request quoting a prompt or XML example.
22
+
23
+ **Applied here:** retain native Codex names before prompt fallbacks, preserve Cursor lifecycle errors, and normalize only recognized leading context. Strip context before payload truncation so a long injected preamble cannot consume the real prompt's entire budget. Keep literal markup inside user queries intact. Context-only blocks remain source events rather than user-message dots.
24
+
25
+ ## Hermes's native writer is the content-format authority
26
+
27
+ Hermes [encodes and decodes structured content](https://github.com/NousResearch/hermes-agent/blob/90d6b98fd86d20981ee06ddd5b7d93e4320f26a4/hermes_state_messages.py#L139-L169) using a reserved NUL + `json:` prefix. Ordinary strings are unchanged, even if they are valid JSON. Literal strings starting with the reserved prefix are JSON-string-escaped. Malformed marked content falls back to its original text.
28
+
29
+ **Applied here:** follow that contract exactly. Do not parse `[IMPORTANT: ...]`, JSON followed by prose, or a literal JSON example as structured conversation blocks. This fixes whole-session rejection without discarding the offending message. Empty native sessions are reported separately from unreadable histories.
30
+
31
+ ## Tokscale
32
+
33
+ [Tokscale at `82613d2`](https://github.com/junhoyeo/tokscale/tree/82613d2f5e96654ce3729892afbb0025979f1c75) remains useful for format discovery, native IDs, and archived rollout coverage. Its [Codex parser](https://github.com/junhoyeo/tokscale/blob/82613d2f5e96654ce3729892afbb0025979f1c75/crates/tokscale-core/src/sessions/codex.rs) derives deduplication identity from in-file session metadata. Its [Hermes parser](https://github.com/junhoyeo/tokscale/blob/82613d2f5e96654ce3729892afbb0025979f1c75/crates/tokscale-core/src/sessions/hermes.rs#L1-L19) primarily reconstructs usage from session aggregates and logged API calls.
34
+
35
+ **Boundary:** usage aggregates and billing deduplication are not conversation reconstruction. SessionGraph imports recorded messages and times rather than manufacturing turns or allocating aggregate usage to prompts.
36
+
37
+ ## T3 / provider overlap
38
+
39
+ The inspected connectors do not establish a reusable T3-to-provider ownership rule. SessionGraph uses T3's explicit, strong provider bindings. Matching titles, timestamps, or similar messages never establish identity.
40
+
41
+ - A uniquely bound T3 thread with imported user messages occupies one map entry, even when attachment or payload omissions make it partial.
42
+ - The inspector offers the separately saved provider history. Grouping does not overwrite, append, or merge the two transcripts, and partial coverage remains visible.
43
+ - Empty or pending T3 histories do not hide native sessions. All binding claimants count when checking ambiguity, including pending or partial ones.
44
+ - Snapshot changes during T3 discovery get up to three fresh-copy attempts. Only the consistency-race error is retried; schema errors still surface. Paged reads remain pinned to one verified snapshot.
45
+
46
+ ## Remaining format boundaries
47
+
48
+ Attachments and checkpoint snapshots are still not imported by T3. Cursor Composer values above the existing 32 MB limit are still bounded and reported; NULL markers are excluded from that warning. Native histories that are genuinely empty cannot supply conversation messages. Live validation covers installed sources; fixture tests cover parser families for unavailable harnesses.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sessiongraph",
3
- "version": "1.0.12",
3
+ "version": "1.0.13",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -25,11 +25,11 @@
25
25
  "README.md"
26
26
  ],
27
27
  "optionalDependencies": {
28
- "sessiongraph-app-darwin-arm64": "1.0.12",
29
- "sessiongraph-app-darwin-x64": "1.0.12",
30
- "sessiongraph-app-linux-arm64": "1.0.12",
31
- "sessiongraph-app-linux-x64": "1.0.12",
32
- "sessiongraph-app-win32-x64": "1.0.12"
28
+ "sessiongraph-app-darwin-arm64": "1.0.13",
29
+ "sessiongraph-app-darwin-x64": "1.0.13",
30
+ "sessiongraph-app-linux-arm64": "1.0.13",
31
+ "sessiongraph-app-linux-x64": "1.0.13",
32
+ "sessiongraph-app-win32-x64": "1.0.13"
33
33
  },
34
34
  "type": "module",
35
35
  "engines": {
@@ -75,5 +75,5 @@
75
75
  "vite": "^7.2.0"
76
76
  },
77
77
  "packageManager": "pnpm@11.10.0",
78
- "sessionGraphCommit": "d99e40d05031062b93e980d62c5fd68e296d7e2c"
78
+ "sessionGraphCommit": "d00c1acc83ab582debcd7ef1316d56d47cc53575"
79
79
  }