my-durable 0.0.77 → 0.0.78

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.
@@ -54,8 +54,15 @@ export function cacheKey(p: string, platform: NodeJS.Platform = process.platform
54
54
  return platform === "win32" ? trimmed.toLowerCase() : trimmed;
55
55
  }
56
56
 
57
- /** Same, for the `-- <paths...>` lists (stage/discard/commit/unstage/resolve). */
58
- const gitPaths = (paths: string[]): string[] => paths.map(gitPath);
57
+ /** Same, for the `-- <paths...>` lists (stage/discard/commit/unstage/resolve).
58
+ * run-8 U2: NUL/empty are refused for EVERY files-bearing op (commit-only
59
+ * before) — with -z parsing the returned spellings are exact bytes, so the
60
+ * parity check is load-bearing. */
61
+ const gitPaths = (paths: string[]): string[] =>
62
+ paths.map((p) => {
63
+ if (typeof p !== "string" || p.includes("\0") || p === "") throw Error("bad file path");
64
+ return gitPath(p);
65
+ });
59
66
 
60
67
  /** Child-process options, exported so a test can assert the Windows console
61
68
  * window stays hidden: a daemon that polls git must never flash a terminal. */
@@ -370,12 +377,12 @@ async function statusOnce(path: string, key: string): Promise<GitStatus> {
370
377
  const [branchP, headP, statusP, gitDirP, wlP, branchesP, numWorkP, numIdxP, mergeP, nameP, emailP, remoteP] = await Promise.allSettled([
371
378
  g(["branch", "--show-current"]),
372
379
  g(["log", "-1", "--pretty=%h%x09%s"]),
373
- g(["--no-optional-locks", "status", "--porcelain=v1", "-b"], GIT_SLOW_TIMEOUT),
380
+ g(["--no-optional-locks", "status", "--porcelain=v1", "-z", "-b"], GIT_SLOW_TIMEOUT),
374
381
  g(["rev-parse", "--git-dir"]),
375
382
  g(["worktree", "list", "--porcelain"], GIT_SLOW_TIMEOUT),
376
383
  g(["for-each-ref", "refs/heads", "--format=%(refname:short)%09%(upstream:short)%09%(if)%(HEAD)%(then)1%(else)0%(end)"]),
377
- g(["--no-optional-locks", "diff", "--numstat", "--no-renames"], GIT_SLOW_TIMEOUT),
378
- g(["--no-optional-locks", "diff", "--numstat", "--cached", "--no-renames"]),
384
+ g(["--no-optional-locks", "diff", "--numstat", "-z", "--no-renames"], GIT_SLOW_TIMEOUT),
385
+ g(["--no-optional-locks", "diff", "--numstat", "-z", "--cached", "--no-renames"]),
379
386
  // MERGE_HEAD exists ⇔ a merge is waiting to be resolved.
380
387
  g(["rev-parse", "-q", "--verify", "MERGE_HEAD"]),
381
388
  g(["config", "user.name"]),
@@ -393,8 +400,14 @@ async function statusOnce(path: string, key: string): Promise<GitStatus> {
393
400
  }
394
401
  if (statusP.status === "rejected") throw statusP.reason;
395
402
  const status = statusP.value;
396
- const lines = status.split("\n");
397
- const head2 = lines[0] ?? "";
403
+ // run-8 U2: parse the -z stream (NUL-delimited, NEVER C-quoted). The
404
+ // v1 line form C-quotes control/backslash/non-ASCII names; stripping
405
+ // only the outer quotes handed the ESCAPED spelling to the FE, and its
406
+ // verbatim round-trip into stage/discard reported success while missing
407
+ // the real file (leader-probed: "discarded 1 file(s)" with the
408
+ // TAB-named file still modified).
409
+ const records = status.split("\0").filter(Boolean);
410
+ const head2 = records[0]?.startsWith("## ") ? records[0] : "";
398
411
  // "## main...origin/main [ahead 2, behind 1]" — split by hand: a lazy \S+?
399
412
  // ate the branch down to one letter.
400
413
  const info = head2.replace(/^## /, "");
@@ -407,10 +420,21 @@ async function statusOnce(path: string, key: string): Promise<GitStatus> {
407
420
  out.ahead = Number(ab.match(/ahead (\d+)/)?.[1] ?? 0);
408
421
  out.behind = Number(ab.match(/behind (\d+)/)?.[1] ?? 0);
409
422
  }
410
- // Per line — a ^-anchored regex on the joined blob only ever sees line 1.
411
- const body = lines.slice(1).filter(Boolean);
423
+ // Per record — NUL-delimited, so an embedded newline can never forge a
424
+ // record boundary (the old line-form regex was per-line). A rename/copy
425
+ // record is followed by its ORIGIN path as a separate record; that record
426
+ // is status text too, so it must be dropped ONCE here — leaving it in made
427
+ // the counters at the bottom count an old path that starts with M/A/U.
428
+ const raw = records.filter((r) => !r.startsWith("## "));
429
+ const body: string[] = [];
430
+ for (let i = 0; i < raw.length; i++) {
431
+ const rec = raw[i]!;
432
+ body.push(rec);
433
+ const x = rec[0] ?? " ";
434
+ if ((x === "R" || x === "C") && i + 1 < raw.length) i++;
435
+ }
412
436
  out.merge = mergeP.status === "fulfilled";
413
- out.conflicts = count(body.join("\n"), /^(UU|AA|DD|AU|UA|DU|UD)/gm);
437
+ out.conflicts = body.filter((r) => /^(UU|AA|DD|AU|UA|DU|UD)/.test(r)).length;
414
438
  out.identity = {
415
439
  name: nameP.status === "fulfilled" ? nameP.value.trim() || undefined : undefined,
416
440
  email: emailP.status === "fulfilled" ? emailP.value.trim() || undefined : undefined,
@@ -419,8 +443,10 @@ async function statusOnce(path: string, key: string): Promise<GitStatus> {
419
443
  // ±n per file: worktree-vs-index numstat for unstaged paths, cached for staged.
420
444
  const numstat = (raw: string) => {
421
445
  const m = new Map<string, { a: number; d: number }>();
422
- for (const l of raw.split("\n")) {
423
- const mt = l.match(/^(\d+|-)\t(\d+|-)\t(.+)$/);
446
+ // run-8 U2: -z is NUL-delimited and unquoted (renames disabled, so no
447
+ // trailing original-path record). Paths may contain any byte but NUL.
448
+ for (const rec of raw.split("\0")) {
449
+ const mt = rec.match(/^(\d+|-)\t(\d+|-)\t([\s\S]+)$/);
424
450
  if (!mt) continue;
425
451
  m.set(mt[3]!, { a: mt[1] === "-" ? -1 : Number(mt[1]), d: mt[2] === "-" ? -1 : Number(mt[2]) });
426
452
  }
@@ -428,12 +454,15 @@ async function statusOnce(path: string, key: string): Promise<GitStatus> {
428
454
  };
429
455
  const workNum = numstat(numWorkP.status === "fulfilled" ? numWorkP.value : "");
430
456
  const idxNum = numstat(numIdxP.status === "fulfilled" ? numIdxP.value : "");
431
- out.files = body.slice(0, 500).map((l) => {
432
- const p = l.slice(3).replace(/^"|"$/g, "");
433
- const staged = l[0] !== " " && l[0] !== "?";
457
+ out.files = [];
458
+ for (const l of body.slice(0, 500)) {
459
+ const x = l[0] ?? " ";
460
+ const y = l[1] ?? " ";
461
+ const p = l.slice(3);
462
+ const staged = x !== " " && x !== "?";
434
463
  const n = staged ? idxNum.get(p) : workNum.get(p);
435
- return { path: p, x: l[0] ?? " ", y: l[1] ?? " ", ...(n ? { a: n.a, d: n.d } : {}) };
436
- });
464
+ out.files.push({ path: p, x, y, ...(n ? { a: n.a, d: n.d } : {}) });
465
+ }
437
466
  if (branchesP.status === "fulfilled")
438
467
  out.branches = branchesP.value
439
468
  .split("\n")
@@ -444,9 +473,11 @@ async function statusOnce(path: string, key: string): Promise<GitStatus> {
444
473
  return { name: name ?? "", current: head === "1", upstream: upstream || undefined };
445
474
  })
446
475
  .filter((b) => b.name);
447
- out.staged = count(body.join("\n"), /^[MADRC]/gm);
448
- out.unstaged = count(body.join("\n"), /^ [MD]/gm);
449
- out.untracked = count(body.join("\n"), /^\?\?/gm);
476
+ // run-8 U2: count PER RECORD — with -z a filename may contain a newline,
477
+ // so the old joined-text ^-anchored regexes could be forged by a name.
478
+ out.staged = body.filter((r) => /^[MADRC]/.test(r)).length;
479
+ out.unstaged = body.filter((r) => /^ [MD]/.test(r)).length;
480
+ out.untracked = body.filter((r) => /^\?\?/.test(r)).length;
450
481
  // In a linked worktree --git-dir is "<main>/.git/worktrees/<name>";
451
482
  // the main checkout is the .git's parent.
452
483
  const gitDir = (gitDirP.status === "fulfilled" ? gitDirP.value : "").trim();
@@ -697,7 +697,9 @@ export class DevicePairing {
697
697
  )
698
698
  ) {
699
699
  this.pending = undefined;
700
- this.lastFailure = `${code}: ${message}`;
700
+ // run-8 U6: the hub controls this message; the TUI renders (and
701
+ // re-wraps) it every poll — bound it at the seam.
702
+ this.lastFailure = `${code}: ${String(message ?? "").slice(0, 400)}`;
701
703
  return;
702
704
  }
703
705
  await sleep(pollMs * 2, pending.abort.signal);
@@ -59,22 +59,83 @@ export interface SalvageOutcome {
59
59
  */
60
60
  const WORKER_SRC = `
61
61
  const { parentPort, workerData } = require("node:worker_threads");
62
- const { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } = require("node:fs");
62
+ const { copyFileSync, existsSync, lstatSync, statSync, fstatSync, readSync, openSync, closeSync, rmSync, writeSync } = require("node:fs");
63
+ const fsConstants = require("node:fs").constants;
63
64
  const { DatabaseSync } = require("node:sqlite");
64
65
  const main = workerData.dbPath;
65
66
  const copy = workerData.copyPath; // R10 5.2: unique per attempt — two workers never share scratch files
66
67
  const fail = (reason) => parentPort.postMessage({ ok: false, reason: String(reason).slice(0, 80) });
68
+ /** run-8 U7: the copy source must be a REGULAR file of bounded size. Nothing
69
+ * validated it (archived.ts lstats the same name for reads), so a planted
70
+ * symlink to /dev/zero, a FIFO or a huge file turned this into an unbounded
71
+ * synchronous copy — and the 5s ceiling only settles the parent promise, it
72
+ * cannot recall a thread blocked in a native fs call. */
73
+ const MAX_DB_BYTES = 256 * 1024 * 1024;
74
+ function assertRegular(path, label) {
75
+ let st;
76
+ try {
77
+ st = lstatSync(path, { throwIfNoEntry: false });
78
+ } catch {
79
+ return "unreadable";
80
+ }
81
+ if (!st) return "missing";
82
+ if (!st.isFile()) return label + " is not a regular file";
83
+ if (st.size > MAX_DB_BYTES) return label + " is too large to salvage";
84
+ return null;
85
+ }
67
86
  function run() {
68
87
  try {
69
88
  // 1. Copy main + sidecars aside. The original is only ever read.
89
+ const bad = assertRegular(main, "database");
90
+ if (bad) return fail(bad);
91
+ for (const suffix of ["-wal", "-shm"]) {
92
+ if (!existsSync(main + suffix)) continue;
93
+ const sideBad = assertRegular(main + suffix, "database" + suffix);
94
+ if (sideBad && sideBad !== "missing") return fail(sideBad);
95
+ }
70
96
  rmSync(copy, { force: true });
71
- copyFileSync(main, copy);
97
+ // cold-3 M4: the lstat above is a PATH pre-check; copyFileSync re-opens the
98
+ // path, so a same-user swap re-opened a different file (the exact race
99
+ // archived.ts pinned with O_NOFOLLOW). Pin the source fd, fstat THAT fd, and
100
+ // copy from it — a swap after the open cannot change what we read.
101
+ const srcFd = openSync(main, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
102
+ try {
103
+ const fst = fstatSync(srcFd);
104
+ if (!fst.isFile()) return fail("database is not a regular file");
105
+ if (fst.size > MAX_DB_BYTES) return fail("database is too large to salvage");
106
+ const dstFd = openSync(copy, "w", 0o600);
107
+ try {
108
+ const buf = Buffer.allocUnsafe(256 * 1024);
109
+ let pos = 0;
110
+ for (;;) {
111
+ const n = readSync(srcFd, buf, 0, buf.length, pos);
112
+ if (n <= 0) break;
113
+ writeSync(dstFd, buf, 0, n);
114
+ pos += n;
115
+ }
116
+ } finally {
117
+ closeSync(dstFd);
118
+ }
119
+ } finally {
120
+ closeSync(srcFd);
121
+ }
72
122
  for (const suffix of ["-wal", "-shm"]) {
73
123
  if (existsSync(main + suffix)) copyFileSync(main + suffix, copy + suffix);
74
124
  else rmSync(copy + suffix, { force: true });
75
125
  }
76
126
  // 2. Patch the copy's header: only fields sqlite validates at open (see module doc).
77
- const b = readFileSync(copy);
127
+ // run-8 U7: patch the first 100 header bytes positionally — reading and
128
+ // rewriting the WHOLE database cost ~2x its size in RSS for a 100-byte fix.
129
+ const HEADER_BYTES = 100;
130
+ const fd = openSync(copy, "r+");
131
+ let b;
132
+ try {
133
+ b = Buffer.alloc(HEADER_BYTES);
134
+ const n = readSync(fd, b, 0, HEADER_BYTES, 0);
135
+ if (n < HEADER_BYTES) return fail("truncated database header");
136
+ } finally {
137
+ closeSync(fd);
138
+ }
78
139
  const MAGIC = "SQLite format 3\\0";
79
140
  if (b.slice(0, 16).toString("latin1") !== MAGIC) b.write(MAGIC, 0, 16, "latin1");
80
141
  const pageSize = b.readUInt16BE(16);
@@ -90,7 +151,12 @@ try {
90
151
  b.writeUInt32BE(0, 52); // largest root b-tree page: nonzero garbage turns ptrmap validation on
91
152
  const encoding = b.readUInt32BE(56);
92
153
  if (!(encoding >= 1 && encoding <= 3)) b.writeUInt32BE(1, 56); // UTF-8
93
- writeFileSync(copy, b);
154
+ const wfd = openSync(copy, "r+");
155
+ try {
156
+ writeSync(wfd, b, 0, b.length, 0);
157
+ } finally {
158
+ closeSync(wfd);
159
+ }
94
160
  // 3. Integrity is the ONLY gate for promotion.
95
161
  let db;
96
162
  try {
@@ -73,6 +73,7 @@ import {
73
73
  import {
74
74
  listArchived,
75
75
  findBundle,
76
+ BUNDLE_DIR_PATTERN,
76
77
  readArchiveManifest,
77
78
  archivedTranscript,
78
79
  restoreArchive,
@@ -82,7 +83,7 @@ import {
82
83
  import { NotifySinks, type DeliveryResult, type SinkInput, type SinkRecord } from "./notify-sinks.js";
83
84
  import { zipSync, EXPORT_RAW_LIMIT_BYTES, type ZipEntry } from "./zip.js";
84
85
  import { salvageFailureNote, salvageSessionDb } from "./salvage.js";
85
- import { mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, renameSync, rmSync, statSync } from "node:fs";
86
+ import { existsSync, mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, renameSync, rmSync, statSync, realpathSync } from "node:fs";
86
87
  import { lstat } from "node:fs/promises";
87
88
  import { ensurePrivateDir } from "../../dpi-sdk/src/node/private-dir.js";
88
89
  import { join, dirname, relative, resolve, sep } from "node:path";
@@ -627,6 +628,138 @@ export class Store {
627
628
  * committed storage at boot; a session whose db fails to open keeps its row with the
628
629
  * boot loop's failure message. Names are placeholders — the transcript is intact.
629
630
  */
631
+ /** run-8 U1: the newest archive bundle for a session id, or null. Used by
632
+ * archive() to finish an interrupted archive idempotently. */
633
+ private findBundleDir(sessionId: string): string | null {
634
+ let names: string[];
635
+ try {
636
+ names = readdirSync(this.archiveDir);
637
+ } catch {
638
+ return null;
639
+ }
640
+ // cold-3 M3: the SAME grammar every other reader uses (BUNDLE_DIR_PATTERN,
641
+ // 13-digit ms). A looser prefix+Number() match accepted `<id>-17e5` /
642
+ // `<id>-0x1f` / `<id>-`, and this helper gates row DELETION — so a bundle
643
+ // restore cannot see was treated as "already archived" and the row went away
644
+ // with its name/cwd.
645
+ let best: string | null = null;
646
+ let bestTs = -1;
647
+ for (const name of names) {
648
+ const match = BUNDLE_DIR_PATTERN.exec(name);
649
+ if (!match || match[1] !== sessionId) continue;
650
+ const ts = Number(match[2]);
651
+ if (ts > bestTs) {
652
+ bestTs = ts;
653
+ best = name;
654
+ }
655
+ }
656
+ return best ? join(this.archiveDir, best) : null;
657
+ }
658
+
659
+ /**
660
+ * run-8 U1: reconcile the two crash windows the archive lifecycle left open
661
+ * (leader-probed all three variants before this existed):
662
+ *
663
+ * A. a row whose sessions/<id> dir is gone but whose bundle sits in
664
+ * archive/ — the process died between the rename and the catalog
665
+ * DELETEs. restore then refused forever ("a live session with this id
666
+ * already exists") and DELETE /v1/sessions re-threw ENOENT, so the row
667
+ * was immortal. Complete the archive: repair/write the manifest from the
668
+ * row's own fields, then delete the row (one transaction).
669
+ * A2. same window before the manifest was written — the bundle was
670
+ * unrestorable even after manual row removal ("no usable cwd"). The row
671
+ * carries every manifest field, so this is fully recoverable here.
672
+ * B. a sessions/<uuid> dir with no catalog row (a restore that died
673
+ * between the rename and the INSERT, or a rolled-back INSERT): invisible
674
+ * to list() and a 404 on restore retry. Re-add a recovered row.
675
+ *
676
+ * Bounded: one readdir of sessions/ + one of archive/, no per-row spawns.
677
+ */
678
+ private reconcileArchiveWindows(): void {
679
+ let dirs: string[];
680
+ try {
681
+ dirs = readdirSync(this.sessionsDir);
682
+ } catch (e) {
683
+ // cold-3 L6: EACCES/EMFILE/EIO is NOT "no sessions exist" — reconciling on
684
+ // a transient readdir failure would complete-and-delete every row whose
685
+ // bundle exists, losing name/model/cwd. Only a genuinely absent dir is
686
+ // "nothing to do".
687
+ if ((e as NodeJS.ErrnoException).code === "ENOENT") return;
688
+ return;
689
+ }
690
+ const onDisk = new Set(dirs);
691
+ const rows = this.list();
692
+ const known = new Set(rows.map((r) => r.id));
693
+
694
+ for (const row of rows) {
695
+ if (onDisk.has(row.id)) continue; // live dir present: nothing to repair
696
+ const bundle = this.findBundleDir(row.id);
697
+ if (!bundle) {
698
+ // Data genuinely gone (offline wipe / manual rm): a bounded, distinct
699
+ // fault instead of a permanent per-request ENOENT error row.
700
+ this.errors.set(row.id, "session data is missing and no archived bundle exists");
701
+ continue;
702
+ }
703
+ const manifest = readArchiveManifest(bundle);
704
+ if (!manifest || !manifest.cwd) {
705
+ try {
706
+ writeArchiveManifest(bundle, {
707
+ sessionId: row.id,
708
+ name: row.name,
709
+ cwd: row.cwd,
710
+ model: row.model,
711
+ provider: row.provider,
712
+ createdAt: row.createdAt,
713
+ archivedAt: Date.now(),
714
+ packageVersion: PACKAGE_VERSION,
715
+ });
716
+ } catch {
717
+ // Unwritable bundle: keep the row and the fault, never delete data.
718
+ this.errors.set(row.id, "interrupted archive: bundle is not writable");
719
+ continue;
720
+ }
721
+ }
722
+ this.catalog.exec("BEGIN");
723
+ try {
724
+ this.catalog.prepare("DELETE FROM conversation_names WHERE sessionId=?").run(row.id);
725
+ this.catalog.prepare("DELETE FROM sessions WHERE id=?").run(row.id);
726
+ this.catalog.exec("COMMIT");
727
+ } catch (e) {
728
+ this.catalog.exec("ROLLBACK");
729
+ this.errors.set(row.id, `interrupted archive: ${e instanceof Error ? e.message : String(e)}`);
730
+ }
731
+ }
732
+
733
+ // Variant B: an orphan session dir with no row.
734
+ for (const name of onDisk) {
735
+ if (known.has(name)) continue;
736
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(name)) continue;
737
+ const dbPath = join(this.sessionsDir, name, "agent.sqlite");
738
+ let createdAt = Date.now();
739
+ try {
740
+ createdAt = Math.round(statSync(dbPath).mtimeMs);
741
+ } catch {
742
+ continue; // no database in it: not a session
743
+ }
744
+ const fallback = this.defaultModelRef();
745
+ try {
746
+ this.catalog
747
+ .prepare(
748
+ "INSERT OR IGNORE INTO sessions(id,name,cwd,dbPath,createdAt,model,provider) VALUES(?,?,?,?,?,?,?)",
749
+ )
750
+ .run(
751
+ name,
752
+ `Recovered session ${name.slice(0, 8)}`,
753
+ this.startDirs[0] ?? homedir(),
754
+ dbPath,
755
+ createdAt,
756
+ fallback?.modelId ?? "unknown",
757
+ fallback?.provider ?? "unknown",
758
+ );
759
+ } catch {}
760
+ }
761
+ }
762
+
630
763
  private reseedCatalog(db: DatabaseSync): void {
631
764
  let entries;
632
765
  try {
@@ -736,6 +869,10 @@ export class Store {
736
869
  store.unlockShared = lockFile(`${store.sharedStatePath}.lock`);
737
870
  store.shared = await SharedState.open(store.sharedStatePath);
738
871
  store.shared.harness.subscribeCommits(() => store.notify());
872
+ // run-8 U1: repair the archive/restore crash windows BEFORE the open
873
+ // loop, so a zombie row is completed (or faulted) instead of producing a
874
+ // permanent ENOENT error session that search and the tree keep paying for.
875
+ store.reconcileArchiveWindows();
739
876
  for (const row of store.list()) {
740
877
  try {
741
878
  await store.openAgent(row);
@@ -816,7 +953,18 @@ export class Store {
816
953
  durableVersion: DURABLE_VERSION,
817
954
  packageVersion: PACKAGE_VERSION,
818
955
  startedAt: this.startedAt,
819
- startDirs: this.startDirs,
956
+ // run-8 U4: report the REALPATH spelling — session cwds and the git/fs
957
+ // enforcement roots are realpath'd (startDirRoots), so a configured
958
+ // spelling with a symlink component (macOS /tmp -> /private/tmp, win
959
+ // junctions) made the FE advisory pre-check reject every session under
960
+ // it with a permanent, un-retryable error while the device answered 200.
961
+ startDirs: this.startDirs.map((d) => {
962
+ try {
963
+ return realpathSync(d);
964
+ } catch {
965
+ return d;
966
+ }
967
+ }),
820
968
  models: this.modelList,
821
969
  defaultModel: this.defaultModel(),
822
970
  provider: this.options.provider,
@@ -1581,6 +1729,27 @@ export class Store {
1581
1729
  await renamePath(dirname(row.dbPath), target);
1582
1730
  } catch (e) {
1583
1731
  if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
1732
+ // run-8 U1: a missing source dir used to be treated as success, and the
1733
+ // manifest write then threw into a never-created target — the row was
1734
+ // immortal through the API (probe: ENOENT + row survives forever). An
1735
+ // earlier interrupted archive already holds the bundle, so finish the
1736
+ // row removal idempotently instead of minting an empty one.
1737
+ // cold-3 L8: rename() also ENOENTs when the DESTINATION parent vanished
1738
+ // (e.g. a concurrent gc of archive/), so require the source dir to be
1739
+ // gone before the idempotent completion below can delete the row.
1740
+ if (existsSync(dirname(row.dbPath))) throw e;
1741
+ const existing = this.findBundleDir(row.id);
1742
+ if (!existing) {
1743
+ this.errors.set(row.id, "session directory is missing (no archived bundle); row left in place");
1744
+ throw new Error("session directory is missing and no archived bundle exists");
1745
+ }
1746
+ this.catalog.prepare("DELETE FROM conversation_names WHERE sessionId=?").run(row.id);
1747
+ this.catalog.prepare("DELETE FROM sessions WHERE id=?").run(row.id);
1748
+ this.opened.delete(row.id);
1749
+ this.salvageFailedSessions.delete(row.id);
1750
+ this.errors.delete(row.id);
1751
+ this.notify();
1752
+ return { archived: existing };
1584
1753
  }
1585
1754
  // The bundle keeps its identity: from now on every archive carries a
1586
1755
  // session.json so the archive stays browsable years later (old bundles