my-durable 0.0.59 → 0.0.61

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.
Files changed (27) hide show
  1. package/apps/dpi-backend/src/daemon.ts +55 -1
  2. package/apps/dpi-backend/src/doctor.ts +17 -4
  3. package/apps/dpi-backend/src/gc-cli.ts +28 -2
  4. package/apps/dpi-backend/src/main.ts +29 -3
  5. package/apps/dpi-backend/src/salvage.ts +187 -0
  6. package/apps/dpi-backend/src/store.ts +64 -8
  7. package/apps/dpi-backend/src/vitals.ts +72 -0
  8. package/apps/dpi-backend/src/zip.ts +17 -0
  9. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-4Kyozhl0.js +81 -0
  10. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-DxGrKN6X.css → index-BkSQ2clA.css} +1 -1
  11. package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
  12. package/apps/dpi-playground/apps/dpi-playground-fe/src/App.vue +9 -2
  13. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/dialog-escape.ts +13 -0
  14. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/export-bundle.ts +70 -0
  15. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/state-draft.ts +72 -0
  16. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/store.ts +15 -0
  17. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ContextBar.vue +14 -3
  18. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +82 -69
  19. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ModelPicker.vue +22 -4
  20. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/PromptDialog.vue +3 -0
  21. package/apps/dpi-playground/apps/dpi-playground-fe/src/style.css +19 -0
  22. package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +5 -1
  23. package/apps/dpi-playground/apps/dpi-playground-hub/src/pairing.ts +38 -17
  24. package/apps/dpi-tui/src/main.ts +46 -19
  25. package/bin/dpi.mjs +83 -0
  26. package/package.json +1 -1
  27. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DC0Iicch.js +0 -81
@@ -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
 
@@ -172,6 +178,43 @@ const execDefault = (cmd: string, args: string[]) =>
172
178
 
173
179
  const delay = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
174
180
 
181
+ /** R6 cli finding 10: `dpi device stop` twice hung 40s+ with zero output while
182
+ * the daemon stayed healthy. No shutdown step may block forever: race the
183
+ * step against a ceiling; on expiry say so and CONTINUE (the shutdown caller
184
+ * still force-exits). A step that throws rejects normally — only the hang is
185
+ * bounded. Exported so the sequencing is unit-testable. */
186
+ export async function boundedStep<T>(
187
+ label: string,
188
+ ms: number,
189
+ run: () => T | Promise<T>,
190
+ log: (line: string) => void = () => {},
191
+ ): Promise<T | undefined> {
192
+ let done = false;
193
+ let failed: { error: unknown } | undefined;
194
+ const step = Promise.resolve(run()).then(
195
+ (v) => {
196
+ done = true;
197
+ return v;
198
+ },
199
+ (error: unknown) => {
200
+ done = true;
201
+ failed = { error };
202
+ },
203
+ );
204
+ let timer: NodeJS.Timeout | undefined;
205
+ const ceiling = new Promise<void>((resolve) => {
206
+ timer = setTimeout(() => resolve(), ms);
207
+ });
208
+ await Promise.race([step, ceiling]);
209
+ if (timer) clearTimeout(timer);
210
+ if (!done) {
211
+ log(`shutdown: ${label} did not finish within ${ms}ms — continuing without it`);
212
+ return undefined;
213
+ }
214
+ if (failed) throw failed.error;
215
+ return (await step) as T;
216
+ }
217
+
175
218
  function ioOf(opts: RunOpts): Io {
176
219
  return {
177
220
  env: opts.env ?? process.env,
@@ -385,6 +428,17 @@ async function cmdInstall(io: Io): Promise<number> {
385
428
  if (!env.DPI_HOME) env.DPI_HOME = daemonPaths(io.env).home;
386
429
  if (p === "linux") {
387
430
  const unit = join(homedir(), ".config/systemd/user/dpi-device.service");
431
+ // R6 cli finding 8: probe systemd BEFORE writing anything. A host without a
432
+ // user systemd (containers, non-systemd distros) used to get a stray unit
433
+ // file plus an empty "systemctl enable failed:" — daemon-reload is the same
434
+ // first step a real install takes, so it is the honest probe.
435
+ const probe = await io.exec("systemctl", ["--user", "daemon-reload"]);
436
+ if (!probe.ok) {
437
+ const reason = probe.output.trim().split("\n")[0] || "systemctl is not usable on this host";
438
+ io.print(`no systemd --user on this host — nothing was installed (${reason})`);
439
+ io.print("start the daemon after login instead: dpi device start");
440
+ return 1;
441
+ }
388
442
  await io.writeFile(unit, systemdUnit({ node, dpi, env }));
389
443
  await io.exec("systemctl", ["--user", "daemon-reload"]);
390
444
  const enable = await io.exec("systemctl", ["--user", "enable", "--now", "dpi-device.service"]);
@@ -131,6 +131,11 @@ export function splitModel(
131
131
  ): { provider: string; modelId: string } | undefined {
132
132
  const exact = models?.find((m) => `${m.provider}/${m.id}` === defaultModel);
133
133
  if (exact) return { provider: exact.provider, modelId: exact.id };
134
+ // R6 cli finding 7: local catalogs (faux provider) report a BARE id as the
135
+ // defaultModel — match it against models[].id before the split heuristic so
136
+ // healthy faux devices stop warning "no usable defaultModel".
137
+ const bare = models?.find((m) => m.id === defaultModel && m.provider);
138
+ if (bare) return { provider: bare.provider, modelId: bare.id };
134
139
  const i = defaultModel.indexOf("/");
135
140
  if (i <= 0 || i === defaultModel.length - 1) return undefined;
136
141
  return { provider: defaultModel.slice(0, i), modelId: defaultModel.slice(i + 1) };
@@ -321,13 +326,21 @@ async function hubCheck(io: DoctorIo, cfg: DeviceEndpoint): Promise<DoctorCheck>
321
326
  const source = origin ? "DPI_HUB_URL" : "pairing.json";
322
327
  if (!origin) {
323
328
  const file = join(cfg.home, "pairing.json");
324
- try {
325
- if (io.exists(file)) {
329
+ if (io.exists(file)) {
330
+ try {
326
331
  const paired = JSON.parse(io.readFile(file)) as { hubOrigin?: unknown };
327
332
  if (typeof paired.hubOrigin === "string") origin = paired.hubOrigin.trim().replace(/\/+$/, "");
333
+ } catch (error) {
334
+ // R6 cli finding 6: a corrupt/unreadable pairing file is NOT "no hub
335
+ // configured" — the operator must learn the file is broken, because
336
+ // the hub check cannot run at all until it is fixed.
337
+ return {
338
+ id,
339
+ label: "hub",
340
+ status: "warn",
341
+ detail: `pairing.json is corrupt/unreadable — fix or delete ${file} (${describeError(error, 0)})`,
342
+ };
328
343
  }
329
- } catch {
330
- /* unreadable/garbled pairing file: report as not configured */
331
344
  }
332
345
  }
333
346
  if (!origin) return { id, label: "hub", status: "skip", detail: "no hub configured (no DPI_HUB_URL, no saved pairing)" };
@@ -52,7 +52,25 @@ export function resolveDataDir(argv: readonly string[], io: GcIo): string {
52
52
  return i >= 0 ? argv[i + 1] : undefined;
53
53
  };
54
54
  const envFile = io.env.DPI_ENV_FILE;
55
- const fileEnv = envFile ? readEnvFile(io.readFile(envFile)) : {};
55
+ let fileEnv: Record<string, string> = {};
56
+ if (envFile) {
57
+ // R6 cli finding 2: a missing/unreadable env file used to escape as a raw
58
+ // ENOENT/EACCES stack from deep inside resolution — say it in one line.
59
+ try {
60
+ fileEnv = readEnvFile(io.readFile(envFile));
61
+ } catch (e) {
62
+ const code = (e as NodeJS.ErrnoException)?.code;
63
+ const why =
64
+ code === "ENOENT"
65
+ ? "the file does not exist"
66
+ : code === "EACCES"
67
+ ? "the file is not readable"
68
+ : e instanceof Error
69
+ ? e.message
70
+ : String(e);
71
+ throw new Error(`cannot read DPI_ENV_FILE '${envFile}' — ${why}`);
72
+ }
73
+ }
56
74
  const value = (key: string) =>
57
75
  io.env[key] ?? (typeof fileEnv[key] === "string" ? fileEnv[key] : undefined);
58
76
  const dataDirArg = flag("--data-dir") ?? value("DPI_DATA_DIR");
@@ -87,7 +105,15 @@ export async function gcCli(args: GcArgs, io: GcIo = defaultGcIo()): Promise<num
87
105
  return 2;
88
106
  }
89
107
  const apply = argv.includes("--yes");
90
- const archiveDir = join(resolveDataDir(argv, io), "archive");
108
+ // R6 cli finding 2: resolveDataDir touches the env file — keep its failures
109
+ // in the one-line pretty-error regime (exit 1), like the plan/apply calls.
110
+ let archiveDir: string;
111
+ try {
112
+ archiveDir = join(resolveDataDir(argv, io), "archive");
113
+ } catch (e) {
114
+ io.printErr(`dpi gc: ${e instanceof Error ? e.message : String(e)}`);
115
+ return 1;
116
+ }
91
117
  const options = { closedBeforeDays: days, now: io.now() };
92
118
 
93
119
  // The plan/apply calls live inside the pretty-error path (R5 finding 6): a bad
@@ -14,7 +14,8 @@ import { v1 } from "./routes.js";
14
14
  import { DevicePairing } from "./pairing.js";
15
15
  import { DeviceConnector, readCaPem } from "./tunnel.js";
16
16
  import { PAIR_PAGE_HTML } from "./pair-page.js";
17
- import { parseDeviceSub, runDeviceCommand, daemonPaths } from "./daemon.js";
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 } from "./daemon.js";
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,
@@ -249,15 +255,35 @@ let closing = false;
249
255
  const shutdown = async () => {
250
256
  if (closing) return;
251
257
  closing = true;
252
- connector.stop("backend shutdown"); // readers/pending ops before storage closes
258
+ // R6 cli finding 10: `dpi device stop` hung twice at teardown (40s+, zero
259
+ // output, device stayed healthy; direct SIGTERM exits <5s). No step of the
260
+ // shutdown may block forever:
261
+ // - connector.stop is synchronous; a throw is logged, never fatal;
262
+ // - store.close is raced against a 5s ceiling (boundedStep) and abandoned;
263
+ // - a hard watchdog guarantees the process still exits at 10s.
264
+ const log = (line: string) => console.log(line);
265
+ const watchdog = setTimeout(() => {
266
+ console.log("shutdown: still not down after 10s — forcing exit");
267
+ process.exit(0);
268
+ }, 10_000);
269
+ try {
270
+ await boundedStep("connector.stop", 5_000, () => connector.stop("backend shutdown"), log);
271
+ } catch (e) {
272
+ log(`shutdown: connector stop failed (${e instanceof Error ? e.message : String(e)}) — continuing`);
273
+ }
253
274
  server.close();
254
275
  server.closeAllConnections();
255
- await store.close();
276
+ try {
277
+ await boundedStep("store.close", 5_000, () => store.close(), log);
278
+ } catch (e) {
279
+ log(`shutdown: store close failed (${e instanceof Error ? e.message : String(e)}) — exiting anyway`);
280
+ }
256
281
  try {
257
282
  rmSync(daemonPaths(process.env).pid, { force: true });
258
283
  } catch {
259
284
  /* nothing to clean */
260
285
  }
286
+ clearTimeout(watchdog);
261
287
  process.exit(0);
262
288
  };
263
289
  process.on("SIGTERM", () => void shutdown());
@@ -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`;
@@ -77,7 +77,8 @@ import {
77
77
  type ArchivedView,
78
78
  } from "./archived.js";
79
79
  import { NotifySinks, type DeliveryResult, type SinkInput, type SinkRecord } from "./notify-sinks.js";
80
- import { zipSync, type ZipEntry } from "./zip.js";
80
+ import { zipSync, EXPORT_RAW_LIMIT_BYTES, type ZipEntry } from "./zip.js";
81
+ import { salvageFailureNote, salvageSessionDb } from "./salvage.js";
81
82
  import { mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, renameSync, statSync } from "node:fs";
82
83
  import { ensurePrivateDir } from "../../dpi-sdk/src/node/private-dir.js";
83
84
  import { join, dirname, relative, resolve, sep } from "node:path";
@@ -1516,8 +1517,43 @@ export class Store {
1516
1517
  // Custom extensions are installed but not selected: an agent turns them on in its own selection.
1517
1518
  const addons = createAddons({ offline: this.options.provider === "faux" });
1518
1519
  for (const extension of addons.list) registry.install(extension);
1520
+ // R7: an unreadable db (a corrupt header, per the R5 audit recipe — garbage
1521
+ // bytes 32-64) used to hide intact data forever: the close-path checkpoint
1522
+ // folds the WAL into the corrupt main file without fixing page 1, and the
1523
+ // only recovery was a manual header patch. Before failing the open, ONE
1524
+ // bounded salvage on a COPY (header patch + integrity_check + atomic
1525
+ // promote; see salvage.ts). The original file is never modified — a failed
1526
+ // salvage leaves it byte-identical and the failure surface says so. Any other
1527
+ // open error (a held lock, a schema mismatch) keeps its existing behavior.
1528
+ let storage: Awaited<ReturnType<typeof openNodeSqliteStorage>>;
1529
+ try {
1530
+ storage = await openNodeSqliteStorage(row.dbPath);
1531
+ } catch (error) {
1532
+ if (create || !isUnreadableStorage(error)) throw error;
1533
+ const outcome = await salvageSessionDb(row.dbPath);
1534
+ if (!outcome.recovered) {
1535
+ const note = salvageFailureNote(outcome);
1536
+ const previous = this.errors.get(row.id);
1537
+ this.errors.set(row.id, note); // rides the session summary and every later fault
1538
+ this.notify();
1539
+ // Same operator visibility failSession gives a mid-run failure — once per
1540
+ // distinct note, so repeated failed opens do not spam the sinks.
1541
+ if (previous !== note)
1542
+ void this.notifyEvent({
1543
+ kind: "session.failed",
1544
+ title: `Session failed on ${this.name}`,
1545
+ body: `${this.sessionName(row.id)}: ${note}`,
1546
+ data: { sessionId: row.id, device: this.name },
1547
+ });
1548
+ throw new ApiFault("unavailable", note);
1549
+ }
1550
+ process.emitWarning(
1551
+ `[dpi-backend] session ${row.id}'s database was unreadable; salvaged a copy (original kept as ${outcome.keptAs})`,
1552
+ );
1553
+ storage = await openNodeSqliteStorage(row.dbPath); // the ONE retry, on the promoted copy
1554
+ }
1519
1555
  const harness = await Harness.open(
1520
- await openNodeSqliteStorage(row.dbPath),
1556
+ storage,
1521
1557
  {
1522
1558
  models: this.models,
1523
1559
  registry,
@@ -1895,6 +1931,10 @@ export class Store {
1895
1931
  h = await this.reopenOnce(row);
1896
1932
  } catch (retryError) {
1897
1933
  if (isStorageBusy(retryError)) throw storageBusyFault();
1934
+ // R7: a reopen that failed with its own typed fault (a salvage that was
1935
+ // attempted and did not recover) is MORE specific than the recorded
1936
+ // "Session X is unavailable" this path used to re-throw — surface it.
1937
+ if (retryError instanceof ApiFault) throw retryError;
1898
1938
  throw e; // the recorded, bounded reason — never the raw storage error
1899
1939
  }
1900
1940
  }
@@ -2404,19 +2444,35 @@ export class Store {
2404
2444
  session: { id: row.id, name: row.name, cwd: row.cwd, model: row.model, createdAt: row.createdAt },
2405
2445
  agents: agents.map((a) => ({ id: a.id, name: a.name, kind: a.kind })),
2406
2446
  };
2407
- files.push({ path: "manifest.json", text: `${JSON.stringify(manifest, null, 2)}\n` });
2408
- files.push({ path: "session.json", text: `${JSON.stringify(this.sessionSummaryBase(row), null, 2)}\n` });
2409
2447
  const opened = this.opened.get(row.id);
2448
+ // R7 memory guard: every entry text is held in RAM at zip time, and the zip
2449
+ // writer adds deflate + base64 copies (≈2-3× raw). Refuse over the raw limit
2450
+ // BEFORE the second copy exists — checked as files accumulate so a huge
2451
+ // transcript also skips the per-agent extras that would follow it.
2452
+ let rawBytes = 0;
2453
+ const push = (entry: ZipEntry) => {
2454
+ rawBytes += Buffer.byteLength(entry.text, "utf8");
2455
+ if (rawBytes > EXPORT_RAW_LIMIT_BYTES) {
2456
+ const mb = (n: number) => `${(n / (1024 * 1024)).toFixed(1)} MiB`;
2457
+ throw invalid(
2458
+ `Export refused: transcripts are ${mb(rawBytes)} of text, over the ${mb(EXPORT_RAW_LIMIT_BYTES)} in-memory limit. ` +
2459
+ `Compact the session first, then export again`,
2460
+ );
2461
+ }
2462
+ files.push(entry);
2463
+ };
2464
+ push({ path: "manifest.json", text: `${JSON.stringify(manifest, null, 2)}\n` });
2465
+ push({ path: "session.json", text: `${JSON.stringify(this.sessionSummaryBase(row), null, 2)}\n` });
2410
2466
  for (const agent of agents) {
2411
2467
  const c = opened ? await opened.harness.conversation(agent.id as ConversationId, ctx) : undefined;
2412
2468
  if (!c) continue;
2413
2469
  const dir = `agents/${agent.id}`;
2414
- files.push({ path: `${dir}/transcript.json`, text: `${JSON.stringify(await this.transcript(c, "json"), null, 2)}\n` });
2470
+ push({ path: `${dir}/transcript.json`, text: `${JSON.stringify(await this.transcript(c, "json"), null, 2)}\n` });
2415
2471
  const md = await this.transcript(c, "markdown");
2416
- if (typeof md.text === "string") files.push({ path: `${dir}/transcript.md`, text: md.text });
2417
- files.push({ path: `${dir}/config.json`, text: `${JSON.stringify((await this.agentDetail(row, c)).config, null, 2)}\n` });
2472
+ if (typeof md.text === "string") push({ path: `${dir}/transcript.md`, text: md.text });
2473
+ push({ path: `${dir}/config.json`, text: `${JSON.stringify((await this.agentDetail(row, c)).config, null, 2)}\n` });
2418
2474
  }
2419
- if (!agents.length) files.push({ path: "README.txt", text: NOT_OPENED_README });
2475
+ if (!agents.length) push({ path: "README.txt", text: NOT_OPENED_README });
2420
2476
  const zip = zipSync(files);
2421
2477
  return {
2422
2478
  filename: `${slugName(row.name || row.id)}.bundle.zip`,
@@ -9,6 +9,75 @@
9
9
  */
10
10
  import { statfsSync } from "node:fs";
11
11
  import { cpus, loadavg, uptime as osUptime, freemem, totalmem } from "node:os";
12
+ import { monitorEventLoopDelay } from "node:perf_hooks";
13
+
14
+ // --- Event-loop lag (R7 perf lane) -----------------------------------------
15
+ //
16
+ // The R6 soak caught the device event loop stalling up to 1.44 s while the
17
+ // paired hub stayed ≤9 ms on the same machine — load-average says "healthy",
18
+ // RTT spikes say "blocked". host loadavg cannot see that (it is host-wide),
19
+ // so vitals carries its own lag numbers. `monitorEventLoopDelay` is a native
20
+ // histogram (one C++ sampler, no JS churn), measurably lighter than a JS
21
+ // setInterval-drift probe and immune to the very stalls it measures.
22
+
23
+ /** One window of lag samples (a 1 s "window" is the worst delay in that second). */
24
+ const LAG_WINDOW = 60;
25
+ const LAG_SAMPLE_MS = 1_000;
26
+ /** Histogram resolution in ms; 20 (the Node default) is plenty — we hunt ≥500 ms stalls. */
27
+ const LAG_RESOLUTION_MS = 20;
28
+
29
+ let lagHistogram: ReturnType<typeof monitorEventLoopDelay> | null = null;
30
+ let lagRing: number[] = [];
31
+
32
+ export interface EventLoopLagVitals {
33
+ /** Worst event-loop delay in the most recent 1 s window, ms (0 before the first window completes). */
34
+ lagMsLast: number;
35
+ /** Worst delay across the last 60 windows (a rolling minute), ms. */
36
+ lagMsMax1m: number;
37
+ /** Windows sampled so far — grows to 60 as the process ages; <60 right after boot. */
38
+ samples: number;
39
+ }
40
+
41
+ /**
42
+ * Start (once; idempotent) the event-loop lag monitor. Called at daemon boot
43
+ * (`main.ts`) so the minute-window has history from the start, and lazily from
44
+ * `deviceVitals()` so any context that only reads vitals still gets numbers.
45
+ */
46
+ export function startEventLoopMonitor(): void {
47
+ if (lagHistogram) return;
48
+ lagHistogram = monitorEventLoopDelay({ resolution: LAG_RESOLUTION_MS });
49
+ lagHistogram.enable();
50
+ const tick = setInterval(() => {
51
+ const h = lagHistogram;
52
+ if (!h) return;
53
+ // Node's histogram records NANOseconds even though `resolution` is in ms
54
+ // (verified by tests/vitals-lag.test.ts's ms-not-ns bound — 160 ms block
55
+ // read as 168_689_663 before the /1e6).
56
+ lagRing.push(h.max / 1e6); // worst delay since the previous tick, in ms
57
+ h.reset();
58
+ if (lagRing.length > LAG_WINDOW) lagRing.shift();
59
+ }, LAG_SAMPLE_MS);
60
+ tick.unref?.(); // never hold the process open just to keep counting
61
+ }
62
+
63
+ /** The rolling lag window. Starts the monitor on first use. */
64
+ export function eventLoopLag(): EventLoopLagVitals {
65
+ startEventLoopMonitor();
66
+ let max = 0;
67
+ let last = 0;
68
+ for (const v of lagRing) {
69
+ if (v > max) max = v;
70
+ last = v;
71
+ }
72
+ return { lagMsLast: Math.round(last), lagMsMax1m: Math.round(max), samples: lagRing.length };
73
+ }
74
+
75
+ /** Stop and forget the monitor (tests; daemon teardown). */
76
+ export function stopEventLoopMonitor(): void {
77
+ lagHistogram?.disable();
78
+ lagHistogram = null;
79
+ lagRing = [];
80
+ }
12
81
 
13
82
  export interface DiskVitals {
14
83
  path: string;
@@ -28,6 +97,8 @@ export interface DeviceVitals {
28
97
  cpuCount: number;
29
98
  memory: { totalBytes: number; freeBytes: number; usedBytes: number; processRssBytes: number; heapUsedBytes: number };
30
99
  disk: DiskVitals;
100
+ /** Event-loop lag — the number `loadavg` cannot express: how long ready JS waited to run. */
101
+ eventLoop: EventLoopLagVitals;
31
102
  pid: number;
32
103
  at: number;
33
104
  }
@@ -65,6 +136,7 @@ export function deviceVitals(diskPath: string, startedAt: number, now = Date.now
65
136
  heapUsedBytes: memory.heapUsed,
66
137
  },
67
138
  disk: diskVitals(diskPath),
139
+ eventLoop: eventLoopLag(),
68
140
  pid: process.pid,
69
141
  at: now,
70
142
  };
@@ -18,6 +18,23 @@ export interface ZipEntry {
18
18
  text: string;
19
19
  }
20
20
 
21
+ /**
22
+ * R7 export memory guard. A bundle is built entirely in RAM — raw entry texts,
23
+ * then deflate, then base64 — which the R5 audit measured at ≈2-3× the transcript
24
+ * size held at once (a 13 MB probe already pushed RSS to ~150 MB). Until export
25
+ * streams (R8+), refuse above this ceiling instead of hitting the scale cliff:
26
+ * 32 MiB of raw serialized entries is a transcript nobody has compacted, and the
27
+ * refusal names the size and tells the operator to compact first.
28
+ */
29
+ export const EXPORT_RAW_LIMIT_BYTES = 32 * 1024 * 1024;
30
+
31
+ /** Total UTF-8 bytes an archive would hold — the "raw" side of the guard (pre-deflate). */
32
+ export function zipRawBytes(entries: readonly ZipEntry[]): number {
33
+ let bytes = 0;
34
+ for (const entry of entries) bytes += Buffer.byteLength(entry.text, "utf8");
35
+ return bytes;
36
+ }
37
+
21
38
  const LOCAL_SIG = 0x04034b50;
22
39
  const CENTRAL_SIG = 0x02014b50;
23
40
  const EOCD_SIG = 0x06054b50;