my-durable 0.0.60 → 0.0.62

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.
@@ -0,0 +1,284 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * R8 store-perf benchmark — plain node script, no test framework.
4
+ *
5
+ * Measures per-op latency (p50/p95/max in ms) of the real Store APIs against a
6
+ * throwaway sandbox home (default /tmp/r8perf), plus a paired raw-sqlite
7
+ * commit control (synchronous=FULL vs NORMAL) so any catalog pragma change is
8
+ * evidence-backed rather than assumed.
9
+ *
10
+ * Mix (flags tune the counts):
11
+ * - N session creates (Store.create → catalog INSERT + per-session sqlite open)
12
+ * - M catalog insert+commit cycles (BEGIN/INSERT/COMMIT on the real catalog,
13
+ * the exact shape idempotency.ts writes per POST)
14
+ * - A entry appends (conversation commit → tx.appendEntry → per-session DB)
15
+ * - P entry-list pages (Store.entries, first-page + full-walk pages)
16
+ * - G git-status cycles (fresh spawn each, cache bypassed via a future `now`)
17
+ *
18
+ * Run with the backend's tsx loader (same as `npm start`):
19
+ * cd apps/dpi-backend && node --import tsx scripts/bench-store.mjs
20
+ * (equivalently: npx tsx scripts/bench-store.mjs)
21
+ *
22
+ * Flags: --home /tmp/r8perf --sessions 100 --appends 2000 --pages 500
23
+ * --git 6 --catalog-commits 300 --label before
24
+ *
25
+ * The sandbox home's data dir is WIPED at start so every run (before/after a
26
+ * store change) starts from the same empty state.
27
+ */
28
+ import { BACKGROUND_CONTEXT as ctx } from "@earendil-works/chord/context";
29
+ import { DatabaseSync } from "node:sqlite";
30
+ import { execFileSync } from "node:child_process";
31
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
32
+ import { join } from "node:path";
33
+ import { loadavg } from "node:os";
34
+ import { performance } from "node:perf_hooks";
35
+ import { randomUUID } from "node:crypto";
36
+ import { fileURLToPath } from "node:url";
37
+ import { dirname } from "node:path";
38
+
39
+ const here = dirname(fileURLToPath(import.meta.url));
40
+ const { Store } = await import(join(here, "../src/store.js"));
41
+ const { gitStatus } = await import(join(here, "../src/git.js"));
42
+
43
+ // ---------------------------------------------------------------- flags
44
+ const arg = (name, fallback) => {
45
+ const i = process.argv.indexOf(`--${name}`);
46
+ return i >= 0 && process.argv[i + 1] !== undefined ? process.argv[i + 1] : fallback;
47
+ };
48
+ const HOME = String(arg("home", "/tmp/r8perf"));
49
+ const N_SESSIONS = Number(arg("sessions", 100));
50
+ const N_APPENDS = Number(arg("appends", 2000));
51
+ const N_PAGES = Number(arg("pages", 500));
52
+ const N_GIT = Number(arg("git", 6));
53
+ const N_CATALOG_COMMITS = Number(arg("catalog-commits", 300));
54
+ const LABEL = String(arg("label", "run"));
55
+
56
+ // ---------------------------------------------------------------- sandbox
57
+ const DATA_DIR = join(HOME, "backend");
58
+ const WORK = join(HOME, "work");
59
+ const REPO = join(WORK, "repo");
60
+ rmSync(DATA_DIR, { recursive: true, force: true });
61
+ rmSync(REPO, { recursive: true, force: true });
62
+ mkdirSync(join(REPO, "nested"), { recursive: true });
63
+ writeFileSync(join(REPO, "README.md"), "# r8 bench\n");
64
+ const git = (...args) => execFileSync("git", args, { cwd: REPO, stdio: "ignore" });
65
+ git("init", "-q");
66
+ git("config", "user.email", "bench@example.com");
67
+ git("config", "user.name", "r8 bench");
68
+ git("add", ".");
69
+ git("commit", "-qm", "bench seed");
70
+
71
+ // ---------------------------------------------------------------- stats
72
+ const pct = (samples, p) => {
73
+ const s = [...samples].sort((a, b) => a - b);
74
+ const idx = Math.min(s.length - 1, Math.max(0, Math.ceil((p / 100) * s.length) - 1));
75
+ return s[idx];
76
+ };
77
+ const mean = (s) => s.reduce((a, b) => a + b, 0) / s.length;
78
+ const r = (ms) => (ms >= 100 ? Math.round(ms) : Math.round(ms * 1000) / 1000);
79
+ const results = [];
80
+ const bench = (name, count, fn) => {
81
+ const samples = [];
82
+ const t0 = performance.now();
83
+ for (let i = 0; i < count; i += 1) {
84
+ const s = performance.now();
85
+ fn(i);
86
+ samples.push(performance.now() - s);
87
+ }
88
+ const total = performance.now() - t0;
89
+ const row = {
90
+ op: name,
91
+ count,
92
+ totalMs: r(total),
93
+ meanMs: r(mean(samples)),
94
+ p50: r(pct(samples, 50)),
95
+ p95: r(pct(samples, 95)),
96
+ max: r(Math.max(...samples)),
97
+ over20ms: samples.filter((x) => x > 20).length,
98
+ };
99
+ results.push(row);
100
+ return row;
101
+ };
102
+ const benchAsync = async (name, count, fn) => {
103
+ const samples = [];
104
+ const t0 = performance.now();
105
+ for (let i = 0; i < count; i += 1) {
106
+ const s = performance.now();
107
+ await fn(i);
108
+ samples.push(performance.now() - s);
109
+ }
110
+ const total = performance.now() - t0;
111
+ const row = {
112
+ op: name,
113
+ count,
114
+ totalMs: r(total),
115
+ meanMs: r(mean(samples)),
116
+ p50: r(pct(samples, 50)),
117
+ p95: r(pct(samples, 95)),
118
+ max: r(Math.max(...samples)),
119
+ over20ms: samples.filter((x) => x > 20).length,
120
+ };
121
+ results.push(row);
122
+ return row;
123
+ };
124
+
125
+ // ---------------------------------------------------------------- run
126
+ const started = performance.now();
127
+ const load0 = loadavg()[0];
128
+ console.log(`[r8-bench] home=${HOME} label=${LABEL} load1m(start)=${load0.toFixed(2)}`);
129
+
130
+ const store = await Store.open({
131
+ dataDir: DATA_DIR,
132
+ startDirs: [WORK],
133
+ name: "r8-bench",
134
+ provider: "faux",
135
+ });
136
+
137
+ // 1) Session creates: catalog insert + openAgent (fresh per-session sqlite) + gitStatus.
138
+ console.log("[r8-bench] store open — starting session.create");
139
+ const ids = [];
140
+ await benchAsync("session.create", N_SESSIONS, async (i) => {
141
+ const s = await store.create({ name: `bench-${String(i).padStart(4, "0")}`, cwd: REPO });
142
+ ids.push(s.id);
143
+ });
144
+ console.log("[r8-bench] session.create done");
145
+
146
+ // 2) Catalog insert+commit cycles — the exact write shape idempotency.ts does per POST.
147
+ // This is the pragma-sensitive path: journal WAL + synchronous=<default FULL> today.
148
+ const insert = store.catalog.prepare(
149
+ "INSERT OR REPLACE INTO requests(key,route,status,body,createdAt) VALUES(?,?,?,?,?)",
150
+ );
151
+ console.log("[r8-bench] starting catalog.insert+commit");
152
+ bench("catalog.insert+commit", N_CATALOG_COMMITS, (i) => {
153
+ store.catalog.exec("BEGIN");
154
+ try {
155
+ insert.run(`bench-${LABEL}-${i}`, "POST /v1/sessions", 201, '"bench"', Date.now());
156
+ store.catalog.exec("COMMIT");
157
+ } catch (e) {
158
+ store.catalog.exec("ROLLBACK");
159
+ throw e;
160
+ }
161
+ });
162
+
163
+ // 2b) openAgent isolation: catalog rows inserted by hand, then ONLY the harness/sqlite
164
+ // open is timed — splits session.create's cost between the catalog write and the
165
+ // per-session DB open (migrations + Harness.open).
166
+ const agentRows = [];
167
+ for (let i = 0; i < Math.min(10, N_SESSIONS); i += 1) {
168
+ const base = store.row(ids[i]);
169
+ const id = randomUUID();
170
+ const row = {
171
+ id,
172
+ name: `bench-agent-${String(i).padStart(4, "0")}`,
173
+ cwd: REPO,
174
+ dbPath: join(store.sessionsDir, id, "agent.sqlite"),
175
+ createdAt: Date.now(),
176
+ model: base.model,
177
+ provider: base.provider,
178
+ };
179
+ store.catalog
180
+ .prepare("INSERT INTO sessions(id,name,cwd,dbPath,createdAt,model,provider) VALUES(?,?,?,?,?,?,?)")
181
+ .run(row.id, row.name, row.cwd, row.dbPath, row.createdAt, row.model, row.provider);
182
+ agentRows.push(row);
183
+ }
184
+ await benchAsync("agent.open(solo)", agentRows.length, async (i) => {
185
+ await store.openAgent(agentRows[i], true);
186
+ });
187
+
188
+ // 3) Entry appends into session 0's conversation (real append API: commit → tx.appendEntry).
189
+ console.log("[r8-bench] starting entry.append");
190
+ const row0 = store.row(ids[0]);
191
+ const { c } = await store.resolveAgent(row0.id, "main");
192
+ await benchAsync("entry.append", N_APPENDS, async (i) => {
193
+ await c.commit(async (tx) => {
194
+ await tx.appendEntry(c.id, {
195
+ kind: "bench.entry",
196
+ data: { i, text: `r8 benchmark entry ${i} — realistic mixed-length payload ${"x".repeat(80 + (i % 120))}` },
197
+ });
198
+ }, ctx);
199
+ });
200
+
201
+ // 4) Entry-list pages: first page re-reads (UI poll shape) + one full walk (deep pages).
202
+ console.log("[r8-bench] starting entries pages");
203
+ await benchAsync("entries.page(first)", N_PAGES, async () => {
204
+ const page = await store.entries(c, undefined, 100);
205
+ if (!page.items.length) throw Error("expected entries");
206
+ });
207
+ await benchAsync("entries.page(full-walk)", N_PAGES, async () => {
208
+ let cursor;
209
+ let pages = 0;
210
+ let items = 0;
211
+ for (;;) {
212
+ const page = await store.entries(c, cursor, 100);
213
+ pages += 1;
214
+ items += page.items.length;
215
+ cursor = page.next;
216
+ if (!cursor) break;
217
+ if (pages > 500) throw Error("walk did not terminate");
218
+ }
219
+ if (items === 0) throw Error("expected entries");
220
+ });
221
+
222
+ // 5) Git-status cycles: fresh git spawn each time (cache bypassed via a future `now`).
223
+ console.log("[r8-bench] starting git.status");
224
+ const futureNow = () => Date.now() + 3_600_000;
225
+ bench("git.status(fresh)", N_GIT, (i) => {
226
+ writeFileSync(join(REPO, `scratch-${i}.txt`), `dirty ${i}\n`);
227
+ const st = gitStatus(REPO, futureNow());
228
+ if (!st) throw Error("no status");
229
+ });
230
+
231
+ // 6) Paired pragma control on throwaway files: identical commit loop, FULL vs NORMAL.
232
+ // Directly quantifies what the catalog's missing synchronous=NORMAL costs per commit.
233
+ console.log("[r8-bench] starting pragma control");
234
+ const pragmaControl = (path, synchronous) => {
235
+ const db = new DatabaseSync(path);
236
+ db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=${synchronous};
237
+ CREATE TABLE IF NOT EXISTS requests(key TEXT PRIMARY KEY,route TEXT NOT NULL,status INTEGER NOT NULL,body TEXT NOT NULL,createdAt INTEGER NOT NULL);`);
238
+ const ins = db.prepare("INSERT OR REPLACE INTO requests(key,route,status,body,createdAt) VALUES(?,?,?,?,?)");
239
+ const samples = [];
240
+ for (let i = 0; i < N_CATALOG_COMMITS; i += 1) {
241
+ const s = performance.now();
242
+ db.exec("BEGIN");
243
+ ins.run(`ctl-${synchronous}-${i}`, "POST /v1/sessions", 201, '"ctl"', Date.now());
244
+ db.exec("COMMIT");
245
+ samples.push(performance.now() - s);
246
+ }
247
+ db.close();
248
+ return samples;
249
+ };
250
+ const full = pragmaControl(join(HOME, "ctl-full.sqlite"), "FULL");
251
+ const normal = pragmaControl(join(HOME, "ctl-normal.sqlite"), "NORMAL");
252
+ for (const [name, samples] of [
253
+ ["control.commit(sync=FULL)", full],
254
+ ["control.commit(sync=NORMAL)", normal],
255
+ ]) {
256
+ results.push({
257
+ op: name,
258
+ count: samples.length,
259
+ totalMs: r(samples.reduce((a, b) => a + b, 0)),
260
+ meanMs: r(mean(samples)),
261
+ p50: r(pct(samples, 50)),
262
+ p95: r(pct(samples, 95)),
263
+ max: r(Math.max(...samples)),
264
+ over20ms: samples.filter((x) => x > 20).length,
265
+ });
266
+ }
267
+
268
+ await store.close().catch(() => {});
269
+
270
+ // ---------------------------------------------------------------- report
271
+ const pad = (v, n) => String(v).padStart(n);
272
+ console.log(`\n[r8-bench] label=${LABEL} totalMs=${r(performance.now() - started)} load1m(end)=${loadavg()[0].toFixed(2)}`);
273
+ console.log(
274
+ `${pad("op", 26)} ${pad("count", 7)} ${pad("totalMs", 9)} ${pad("meanMs", 9)} ${pad("p50", 9)} ${pad("p95", 9)} ${pad("max", 9)} ${pad(">20ms", 7)}`,
275
+ );
276
+ for (const row of results)
277
+ console.log(
278
+ `${pad(row.op, 26)} ${pad(row.count, 7)} ${pad(row.totalMs, 9)} ${pad(row.meanMs, 9)} ${pad(row.p50, 9)} ${pad(row.p95, 9)} ${pad(row.max, 9)} ${pad(row.over20ms, 7)}`,
279
+ );
280
+ writeFileSync(join(HOME, `bench-${LABEL}.json`), JSON.stringify({ label: LABEL, home: HOME, results }, null, 2));
281
+ console.log(`[r8-bench] json → ${join(HOME, `bench-${LABEL}.json`)}`);
282
+ // The Store's watchers (awake/git/telegram timers) keep the event loop alive after
283
+ // close(); the measurements are done — exit explicitly.
284
+ process.exit(0);
@@ -40,7 +40,7 @@ const FILE_MODE = 0o600;
40
40
  const DIR_MODE = 0o700;
41
41
 
42
42
  /** `<uuid>-<archivedAtMs>`: the only identity an old bundle has. 36 uuid chars + 13 ms digits. */
43
- const BUNDLE_DIR_PATTERN = /^([0-9a-f-]{36})-(\d{13})$/;
43
+ export const BUNDLE_DIR_PATTERN = /^([0-9a-f-]{36})-(\d{13})$/;
44
44
  /** Full lowercase uuid, 8-4-4-4-12: a PREFIX of another uuid must never match a bundle. */
45
45
  const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
46
46
 
@@ -77,11 +77,17 @@ export function serviceEnv(env: Record<string, string | undefined>): Record<stri
77
77
  return out;
78
78
  }
79
79
 
80
- /** The env the detached child inherits: drop the Electron-node hazards (paseo lesson). */
80
+ /** The env the detached child inherits: drop the Electron-node hazards (paseo lesson)
81
+ * and the R6 relaunch marker. DPI_WRAPPER_PID is the launcher wrapper's pid for the
82
+ * 2s orphan-watch in bin/dpi.mjs — a DETACHED daemon outlives that wrapper by days
83
+ * (the wrapper exits as soon as `device start` returns), so inheriting the marker
84
+ * made every started daemon kill itself the moment its start shell's wrapper went
85
+ * away. The daemon is its own supervisor; it must never watch a short-lived pid. */
81
86
  export function cleanChildEnv(env: Record<string, string | undefined>): NodeJS.ProcessEnv {
82
87
  const out: NodeJS.ProcessEnv = { ...env };
83
88
  delete out.ELECTRON_RUN_AS_NODE;
84
89
  delete out.ELECTRON_NO_ATTACH_CONSOLE;
90
+ delete out.DPI_WRAPPER_PID;
85
91
  return out;
86
92
  }
87
93
 
@@ -7,11 +7,17 @@
7
7
  * explicitly. `--dry-run` is the default at the CLI, following piggery's
8
8
  * `gc --closed-before DURATION [--dry-run]` shape.
9
9
  *
10
- * An archived session directory is `<archiveDir>/<sessionId>-<closedAtMs>`, so
11
- * age and size are readable without opening any database.
10
+ * An archived session directory is `<archiveDir>/<uuid>-<closedAtMs>` — parsed
11
+ * with the SAME strict `BUNDLE_DIR_PATTERN` the archive browser and restore use
12
+ * (audit 3.1: the old loose `<name>-<10+ digits>` form let gc delete operator
13
+ * directories like `nas-backup-2025010112` that the UI never listed). Any
14
+ * directory in archive/ that does not parse strictly — or whose closedAt is out
15
+ * of range — is reported as skipped and never deleted, so age and size remain
16
+ * readable without opening any database.
12
17
  */
13
18
  import { readdir, rm, stat } from "node:fs/promises";
14
19
  import { join } from "node:path";
20
+ import { BUNDLE_DIR_PATTERN } from "./archived.js";
15
21
 
16
22
  export interface ArchivedEntry {
17
23
  /** Directory name inside archive/. */
@@ -49,16 +55,25 @@ async function dirBytes(path: string): Promise<number> {
49
55
  return total;
50
56
  }
51
57
 
52
- /** Parse `<sessionId>-<closedAtMs>`; anything else is reported as skipped, never guessed at. */
58
+ /**
59
+ * Parse `<uuid>-<closedAtMs>` with the exact strict pattern the archive browser
60
+ * and restore use (`archived.ts` BUNDLE_DIR_PATTERN); anything else is reported
61
+ * as skipped, never guessed at. A shape-match with an out-of-range value (13
62
+ * zeros → closedAt 0) is refused too: skip, don't delete.
63
+ */
53
64
  export function parseArchivedName(name: string): { sessionId: string; closedAt: number } | undefined {
54
- const match = /^(.+)-(\d{10,})$/u.exec(name);
65
+ const match = BUNDLE_DIR_PATTERN.exec(name);
55
66
  if (!match) return undefined;
56
67
  const closedAt = Number(match[2]);
57
68
  if (!Number.isFinite(closedAt) || closedAt <= 0) return undefined;
58
69
  return { sessionId: match[1], closedAt };
59
70
  }
60
71
 
61
- export async function archivedEntries(archiveDir: string): Promise<{ entries: ArchivedEntry[]; skipped: GcPlan["skipped"] }> {
72
+ export async function archivedEntries(
73
+ archiveDir: string,
74
+ /** Clock for the future-closedAt guard; defaults to wall time. */
75
+ now: number = Date.now(),
76
+ ): Promise<{ entries: ArchivedEntry[]; skipped: GcPlan["skipped"] }> {
62
77
  const entries: ArchivedEntry[] = [];
63
78
  const skipped: GcPlan["skipped"] = [];
64
79
  for (const entry of await readdir(archiveDir, { withFileTypes: true }).catch(() => [])) {
@@ -68,6 +83,12 @@ export async function archivedEntries(archiveDir: string): Promise<{ entries: Ar
68
83
  skipped.push({ name: entry.name, reason: "not an archived-session directory" });
69
84
  continue;
70
85
  }
86
+ if (parsed.closedAt > now) {
87
+ // A bundle stamped in the future (bad clock, corrupted name) is reported
88
+ // and never considered for deletion.
89
+ skipped.push({ name: entry.name, reason: "closedAt is in the future — never auto-deleted" });
90
+ continue;
91
+ }
71
92
  const path = join(archiveDir, entry.name);
72
93
  entries.push({ name: entry.name, path, ...parsed, bytes: await dirBytes(path) });
73
94
  }
@@ -81,7 +102,7 @@ export async function gcPlan(archiveDir: string, options: { closedBeforeDays: nu
81
102
  // Sub-day cutoffs are legal (R5 finding 6): the CLI advertises 90m/12h and
82
103
  // parseDuration delivers them as fractional days. Only non-positive values refuse.
83
104
  if (!Number.isFinite(days) || days <= 0) throw new Error(`closedBeforeDays must be positive, got ${String(days)}`);
84
- const { entries, skipped } = await archivedEntries(archiveDir);
105
+ const { entries, skipped } = await archivedEntries(archiveDir, now);
85
106
  const cutoff = now - days * 86_400_000;
86
107
  const candidates = entries
87
108
  .filter((entry) => entry.closedAt <= cutoff)
@@ -15,6 +15,7 @@ import { DevicePairing } from "./pairing.js";
15
15
  import { DeviceConnector, readCaPem } from "./tunnel.js";
16
16
  import { PAIR_PAGE_HTML } from "./pair-page.js";
17
17
  import { parseDeviceSub, runDeviceCommand, daemonPaths, boundedStep } from "./daemon.js";
18
+ import { startEventLoopMonitor } from "./vitals.js";
18
19
 
19
20
  // `dpi device start|stop|status|install|uninstall` manage a background daemon
20
21
  // and exit; everything else (bare `dpi device` or flags) runs the daemon here.
@@ -25,6 +26,11 @@ import { parseDeviceSub, runDeviceCommand, daemonPaths, boundedStep } from "./da
25
26
 
26
27
  assertLimitsConfig();
27
28
 
29
+ // Event-loop lag sampling starts before anything else can block: if boot
30
+ // itself stalls (sync SQLite migrations, registry writes), the first vitals
31
+ // window records it. Idempotent; vitals() also starts it lazily.
32
+ startEventLoopMonitor();
33
+
28
34
  // Crash reports (policy gate #1) are installed FIRST, before anything below can
29
35
  // throw: a config or store failure still leaves a redacted local report (nothing
30
36
  // is ever uploaded). The state getter reads the store lazily — before it opens,
@@ -1,11 +1,14 @@
1
1
  // REST v1. Every route requires the device token (see auth.ts). Session refs are a UUID or a
2
2
  // unique name; agent refs are a numeric id, `main`, or a unique name.
3
3
  import { Router, type Request, type Response, type NextFunction } from "express";
4
+ import { createReadStream } from "node:fs";
5
+ import { pipeline } from "node:stream/promises";
4
6
  import type { Conversation, Harness } from "@earendil-works/pi-durable";
5
7
  import { DEVICE_DOC_KINDS, type SessionRow, type Store } from "./store.js";
6
8
  import { agentStream, deviceStream, sessionStream } from "./streams.js";
7
9
  import { idempotent } from "./idempotency.js";
8
10
  import { invalid, notFound } from "./errors.js";
11
+ import { streamSessionBundle } from "./zip.js";
9
12
  import type { DevicePairing } from "./pairing.js";
10
13
 
11
14
  type Async = (req: Request, res: Response) => Promise<unknown>;
@@ -332,7 +335,27 @@ export function v1(
332
335
  res.status(201).json(await store.restoreArchivedSession(param(req, "id"))),
333
336
  ));
334
337
  // One downloadable .zip: manifest + session record + every agent's transcript/config.
335
- r.get("/sessions/:s/export", route(async (_req, res) => res.json(await store.exportSession(L(res).row))));
338
+ // R8: the bundle streams through a temp file (deflate piped to disk, never the
339
+ // whole archive in RAM) and the route pipes that file out, unlinks it in the
340
+ // finally, and speaks plain zip bytes — Content-Disposition names the download.
341
+ // Guards (256 MiB uncompressed ceiling, zip64-less limits) run during the temp
342
+ // write, so refusals surface as the usual JSON faults before any byte is sent.
343
+ r.get(
344
+ "/sessions/:s/export",
345
+ route(async (_req, res) => {
346
+ const bundle = await streamSessionBundle(store, L(res).row);
347
+ try {
348
+ res.set({
349
+ "Content-Type": bundle.mime,
350
+ "Content-Length": String(bundle.bytes),
351
+ "Content-Disposition": `attachment; filename="${bundle.filename}"`,
352
+ });
353
+ await pipeline(createReadStream(bundle.path), res);
354
+ } finally {
355
+ await bundle.cleanup();
356
+ }
357
+ }),
358
+ );
336
359
  r.get("/sessions/:s/events", route(async (_req, res) => sessionStream(store, L(res).row, res)));
337
360
  // The zcode flagship, adapted: which files has THIS session's agent touched?
338
361
  // Powers "commit session changes" in the git panel.
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Bounded, single-attempt salvage of an unreadable session database (R7).
3
+ *
4
+ * R5 store audit finding: garbage in the SQLite header (the audit recipe wrote
5
+ * 0x41 over bytes 32-64) hides intact data forever — the close-path WAL
6
+ * checkpoint folds the WAL into the corrupt main file without ever fixing
7
+ * page 1, and the only recovery was a manual header patch. The auditor proved
8
+ * the patch on a copy: fix the first 100 header bytes, integrity_check passes,
9
+ * every entry reads back.
10
+ *
11
+ * `salvageSessionDb` automates exactly that, conservatively:
12
+ *
13
+ * 1. COPY the db aside (`<db>.salvage`, plus its `-wal`/`-shm` sidecars when
14
+ * present, so an unclean shutdown's frames replay onto the copy). The
15
+ * original file is NEVER opened for write and never modified.
16
+ * 2. Patch the copy's first 100 header bytes: restore the magic string, a
17
+ * legal page size and versions when they are garbage, zero the freelist
18
+ * and the auto-vacuum root page (garbage there turns ptrmap validation
19
+ * on), and re-seat the schema-format and text-encoding fields. Every
20
+ * write targets header fields sqlite validates at open; page data is
21
+ * untouched, so a wrong guess can only fail integrity_check, never
22
+ * "recover" to something wrong.
23
+ * 3. `PRAGMA integrity_check` on the copy. Only "ok" counts.
24
+ * 4. Promote on the caller's thread: the original is renamed aside
25
+ * (`<db>.corrupt-<ts>` — the house quarantine rule: it is the only copy
26
+ * of that data, so it is kept, never deleted) and the copy is atomically
27
+ * renamed into place.
28
+ *
29
+ * The whole attempt runs in a worker thread under a hard time ceiling
30
+ * (`SALVAGE_CEILING_MS`): `PRAGMA integrity_check` is synchronous, so on a
31
+ * pathological multi-gigabyte database the only honest bound is terminating
32
+ * the worker — the device's event loop never stalls, and the open path fails
33
+ * on schedule instead of hanging. On timeout or any failure the copy files
34
+ * are removed and the original is left byte-identical.
35
+ */
36
+ import { Worker } from "node:worker_threads";
37
+ import { existsSync, renameSync, rmSync } from "node:fs";
38
+
39
+ /** The open path must never hang on salvage: everything above this ceiling is abandoned. */
40
+ export const SALVAGE_CEILING_MS = 5_000;
41
+
42
+ /** What happened to ONE salvage attempt. Bounded and secret-free — it reaches operator surfaces. */
43
+ export interface SalvageOutcome {
44
+ /** Always true when salvageSessionDb returned: the attempt was made. */
45
+ attempted: boolean;
46
+ /** The patched copy passed integrity_check and was promoted into place. */
47
+ recovered: boolean;
48
+ /** Why the salvage did not recover, when it did not. */
49
+ reason?: string;
50
+ /** Where the original (still corrupt) file was kept when promotion happened. */
51
+ keptAs?: string;
52
+ }
53
+
54
+ /**
55
+ * The copy/patch/integrity_check work, as plain CommonJS so it can run in a
56
+ * `new Worker(src, { eval: true })` thread. No imports of project code: the
57
+ * worker is self-contained and terminable at any instruction.
58
+ */
59
+ const WORKER_SRC = `
60
+ const { parentPort, workerData } = require("node:worker_threads");
61
+ const { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } = require("node:fs");
62
+ const { DatabaseSync } = require("node:sqlite");
63
+ const main = workerData.dbPath;
64
+ const copy = main + ".salvage";
65
+ const fail = (reason) => parentPort.postMessage({ ok: false, reason: String(reason).slice(0, 80) });
66
+ function run() {
67
+ try {
68
+ // 1. Copy main + sidecars aside. The original is only ever read.
69
+ rmSync(copy, { force: true });
70
+ copyFileSync(main, copy);
71
+ for (const suffix of ["-wal", "-shm"]) {
72
+ if (existsSync(main + suffix)) copyFileSync(main + suffix, copy + suffix);
73
+ else rmSync(copy + suffix, { force: true });
74
+ }
75
+ // 2. Patch the copy's header: only fields sqlite validates at open (see module doc).
76
+ const b = readFileSync(copy);
77
+ const MAGIC = "SQLite format 3\\0";
78
+ if (b.slice(0, 16).toString("latin1") !== MAGIC) b.write(MAGIC, 0, 16, "latin1");
79
+ const pageSize = b.readUInt16BE(16);
80
+ const legalPageSize = pageSize === 1 || (pageSize >= 512 && pageSize <= 32768 && (pageSize & (pageSize - 1)) === 0);
81
+ if (!legalPageSize) b.writeUInt16BE(4096, 16); // sqlite's default; a wrong guess fails integrity, never lies
82
+ if (b[18] !== 1 && b[18] !== 2) b[18] = 2; // write version: WAL (pi-durable's journal mode)
83
+ if (b[19] !== 1 && b[19] !== 2) b[19] = 2; // read version
84
+ if (b[20] > 32) b[20] = 0; // reserved bytes per page: node:sqlite uses 0
85
+ b.writeUInt32BE(0, 32); // first freelist trunk page (garbage here = freelist corruption)
86
+ b.writeUInt32BE(0, 36); // freelist page count
87
+ const schemaFormat = b.readUInt32BE(44);
88
+ if (!(schemaFormat >= 1 && schemaFormat <= 4)) b.writeUInt32BE(4, 44); // "unsupported file format" otherwise
89
+ b.writeUInt32BE(0, 52); // largest root b-tree page: nonzero garbage turns ptrmap validation on
90
+ const encoding = b.readUInt32BE(56);
91
+ if (!(encoding >= 1 && encoding <= 3)) b.writeUInt32BE(1, 56); // UTF-8
92
+ writeFileSync(copy, b);
93
+ // 3. Integrity is the ONLY gate for promotion.
94
+ let db;
95
+ try {
96
+ db = new DatabaseSync(copy); // read-write: a copied -wal may need recovery replay
97
+ const rows = db.prepare("PRAGMA integrity_check").all();
98
+ const ok = rows.length === 1 && rows[0].integrity_check === "ok";
99
+ if (!ok) {
100
+ db.close();
101
+ db = undefined;
102
+ parentPort.postMessage({ ok: false, reason: "integrity check failed" });
103
+ return;
104
+ }
105
+ // Fold any replayed WAL into the copy so the promoted file is self-contained
106
+ // (the same checkpoint pi-durable's own close runs).
107
+ db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
108
+ db.close();
109
+ db = undefined;
110
+ parentPort.postMessage({ ok: true });
111
+ } finally {
112
+ try { db && db.close(); } catch (e) {}
113
+ }
114
+ } catch (error) {
115
+ fail((error && error.message) || error);
116
+ }
117
+ }
118
+ run();
119
+ `;
120
+
121
+ const rmCopyFiles = (dbPath: string) => {
122
+ for (const suffix of [".salvage", ".salvage-wal", ".salvage-shm"]) rmSync(dbPath + suffix, { force: true });
123
+ };
124
+
125
+ /** Promote the verified copy: original aside (kept), copy atomically into place. */
126
+ const promote = (dbPath: string): string => {
127
+ const aside = `${dbPath}.corrupt-${Date.now()}`;
128
+ renameSync(dbPath, aside);
129
+ for (const suffix of ["-wal", "-shm"]) if (existsSync(dbPath + suffix)) renameSync(dbPath + suffix, `${aside}${suffix}`);
130
+ renameSync(`${dbPath}.salvage`, dbPath);
131
+ rmCopyFiles(dbPath); // the copy's own sidecars were checkpointed away; drop leftovers
132
+ return aside;
133
+ };
134
+
135
+ /**
136
+ * ONE bounded salvage attempt for the session db at `dbPath`. Resolves — never
137
+ * rejects: a salvage that cannot run is a failed salvage, and the caller's
138
+ * failure surface (not this module) owns what the client sees.
139
+ */
140
+ export function salvageSessionDb(dbPath: string, ceilingMs: number = SALVAGE_CEILING_MS): Promise<SalvageOutcome> {
141
+ return new Promise((resolve) => {
142
+ let worker: Worker;
143
+ try {
144
+ worker = new Worker(WORKER_SRC, { eval: true, workerData: { dbPath } });
145
+ } catch {
146
+ resolve({ attempted: false, recovered: false, reason: "salvage worker unavailable" });
147
+ return;
148
+ }
149
+ let settled = false;
150
+ const finish = (result: SalvageOutcome) => {
151
+ if (settled) return;
152
+ settled = true;
153
+ clearTimeout(timer);
154
+ void worker.terminate().catch(() => {});
155
+ let outcome = result;
156
+ if (outcome.recovered) {
157
+ try {
158
+ outcome = { ...outcome, keptAs: promote(dbPath) };
159
+ } catch {
160
+ outcome = { attempted: true, recovered: false, reason: "promotion failed" };
161
+ }
162
+ }
163
+ if (!outcome.recovered) rmCopyFiles(dbPath);
164
+ resolve(outcome);
165
+ };
166
+ const timer = setTimeout(() => {
167
+ finish({ attempted: true, recovered: false, reason: `timed out after ${ceilingMs}ms` });
168
+ }, Math.max(0, ceilingMs));
169
+ worker.once("message", (message: { ok?: boolean; reason?: string }) => {
170
+ if (message?.ok) finish({ attempted: true, recovered: true });
171
+ else finish({ attempted: true, recovered: false, reason: message?.reason ?? "salvage failed" });
172
+ });
173
+ worker.once("error", (error: Error) => finish({ attempted: true, recovered: false, reason: error.name }));
174
+ worker.once("exit", () => finish({ attempted: true, recovered: false, reason: "salvage worker exited" }));
175
+ });
176
+ }
177
+
178
+ /**
179
+ * The operator-facing note when a salvage was attempted and did not recover.
180
+ * House pattern of `sessionFailureMessage`, extended so the session list says
181
+ * a salvage WAS attempted (and that the original file is untouched — the one
182
+ * fact an operator needs before reaching for a backup).
183
+ */
184
+ export const salvageFailureNote = (outcome: SalvageOutcome): string =>
185
+ `Session failed and is unavailable (UnreadableStorage); a salvage copy was attempted but ${
186
+ outcome.reason ? `failed (${outcome.reason}); ` : "did not pass integrity checks; "
187
+ }the original file is untouched`;