my-durable 0.0.76 → 0.0.77

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.
@@ -47,7 +47,7 @@ import {
47
47
  } from "../../dpi-sdk/src/transcript.js";
48
48
  import { ApiFault, invalid, isStorageBusy, isUnreadableStorage, notFound, storageBusyFault } from "./errors.js";
49
49
  import { searchHistory } from "./history.js";
50
- import { git, gitDirtyMarks, gitStatus, onGitDirty } from "./git.js";
50
+ import { configureGitRootGuard, git, gitDirtyMarks, gitStatus, onGitDirty } from "./git.js";
51
51
  import { DatabaseSync } from "node:sqlite";
52
52
  import { mkdir, readdir, realpath, rename as renamePath, stat } from "node:fs/promises";
53
53
  import { deviceVitals, type DeviceVitals } from "./vitals.js";
@@ -82,7 +82,7 @@ import {
82
82
  import { NotifySinks, type DeliveryResult, type SinkInput, type SinkRecord } from "./notify-sinks.js";
83
83
  import { zipSync, EXPORT_RAW_LIMIT_BYTES, type ZipEntry } from "./zip.js";
84
84
  import { salvageFailureNote, salvageSessionDb } from "./salvage.js";
85
- import { mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, renameSync, statSync } from "node:fs";
85
+ import { mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, renameSync, rmSync, statSync } from "node:fs";
86
86
  import { lstat } from "node:fs/promises";
87
87
  import { ensurePrivateDir } from "../../dpi-sdk/src/node/private-dir.js";
88
88
  import { join, dirname, relative, resolve, sep } from "node:path";
@@ -433,6 +433,11 @@ export class Store {
433
433
  readonly models = createModels({ credentials: this.pi.credentials });
434
434
  readonly opened = new Map<string, Opened>();
435
435
  readonly errors = new Map<string, string>();
436
+ /** run-7 B1-A: archive() bumps this as its FIRST act; openAgent compares
437
+ * its entry snapshot before arming — a reopen that raced the archive
438
+ * window (opened.delete → rename → catalog DELETE) must not re-arm a live
439
+ * harness over the moved-away bundle. */
440
+ readonly archiveEpoch = new Map<string, number>();
436
441
  readonly catalog: DatabaseSync;
437
442
  readonly startedAt = Date.now();
438
443
  shared!: SharedState;
@@ -671,6 +676,23 @@ export class Store {
671
676
  }
672
677
  // Start dirs are where new sessions begin; create any that do not exist yet.
673
678
  await Promise.all(options.startDirs.map((dir) => mkdir(dir, { recursive: true }).catch(() => {})));
679
+ // run-7 D1: every git effect (status disclosure, watcher, .gitignore write)
680
+ // must stay under the start dirs even when git's repo discovery walks up
681
+ // from a contained slice to an enclosing repo rooted OUTSIDE the sandbox.
682
+ // Installed before any gitStatus call below can seed projects from a walk-up.
683
+ configureGitRootGuard(async (root) => {
684
+ // run-7 cold-1 M2: git prints FORWARD-SLASHED, drive-case-variant paths
685
+ // on win32 while realpath roots are backslashed — compare normalized
686
+ // forms or every Windows repo fails confinement (all git features die).
687
+ const norm = (p: string) =>
688
+ process.platform === "win32" ? p.replace(/\//g, "\\").replace(/\\+$/, "").toLowerCase() : p;
689
+ const sep = process.platform === "win32" ? "\\" : "/";
690
+ const n = norm(root);
691
+ return (await store.startDirRoots()).some((r) => {
692
+ const b = norm(r);
693
+ return !!b && (n === b || n.startsWith(b + sep));
694
+ });
695
+ });
674
696
  try {
675
697
  store.projects = await ProjectRegistry.open(store.projectsPath, {
676
698
  warn: (m) => process.emitWarning(`projects: ${m}`),
@@ -1535,6 +1557,9 @@ export class Store {
1535
1557
 
1536
1558
  /** Stop all work, close the harness and move its files to archive/. Nothing is deleted. */
1537
1559
  async archive(row: SessionRow) {
1560
+ // FIRST act, before any await: reopens racing the window below compare
1561
+ // against this epoch and fail like any dead row (run-7 B1-A).
1562
+ this.archiveEpoch.set(row.id, (this.archiveEpoch.get(row.id) ?? 0) + 1);
1538
1563
  const opened = this.opened.get(row.id);
1539
1564
  if (opened) {
1540
1565
  for (const record of await this.scanAll(opened.harness)) {
@@ -1633,14 +1658,30 @@ export class Store {
1633
1658
  // VALIDATED pre-move manifest, not restoreArchive's second, unpinned
1634
1659
  // re-read — a manifest swapped in during the move can no longer skew
1635
1660
  // id/dbPath (cwd stays the validated realpath either way).
1661
+ // run-7 B1-B: the create/rename choke points must hold for restores too
1662
+ // — a planted manifest (the r18 same-user-planter threat) must not land a
1663
+ // ~1MiB / control-char / reserved-'search' name or unbounded model strings
1664
+ // in the catalog: they reach every tree() broadcast, notify titles and
1665
+ // harness.root. A bad name degrades to a bounded fallback (the bundle
1666
+ // stays restorable); model strings are bounded and stripped.
1667
+ const rawName = pre?.name || manifest.name || "Untitled session";
1668
+ const name = (() => {
1669
+ try {
1670
+ return assertSessionName(rawName) || "Untitled session";
1671
+ } catch {
1672
+ return `archived-${sessionId.slice(0, 8)}`;
1673
+ }
1674
+ })();
1675
+ const boundModelish = (v: string | undefined): string | undefined =>
1676
+ typeof v === "string" ? v.replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 200) || undefined : undefined;
1636
1677
  const row: SessionRow = {
1637
1678
  id: sessionId,
1638
- name: pre?.name || manifest.name || "Untitled session",
1679
+ name,
1639
1680
  cwd: restoredCwd,
1640
1681
  dbPath: join(this.sessionsDir, sessionId, "agent.sqlite"),
1641
1682
  createdAt: pre?.createdAt ?? manifest.createdAt,
1642
- model: pre?.model ?? manifest.model,
1643
- provider: pre?.provider ?? manifest.provider,
1683
+ model: boundModelish(pre?.model ?? manifest.model) ?? "faux",
1684
+ provider: boundModelish(pre?.provider ?? manifest.provider) ?? "faux",
1644
1685
  };
1645
1686
  this.catalog.exec("BEGIN");
1646
1687
  try {
@@ -1663,15 +1704,39 @@ export class Store {
1663
1704
  async openAgent(row: SessionRow, create = false, thinkingLevel: ThinkingLevel = "medium") {
1664
1705
  const current = this.opened.get(row.id);
1665
1706
  if (current) return current.harness;
1707
+ const epoch = this.archiveEpoch.get(row.id) ?? 0; // run-7 B1-A: liveness is re-checked at the arm point
1666
1708
  // R20 (run-6 h6): attempt-once — the memo was only read by the search
1667
1709
  // path, so every agent-touching request re-ran the FULL salvage (leader
1668
1710
  // probe: 5.0 s per request on a corrupt session, unbounded). Fail fast
1669
1711
  // from the recorded fault without touching storage.
1670
1712
  if (!create && this.salvageFailedSessions.has(row.id))
1671
1713
  throw new ApiFault("unavailable", this.errors.get(row.id) ?? "session database is unreadable (salvage failed)");
1672
- if (!create) await stat(row.dbPath);
1673
- await mkdir(dirname(row.dbPath), { recursive: true });
1674
- const unlock = lockFile(`${row.dbPath}.lock`);
1714
+ let unlock: () => void;
1715
+ try {
1716
+ if (!create) await stat(row.dbPath);
1717
+ await mkdir(dirname(row.dbPath), { recursive: true });
1718
+ unlock = lockFile(`${row.dbPath}.lock`);
1719
+ } catch (e) {
1720
+ // run-7 B1-A (variant 3): archive() moved the session dir between the
1721
+ // entry stat and here — mkdir may have just RESURRECTED an empty
1722
+ // sessions/<id>/ husk that permanently blocks a later restore. When the
1723
+ // epoch proves archive ran in the window, remove the husk and refuse.
1724
+ if ((this.archiveEpoch.get(row.id) ?? 0) !== epoch) {
1725
+ // run-7 cold-1 M4: ONLY remove the empty husk THIS call resurrected —
1726
+ // a concurrent restore may have just moved the REAL bundle back into
1727
+ // sessions/<id>/ (the archive copy is consumed by the move); deleting
1728
+ // it would be unrecoverable data loss. A husk has no agent.sqlite.
1729
+ const dir = dirname(row.dbPath);
1730
+ let entries: string[] = [];
1731
+ try {
1732
+ entries = readdirSync(dir);
1733
+ } catch {}
1734
+ if (!entries.some((f) => f === "agent.sqlite" || f.endsWith(".sqlite-wal") || f.endsWith(".sqlite-shm")))
1735
+ rmSync(dir, { recursive: true, force: true });
1736
+ throw new ApiFault("unavailable", "session was archived while opening");
1737
+ }
1738
+ throw e;
1739
+ }
1675
1740
  try {
1676
1741
  const shellEnv = Object.fromEntries(
1677
1742
  ["PATH", "HOME", "USER", "SHELL", "TMPDIR", "LANG", "TERM"].flatMap((k) =>
@@ -1787,6 +1852,15 @@ export class Store {
1787
1852
  row.model = rootModel.modelId;
1788
1853
  this.catalog.prepare("UPDATE sessions SET provider=?,model=? WHERE id=?").run(row.provider, row.model, row.id);
1789
1854
  const unsubscribe = harness.subscribeCommits(() => this.notify());
1855
+ // run-7 B1-A: the row was ALIVE at entry, but archive() may have moved
1856
+ // the session dir away while the opens above were awaiting — arming now
1857
+ // would park a live harness over the archived bundle (post-archive
1858
+ // writes, mis-bound restores, silent loss when gc unlinks it).
1859
+ if ((this.archiveEpoch.get(row.id) ?? 0) !== epoch) {
1860
+ await harness.close(ctx).catch(() => {});
1861
+ unlock();
1862
+ throw new ApiFault("unavailable", "session was archived while opening");
1863
+ }
1790
1864
  this.opened.set(row.id, { harness, unlock, unsubscribe, jobs, addons });
1791
1865
  this.errors.delete(row.id);
1792
1866
  // pi-durable 1.2+: any failed Storage call closes the Session, without waiting for the next event.
@@ -1930,18 +2004,33 @@ export class Store {
1930
2004
  // version (git truth, not snapshots) and re-apply the recorded tool calls
1931
2005
  // in order; a turn's ±n is the net line delta at its boundary.
1932
2006
  const lines = (t: string | null | undefined) => (t == null ? 0 : t.split("\n").length - (t.endsWith("\n") ? 1 : 0));
1933
- let root = "";
2007
+ // run-7 cold-2 M3: this was the ONE git effect skipping the confinement
2008
+ // the store itself installs — discovery could walk up out of a start-dir
2009
+ // slice (or a planted .git gitdir redirect) and make `git show HEAD:<rel>`
2010
+ // an existence oracle over an OUTSIDE repo, with rel bounded against the
2011
+ // foreign root. Resolve the pin through the same guard, pin both spawns,
2012
+ // and bound rel against the PINNED (validated) worktree.
2013
+ const { resolveRepoPin } = await import("./git.js");
2014
+ let pin: Awaited<ReturnType<typeof resolveRepoPin>> = undefined;
1934
2015
  try {
1935
- root = (await git(row.cwd, ["rev-parse", "--show-toplevel"])).trim();
1936
- } catch {
1937
- root = row.cwd;
1938
- }
2016
+ pin = await resolveRepoPin(row.cwd);
2017
+ } catch (e) {
2018
+ // Fail CLOSED on confinement AND on transient resolve failures (a
2019
+ // timeout here with a later unpinned walk-up spawn succeeding would
2020
+ // reopen the counts oracle for that request). Only a GENUINE non-repo
2021
+ // (the common case before the first commit) keeps the no-pin fallback.
2022
+ const msg = String((e as Error).message);
2023
+ if (msg.includes("start dirs")) return [];
2024
+ if (!msg.includes("not a git repository")) return [];
2025
+ }
2026
+ const root = pin?.workTree ?? row.cwd;
2027
+ const gP = (args: string[]) => git(row.cwd, args, undefined, pin);
1939
2028
  const headOf = async (p: string) => {
1940
2029
  const abs = resolve(row.cwd, p);
1941
2030
  const rel = relative(root, abs);
1942
2031
  if (!rel || rel.startsWith("..")) return null;
1943
2032
  try {
1944
- return await git(row.cwd, ["show", `HEAD:${rel}`]);
2033
+ return await gP(["show", `HEAD:${rel}`]);
1945
2034
  } catch {
1946
2035
  return null;
1947
2036
  }