my-durable 0.0.63 → 0.0.65

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.
@@ -39,8 +39,14 @@ const DB_NAME = "agent.sqlite";
39
39
  const FILE_MODE = 0o600;
40
40
  const DIR_MODE = 0o700;
41
41
 
42
- /** `<uuid>-<archivedAtMs>`: the only identity an old bundle has. 36 uuid chars + 13 ms digits. */
43
- export const BUNDLE_DIR_PATTERN = /^([0-9a-f-]{36})-(\d{13})$/;
42
+ /** `<uuid>-<archivedAtMs>`: the only identity an old bundle has. R11 4.1:
43
+ * CANONICAL uuid shape (8-4-4-4-12 lowercase hex) — the old `[0-9a-f-]{36}`
44
+ * character class also matched 36 dashes, hex-without-dashes and other
45
+ * lookalikes an operator might drop in archive/ from another tool; those are
46
+ * now skipped+reported by BOTH gc and the browser (this ONE pattern is the
47
+ * shared source — real bundles are canonical-uuid session ids by
48
+ * construction, so nothing legitimate is lost). */
49
+ export const BUNDLE_DIR_PATTERN = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})-(\d{13})$/;
44
50
  /** Full lowercase uuid, 8-4-4-4-12: a PREFIX of another uuid must never match a bundle. */
45
51
  const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
46
52
 
@@ -8,8 +8,11 @@
8
8
  import { readFileSync } from "node:fs";
9
9
  import { join } from "node:path";
10
10
  import { homedir } from "node:os";
11
- import { gcApply, gcPlan, humanBytes, parseDuration } from "./gc.js";
11
+ import { gcApply, gcPlan, humanBytes, parseDuration, removedSessionIds } from "./gc.js";
12
12
  import { expand, readEnvFile } from "./doctor.js";
13
+ import { lockFile, DeviceAlreadyRunningError } from "./store.js";
14
+ import { ScheduleRegistry } from "./schedules.js";
15
+ import { GraphRegistry } from "./graphs.js";
13
16
 
14
17
  export interface GcArgs {
15
18
  argv: readonly string[];
@@ -133,14 +136,97 @@ export async function gcCli(args: GcArgs, io: GcIo = defaultGcIo()): Promise<num
133
136
  io.print("re-run with --yes to delete.");
134
137
  }
135
138
  for (const skip of plan.skipped) io.printErr(`skipped ${skip.name}: ${skip.reason}`);
139
+ if (plan.danglingRefs.schedules > 0 || plan.danglingRefs.graphRuns > 0) {
140
+ io.print(
141
+ `sweep would clear ${plan.danglingRefs.schedules} schedule ref(s) and ${plan.danglingRefs.graphRuns} graph-run ref(s) pointing at the deletions.`,
142
+ );
143
+ }
136
144
  return 0;
137
145
  }
138
146
 
139
147
  const { removed, bytes } = await gcApply(archiveDir, options);
140
148
  io.print(`deleted ${removed.length} archived session(s), ${humanBytes(bytes)} freed.`);
149
+
150
+ // R10 Design B: sweep refs pointing at what we just removed. Daemon-first
151
+ // (registry mutations happen in-process, no file race); offline falls back
152
+ // to the same advisory lock Store.open takes.
153
+ const ids = removedSessionIds(removed);
154
+ if (ids.length > 0) {
155
+ try {
156
+ await sweepRefs(dataDirOf(archiveDir), ids, io, deviceToken(io));
157
+ } catch (e) {
158
+ io.printErr(
159
+ `dpi gc: deleted ${ids.length} session(s) but the ref sweep failed: ${
160
+ e instanceof Error ? e.message : String(e)
161
+ } (re-run later — the sweep is idempotent)`,
162
+ );
163
+ }
164
+ }
141
165
  return 0;
142
166
  } catch (e) {
143
167
  io.printErr(`dpi gc: ${e instanceof Error ? e.message : String(e)}`);
144
168
  return 2;
145
169
  }
146
170
  }
171
+
172
+ const dataDirOf = (archiveDir: string) => archiveDir.slice(0, archiveDir.length - "/archive".length);
173
+
174
+ /** The device token, from the process env or the env file (DPI_ENV_FILE) —
175
+ * only needed for the daemon-first sweep route. */
176
+ function deviceToken(io: GcIo): string | undefined {
177
+ if (io.env.DPI_TOKEN) return io.env.DPI_TOKEN;
178
+ const envFile = io.env.DPI_ENV_FILE;
179
+ if (!envFile) return undefined;
180
+ try {
181
+ return readEnvFile(io.readFile(envFile)).DPI_TOKEN;
182
+ } catch {
183
+ return undefined; // unreadable env file already failed loudly in resolveDataDir
184
+ }
185
+ }
186
+
187
+ /** Daemon-first dangling-ref sweep: POST /v1/gc/sweep-refs when the device
188
+ * answers locally, else the offline lock-guarded registry sweep. Reports what
189
+ * was cleared either way. Throws on failure (the caller prints and exits
190
+ * non-zero — the DELETE already happened; the sweep is idempotent, retryable). */
191
+ async function sweepRefs(dataDir: string, ids: string[], io: GcIo, token?: string): Promise<void> {
192
+ const port = Number(io.env.DPI_PORT ?? "4780");
193
+ if (token && Number.isInteger(port)) {
194
+ try {
195
+ const res = await fetch(`http://127.0.0.1:${port}/v1/gc/sweep-refs`, {
196
+ method: "POST",
197
+ headers: { "content-type": "application/json", "x-dpi-token": token },
198
+ body: JSON.stringify({ sessionIds: ids }),
199
+ signal: AbortSignal.timeout(10_000),
200
+ });
201
+ if (res.ok) {
202
+ const cleared = (await res.json()) as { schedules: number; graphRuns: number };
203
+ if (cleared.schedules || cleared.graphRuns)
204
+ io.print(`swept ${cleared.schedules} schedule ref(s), ${cleared.graphRuns} graph-run ref(s).`);
205
+ return;
206
+ }
207
+ // A non-OK from a LIVE device is a real fault — fall through to the
208
+ // offline path would race the daemon; surface it instead.
209
+ throw new Error(`device answered ${res.status} to the sweep route`);
210
+ } catch (e) {
211
+ if (e instanceof TypeError || (e instanceof Error && /fetch|network|ECONN/i.test(e.message))) {
212
+ /* device not reachable locally — offline path below */
213
+ } else throw e;
214
+ }
215
+ }
216
+ // Offline: the same advisory lock Store.open takes, so a live (but
217
+ // unreachable) daemon refuses instead of racing us on the registry files.
218
+ const unlock = lockFile(join(dataDir, "app-state.sqlite.lock"));
219
+ try {
220
+ const schedules = await ScheduleRegistry.open(join(dataDir, "schedules.json"));
221
+ const graphs = await GraphRegistry.open(join(dataDir, "graphs.json"));
222
+ const s = await schedules.clearSessionRefs(new Set(ids));
223
+ const g = await graphs.clearSessionRefs(new Set(ids));
224
+ if (s || g) io.print(`swept ${s} schedule ref(s), ${g} graph-run ref(s).`);
225
+ } catch (e) {
226
+ if (e instanceof DeviceAlreadyRunningError)
227
+ throw new Error("device is running — retry via the API route (dpi gc after the device answers, or restart it)");
228
+ throw e;
229
+ } finally {
230
+ unlock();
231
+ }
232
+ }
@@ -16,7 +16,8 @@
16
16
  * readable without opening any database.
17
17
  */
18
18
  import { readdir, rm, stat } from "node:fs/promises";
19
- import { join } from "node:path";
19
+ import { readFileSync } from "node:fs";
20
+ import { dirname, join } from "node:path";
20
21
  import { BUNDLE_DIR_PATTERN } from "./archived.js";
21
22
 
22
23
  export interface ArchivedEntry {
@@ -43,6 +44,10 @@ export interface GcPlan {
43
44
  candidateBytes: number;
44
45
  /** Directories we could not read (kept, never deleted). */
45
46
  skipped: { name: string; reason: string }[];
47
+ /** R10 Design B: refs that WOULD dangle if the candidates were deleted —
48
+ * schedule `lastSessionId`s and graph `TaskRunState.sessionId`s pointing at
49
+ * candidate session ids. The operator sees the referential cost of --yes. */
50
+ danglingRefs: { schedules: number; graphRuns: number };
46
51
  }
47
52
 
48
53
  async function dirBytes(path: string): Promise<number> {
@@ -77,7 +82,13 @@ export async function archivedEntries(
77
82
  const entries: ArchivedEntry[] = [];
78
83
  const skipped: GcPlan["skipped"] = [];
79
84
  for (const entry of await readdir(archiveDir, { withFileTypes: true }).catch(() => [])) {
80
- if (!entry.isDirectory()) continue;
85
+ if (!entry.isDirectory()) {
86
+ // R11 4.2: files and SYMLINKED dirs at archive/ root used to be silently
87
+ // invisible (not in total, not in skipped, never explained). Now the plan
88
+ // says what it ignored and why — an honest plan is auditable.
89
+ skipped.push({ name: entry.name, reason: "not a directory (file or symlink) — left untouched" });
90
+ continue;
91
+ }
81
92
  const parsed = parseArchivedName(entry.name);
82
93
  if (!parsed) {
83
94
  skipped.push({ name: entry.name, reason: "not an archived-session directory" });
@@ -95,6 +106,39 @@ export async function archivedEntries(
95
106
  return { entries: entries.sort((a, b) => b.closedAt - a.closedAt), skipped };
96
107
  }
97
108
 
109
+ /** R10 Design B: count refs that would dangle if `ids` were removed. Tolerant
110
+ * raw reads — the registries may not exist yet, and a corrupt file must never
111
+ * stop a gc plan (the sweep itself runs through the registries' own safe
112
+ * commit paths). */
113
+ export function danglingRefCounts(
114
+ dataDir: string,
115
+ ids: ReadonlySet<string>,
116
+ readFile: (p: string) => string = (p) => readFileSync(p, "utf8"),
117
+ ): { schedules: number; graphRuns: number } {
118
+ if (ids.size === 0) return { schedules: 0, graphRuns: 0 };
119
+ let schedules = 0;
120
+ let graphRuns = 0;
121
+ try {
122
+ const doc = JSON.parse(readFile(join(dataDir, "schedules.json"))) as {
123
+ schedules?: Array<{ lastSessionId?: string }>;
124
+ };
125
+ for (const s of doc.schedules ?? []) if (s.lastSessionId && ids.has(s.lastSessionId)) schedules += 1;
126
+ } catch {
127
+ /* absent or unreadable — nothing countable */
128
+ }
129
+ try {
130
+ const doc = JSON.parse(readFile(join(dataDir, "graphs.json"))) as {
131
+ runs?: Array<{ tasks?: Record<string, { sessionId?: string }> }>;
132
+ };
133
+ for (const run of doc.runs ?? [])
134
+ for (const task of Object.values(run.tasks ?? {}))
135
+ if (task.sessionId && ids.has(task.sessionId)) graphRuns += 1;
136
+ } catch {
137
+ /* absent or unreadable — nothing countable */
138
+ }
139
+ return { schedules, graphRuns };
140
+ }
141
+
98
142
  /** What a retention policy would delete. Pure read: nothing is touched. */
99
143
  export async function gcPlan(archiveDir: string, options: { closedBeforeDays: number; now?: number }): Promise<GcPlan> {
100
144
  const now = options.now ?? Date.now();
@@ -107,11 +151,13 @@ export async function gcPlan(archiveDir: string, options: { closedBeforeDays: nu
107
151
  const candidates = entries
108
152
  .filter((entry) => entry.closedAt <= cutoff)
109
153
  .map((entry) => ({ ...entry, ageDays: Math.floor((now - entry.closedAt) / 86_400_000) }));
154
+ const candidateIds = new Set(candidates.map((c) => c.sessionId));
110
155
  return {
111
156
  total: { count: entries.length, bytes: entries.reduce((n, e) => n + e.bytes, 0) },
112
157
  candidates,
113
158
  candidateBytes: candidates.reduce((n, e) => n + e.bytes, 0),
114
159
  skipped,
160
+ danglingRefs: danglingRefCounts(dirname(archiveDir), candidateIds),
115
161
  };
116
162
  }
117
163
 
@@ -138,6 +184,13 @@ export async function gcApply(
138
184
  return { removed, bytes: removed.reduce((n, e) => n + e.bytes, 0) };
139
185
  }
140
186
 
187
+ /** R10 Design B: the removed ids a ref-sweep should target (gcApply callers
188
+ * pass these on — to the daemon route when it answers, else the offline
189
+ * sweep). Derived from what gcApply actually removed. */
190
+ export function removedSessionIds(removed: readonly GcCandidate[]): string[] {
191
+ return removed.map((c) => c.sessionId);
192
+ }
193
+
141
194
  /**
142
195
  * "30d", "12h", "90m", "2w" → days (fractional). Days is the unit the plan
143
196
  * reasons in, so hours/weeks are converted here rather than refused.
@@ -682,6 +682,34 @@ export class GraphRegistry {
682
682
  });
683
683
  }
684
684
 
685
+ /** R10 Design B: clear TaskRunState.sessionId links pointing at sessions a gc
686
+ * pass removed — the run's status/error/timestamps stay (history is true,
687
+ * the link is gone). Idempotent by construction; returns how many links
688
+ * were cleared (for the CLI report and the dry-run parity check). */
689
+ async clearSessionRefs(ids: Set<string>): Promise<number> {
690
+ if (ids.size === 0) return 0;
691
+ let cleared = 0;
692
+ await this.run(async () => {
693
+ const runs = this.runRecords.map((run) => {
694
+ if (!run.tasks) return run;
695
+ let touched = false;
696
+ const tasks: Record<string, TaskRunState> = {};
697
+ for (const [taskId, task] of Object.entries(run.tasks)) {
698
+ if (task.sessionId !== undefined && ids.has(task.sessionId)) {
699
+ const { sessionId, ...rest } = task;
700
+ void sessionId;
701
+ tasks[taskId] = rest as TaskRunState;
702
+ cleared += 1;
703
+ touched = true;
704
+ } else tasks[taskId] = task;
705
+ }
706
+ return touched ? { ...run, tasks } : run;
707
+ });
708
+ await this.commit(new Map(this.graphs), runs);
709
+ });
710
+ return cleared;
711
+ }
712
+
685
713
  /**
686
714
  * Soft delete. Archiving an already-archived graph keeps the original stamp —
687
715
  * the first archive is the fact, a second one is a double click.
@@ -50,6 +50,12 @@ export function v1(
50
50
  // (/V1/DEVICE used to answer 200 over loopback and 404 through the tunnel).
51
51
  // Every client (sdk/TUI/web) speaks lowercase — verified against sdk client.ts.
52
52
  const r = Router({ caseSensitive: true });
53
+ // R11 6.3 (doc): `create` auto-keys un-keyed mutations (sha256 of method+path+body,
54
+ // 24 h retention) — a deliberate second identical create (same body) within 24 h
55
+ // REPLAYS the first response instead of creating again. That collapse is the
56
+ // accepted retry-safety tradeoff; clients that need deliberate repeats must send
57
+ // their own Idempotency-Key (which always wins over the auto-key), and replays
58
+ // are visible in the Idempotent-Replay: true response header.
53
59
  const create = idempotent(store);
54
60
  // `dpi device stop`: graceful local shutdown (token-authed like every /v1
55
61
  // route). The response flushes BEFORE the daemon tears down so the caller
@@ -307,10 +313,19 @@ export function v1(
307
313
  // The device owns execution (systemd/cron are deliberately rejected by config);
308
314
  // these routes only read and edit the schedule records.
309
315
  r.get("/schedules", (_req, res) => res.json({ schedules: store.scheduleList() }));
316
+ // R10 Design B: the daemon-side dangling-ref sweep. Deliberately NOT in the
317
+ // tunnel REST allowlist (apps/dpi-sdk/src/protocol/rest-routes.ts): this is
318
+ // device-LOCAL operator maintenance (the gc CLI calls it when the device is
319
+ // up, so registry mutations happen in-process with no file race) — the same
320
+ // operator-only surface as `dpi gc` itself.
321
+ r.post("/gc/sweep-refs", route(async (req, res) => res.json(await store.gcSweepRefs((req.body ?? {}).sessionIds))));
310
322
  r.post("/schedules", route(async (req, res) => res.status(201).json(await store.createSchedule(req.body ?? {}))));
311
323
  r.patch("/schedules/:id", route(async (req, res) => res.json(await store.updateSchedule(param(req, "id"), req.body ?? {}))));
312
324
  r.delete("/schedules/:id", route(async (req, res) => res.json(await store.removeSchedule(param(req, "id")))));
313
- r.post("/schedules/:id/run", route(async (req, res) => res.json(await store.runScheduleNow(param(req, "id")))));
325
+ // R11 2.3: 202 Accepted — the run is ARMED, not finished; the turn is bounded
326
+ // by the dispatch deadlines (60 s submit + 120 s settle) and its outcome lands
327
+ // in the schedule record (GET /schedules) and the schedule.ok/failed events.
328
+ r.post("/schedules/:id/run", route(async (_req, res) => res.status(202).json(await store.runScheduleNow(param(_req, "id")))));
314
329
 
315
330
  // ---------------------------------------------------------- sessions
316
331
  r.get("/sessions", route(async (_req, res) => res.json((await store.tree()).sessions)));
@@ -34,7 +34,8 @@
34
34
  * are removed and the original is left byte-identical.
35
35
  */
36
36
  import { Worker } from "node:worker_threads";
37
- import { existsSync, renameSync, rmSync } from "node:fs";
37
+ import { existsSync, linkSync, renameSync, rmSync } from "node:fs";
38
+ import { randomUUID } from "node:crypto";
38
39
 
39
40
  /** The open path must never hang on salvage: everything above this ceiling is abandoned. */
40
41
  export const SALVAGE_CEILING_MS = 5_000;
@@ -61,7 +62,7 @@ const { parentPort, workerData } = require("node:worker_threads");
61
62
  const { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } = require("node:fs");
62
63
  const { DatabaseSync } = require("node:sqlite");
63
64
  const main = workerData.dbPath;
64
- const copy = main + ".salvage";
65
+ const copy = workerData.copyPath; // R10 5.2: unique per attempt — two workers never share scratch files
65
66
  const fail = (reason) => parentPort.postMessage({ ok: false, reason: String(reason).slice(0, 80) });
66
67
  function run() {
67
68
  try {
@@ -118,17 +119,36 @@ try {
118
119
  run();
119
120
  `;
120
121
 
121
- const rmCopyFiles = (dbPath: string) => {
122
- for (const suffix of [".salvage", ".salvage-wal", ".salvage-shm"]) rmSync(dbPath + suffix, { force: true });
122
+ const rmCopyFiles = (copyPath: string) => {
123
+ for (const suffix of ["", "-wal", "-shm"]) rmSync(copyPath + suffix, { force: true });
123
124
  };
124
125
 
125
- /** Promote the verified copy: original aside (kept), copy atomically into place. */
126
- const promote = (dbPath: string): string => {
126
+ /** R10 5.2: a scratch name unique per attempt, so a second salvage on the same
127
+ * session (two routes opening one corrupt db concurrently) can never eat the
128
+ * first attempt's in-flight copy — the audit's strand-the-db scenario. */
129
+ const scratchPath = (dbPath: string): string =>
130
+ `${dbPath}.salvage-${process.pid.toString(36)}-${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`;
131
+
132
+ /** Promote the verified copy (R10 5.1: crash-window free). The ORIGINAL and its
133
+ * sidecars are hardlink-kept aside FIRST (link(2) — same bytes, no copy), the
134
+ * stale live sidecars are then removed, and ONE atomic rename puts the copy in
135
+ * place. At every crash point either the original or the promoted copy sits at
136
+ * the db path — never neither:
137
+ * - before the sidecar rm: retry sees the untouched original (+ its sidecars).
138
+ * - after it, before the rename: the original main is still in place (its
139
+ * sidecars live on via the aside links; a retry re-salvages to the last
140
+ * checkpoint — the honest-stale case, disclosed in the promote warning). */
141
+ const promote = (dbPath: string, copyPath: string): string => {
127
142
  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
143
+ linkSync(dbPath, aside);
144
+ for (const suffix of ["-wal", "-shm"]) {
145
+ if (existsSync(dbPath + suffix)) {
146
+ linkSync(dbPath + suffix, `${aside}${suffix}`);
147
+ rmSync(dbPath + suffix, { force: true }); // stale against the promoted main
148
+ }
149
+ }
150
+ renameSync(copyPath, dbPath); // POSIX rename: atomic replace
151
+ rmCopyFiles(copyPath); // the copy's own sidecars were checkpointed away; drop leftovers
132
152
  return aside;
133
153
  };
134
154
 
@@ -140,8 +160,9 @@ const promote = (dbPath: string): string => {
140
160
  export function salvageSessionDb(dbPath: string, ceilingMs: number = SALVAGE_CEILING_MS): Promise<SalvageOutcome> {
141
161
  return new Promise((resolve) => {
142
162
  let worker: Worker;
163
+ const copyPath = scratchPath(dbPath); // R10 5.2: unique scratch per attempt
143
164
  try {
144
- worker = new Worker(WORKER_SRC, { eval: true, workerData: { dbPath } });
165
+ worker = new Worker(WORKER_SRC, { eval: true, workerData: { dbPath, copyPath } });
145
166
  } catch {
146
167
  resolve({ attempted: false, recovered: false, reason: "salvage worker unavailable" });
147
168
  return;
@@ -155,12 +176,12 @@ export function salvageSessionDb(dbPath: string, ceilingMs: number = SALVAGE_CEI
155
176
  let outcome = result;
156
177
  if (outcome.recovered) {
157
178
  try {
158
- outcome = { ...outcome, keptAs: promote(dbPath) };
179
+ outcome = { ...outcome, keptAs: promote(dbPath, copyPath) };
159
180
  } catch {
160
181
  outcome = { attempted: true, recovered: false, reason: "promotion failed" };
161
182
  }
162
183
  }
163
- if (!outcome.recovered) rmCopyFiles(dbPath);
184
+ if (!outcome.recovered) rmCopyFiles(copyPath);
164
185
  resolve(outcome);
165
186
  };
166
187
  const timer = setTimeout(() => {
@@ -188,14 +188,21 @@ export async function scheduleCli(argv: readonly string[], io: ScheduleIo = defa
188
188
  return 0;
189
189
  }
190
190
  if (sub === "run") {
191
- io.print(`${target.name}: running…`);
191
+ io.print(`${target.name}: starting…`);
192
+ // R11 2.3: the route answers 202 as soon as the run is ARMED — the turn
193
+ // itself is bounded by the dispatch deadlines and lands in the record and
194
+ // the schedule.ok/failed events. `dpi schedule list` shows the outcome.
192
195
  const ran = await call<ScheduleView>(io, "POST", `/v1/schedules/${target.id}/run`, {});
193
196
  if (!ran.ok) {
194
197
  io.printErr(`dpi schedule: ${ran.error}`);
195
198
  return 1;
196
199
  }
197
- io.print(`${ran.data.lastOutcome ?? "ok"}${ran.data.lastError ? ` — ${ran.data.lastError}` : ""}; next ${when(ran.data.nextRunAt)}`);
198
- return ran.data.lastOutcome === "failed" ? 1 : 0;
200
+ io.print(
201
+ ran.data.running
202
+ ? `run started (watch \`dpi schedule list\` for the outcome); next ${when(ran.data.nextRunAt)}`
203
+ : `armed; next ${when(ran.data.nextRunAt)}`,
204
+ );
205
+ return 0;
199
206
  }
200
207
  if (sub === "remove") {
201
208
  const removed = await call<{ removed: boolean }>(io, "DELETE", `/v1/schedules/${target.id}`);
@@ -45,6 +45,19 @@ export const MIN_EVERY_MINUTES = 5;
45
45
  /** A day: longer than this and `dailyAt` is the better trigger anyway. */
46
46
  export const MAX_EVERY_MINUTES = 1440;
47
47
 
48
+ /** R10 Design A: bounds for per-schedule session retention. 1 = keep only the
49
+ * latest run live; 100 x 5-min runs ≈ 8h of live transcripts — enough for any
50
+ * "recent context" use, small enough that a fat-finger cannot pin 100k sessions. */
51
+ export const MIN_KEEP_RUNS = 1;
52
+ export const MAX_KEEP_RUNS = 100;
53
+
54
+ /** Throws unless v is a legal keepRuns (integer 1..100). Shared by create/patch. */
55
+ function normaliseKeepRuns(v: unknown): number {
56
+ if (typeof v !== "number" || !Number.isInteger(v) || v < MIN_KEEP_RUNS || v > MAX_KEEP_RUNS)
57
+ throw invalid(`keepRuns must be an integer between ${MIN_KEEP_RUNS} and ${MAX_KEEP_RUNS}`);
58
+ return v;
59
+ }
60
+
48
61
  /** `HH:MM`, 24-hour, local time. Strict two digits so the file has one spelling per time. */
49
62
  const DAILY_AT_PATTERN = /^([01]\d|2[0-3]):([0-5]\d)$/;
50
63
  const MINUTE_MS = 60_000;
@@ -98,6 +111,13 @@ export interface ScheduleRecord {
98
111
  lastOutcome?: ScheduleRunOutcome;
99
112
  /** Why the last run failed. Cleared by the next successful run. */
100
113
  lastError?: string;
114
+ /** R10 Design A: keep the last N runs' sessions live; archive older ones at
115
+ * the end of a successful dispatch. Absent = never auto-archive. */
116
+ keepRuns?: number;
117
+ /** R10 Design A: bounded ring of the newest keepRuns run session ids — the
118
+ * retention window. Pushed by markRun, trimmed to keepRuns; the ONLY
119
+ * registry growth this feature adds, bounded by construction. */
120
+ recentSessionIds?: string[];
101
121
  createdAt: number;
102
122
  updatedAt: number;
103
123
  }
@@ -113,10 +133,11 @@ export interface ScheduleInput {
113
133
  }
114
134
 
115
135
  /** `create` also takes the initial `enabled` bit, so a schedule can be staged switched-off. */
116
- export type ScheduleCreateInput = ScheduleInput & { enabled?: boolean };
136
+ export type ScheduleCreateInput = ScheduleInput & { enabled?: boolean; keepRuns?: number };
117
137
 
118
- /** What `update` accepts: everything a user owns, plus the switch. */
119
- export type SchedulePatch = Partial<ScheduleInput> & { enabled?: boolean };
138
+ /** What `update` accepts: everything a user owns, plus the switch. `keepRuns:
139
+ * null` CLEARS retention (R10 Design A). */
140
+ export type SchedulePatch = Partial<ScheduleInput> & { enabled?: boolean; keepRuns?: number | null };
120
141
 
121
142
  /** The fields `computeNextRun` reads. Narrowed so callers can pass a bare object in tests. */
122
143
  export type ScheduleTiming = Pick<
@@ -364,6 +385,18 @@ function coerceRecord(raw: unknown, now: number): ScheduleRecord {
364
385
  if (isOutcome(source.lastOutcome)) record.lastOutcome = source.lastOutcome;
365
386
  const lastError = nonEmptyString(source.lastError);
366
387
  if (lastError) record.lastError = lastError;
388
+ // R10 Design A: retention window — defensive parse (bounds enforced, ring
389
+ // trimmed, junk entries dropped) so a hand-edited or future file cannot
390
+ // unbound the registry.
391
+ if (typeof source.keepRuns === "number" && Number.isInteger(source.keepRuns)) {
392
+ const keepRuns = Math.min(Math.max(source.keepRuns, MIN_KEEP_RUNS), MAX_KEEP_RUNS);
393
+ record.keepRuns = keepRuns;
394
+ if (Array.isArray(source.recentSessionIds)) {
395
+ const ring = source.recentSessionIds.filter((id): id is string => typeof id === "string" && id.length > 0);
396
+ const unique = [...new Set(ring)].slice(-keepRuns);
397
+ if (unique.length > 0) record.recentSessionIds = unique;
398
+ }
399
+ }
367
400
  return record;
368
401
  }
369
402
 
@@ -477,6 +510,7 @@ export class ScheduleRegistry {
477
510
  throw invalid("enabled must be a boolean");
478
511
  }
479
512
  const enabled = input?.enabled ?? true;
513
+ const keepRuns = input?.keepRuns !== undefined ? normaliseKeepRuns(input.keepRuns) : undefined;
480
514
  return this.run(async () => {
481
515
  const staged = new Map(this.records);
482
516
  let id = newScheduleId();
@@ -485,6 +519,7 @@ export class ScheduleRegistry {
485
519
  const created: ScheduleRecord = { id, name, cwd, model, prompt, enabled, createdAt: now, updatedAt: now };
486
520
  if (trigger.everyMinutes !== undefined) created.everyMinutes = trigger.everyMinutes;
487
521
  if (trigger.dailyAt !== undefined) created.dailyAt = trigger.dailyAt;
522
+ if (keepRuns !== undefined) created.keepRuns = keepRuns;
488
523
  staged.set(created.id, created);
489
524
  await this.commit(staged);
490
525
  return clone(created);
@@ -501,6 +536,7 @@ export class ScheduleRegistry {
501
536
  if (patch?.enabled !== undefined && typeof patch.enabled !== "boolean") {
502
537
  throw invalid("enabled must be a boolean");
503
538
  }
539
+ if (patch?.keepRuns !== undefined && patch.keepRuns !== null) normaliseKeepRuns(patch.keepRuns);
504
540
  return this.run(async () => {
505
541
  const staged = new Map(this.records);
506
542
  const existing = staged.get(id);
@@ -511,6 +547,22 @@ export class ScheduleRegistry {
511
547
  if ("model" in patch) next.model = normaliseModel(patch.model);
512
548
  if ("prompt" in patch) next.prompt = normalisePrompt(patch.prompt);
513
549
  if ("enabled" in patch) next.enabled = patch.enabled as boolean;
550
+ if ("keepRuns" in patch) {
551
+ if (patch.keepRuns === null) {
552
+ // Clearing retention: the ring goes with it (the sessions stay live
553
+ // forever, exactly as before this feature existed).
554
+ delete next.keepRuns;
555
+ delete next.recentSessionIds;
556
+ } else if (patch.keepRuns === undefined) {
557
+ /* explicit undefined = no change */
558
+ } else {
559
+ next.keepRuns = normaliseKeepRuns(patch.keepRuns);
560
+ const ring = next.recentSessionIds ?? [];
561
+ const trimmed = ring.slice(-next.keepRuns);
562
+ if (trimmed.length > 0) next.recentSessionIds = trimmed;
563
+ else delete next.recentSessionIds;
564
+ }
565
+ }
514
566
  if ("everyMinutes" in patch || "dailyAt" in patch) {
515
567
  const trigger = normaliseTrigger({
516
568
  everyMinutes: "everyMinutes" in patch ? patch.everyMinutes : existing.everyMinutes,
@@ -595,6 +647,13 @@ export class ScheduleRegistry {
595
647
  const sessionId = nonEmptyString(result.sessionId);
596
648
  if (sessionId) next.lastSessionId = sessionId;
597
649
  else delete next.lastSessionId;
650
+ // R10 Design A: the retention window ring — push the run's session, trim
651
+ // to keepRuns. The ids that FALL OFF the window (evicted) are the prune
652
+ // candidates; the caller snapshots the ring before this call and diffs.
653
+ if (sessionId && typeof next.keepRuns === "number") {
654
+ const ring = [...(next.recentSessionIds ?? []).filter((id) => id !== sessionId), sessionId];
655
+ next.recentSessionIds = ring.slice(-next.keepRuns);
656
+ }
598
657
  const error = nonEmptyString(result.error);
599
658
  if (result.outcome !== "ok" && error) next.lastError = error;
600
659
  else delete next.lastError; // a success (or a fresh intent) clears the reason the last one failed
@@ -604,6 +663,42 @@ export class ScheduleRegistry {
604
663
  });
605
664
  }
606
665
 
666
+ /** R10 Design B: clear `lastSessionId` (and retention-ring entries) pointing
667
+ * at sessions a gc pass removed. The run outcome/error/history STAY — only
668
+ * the link goes. Idempotent; returns how many records were touched. */
669
+ async clearSessionRefs(ids: Set<string>): Promise<number> {
670
+ if (ids.size === 0) return 0;
671
+ return this.run(async () => {
672
+ let touched = 0;
673
+ const staged = new Map(this.records);
674
+ for (const [id, existing] of staged) {
675
+ let next = existing;
676
+ let changed = false;
677
+ if (existing.lastSessionId !== undefined && ids.has(existing.lastSessionId)) {
678
+ const { lastSessionId, ...rest } = existing;
679
+ void lastSessionId;
680
+ next = rest as ScheduleRecord;
681
+ changed = true;
682
+ }
683
+ // Design A interplay: ring ids pointing at removed sessions are dangling
684
+ // too — drop them so archivedRuns does not count ghosts forever.
685
+ if (next.recentSessionIds?.some((sid) => ids.has(sid))) {
686
+ const kept = next.recentSessionIds.filter((sid) => !ids.has(sid));
687
+ next = { ...next, recentSessionIds: kept.length > 0 ? kept : undefined } as ScheduleRecord;
688
+ if (kept.length === 0) delete next.recentSessionIds;
689
+ changed = true;
690
+ }
691
+ if (changed) {
692
+ next.updatedAt = this.now();
693
+ staged.set(id, next);
694
+ touched += 1;
695
+ }
696
+ }
697
+ if (touched > 0) await this.commit(staged);
698
+ return touched;
699
+ });
700
+ }
701
+
607
702
  /**
608
703
  * Boot-time recovery (R8 2.4): a run still marked `started` never recorded its
609
704
  * outcome — the daemon died between the intent marker and the write-back. Flip
@@ -1593,7 +1593,15 @@ export class Store {
1593
1593
  storage = await openNodeSqliteStorage(row.dbPath);
1594
1594
  } catch (error) {
1595
1595
  if (create || !isUnreadableStorage(error)) throw error;
1596
- const outcome = await salvageSessionDb(row.dbPath);
1596
+ // R10 5.2: single-flight per session — two routes opening one corrupt db
1597
+ // (UI refresh fetching git-files + agents) used to spawn two salvage
1598
+ // workers racing on shared scratch; both attempts now share ONE outcome.
1599
+ const inFlight = this.salvageInFlight.get(row.id) ?? salvageSessionDb(row.dbPath).then((outcome) => {
1600
+ this.salvageInFlight.delete(row.id);
1601
+ return outcome;
1602
+ });
1603
+ this.salvageInFlight.set(row.id, inFlight);
1604
+ const outcome = await inFlight;
1597
1605
  if (!outcome.recovered) {
1598
1606
  const note = salvageFailureNote(outcome);
1599
1607
  const previous = this.errors.get(row.id);
@@ -1611,7 +1619,8 @@ export class Store {
1611
1619
  throw new ApiFault("unavailable", note);
1612
1620
  }
1613
1621
  process.emitWarning(
1614
- `[dpi-backend] session ${row.id}'s database was unreadable; salvaged a copy (original kept as ${outcome.keptAs})`,
1622
+ `[dpi-backend] session ${row.id}'s database was unreadable; salvaged a copy (original kept as ${outcome.keptAs}). ` +
1623
+ `The copy reflects the database's last consistent state — if its write-ahead log was lost in the crash, the final turns may be missing (the quarantined original retains every byte).`,
1615
1624
  );
1616
1625
  storage = await openNodeSqliteStorage(row.dbPath); // the ONE retry, on the promoted copy
1617
1626
  }
@@ -2570,6 +2579,22 @@ export class Store {
2570
2579
  return this.scheduleView(record);
2571
2580
  }
2572
2581
 
2582
+ /** R10 Design B: clear schedule/graph refs pointing at sessions a gc pass
2583
+ * removed (the daemon-side sweep — the CLI routes here when the device is
2584
+ * up, so registry mutations happen in-process with no file race). The
2585
+ * registries keep outcome/error history; only the links go. Cap 10k ids. */
2586
+ async gcSweepRefs(sessionIds: unknown): Promise<{ schedules: number; graphRuns: number }> {
2587
+ if (!Array.isArray(sessionIds)) throw new ApiFault("invalid", "sessionIds must be an array");
2588
+ if (sessionIds.length > 10_000) throw new ApiFault("invalid", "sessionIds capped at 10000");
2589
+ const ids = new Set(
2590
+ sessionIds.filter((id): id is string => typeof id === "string" && id.length > 0 && id.length <= 64),
2591
+ );
2592
+ const schedules = await this.schedules.clearSessionRefs(ids);
2593
+ const graphRuns = await this.graphs.clearSessionRefs(ids);
2594
+ if (schedules > 0 || graphRuns > 0) this.notify();
2595
+ return { schedules, graphRuns };
2596
+ }
2597
+
2573
2598
  async removeSchedule(id: string): Promise<{ removed: boolean }> {
2574
2599
  const removed = await this.schedules.remove(id);
2575
2600
  this.notify();
@@ -2580,11 +2605,23 @@ export class Store {
2580
2605
  * Throws ApiFault("busy") (HTTP 409, "already running") when the schedule
2581
2606
  * has a run in flight: the guard lives in the shared dispatch entry point
2582
2607
  * (R8 2.1), so a double-clicked Run button gets a typed fault instead of a
2583
- * second concurrent run with duplicated side effects. */
2608
+ * second concurrent run with duplicated side effects.
2609
+ *
2610
+ * R11 2.3: returns AS SOON AS the run is armed, not when the turn finishes —
2611
+ * a slow turn used to hold the HTTP request (and the hub tunnel) hostage
2612
+ * for up to the full 60 s dispatch deadline + 120 s settle cap; browsers
2613
+ * and proxies time out long before that. No awaits sit between the busy
2614
+ * pre-check and the dispatch (whose guard-add also runs synchronously), so
2615
+ * two Run clicks in one turn cannot both pass. The outcome lands in the
2616
+ * record (scheduleList/view) and the schedule.ok/failed events, exactly as
2617
+ * the timer path's outcomes always have. The route answers 202. */
2584
2618
  async runScheduleNow(id: string): Promise<ScheduleView> {
2585
2619
  const record = this.schedules.get(id);
2586
2620
  if (!record) throw notFound(`no schedule ${id}`);
2587
- await this.dispatchSchedule(record);
2621
+ if (this.scheduleInFlight.has(record.id)) {
2622
+ throw new ApiFault("busy", `Schedule "${record.name}" is already running`);
2623
+ }
2624
+ void this.dispatchSchedule(record).catch(() => undefined);
2588
2625
  return this.scheduleView(this.schedules.get(id) ?? record);
2589
2626
  }
2590
2627
 
@@ -2594,9 +2631,18 @@ export class Store {
2594
2631
  // dpi-sdk is not this fix's file, so carry the recorded value through with
2595
2632
  // a narrowing cast. UIs treat the field as opaque text.
2596
2633
  const { lastOutcome, ...rest } = record;
2634
+ // R10 Design A: derived count of ring ids no longer live (archived or gone)
2635
+ // so the UI can render "keeping last N" truthfully. Bounded: ring ≤ 100.
2636
+ let archivedRuns: number | undefined;
2637
+ if (record.keepRuns !== undefined && record.recentSessionIds?.length) {
2638
+ archivedRuns = record.recentSessionIds.filter(
2639
+ (id) => !this.catalog.prepare("SELECT 1 FROM sessions WHERE id=?").get(id),
2640
+ ).length;
2641
+ }
2597
2642
  return {
2598
2643
  ...rest,
2599
2644
  ...(lastOutcome === undefined ? {} : { lastOutcome: lastOutcome as ScheduleView["lastOutcome"] }),
2645
+ ...(archivedRuns !== undefined ? { archivedRuns } : {}),
2600
2646
  nextRunAt: this.schedules.nextRunAt(record, Date.now()) ?? null,
2601
2647
  running: this.scheduleInFlight.has(record.id),
2602
2648
  };
@@ -2608,6 +2654,14 @@ export class Store {
2608
2654
  private scheduleInFlight = new Set<string>();
2609
2655
  private scheduleTimer?: ReturnType<typeof setTimeout>;
2610
2656
 
2657
+ /** R11 2.2: schedules whose registry (schedules.json) is currently
2658
+ * unwritable — each is reported ONCE per degraded episode, not per tick. */
2659
+ private scheduleRegistryDegraded = new Set<string>();
2660
+
2661
+ /** R10 5.2: per-session salvage single-flight — concurrent openers of one
2662
+ * corrupt session share ONE bounded attempt instead of racing scratch files. */
2663
+ private salvageInFlight = new Map<string, Promise<import("./salvage.js").SalvageOutcome>>();
2664
+
2611
2665
  /** R8 schedule budgets (StoreOptions-overridable so tests simulate wedged
2612
2666
  * dispatches in milliseconds instead of minutes). */
2613
2667
  private get scheduleTickMs(): number {
@@ -2680,14 +2734,42 @@ export class Store {
2680
2734
  this.scheduleInFlight.add(record.id);
2681
2735
  this.notify();
2682
2736
  try {
2683
- // Persist the intent before any await that can wedge. If this persist
2684
- // itself fails (disk full), the run still proceeds — it just loses the
2685
- // crash-safety guarantee, like every version before R8.
2686
- await deadline(
2737
+ // R11 2.2: the intent marker is the at-most-once anchor. Without it,
2738
+ // `due()` re-offers this slot on EVERY tick while the registry is
2739
+ // unwritable (disk full, AV lock) and the prompt would re-fire at tick
2740
+ // rate — up to 2,880 duplicate real runs/day, each with a notify event.
2741
+ // So a failed intent persist now SKIPS the dispatch (the run has not
2742
+ // started, so not running it is correct) and surfaces the degraded
2743
+ // state ONCE per episode; the next successful write ends the episode.
2744
+ // Outcome persists inside dispatchBounded stay best-effort.
2745
+ const intentOk = await deadline(
2687
2746
  this.schedules.markRun(record.id, { outcome: "started" }),
2688
2747
  SCHEDULE_REGISTRY_IO_MS,
2689
2748
  "schedule registry write timed out (started)",
2690
- ).catch(() => undefined);
2749
+ ).then(
2750
+ () => true,
2751
+ () => false,
2752
+ );
2753
+ if (!intentOk) {
2754
+ if (!this.scheduleRegistryDegraded.has(record.id)) {
2755
+ this.scheduleRegistryDegraded.add(record.id);
2756
+ void this.notifyEvent({
2757
+ kind: "schedule.failed",
2758
+ title: `Schedule paused: ${record.name}`,
2759
+ body: "its registry is unwritable (disk full or locked) — the run was skipped so it cannot re-fire every tick; it resumes when the registry is writable again",
2760
+ data: { scheduleId: record.id },
2761
+ });
2762
+ }
2763
+ return;
2764
+ }
2765
+ if (this.scheduleRegistryDegraded.delete(record.id)) {
2766
+ void this.notifyEvent({
2767
+ kind: "schedule.ok",
2768
+ title: `Schedule resumed: ${record.name}`,
2769
+ body: "registry writes recovered; scheduled runs continue",
2770
+ data: { scheduleId: record.id },
2771
+ });
2772
+ }
2691
2773
  await this.dispatchBounded(record);
2692
2774
  } finally {
2693
2775
  this.scheduleInFlight.delete(record.id);
@@ -2754,11 +2836,16 @@ export class Store {
2754
2836
  return;
2755
2837
  }
2756
2838
  if (result.status === "done") {
2757
- await deadline(
2839
+ // R10 Design A: snapshot the retention ring BEFORE markRun pushes+trims,
2840
+ // then prune whatever fell out of the window (void: never blocks the
2841
+ // guard release, no new timers — best-effort archive with retry next run).
2842
+ const ringBefore = [...(record.recentSessionIds ?? [])];
2843
+ const okRecord = await deadline(
2758
2844
  this.schedules.markRun(record.id, { sessionId, outcome: "ok" }),
2759
2845
  SCHEDULE_REGISTRY_IO_MS,
2760
2846
  "schedule registry write timed out (ok)",
2761
2847
  ).catch(() => undefined);
2848
+ if (okRecord?.keepRuns) void this.pruneScheduleSessions(okRecord, ringBefore).catch(() => undefined);
2762
2849
  void this.notifyEvent({
2763
2850
  kind: "schedule.ok",
2764
2851
  title: `Schedule ran: ${record.name}`,
@@ -2786,6 +2873,26 @@ export class Store {
2786
2873
  }
2787
2874
  }
2788
2875
 
2876
+ /** R10 Design A: archive run sessions that fell out of the schedule's
2877
+ * keepRuns window. Called (void, best-effort) only from the ok-path of a
2878
+ * successful dispatch, with the ring as it was BEFORE markRun trimmed it.
2879
+ * `ringBefore \ ringAfter` = evicted ids; each LIVE evicted session is
2880
+ * archived via the existing store.archive path (abort-open → atomic rename
2881
+ * to archive/ → catalog row deleted — nothing deleted, restorable, ages into
2882
+ * the gc plan). Archive failure leaves the session live; the id is already
2883
+ * gone from the ring, but the session stays restorable and the operator can
2884
+ * archive it manually — at most keepRuns stragglers can overstay (bounded). */
2885
+ private async pruneScheduleSessions(record: ScheduleRecord, ringBefore: string[]): Promise<void> {
2886
+ if (typeof record.keepRuns !== "number") return;
2887
+ const ringNow = new Set(record.recentSessionIds ?? []);
2888
+ const evicted = [...new Set(ringBefore)].filter((id) => !ringNow.has(id));
2889
+ for (const id of evicted) {
2890
+ const row = this.catalog.prepare("SELECT * FROM sessions WHERE id=?").get(id) as SessionRow | undefined;
2891
+ if (!row) continue; // already gone (archived/corrupt-removed) — nothing to do
2892
+ await this.archive(row);
2893
+ }
2894
+ }
2895
+
2789
2896
  // ------------------------------------------------- projects (Wave 2)
2790
2897
 
2791
2898
  /** The project a path belongs to: its longest registered root. */
@@ -130,7 +130,12 @@ async function readBodyCapped(
130
130
  * absent for textual responses so older hubs see an unchanged frame. */
131
131
  const TEXTUAL_CT_RE = /^(?:text\/|application\/(?:json|javascript|xml|x-www-form-urlencoded)(?:;|$))/i;
132
132
  /** base64 inflates by 4/3 and the serialized envelope must still fit the chunk budget
133
- * (CHUNK_RAW_BYTES × MAX_CHUNKS_PER_MESSAGE = 16 MiB), so binaries get their own headroom. */
133
+ * (CHUNK_RAW_BYTES × MAX_CHUNKS_PER_MESSAGE = 16 MiB), so binaries get their own headroom.
134
+ * R11 3.2 (doc): this 12 MB is the ceiling for EVERY tunnelled binary — an export
135
+ * larger than this refuses with response_too_large (deflate ≈ 3-5× on transcripts,
136
+ * so most sessions fit; the LOCAL device ceiling is the 256 MiB streaming one in
137
+ * zip.ts). The asymmetry is physics: textual frames get 16 MiB logical because
138
+ * they never carry the 4/3 inflation; binaries pay it, so they get 12 MB pre-base64. */
134
139
  const BINARY_RESPONSE_MAX_BYTES = 12_000_000;
135
140
  const safeHeaderValue = (value: string | null | undefined): string | undefined => {
136
141
  if (!value) return undefined;
@@ -739,7 +744,13 @@ export class DeviceConnector {
739
744
  tooLarge(
740
745
  textual
741
746
  ? `Device response exceeds ${LOGICAL_MESSAGE_MAX_BYTES} bytes`
742
- : `Binary response exceeds the ${BINARY_RESPONSE_MAX_BYTES}-byte tunnel budget`,
747
+ : `Binary response exceeds the ${BINARY_RESPONSE_MAX_BYTES}-byte tunnel budget` +
748
+ // R11 1.3: the two export ceilings must tell ONE story — the
749
+ // tunnel cap is 12 MB compressed, the local one 256 MiB raw;
750
+ // name the remedies instead of a bare byte count.
751
+ (frame.path.endsWith("/export")
752
+ ? " — compact the session (archive old agents), or export it directly from the device"
753
+ : ""),
743
754
  );
744
755
  return;
745
756
  }
@@ -13,13 +13,20 @@
13
13
  * whole bundle (raw texts + deflate + base64 ≈ 2-3× transcript size, the R5
14
14
  * audit's scale cliff) — `streamSessionBundle` composes the same entries from
15
15
  * the store's public APIs, deflates each one through a pipe while writing a
16
- * temp file under `os.tmpdir()`, and the route pipes that file to the HTTP
17
- * response before unlinking it. Entries keep today's paths/payloads; the only
18
- * layout difference is the streaming form's data descriptor (spec bit 3) so
19
- * entry sizes can be written after the deflated body without buffering it.
16
+ * temp file, and the route pipes that file to the HTTP response before
17
+ * unlinking it. Entries keep today's paths/payloads; the only layout
18
+ * difference is the streaming form's data descriptor (spec bit 3) so entry
19
+ * sizes can be written after the deflated body without buffering it.
20
+ *
21
+ * R11 1.1: the temp file lives BESIDE THE DATA DIR (same volume as the store,
22
+ * DPI_EXPORT_TMPDIR overrides), not `os.tmpdir()` — a tmpfs-backed /tmp is
23
+ * RAM, and the R5 cliff would return through the back door (or ENOSPC at
24
+ * tmpfs size while the real disk sits empty). "Streaming lifted the RAM
25
+ * cliff" is volume-dependent: the deflate WINDOW is always RAM-bounded, the
26
+ * spill file is disk-bounded only where the data dir lives on real disk.
20
27
  */
21
28
  import { randomUUID } from "node:crypto";
22
- import { open, rm } from "node:fs/promises";
29
+ import { open, rm, stat } from "node:fs/promises";
23
30
  import { tmpdir, hostname, platform } from "node:os";
24
31
  import { join } from "node:path";
25
32
  import { Readable } from "node:stream";
@@ -218,10 +225,20 @@ const FLAG_DESCRIPTOR = 0x0008;
218
225
  const DATA_DESCRIPTOR_SIG = 0x08074b50;
219
226
 
220
227
  /**
221
- * A temp file under the OS temp dir (never a hardcoded path — Windows-safe),
222
- * written 0600 like every other transcript-bearing file on the device.
228
+ * A temp file (never a hardcoded path — Windows-safe), written 0600 like
229
+ * every other transcript-bearing file on the device. R11 1.1: the SPILL
230
+ * volume is the data dir (real disk, same filesystem the store already
231
+ * writes), `DPI_EXPORT_TMPDIR` overrides, `os.tmpdir()` is the last resort —
232
+ * tmpfs-backed /tmp is RAM and would silently reintroduce the R5 cliff.
223
233
  */
224
- const tempZipPath = () => join(tmpdir(), `dpi-export-${process.pid}-${randomUUID()}.zip`);
234
+ const tempZipPath = (baseDir: string) => join(baseDir, `.dpi-export-${process.pid}-${randomUUID()}.zip`);
235
+
236
+ /** Where the export spill file goes: explicit operator override → the store's
237
+ * own data dir (R11 1.1) → the OS temp dir. Dot-prefixed so a casual `ls`
238
+ * of the data dir does not read as a session artifact. */
239
+ export function exportTempDir(dataDir: string): string {
240
+ return process.env.DPI_EXPORT_TMPDIR || dataDir || tmpdir();
241
+ }
225
242
 
226
243
  /**
227
244
  * The streaming half of the zip writer. Entries are deflated through a pipe and
@@ -252,8 +269,8 @@ class ZipStreamWriter {
252
269
  }
253
270
 
254
271
  /** Create the temp file exclusively, so two exports never share one archive. */
255
- static async create(): Promise<ZipStreamWriter> {
256
- const path = tempZipPath();
272
+ static async create(baseDir: string): Promise<ZipStreamWriter> {
273
+ const path = tempZipPath(baseDir);
257
274
  const handle = await open(path, "wx", 0o600);
258
275
  return new ZipStreamWriter(path, handle);
259
276
  }
@@ -416,7 +433,38 @@ export async function streamSessionBundle(
416
433
  opts: { ceilingBytes?: number } = {},
417
434
  ): Promise<StreamedBundle> {
418
435
  const ceilingBytes = opts.ceilingBytes ?? EXPORT_TOTAL_LIMIT_BYTES;
419
- const writer = await ZipStreamWriter.create();
436
+ // R11 1.2: refuse MONSTROUS sessions BEFORE the first stringify. The store db
437
+ // holds every entry the bundle re-serializes, so a db over the ceiling can
438
+ // only refuse later — after a ~2-4× transient (entries clone + pretty JSON)
439
+ // that OOMs instead of answering. A cheap stat converts heap death into the
440
+ // polite, remedy-naming refusal. (A db under the ceiling can still overflow
441
+ // mid-write — json+md ≈ 2× content — and the streaming `add()` guard catches
442
+ // that gracefully, as it always has.)
443
+ const dbBytes = await stat(row.dbPath).then(
444
+ (s) => s.size,
445
+ () => 0,
446
+ );
447
+ if (dbBytes > ceilingBytes) {
448
+ throw invalid(
449
+ `Export refused: this session's store is ${mb(dbBytes)} of data, over the ${mb(ceilingBytes)} export ceiling. ` +
450
+ `Compact the session first (archive old agents), or export it directly from the device`,
451
+ );
452
+ }
453
+ const tempDir = exportTempDir(store.options.dataDir);
454
+ let writer: ZipStreamWriter;
455
+ try {
456
+ writer = await ZipStreamWriter.create(tempDir);
457
+ } catch (e) {
458
+ // R11 1.4: disk-full surfaces as a typed invalid fault naming the remedy
459
+ // (which volume, which knob), not a raw ENOSPC string on a 500.
460
+ if ((e as NodeJS.ErrnoException).code === "ENOSPC") {
461
+ throw invalid(
462
+ `disk full while creating the export temp file under ${tempDir} — free space on that volume ` +
463
+ `(or point DPI_EXPORT_TMPDIR at one with room) and retry`,
464
+ );
465
+ }
466
+ throw e;
467
+ }
420
468
  try {
421
469
  for await (const entry of sessionBundleEntries(store, row)) await writer.add(entry, ceilingBytes);
422
470
  const bytes = await writer.finish();
@@ -430,6 +478,13 @@ export async function streamSessionBundle(
430
478
  };
431
479
  } catch (cause) {
432
480
  await writer.dispose();
481
+ if ((cause as NodeJS.ErrnoException).code === "ENOSPC") {
482
+ // R11 1.4: mid-write disk-full gets the same typed refusal as create-time.
483
+ throw invalid(
484
+ `disk full while writing the export under ${tempDir} — free space on that volume ` +
485
+ `(or point DPI_EXPORT_TMPDIR at one with room) and retry`,
486
+ );
487
+ }
433
488
  throw cause;
434
489
  }
435
490
  }
@@ -390,6 +390,10 @@ export interface ScheduleRecord {
390
390
  lastSessionId?: string;
391
391
  lastOutcome?: "ok" | "failed";
392
392
  lastError?: string;
393
+ /** R10: keep the last N runs' sessions live, archive older ones. Absent = never. */
394
+ keepRuns?: number;
395
+ /** R10: the retention window (newest keepRuns run session ids). */
396
+ recentSessionIds?: string[];
393
397
  createdAt: number;
394
398
  updatedAt: number;
395
399
  }
@@ -399,6 +403,8 @@ export interface ScheduleView extends ScheduleRecord {
399
403
  nextRunAt: number | null;
400
404
  /** A turn is in flight for this schedule right now. */
401
405
  running: boolean;
406
+ /** R10: count of retention-ring ids no longer live (so "keeping last N" renders truthfully). */
407
+ archivedRuns?: number;
402
408
  }
403
409
 
404
410
  export interface SchedulePatchBody {
@@ -409,6 +415,8 @@ export interface SchedulePatchBody {
409
415
  everyMinutes?: number;
410
416
  dailyAt?: string;
411
417
  enabled?: boolean;
418
+ /** R10: set retention (1–100) or null to clear it. */
419
+ keepRuns?: number | null;
412
420
  }
413
421
 
414
422
  /** Device usage rollup over the sessions it still holds (archived are closed). */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-durable",
3
- "version": "0.0.63",
3
+ "version": "0.0.65",
4
4
  "description": "Durable Pi — the durable agent network: hub web UI, device backend daemon, TUI admin and the shared SDK, packaged as one runnable monorepo install",
5
5
  "license": "MIT",
6
6
  "repository": {