sessiongraph-app-darwin-arm64 1.0.22 → 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.
@@ -2833,12 +2833,12 @@ function summarizeUsage(session, messages, historyPartial) {
2833
2833
  const lastSnapshot = cumulative.at(-1);
2834
2834
  if (lastSnapshot?.usage) return sessionUsage(lastSnapshot.usage, true);
2835
2835
  const unique = /* @__PURE__ */ new Map();
2836
- let missing = 0;
2836
+ let missing2 = 0;
2837
2837
  for (const message2 of messages) {
2838
2838
  if (message2.usage?.scope === "message") {
2839
2839
  const key = message2.usage.id || message2.id, previous = unique.get(key);
2840
2840
  unique.set(key, previous ? mergeUsage(previous, message2.usage) : message2.usage);
2841
- } else if (message2.role === "assistant") missing++;
2841
+ } else if (message2.role === "assistant") missing2++;
2842
2842
  }
2843
2843
  const records = [...unique.values()], known = records.filter((value) => value.total !== null);
2844
2844
  if (!known.length && native) return { ...native, partial: true };
@@ -2852,8 +2852,8 @@ function summarizeUsage(session, messages, historyPartial) {
2852
2852
  costEstimated: totals.cost !== null ? totals.costEstimated : native?.cost != null ? native.costEstimated : void 0,
2853
2853
  source: records.length ? "messages" : "unavailable",
2854
2854
  reportedMessages: known.length,
2855
- missingMessages: missing + records.length - known.length,
2856
- partial: historyPartial || total === null || missing > 0 || known.length !== records.length || !records.length
2855
+ missingMessages: missing2 + records.length - known.length,
2856
+ partial: historyPartial || total === null || missing2 > 0 || known.length !== records.length || !records.length
2857
2857
  };
2858
2858
  }
2859
2859
 
@@ -34783,6 +34783,40 @@ var SessionGraphStore = class {
34783
34783
  autoImportEnabled() {
34784
34784
  return this.setting("autoImport") === true;
34785
34785
  }
34786
+ savedSources() {
34787
+ return [.../* @__PURE__ */ new Set([
34788
+ ...this.selected(),
34789
+ ...Object.keys(this.setting("sourcePaths") || {}),
34790
+ ...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))
34791
+ ])];
34792
+ }
34793
+ /** Called under the import lock and a caller-owned IMMEDIATE transaction.
34794
+ * Match native source ownership, never linked-provider display filters. */
34795
+ purgeSources(sources2, dryRun) {
34796
+ const ids = JSON.stringify(sources2), selected = "SELECT value FROM json_each(?)";
34797
+ const sessions = `SELECT id FROM sessions WHERE source IN (${selected})`;
34798
+ const count = (table, column) => Number(this.db.prepare(`SELECT COUNT(*) AS n FROM ${table} WHERE ${column} IN (${sessions})`).get(ids).n);
34799
+ const orphanProjects = `source IN (${selected}) AND NOT EXISTS (
34800
+ SELECT 1 FROM sessions WHERE json_extract(metadata,'$.projectID')=projects.id AND source NOT IN (${selected}))`;
34801
+ const deleted = {
34802
+ sessions: Number(this.db.prepare(`SELECT COUNT(*) AS n FROM sessions WHERE source IN (${selected})`).get(ids).n),
34803
+ messages: count("messages", "session_id"),
34804
+ events: count("timeline_items", "session_id"),
34805
+ commits: count("session_commits", "session_id"),
34806
+ pullRequests: count("session_pull_requests", "session_id"),
34807
+ searchCheckpoints: count("search_cache", "id"),
34808
+ projects: Number(this.db.prepare(`SELECT COUNT(*) AS n FROM projects WHERE ${orphanProjects}`).get(ids, ids).n)
34809
+ };
34810
+ if (!dryRun) {
34811
+ this.setting("selected", this.selected().filter((source) => !sources2.includes(source)));
34812
+ this.setting("sourcePaths", Object.fromEntries(Object.entries(this.setting("sourcePaths") || {}).filter(([source]) => !sources2.includes(source))));
34813
+ this.db.prepare(`DELETE FROM sessions WHERE source IN (${selected})`).run(ids);
34814
+ this.db.prepare(`DELETE FROM projects WHERE ${orphanProjects}`).run(ids, ids);
34815
+ this.db.prepare(`DELETE FROM sources WHERE id IN (${selected})`).run(ids);
34816
+ this.setting("indexEpoch", (this.setting("indexEpoch") || 0) + 1);
34817
+ }
34818
+ return deleted;
34819
+ }
34786
34820
  acquireImport() {
34787
34821
  this.db.exec("BEGIN IMMEDIATE");
34788
34822
  try {
@@ -35360,6 +35394,7 @@ function launchCommand(binary, args, directory3, platform = process.platform) {
35360
35394
  // server/handoff.ts
35361
35395
  import { createHash as createHash4, randomUUID as randomUUID3 } from "node:crypto";
35362
35396
  import { mkdir, writeFile as writeFile2, rename as rename2, rm as rm4 } from "node:fs/promises";
35397
+ import { renameSync as renameSync2 } from "node:fs";
35363
35398
  import { join as join26 } from "node:path";
35364
35399
  function handoffDocument(snapshot2) {
35365
35400
  const { session, messages, firstUser, totalMessages } = snapshot2;
@@ -35423,7 +35458,8 @@ This handoff transfers saved text and file-change evidence, not files, credentia
35423
35458
  ` + chunks.map((c) => c.text).join("\n");
35424
35459
  return { text: text2, messages: chunks.length, totalMessages, partial, note };
35425
35460
  }
35426
- async function saveHandoff(snapshot2, directory3) {
35461
+ async function saveHandoff(snapshot2, directory3, store) {
35462
+ const epoch = store?.setting("indexEpoch") || 0;
35427
35463
  const { text: text2, ...coverage2 } = handoffDocument(snapshot2);
35428
35464
  const digest2 = createHash4("sha256").update(text2).digest("hex");
35429
35465
  const root2 = join26(directory3, "handoffs");
@@ -35431,7 +35467,17 @@ async function saveHandoff(snapshot2, directory3) {
35431
35467
  const path = join26(root2, `${digest2}.md`), temporary = join26(root2, `.${randomUUID3()}.tmp`);
35432
35468
  try {
35433
35469
  await writeFile2(temporary, text2, { mode: 384, flag: "wx" });
35434
- await rename2(temporary, path);
35470
+ if (store) {
35471
+ store.db.exec("BEGIN IMMEDIATE");
35472
+ try {
35473
+ if (!store.getSession(snapshot2.session.id) || epoch !== (store.setting("indexEpoch") || 0)) throw new LibraryError("STALE_CURSOR", "Saved history changed. Reload the session before preparing a handoff.");
35474
+ renameSync2(temporary, path);
35475
+ store.db.exec("COMMIT");
35476
+ } catch (error) {
35477
+ store.db.exec("ROLLBACK");
35478
+ throw error;
35479
+ }
35480
+ } else await rename2(temporary, path);
35435
35481
  } finally {
35436
35482
  await rm4(temporary, { force: true });
35437
35483
  }
@@ -35475,7 +35521,7 @@ async function prepareLaunch(store, session, target, directory3 = session.direct
35475
35521
  }
35476
35522
  const mode = args ? "resume" : "handoff";
35477
35523
  if (mode === "handoff" && store.path === ":memory:") invalid("Save this library before creating a context handoff.");
35478
- const context2 = mode === "handoff" ? await saveHandoff(store.handoff(session.id), dirname11(store.path)).catch((error) => {
35524
+ const context2 = mode === "handoff" ? await saveHandoff(store.handoff(session.id), dirname11(store.path), store).catch((error) => {
35479
35525
  throw storageFailure(error, true) ?? new LibraryError("HANDOFF_FAILED", "Could not save the session handoff.");
35480
35526
  }) : void 0;
35481
35527
  if (context2) {
@@ -35948,7 +35994,7 @@ async function annotateGitCheckouts(sessions) {
35948
35994
  }
35949
35995
 
35950
35996
  // server/library-service.ts
35951
- import { basename as basename14, isAbsolute as isAbsolute10 } from "node:path";
35997
+ import { basename as basename15, dirname as dirname13, isAbsolute as isAbsolute10 } from "node:path";
35952
35998
 
35953
35999
  // node_modules/.pnpm/minisearch@7.2.0/node_modules/minisearch/dist/es/index.js
35954
36000
  var ENTRIES = "ENTRIES";
@@ -37935,6 +37981,73 @@ function sampleContent(page2, budget2) {
37935
37981
  return { fragments, characters: Math.max(0, budget2) - remaining, partial: page2.truncated || sampled };
37936
37982
  }
37937
37983
 
37984
+ // server/purge-handoffs.ts
37985
+ import { closeSync as closeSync2, constants as constants7, fstatSync, lstatSync as lstatSync4, openSync as openSync2, opendirSync, readSync as readSync2, unlinkSync as unlinkSync2 } from "node:fs";
37986
+ import { basename as basename14, join as join28 } from "node:path";
37987
+ var MAX_ENTRIES = 2e4;
37988
+ var HEADER_BYTES = 64 * 1024;
37989
+ 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)$/;
37990
+ var missing = (error) => error.code === "ENOENT";
37991
+ function findPurgeHandoffs(directory3, sources2, all = false) {
37992
+ const root2 = join28(directory3, "handoffs"), paths2 = [], warnings = [], foundSources = /* @__PURE__ */ new Set();
37993
+ try {
37994
+ if (!lstatSync4(root2).isDirectory()) return { paths: paths2, sources: [], warnings: ["Handoff cleanup skipped: handoffs is not a regular directory."] };
37995
+ const entries2 = opendirSync(root2);
37996
+ try {
37997
+ let count = 0;
37998
+ for (let entry = entries2.readSync(); entry; entry = entries2.readSync()) {
37999
+ if (++count > MAX_ENTRIES) {
38000
+ warnings.push("Handoff scan limited to 20,000 entries. Retry purge after cleaning this directory.");
38001
+ break;
38002
+ }
38003
+ if (!generatedName.test(entry.name)) continue;
38004
+ if (!entry.isFile()) {
38005
+ warnings.push(`Handoff cleanup skipped non-regular file ${entry.name}.`);
38006
+ continue;
38007
+ }
38008
+ const path = join28(root2, entry.name);
38009
+ let fd2;
38010
+ try {
38011
+ fd2 = openSync2(path, constants7.O_RDONLY | (constants7.O_NOFOLLOW || 0) | (constants7.O_NONBLOCK || 0));
38012
+ if (!fstatSync(fd2).isFile()) throw new Error("Not a regular file");
38013
+ const buffer = Buffer.alloc(HEADER_BYTES);
38014
+ const header = buffer.subarray(0, readSync2(fd2, buffer, 0, buffer.length, 0)).toString("utf8");
38015
+ const match2 = header.startsWith("# SessionGraph handoff\n\n") && /\nTitle: [^\n]*\nSource: ([^\n]+)\nNative session: /.exec(header);
38016
+ const source = match2 ? JSON.parse(match2[1]) : void 0;
38017
+ if (typeof source !== "string") {
38018
+ warnings.push(`Could not identify handoff ${entry.name}; it was not removed.`);
38019
+ continue;
38020
+ }
38021
+ foundSources.add(source);
38022
+ if (all || sources2.includes(source)) paths2.push(path);
38023
+ } catch (error) {
38024
+ if (!missing(error)) warnings.push(`Could not inspect handoff ${entry.name}; it was not removed.`);
38025
+ } finally {
38026
+ if (fd2 !== void 0) closeSync2(fd2);
38027
+ }
38028
+ }
38029
+ } finally {
38030
+ entries2.closeSync();
38031
+ }
38032
+ } catch (error) {
38033
+ if (!missing(error)) warnings.push("Could not inspect the handoffs directory. Check permissions and retry purge.");
38034
+ }
38035
+ return { paths: paths2, sources: [...foundSources], warnings };
38036
+ }
38037
+ function removePurgeHandoffs(paths2) {
38038
+ let removed = 0;
38039
+ const warnings = [];
38040
+ for (const path of paths2) {
38041
+ try {
38042
+ unlinkSync2(path);
38043
+ removed++;
38044
+ } catch (error) {
38045
+ if (!missing(error)) warnings.push(`Could not delete handoff ${basename14(path)}. Check permissions and retry purge.`);
38046
+ }
38047
+ }
38048
+ return { removed, warnings };
38049
+ }
38050
+
37938
38051
  // server/library-service.ts
37939
38052
  var utc = (ms) => ms > 0 && ms <= 864e13 ? new Date(ms).toISOString() : null;
37940
38053
  var LibraryService = class {
@@ -38038,6 +38151,37 @@ var LibraryService = class {
38038
38151
  this.store.setting("sourcePaths", paths2);
38039
38152
  });
38040
38153
  }
38154
+ purgeSources(ids, options = {}) {
38155
+ if (!!options.all === !!ids.length) invalid("Choose source IDs or --all.");
38156
+ if (options.dryRun && options.confirmed) invalid("Choose a dry run or a confirmed purge, not both.");
38157
+ if (!options.dryRun && options.confirmed !== true) invalid("Purging saved history requires confirmation. Use --dry-run to preview, or --yes to delete.");
38158
+ if (this.importer.status.running || !this.store.acquireImport()) throw new LibraryError("IMPORT_BUSY", "Another import is running. Try again when it finishes.");
38159
+ try {
38160
+ this.store.db.exec("BEGIN IMMEDIATE");
38161
+ let result;
38162
+ try {
38163
+ const handoffs = this.store.path === ":memory:" ? { paths: [], sources: [], warnings: [] } : findPurgeHandoffs(dirname13(this.store.path), ids, options.all);
38164
+ const known = [.../* @__PURE__ */ new Set([...this.importer.adapters.map((adapter) => adapter.id), ...this.store.savedSources(), ...handoffs.sources])];
38165
+ for (const id2 of ids) if (!known.includes(id2)) invalid(`Unknown source "${id2}". Run sessiongraph sources list.`);
38166
+ const sources2 = [...new Set(options.all ? known : ids)];
38167
+ result = { sources: sources2, handoffs, deleted: this.store.purgeSources(sources2, options.dryRun === true) };
38168
+ this.store.db.exec("COMMIT");
38169
+ } catch (error) {
38170
+ this.store.db.exec("ROLLBACK");
38171
+ throw error;
38172
+ }
38173
+ const cleanup2 = options.dryRun ? { removed: result.handoffs.paths.length, warnings: [] } : removePurgeHandoffs(result.handoffs.paths);
38174
+ if (!options.dryRun) this.searchCache = void 0;
38175
+ return {
38176
+ dryRun: options.dryRun === true,
38177
+ sources: result.sources,
38178
+ deleted: { ...result.deleted, handoffFiles: cleanup2.removed },
38179
+ warnings: [...result.handoffs.warnings, ...cleanup2.warnings]
38180
+ };
38181
+ } finally {
38182
+ this.store.releaseImport();
38183
+ }
38184
+ }
38041
38185
  async importSessions(ids) {
38042
38186
  const selected = this.store.selected(), sources2 = ids?.length ? ids : selected;
38043
38187
  this.validateSources(sources2);
@@ -38063,7 +38207,7 @@ var LibraryService = class {
38063
38207
  title: s.title,
38064
38208
  source: s.source,
38065
38209
  projectID: s.projectID,
38066
- projectLabel: names.get(s.projectID) || basename14(s.directory) || "Unknown project",
38210
+ projectLabel: names.get(s.projectID) || basename15(s.directory) || "Unknown project",
38067
38211
  created: utc(s.created),
38068
38212
  lastActivity: utc(sessionEnd(s)),
38069
38213
  relationship: relationshipOf(s),
@@ -38190,7 +38334,7 @@ var LibraryService = class {
38190
38334
  }
38191
38335
  const groups = [...grouped2].sort(([a], [b]) => a.localeCompare(b)).map(([key, values]) => ({
38192
38336
  key,
38193
- label: groupBy === "project" ? names.get(key) || basename14(values[0].directory) || "Unknown project" : groupBy === "repository" ? values[0].checkout?.repositoryLabel || "Unverified repository" : key,
38337
+ label: groupBy === "project" ? names.get(key) || basename15(values[0].directory) || "Unknown project" : groupBy === "repository" ? values[0].checkout?.repositoryLabel || "Unverified repository" : key,
38194
38338
  ...groupBy === "repository" ? { worktrees: [...new Set(values.flatMap((s) => s.checkout?.worktree || []))].sort() } : {},
38195
38339
  ...groupBy === "relationship" ? { origins: values.reduce((counts, s) => {
38196
38340
  counts[s.origin ?? "unknown"]++;
@@ -38343,6 +38487,15 @@ async function sessionGraphMiddleware(req, res, next) {
38343
38487
  const result = await service.discoverSources([value.source]);
38344
38488
  return json5(200, { saved: true, source: result.sources[0] });
38345
38489
  }
38490
+ if (url.pathname === "/api/sessiongraph/sources/purge") {
38491
+ if (req.method !== "POST") {
38492
+ res.setHeader("Allow", "POST");
38493
+ return json5(405, { error: "Method not allowed." });
38494
+ }
38495
+ const value = await body(req);
38496
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => !["sources", "all", "dryRun", "confirmed"].includes(key)) || value.sources !== void 0 && (!Array.isArray(value.sources) || value.sources.some((source) => typeof source !== "string")) || ["all", "dryRun", "confirmed"].some((key) => value[key] !== void 0 && typeof value[key] !== "boolean")) return json5(400, { error: "Choose source IDs or all, and a dry run or confirmed purge." });
38497
+ return json5(200, new LibraryService(store, importer).purgeSources(value.sources || [], { all: value.all, dryRun: value.dryRun, confirmed: value.confirmed }));
38498
+ }
38346
38499
  if (url.pathname === "/api/sessiongraph/import") {
38347
38500
  if (req.method === "GET") return json5(200, importer.status);
38348
38501
  if (req.method === "POST") {
@@ -18,11 +18,11 @@
18
18
  </data>
19
19
  <key>Resources/resources/cli-package.json</key>
20
20
  <data>
21
- 6QsX4sO+QtUAvKQH1oAjWekbEMc=
21
+ s28hq2O7ILA2UtcLcLF6U1etYS0=
22
22
  </data>
23
23
  <key>Resources/resources/cli.mjs</key>
24
24
  <data>
25
- CLCliQnTMw0lMRVimBXF09sy2XU=
25
+ DAdCXOJsfrlsXTNOSfUpibhOO1w=
26
26
  </data>
27
27
  <key>Resources/resources/install-cli.mjs</key>
28
28
  <data>
@@ -34,7 +34,7 @@
34
34
  </data>
35
35
  <key>Resources/resources/server.mjs</key>
36
36
  <data>
37
- ATUKryrD1m4O0UvhqXdtyUiuOPY=
37
+ vwkz/tVBAART4vfjlyPavHsAmI8=
38
38
  </data>
39
39
  <key>Resources/resources/web/apple-touch-icon.png</key>
40
40
  <data>
@@ -416,14 +416,14 @@
416
416
  <dict>
417
417
  <key>hash2</key>
418
418
  <data>
419
- hgwDS16Mxv5pPzrRlA2wXQ3Kx7fh/+HijnYFEaNjFbk=
419
+ ssz2kat1NginI7VJe9dAgSQpWrKaj64JGZOAt7br0VA=
420
420
  </data>
421
421
  </dict>
422
422
  <key>Resources/resources/cli.mjs</key>
423
423
  <dict>
424
424
  <key>hash2</key>
425
425
  <data>
426
- AL/InAASf65qMH6oW9Bini1TMZA47VmX5ktoYQ3v3Qg=
426
+ mDgqbjSTKQfu42/G2oiWKf7UMaCj+QMnFJlbfrLyd2Q=
427
427
  </data>
428
428
  </dict>
429
429
  <key>Resources/resources/install-cli.mjs</key>
@@ -444,7 +444,7 @@
444
444
  <dict>
445
445
  <key>hash2</key>
446
446
  <data>
447
- A1M+hZWqsgdHOvk720PlqWac5kX8c9MoY6TlSJC+5vo=
447
+ LwxoI7U+bNl9PKdkK7X+2dGO/Fpe91eDMeJX2UZExUo=
448
448
  </data>
449
449
  </dict>
450
450
  <key>Resources/resources/web/apple-touch-icon.png</key>