sessiongraph-app-darwin-arm64 1.0.21 → 1.0.23

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.
@@ -679,6 +679,17 @@ var init_library_query = __esm({
679
679
  }
680
680
  });
681
681
 
682
+ // server/sqlite.ts
683
+ function iterate(db2, sql, ...values) {
684
+ const statement = db2.prepare(sql);
685
+ return Object.assign(statement.iterate(...values), { retainedStatement: statement });
686
+ }
687
+ var init_sqlite = __esm({
688
+ "server/sqlite.ts"() {
689
+ "use strict";
690
+ }
691
+ });
692
+
682
693
  // server/commit-store.ts
683
694
  function writeCommits(db2, session) {
684
695
  db2.prepare("DELETE FROM session_commits WHERE session_id=?").run(session.id);
@@ -686,7 +697,7 @@ function writeCommits(db2, session) {
686
697
  if (!supported.has(session.source || "")) return { ...base, state: "unavailable", count: null, note: "Commit history unavailable for this source." };
687
698
  const calls = /* @__PURE__ */ new Map();
688
699
  const results = /* @__PURE__ */ new Map();
689
- const rows2 = () => db2.prepare("SELECT data FROM timeline_items WHERE session_id=? AND kind IN ('tool_call','tool_result') ORDER BY ordinal").iterate(session.id);
700
+ const rows2 = () => iterate(db2, "SELECT data FROM timeline_items WHERE session_id=? AND kind IN ('tool_call','tool_result') ORDER BY ordinal", session.id);
690
701
  let tools = 0, partial2 = session.coverage?.history !== "complete" || Boolean(db2.prepare("SELECT partial FROM timeline_coverage WHERE session_id=?").get(session.id)?.partial);
691
702
  for (const row of rows2()) {
692
703
  const item = JSON.parse(String(row.data));
@@ -767,6 +778,7 @@ var init_commit_store = __esm({
767
778
  init_commits();
768
779
  init_commit_extraction();
769
780
  init_library_query();
781
+ init_sqlite();
770
782
  COMMIT_SCHEMA = `CREATE TABLE IF NOT EXISTS session_commits (
771
783
  session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
772
784
  sha TEXT NOT NULL, repository_path TEXT NOT NULL, operation TEXT NOT NULL,
@@ -1095,12 +1107,12 @@ function summarizeUsage(session, messages, historyPartial) {
1095
1107
  const lastSnapshot = cumulative.at(-1);
1096
1108
  if (lastSnapshot?.usage) return sessionUsage(lastSnapshot.usage, true);
1097
1109
  const unique = /* @__PURE__ */ new Map();
1098
- let missing = 0;
1110
+ let missing2 = 0;
1099
1111
  for (const message2 of messages) {
1100
1112
  if (message2.usage?.scope === "message") {
1101
1113
  const key = message2.usage.id || message2.id, previous = unique.get(key);
1102
1114
  unique.set(key, previous ? mergeUsage(previous, message2.usage) : message2.usage);
1103
- } else if (message2.role === "assistant") missing++;
1115
+ } else if (message2.role === "assistant") missing2++;
1104
1116
  }
1105
1117
  const records = [...unique.values()], known = records.filter((value) => value.total !== null);
1106
1118
  if (!known.length && native) return { ...native, partial: true };
@@ -1114,8 +1126,8 @@ function summarizeUsage(session, messages, historyPartial) {
1114
1126
  costEstimated: totals.cost !== null ? totals.costEstimated : native?.cost != null ? native.costEstimated : void 0,
1115
1127
  source: records.length ? "messages" : "unavailable",
1116
1128
  reportedMessages: known.length,
1117
- missingMessages: missing + records.length - known.length,
1118
- partial: historyPartial || total === null || missing > 0 || known.length !== records.length || !records.length
1129
+ missingMessages: missing2 + records.length - known.length,
1130
+ partial: historyPartial || total === null || missing2 > 0 || known.length !== records.length || !records.length
1119
1131
  };
1120
1132
  }
1121
1133
  var IMPORT_METADATA_VERSION, object2, string2, tokenCount, recordedCost, fields;
@@ -24284,18 +24296,18 @@ var init_opencode_events = __esm({
24284
24296
 
24285
24297
  // server/adapters/harness-paths.ts
24286
24298
  import { homedir as homedir3 } from "node:os";
24287
- import { join as join2 } from "node:path";
24299
+ import { join as join3 } from "node:path";
24288
24300
  var homePath, dataPath, configPath, appPath, tokscalePath, envHome, harnessRoots;
24289
24301
  var init_harness_paths = __esm({
24290
24302
  "server/adapters/harness-paths.ts"() {
24291
24303
  "use strict";
24292
24304
  init_source_paths();
24293
- homePath = (...parts) => join2(homedir3(), ...parts);
24294
- dataPath = (...parts) => join2(process.env.XDG_DATA_HOME || homePath(".local/share"), ...parts);
24295
- configPath = (...parts) => join2(process.env.XDG_CONFIG_HOME || homePath(".config"), ...parts);
24296
- appPath = (...parts) => join2(process.platform === "darwin" ? homePath("Library/Application Support") : process.platform === "win32" ? process.env.APPDATA || homePath("AppData/Roaming") : process.env.XDG_CONFIG_HOME || homePath(".config"), ...parts);
24297
- tokscalePath = (...parts) => join2(process.env.TOKSCALE_CONFIG_DIR || (process.platform === "win32" ? appPath("tokscale") : configPath("tokscale")), ...parts);
24298
- envHome = (env2, fallback, ...parts) => join2(process.env[env2]?.trim() || homePath(fallback), ...parts);
24305
+ homePath = (...parts) => join3(homedir3(), ...parts);
24306
+ dataPath = (...parts) => join3(process.env.XDG_DATA_HOME || homePath(".local/share"), ...parts);
24307
+ configPath = (...parts) => join3(process.env.XDG_CONFIG_HOME || homePath(".config"), ...parts);
24308
+ appPath = (...parts) => join3(process.platform === "darwin" ? homePath("Library/Application Support") : process.platform === "win32" ? process.env.APPDATA || homePath("AppData/Roaming") : process.env.XDG_CONFIG_HOME || homePath(".config"), ...parts);
24309
+ tokscalePath = (...parts) => join3(process.env.TOKSCALE_CONFIG_DIR || (process.platform === "win32" ? appPath("tokscale") : configPath("tokscale")), ...parts);
24310
+ envHome = (env2, fallback, ...parts) => join3(process.env[env2]?.trim() || homePath(fallback), ...parts);
24299
24311
  harnessRoots = (id3, defaults) => () => {
24300
24312
  const override = sourcePath(id3) || process.env[`SESSIONGRAPH_${id3.replace(/-/g, "_").toUpperCase()}_HISTORY_DIR`]?.trim();
24301
24313
  return override ? [override] : defaults();
@@ -24318,9 +24330,9 @@ var init_compressed = __esm({
24318
24330
  });
24319
24331
 
24320
24332
  // server/adapters/local-files.ts
24321
- import { constants } from "node:fs";
24333
+ import { constants as constants2 } from "node:fs";
24322
24334
  import { lstat, open as open2, readdir } from "node:fs/promises";
24323
- import { join as join3, relative as relative2 } from "node:path";
24335
+ import { join as join4, relative as relative2 } from "node:path";
24324
24336
  async function fileState(path) {
24325
24337
  try {
24326
24338
  const s = await lstat(path);
@@ -24357,7 +24369,7 @@ async function historyFiles(roots2, match2) {
24357
24369
  limited = true;
24358
24370
  break;
24359
24371
  }
24360
- const file2 = join3(path, entry.name);
24372
+ const file2 = join4(path, entry.name);
24361
24373
  if (entry.isDirectory()) {
24362
24374
  if (depth < 6 && queue.length < MAX_FILES) queue.push({ root: root2, path: file2, depth: depth + 1 });
24363
24375
  else limited = true;
@@ -24401,7 +24413,7 @@ function localFileAdapter(source) {
24401
24413
  const files = /* @__PURE__ */ new Map();
24402
24414
  let expanded = 0;
24403
24415
  for (const s of before.filter((s2) => s2.signature !== "missing")) {
24404
- const handle = await open2(s.path, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
24416
+ const handle = await open2(s.path, constants2.O_RDONLY | (constants2.O_NOFOLLOW || 0));
24405
24417
  try {
24406
24418
  const buffer = Buffer.alloc(s.size + 1);
24407
24419
  let bytes2 = 0;
@@ -24524,14 +24536,14 @@ var init_local_files = __esm({
24524
24536
 
24525
24537
  // server/adapters/sqlite-snapshot.ts
24526
24538
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
24527
- import { chmodSync as chmodSync2, constants as constants2, copyFileSync, lstatSync, mkdtempSync, rmSync } from "node:fs";
24539
+ import { chmodSync as chmodSync2, constants as constants3, copyFileSync, lstatSync as lstatSync2, mkdtempSync, rmSync } from "node:fs";
24528
24540
  import { copyFile, statfs } from "node:fs/promises";
24529
24541
  import { tmpdir } from "node:os";
24530
- import { join as join4 } from "node:path";
24542
+ import { join as join5 } from "node:path";
24531
24543
  function snapshotFiles(path, large) {
24532
24544
  return [path, `${path}-wal`].map((file2, i) => {
24533
24545
  try {
24534
- const s = lstatSync(file2);
24546
+ const s = lstatSync2(file2);
24535
24547
  const kind = i ? "History database WAL" : "History database";
24536
24548
  if (!s.isFile()) throw new SqliteSnapshotFileError(`${kind} is not a regular file.`);
24537
24549
  if (!large && s.size > 8e9) throw new SqliteSnapshotFileError(`${kind} exceeds 8 GB.`);
@@ -24567,15 +24579,15 @@ async function withLargeSqliteSnapshot(path, read2, expected) {
24567
24579
  }
24568
24580
  close(path);
24569
24581
  while (copies.size >= 2) close(copies.keys().next().value);
24570
- const directory3 = mkdtempSync(join4(tmpdir(), "sessiongraph-history-"));
24571
- const destination = join4(directory3, "history.db");
24582
+ const directory3 = mkdtempSync(join5(tmpdir(), "sessiongraph-history-"));
24583
+ const destination = join5(directory3, "history.db");
24572
24584
  let db2;
24573
24585
  try {
24574
24586
  for (const [index, suffix] of ["", "-wal"].entries()) {
24575
24587
  const file2 = files[index];
24576
24588
  if (!file2) continue;
24577
24589
  try {
24578
- await copyFile(path + suffix, destination + suffix, constants2.COPYFILE_FICLONE_FORCE);
24590
+ await copyFile(path + suffix, destination + suffix, constants3.COPYFILE_FICLONE_FORCE);
24579
24591
  } catch (error62) {
24580
24592
  if (!["ENOSYS", "ENOTSUP", "EOPNOTSUPP", "EXDEV", "EINVAL"].includes(error62.code || "")) throw error62;
24581
24593
  const { bavail, bsize } = await statfs(directory3);
@@ -24613,14 +24625,14 @@ function withSqliteSnapshot(path, read2, expected, pinned = false) {
24613
24625
  if (copy?.revision !== revision2) {
24614
24626
  close(path);
24615
24627
  while (copies.size >= 2) close(copies.keys().next().value);
24616
- const directory3 = mkdtempSync(join4(tmpdir(), "sessiongraph-history-"));
24628
+ const directory3 = mkdtempSync(join5(tmpdir(), "sessiongraph-history-"));
24617
24629
  let db2;
24618
24630
  try {
24619
24631
  chmodSync2(directory3, 448);
24620
- const destination = join4(directory3, "history.db");
24632
+ const destination = join5(directory3, "history.db");
24621
24633
  for (const suffix of ["", "-wal"]) {
24622
24634
  try {
24623
- copyFileSync(path + suffix, destination + suffix, constants2.COPYFILE_FICLONE);
24635
+ copyFileSync(path + suffix, destination + suffix, constants3.COPYFILE_FICLONE);
24624
24636
  chmodSync2(destination + suffix, 384);
24625
24637
  } catch (error62) {
24626
24638
  if (suffix && error62.code === "ENOENT") continue;
@@ -24704,14 +24716,18 @@ function rows(db2, table2, fields3, filter, order, limit = 5e4) {
24704
24716
  for (const name of [...fields3, ...filter ? [filter[0]] : [], ...order ? [order] : []]) if (!/^[a-zA-Z_][\w]*$/.test(name)) throw new Error("Invalid history column.");
24705
24717
  if (filter && !available.has(filter[0])) throw new Error("Unsupported history relation.");
24706
24718
  const size = (f) => `length(CAST("${f}" AS BLOB))`;
24707
- const select = fields3.map((f) => available.has(f) ? `CASE WHEN ${size(f)}<=32000000 THEN "${f}" END AS "${f}"` : `NULL AS "${f}"`).join(",");
24719
+ const select = fields3.map((f) => available.has(f) ? `CASE WHEN ${size(f)}<=32000000 THEN CASE WHEN typeof("${f}")='text' THEN CAST("${f}" AS BLOB) ELSE "${f}" END END AS "${f}", typeof("${f}")='text' AS "__sessiongraph_text_${f}"` : `NULL AS "${f}"`).join(",");
24708
24720
  const oversized = fields3.filter((f) => available.has(f)).map((f) => `COALESCE(${size(f)},0)>32000000`).join(" OR ") || "0";
24709
24721
  const query2 = `SELECT ${select}, (${oversized}) AS __sessiongraph_oversized FROM "${table2}"${filter ? ` WHERE "${filter[0]}"=?` : ""}${order && available.has(order) ? ` ORDER BY "${order}"` : ""} LIMIT ${limit + 1}`;
24710
24722
  const result = [];
24711
24723
  let bytes2 = 0;
24712
- for (const row of db2.prepare(query2).iterate(...filter ? [filter[1]] : [])) {
24724
+ for (const row of iterate(db2, query2, ...filter ? [filter[1]] : [])) {
24713
24725
  if (row.__sessiongraph_oversized) throw new Error("History field exceeds the 32 MB snapshot limit.");
24714
24726
  delete row.__sessiongraph_oversized;
24727
+ for (const field of fields3) {
24728
+ if (row[`__sessiongraph_text_${field}`] && row[field] instanceof Uint8Array) row[field] = Buffer.from(row[field]).toString("utf8");
24729
+ delete row[`__sessiongraph_text_${field}`];
24730
+ }
24715
24731
  const size2 = rowBytes(row);
24716
24732
  bytes2 += size2;
24717
24733
  consume(size2, 1);
@@ -24876,6 +24892,7 @@ var init_sqlite_histories = __esm({
24876
24892
  init_local_files();
24877
24893
  init_sqlite_snapshot();
24878
24894
  init_compressed();
24895
+ init_sqlite();
24879
24896
  rowBytes = (row) => Object.values(row).reduce((n, v3) => n + (typeof v3 === "string" ? Buffer.byteLength(v3) : v3 instanceof Uint8Array ? v3.byteLength : 8), 0);
24880
24897
  }
24881
24898
  });
@@ -24932,7 +24949,7 @@ var init_opencode_v1 = __esm({
24932
24949
 
24933
24950
  // server/adapters/opencode.ts
24934
24951
  import { lstat as lstat3, readdir as readdir2 } from "node:fs/promises";
24935
- import { join as join5 } from "node:path";
24952
+ import { join as join6 } from "node:path";
24936
24953
  function openCodeMessage(raw, sessionID) {
24937
24954
  const content = extractContent([raw]), detail = summarizeMessages(sessionID, [raw], null);
24938
24955
  const message2 = {
@@ -24962,7 +24979,7 @@ async function openCodeDatabases() {
24962
24979
  if (files.length > 20) throw new Error("Too many OpenCode databases. Choose a database file with a source path override.");
24963
24980
  const paths2 = [];
24964
24981
  for (const file2 of files) {
24965
- const path = join5(root2, file2);
24982
+ const path = join6(root2, file2);
24966
24983
  if ((await lstat3(path)).isFile()) paths2.push(path);
24967
24984
  }
24968
24985
  return paths2;
@@ -24995,7 +25012,7 @@ function historyRevisions(db2, schema) {
24995
25012
  const names = columns(db2, table2);
24996
25013
  if (!names.has("session_id")) continue;
24997
25014
  const updated = names.has("time_updated") ? "MAX(time_updated)" : "NULL";
24998
- for (const row of db2.prepare(`SELECT session_id, COUNT(*) AS count, ${updated} AS updated FROM "${table2}" GROUP BY session_id`).iterate()) {
25015
+ for (const row of iterate(db2, `SELECT session_id, COUNT(*) AS count, ${updated} AS updated FROM "${table2}" GROUP BY session_id`)) {
24999
25016
  const id3 = text3(row.session_id);
25000
25017
  result.set(id3, [...result.get(id3) || [], row.count, row.updated]);
25001
25018
  }
@@ -25084,7 +25101,7 @@ function discoverDatabase(db2, path, snapshot2) {
25084
25101
  }
25085
25102
  function payloadRows(db2, query2, values, budget2) {
25086
25103
  const result = [];
25087
- for (const row of db2.prepare(query2).iterate(...values)) {
25104
+ for (const row of iterate(db2, query2, ...values)) {
25088
25105
  if (typeof row.data !== "string") throw new Error("OpenCode history contains a missing or oversized JSON field (4 MB limit).");
25089
25106
  budget2.bytes += Buffer.byteLength(row.data);
25090
25107
  budget2.records++;
@@ -25108,6 +25125,7 @@ var init_opencode2 = __esm({
25108
25125
  init_sqlite_snapshot();
25109
25126
  init_local_files();
25110
25127
  init_opencode_v1();
25128
+ init_sqlite();
25111
25129
  PAGE = 60;
25112
25130
  MAX_JSON = 4e6;
25113
25131
  sessionFields = [
@@ -25133,7 +25151,7 @@ var init_opencode2 = __esm({
25133
25151
  opencodeAdapter = {
25134
25152
  id: "opencode",
25135
25153
  name: "OpenCode",
25136
- description: "Local SQLite history \xB7 V1 and V2 \xB7 no running service needed",
25154
+ description: "Local SQLite history \xB7 V1 and V2",
25137
25155
  capabilities: { history: true, forks: true, children: true, files: true },
25138
25156
  async detect() {
25139
25157
  return (await openCodeDatabases()).length > 0;
@@ -51869,9 +51887,9 @@ ${n.join(`
51869
51887
  });
51870
51888
 
51871
51889
  // server/adapters/claude-transcripts.ts
51872
- import { constants as constants4 } from "node:fs";
51890
+ import { constants as constants5 } from "node:fs";
51873
51891
  import { lstat as lstat4, open as open3 } from "node:fs/promises";
51874
- import { basename as basename4 } from "node:path";
51892
+ import { basename as basename5 } from "node:path";
51875
51893
  async function state(path) {
51876
51894
  const s = await lstat4(path);
51877
51895
  if (!s.isFile()) throw new Error("Claude transcript must be a regular file.");
@@ -51892,7 +51910,7 @@ async function claudeRevision(path) {
51892
51910
  async function bytes(path, max) {
51893
51911
  const before = await state(path);
51894
51912
  if (before.size > max) throw new Error(`Claude transcript exceeds the ${max === MAX_BYTES2 ? "128 MB import" : "metadata size"} limit.`);
51895
- const file2 = await open3(path, constants4.O_RDONLY | (constants4.O_NOFOLLOW || 0) | (constants4.O_NONBLOCK || 0));
51913
+ const file2 = await open3(path, constants5.O_RDONLY | (constants5.O_NOFOLLOW || 0) | (constants5.O_NONBLOCK || 0));
51896
51914
  try {
51897
51915
  const opened = await file2.stat();
51898
51916
  if (!opened.isFile() || opened.dev !== before.signature[0] || opened.ino !== before.signature[1]) throw new Error("Claude transcript changed during import; import again.");
@@ -51978,7 +51996,7 @@ var init_claude_transcripts = __esm({
51978
51996
  init_common();
51979
51997
  claudeSessionID = (value) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
51980
51998
  MAX_BYTES2 = 128e6;
51981
- sidecar = (path) => basename4(path).startsWith("agent-") ? path.replace(/\.jsonl$/, ".meta.json") : void 0;
51999
+ sidecar = (path) => basename5(path).startsWith("agent-") ? path.replace(/\.jsonl$/, ".meta.json") : void 0;
51982
52000
  }
51983
52001
  });
51984
52002
 
@@ -52071,7 +52089,7 @@ var init_local_messages = __esm({
52071
52089
 
52072
52090
  // server/adapters/pi.ts
52073
52091
  import { homedir as homedir4 } from "node:os";
52074
- import { join as join7 } from "node:path";
52092
+ import { join as join8 } from "node:path";
52075
52093
  function piHistory(value) {
52076
52094
  const { rows: rows2, partial: partial2 } = jsonLines(value);
52077
52095
  const header = rows2[0];
@@ -52111,7 +52129,7 @@ var init_pi = __esm({
52111
52129
  name: "Pi",
52112
52130
  description: "Local JSONL sessions \xB7 messages, tools, compaction, and branch entries",
52113
52131
  capabilities: { history: true, forks: false, children: false, files: true },
52114
- roots: () => [sourcePath("pi") || process.env.SESSIONGRAPH_PI_SESSIONS_DIR || join7(process.env.PI_CODING_AGENT_DIR || join7(homedir4(), ".pi", "agent"), "sessions")],
52132
+ roots: () => [sourcePath("pi") || process.env.SESSIONGRAPH_PI_SESSIONS_DIR || join8(process.env.PI_CODING_AGENT_DIR || join8(homedir4(), ".pi", "agent"), "sessions")],
52115
52133
  match: (path) => path.endsWith(".jsonl"),
52116
52134
  parse(path, files) {
52117
52135
  const history = piHistory(files.get(path));
@@ -52123,7 +52141,7 @@ var init_pi = __esm({
52123
52141
  });
52124
52142
 
52125
52143
  // server/adapters/harness-formats.ts
52126
- import { basename as basename5, dirname as dirname3, join as join8 } from "node:path";
52144
+ import { basename as basename6, dirname as dirname4, join as join9 } from "node:path";
52127
52145
  function message(raw, id3, timestamp) {
52128
52146
  if (!roles.includes(raw.role)) return;
52129
52147
  if (raw.content == null && !Array.isArray(raw.toolCalls ?? raw.tool_calls)) return;
@@ -52198,13 +52216,13 @@ function codebuffHistory(path, files, free) {
52198
52216
  const m = message({ ...r, role: r.role || r.type, content }, text3(r.id) || `message:${i}`);
52199
52217
  return m ? [m] : [];
52200
52218
  });
52201
- const chat = basename5(dirname3(path)), project2 = basename5(dirname3(dirname3(dirname3(path))));
52219
+ const chat = basename6(dirname4(path)), project2 = basename6(dirname4(dirname4(dirname4(path))));
52202
52220
  return { nativeID: `${project2}/${chat}`, messages, partial: true };
52203
52221
  }
52204
52222
  function vibeHistory(path, files) {
52205
- const raw = object4(json4(files.get(path))), legacy = basename5(path) !== "meta.json";
52223
+ const raw = object4(json4(files.get(path))), legacy = basename6(path) !== "meta.json";
52206
52224
  const meta3 = legacy ? object4(raw.metadata) : raw;
52207
- const transcript = join8(dirname3(path), "messages.jsonl");
52225
+ const transcript = join9(dirname4(path), "messages.jsonl");
52208
52226
  const parsed = files.has(transcript) ? jsonLines(files.get(transcript)) : { rows: [], partial: false };
52209
52227
  const records = legacy ? raw.messages : parsed.rows;
52210
52228
  if (!text3(meta3.session_id) || !Array.isArray(records)) throw new Error("Unsupported Vibe session.");
@@ -52286,7 +52304,7 @@ var init_harness_formats = __esm({
52286
52304
  init_usage();
52287
52305
  nativeText = (v3) => typeof v3 === "number" && Number.isSafeInteger(v3) ? String(v3) : text3(v3);
52288
52306
  seconds = (v3) => typeof v3 === "number" && Number.isFinite(v3) && v3 > 0 ? v3 * 1e3 : time3(v3);
52289
- fileID = (path) => basename5(path).replace(/\.jsonl(?:\..*)?$|\.json$/, "");
52307
+ fileID = (path) => basename6(path).replace(/\.jsonl(?:\..*)?$|\.json$/, "");
52290
52308
  sidecar2 = (files, path) => object4(files.has(path) ? json4(files.get(path)) : void 0);
52291
52309
  roles = ["user", "assistant", "system", "tool", "toolResult", "model"];
52292
52310
  }
@@ -52295,7 +52313,7 @@ var init_harness_formats = __esm({
52295
52313
  // server/adapters/claude-locations.ts
52296
52314
  import { lstat as lstat5, opendir } from "node:fs/promises";
52297
52315
  import { homedir as homedir5 } from "node:os";
52298
- import { basename as basename6, dirname as dirname4, join as join9, resolve as resolve3 } from "node:path";
52316
+ import { basename as basename7, dirname as dirname5, join as join10, resolve as resolve3 } from "node:path";
52299
52317
  async function computerRoots(platform = process.platform) {
52300
52318
  if (platform !== "win32") return ["/"];
52301
52319
  const drives = Array.from({ length: 26 }, (_, i) => `${String.fromCharCode(65 + i)}:\\`);
@@ -52316,7 +52334,7 @@ function createClaudeLocationScanner(options) {
52316
52334
  async function scan() {
52317
52335
  const started = now();
52318
52336
  if (!initialized || finishedAt !== void 0 && started - finishedAt >= (options.refreshMs ?? 3e5)) {
52319
- queue = [.../* @__PURE__ */ new Set([dirname4(options.preferredHome()), ...await options.roots()])].map((path) => ({ path: resolve3(path), depth: 0, offset: 0 }));
52337
+ queue = [.../* @__PURE__ */ new Set([dirname5(options.preferredHome()), ...await options.roots()])].map((path) => ({ path: resolve3(path), depth: 0, offset: 0 }));
52320
52338
  index = 0;
52321
52339
  visited = /* @__PURE__ */ new Set();
52322
52340
  skipped = /* @__PURE__ */ new Set();
@@ -52349,12 +52367,12 @@ function createClaudeLocationScanner(options) {
52349
52367
  for await (const entry of await openDirectory(path)) {
52350
52368
  if (offset++ < item.offset) continue;
52351
52369
  if (entry.isDirectory()) {
52352
- const child = join9(path, entry.name);
52370
+ const child = join10(path, entry.name);
52353
52371
  if (entry.name === ".claude") addHome(child);
52354
52372
  if (item.depth < 128 && queue.length < 1e5) queue.push({ path: child, depth: item.depth + 1, offset: 0 });
52355
52373
  else limited = true;
52356
- } else if (entry.isFile() && entry.name.endsWith(".jsonl") && claudeSessionID(entry.name.slice(0, -6)) && basename6(dirname4(path)) === "projects") {
52357
- addHome(dirname4(dirname4(path)));
52374
+ } else if (entry.isFile() && entry.name.endsWith(".jsonl") && claudeSessionID(entry.name.slice(0, -6)) && basename7(dirname5(path)) === "projects") {
52375
+ addHome(dirname5(dirname5(path)));
52358
52376
  }
52359
52377
  entries2++;
52360
52378
  item.offset = offset;
@@ -52382,12 +52400,12 @@ function createClaudeLocationScanner(options) {
52382
52400
  }
52383
52401
  for (const name of ["projects", "transcripts"]) {
52384
52402
  try {
52385
- if ((await lstat5(join9(home, name))).isDirectory()) {
52403
+ if ((await lstat5(join10(home, name))).isDirectory()) {
52386
52404
  found.push(home);
52387
52405
  break;
52388
52406
  }
52389
52407
  } catch (error62) {
52390
- if (!["ENOENT", "ENOTDIR"].includes(error62.code || "")) skipped.add(join9(home, name));
52408
+ if (!["ENOENT", "ENOTDIR"].includes(error62.code || "")) skipped.add(join10(home, name));
52391
52409
  }
52392
52410
  }
52393
52411
  }
@@ -52425,7 +52443,7 @@ var init_claude_locations = __esm({
52425
52443
  "use strict";
52426
52444
  init_source_paths();
52427
52445
  init_claude_transcripts();
52428
- activeClaudeHome = () => resolve3(process.env.CLAUDE_CONFIG_DIR || join9(homedir5(), ".claude"));
52446
+ activeClaudeHome = () => resolve3(process.env.CLAUDE_CONFIG_DIR || join10(homedir5(), ".claude"));
52429
52447
  scanComputer = createClaudeLocationScanner({
52430
52448
  roots: computerRoots,
52431
52449
  preferredHome: activeClaudeHome,
@@ -52437,7 +52455,7 @@ var init_claude_locations = __esm({
52437
52455
  // server/adapters/claude.ts
52438
52456
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
52439
52457
  import { lstat as lstat6, readdir as readdir3, stat } from "node:fs/promises";
52440
- import { basename as basename7, dirname as dirname5, join as join10, resolve as resolve4 } from "node:path";
52458
+ import { basename as basename8, dirname as dirname6, join as join11, resolve as resolve4 } from "node:path";
52441
52459
  function claudeMessages(rows2, candidate, times, entries2) {
52442
52460
  const calls = /* @__PURE__ */ new Map();
52443
52461
  return rows2.map((row) => {
@@ -52524,12 +52542,12 @@ var init_claude = __esm({
52524
52542
  description: "Computer-wide local CLI and VS Code history \xB7 all projects and subagent transcripts",
52525
52543
  capabilities: { history: true, forks: false, children: true, files: true },
52526
52544
  async detect() {
52527
- for (const home of homes()) if ((await lstat6(join10(home, "projects")).catch(() => void 0))?.isDirectory()) return true;
52545
+ for (const home of homes()) if ((await lstat6(join11(home, "projects")).catch(() => void 0))?.isDirectory()) return true;
52528
52546
  return false;
52529
52547
  },
52530
52548
  async discover() {
52531
52549
  const sessions = [], warnings = [];
52532
- const listing = await historyFiles(homes().map((home) => join10(home, "projects")), (p) => {
52550
+ const listing = await historyFiles(homes().map((home) => join11(home, "projects")), (p) => {
52533
52551
  const parts = p.split("/");
52534
52552
  return parts.length === 2 && parts[1].endsWith(".jsonl") && claudeSessionID(parts[1].slice(0, -6));
52535
52553
  });
@@ -52537,11 +52555,11 @@ var init_claude = __esm({
52537
52555
  const files = /* @__PURE__ */ new Map();
52538
52556
  let unreadable = 0;
52539
52557
  for (const path of listing.files) {
52540
- const name = basename7(path);
52541
- const id3 = name.slice(0, -6), home = dirname5(dirname5(dirname5(path)));
52558
+ const name = basename8(path);
52559
+ const id3 = name.slice(0, -6), home = dirname6(dirname6(dirname6(path)));
52542
52560
  try {
52543
52561
  const modified = (await stat(path)).mtimeMs, old = files.get(id3);
52544
- if (!old || modified > old.modified || modified === old.modified && home === resolve4(activeHome()) && old.home !== home) files.set(id3, { path, home, modified, children: join10(dirname5(path), id3, "subagents") });
52562
+ if (!old || modified > old.modified || modified === old.modified && home === resolve4(activeHome()) && old.home !== home) files.set(id3, { path, home, modified, children: join11(dirname6(path), id3, "subagents") });
52545
52563
  } catch {
52546
52564
  unreadable++;
52547
52565
  }
@@ -52590,7 +52608,7 @@ var init_claude = __esm({
52590
52608
  }
52591
52609
  if (!child.isFile() || !/^agent-[\w-]+\.jsonl$/.test(child.name)) continue;
52592
52610
  try {
52593
- const agent = child.name.slice(6, -6), path = join10(file2.children, child.name), stats = await stat(path);
52611
+ const agent = child.name.slice(6, -6), path = join11(file2.children, child.name), stats = await stat(path);
52594
52612
  sessions.push({ session: { ...s, id: identity("claude-code", `${info.sessionId}/agent/${agent}`), nativeID: `${info.sessionId}/agent/${agent}`, title: `Subagent ${agent}`, created: stats.birthtimeMs || s.created, updated: stats.mtimeMs, parentID: s.id, origin: "automated", agent }, revision: await claudeRevision(path), locator: { path, dir: info.cwd || "", parent: info.sessionId, agent } });
52595
52613
  } catch {
52596
52614
  unreadable++;
@@ -52638,7 +52656,7 @@ var init_claude = __esm({
52638
52656
  name: "Claude Code",
52639
52657
  description: "Legacy local transcript exports",
52640
52658
  capabilities: { history: true, forks: false, children: false, files: false },
52641
- roots: () => homes().map((home) => join10(home, "transcripts")),
52659
+ roots: () => homes().map((home) => join11(home, "transcripts")),
52642
52660
  match: (p) => p.endsWith(".jsonl"),
52643
52661
  parse: (path, files) => envelopeHistory(path, files.get(path))
52644
52662
  });
@@ -52648,11 +52666,11 @@ var init_claude = __esm({
52648
52666
 
52649
52667
  // server/adapters/jsonl.ts
52650
52668
  import { open as open4, readdir as readdir4 } from "node:fs/promises";
52651
- import { join as join11 } from "node:path";
52652
- import { constants as constants5 } from "node:fs";
52669
+ import { join as join12 } from "node:path";
52670
+ import { constants as constants6 } from "node:fs";
52653
52671
  async function readJSONL(path, offset = 0, budget2 = 2e6, limit = 200) {
52654
52672
  if (!Number.isSafeInteger(offset) || offset < 0) throw new Error("Invalid transcript cursor.");
52655
- const file2 = await open4(path, constants5.O_RDONLY | (constants5.O_NOFOLLOW || 0));
52673
+ const file2 = await open4(path, constants6.O_RDONLY | (constants6.O_NOFOLLOW || 0));
52656
52674
  const rows2 = [];
52657
52675
  let position = offset, carry = Buffer.alloc(0), lineStart = offset, partial2 = false, skipping = false, eof = false;
52658
52676
  try {
@@ -52730,8 +52748,8 @@ async function transcriptFiles(root2, max = 2e4, match2 = (name) => name.endsWit
52730
52748
  throw error62;
52731
52749
  }
52732
52750
  for (const entry of entries2) {
52733
- if (entry.isDirectory() && queue.length < 2e4) queue.push(join11(queue[i], entry.name));
52734
- if (entry.isFile() && match2(entry.name)) files.push(join11(queue[i], entry.name));
52751
+ if (entry.isDirectory() && queue.length < 2e4) queue.push(join12(queue[i], entry.name));
52752
+ if (entry.isFile() && match2(entry.name)) files.push(join12(queue[i], entry.name));
52735
52753
  if (files.length >= max) break;
52736
52754
  }
52737
52755
  }
@@ -52748,7 +52766,7 @@ var init_jsonl = __esm({
52748
52766
  // server/adapters/codex.ts
52749
52767
  import { stat as stat2 } from "node:fs/promises";
52750
52768
  import { homedir as homedir6 } from "node:os";
52751
- import { join as join12, sep as sep3 } from "node:path";
52769
+ import { join as join13, sep as sep3 } from "node:path";
52752
52770
  function changedPaths(value) {
52753
52771
  if (!value || typeof value !== "object") return [];
52754
52772
  const changes = Array.isArray(value) ? value : Object.entries(value).map(([path, change]) => ({ ...change && typeof change === "object" ? change : {}, path }));
@@ -52772,7 +52790,7 @@ async function sessionNames() {
52772
52790
  let cursor2, count = 0;
52773
52791
  try {
52774
52792
  do {
52775
- const page3 = await readJSONL(join12(root(), "session_index.jsonl"), cursor2, 2e6, 1e3);
52793
+ const page3 = await readJSONL(join13(root(), "session_index.jsonl"), cursor2, 2e6, 1e3);
52776
52794
  for (const { value } of page3.rows) if (typeof value.id === "string" && typeof value.thread_name === "string" && value.thread_name.trim()) names.set(value.id, value.thread_name.trim().slice(0, 300));
52777
52795
  cursor2 = page3.cursor;
52778
52796
  count += page3.rows.length;
@@ -52857,7 +52875,7 @@ var init_codex = __esm({
52857
52875
  init_source_paths();
52858
52876
  init_commit_extraction();
52859
52877
  init_usage();
52860
- root = () => sourcePath("codex") || process.env.CODEX_HOME || join12(homedir6(), ".codex");
52878
+ root = () => sourcePath("codex") || process.env.CODEX_HOME || join13(homedir6(), ".codex");
52861
52879
  revision = async (path) => {
52862
52880
  const s = await stat2(path);
52863
52881
  return digest([10, s.mtimeMs, s.size]);
@@ -52878,7 +52896,7 @@ var init_codex = __esm({
52878
52896
  const found = /* @__PURE__ */ new Map(), warnings = [];
52879
52897
  const names = await sessionNames();
52880
52898
  const match2 = (name) => /\.jsonl(?:\.[\w.-]+)?$/.test(name);
52881
- const paths2 = [...await transcriptFiles(join12(root(), "sessions"), 2e4, match2), ...await transcriptFiles(join12(root(), "archived_sessions"), 2e4, match2)];
52899
+ const paths2 = [...await transcriptFiles(join13(root(), "sessions"), 2e4, match2), ...await transcriptFiles(join13(root(), "archived_sessions"), 2e4, match2)];
52882
52900
  if (paths2.length >= 2e4) warnings.push("Codex transcript listing may be partial (20,000 files per history folder).");
52883
52901
  let unsupported = 0;
52884
52902
  for (const path of paths2) {
@@ -52935,7 +52953,7 @@ var init_codex = __esm({
52935
52953
  // server/adapters/t3-code.ts
52936
52954
  import { lstat as lstat7 } from "node:fs/promises";
52937
52955
  import { homedir as homedir7 } from "node:os";
52938
- import { isAbsolute as isAbsolute5, join as join13 } from "node:path";
52956
+ import { isAbsolute as isAbsolute5, join as join14 } from "node:path";
52939
52957
  function parsedObject(value) {
52940
52958
  if (typeof value !== "string") return;
52941
52959
  try {
@@ -52953,12 +52971,12 @@ function status(value) {
52953
52971
  return ["pending", "running", "completed", "failed"].includes(string6(value)) ? value : "unknown";
52954
52972
  }
52955
52973
  async function databasePath2() {
52956
- const root2 = sourcePath("t3-code") || process.env.SESSIONGRAPH_T3_CODE_HISTORY_DIR || process.env.T3CODE_HOME || join13(homedir7(), ".t3");
52974
+ const root2 = sourcePath("t3-code") || process.env.SESSIONGRAPH_T3_CODE_HISTORY_DIR || process.env.T3CODE_HOME || join14(homedir7(), ".t3");
52957
52975
  const paths2 = /\.sqlite$/.test(root2) ? [root2] : [
52958
- join13(root2, "userdata", "statev2.sqlite"),
52959
- join13(root2, "statev2.sqlite"),
52960
- join13(root2, "userdata", "state.sqlite"),
52961
- join13(root2, "state.sqlite")
52976
+ join14(root2, "userdata", "statev2.sqlite"),
52977
+ join14(root2, "statev2.sqlite"),
52978
+ join14(root2, "userdata", "state.sqlite"),
52979
+ join14(root2, "state.sqlite")
52962
52980
  ];
52963
52981
  for (const path of paths2) {
52964
52982
  try {
@@ -53154,7 +53172,7 @@ function v2Message(row, directory3) {
53154
53172
  message2.events = [eventFor(message2, id3, kind2, file2, "", { ...fields3, callID: string6(native.nativeId) || void 0 })];
53155
53173
  return message2;
53156
53174
  }
53157
- if (file2 && completed) message2.files.push({ path: isAbsolute5(file2) ? file2 : join13(directory3, file2), source: "file change", steps: 1 });
53175
+ if (file2 && completed) message2.files.push({ path: isAbsolute5(file2) ? file2 : join14(directory3, file2), source: "file change", steps: 1 });
53158
53176
  message2.events = [eventFor(message2, id3, "file_change", file2 || name, "", fields3)];
53159
53177
  return message2;
53160
53178
  }
@@ -53362,14 +53380,14 @@ var init_cursor_message = __esm({
53362
53380
 
53363
53381
  // server/adapters/cursor-store.ts
53364
53382
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
53365
- import { chmodSync as chmodSync3, copyFileSync as copyFileSync2, lstatSync as lstatSync3, mkdtempSync as mkdtempSync2, rmSync as rmSync3 } from "node:fs";
53383
+ import { chmodSync as chmodSync3, copyFileSync as copyFileSync2, lstatSync as lstatSync4, mkdtempSync as mkdtempSync2, rmSync as rmSync3 } from "node:fs";
53366
53384
  import { tmpdir as tmpdir2 } from "node:os";
53367
- import { join as join14 } from "node:path";
53385
+ import { join as join15 } from "node:path";
53368
53386
  function withStore(path, read2) {
53369
53387
  const files = [path, `${path}-wal`];
53370
53388
  const stats = () => files.map((file2) => {
53371
53389
  try {
53372
- const s = lstatSync3(file2);
53390
+ const s = lstatSync4(file2);
53373
53391
  if (!s.isFile() || s.size > 256e6) throw new Error("Cursor store must be a regular file below 256 MB (including each WAL).");
53374
53392
  return [s.ino, s.size, s.mtimeMs, s.ctimeMs];
53375
53393
  } catch (error62) {
@@ -53377,11 +53395,11 @@ function withStore(path, read2) {
53377
53395
  throw error62;
53378
53396
  }
53379
53397
  });
53380
- const before = stats(), directory3 = mkdtempSync2(join14(tmpdir2(), "sessiongraph-cursor-"));
53398
+ const before = stats(), directory3 = mkdtempSync2(join15(tmpdir2(), "sessiongraph-cursor-"));
53381
53399
  let db2;
53382
53400
  try {
53383
53401
  chmodSync3(directory3, 448);
53384
- const copy = join14(directory3, "store.db");
53402
+ const copy = join15(directory3, "store.db");
53385
53403
  files.forEach((file2, index) => {
53386
53404
  if (before[index]) {
53387
53405
  const target = index ? `${copy}-wal` : copy;
@@ -53550,7 +53568,7 @@ function discoverComposers(path, workspace = "") {
53550
53568
  for (const table2 of ["cursorDiskKV", "ItemTable"]) {
53551
53569
  if (!hasTable(db2, table2)) continue;
53552
53570
  let failed = 0, count = 0;
53553
- const rows2 = db2.prepare(`SELECT key, CASE WHEN length(value)<=? THEN value END AS value FROM ${table2} WHERE key LIKE 'composerData:%' AND value IS NOT NULL ORDER BY key LIMIT 20001`).iterate(MAX_VALUE2);
53571
+ const rows2 = iterate(db2, `SELECT key, CASE WHEN length(value)<=? THEN value END AS value FROM ${table2} WHERE key LIKE 'composerData:%' AND value IS NOT NULL ORDER BY key LIMIT 20001`, MAX_VALUE2);
53554
53572
  for (const row of rows2) {
53555
53573
  if (++count > 2e4) {
53556
53574
  warnings.push("Cursor Composer listing reached its 20,000-session limit.");
@@ -53645,6 +53663,7 @@ var init_cursor_composer = __esm({
53645
53663
  init_cursor_message();
53646
53664
  init_local_files();
53647
53665
  init_sqlite_snapshot();
53666
+ init_sqlite();
53648
53667
  MAX_VALUE2 = 32e6;
53649
53668
  MAX_BUBBLE = 8e6;
53650
53669
  MAX_MESSAGES = 5e4;
@@ -53656,7 +53675,7 @@ var init_cursor_composer = __esm({
53656
53675
  import { createHash as createHash5 } from "node:crypto";
53657
53676
  import { lstat as lstat8, opendir as opendir2, readFile as readFile2 } from "node:fs/promises";
53658
53677
  import { homedir as homedir8 } from "node:os";
53659
- import { isAbsolute as isAbsolute7, join as join15 } from "node:path";
53678
+ import { isAbsolute as isAbsolute7, join as join16 } from "node:path";
53660
53679
  import { fileURLToPath as fileURLToPath2 } from "node:url";
53661
53680
  async function fileStats(path) {
53662
53681
  try {
@@ -53700,12 +53719,12 @@ async function entries(path, warnings) {
53700
53719
  }
53701
53720
  async function workspacePaths(root2, warnings) {
53702
53721
  const stores = /* @__PURE__ */ new Map();
53703
- const storage = join15(root2, "User/workspaceStorage");
53722
+ const storage = join16(root2, "User/workspaceStorage");
53704
53723
  for (const entry of await entries(storage, warnings)) if (entry.isDirectory()) {
53705
- const database = join15(storage, entry.name, "state.vscdb");
53724
+ const database = join16(storage, entry.name, "state.vscdb");
53706
53725
  stores.set(database, "");
53707
53726
  try {
53708
- const info = await json5(join15(storage, entry.name, "workspace.json"));
53727
+ const info = await json5(join16(storage, entry.name, "workspace.json"));
53709
53728
  if (typeof info.folder === "string" && info.folder.startsWith("file:")) {
53710
53729
  const path = cwd(fileURLToPath2(info.folder));
53711
53730
  if (path) stores.set(database, path);
@@ -53717,7 +53736,7 @@ async function workspacePaths(root2, warnings) {
53717
53736
  return stores;
53718
53737
  }
53719
53738
  function createCursorAdapter(options = {}) {
53720
- const root2 = () => options.home || sourcePath("cursor") || process.env.SESSIONGRAPH_CURSOR_HOME || process.env.SESSION_ATLAS_CURSOR_HOME || join15(homedir8(), ".cursor");
53739
+ const root2 = () => options.home || sourcePath("cursor") || process.env.SESSIONGRAPH_CURSOR_HOME || process.env.SESSION_ATLAS_CURSOR_HOME || join16(homedir8(), ".cursor");
53721
53740
  const editor = () => options.userData || process.env.SESSIONGRAPH_CURSOR_USER_DATA_DIR || process.env.SESSION_ATLAS_CURSOR_USER_DATA_DIR || userData();
53722
53741
  return {
53723
53742
  id: "cursor",
@@ -53725,13 +53744,13 @@ function createCursorAdapter(options = {}) {
53725
53744
  description: "Local IDE, Composer, and CLI sessions",
53726
53745
  capabilities: { history: true, forks: false, children: true, files: false },
53727
53746
  async detect() {
53728
- if (await fileStats(join15(editor(), "User/globalStorage/state.vscdb"))) return true;
53729
- for (const entry of await entries(join15(editor(), "User/workspaceStorage"), [])) {
53730
- if (entry.isDirectory() && await fileStats(join15(editor(), "User/workspaceStorage", entry.name, "state.vscdb"))) return true;
53747
+ if (await fileStats(join16(editor(), "User/globalStorage/state.vscdb"))) return true;
53748
+ for (const entry of await entries(join16(editor(), "User/workspaceStorage"), [])) {
53749
+ if (entry.isDirectory() && await fileStats(join16(editor(), "User/workspaceStorage", entry.name, "state.vscdb"))) return true;
53731
53750
  }
53732
53751
  for (const name of ["projects", "chats", "acp-sessions"]) {
53733
53752
  try {
53734
- if ((await lstat8(join15(root2(), name))).isDirectory()) return true;
53753
+ if ((await lstat8(join16(root2(), name))).isDirectory()) return true;
53735
53754
  } catch {
53736
53755
  }
53737
53756
  }
@@ -53741,7 +53760,7 @@ function createCursorAdapter(options = {}) {
53741
53760
  const warnings = [], errors = [], found = /* @__PURE__ */ new Map(), blocked = /* @__PURE__ */ new Set();
53742
53761
  const workspaceStores = await workspacePaths(editor(), warnings);
53743
53762
  const paths2 = [...new Set([...workspaceStores.values()].filter(Boolean))];
53744
- const legacyStores = new Map([[join15(editor(), "User/globalStorage/state.vscdb"), ""], ...workspaceStores]);
53763
+ const legacyStores = new Map([[join16(editor(), "User/globalStorage/state.vscdb"), ""], ...workspaceStores]);
53745
53764
  for (const [path, workspace] of legacyStores) {
53746
53765
  try {
53747
53766
  if (!await fileStats(path)) continue;
@@ -53772,7 +53791,7 @@ function createCursorAdapter(options = {}) {
53772
53791
  if (!stats) return;
53773
53792
  const native = parent ? `${parent}/agent/${id3}` : id3;
53774
53793
  const locator = { path, kind };
53775
- if (kind !== "transcript") locator.meta = join15(path, "..", "meta.json");
53794
+ if (kind !== "transcript") locator.meta = join16(path, "..", "meta.json");
53776
53795
  const before = await snapshot(locator);
53777
53796
  const extra2 = locator.meta ? await json5(locator.meta) : {};
53778
53797
  const meta3 = kind === "transcript" ? {} : cursorStoreMetadata(path);
@@ -53814,7 +53833,7 @@ function createCursorAdapter(options = {}) {
53814
53833
  }
53815
53834
  if (!session.directory) locator.directoryNote = "Working directory is unknown; choose one when continuing.";
53816
53835
  session.projectID = project("cursor", session.directory).id;
53817
- session.nativeResume = kind === "cli" && Boolean(session.directory) && hashCwd(session.directory) === workspaceHash && root2() === join15(homedir8(), ".cursor");
53836
+ session.nativeResume = kind === "cli" && Boolean(session.directory) && hashCwd(session.directory) === workspaceHash && root2() === join16(homedir8(), ".cursor");
53818
53837
  locator.snapshot = before;
53819
53838
  if (await snapshot(locator) !== before) throw new Error("Cursor session changed during discovery.");
53820
53839
  const previous = found.get(session.id);
@@ -53837,39 +53856,39 @@ function createCursorAdapter(options = {}) {
53837
53856
  if (kind !== "transcript") blocked.add(identity("cursor", id3));
53838
53857
  }
53839
53858
  };
53840
- const projects = join15(root2(), "projects");
53859
+ const projects = join16(root2(), "projects");
53841
53860
  for (const dir of await entries(projects, warnings)) {
53842
53861
  if (!dir.isDirectory() || scanned >= LIMIT) continue;
53843
- const transcripts = join15(projects, dir.name, "agent-transcripts"), directory3 = match2(dir.name, slug);
53862
+ const transcripts = join16(projects, dir.name, "agent-transcripts"), directory3 = match2(dir.name, slug);
53844
53863
  for (const entry of await entries(transcripts, warnings)) {
53845
53864
  if (scanned >= LIMIT) break;
53846
- if (entry.isFile() && entry.name.endsWith(".jsonl")) await add(join15(transcripts, entry.name), entry.name.slice(0, -6), "transcript", directory3);
53865
+ if (entry.isFile() && entry.name.endsWith(".jsonl")) await add(join16(transcripts, entry.name), entry.name.slice(0, -6), "transcript", directory3);
53847
53866
  else if (entry.isFile() && entry.name.endsWith(".txt")) legacy++;
53848
53867
  else if (entry.isDirectory() && validID(entry.name)) {
53849
- await add(join15(transcripts, entry.name, `${entry.name}.jsonl`), entry.name, "transcript", directory3);
53850
- for (const child of await entries(join15(transcripts, entry.name, "subagents"), warnings)) {
53851
- if (child.isFile() && child.name.endsWith(".jsonl")) await add(join15(transcripts, entry.name, "subagents", child.name), child.name.slice(0, -6), "transcript", directory3, entry.name);
53868
+ await add(join16(transcripts, entry.name, `${entry.name}.jsonl`), entry.name, "transcript", directory3);
53869
+ for (const child of await entries(join16(transcripts, entry.name, "subagents"), warnings)) {
53870
+ if (child.isFile() && child.name.endsWith(".jsonl")) await add(join16(transcripts, entry.name, "subagents", child.name), child.name.slice(0, -6), "transcript", directory3, entry.name);
53852
53871
  if (scanned >= LIMIT) break;
53853
53872
  }
53854
53873
  }
53855
53874
  }
53856
53875
  }
53857
- const chats = join15(root2(), "chats");
53876
+ const chats = join16(root2(), "chats");
53858
53877
  for (const bucket of await entries(chats, warnings)) {
53859
53878
  if (!bucket.isDirectory() || scanned >= LIMIT) continue;
53860
- const folder = join15(chats, bucket.name), directory3 = match2(bucket.name, hashCwd);
53861
- if (/^[a-f\d]{32}$/i.test(bucket.name) && await fileStats(join15(folder, "store.db"))) {
53879
+ const folder = join16(chats, bucket.name), directory3 = match2(bucket.name, hashCwd);
53880
+ if (/^[a-f\d]{32}$/i.test(bucket.name) && await fileStats(join16(folder, "store.db"))) {
53862
53881
  const id3 = bucket.name.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, "$1-$2-$3-$4-$5");
53863
- await add(join15(folder, "store.db"), id3, "cli", "");
53882
+ await add(join16(folder, "store.db"), id3, "cli", "");
53864
53883
  }
53865
53884
  for (const entry of await entries(folder, warnings)) {
53866
- if (entry.isDirectory()) await add(join15(folder, entry.name, "store.db"), entry.name, "cli", directory3, "", bucket.name);
53885
+ if (entry.isDirectory()) await add(join16(folder, entry.name, "store.db"), entry.name, "cli", directory3, "", bucket.name);
53867
53886
  if (scanned >= LIMIT) break;
53868
53887
  }
53869
53888
  }
53870
- const acp = join15(root2(), "acp-sessions");
53889
+ const acp = join16(root2(), "acp-sessions");
53871
53890
  for (const entry of await entries(acp, warnings)) {
53872
- if (entry.isDirectory()) await add(join15(acp, entry.name, "store.db"), entry.name, "acp", "");
53891
+ if (entry.isDirectory()) await add(join16(acp, entry.name, "store.db"), entry.name, "acp", "");
53873
53892
  if (scanned >= LIMIT) break;
53874
53893
  }
53875
53894
  if (scanned >= LIMIT) warnings.push("Cursor discovery limited to 20,000 history files.");
@@ -53929,17 +53948,17 @@ var init_cursor = __esm({
53929
53948
  cwd = (value) => typeof value === "string" && isAbsolute7(value) && !/[\x00-\x1f\x7f]/.test(value) ? value : "";
53930
53949
  slug = (path) => path.replace(/\\/g, "/").replace(/^([A-Z]):/i, (_, drive) => drive.toLowerCase()).replace(/^\/+|\/+$/g, "").replace(/[/:]+/g, "-");
53931
53950
  hashCwd = (path) => createHash5("md5").update(path).digest("hex");
53932
- userData = () => process.platform === "darwin" ? join15(homedir8(), "Library/Application Support/Cursor") : process.platform === "win32" ? join15(process.env.APPDATA || join15(homedir8(), "AppData/Roaming"), "Cursor") : join15(process.env.XDG_CONFIG_HOME || join15(homedir8(), ".config"), "Cursor");
53951
+ userData = () => process.platform === "darwin" ? join16(homedir8(), "Library/Application Support/Cursor") : process.platform === "win32" ? join16(process.env.APPDATA || join16(homedir8(), "AppData/Roaming"), "Cursor") : join16(process.env.XDG_CONFIG_HOME || join16(homedir8(), ".config"), "Cursor");
53933
53952
  cursorAdapter = createCursorAdapter();
53934
53953
  }
53935
53954
  });
53936
53955
 
53937
53956
  // server/adapters/gemini.ts
53938
53957
  import { homedir as homedir9 } from "node:os";
53939
- import { basename as basename8, dirname as dirname6, join as join16, sep as sep4 } from "node:path";
53958
+ import { basename as basename9, dirname as dirname7, join as join17, sep as sep4 } from "node:path";
53940
53959
  function projectRootFile(path) {
53941
53960
  const parts = path.split(sep4);
53942
- return join16(parts.slice(0, parts.lastIndexOf("chats")).join(sep4), ".project_root");
53961
+ return join17(parts.slice(0, parts.lastIndexOf("chats")).join(sep4), ".project_root");
53943
53962
  }
53944
53963
  function geminiConversation(contents, lines) {
53945
53964
  const parsed = lines ? jsonLines(contents) : { rows: [object4(json4(contents))], partial: false };
@@ -54000,7 +54019,7 @@ var init_gemini = __esm({
54000
54019
  name: "Gemini CLI",
54001
54020
  description: "Local JSON and JSONL chats, including recorded subagent histories",
54002
54021
  capabilities: { history: true, forks: false, children: true, files: true },
54003
- roots: () => sourcePath("gemini") || process.env.SESSIONGRAPH_GEMINI_HOME ? [join16(sourcePath("gemini") || process.env.SESSIONGRAPH_GEMINI_HOME, "tmp")] : [join16(process.env.GEMINI_CLI_HOME || homedir9(), ".gemini", "tmp"), join16(process.env.GEMINI_CLI_HOME || homedir9(), ".cache", ".gemini", "tmp")],
54022
+ roots: () => sourcePath("gemini") || process.env.SESSIONGRAPH_GEMINI_HOME ? [join17(sourcePath("gemini") || process.env.SESSIONGRAPH_GEMINI_HOME, "tmp")] : [join17(process.env.GEMINI_CLI_HOME || homedir9(), ".gemini", "tmp"), join17(process.env.GEMINI_CLI_HOME || homedir9(), ".cache", ".gemini", "tmp")],
54004
54023
  match: (path) => /^[^/]+\/chats\/(?:[^/]+\/)?[^/]+\.jsonl?$/.test(path),
54005
54024
  extras: (path) => [projectRootFile(path)],
54006
54025
  parse(path, files) {
@@ -54025,7 +54044,7 @@ var init_gemini = __esm({
54025
54044
  return message2;
54026
54045
  });
54027
54046
  successfulEdits(messages, ["write_file", "replace"]);
54028
- const parent = meta3.kind === "subagent" && basename8(dirname6(dirname6(path))) === "chats" ? basename8(dirname6(path)) : void 0;
54047
+ const parent = meta3.kind === "subagent" && basename9(dirname7(dirname7(path))) === "chats" ? basename9(dirname7(path)) : void 0;
54029
54048
  return {
54030
54049
  nativeID: meta3.sessionId,
54031
54050
  messages,
@@ -54040,7 +54059,7 @@ var init_gemini = __esm({
54040
54059
 
54041
54060
  // server/adapters/qwen.ts
54042
54061
  import { homedir as homedir10 } from "node:os";
54043
- import { join as join17 } from "node:path";
54062
+ import { join as join18 } from "node:path";
54044
54063
  var qwenAdapter;
54045
54064
  var init_qwen = __esm({
54046
54065
  "server/adapters/qwen.ts"() {
@@ -54056,7 +54075,7 @@ var init_qwen = __esm({
54056
54075
  name: "Qwen Code",
54057
54076
  description: "Local project chat records \xB7 tool results, forks, and child sessions",
54058
54077
  capabilities: { history: true, forks: true, children: true, files: true },
54059
- roots: () => [join17(sourcePath("qwen-code") || process.env.SESSIONGRAPH_QWEN_HOME || process.env.QWEN_RUNTIME_DIR || process.env.QWEN_HOME || join17(homedir10(), ".qwen"), "projects")],
54078
+ roots: () => [join18(sourcePath("qwen-code") || process.env.SESSIONGRAPH_QWEN_HOME || process.env.QWEN_RUNTIME_DIR || process.env.QWEN_HOME || join18(homedir10(), ".qwen"), "projects")],
54060
54079
  match: (path) => /^[^/]+\/chats\/[^/]+\.jsonl$/.test(path),
54061
54080
  parse(path, files) {
54062
54081
  const { rows: rows2, partial: partial2 } = jsonLines(files.get(path));
@@ -54097,7 +54116,7 @@ var init_qwen = __esm({
54097
54116
 
54098
54117
  // server/adapters/copilot.ts
54099
54118
  import { homedir as homedir11 } from "node:os";
54100
- import { join as join18 } from "node:path";
54119
+ import { join as join19 } from "node:path";
54101
54120
  var copilotAdapter;
54102
54121
  var init_copilot = __esm({
54103
54122
  "server/adapters/copilot.ts"() {
@@ -54111,7 +54130,7 @@ var init_copilot = __esm({
54111
54130
  name: "GitHub Copilot CLI",
54112
54131
  description: "Local session event logs \xB7 conversations and completed file edits",
54113
54132
  capabilities: { history: true, forks: false, children: true, files: true },
54114
- roots: () => [join18(sourcePath("copilot") || process.env.SESSIONGRAPH_COPILOT_HOME || join18(homedir11(), ".copilot"), "session-state")],
54133
+ roots: () => [join19(sourcePath("copilot") || process.env.SESSIONGRAPH_COPILOT_HOME || join19(homedir11(), ".copilot"), "session-state")],
54115
54134
  match: (path) => /(?:^|\/)events\.jsonl$/.test(path),
54116
54135
  parse(path, files) {
54117
54136
  const { rows: rows2, partial: partial2 } = jsonLines(files.get(path));
@@ -54209,7 +54228,7 @@ var init_vscode_chat_log = __esm({
54209
54228
 
54210
54229
  // server/adapters/copilot-chat.ts
54211
54230
  import { homedir as homedir12 } from "node:os";
54212
- import { basename as basename9, dirname as dirname7, join as join19, posix as posix2, win32 as win323 } from "node:path";
54231
+ import { basename as basename10, dirname as dirname8, join as join20, posix as posix2, win32 as win323 } from "node:path";
54213
54232
  import { fileURLToPath as fileURLToPath3 } from "node:url";
54214
54233
  function copilotChatRoots(platform = process.platform, home = homedir12(), env2 = process.env) {
54215
54234
  const path = platform === "win32" ? win323 : posix2;
@@ -54326,16 +54345,16 @@ var init_copilot_chat = __esm({
54326
54345
  capabilities: { history: true, forks: false, children: false, files: true },
54327
54346
  roots,
54328
54347
  match,
54329
- authoritativeIdentity: (path) => path.endsWith(".jsonl") ? basename9(path, ".jsonl") : void 0,
54330
- extras: (path) => [...basename9(dirname7(path)) === "chatSessions" ? [join19(dirname7(dirname7(path)), "workspace.json")] : [], ...path.endsWith(".json") ? [`${path}l`] : []],
54348
+ authoritativeIdentity: (path) => path.endsWith(".jsonl") ? basename10(path, ".jsonl") : void 0,
54349
+ extras: (path) => [...basename10(dirname8(path)) === "chatSessions" ? [join20(dirname8(dirname8(path)), "workspace.json")] : [], ...path.endsWith(".json") ? [`${path}l`] : []],
54331
54350
  parse(path, files) {
54332
54351
  const log = path.endsWith(".jsonl") ? path : `${path}l`;
54333
54352
  const data = files.has(log) ? vscodeChatLog(files.get(log)) : object4(JSON.parse(files.get(path)));
54334
54353
  if (!text3(data.sessionId) || !Array.isArray(data.requests) || data.version !== void 0 && ![1, 2, 3].includes(data.version)) throw new Error("Unsupported VS Code chat history.");
54335
- if (data.sessionId !== basename9(path).replace(/\.jsonl?$/, "")) throw new Error("VS Code chat identity mismatch.");
54354
+ if (data.sessionId !== basename10(path).replace(/\.jsonl?$/, "")) throw new Error("VS Code chat identity mismatch.");
54336
54355
  if (!data.requests.length) return;
54337
54356
  if (data.requests.length > 25e3) throw new Error("Chat exceeds the 50,000-message limit.");
54338
- const workspacePath = join19(dirname7(dirname7(path)), "workspace.json");
54357
+ const workspacePath = join20(dirname8(dirname8(path)), "workspace.json");
54339
54358
  const workspace = files.has(workspacePath) ? object4(JSON.parse(files.get(workspacePath))) : {};
54340
54359
  const messages = chatMessages(data.requests);
54341
54360
  const model = [...data.requests].reverse().find((r) => text3(r.modelId));
@@ -54355,7 +54374,7 @@ var init_copilot_chat = __esm({
54355
54374
 
54356
54375
  // server/adapters/extensions.ts
54357
54376
  import { homedir as homedir13 } from "node:os";
54358
- import { basename as basename10, dirname as dirname8, join as join20 } from "node:path";
54377
+ import { basename as basename11, dirname as dirname9, join as join21 } from "node:path";
54359
54378
  function taskUsage(value, source) {
54360
54379
  if (!Array.isArray(value)) return;
54361
54380
  const records = /* @__PURE__ */ new Map();
@@ -54386,12 +54405,12 @@ function taskUsage(value, source) {
54386
54405
  }
54387
54406
  function editorTaskRoots(extension) {
54388
54407
  const home = homedir13();
54389
- const base = process.platform === "darwin" ? join20(home, "Library", "Application Support") : process.platform === "win32" ? process.env.APPDATA || join20(home, "AppData", "Roaming") : process.env.XDG_CONFIG_HOME || join20(home, ".config");
54390
- return ["Code", "Code - Insiders", "VSCodium", "Cursor", "Windsurf"].map((app) => join20(base, app, "User", "globalStorage", extension, "tasks")).concat([".vscode-server", ".vscode-server-insiders"].map((app) => join20(home, app, "data", "User", "globalStorage", extension, "tasks")));
54408
+ const base = process.platform === "darwin" ? join21(home, "Library", "Application Support") : process.platform === "win32" ? process.env.APPDATA || join21(home, "AppData", "Roaming") : process.env.XDG_CONFIG_HOME || join21(home, ".config");
54409
+ return ["Code", "Code - Insiders", "VSCodium", "Cursor", "Windsurf"].map((app) => join21(base, app, "User", "globalStorage", extension, "tasks")).concat([".vscode-server", ".vscode-server-insiders"].map((app) => join21(home, app, "data", "User", "globalStorage", extension, "tasks")));
54391
54410
  }
54392
54411
  function taskAdapter(id3, name, extension, env2) {
54393
54412
  const home = () => sourcePath(id3) || process.env[env2];
54394
- const roots2 = () => home() ? [join20(home(), "tasks"), ...id3 === "cline" ? [join20(home(), "data", "sessions")] : []] : [...editorTaskRoots(extension), ...id3 === "cline" ? [process.env.CLINE_SESSION_DATA_DIR || join20(process.env.CLINE_DATA_DIR || join20(process.env.CLINE_DIR || join20(homedir13(), ".cline"), "data"), "sessions")] : []];
54413
+ const roots2 = () => home() ? [join21(home(), "tasks"), ...id3 === "cline" ? [join21(home(), "data", "sessions")] : []] : [...editorTaskRoots(extension), ...id3 === "cline" ? [process.env.CLINE_SESSION_DATA_DIR || join21(process.env.CLINE_DATA_DIR || join21(process.env.CLINE_DIR || join21(homedir13(), ".cline"), "data"), "sessions")] : []];
54395
54414
  return localFileAdapter({
54396
54415
  id: id3,
54397
54416
  name,
@@ -54399,14 +54418,14 @@ function taskAdapter(id3, name, extension, env2) {
54399
54418
  capabilities: { history: true, forks: id3 === "cline", children: true, files: true },
54400
54419
  roots: roots2,
54401
54420
  match: (path) => /^[^/]+\/api_conversation_history\.json$/.test(path) || id3 === "cline" && /^[^/]+\/[^/]+\.messages\.json$/.test(path),
54402
- extras: (path) => ["history_item.json", "task_metadata.json", "session.json", "ui_messages.json"].map((file2) => join20(dirname8(path), file2)),
54421
+ extras: (path) => ["history_item.json", "task_metadata.json", "session.json", "ui_messages.json"].map((file2) => join21(dirname9(path), file2)),
54403
54422
  parse(path, files) {
54404
54423
  const sdk = path.endsWith(".messages.json"), value = json4(files.get(path));
54405
54424
  const records = sdk ? object4(value).messages : value;
54406
54425
  if (!Array.isArray(records) || sdk && !text3(value.sessionId)) throw new Error("Unsupported task history.");
54407
- const read2 = (name2) => object4(files.has(join20(dirname8(path), name2)) ? json4(files.get(join20(dirname8(path), name2))) : void 0);
54426
+ const read2 = (name2) => object4(files.has(join21(dirname9(path), name2)) ? json4(files.get(join21(dirname9(path), name2))) : void 0);
54408
54427
  const history = read2("history_item.json"), info = read2("session.json"), task = read2("task_metadata.json");
54409
- const nativeID = sdk ? value.sessionId : basename10(dirname8(path));
54428
+ const nativeID = sdk ? value.sessionId : basename11(dirname9(path));
54410
54429
  if (history.id && history.id !== nativeID || info.session_id && info.session_id !== nativeID) throw new Error("Task metadata identity mismatch.");
54411
54430
  const messages = records.map((raw, index) => {
54412
54431
  const row = object4(raw), message2 = conversationMessage(row, `record:${index}`);
@@ -54446,7 +54465,7 @@ function taskAdapter(id3, name, extension, env2) {
54446
54465
  title: text3(history.task || info.metadata?.title),
54447
54466
  model: text3(lastModel?.modelInfo?.id || lastModel?.model || info.model) || "Unknown model",
54448
54467
  provider: text3(lastModel?.modelInfo?.provider || info.provider),
54449
- usage: !sdk && files.has(join20(dirname8(path), "ui_messages.json")) ? taskUsage(json4(files.get(join20(dirname8(path), "ui_messages.json"))), id3) : void 0
54468
+ usage: !sdk && files.has(join21(dirname9(path), "ui_messages.json")) ? taskUsage(json4(files.get(join21(dirname9(path), "ui_messages.json"))), id3) : void 0
54450
54469
  },
54451
54470
  note: sdk ? void 0 : "Earlier and editor-only messages may be missing."
54452
54471
  };
@@ -54471,14 +54490,14 @@ var init_extensions = __esm({
54471
54490
  name: "Continue",
54472
54491
  description: "Local IDE and CLI session JSON \xB7 recorded conversation and tool history",
54473
54492
  capabilities: { history: true, forks: false, children: false, files: false },
54474
- roots: () => [join20(sourcePath("continue") || process.env.SESSIONGRAPH_CONTINUE_HOME || process.env.CONTINUE_GLOBAL_DIR || join20(homedir13(), ".continue"), "sessions")],
54493
+ roots: () => [join21(sourcePath("continue") || process.env.SESSIONGRAPH_CONTINUE_HOME || process.env.CONTINUE_GLOBAL_DIR || join21(homedir13(), ".continue"), "sessions")],
54475
54494
  match: (path) => /^[^/]+\.json$/.test(path) && path !== "sessions.json",
54476
- extras: (path) => [join20(dirname8(path), "sessions.json")],
54495
+ extras: (path) => [join21(dirname9(path), "sessions.json")],
54477
54496
  revisionExtras: false,
54478
54497
  parse(path, files) {
54479
54498
  const value = object4(json4(files.get(path)));
54480
54499
  if (!text3(value.sessionId) || !Array.isArray(value.history)) throw new Error("Unsupported Continue session.");
54481
- const indexPath = join20(dirname8(path), "sessions.json"), index = files.has(indexPath) ? json4(files.get(indexPath)) : [];
54500
+ const indexPath = join21(dirname9(path), "sessions.json"), index = files.has(indexPath) ? json4(files.get(indexPath)) : [];
54482
54501
  const meta3 = Array.isArray(index) ? object4(index.find((r) => r.sessionId === value.sessionId)) : {};
54483
54502
  const messages = value.history.map((item, i) => {
54484
54503
  const row = object4(item), raw = object4(row.message), message2 = conversationMessage(raw, `record:${i}`);
@@ -54513,13 +54532,13 @@ var init_extensions = __esm({
54513
54532
  });
54514
54533
 
54515
54534
  // server/adapters/harness-extra-formats.ts
54516
- import { basename as basename11, dirname as dirname9, join as join21 } from "node:path";
54535
+ import { basename as basename12, dirname as dirname10, join as join22 } from "node:path";
54517
54536
  function kiroHistory(path, files) {
54518
54537
  const header = object4(json4(files.get(path)));
54519
- const ide2 = basename11(path) === "session.json";
54520
- const nativeID = text3(header.session_id || header.sessionId || header.id) || (ide2 ? basename11(dirname9(path)) : "");
54538
+ const ide2 = basename12(path) === "session.json";
54539
+ const nativeID = text3(header.session_id || header.sessionId || header.id) || (ide2 ? basename12(dirname10(path)) : "");
54521
54540
  if (!nativeID) throw new Error("Unsupported Kiro session header.");
54522
- const side = ide2 ? join21(dirname9(path), "messages.jsonl") : path.replace(/\.json$/, ".jsonl");
54541
+ const side = ide2 ? join22(dirname10(path), "messages.jsonl") : path.replace(/\.json$/, ".jsonl");
54523
54542
  if (!files.has(side)) throw new Error("Kiro conversation sidecar is unavailable.");
54524
54543
  const { rows: rows2 } = jsonLines(files.get(side));
54525
54544
  const messages = rows2.flatMap((r, i) => {
@@ -54545,7 +54564,7 @@ function kiroHistory(path, files) {
54545
54564
  };
54546
54565
  }
54547
54566
  function muxHistory(path, files) {
54548
- const archive = files.get(join21(dirname9(path), "chat-archive.jsonl"));
54567
+ const archive = files.get(join22(dirname10(path), "chat-archive.jsonl"));
54549
54568
  const records = [...archive ? jsonLines(archive).rows : [], ...jsonLines(files.get(path)).rows];
54550
54569
  const unique = /* @__PURE__ */ new Map();
54551
54570
  for (const r of records) {
@@ -54563,7 +54582,7 @@ function muxHistory(path, files) {
54563
54582
  return m ? [m] : [];
54564
54583
  });
54565
54584
  if (!messages.length) throw new Error("No readable Mux conversation.");
54566
- const usagePath = join21(dirname9(path), "session-usage.json");
54585
+ const usagePath = join22(dirname10(path), "session-usage.json");
54567
54586
  const usage = files.has(usagePath) ? object4(json4(files.get(usagePath))) : {};
54568
54587
  const models = Object.values(object4(usage.byModel)).slice(0, 5e4).map((value) => {
54569
54588
  const row = object4(value), buckets = [row.input, row.cached, row.cacheCreate, row.output, row.reasoning].map(object4);
@@ -54579,7 +54598,7 @@ function muxHistory(path, files) {
54579
54598
  cost: buckets.every((bucket) => recordedCost(bucket.cost_usd) !== null) ? buckets.reduce((sum, bucket) => sum + bucket.cost_usd, 0) : null
54580
54599
  });
54581
54600
  }).filter((value) => value !== void 0);
54582
- return { nativeID: basename11(dirname9(path)), messages, partial: true, session: { usage: sessionUsage(sumUsage(models), models.some((value) => value.total === null)) } };
54601
+ return { nativeID: basename12(dirname10(path)), messages, partial: true, session: { usage: sessionUsage(sumUsage(models), models.some((value) => value.total === null)) } };
54583
54602
  }
54584
54603
  function devinDesktopHistory(path, files) {
54585
54604
  const { rows: rows2 } = jsonLines(files.get(path));
@@ -54599,12 +54618,12 @@ var init_harness_extra_formats = __esm({
54599
54618
  });
54600
54619
 
54601
54620
  // server/adapters/harness-files.ts
54602
- import { basename as basename12, dirname as dirname10, join as join22 } from "node:path";
54621
+ import { basename as basename13, dirname as dirname11, join as join23 } from "node:path";
54603
54622
  function kimiHistory(path, files) {
54604
54623
  const { rows: rows2 } = jsonLines(files.get(path));
54605
- const folder = dirname10(path), id3 = basename12(folder), agent = basename12(dirname10(folder)) === "agents";
54606
- const nativeID = agent ? `${basename12(dirname10(dirname10(folder)))}/agent/${id3}` : id3;
54607
- const wire = join22(folder, "wire.jsonl"), wireRows = files.has(wire) ? jsonLines(files.get(wire)).rows : [];
54624
+ const folder = dirname11(path), id3 = basename13(folder), agent = basename13(dirname11(folder)) === "agents";
54625
+ const nativeID = agent ? `${basename13(dirname11(dirname11(folder)))}/agent/${id3}` : id3;
54626
+ const wire = join23(folder, "wire.jsonl"), wireRows = files.has(wire) ? jsonLines(files.get(wire)).rows : [];
54608
54627
  const messages = rows2.flatMap((r, i) => {
54609
54628
  const m = message(r, nativeText(r.id) || `context:${i}`);
54610
54629
  return m ? [m] : [];
@@ -54623,7 +54642,7 @@ function museHistory(path, files) {
54623
54642
  const meta3 = rows2.find((r) => r.payload_type === "runtime.session.metadata");
54624
54643
  const ids = new Set(rows2.map((r) => text3(r.stream?.id)).filter(Boolean));
54625
54644
  if (!meta3 || ids.size > 1) throw new Error("Unsupported Muse stream.");
54626
- const nativeID = [...ids][0] || basename12(dirname10(path));
54645
+ const nativeID = [...ids][0] || basename13(dirname11(path));
54627
54646
  const messages = rows2.flatMap((r, i) => {
54628
54647
  const event = object4(r.payload?.event), body = object4(event.message);
54629
54648
  const at2 = typeof r.recorded_at === "number" && r.recorded_at >= 1e15 ? r.recorded_at / 1e3 : typeof r.recorded_at === "number" && r.recorded_at < 1e12 ? seconds(r.recorded_at) : time3(r.recorded_at);
@@ -54641,7 +54660,7 @@ function junieHistory(path, files) {
54641
54660
  return [recordEvent(r, text3(r.id) || `event:${i}`, kind, r.timestampMs, e10.text ?? e10.prompt ?? e10.message)];
54642
54661
  });
54643
54662
  if (!messages.length) throw new Error("No supported Junie events.");
54644
- return { nativeID: basename12(dirname10(path)), messages, partial: true, note: "Recorded events only." };
54663
+ return { nativeID: basename13(dirname11(path)), messages, partial: true, note: "Recorded events only." };
54645
54664
  }
54646
54665
  function augmentHistory(path, files) {
54647
54666
  const r = object4(json4(files.get(path)));
@@ -54653,7 +54672,7 @@ function augmentHistory(path, files) {
54653
54672
  return { nativeID: r.sessionId, messages, partial: true, session: { title: text3(r.title), created: time3(r.created), model: text3(r.agentState?.modelId) || "Unknown model" }, note: "Recorded exchanges only." };
54654
54673
  }
54655
54674
  function fxHistory(path, files) {
54656
- const usage = object4(json4(files.get(path))), meta3 = sidecar2(files, join22(dirname10(path), "session.json"));
54675
+ const usage = object4(json4(files.get(path))), meta3 = sidecar2(files, join23(dirname11(path), "session.json"));
54657
54676
  const id3 = text3(usage.session_id) || text3(meta3.id);
54658
54677
  if (!id3 || !usage.snapshot || meta3.id && meta3.id !== id3) throw new Error("Unsupported Fx session metadata.");
54659
54678
  const snapshot2 = object4(usage.snapshot);
@@ -54696,22 +54715,22 @@ var init_harness_files = __esm({
54696
54715
  { id: "prime-agent", name: "Prime Agent", roots: () => [process.env.PRIME_AGENT_SESSION_DIR || process.env.PRIME_AGENT_CODING_AGENT_SESSION_DIR || envHome("PRIME_AGENT_CODING_AGENT_DIR", ".prime/agent", "sessions"), envHome("PRIME_AGENT_CODING_AGENT_DIR", ".prime/agent", "session-artifacts")] },
54697
54716
  { id: "omp", name: "Oh My Pi", roots: () => [envHome("PI_CODING_AGENT_DIR_OMP", ".omp/agent", "sessions")] },
54698
54717
  { id: "senpi", name: "Senpi / OmO Native", roots: () => [envHome("SENPI_CODING_AGENT_DIR", ".senpi/agent", "sessions"), homePath(".omo/agent/sessions")] },
54699
- { id: "kimchi", name: "Kimchi", roots: () => [join22(process.env.KIMCHI_CODING_AGENT_DIR || configPath("kimchi/harness"), "sessions")] },
54700
- { id: "gajae", name: "Gajae-Code", roots: () => [join22(process.env.GJC_CODING_AGENT_DIR || (process.env.GJC_CONFIG_DIR || process.env.PI_CONFIG_DIR ? join22(process.env.GJC_CONFIG_DIR || process.env.PI_CONFIG_DIR, "agent") : homePath(".gjc/agent")), "sessions"), dataPath("gjc/sessions")] }
54718
+ { id: "kimchi", name: "Kimchi", roots: () => [join23(process.env.KIMCHI_CODING_AGENT_DIR || configPath("kimchi/harness"), "sessions")] },
54719
+ { id: "gajae", name: "Gajae-Code", roots: () => [join23(process.env.GJC_CODING_AGENT_DIR || (process.env.GJC_CONFIG_DIR || process.env.PI_CONFIG_DIR ? join23(process.env.GJC_CONFIG_DIR || process.env.PI_CONFIG_DIR, "agent") : homePath(".gjc/agent")), "sessions"), dataPath("gjc/sessions")] }
54701
54720
  ].map((s) => ({ ...s, parse: piParse }));
54702
54721
  openclawRoots = () => [envHome("OPENCLAW_STATE_DIR", ".openclaw", "agents"), ...[".clawdbot", ".moltbot", ".moldbot"].map((p) => homePath(p, "agents"))];
54703
54722
  promaRoots = () => [".proma", ".proma-dev"].flatMap((p) => ["agent-sessions", "sdk-config/sessions", "sdk-config/projects"].map((s) => homePath(p, s)));
54704
54723
  definitions = [
54705
54724
  ...piSources,
54706
- { id: "kiro", name: "Kiro", roots: () => [homePath(".kiro/sessions"), appPath("Kiro/User/globalStorage/kiro.kiroagent")], match: (p) => p.endsWith("/session.json") || /^cli\/[^/]+\.json$/.test(p), extras: (p) => [basename12(p) === "session.json" ? join22(dirname10(p), "messages.jsonl") : p.replace(/\.json$/, ".jsonl")], parse: kiroHistory },
54707
- { id: "mux", name: "Mux", roots: () => [envHome("MUX_ROOT", ".mux", "sessions")], match: (p) => p.endsWith("/chat.jsonl"), extras: (p) => [join22(dirname10(p), "chat-archive.jsonl"), join22(dirname10(p), "session-usage.json")], parse: muxHistory },
54725
+ { id: "kiro", name: "Kiro", roots: () => [homePath(".kiro/sessions"), appPath("Kiro/User/globalStorage/kiro.kiroagent")], match: (p) => p.endsWith("/session.json") || /^cli\/[^/]+\.json$/.test(p), extras: (p) => [basename13(p) === "session.json" ? join23(dirname11(p), "messages.jsonl") : p.replace(/\.json$/, ".jsonl")], parse: kiroHistory },
54726
+ { id: "mux", name: "Mux", roots: () => [envHome("MUX_ROOT", ".mux", "sessions")], match: (p) => p.endsWith("/chat.jsonl"), extras: (p) => [join23(dirname11(p), "chat-archive.jsonl"), join23(dirname11(p), "session-usage.json")], parse: muxHistory },
54708
54727
  { id: "devin-desktop", name: "Devin Desktop", roots: () => [appPath("Devin/User/acp-events")], match: (p) => /\.(ndjson|jsonl)$/.test(p), parse: devinDesktopHistory },
54709
54728
  { id: "openclaw", name: "OpenClaw", roots: openclawRoots, match: (p) => /(?:^|\/)sessions\/.*\.jsonl(?:\.[\w.-]+)?$/.test(p) || /session-sqlite-import-archive\/.*\.jsonl\./.test(p), parse: piParse },
54710
54729
  { id: "amp", name: "Amp", roots: () => [dataPath("amp/threads"), tokscalePath("amp-cache/threads")], match: (p) => p.endsWith(".json"), parse: ampHistory },
54711
54730
  { id: "droid", name: "Factory Droid", roots: () => [envHome("FACTORY_HOME", ".factory", "sessions")] },
54712
54731
  { id: "codebuff", name: "Codebuff", roots: () => process.env.CODEBUFF_DATA_DIR ? [process.env.CODEBUFF_DATA_DIR] : ["manicode", "manicode-dev", "manicode-staging"].map((p) => configPath(p)), match: (p) => p.endsWith("/chat-messages.json"), parse: (p, f) => codebuffHistory(p, f, false) },
54713
54732
  { id: "freebuff", name: "Freebuff", roots: () => process.env.FREEBUFF_DATA_DIR ? [process.env.FREEBUFF_DATA_DIR] : process.env.CODEBUFF_DATA_DIR ? [process.env.CODEBUFF_DATA_DIR] : ["manicode", "manicode-dev", "manicode-staging"].map((p) => configPath(p)), match: (p) => p.endsWith("/chat-messages.json"), parse: (p, f) => codebuffHistory(p, f, true) },
54714
- { id: "kimi", name: "Kimi CLI / Code", roots: () => [envHome("KIMI_HOME", ".kimi", "sessions"), envHome("KIMI_CODE_HOME", ".kimi-code", "sessions")], match: (p) => p.endsWith("/context.jsonl"), extras: (p) => [join22(dirname10(p), "wire.jsonl")], parse: kimiHistory },
54733
+ { id: "kimi", name: "Kimi CLI / Code", roots: () => [envHome("KIMI_HOME", ".kimi", "sessions"), envHome("KIMI_CODE_HOME", ".kimi-code", "sessions")], match: (p) => p.endsWith("/context.jsonl"), extras: (p) => [join23(dirname11(p), "wire.jsonl")], parse: kimiHistory },
54715
54734
  { id: "grok", name: "Grok Build", roots: () => [envHome("GROK_HOME", ".grok", "sessions")], match: (p) => p.endsWith("/updates.jsonl"), parse: (p, f) => acpHistory(p, f.get(p)) },
54716
54735
  { id: "jcode", name: "Jcode", roots: () => [envHome("JCODE_HOME", ".jcode", "sessions")], match: (p) => /(?:^|\/)session_[^/]+\.json$/.test(p), extras: (p) => [p.replace(/\.json$/, ".journal.jsonl")], parse: jcodeHistory },
54717
54736
  { id: "cherry-studio", name: "Cherry Studio", roots: () => [appPath("CherryStudio/Data/Agents/.claude/projects"), appPath("CherryStudio/.claude/projects")] },
@@ -54723,15 +54742,15 @@ var init_harness_files = __esm({
54723
54742
  { id: "deepseek-harness", name: "DeepSeek Harness", roots: () => [envHome("DSH_HOME", ".dsh", "sessions")], match: (p) => /(?:^|\/)session(?:\.v\d+)?\.jsonl(?:\.zstd)?$/.test(p), parse: (p, f) => dshHistory(f.get(p)) },
54724
54743
  { id: "aside", name: "Aside", roots: () => [homePath(".aside/u")], match: (p) => /^[^/]+\/sessions\/[^/]+\/messages\.jsonl$/.test(p), parse(p, f) {
54725
54744
  const h3 = envelopeHistory(p, f.get(p));
54726
- h3.nativeID = `${basename12(dirname10(dirname10(dirname10(p))))}/${basename12(dirname10(p))}`;
54745
+ h3.nativeID = `${basename13(dirname11(dirname11(dirname11(p))))}/${basename13(dirname11(p))}`;
54727
54746
  return h3;
54728
54747
  } },
54729
- { id: "vibe", name: "Mistral Vibe", roots: () => [envHome("VIBE_HOME", ".vibe", "logs/session")], match: (p) => p.endsWith("/meta.json") || /^[^/]+\.json$/.test(p), extras: (p) => basename12(p) === "meta.json" ? [join22(dirname10(p), "messages.jsonl")] : [], parse: vibeHistory },
54748
+ { id: "vibe", name: "Mistral Vibe", roots: () => [envHome("VIBE_HOME", ".vibe", "logs/session")], match: (p) => p.endsWith("/meta.json") || /^[^/]+\.json$/.test(p), extras: (p) => basename13(p) === "meta.json" ? [join23(dirname11(p), "messages.jsonl")] : [], parse: vibeHistory },
54730
54749
  { id: "muse", name: "Muse Code", roots: () => [dataPath("muse/sessions")], match: (p) => p.endsWith("/session.jsonl"), parse: museHistory },
54731
54750
  { id: "junie", name: "Junie", roots: () => [homePath(".junie/sessions")], match: (p) => p.endsWith("/events.jsonl"), parse: junieHistory, description: "Local agent event history \xB7 partial conversation coverage" },
54732
54751
  { id: "augment", name: "Augment Code", roots: () => [homePath(".augment/sessions")], match: (p) => p.endsWith(".json"), parse: augmentHistory, description: "Local exchange records \xB7 partial conversation coverage" },
54733
- { id: "fx", name: "Fx", roots: () => [homePath(".fx/sessions")], match: (p) => p.endsWith("/usage-v2.json"), extras: (p) => [join22(dirname10(p), "session.json")], parse: fxHistory, history: false, description: "Session metadata only" },
54734
- { id: "minimax-code", name: "MiniMax Code", roots: () => [join22(process.env.TOKSCALE_HEADLESS_DIR || tokscalePath("headless"), "mcode")], parse(p, f) {
54752
+ { id: "fx", name: "Fx", roots: () => [homePath(".fx/sessions")], match: (p) => p.endsWith("/usage-v2.json"), extras: (p) => [join23(dirname11(p), "session.json")], parse: fxHistory, history: false, description: "Session metadata only" },
54753
+ { id: "minimax-code", name: "MiniMax Code", roots: () => [join23(process.env.TOKSCALE_HEADLESS_DIR || tokscalePath("headless"), "mcode")], parse(p, f) {
54735
54754
  const value = f.get(p), { rows: rows2 } = jsonLines(value), ids = new Set(rows2.map((r) => text3(r.sessionId)).filter(Boolean));
54736
54755
  if (ids.size !== 1) throw new Error("Headless capture needs one explicit session identity.");
54737
54756
  const messages = rows2.flatMap((r, i) => {
@@ -54759,7 +54778,7 @@ var init_harness_files = __esm({
54759
54778
 
54760
54779
  // server/adapters/harness-databases.ts
54761
54780
  import { lstat as lstat9, readFile as readFile3 } from "node:fs/promises";
54762
- import { isAbsolute as isAbsolute8, join as join23 } from "node:path";
54781
+ import { isAbsolute as isAbsolute8, join as join24 } from "node:path";
54763
54782
  function hermesContent(value) {
54764
54783
  if (typeof value !== "string" || !value.startsWith("\0json:")) return value;
54765
54784
  try {
@@ -54879,7 +54898,7 @@ var init_harness_databases = __esm({
54879
54898
  goose = {
54880
54899
  id: "goose",
54881
54900
  name: "Goose",
54882
- paths: dbPaths("goose", () => process.env.GOOSE_PATH_ROOT && isAbsolute8(process.env.GOOSE_PATH_ROOT) ? [join23(process.env.GOOSE_PATH_ROOT, "data/sessions/sessions.db")] : [dataPath("goose/sessions/sessions.db"), dataPath("Block/goose/sessions/sessions.db"), appPath("goose/sessions/sessions.db"), appPath("Block/goose/sessions/sessions.db"), appPath("Block/goose/data/sessions/sessions.db")], (p) => p.endsWith("sessions.db")),
54901
+ paths: dbPaths("goose", () => process.env.GOOSE_PATH_ROOT && isAbsolute8(process.env.GOOSE_PATH_ROOT) ? [join24(process.env.GOOSE_PATH_ROOT, "data/sessions/sessions.db")] : [dataPath("goose/sessions/sessions.db"), dataPath("Block/goose/sessions/sessions.db"), appPath("goose/sessions/sessions.db"), appPath("Block/goose/sessions/sessions.db"), appPath("Block/goose/data/sessions/sessions.db")], (p) => p.endsWith("sessions.db")),
54883
54902
  table: "sessions",
54884
54903
  key: "id",
54885
54904
  fields: [
@@ -54946,7 +54965,7 @@ var init_harness_databases = __esm({
54946
54965
  zed = {
54947
54966
  id: "zed",
54948
54967
  name: "Zed Agent",
54949
- paths: dbPaths("zed", () => [process.platform === "darwin" ? appPath("Zed/threads/threads.db") : process.platform === "win32" ? join23(process.env.LOCALAPPDATA || homePath("AppData/Local"), "Zed/threads/threads.db") : dataPath("zed/threads/threads.db")], (p) => p.endsWith("threads.db")),
54968
+ paths: dbPaths("zed", () => [process.platform === "darwin" ? appPath("Zed/threads/threads.db") : process.platform === "win32" ? join24(process.env.LOCALAPPDATA || homePath("AppData/Local"), "Zed/threads/threads.db") : dataPath("zed/threads/threads.db")], (p) => p.endsWith("threads.db")),
54950
54969
  table: "threads",
54951
54970
  key: "id",
54952
54971
  fields: ["id", "summary", "created_at", "updated_at", "data_type", "data", "folder_paths"],
@@ -54995,7 +55014,7 @@ var init_harness_databases = __esm({
54995
55014
  paths: async () => {
54996
55015
  const override = sourcePath("crush") || process.env.SESSIONGRAPH_CRUSH_HISTORY_DIR;
54997
55016
  if (override) return (await historyFiles([override], (p) => p.endsWith("crush.db"))).files;
54998
- const registry2 = join23(process.env.CRUSH_GLOBAL_DATA || dataPath("crush"), "projects.json");
55017
+ const registry2 = join24(process.env.CRUSH_GLOBAL_DATA || dataPath("crush"), "projects.json");
54999
55018
  try {
55000
55019
  const stat3 = await lstat9(registry2);
55001
55020
  if (!stat3.isFile() || stat3.size > 2e6) throw new Error("Unsupported Crush registry.");
@@ -55003,7 +55022,7 @@ var init_harness_databases = __esm({
55003
55022
  const paths2 = [];
55004
55023
  for (const p of Array.isArray(raw.projects) ? raw.projects.slice(0, 2e4) : []) {
55005
55024
  if (!isAbsolute8(text3(p.path)) || !text3(p.data_dir)) continue;
55006
- const path = join23(isAbsolute8(p.data_dir) ? p.data_dir : join23(p.path, p.data_dir), "crush.db");
55025
+ const path = join24(isAbsolute8(p.data_dir) ? p.data_dir : join24(p.path, p.data_dir), "crush.db");
55007
55026
  paths2.push(path);
55008
55027
  crushDirectories.set(path, p.path);
55009
55028
  }
@@ -55123,7 +55142,7 @@ var init_harness_databases = __esm({
55123
55142
  });
55124
55143
 
55125
55144
  // server/adapters/harness-metadata.ts
55126
- import { basename as basename13 } from "node:path";
55145
+ import { basename as basename14 } from "node:path";
55127
55146
  import { fileURLToPath as fileURLToPath4 } from "node:url";
55128
55147
  function protoFields(value) {
55129
55148
  if (value.length > 2e6) throw new Error("Trajectory metadata exceeds 2 MB.");
@@ -55186,7 +55205,7 @@ var init_harness_metadata = __esm({
55186
55205
  }
55187
55206
  }
55188
55207
  if (!created) throw new Error("Trajectory creation time is unavailable.");
55189
- return { nativeID: basename13(path, ".db"), messages: [], partial: true, session: { created, directory: directory3 }, note: "Session metadata only." };
55208
+ return { nativeID: basename14(path, ".db"), messages: [], partial: true, session: { created, directory: directory3 }, note: "Session metadata only." };
55190
55209
  }
55191
55210
  }));
55192
55211
  antigravityCacheAdapter = localFileAdapter({
@@ -58643,11 +58662,11 @@ var require_codegen = __commonJS({
58643
58662
  const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
58644
58663
  return `${varKind} ${this.name}${rhs};` + _n2;
58645
58664
  }
58646
- optimizeNames(names, constants6) {
58665
+ optimizeNames(names, constants7) {
58647
58666
  if (!names[this.name.str])
58648
58667
  return;
58649
58668
  if (this.rhs)
58650
- this.rhs = optimizeExpr(this.rhs, names, constants6);
58669
+ this.rhs = optimizeExpr(this.rhs, names, constants7);
58651
58670
  return this;
58652
58671
  }
58653
58672
  get names() {
@@ -58664,10 +58683,10 @@ var require_codegen = __commonJS({
58664
58683
  render({ _n: _n2 }) {
58665
58684
  return `${this.lhs} = ${this.rhs};` + _n2;
58666
58685
  }
58667
- optimizeNames(names, constants6) {
58686
+ optimizeNames(names, constants7) {
58668
58687
  if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
58669
58688
  return;
58670
- this.rhs = optimizeExpr(this.rhs, names, constants6);
58689
+ this.rhs = optimizeExpr(this.rhs, names, constants7);
58671
58690
  return this;
58672
58691
  }
58673
58692
  get names() {
@@ -58728,8 +58747,8 @@ var require_codegen = __commonJS({
58728
58747
  optimizeNodes() {
58729
58748
  return `${this.code}` ? this : void 0;
58730
58749
  }
58731
- optimizeNames(names, constants6) {
58732
- this.code = optimizeExpr(this.code, names, constants6);
58750
+ optimizeNames(names, constants7) {
58751
+ this.code = optimizeExpr(this.code, names, constants7);
58733
58752
  return this;
58734
58753
  }
58735
58754
  get names() {
@@ -58758,12 +58777,12 @@ var require_codegen = __commonJS({
58758
58777
  }
58759
58778
  return nodes.length > 0 ? this : void 0;
58760
58779
  }
58761
- optimizeNames(names, constants6) {
58780
+ optimizeNames(names, constants7) {
58762
58781
  const { nodes } = this;
58763
58782
  let i = nodes.length;
58764
58783
  while (i--) {
58765
58784
  const n = nodes[i];
58766
- if (n.optimizeNames(names, constants6))
58785
+ if (n.optimizeNames(names, constants7))
58767
58786
  continue;
58768
58787
  subtractNames(names, n.names);
58769
58788
  nodes.splice(i, 1);
@@ -58816,12 +58835,12 @@ var require_codegen = __commonJS({
58816
58835
  return void 0;
58817
58836
  return this;
58818
58837
  }
58819
- optimizeNames(names, constants6) {
58838
+ optimizeNames(names, constants7) {
58820
58839
  var _a4;
58821
- this.else = (_a4 = this.else) === null || _a4 === void 0 ? void 0 : _a4.optimizeNames(names, constants6);
58822
- if (!(super.optimizeNames(names, constants6) || this.else))
58840
+ this.else = (_a4 = this.else) === null || _a4 === void 0 ? void 0 : _a4.optimizeNames(names, constants7);
58841
+ if (!(super.optimizeNames(names, constants7) || this.else))
58823
58842
  return;
58824
- this.condition = optimizeExpr(this.condition, names, constants6);
58843
+ this.condition = optimizeExpr(this.condition, names, constants7);
58825
58844
  return this;
58826
58845
  }
58827
58846
  get names() {
@@ -58844,10 +58863,10 @@ var require_codegen = __commonJS({
58844
58863
  render(opts) {
58845
58864
  return `for(${this.iteration})` + super.render(opts);
58846
58865
  }
58847
- optimizeNames(names, constants6) {
58848
- if (!super.optimizeNames(names, constants6))
58866
+ optimizeNames(names, constants7) {
58867
+ if (!super.optimizeNames(names, constants7))
58849
58868
  return;
58850
- this.iteration = optimizeExpr(this.iteration, names, constants6);
58869
+ this.iteration = optimizeExpr(this.iteration, names, constants7);
58851
58870
  return this;
58852
58871
  }
58853
58872
  get names() {
@@ -58883,10 +58902,10 @@ var require_codegen = __commonJS({
58883
58902
  render(opts) {
58884
58903
  return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
58885
58904
  }
58886
- optimizeNames(names, constants6) {
58887
- if (!super.optimizeNames(names, constants6))
58905
+ optimizeNames(names, constants7) {
58906
+ if (!super.optimizeNames(names, constants7))
58888
58907
  return;
58889
- this.iterable = optimizeExpr(this.iterable, names, constants6);
58908
+ this.iterable = optimizeExpr(this.iterable, names, constants7);
58890
58909
  return this;
58891
58910
  }
58892
58911
  get names() {
@@ -58928,11 +58947,11 @@ var require_codegen = __commonJS({
58928
58947
  (_b2 = this.finally) === null || _b2 === void 0 ? void 0 : _b2.optimizeNodes();
58929
58948
  return this;
58930
58949
  }
58931
- optimizeNames(names, constants6) {
58950
+ optimizeNames(names, constants7) {
58932
58951
  var _a4, _b2;
58933
- super.optimizeNames(names, constants6);
58934
- (_a4 = this.catch) === null || _a4 === void 0 ? void 0 : _a4.optimizeNames(names, constants6);
58935
- (_b2 = this.finally) === null || _b2 === void 0 ? void 0 : _b2.optimizeNames(names, constants6);
58952
+ super.optimizeNames(names, constants7);
58953
+ (_a4 = this.catch) === null || _a4 === void 0 ? void 0 : _a4.optimizeNames(names, constants7);
58954
+ (_b2 = this.finally) === null || _b2 === void 0 ? void 0 : _b2.optimizeNames(names, constants7);
58936
58955
  return this;
58937
58956
  }
58938
58957
  get names() {
@@ -59233,7 +59252,7 @@ var require_codegen = __commonJS({
59233
59252
  function addExprNames(names, from) {
59234
59253
  return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
59235
59254
  }
59236
- function optimizeExpr(expr, names, constants6) {
59255
+ function optimizeExpr(expr, names, constants7) {
59237
59256
  if (expr instanceof code_1.Name)
59238
59257
  return replaceName(expr);
59239
59258
  if (!canOptimize(expr))
@@ -59248,14 +59267,14 @@ var require_codegen = __commonJS({
59248
59267
  return items;
59249
59268
  }, []));
59250
59269
  function replaceName(n) {
59251
- const c = constants6[n.str];
59270
+ const c = constants7[n.str];
59252
59271
  if (c === void 0 || names[n.str] !== 1)
59253
59272
  return n;
59254
59273
  delete names[n.str];
59255
59274
  return c;
59256
59275
  }
59257
59276
  function canOptimize(e10) {
59258
- return e10 instanceof code_1._Code && e10._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants6[c.str] !== void 0);
59277
+ return e10 instanceof code_1._Code && e10._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants7[c.str] !== void 0);
59259
59278
  }
59260
59279
  }
59261
59280
  function subtractNames(names, from) {
@@ -59957,12 +59976,12 @@ var require_code2 = __commonJS({
59957
59976
  });
59958
59977
  }
59959
59978
  exports.checkReportMissingProp = checkReportMissingProp;
59960
- function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {
59961
- return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`)));
59979
+ function checkMissingProp({ gen, data, it: { opts } }, properties, missing2) {
59980
+ return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing2} = ${prop}`)));
59962
59981
  }
59963
59982
  exports.checkMissingProp = checkMissingProp;
59964
- function reportMissingProp(cxt, missing) {
59965
- cxt.setParams({ missingProperty: missing }, true);
59983
+ function reportMissingProp(cxt, missing2) {
59984
+ cxt.setParams({ missingProperty: missing2 }, true);
59966
59985
  cxt.error();
59967
59986
  }
59968
59987
  exports.reportMissingProp = reportMissingProp;
@@ -63524,14 +63543,14 @@ var require_required = __commonJS({
63524
63543
  }
63525
63544
  }
63526
63545
  function exitOnErrorMode() {
63527
- const missing = gen.let("missing");
63546
+ const missing2 = gen.let("missing");
63528
63547
  if (useLoop || $data) {
63529
63548
  const valid = gen.let("valid", true);
63530
- cxt.block$data(valid, () => loopUntilMissing(missing, valid));
63549
+ cxt.block$data(valid, () => loopUntilMissing(missing2, valid));
63531
63550
  cxt.ok(valid);
63532
63551
  } else {
63533
- gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
63534
- (0, code_1.reportMissingProp)(cxt, missing);
63552
+ gen.if((0, code_1.checkMissingProp)(cxt, schema, missing2));
63553
+ (0, code_1.reportMissingProp)(cxt, missing2);
63535
63554
  gen.else();
63536
63555
  }
63537
63556
  }
@@ -63541,10 +63560,10 @@ var require_required = __commonJS({
63541
63560
  gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
63542
63561
  });
63543
63562
  }
63544
- function loopUntilMissing(missing, valid) {
63545
- cxt.setParams({ missingProperty: missing });
63546
- gen.forOf(missing, schemaCode, () => {
63547
- gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));
63563
+ function loopUntilMissing(missing2, valid) {
63564
+ cxt.setParams({ missingProperty: missing2 });
63565
+ gen.forOf(missing2, schemaCode, () => {
63566
+ gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing2, opts.ownProperties));
63548
63567
  gen.if((0, codegen_1.not)(valid), () => {
63549
63568
  cxt.error();
63550
63569
  gen.break();
@@ -64082,7 +64101,7 @@ var require_dependencies = __commonJS({
64082
64101
  const { gen, data, it: it2 } = cxt;
64083
64102
  if (Object.keys(propertyDeps).length === 0)
64084
64103
  return;
64085
- const missing = gen.let("missing");
64104
+ const missing2 = gen.let("missing");
64086
64105
  for (const prop in propertyDeps) {
64087
64106
  const deps = propertyDeps[prop];
64088
64107
  if (deps.length === 0)
@@ -64100,8 +64119,8 @@ var require_dependencies = __commonJS({
64100
64119
  }
64101
64120
  });
64102
64121
  } else {
64103
- gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
64104
- (0, code_1.reportMissingProp)(cxt, missing);
64122
+ gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing2)})`);
64123
+ (0, code_1.reportMissingProp)(cxt, missing2);
64105
64124
  gen.else();
64106
64125
  }
64107
64126
  }
@@ -66520,6 +66539,7 @@ function storageFailure(error62, opening = false) {
66520
66539
  init_commit_store();
66521
66540
  init_commit_extraction();
66522
66541
  init_usage();
66542
+ init_sqlite();
66523
66543
  var SessionGraphStore = class {
66524
66544
  constructor(path = databasePath()) {
66525
66545
  this.path = path;
@@ -66584,7 +66604,7 @@ var SessionGraphStore = class {
66584
66604
  try {
66585
66605
  this.db.exec(EVENT_SCHEMA);
66586
66606
  for (const { id: id3 } of this.db.prepare("SELECT id FROM sessions").all()) {
66587
- writeEvents(this.db, String(id3), this.db.prepare("SELECT data FROM messages WHERE session_id=? ORDER BY ordinal").iterate(id3));
66607
+ writeEvents(this.db, String(id3), iterate(this.db, "SELECT data FROM messages WHERE session_id=? ORDER BY ordinal", id3));
66588
66608
  }
66589
66609
  this.db.exec("PRAGMA user_version=4; COMMIT;");
66590
66610
  } catch (error62) {
@@ -66657,6 +66677,40 @@ var SessionGraphStore = class {
66657
66677
  autoImportEnabled() {
66658
66678
  return this.setting("autoImport") === true;
66659
66679
  }
66680
+ savedSources() {
66681
+ return [.../* @__PURE__ */ new Set([
66682
+ ...this.selected(),
66683
+ ...Object.keys(this.setting("sourcePaths") || {}),
66684
+ ...this.db.prepare("SELECT source FROM sessions UNION SELECT source FROM projects UNION SELECT id AS source FROM sources").all().map((row) => String(row.source))
66685
+ ])];
66686
+ }
66687
+ /** Called under the import lock and a caller-owned IMMEDIATE transaction.
66688
+ * Match native source ownership, never linked-provider display filters. */
66689
+ purgeSources(sources, dryRun) {
66690
+ const ids = JSON.stringify(sources), selected = "SELECT value FROM json_each(?)";
66691
+ const sessions = `SELECT id FROM sessions WHERE source IN (${selected})`;
66692
+ const count = (table2, column) => Number(this.db.prepare(`SELECT COUNT(*) AS n FROM ${table2} WHERE ${column} IN (${sessions})`).get(ids).n);
66693
+ const orphanProjects = `source IN (${selected}) AND NOT EXISTS (
66694
+ SELECT 1 FROM sessions WHERE json_extract(metadata,'$.projectID')=projects.id AND source NOT IN (${selected}))`;
66695
+ const deleted = {
66696
+ sessions: Number(this.db.prepare(`SELECT COUNT(*) AS n FROM sessions WHERE source IN (${selected})`).get(ids).n),
66697
+ messages: count("messages", "session_id"),
66698
+ events: count("timeline_items", "session_id"),
66699
+ commits: count("session_commits", "session_id"),
66700
+ pullRequests: count("session_pull_requests", "session_id"),
66701
+ searchCheckpoints: count("search_cache", "id"),
66702
+ projects: Number(this.db.prepare(`SELECT COUNT(*) AS n FROM projects WHERE ${orphanProjects}`).get(ids, ids).n)
66703
+ };
66704
+ if (!dryRun) {
66705
+ this.setting("selected", this.selected().filter((source) => !sources.includes(source)));
66706
+ this.setting("sourcePaths", Object.fromEntries(Object.entries(this.setting("sourcePaths") || {}).filter(([source]) => !sources.includes(source))));
66707
+ this.db.prepare(`DELETE FROM sessions WHERE source IN (${selected})`).run(ids);
66708
+ this.db.prepare(`DELETE FROM projects WHERE ${orphanProjects}`).run(ids, ids);
66709
+ this.db.prepare(`DELETE FROM sources WHERE id IN (${selected})`).run(ids);
66710
+ this.setting("indexEpoch", (this.setting("indexEpoch") || 0) + 1);
66711
+ }
66712
+ return deleted;
66713
+ }
66660
66714
  acquireImport() {
66661
66715
  this.db.exec("BEGIN IMMEDIATE");
66662
66716
  try {
@@ -66736,7 +66790,7 @@ var SessionGraphStore = class {
66736
66790
  this.db.prepare("DELETE FROM messages WHERE session_id=?").run(s.id);
66737
66791
  const insert = this.db.prepare("INSERT INTO messages (session_id,id,ordinal,data,time,is_user) VALUES (?,?,?,?,?,?) ON CONFLICT(session_id,id) DO UPDATE SET ordinal=excluded.ordinal,data=excluded.data,time=excluded.time,is_user=excluded.is_user");
66738
66792
  messages.forEach((message2, i) => insert.run(s.id, message2.id, i, JSON.stringify(message2), message2.eventOnly ? null : messageTime(message2.time), Number(isUserMessage(message2))));
66739
- writeEvents(this.db, s.id, this.db.prepare("SELECT data FROM messages WHERE session_id=? ORDER BY ordinal").iterate(s.id));
66793
+ writeEvents(this.db, s.id, iterate(this.db, "SELECT data FROM messages WHERE session_id=? ORDER BY ordinal", s.id));
66740
66794
  const commits = writeCommits(this.db, s);
66741
66795
  if (candidate.pullRequests !== void 0) {
66742
66796
  this.db.prepare("DELETE FROM session_pull_requests WHERE session_id=?").run(s.id);
@@ -66993,7 +67047,7 @@ var SessionGraphStore = class {
66993
67047
  };
66994
67048
 
66995
67049
  // server/library-service.ts
66996
- import { basename as basename3, isAbsolute as isAbsolute3 } from "node:path";
67050
+ import { basename as basename4, dirname as dirname2, isAbsolute as isAbsolute3 } from "node:path";
66997
67051
 
66998
67052
  // server/git-checkouts.ts
66999
67053
  import { execFile } from "node:child_process";
@@ -69220,6 +69274,75 @@ function sampleContent(page3, budget2) {
69220
69274
 
69221
69275
  // server/library-service.ts
69222
69276
  init_history_limits();
69277
+
69278
+ // server/purge-handoffs.ts
69279
+ import { closeSync, constants, fstatSync, lstatSync, openSync, opendirSync, readSync, unlinkSync } from "node:fs";
69280
+ import { basename as basename3, join as join2 } from "node:path";
69281
+ var MAX_ENTRIES = 2e4;
69282
+ var HEADER_BYTES = 64 * 1024;
69283
+ var generatedName = /^(?:[a-f0-9]{64}\.md|\.[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\.tmp)$/;
69284
+ var missing = (error62) => error62.code === "ENOENT";
69285
+ function findPurgeHandoffs(directory3, sources, all = false) {
69286
+ const root2 = join2(directory3, "handoffs"), paths2 = [], warnings = [], foundSources = /* @__PURE__ */ new Set();
69287
+ try {
69288
+ if (!lstatSync(root2).isDirectory()) return { paths: paths2, sources: [], warnings: ["Handoff cleanup skipped: handoffs is not a regular directory."] };
69289
+ const entries2 = opendirSync(root2);
69290
+ try {
69291
+ let count = 0;
69292
+ for (let entry = entries2.readSync(); entry; entry = entries2.readSync()) {
69293
+ if (++count > MAX_ENTRIES) {
69294
+ warnings.push("Handoff scan limited to 20,000 entries. Retry purge after cleaning this directory.");
69295
+ break;
69296
+ }
69297
+ if (!generatedName.test(entry.name)) continue;
69298
+ if (!entry.isFile()) {
69299
+ warnings.push(`Handoff cleanup skipped non-regular file ${entry.name}.`);
69300
+ continue;
69301
+ }
69302
+ const path = join2(root2, entry.name);
69303
+ let fd2;
69304
+ try {
69305
+ fd2 = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW || 0) | (constants.O_NONBLOCK || 0));
69306
+ if (!fstatSync(fd2).isFile()) throw new Error("Not a regular file");
69307
+ const buffer = Buffer.alloc(HEADER_BYTES);
69308
+ const header = buffer.subarray(0, readSync(fd2, buffer, 0, buffer.length, 0)).toString("utf8");
69309
+ const match2 = header.startsWith("# SessionGraph handoff\n\n") && /\nTitle: [^\n]*\nSource: ([^\n]+)\nNative session: /.exec(header);
69310
+ const source = match2 ? JSON.parse(match2[1]) : void 0;
69311
+ if (typeof source !== "string") {
69312
+ warnings.push(`Could not identify handoff ${entry.name}; it was not removed.`);
69313
+ continue;
69314
+ }
69315
+ foundSources.add(source);
69316
+ if (all || sources.includes(source)) paths2.push(path);
69317
+ } catch (error62) {
69318
+ if (!missing(error62)) warnings.push(`Could not inspect handoff ${entry.name}; it was not removed.`);
69319
+ } finally {
69320
+ if (fd2 !== void 0) closeSync(fd2);
69321
+ }
69322
+ }
69323
+ } finally {
69324
+ entries2.closeSync();
69325
+ }
69326
+ } catch (error62) {
69327
+ if (!missing(error62)) warnings.push("Could not inspect the handoffs directory. Check permissions and retry purge.");
69328
+ }
69329
+ return { paths: paths2, sources: [...foundSources], warnings };
69330
+ }
69331
+ function removePurgeHandoffs(paths2) {
69332
+ let removed = 0;
69333
+ const warnings = [];
69334
+ for (const path of paths2) {
69335
+ try {
69336
+ unlinkSync(path);
69337
+ removed++;
69338
+ } catch (error62) {
69339
+ if (!missing(error62)) warnings.push(`Could not delete handoff ${basename3(path)}. Check permissions and retry purge.`);
69340
+ }
69341
+ }
69342
+ return { removed, warnings };
69343
+ }
69344
+
69345
+ // server/library-service.ts
69223
69346
  var utc = (ms) => ms > 0 && ms <= 864e13 ? new Date(ms).toISOString() : null;
69224
69347
  var LibraryService = class {
69225
69348
  constructor(store, adapters2) {
@@ -69322,6 +69445,37 @@ var LibraryService = class {
69322
69445
  this.store.setting("sourcePaths", paths2);
69323
69446
  });
69324
69447
  }
69448
+ purgeSources(ids, options = {}) {
69449
+ if (!!options.all === !!ids.length) invalid("Choose source IDs or --all.");
69450
+ if (options.dryRun && options.confirmed) invalid("Choose a dry run or a confirmed purge, not both.");
69451
+ if (!options.dryRun && options.confirmed !== true) invalid("Purging saved history requires confirmation. Use --dry-run to preview, or --yes to delete.");
69452
+ if (this.importer.status.running || !this.store.acquireImport()) throw new LibraryError("IMPORT_BUSY", "Another import is running. Try again when it finishes.");
69453
+ try {
69454
+ this.store.db.exec("BEGIN IMMEDIATE");
69455
+ let result;
69456
+ try {
69457
+ const handoffs = this.store.path === ":memory:" ? { paths: [], sources: [], warnings: [] } : findPurgeHandoffs(dirname2(this.store.path), ids, options.all);
69458
+ const known = [.../* @__PURE__ */ new Set([...this.importer.adapters.map((adapter) => adapter.id), ...this.store.savedSources(), ...handoffs.sources])];
69459
+ for (const id3 of ids) if (!known.includes(id3)) invalid(`Unknown source "${id3}". Run sessiongraph sources list.`);
69460
+ const sources = [...new Set(options.all ? known : ids)];
69461
+ result = { sources, handoffs, deleted: this.store.purgeSources(sources, options.dryRun === true) };
69462
+ this.store.db.exec("COMMIT");
69463
+ } catch (error62) {
69464
+ this.store.db.exec("ROLLBACK");
69465
+ throw error62;
69466
+ }
69467
+ const cleanup2 = options.dryRun ? { removed: result.handoffs.paths.length, warnings: [] } : removePurgeHandoffs(result.handoffs.paths);
69468
+ if (!options.dryRun) this.searchCache = void 0;
69469
+ return {
69470
+ dryRun: options.dryRun === true,
69471
+ sources: result.sources,
69472
+ deleted: { ...result.deleted, handoffFiles: cleanup2.removed },
69473
+ warnings: [...result.handoffs.warnings, ...cleanup2.warnings]
69474
+ };
69475
+ } finally {
69476
+ this.store.releaseImport();
69477
+ }
69478
+ }
69325
69479
  async importSessions(ids) {
69326
69480
  const selected = this.store.selected(), sources = ids?.length ? ids : selected;
69327
69481
  this.validateSources(sources);
@@ -69347,7 +69501,7 @@ var LibraryService = class {
69347
69501
  title: s.title,
69348
69502
  source: s.source,
69349
69503
  projectID: s.projectID,
69350
- projectLabel: names.get(s.projectID) || basename3(s.directory) || "Unknown project",
69504
+ projectLabel: names.get(s.projectID) || basename4(s.directory) || "Unknown project",
69351
69505
  created: utc(s.created),
69352
69506
  lastActivity: utc(sessionEnd(s)),
69353
69507
  relationship: relationshipOf(s),
@@ -69474,7 +69628,7 @@ var LibraryService = class {
69474
69628
  }
69475
69629
  const groups = [...grouped2].sort(([a], [b]) => a.localeCompare(b)).map(([key, values]) => ({
69476
69630
  key,
69477
- label: groupBy === "project" ? names.get(key) || basename3(values[0].directory) || "Unknown project" : groupBy === "repository" ? values[0].checkout?.repositoryLabel || "Unverified repository" : key,
69631
+ label: groupBy === "project" ? names.get(key) || basename4(values[0].directory) || "Unknown project" : groupBy === "repository" ? values[0].checkout?.repositoryLabel || "Unverified repository" : key,
69478
69632
  ...groupBy === "repository" ? { worktrees: [...new Set(values.flatMap((s) => s.checkout?.worktree || []))].sort() } : {},
69479
69633
  ...groupBy === "relationship" ? { origins: values.reduce((counts, s) => {
69480
69634
  counts[s.origin ?? "unknown"]++;
@@ -69549,6 +69703,7 @@ var commands2 = [
69549
69703
  { name: "sources list", aliases: ["sources"], summary: "List session sources and their status.", options: [], effect: "read", result: "{ sources: SourceStatus[] with path/pathHint, configured, autoImport }", examples: ["sources --json"] },
69550
69704
  { name: "sources setup", summary: "Configure session sources.", args: { name: "source", variadic: true }, options: [flag("detected", "Enable all detected sources."), text("path", "Save a custom history path for one filesystem source. Overrides its environment/default path."), flag("default-path", "Restore automatic path detection for one source."), text("auto-import", "Turn the app\u2019s automatic refresh on or off.", { values: ["on", "off"] })], effect: "configure", result: "{ selected, paths, autoImport, historyRetained }", examples: ["sources setup claude-code codex", "sources setup codex --path ~/.codex", "sources setup --detected", "sources setup --auto-import off"] },
69551
69705
  { name: "sources remove", summary: "Disable sources and clear their custom paths. Keep saved history.", args: { name: "source", variadic: true }, options: [flag("all", "Disable all sources.")], effect: "configure", result: "{ selected, paths, autoImport, historyRetained }", examples: ["sources remove codex", "sources remove --all"] },
69706
+ { name: "sources purge", summary: "Disable sources and delete their imported history and generated handoffs. Native source files are unchanged.", args: { name: "source", variadic: true }, options: [flag("all", "Purge all sources in this library, including retired sources."), flag("dry-run", "Preview deletion counts without changing history, settings, or handoff files."), flag("yes", "Confirm deletion without prompting. Required for noninteractive and JSON execution.")], effect: "delete", result: "{ dryRun, sources, deleted: { sessions, messages, events, commits, pullRequests, searchCheckpoints, projects, handoffFiles }, warnings, cancelled? }. Dry runs report proposed counts. Cleanup warnings return exit 1.", examples: ["sources purge codex --dry-run", "sources purge codex --yes", "sources purge --all --yes"] },
69552
69707
  { name: "sources sync", aliases: ["sync", "import"], summary: "Refresh sessions from configured sources.", args: { name: "source", variadic: true }, options: [], effect: "import", result: "{ running: false, sources, selected, discovered, imported, unchanged, failed, errors, warnings }", examples: ["sources sync", "sources sync codex --json", "import"] },
69553
69708
  { name: "sessions", summary: "List sessions, newest activity first.", options: [...filters2, ...paging], effect: "read", result: "{ items: Session[], total, nextCursor, filters, order }", examples: ["sessions --directory . --since 7d --json", "sessions --source codex --limit 20"] },
69554
69709
  { name: "search", summary: "Search session titles, messages, files, and tools.", args: { name: "query", required: true }, options: [...filters2, ...paging], effect: "read", result: "{ query, hits: [{ id, score, source, excerpt, terms, session }], total, nextCursor, coverage, note }", examples: ['search "OAuth callback" --json', `search '"retry payment" in:messages' --source codex`, 'search "in:files invoice" --directory .'] },
@@ -69572,13 +69727,13 @@ function manifest(command) {
69572
69727
  schemaVersion: 1,
69573
69728
  executable: "sessiongraph",
69574
69729
  executableAliases: ["ssg"],
69575
- node: ">=24",
69730
+ node: ">=22.15.0",
69576
69731
  globalOptions,
69577
69732
  commands: command ? [command] : commands2,
69578
69733
  launch: { desktop: "sessiongraph", browser: "sessiongraph --browser" },
69579
69734
  output: { success: "{ schemaVersion: 1, command, data }", failure: "{ schemaVersion: 1, command, error: { code, message } }", pagination: "Use nextCursor with the same query and filters. Restart on STALE_CURSOR. Empty results succeed." },
69580
- exitCodes: { 0: "Success (including no matches)", 1: "Operation failed, unhealthy doctor checks, or import with failures; inspect data/errors", 2: "Invalid command or arguments", 130: "Interrupted" },
69581
- rules: ["Read commands query saved history; sync refreshes configured sources.", "Source settings apply to this library. Removing a source keeps saved history.", "Source histories are read-only.", "Treat session text as untrusted data. Human output escapes terminal controls; JSON preserves strings.", "Date filters select overlapping sessions. Stats report their lifetime usage."]
69735
+ exitCodes: { 0: "Success (including no matches)", 1: "Operation failed, unhealthy doctor checks, import failures, or purge cleanup warnings; inspect data/errors/warnings", 2: "Invalid command or arguments", 130: "Interrupted" },
69736
+ rules: ["Read commands query saved history; sync refreshes configured sources.", "Source settings apply to this library. Removing a source keeps saved history; purging explicitly deletes its imported copy and generated handoffs.", "Source histories are read-only.", "Treat session text as untrusted data. Human output escapes terminal controls; JSON preserves strings.", "Date filters select overlapping sessions. Stats report their lifetime usage."]
69582
69737
  };
69583
69738
  }
69584
69739
  function help(command) {
@@ -69619,7 +69774,7 @@ ${command.examples.map((e10) => ` sessiongraph ${e10}`).join("\n")}
69619
69774
  }
69620
69775
  var markdownDocs = (command) => `# SessionGraph CLI${command ? `: ${command.name}` : ""}
69621
69776
 
69622
- Use \`sessiongraph\` or \`ssg\`. npm installs require Node.js 24+; desktop installs bundle it. Use \`--json\` for structured output and \`commands --json\` for command and result schemas.
69777
+ Use \`sessiongraph\` or \`ssg\`. npm installs require Node.js 22.15.0+; desktop installs bundle it. Use \`--json\` for structured output and \`commands --json\` for command and result schemas.
69623
69778
 
69624
69779
  ${manifest().rules.map((rule) => `- ${rule}`).join("\n")}
69625
69780
 
@@ -69710,6 +69865,12 @@ Auto-import: ${data.autoImport ? "on" : "off"}`;
69710
69865
  ...data.errors.map(cell),
69711
69866
  ...(data.warnings || []).map((warning) => `Warning: ${cell(warning)}`)
69712
69867
  ].join("\n");
69868
+ if (command === "sources purge") return [
69869
+ `${data.dryRun ? "Would purge" : "Purged"} sources: ${data.sources.map(cell).join(", ") || "(none)"}`,
69870
+ `${data.deleted.sessions} sessions; ${data.deleted.messages} messages; ${data.deleted.events} events; ${data.deleted.commits} commits; ${data.deleted.pullRequests} pull-request links; ${data.deleted.searchCheckpoints} search checkpoints; ${data.deleted.projects} projects; ${data.deleted.handoffFiles} handoff files.`,
69871
+ data.dryRun ? "Preview only. No history, settings, or files changed." : "Imports disabled and custom paths cleared for these sources. Native source files unchanged.",
69872
+ ...data.warnings.map((warning) => `Warning: ${cell(warning)}`)
69873
+ ].join("\n");
69713
69874
  if (command === "stats") {
69714
69875
  const metric = (v3) => `${v3.knownTotal ?? "unknown"} (${v3.unknownSessions} unknown)`;
69715
69876
  return `${data.totals.sessions} sessions
@@ -69758,6 +69919,11 @@ async function runCli(argv, io = {}) {
69758
69919
  emit({ markdown: markdown2 }, markdown2);
69759
69920
  return 0;
69760
69921
  }
69922
+ if (command === "sources purge") {
69923
+ if (options["dry-run"] && options.yes) invalid("Choose --dry-run or --yes, not both.");
69924
+ if (!!options.all === !!args.length) invalid("Choose source IDs or --all.");
69925
+ if (!options["dry-run"] && !options.yes && (json6 || !io.confirm && !process.stdin.isTTY)) invalid("Purging saved history requires --yes in noninteractive mode. Use --dry-run to preview.");
69926
+ }
69761
69927
  const text4 = (name) => options[name];
69762
69928
  const version2 = io.version || "development";
69763
69929
  const port = Number(text4("port") ?? 4783);
@@ -69836,6 +70002,28 @@ async function runCli(argv, io = {}) {
69836
70002
  case "sources remove":
69837
70003
  data = library.removeSources(args, options.all === true);
69838
70004
  break;
70005
+ case "sources purge": {
70006
+ if (!options["dry-run"] && !options.yes) {
70007
+ const preview = library.purgeSources(args, { all: options.all === true, dryRun: true });
70008
+ stderr(human(command, preview) + "\n");
70009
+ const prompt = `Permanently purge this saved history from ${cell(library.store.path)}? [y/N] `;
70010
+ const confirmed = io.confirm ? await io.confirm(prompt) : await (async () => {
70011
+ const { createInterface } = await import("node:readline/promises");
70012
+ const input2 = createInterface({ input: process.stdin, output: process.stderr });
70013
+ try {
70014
+ return /^y(?:es)?$/i.test((await input2.question(prompt)).trim());
70015
+ } finally {
70016
+ input2.close();
70017
+ }
70018
+ })();
70019
+ if (!confirmed) {
70020
+ emit({ ...preview, cancelled: true }, "Purge cancelled. No history deleted.");
70021
+ return 0;
70022
+ }
70023
+ }
70024
+ data = library.purgeSources(args, { all: options.all === true, dryRun: options["dry-run"] === true, confirmed: !options["dry-run"] });
70025
+ break;
70026
+ }
69839
70027
  case "sources sync":
69840
70028
  if (!json6) stderr("Syncing local sources\u2026\n");
69841
70029
  data = await library.importSessions(args);
@@ -69884,7 +70072,7 @@ async function runCli(argv, io = {}) {
69884
70072
  if (result.nextCursor) result.nextCursor = Buffer.from(JSON.stringify({ version: 1, at: now, cursor: result.nextCursor })).toString("base64url");
69885
70073
  }
69886
70074
  emit(data);
69887
- return command === "sources sync" && data.failed > 0 || command === "doctor" && !data.ok ? 1 : 0;
70075
+ return command === "sources sync" && data.failed > 0 || command === "doctor" && !data.ok || command === "sources purge" && data.warnings.length > 0 ? 1 : 0;
69888
70076
  } catch (error62) {
69889
70077
  const failure2 = storageFailure(error62) ?? (error62 instanceof EventReadError ? new LibraryError(error62.status === 409 ? "STALE_CURSOR" : error62.status === 404 ? "NOT_FOUND" : "INVALID_ARGUMENT", error62.message, error62.status === 400 ? 2 : 1) : new LibraryError("OPERATION_FAILED", "Local operation failed."));
69890
70078
  if (json6) stdout(JSON.stringify({ schemaVersion: 1, command, error: { code: failure2.code, message: failure2.message } }) + "\n");