my-durable 0.0.57 → 0.0.59

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 (32) hide show
  1. package/apps/dpi-backend/scripts/check-contract.mjs +9 -2
  2. package/apps/dpi-backend/src/env-vars.ts +10 -1
  3. package/apps/dpi-backend/src/errors.ts +71 -2
  4. package/apps/dpi-backend/src/gc-cli.ts +24 -17
  5. package/apps/dpi-backend/src/gc.ts +3 -1
  6. package/apps/dpi-backend/src/git.ts +26 -6
  7. package/apps/dpi-backend/src/idempotency.ts +47 -1
  8. package/apps/dpi-backend/src/notify-sinks.ts +42 -8
  9. package/apps/dpi-backend/src/pi-config.ts +43 -8
  10. package/apps/dpi-backend/src/routes.ts +6 -2
  11. package/apps/dpi-backend/src/store.ts +285 -18
  12. package/apps/dpi-backend/src/tunnel.ts +24 -2
  13. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-C9ulm0b-.js → index-DC0Iicch.js} +7 -7
  14. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-C8I93zWz.css → index-DxGrKN6X.css} +1 -1
  15. package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
  16. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/store.ts +28 -4
  17. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ModelPicker.vue +13 -4
  18. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/OfflinePanel.vue +6 -6
  19. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/TreeRow.vue +20 -6
  20. package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +67 -29
  21. package/apps/dpi-playground/apps/dpi-playground-hub/src/mux.ts +13 -2
  22. package/apps/dpi-playground/apps/dpi-playground-hub/src/shares.ts +7 -1
  23. package/apps/dpi-sdk/src/node/ops.ts +1 -0
  24. package/apps/dpi-tui/src/app.ts +217 -49
  25. package/apps/dpi-tui/src/commands.ts +57 -22
  26. package/apps/dpi-tui/src/pickers.ts +55 -18
  27. package/apps/dpi-tui/src/scroll.ts +59 -0
  28. package/apps/dpi-tui/src/views.ts +17 -2
  29. package/apps/dpi-tui/src/wrap.ts +42 -0
  30. package/bin/update.mjs +2 -1
  31. package/package.json +1 -1
  32. package/scripts/verify.mjs +7 -0
@@ -44,7 +44,7 @@ import {
44
44
  toTranscript,
45
45
  type UsageSummary,
46
46
  } from "../../dpi-sdk/src/transcript.js";
47
- import { ApiFault, invalid, notFound } from "./errors.js";
47
+ import { ApiFault, invalid, isStorageBusy, isUnreadableStorage, notFound, storageBusyFault } from "./errors.js";
48
48
  import { git, gitDirtyMarks, gitStatus, onGitDirty } from "./git.js";
49
49
  import { DatabaseSync } from "node:sqlite";
50
50
  import { mkdir, readdir, realpath, rename as renamePath, stat } from "node:fs/promises";
@@ -61,7 +61,13 @@ import {
61
61
  type GraphRunRecord,
62
62
  type GraphTask,
63
63
  } from "./graphs.js";
64
- import { ScheduleRegistry, type ScheduleCreateInput, type ScheduleRecord } from "./schedules.js";
64
+ import {
65
+ MAX_SCHEDULE_NAME_LENGTH,
66
+ ScheduleRegistry,
67
+ normaliseCwd,
68
+ type ScheduleCreateInput,
69
+ type ScheduleRecord,
70
+ } from "./schedules.js";
65
71
  import {
66
72
  listArchived,
67
73
  findBundle,
@@ -72,7 +78,7 @@ import {
72
78
  } from "./archived.js";
73
79
  import { NotifySinks, type DeliveryResult, type SinkInput, type SinkRecord } from "./notify-sinks.js";
74
80
  import { zipSync, type ZipEntry } from "./zip.js";
75
- import { mkdirSync, writeFileSync, readFileSync, unlinkSync } from "node:fs";
81
+ import { mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, renameSync, statSync } from "node:fs";
76
82
  import { ensurePrivateDir } from "../../dpi-sdk/src/node/private-dir.js";
77
83
  import { join, dirname, relative, resolve, sep } from "node:path";
78
84
  import { homedir, hostname, platform } from "node:os";
@@ -211,6 +217,11 @@ const NOT_OPENED_README = [
211
217
  "",
212
218
  ].join("\n");
213
219
 
220
+ /** Catalog schema version of the sessions catalog. The ladder in `prepareCatalog` owns upgrades;
221
+ * a HIGHER version than this build knows refuses cleanly (pi-durable's migrations behavior).
222
+ * Version 1: the R5 baseline — provider column mandatory, version row stamped in meta. */
223
+ const CATALOG_SCHEMA_VERSION = 1;
224
+
214
225
  /** "My session #1" → "my-session-1" for the download name. */
215
226
  function slugName(input: string): string {
216
227
  const slug = input
@@ -241,7 +252,7 @@ export function lockFile(path: string) {
241
252
  } catch (e) {
242
253
  if ((e as NodeJS.ErrnoException).code !== "ESRCH") alive = true;
243
254
  }
244
- if (alive && pid !== process.pid) throw Error(`Database already owned by process ${pid}: ${path}`);
255
+ if (alive && pid !== process.pid) throw new DeviceAlreadyRunningError(pid, path);
245
256
  unlinkSync(path);
246
257
  take();
247
258
  }
@@ -252,9 +263,43 @@ export function lockFile(path: string) {
252
263
  };
253
264
  }
254
265
 
266
+ /**
267
+ * A second device on one home (R5 finding 7): the catalog lock is held by a live process.
268
+ * Typed so `Store.open` can turn it into a clean exit instead of an uncaught exception
269
+ * and a crash report that tells the operator to file an issue.
270
+ */
271
+ export class DeviceAlreadyRunningError extends Error {
272
+ constructor(
273
+ readonly pid: number,
274
+ readonly path: string,
275
+ ) {
276
+ super(`Database already owned by process ${pid}: ${path}`);
277
+ this.name = "DeviceAlreadyRunningError";
278
+ }
279
+ }
280
+
255
281
  type Opened = { harness: Harness; unlock: () => void; unsubscribe: () => void; jobs: Jobs; addons: Addons };
256
282
  type Resolved = { row: SessionRow; h: Harness; c: Conversation };
257
283
 
284
+ /**
285
+ * Is `cwd` the project root `root` itself, or inside it? Pure and
286
+ * platform-injected (the gitPathFor convention): on win32 backslashes and
287
+ * forward slashes compare equal and drive/path case is folded, while POSIX
288
+ * stays byte-identical (a backslash is a legal filename character there).
289
+ * Trailing slashes are normalized on both sides, and the prefix match is
290
+ * boundary-checked, so `D:/src/repo-other` is NOT under `D:/src/repo`.
291
+ */
292
+ export function pathsUnder(root: string, cwd: string, platform: NodeJS.Platform = process.platform): boolean {
293
+ const norm = (p: string): string => {
294
+ const slashed = platform === "win32" ? p.replace(/\\/g, "/") : p;
295
+ const trimmed = slashed.length > 1 ? slashed.replace(/\/+$/, "") : slashed;
296
+ return platform === "win32" ? trimmed.toLowerCase() : trimmed;
297
+ };
298
+ const base = norm(root);
299
+ const path = norm(cwd);
300
+ return path === base || path.startsWith(`${base}/`);
301
+ }
302
+
258
303
  /**
259
304
  * Bounded, secret-free description of the error that failed a Session. It names the error class only: never the
260
305
  * cause message, so no SQL values, tokens or transcript can reach a REST error message. The library reports the
@@ -293,6 +338,30 @@ const decodeCursor = (cursor?: string) => {
293
338
  }
294
339
  };
295
340
 
341
+ /**
342
+ * One name rule for Store.create and Store.rename, matching a schedule's name
343
+ * (`MAX_SCHEDULE_NAME_LENGTH`): a display name, not a description — the old
344
+ * create-side slice(0,100) silently swallowed a 10k paste where rename threw.
345
+ *
346
+ * "search" (ANY casing) is reserved: GET /v1/sessions/search is a literal
347
+ * route ahead of /sessions/:s, and resolveSession matches names
348
+ * case-insensitively, so a session named Search/search/SEARCH is unreachable
349
+ * through the name every client naturally types (TUI `client.session(name)`).
350
+ */
351
+ const RESERVED_SESSION_NAME = "search";
352
+ function assertSessionName(name: string): string {
353
+ const trimmed = name.trim();
354
+ if (trimmed.length > MAX_SCHEDULE_NAME_LENGTH)
355
+ throw invalid(`name is ${trimmed.length} characters; the limit is ${MAX_SCHEDULE_NAME_LENGTH}`);
356
+ if (trimmed.toLowerCase() === RESERVED_SESSION_NAME) throw invalid(`"${trimmed}" is a reserved session name`);
357
+ // Control characters never belong in a display name: reject rather than
358
+ // store verbatim (a newline) or silently truncate at a NUL. One rule for
359
+ // create AND rename — the old create path accepted \u0007 etc. and then
360
+ // dead-ended at a rename that refused what it had already stored.
361
+ if (/[\u0000-\u001f\u007f]/.test(trimmed)) throw invalid("name must not contain control characters");
362
+ return trimmed;
363
+ }
364
+
296
365
  export class Store {
297
366
  /** pi's credentials + custom providers on THIS machine (auth.json / models.json). */
298
367
  readonly pi = loadPiConfig();
@@ -387,24 +456,148 @@ export class Store {
387
456
  }
388
457
  ensurePrivateDir(options.dataDir);
389
458
  this.unlockCatalog = lockFile(`${this.catalogPath}.lock`);
390
- this.catalog = new DatabaseSync(this.catalogPath);
391
- this.catalog.exec(`PRAGMA journal_mode=WAL;
459
+ this.catalog = this.openCatalog();
460
+ const uid = this.catalog.prepare("SELECT value FROM meta WHERE key='device_uid'").get() as
461
+ | { value: string }
462
+ | undefined;
463
+ this.uid = uid?.value ?? randomUUID();
464
+ if (!uid) this.catalog.prepare("INSERT INTO meta(key,value) VALUES('device_uid',?)").run(this.uid);
465
+ this.catalog.prepare("DELETE FROM requests WHERE createdAt < ?").run(Date.now() - 24 * 3600_000);
466
+ }
467
+
468
+ // --------------------------------------- catalog: open, migrate, recover
469
+
470
+ /**
471
+ * Open the catalog with migration and corruption recovery (R5 findings 3+4).
472
+ *
473
+ * An unreadable catalog file used to crash-loop the whole device on every boot
474
+ * (all sessions and the tunnel down) — the JSON registries move corrupt files
475
+ * aside (`.corrupt-<ts>`) and rebuild, but the catalog got nothing. Now the same
476
+ * quarantine applies, a fresh catalog boots, and session rows are re-seeded from
477
+ * the sessions/ directory (per-session best-effort; a session whose db fails to
478
+ * open keeps its row with the failure message the boot loop records).
479
+ */
480
+ private openCatalog(): DatabaseSync {
481
+ try {
482
+ return this.prepareCatalog(new DatabaseSync(this.catalogPath));
483
+ } catch (e) {
484
+ // Anything else (a future schema version, a held lock) is NOT a corrupt file —
485
+ // a future version must refuse cleanly, never be quarantined away.
486
+ if (!isUnreadableStorage(e)) throw e;
487
+ this.quarantineCatalog();
488
+ const db = this.prepareCatalog(new DatabaseSync(this.catalogPath));
489
+ // Pass the handle: `this.catalog` is still undefined here (our caller is
490
+ // the `this.catalog = this.openCatalog()` assignment) — reading it from
491
+ // inside reseed was an uncaught TypeError that crashed the boot AFTER
492
+ // the quarantine warning (the R5 test caught exactly that sequence).
493
+ this.reseedCatalog(db);
494
+ return db;
495
+ }
496
+ }
497
+
498
+ /** Run the base DDL, then the schema-version check and the known-old-shape ladder. */
499
+ private prepareCatalog(db: DatabaseSync): DatabaseSync {
500
+ db.exec(`PRAGMA journal_mode=WAL;
392
501
  CREATE TABLE IF NOT EXISTS sessions(id TEXT PRIMARY KEY,name TEXT NOT NULL,cwd TEXT NOT NULL,dbPath TEXT NOT NULL UNIQUE,createdAt INTEGER NOT NULL,model TEXT NOT NULL,provider TEXT NOT NULL);
393
502
  CREATE TABLE IF NOT EXISTS conversation_names(sessionId TEXT NOT NULL,conversationId INTEGER NOT NULL,name TEXT NOT NULL,PRIMARY KEY(sessionId,conversationId));
394
503
  CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);
395
504
  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);
396
505
  CREATE TABLE IF NOT EXISTS session_spawns(key TEXT PRIMARY KEY,sessionId TEXT NOT NULL);
397
506
  CREATE TABLE IF NOT EXISTS session_compaction(sessionId TEXT PRIMARY KEY,settings TEXT NOT NULL);`);
398
- const uid = this.catalog.prepare("SELECT value FROM meta WHERE key='device_uid'").get() as
507
+ const row = db.prepare("SELECT value FROM meta WHERE key='catalog_schema_version'").get() as
399
508
  | { value: string }
400
509
  | undefined;
401
- this.uid = uid?.value ?? randomUUID();
402
- if (!uid) this.catalog.prepare("INSERT INTO meta(key,value) VALUES('device_uid',?)").run(this.uid);
403
- this.catalog.prepare("DELETE FROM requests WHERE createdAt < ?").run(Date.now() - 24 * 3600_000);
510
+ if (row) {
511
+ const version = Number(row.value);
512
+ if (Number.isFinite(version) && version > CATALOG_SCHEMA_VERSION) {
513
+ db.close();
514
+ // pi-durable's migrations refusal, mirrored: clean bounded message, never a silent attempt.
515
+ throw Error(
516
+ `Catalog schema version ${version} is newer than supported version ${CATALOG_SCHEMA_VERSION}; upgrade my-durable to open this device home`,
517
+ );
518
+ }
519
+ return db;
520
+ }
521
+ // Pre-versioning catalog (every device before R5): run the ladder for known-old
522
+ // shapes, then stamp the version. A device already at the current shape just gets stamped.
523
+ const columns = new Set(
524
+ (db.prepare("PRAGMA table_info(sessions)").all() as { name: string }[]).map((c) => c.name),
525
+ );
526
+ if (!columns.has("provider")) {
527
+ db.exec("ALTER TABLE sessions ADD COLUMN provider TEXT NOT NULL DEFAULT ''");
528
+ process.emitWarning("catalog: migrated sessions table to schema version 1 (added provider)");
529
+ }
530
+ db.prepare("INSERT INTO meta(key,value) VALUES('catalog_schema_version',?)").run(String(CATALOG_SCHEMA_VERSION));
531
+ return db;
532
+ }
533
+
534
+ /** Rename an unreadable catalog out of the way instead of deleting it: it is the only copy of that data. */
535
+ private quarantineCatalog(): string {
536
+ const aside = `${this.catalogPath}.corrupt-${Date.now()}`;
537
+ for (const suffix of ["", "-wal", "-shm"] as const) {
538
+ try {
539
+ renameSync(`${this.catalogPath}${suffix}`, `${aside}${suffix}`);
540
+ } catch {}
541
+ }
542
+ process.emitWarning(`catalog.sqlite was unreadable; kept it as ${aside} and rebuilt a fresh catalog`);
543
+ return aside;
544
+ }
545
+
546
+ /**
547
+ * Re-seed session rows from sessions/ after a catalog quarantine. The catalog is the
548
+ * only place names/cwds/models live, so rows come back with best-effort identity:
549
+ * a placeholder name, the first start dir as cwd, the device default model, and the
550
+ * file mtime as createdAt. openAgent corrects model/provider from the session's own
551
+ * committed storage at boot; a session whose db fails to open keeps its row with the
552
+ * boot loop's failure message. Names are placeholders — the transcript is intact.
553
+ */
554
+ private reseedCatalog(db: DatabaseSync): void {
555
+ let entries;
556
+ try {
557
+ entries = readdirSync(this.sessionsDir, { withFileTypes: true });
558
+ } catch {
559
+ return;
560
+ }
561
+ const insert = db.prepare(
562
+ "INSERT OR IGNORE INTO sessions(id,name,cwd,dbPath,createdAt,model,provider) VALUES(?,?,?,?,?,?,?)",
563
+ );
564
+ const fallback = this.defaultModelRef();
565
+ for (const entry of entries) {
566
+ if (!entry.isDirectory() || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(entry.name))
567
+ continue;
568
+ const dbPath = join(this.sessionsDir, entry.name, "agent.sqlite");
569
+ let createdAt = Date.now();
570
+ try {
571
+ createdAt = Math.round(statSync(dbPath).mtimeMs);
572
+ } catch {}
573
+ insert.run(
574
+ entry.name,
575
+ `Recovered session ${entry.name.slice(0, 8)}`,
576
+ this.options.startDirs[0] ?? homedir(),
577
+ dbPath,
578
+ createdAt,
579
+ fallback?.modelId ?? "unknown",
580
+ fallback?.provider ?? "unknown",
581
+ );
582
+ }
404
583
  }
405
584
 
406
585
  static async open(options: StoreOptions) {
407
- const store = new Store({ ...options, dataDir: resolve(options.dataDir) });
586
+ let store: Store;
587
+ try {
588
+ store = new Store({ ...options, dataDir: resolve(options.dataDir) });
589
+ } catch (e) {
590
+ // R5 finding 7: a second device start on one home used to die as an uncaught
591
+ // exception plus a crash report telling the operator to file an issue. It is
592
+ // not a crash: detect the own-lock case and exit cleanly, no report.
593
+ if (e instanceof DeviceAlreadyRunningError) {
594
+ process.stdout.write(`dpi: already running (pid ${e.pid}) — ${e.path} is owned by that process\n`);
595
+ // Exit 0: the operator's intent ("start the device") is already satisfied by
596
+ // the live process, so a supervisor's restart loop must not fight it.
597
+ process.exit(0);
598
+ }
599
+ throw e;
600
+ }
408
601
  // Start dirs are where new sessions begin; create any that do not exist yet.
409
602
  await Promise.all(options.startDirs.map((dir) => mkdir(dir, { recursive: true }).catch(() => {})));
410
603
  try {
@@ -746,6 +939,30 @@ export class Store {
746
939
  return (await this.startDirRoots())[0] ?? resolve(this.startDirs[0] ?? homedir());
747
940
  }
748
941
 
942
+ /** Start-dir containment for a would-be session cwd — the rule behind
943
+ * `create` and every schedule record. `~` expands, a relative path resolves
944
+ * against the FIRST start dir (what `create` has always done), and the
945
+ * resolved path must land inside the start-dir roots: the bare `resolve()`
946
+ * in create used to let an absolute cwd override the base entirely, so
947
+ * {"cwd":"/etc"} could root a session — or a schedule's run — outside the
948
+ * sandbox the operator configured. A path that does not exist (a schedule
949
+ * may point at a mount that is offline right now) is judged lexically, like
950
+ * `containedPath`. Read paths never re-check: existing sessions whose cwd
951
+ * predates the rule are not retroactively broken. */
952
+ async assertSessionCwdAllowed(input: string): Promise<void> {
953
+ const expanded = input === "~" ? homedir() : input.startsWith("~/") ? join(homedir(), input.slice(2)) : input;
954
+ const base = this.startDirs[0] ?? homedir();
955
+ let candidate: string;
956
+ try {
957
+ candidate = await realpath(resolve(base, expanded));
958
+ } catch {
959
+ candidate = resolve(base, expanded);
960
+ }
961
+ const roots = await this.startDirRoots();
962
+ if (!this.underRoots(candidate, roots))
963
+ throw invalid(`cwd must live under a start dir (${roots.join(", ") || "none configured on this device"})`);
964
+ }
965
+
749
966
  async directories(): Promise<DirListing> {
750
967
  const dirs: { name: string; path: string }[] = [];
751
968
  for (const root of this.startDirs) {
@@ -1084,6 +1301,8 @@ export class Store {
1084
1301
  async create(body: CreateSessionBody, spawnKey?: string): Promise<SessionSummary> {
1085
1302
  if (typeof body?.name !== "string") throw invalid("name is required");
1086
1303
  if (typeof body.cwd !== "string" || !body.cwd.trim()) throw invalid("cwd is required");
1304
+ // One name rule for create and rename (assertSessionName, module scope): the old
1305
+ // slice(0,100) silently swallowed a 10k paste where rename threw.
1087
1306
  const path = body.cwd.trim();
1088
1307
  const expanded = path === "~" ? homedir() : path.startsWith("~/") ? join(homedir(), path.slice(2)) : path;
1089
1308
  let cwd: string;
@@ -1093,6 +1312,11 @@ export class Store {
1093
1312
  } catch {
1094
1313
  throw invalid(`cwd must be an existing folder on ${this.name}`);
1095
1314
  }
1315
+ // Same containment rule as the fs/git routes: the resolve() above lets an
1316
+ // absolute cwd override the start-dir base entirely, which is how
1317
+ // {"cwd":"/etc"} used to root a session outside the sandbox. This is the
1318
+ // single choke point — schedule runs and graph runs create here too.
1319
+ await this.assertSessionCwdAllowed(path);
1096
1320
  // Every session roots a project: the registry is the tree's group-by-cwd,
1097
1321
  // promoted to an entity you can name, label and archive (paseo model).
1098
1322
  const status = await gitStatus(cwd).catch(() => undefined);
@@ -1123,7 +1347,7 @@ export class Store {
1123
1347
  const id = randomUUID();
1124
1348
  const row: SessionRow = {
1125
1349
  id,
1126
- name: body.name.trim().slice(0, 100) || "Untitled session",
1350
+ name: assertSessionName(body.name) || "Untitled session",
1127
1351
  cwd,
1128
1352
  dbPath: join(this.sessionsDir, id, "agent.sqlite"),
1129
1353
  createdAt: Date.now(),
@@ -1133,8 +1357,10 @@ export class Store {
1133
1357
  await this.openAgent(row, true, body.thinkingLevel ?? "medium");
1134
1358
  this.catalog.exec("BEGIN");
1135
1359
  try {
1360
+ // Named columns (R5 finding 4): a catalog with an extra or missing future
1361
+ // column fails loudly here instead of mis-binding positionally.
1136
1362
  this.catalog
1137
- .prepare("INSERT INTO sessions VALUES(?,?,?,?,?,?,?)")
1363
+ .prepare("INSERT INTO sessions(id,name,cwd,dbPath,createdAt,model,provider) VALUES(?,?,?,?,?,?,?)")
1138
1364
  .run(id, row.name, cwd, row.dbPath, row.createdAt, row.model, row.provider);
1139
1365
  if (spawnKey) this.catalog.prepare("INSERT OR REPLACE INTO session_spawns VALUES(?,?)").run(spawnKey, id);
1140
1366
  this.catalog.exec("COMMIT");
@@ -1169,7 +1395,9 @@ export class Store {
1169
1395
 
1170
1396
  rename(row: SessionRow, name: unknown) {
1171
1397
  if (typeof name !== "string" || !name.trim()) throw invalid("A name is required");
1172
- this.catalog.prepare("UPDATE sessions SET name=? WHERE id=?").run(name.trim().slice(0, 100), row.id);
1398
+ // assertSessionName owns the whole rule: cap, reserved word, control characters.
1399
+ const trimmed = assertSessionName(name);
1400
+ this.catalog.prepare("UPDATE sessions SET name=? WHERE id=?").run(trimmed, row.id);
1173
1401
  this.notify();
1174
1402
  return this.sessionSummary(this.row(row.id));
1175
1403
  }
@@ -1253,8 +1481,9 @@ export class Store {
1253
1481
  };
1254
1482
  this.catalog.exec("BEGIN");
1255
1483
  try {
1484
+ // Named columns, as in create (R5 finding 4).
1256
1485
  this.catalog
1257
- .prepare("INSERT INTO sessions VALUES(?,?,?,?,?,?,?)")
1486
+ .prepare("INSERT INTO sessions(id,name,cwd,dbPath,createdAt,model,provider) VALUES(?,?,?,?,?,?,?)")
1258
1487
  .run(row.id, row.name, row.cwd, row.dbPath, row.createdAt, row.model, row.provider);
1259
1488
  this.catalog.exec("COMMIT");
1260
1489
  } catch (e) {
@@ -1634,10 +1863,41 @@ export class Store {
1634
1863
  };
1635
1864
  }
1636
1865
 
1866
+ /** Reopens in flight (resolveAgent's one retry): concurrent requests share the attempt instead of stampeding the same db. */
1867
+ private reopenInFlight = new Map<string, Promise<Harness>>();
1868
+
1869
+ /** ONE bounded reopen attempt per session at a time; removes itself when settled. */
1870
+ private reopenOnce(row: SessionRow): Promise<Harness> {
1871
+ const inFlight = this.reopenInFlight.get(row.id);
1872
+ if (inFlight) return inFlight;
1873
+ const attempt = this.openAgent(row).finally(() => this.reopenInFlight.delete(row.id));
1874
+ this.reopenInFlight.set(row.id, attempt);
1875
+ return attempt;
1876
+ }
1877
+
1637
1878
  /** Agent by numeric id, `main`, or unique name (custom or derived, case-insensitive). */
1638
1879
  async resolveAgent(sessionRef: string, agentRef: string): Promise<Resolved> {
1639
1880
  const row = this.resolveSession(sessionRef);
1640
- const h = this.harness(row);
1881
+ let h: Harness;
1882
+ try {
1883
+ h = this.harness(row);
1884
+ } catch (e) {
1885
+ // R5 finding 1 (the availability brick): once a Session failed (failSession),
1886
+ // EVERY agent route used to answer 503 "Session failed and is unavailable"
1887
+ // for the process lifetime — the reopen path existed only in
1888
+ // sessionTouchedFiles/sessionGitTurns, so a transient storage failure
1889
+ // (another process holding the sqlite lock, a full disk) soft-bricked the
1890
+ // session until the device restarted. The unavailable fault is exactly the
1891
+ // "harness is not open" signal: attempt ONE fresh openAgent here, on the
1892
+ // request path every client hits, before answering.
1893
+ if (!(e instanceof ApiFault) || e.code !== "unavailable") throw e;
1894
+ try {
1895
+ h = await this.reopenOnce(row);
1896
+ } catch (retryError) {
1897
+ if (isStorageBusy(retryError)) throw storageBusyFault();
1898
+ throw e; // the recorded, bounded reason — never the raw storage error
1899
+ }
1900
+ }
1641
1901
  let id: number | undefined;
1642
1902
  if (/^\d+$/.test(agentRef)) id = Number(agentRef);
1643
1903
  else if (agentRef.toLowerCase() === "main") id = 1;
@@ -2179,12 +2439,18 @@ export class Store {
2179
2439
  }
2180
2440
 
2181
2441
  async createSchedule(input: ScheduleCreateInput): Promise<ScheduleView> {
2442
+ // The registry stores cwd as typed (it never stats), so an out-of-sandbox
2443
+ // cwd used to surface only when the run spawned its session. Reject the
2444
+ // POST up front with the same rule Store.create applies.
2445
+ if (typeof input?.cwd === "string" && input.cwd.trim()) await this.assertSessionCwdAllowed(normaliseCwd(input.cwd));
2182
2446
  const record = await this.schedules.create(input);
2183
2447
  this.notify();
2184
2448
  return this.scheduleView(record);
2185
2449
  }
2186
2450
 
2187
2451
  async updateSchedule(id: string, patch: SchedulePatchBody): Promise<ScheduleView> {
2452
+ // Same early refusal when a patch repoints the schedule at /etc.
2453
+ if (typeof patch?.cwd === "string" && patch.cwd.trim()) await this.assertSessionCwdAllowed(normaliseCwd(patch.cwd));
2188
2454
  const record = await this.schedules.update(id, patch);
2189
2455
  this.notify();
2190
2456
  return this.scheduleView(record);
@@ -2298,8 +2564,9 @@ export class Store {
2298
2564
  private projectForPath(cwd: string): ProjectRecord | undefined {
2299
2565
  let best: ProjectRecord | undefined;
2300
2566
  for (const project of this.projects.list({ includeArchived: false })) {
2301
- const root = project.rootPath.endsWith("/") ? project.rootPath : `${project.rootPath}/`;
2302
- const isUnder = cwd === project.rootPath || cwd.startsWith(root);
2567
+ // Slash/case-normalized compare (pathsUnder): a session cwd recorded as
2568
+ // `D:\src\repo` must match a project registered as `D:/src/repo`.
2569
+ const isUnder = pathsUnder(project.rootPath, cwd);
2303
2570
  if (isUnder && (!best || project.rootPath.length > best.rootPath.length)) best = project;
2304
2571
  }
2305
2572
  return best;
@@ -654,10 +654,13 @@ export class DeviceConnector {
654
654
  void (async () => {
655
655
  const check = validateRestRequest({ method: frame.method, path: frame.path });
656
656
  if (!check.ok) {
657
+ // Same validator the hub runs first (tunnel-transport request()): the
658
+ // verdict must read the same on both hops — 400 invalid with the
659
+ // validator's message (R5: the device used to answer 404 here).
657
660
  send({
658
661
  type: "rest-response",
659
662
  reqId: frame.reqId,
660
- status: 404,
663
+ status: 400,
661
664
  body: { error: { code: "invalid", message: check.error } },
662
665
  });
663
666
  return;
@@ -758,7 +761,26 @@ export class DeviceConnector {
758
761
  // F07: the hub names the STREAM PATH; scope must reach the device API.
759
762
  // Allow-list the three SSE endpoints — a hub can never aim the reader
760
763
  // at REST-only or pairing routes.
761
- if (!isSubscribePathOk(frame.sub)) return;
764
+ if (!isSubscribePathOk(frame.sub)) {
765
+ // R5: a refusal is never silent — the hub (and through it the browser
766
+ // key named in the envelope) gets a fault with its subscriptionId, so
767
+ // the key surfaces an error instead of starving without frames and
768
+ // without a timeout. The path rides the envelope's `sub` field, so the
769
+ // message stays short (the fault schema caps it at 512 chars).
770
+ send({
771
+ type: "tunnel-data",
772
+ frame: {
773
+ type: "fault",
774
+ error: {
775
+ code: "invalid",
776
+ message: "subscribe refused: the device does not serve this stream path",
777
+ },
778
+ },
779
+ subscriptionId: frame.subscriptionId,
780
+ sub: frame.sub,
781
+ });
782
+ return;
783
+ }
762
784
  const ctl = new AbortController();
763
785
  this.readers.set(frame.subscriptionId, ctl);
764
786
  void (async () => {