my-durable 0.0.65 → 0.0.66

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.
@@ -160,6 +160,10 @@ export async function gcCli(args: GcArgs, io: GcIo = defaultGcIo()): Promise<num
160
160
  e instanceof Error ? e.message : String(e)
161
161
  } (re-run later — the sweep is idempotent)`,
162
162
  );
163
+ // R12 P2-3: cron/scripts gate on the exit code — a failed sweep after
164
+ // a real delete must not read as success (nothing retries it
165
+ // otherwise; a later no-delete gc pass never sweeps).
166
+ return 1;
163
167
  }
164
168
  }
165
169
  return 0;
@@ -204,8 +208,13 @@ async function sweepRefs(dataDir: string, ids: string[], io: GcIo, token?: strin
204
208
  io.print(`swept ${cleared.schedules} schedule ref(s), ${cleared.graphRuns} graph-run ref(s).`);
205
209
  return;
206
210
  }
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.
211
+ // R12 P3-6: name the two skew shapes an operator can actually hit —
212
+ // anything else is a real fault; falling through to the offline path
213
+ // would race the daemon, so surface it instead.
214
+ if (res.status === 404)
215
+ throw new Error("device predates the sweep route — upgrade it (npm i -g my-durable) and re-run dpi gc");
216
+ if (res.status === 401)
217
+ throw new Error("device refused the sweep token — stale DPI_TOKEN in the env file; refresh it and re-run dpi gc");
209
218
  throw new Error(`device answered ${res.status} to the sweep route`);
210
219
  } catch (e) {
211
220
  if (e instanceof TypeError || (e instanceof Error && /fetch|network|ECONN/i.test(e.message))) {
@@ -120,9 +120,15 @@ export function danglingRefCounts(
120
120
  let graphRuns = 0;
121
121
  try {
122
122
  const doc = JSON.parse(readFile(join(dataDir, "schedules.json"))) as {
123
- schedules?: Array<{ lastSessionId?: string }>;
123
+ schedules?: Array<{ lastSessionId?: string; recentSessionIds?: string[] }>;
124
124
  };
125
- for (const s of doc.schedules ?? []) if (s.lastSessionId && ids.has(s.lastSessionId)) schedules += 1;
125
+ // R12 P3-11: count what the sweep actually clears — the retention ring
126
+ // too (clearSessionRefs deletes ring entries alongside lastSessionId), so
127
+ // the dry-run's "would clear N" stops under-promising.
128
+ for (const s of doc.schedules ?? []) {
129
+ if (s.lastSessionId && ids.has(s.lastSessionId)) schedules += 1;
130
+ else if ((s.recentSessionIds ?? []).some((id) => ids.has(id))) schedules += 1;
131
+ }
126
132
  } catch {
127
133
  /* absent or unreadable — nothing countable */
128
134
  }
@@ -705,7 +705,9 @@ export class GraphRegistry {
705
705
  }
706
706
  return touched ? { ...run, tasks } : run;
707
707
  });
708
- await this.commit(new Map(this.graphs), runs);
708
+ // R12 P3-7: no-op sweeps skip the commit — the schedules twin guards the
709
+ // same way; a no-op must not churn graphs.json (+ its .bak) forever.
710
+ if (cleared > 0) await this.commit(new Map(this.graphs), runs);
709
711
  });
710
712
  return cleared;
711
713
  }
@@ -197,11 +197,9 @@ export async function scheduleCli(argv: readonly string[], io: ScheduleIo = defa
197
197
  io.printErr(`dpi schedule: ${ran.error}`);
198
198
  return 1;
199
199
  }
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
- );
200
+ // R12 P3-9: `running` is always true here — the guard-add runs
201
+ // synchronously before the 202 is built — so no ternary.
202
+ io.print(`run started (watch \`dpi schedule list\` for the outcome); next ${when(ran.data.nextRunAt)}`);
205
203
  return 0;
206
204
  }
207
205
  if (sub === "remove") {
@@ -385,15 +385,22 @@ function coerceRecord(raw: unknown, now: number): ScheduleRecord {
385
385
  if (isOutcome(source.lastOutcome)) record.lastOutcome = source.lastOutcome;
386
386
  const lastError = nonEmptyString(source.lastError);
387
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;
388
+ // R10 Design A: retention window — defensive parse (junk dropped, ring
389
+ // trimmed) so a hand-edited or future file cannot unbound the registry.
390
+ // R12 P3-8: out-of-range keepRuns is DROPPED, not clamped — create/patch
391
+ // reject those values at the API, so the parse path must not silently ARM
392
+ // (or sharpen) auto-archive from garbage; dropped reads as "no retention",
393
+ // the safe direction.
394
+ if (
395
+ typeof source.keepRuns === "number" &&
396
+ Number.isInteger(source.keepRuns) &&
397
+ source.keepRuns >= MIN_KEEP_RUNS &&
398
+ source.keepRuns <= MAX_KEEP_RUNS
399
+ ) {
400
+ record.keepRuns = source.keepRuns;
394
401
  if (Array.isArray(source.recentSessionIds)) {
395
402
  const ring = source.recentSessionIds.filter((id): id is string => typeof id === "string" && id.length > 0);
396
- const unique = [...new Set(ring)].slice(-keepRuns);
403
+ const unique = [...new Set(ring)].slice(-source.keepRuns);
397
404
  if (unique.length > 0) record.recentSessionIds = unique;
398
405
  }
399
406
  }
@@ -1596,10 +1596,20 @@ export class Store {
1596
1596
  // R10 5.2: single-flight per session — two routes opening one corrupt db
1597
1597
  // (UI refresh fetching git-files + agents) used to spawn two salvage
1598
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
- });
1599
+ const inFlight = this.salvageInFlight.get(row.id) ?? salvageSessionDb(row.dbPath).then(
1600
+ (outcome) => {
1601
+ this.salvageInFlight.delete(row.id);
1602
+ return outcome;
1603
+ },
1604
+ // R12 P3-10: clear on rejection too — a cached rejected promise would
1605
+ // permanently disable salvage for this session. (Unreachable today:
1606
+ // salvageSessionDb resolves on every path — but the map must not
1607
+ // depend on that staying true.)
1608
+ (error: unknown) => {
1609
+ this.salvageInFlight.delete(row.id);
1610
+ throw error;
1611
+ },
1612
+ );
1603
1613
  this.salvageInFlight.set(row.id, inFlight);
1604
1614
  const outcome = await inFlight;
1605
1615
  if (!outcome.recovered) {
@@ -2597,6 +2607,10 @@ export class Store {
2597
2607
 
2598
2608
  async removeSchedule(id: string): Promise<{ removed: boolean }> {
2599
2609
  const removed = await this.schedules.remove(id);
2610
+ // R12 P3-4: the schedule is gone — its degraded-episode markers must not
2611
+ // linger in the sets forever (random ids, never reused).
2612
+ this.scheduleRegistryDegraded.delete(id);
2613
+ this.schedulePruneDegraded.delete(id);
2600
2614
  this.notify();
2601
2615
  return { removed };
2602
2616
  }
@@ -2658,6 +2672,10 @@ export class Store {
2658
2672
  * unwritable — each is reported ONCE per degraded episode, not per tick. */
2659
2673
  private scheduleRegistryDegraded = new Set<string>();
2660
2674
 
2675
+ /** R12 P2-1: schedules whose retention prune could not archive an evicted
2676
+ * run — reported once per episode; a later successful prune ends it. */
2677
+ private schedulePruneDegraded = new Set<string>();
2678
+
2661
2679
  /** R10 5.2: per-session salvage single-flight — concurrent openers of one
2662
2680
  * corrupt session share ONE bounded attempt instead of racing scratch files. */
2663
2681
  private salvageInFlight = new Map<string, Promise<import("./salvage.js").SalvageOutcome>>();
@@ -2706,8 +2724,10 @@ export class Store {
2706
2724
  const started: string[] = [];
2707
2725
  for (const record of this.schedules.due(at)) {
2708
2726
  if (this.scheduleInFlight.has(record.id)) continue;
2709
- started.push(record.id);
2710
- await this.dispatchSchedule(record).catch(() => undefined);
2727
+ // R12 P3-5: only ids that actually DISPATCHED are reported — an
2728
+ // intent-marker skip (degraded registry) must not read as "started".
2729
+ const ran = await this.dispatchSchedule(record).catch(() => false);
2730
+ if (ran) started.push(record.id);
2711
2731
  }
2712
2732
  return started;
2713
2733
  }
@@ -2726,8 +2746,11 @@ export class Store {
2726
2746
  * BEFORE the session is created, so a crash in the create→outcome window
2727
2747
  * leaves a visible "interrupted" record after restart instead of silently
2728
2748
  * re-firing the same minute.
2749
+ *
2750
+ * R12 P3-5: returns true when the dispatch ran (attempted past the intent
2751
+ * marker), false when skipped — runDueSchedules reports only the true ones.
2729
2752
  */
2730
- private async dispatchSchedule(record: ScheduleRecord): Promise<void> {
2753
+ private async dispatchSchedule(record: ScheduleRecord): Promise<boolean> {
2731
2754
  if (this.scheduleInFlight.has(record.id)) {
2732
2755
  throw new ApiFault("busy", `Schedule "${record.name}" is already running`);
2733
2756
  }
@@ -2760,7 +2783,7 @@ export class Store {
2760
2783
  data: { scheduleId: record.id },
2761
2784
  });
2762
2785
  }
2763
- return;
2786
+ return false;
2764
2787
  }
2765
2788
  if (this.scheduleRegistryDegraded.delete(record.id)) {
2766
2789
  void this.notifyEvent({
@@ -2771,6 +2794,7 @@ export class Store {
2771
2794
  });
2772
2795
  }
2773
2796
  await this.dispatchBounded(record);
2797
+ return true;
2774
2798
  } finally {
2775
2799
  this.scheduleInFlight.delete(record.id);
2776
2800
  this.notify();
@@ -2845,7 +2869,8 @@ export class Store {
2845
2869
  SCHEDULE_REGISTRY_IO_MS,
2846
2870
  "schedule registry write timed out (ok)",
2847
2871
  ).catch(() => undefined);
2848
- if (okRecord?.keepRuns) void this.pruneScheduleSessions(okRecord, ringBefore).catch(() => undefined);
2872
+ if (okRecord?.keepRuns)
2873
+ void this.pruneScheduleSessions(okRecord, ringBefore).catch(() => this.markPruneDegraded(okRecord));
2849
2874
  void this.notifyEvent({
2850
2875
  kind: "schedule.ok",
2851
2876
  title: `Schedule ran: ${record.name}`,
@@ -2882,14 +2907,48 @@ export class Store {
2882
2907
  * the gc plan). Archive failure leaves the session live; the id is already
2883
2908
  * gone from the ring, but the session stays restorable and the operator can
2884
2909
  * archive it manually — at most keepRuns stragglers can overstay (bounded). */
2910
+ /** R12 P2-1: the once-per-episode signal for a retention prune that could
2911
+ * not archive an evicted run — shared by the prune's own failure path and
2912
+ * the void-caller's outer catch. */
2913
+ private markPruneDegraded(record: ScheduleRecord): void {
2914
+ if (this.schedulePruneDegraded.has(record.id)) return;
2915
+ this.schedulePruneDegraded.add(record.id);
2916
+ void this.notifyEvent({
2917
+ kind: "schedule.failed",
2918
+ title: `Retention paused: ${record.name}`,
2919
+ body: `an evicted run's session could not be archived (archive/ unwritable or disk full?) — it stays live; ` +
2920
+ `retention resumes when archiving works again`,
2921
+ data: { scheduleId: record.id },
2922
+ });
2923
+ }
2924
+
2885
2925
  private async pruneScheduleSessions(record: ScheduleRecord, ringBefore: string[]): Promise<void> {
2886
2926
  if (typeof record.keepRuns !== "number") return;
2887
2927
  const ringNow = new Set(record.recentSessionIds ?? []);
2888
2928
  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);
2929
+ let archived = 0;
2930
+ try {
2931
+ for (const id of evicted) {
2932
+ const row = this.catalog.prepare("SELECT * FROM sessions WHERE id=?").get(id) as SessionRow | undefined;
2933
+ if (!row) continue; // already gone (archived/corrupt-removed) — nothing to do
2934
+ await this.archive(row);
2935
+ archived += 1;
2936
+ }
2937
+ } catch {
2938
+ // R12 P2-1: a persistent archive failure (archive/ unwritable, disk full)
2939
+ // used to be swallowed silently — and since markRun already trimmed the
2940
+ // ring, every later run left one more live session behind FOREVER, the
2941
+ // exact growth this feature exists to prevent, with zero signal.
2942
+ this.markPruneDegraded(record);
2943
+ return;
2944
+ }
2945
+ if (evicted.length > 0 && this.schedulePruneDegraded.delete(record.id)) {
2946
+ void this.notifyEvent({
2947
+ kind: "schedule.ok",
2948
+ title: `Retention resumed: ${record.name}`,
2949
+ body: `archived ${archived} evicted run(s); the window is healthy again`,
2950
+ data: { scheduleId: record.id },
2951
+ });
2893
2952
  }
2894
2953
  }
2895
2954
 
@@ -237,6 +237,11 @@ const tempZipPath = (baseDir: string) => join(baseDir, `.dpi-export-${process.pi
237
237
  * own data dir (R11 1.1) → the OS temp dir. Dot-prefixed so a casual `ls`
238
238
  * of the data dir does not read as a session artifact. */
239
239
  export function exportTempDir(dataDir: string): string {
240
+ // R12 P3-12 (known coupling): the spill shares the data volume with the
241
+ // registries — a 12-256 MB export on a nearly-full disk can push registry
242
+ // writes into ENOSPC (schedules degrade gracefully: R11 2.2 skips runs and
243
+ // reports once) until the export finishes and unlinks. Self-healing by
244
+ // design; noted here so nobody "fixes" it back to tmpfs.
240
245
  return process.env.DPI_EXPORT_TMPDIR || dataDir || tmpdir();
241
246
  }
242
247