my-durable 0.0.63 → 0.0.64

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.
@@ -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> {
@@ -95,6 +100,39 @@ export async function archivedEntries(
95
100
  return { entries: entries.sort((a, b) => b.closedAt - a.closedAt), skipped };
96
101
  }
97
102
 
103
+ /** R10 Design B: count refs that would dangle if `ids` were removed. Tolerant
104
+ * raw reads — the registries may not exist yet, and a corrupt file must never
105
+ * stop a gc plan (the sweep itself runs through the registries' own safe
106
+ * commit paths). */
107
+ export function danglingRefCounts(
108
+ dataDir: string,
109
+ ids: ReadonlySet<string>,
110
+ readFile: (p: string) => string = (p) => readFileSync(p, "utf8"),
111
+ ): { schedules: number; graphRuns: number } {
112
+ if (ids.size === 0) return { schedules: 0, graphRuns: 0 };
113
+ let schedules = 0;
114
+ let graphRuns = 0;
115
+ try {
116
+ const doc = JSON.parse(readFile(join(dataDir, "schedules.json"))) as {
117
+ schedules?: Array<{ lastSessionId?: string }>;
118
+ };
119
+ for (const s of doc.schedules ?? []) if (s.lastSessionId && ids.has(s.lastSessionId)) schedules += 1;
120
+ } catch {
121
+ /* absent or unreadable — nothing countable */
122
+ }
123
+ try {
124
+ const doc = JSON.parse(readFile(join(dataDir, "graphs.json"))) as {
125
+ runs?: Array<{ tasks?: Record<string, { sessionId?: string }> }>;
126
+ };
127
+ for (const run of doc.runs ?? [])
128
+ for (const task of Object.values(run.tasks ?? {}))
129
+ if (task.sessionId && ids.has(task.sessionId)) graphRuns += 1;
130
+ } catch {
131
+ /* absent or unreadable — nothing countable */
132
+ }
133
+ return { schedules, graphRuns };
134
+ }
135
+
98
136
  /** What a retention policy would delete. Pure read: nothing is touched. */
99
137
  export async function gcPlan(archiveDir: string, options: { closedBeforeDays: number; now?: number }): Promise<GcPlan> {
100
138
  const now = options.now ?? Date.now();
@@ -107,11 +145,13 @@ export async function gcPlan(archiveDir: string, options: { closedBeforeDays: nu
107
145
  const candidates = entries
108
146
  .filter((entry) => entry.closedAt <= cutoff)
109
147
  .map((entry) => ({ ...entry, ageDays: Math.floor((now - entry.closedAt) / 86_400_000) }));
148
+ const candidateIds = new Set(candidates.map((c) => c.sessionId));
110
149
  return {
111
150
  total: { count: entries.length, bytes: entries.reduce((n, e) => n + e.bytes, 0) },
112
151
  candidates,
113
152
  candidateBytes: candidates.reduce((n, e) => n + e.bytes, 0),
114
153
  skipped,
154
+ danglingRefs: danglingRefCounts(dirname(archiveDir), candidateIds),
115
155
  };
116
156
  }
117
157
 
@@ -138,6 +178,13 @@ export async function gcApply(
138
178
  return { removed, bytes: removed.reduce((n, e) => n + e.bytes, 0) };
139
179
  }
140
180
 
181
+ /** R10 Design B: the removed ids a ref-sweep should target (gcApply callers
182
+ * pass these on — to the daemon route when it answers, else the offline
183
+ * sweep). Derived from what gcApply actually removed. */
184
+ export function removedSessionIds(removed: readonly GcCandidate[]): string[] {
185
+ return removed.map((c) => c.sessionId);
186
+ }
187
+
141
188
  /**
142
189
  * "30d", "12h", "90m", "2w" → days (fractional). Days is the unit the plan
143
190
  * 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.
@@ -307,6 +307,12 @@ export function v1(
307
307
  // The device owns execution (systemd/cron are deliberately rejected by config);
308
308
  // these routes only read and edit the schedule records.
309
309
  r.get("/schedules", (_req, res) => res.json({ schedules: store.scheduleList() }));
310
+ // R10 Design B: the daemon-side dangling-ref sweep. Deliberately NOT in the
311
+ // tunnel REST allowlist (apps/dpi-sdk/src/protocol/rest-routes.ts): this is
312
+ // device-LOCAL operator maintenance (the gc CLI calls it when the device is
313
+ // up, so registry mutations happen in-process with no file race) — the same
314
+ // operator-only surface as `dpi gc` itself.
315
+ r.post("/gc/sweep-refs", route(async (req, res) => res.json(await store.gcSweepRefs((req.body ?? {}).sessionIds))));
310
316
  r.post("/schedules", route(async (req, res) => res.status(201).json(await store.createSchedule(req.body ?? {}))));
311
317
  r.patch("/schedules/:id", route(async (req, res) => res.json(await store.updateSchedule(param(req, "id"), req.body ?? {}))));
312
318
  r.delete("/schedules/:id", route(async (req, res) => res.json(await store.removeSchedule(param(req, "id")))));
@@ -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(() => {
@@ -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();
@@ -2594,9 +2619,18 @@ export class Store {
2594
2619
  // dpi-sdk is not this fix's file, so carry the recorded value through with
2595
2620
  // a narrowing cast. UIs treat the field as opaque text.
2596
2621
  const { lastOutcome, ...rest } = record;
2622
+ // R10 Design A: derived count of ring ids no longer live (archived or gone)
2623
+ // so the UI can render "keeping last N" truthfully. Bounded: ring ≤ 100.
2624
+ let archivedRuns: number | undefined;
2625
+ if (record.keepRuns !== undefined && record.recentSessionIds?.length) {
2626
+ archivedRuns = record.recentSessionIds.filter(
2627
+ (id) => !this.catalog.prepare("SELECT 1 FROM sessions WHERE id=?").get(id),
2628
+ ).length;
2629
+ }
2597
2630
  return {
2598
2631
  ...rest,
2599
2632
  ...(lastOutcome === undefined ? {} : { lastOutcome: lastOutcome as ScheduleView["lastOutcome"] }),
2633
+ ...(archivedRuns !== undefined ? { archivedRuns } : {}),
2600
2634
  nextRunAt: this.schedules.nextRunAt(record, Date.now()) ?? null,
2601
2635
  running: this.scheduleInFlight.has(record.id),
2602
2636
  };
@@ -2608,6 +2642,10 @@ export class Store {
2608
2642
  private scheduleInFlight = new Set<string>();
2609
2643
  private scheduleTimer?: ReturnType<typeof setTimeout>;
2610
2644
 
2645
+ /** R10 5.2: per-session salvage single-flight — concurrent openers of one
2646
+ * corrupt session share ONE bounded attempt instead of racing scratch files. */
2647
+ private salvageInFlight = new Map<string, Promise<import("./salvage.js").SalvageOutcome>>();
2648
+
2611
2649
  /** R8 schedule budgets (StoreOptions-overridable so tests simulate wedged
2612
2650
  * dispatches in milliseconds instead of minutes). */
2613
2651
  private get scheduleTickMs(): number {
@@ -2754,11 +2792,16 @@ export class Store {
2754
2792
  return;
2755
2793
  }
2756
2794
  if (result.status === "done") {
2757
- await deadline(
2795
+ // R10 Design A: snapshot the retention ring BEFORE markRun pushes+trims,
2796
+ // then prune whatever fell out of the window (void: never blocks the
2797
+ // guard release, no new timers — best-effort archive with retry next run).
2798
+ const ringBefore = [...(record.recentSessionIds ?? [])];
2799
+ const okRecord = await deadline(
2758
2800
  this.schedules.markRun(record.id, { sessionId, outcome: "ok" }),
2759
2801
  SCHEDULE_REGISTRY_IO_MS,
2760
2802
  "schedule registry write timed out (ok)",
2761
2803
  ).catch(() => undefined);
2804
+ if (okRecord?.keepRuns) void this.pruneScheduleSessions(okRecord, ringBefore).catch(() => undefined);
2762
2805
  void this.notifyEvent({
2763
2806
  kind: "schedule.ok",
2764
2807
  title: `Schedule ran: ${record.name}`,
@@ -2786,6 +2829,26 @@ export class Store {
2786
2829
  }
2787
2830
  }
2788
2831
 
2832
+ /** R10 Design A: archive run sessions that fell out of the schedule's
2833
+ * keepRuns window. Called (void, best-effort) only from the ok-path of a
2834
+ * successful dispatch, with the ring as it was BEFORE markRun trimmed it.
2835
+ * `ringBefore \ ringAfter` = evicted ids; each LIVE evicted session is
2836
+ * archived via the existing store.archive path (abort-open → atomic rename
2837
+ * to archive/ → catalog row deleted — nothing deleted, restorable, ages into
2838
+ * the gc plan). Archive failure leaves the session live; the id is already
2839
+ * gone from the ring, but the session stays restorable and the operator can
2840
+ * archive it manually — at most keepRuns stragglers can overstay (bounded). */
2841
+ private async pruneScheduleSessions(record: ScheduleRecord, ringBefore: string[]): Promise<void> {
2842
+ if (typeof record.keepRuns !== "number") return;
2843
+ const ringNow = new Set(record.recentSessionIds ?? []);
2844
+ const evicted = [...new Set(ringBefore)].filter((id) => !ringNow.has(id));
2845
+ for (const id of evicted) {
2846
+ const row = this.catalog.prepare("SELECT * FROM sessions WHERE id=?").get(id) as SessionRow | undefined;
2847
+ if (!row) continue; // already gone (archived/corrupt-removed) — nothing to do
2848
+ await this.archive(row);
2849
+ }
2850
+ }
2851
+
2789
2852
  // ------------------------------------------------- projects (Wave 2)
2790
2853
 
2791
2854
  /** The project a path belongs to: its longest registered root. */
@@ -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.64",
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": {