my-durable 0.0.61 → 0.0.62

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.
@@ -0,0 +1,284 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * R8 store-perf benchmark — plain node script, no test framework.
4
+ *
5
+ * Measures per-op latency (p50/p95/max in ms) of the real Store APIs against a
6
+ * throwaway sandbox home (default /tmp/r8perf), plus a paired raw-sqlite
7
+ * commit control (synchronous=FULL vs NORMAL) so any catalog pragma change is
8
+ * evidence-backed rather than assumed.
9
+ *
10
+ * Mix (flags tune the counts):
11
+ * - N session creates (Store.create → catalog INSERT + per-session sqlite open)
12
+ * - M catalog insert+commit cycles (BEGIN/INSERT/COMMIT on the real catalog,
13
+ * the exact shape idempotency.ts writes per POST)
14
+ * - A entry appends (conversation commit → tx.appendEntry → per-session DB)
15
+ * - P entry-list pages (Store.entries, first-page + full-walk pages)
16
+ * - G git-status cycles (fresh spawn each, cache bypassed via a future `now`)
17
+ *
18
+ * Run with the backend's tsx loader (same as `npm start`):
19
+ * cd apps/dpi-backend && node --import tsx scripts/bench-store.mjs
20
+ * (equivalently: npx tsx scripts/bench-store.mjs)
21
+ *
22
+ * Flags: --home /tmp/r8perf --sessions 100 --appends 2000 --pages 500
23
+ * --git 6 --catalog-commits 300 --label before
24
+ *
25
+ * The sandbox home's data dir is WIPED at start so every run (before/after a
26
+ * store change) starts from the same empty state.
27
+ */
28
+ import { BACKGROUND_CONTEXT as ctx } from "@earendil-works/chord/context";
29
+ import { DatabaseSync } from "node:sqlite";
30
+ import { execFileSync } from "node:child_process";
31
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
32
+ import { join } from "node:path";
33
+ import { loadavg } from "node:os";
34
+ import { performance } from "node:perf_hooks";
35
+ import { randomUUID } from "node:crypto";
36
+ import { fileURLToPath } from "node:url";
37
+ import { dirname } from "node:path";
38
+
39
+ const here = dirname(fileURLToPath(import.meta.url));
40
+ const { Store } = await import(join(here, "../src/store.js"));
41
+ const { gitStatus } = await import(join(here, "../src/git.js"));
42
+
43
+ // ---------------------------------------------------------------- flags
44
+ const arg = (name, fallback) => {
45
+ const i = process.argv.indexOf(`--${name}`);
46
+ return i >= 0 && process.argv[i + 1] !== undefined ? process.argv[i + 1] : fallback;
47
+ };
48
+ const HOME = String(arg("home", "/tmp/r8perf"));
49
+ const N_SESSIONS = Number(arg("sessions", 100));
50
+ const N_APPENDS = Number(arg("appends", 2000));
51
+ const N_PAGES = Number(arg("pages", 500));
52
+ const N_GIT = Number(arg("git", 6));
53
+ const N_CATALOG_COMMITS = Number(arg("catalog-commits", 300));
54
+ const LABEL = String(arg("label", "run"));
55
+
56
+ // ---------------------------------------------------------------- sandbox
57
+ const DATA_DIR = join(HOME, "backend");
58
+ const WORK = join(HOME, "work");
59
+ const REPO = join(WORK, "repo");
60
+ rmSync(DATA_DIR, { recursive: true, force: true });
61
+ rmSync(REPO, { recursive: true, force: true });
62
+ mkdirSync(join(REPO, "nested"), { recursive: true });
63
+ writeFileSync(join(REPO, "README.md"), "# r8 bench\n");
64
+ const git = (...args) => execFileSync("git", args, { cwd: REPO, stdio: "ignore" });
65
+ git("init", "-q");
66
+ git("config", "user.email", "bench@example.com");
67
+ git("config", "user.name", "r8 bench");
68
+ git("add", ".");
69
+ git("commit", "-qm", "bench seed");
70
+
71
+ // ---------------------------------------------------------------- stats
72
+ const pct = (samples, p) => {
73
+ const s = [...samples].sort((a, b) => a - b);
74
+ const idx = Math.min(s.length - 1, Math.max(0, Math.ceil((p / 100) * s.length) - 1));
75
+ return s[idx];
76
+ };
77
+ const mean = (s) => s.reduce((a, b) => a + b, 0) / s.length;
78
+ const r = (ms) => (ms >= 100 ? Math.round(ms) : Math.round(ms * 1000) / 1000);
79
+ const results = [];
80
+ const bench = (name, count, fn) => {
81
+ const samples = [];
82
+ const t0 = performance.now();
83
+ for (let i = 0; i < count; i += 1) {
84
+ const s = performance.now();
85
+ fn(i);
86
+ samples.push(performance.now() - s);
87
+ }
88
+ const total = performance.now() - t0;
89
+ const row = {
90
+ op: name,
91
+ count,
92
+ totalMs: r(total),
93
+ meanMs: r(mean(samples)),
94
+ p50: r(pct(samples, 50)),
95
+ p95: r(pct(samples, 95)),
96
+ max: r(Math.max(...samples)),
97
+ over20ms: samples.filter((x) => x > 20).length,
98
+ };
99
+ results.push(row);
100
+ return row;
101
+ };
102
+ const benchAsync = async (name, count, fn) => {
103
+ const samples = [];
104
+ const t0 = performance.now();
105
+ for (let i = 0; i < count; i += 1) {
106
+ const s = performance.now();
107
+ await fn(i);
108
+ samples.push(performance.now() - s);
109
+ }
110
+ const total = performance.now() - t0;
111
+ const row = {
112
+ op: name,
113
+ count,
114
+ totalMs: r(total),
115
+ meanMs: r(mean(samples)),
116
+ p50: r(pct(samples, 50)),
117
+ p95: r(pct(samples, 95)),
118
+ max: r(Math.max(...samples)),
119
+ over20ms: samples.filter((x) => x > 20).length,
120
+ };
121
+ results.push(row);
122
+ return row;
123
+ };
124
+
125
+ // ---------------------------------------------------------------- run
126
+ const started = performance.now();
127
+ const load0 = loadavg()[0];
128
+ console.log(`[r8-bench] home=${HOME} label=${LABEL} load1m(start)=${load0.toFixed(2)}`);
129
+
130
+ const store = await Store.open({
131
+ dataDir: DATA_DIR,
132
+ startDirs: [WORK],
133
+ name: "r8-bench",
134
+ provider: "faux",
135
+ });
136
+
137
+ // 1) Session creates: catalog insert + openAgent (fresh per-session sqlite) + gitStatus.
138
+ console.log("[r8-bench] store open — starting session.create");
139
+ const ids = [];
140
+ await benchAsync("session.create", N_SESSIONS, async (i) => {
141
+ const s = await store.create({ name: `bench-${String(i).padStart(4, "0")}`, cwd: REPO });
142
+ ids.push(s.id);
143
+ });
144
+ console.log("[r8-bench] session.create done");
145
+
146
+ // 2) Catalog insert+commit cycles — the exact write shape idempotency.ts does per POST.
147
+ // This is the pragma-sensitive path: journal WAL + synchronous=<default FULL> today.
148
+ const insert = store.catalog.prepare(
149
+ "INSERT OR REPLACE INTO requests(key,route,status,body,createdAt) VALUES(?,?,?,?,?)",
150
+ );
151
+ console.log("[r8-bench] starting catalog.insert+commit");
152
+ bench("catalog.insert+commit", N_CATALOG_COMMITS, (i) => {
153
+ store.catalog.exec("BEGIN");
154
+ try {
155
+ insert.run(`bench-${LABEL}-${i}`, "POST /v1/sessions", 201, '"bench"', Date.now());
156
+ store.catalog.exec("COMMIT");
157
+ } catch (e) {
158
+ store.catalog.exec("ROLLBACK");
159
+ throw e;
160
+ }
161
+ });
162
+
163
+ // 2b) openAgent isolation: catalog rows inserted by hand, then ONLY the harness/sqlite
164
+ // open is timed — splits session.create's cost between the catalog write and the
165
+ // per-session DB open (migrations + Harness.open).
166
+ const agentRows = [];
167
+ for (let i = 0; i < Math.min(10, N_SESSIONS); i += 1) {
168
+ const base = store.row(ids[i]);
169
+ const id = randomUUID();
170
+ const row = {
171
+ id,
172
+ name: `bench-agent-${String(i).padStart(4, "0")}`,
173
+ cwd: REPO,
174
+ dbPath: join(store.sessionsDir, id, "agent.sqlite"),
175
+ createdAt: Date.now(),
176
+ model: base.model,
177
+ provider: base.provider,
178
+ };
179
+ store.catalog
180
+ .prepare("INSERT INTO sessions(id,name,cwd,dbPath,createdAt,model,provider) VALUES(?,?,?,?,?,?,?)")
181
+ .run(row.id, row.name, row.cwd, row.dbPath, row.createdAt, row.model, row.provider);
182
+ agentRows.push(row);
183
+ }
184
+ await benchAsync("agent.open(solo)", agentRows.length, async (i) => {
185
+ await store.openAgent(agentRows[i], true);
186
+ });
187
+
188
+ // 3) Entry appends into session 0's conversation (real append API: commit → tx.appendEntry).
189
+ console.log("[r8-bench] starting entry.append");
190
+ const row0 = store.row(ids[0]);
191
+ const { c } = await store.resolveAgent(row0.id, "main");
192
+ await benchAsync("entry.append", N_APPENDS, async (i) => {
193
+ await c.commit(async (tx) => {
194
+ await tx.appendEntry(c.id, {
195
+ kind: "bench.entry",
196
+ data: { i, text: `r8 benchmark entry ${i} — realistic mixed-length payload ${"x".repeat(80 + (i % 120))}` },
197
+ });
198
+ }, ctx);
199
+ });
200
+
201
+ // 4) Entry-list pages: first page re-reads (UI poll shape) + one full walk (deep pages).
202
+ console.log("[r8-bench] starting entries pages");
203
+ await benchAsync("entries.page(first)", N_PAGES, async () => {
204
+ const page = await store.entries(c, undefined, 100);
205
+ if (!page.items.length) throw Error("expected entries");
206
+ });
207
+ await benchAsync("entries.page(full-walk)", N_PAGES, async () => {
208
+ let cursor;
209
+ let pages = 0;
210
+ let items = 0;
211
+ for (;;) {
212
+ const page = await store.entries(c, cursor, 100);
213
+ pages += 1;
214
+ items += page.items.length;
215
+ cursor = page.next;
216
+ if (!cursor) break;
217
+ if (pages > 500) throw Error("walk did not terminate");
218
+ }
219
+ if (items === 0) throw Error("expected entries");
220
+ });
221
+
222
+ // 5) Git-status cycles: fresh git spawn each time (cache bypassed via a future `now`).
223
+ console.log("[r8-bench] starting git.status");
224
+ const futureNow = () => Date.now() + 3_600_000;
225
+ bench("git.status(fresh)", N_GIT, (i) => {
226
+ writeFileSync(join(REPO, `scratch-${i}.txt`), `dirty ${i}\n`);
227
+ const st = gitStatus(REPO, futureNow());
228
+ if (!st) throw Error("no status");
229
+ });
230
+
231
+ // 6) Paired pragma control on throwaway files: identical commit loop, FULL vs NORMAL.
232
+ // Directly quantifies what the catalog's missing synchronous=NORMAL costs per commit.
233
+ console.log("[r8-bench] starting pragma control");
234
+ const pragmaControl = (path, synchronous) => {
235
+ const db = new DatabaseSync(path);
236
+ db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=${synchronous};
237
+ CREATE TABLE IF NOT EXISTS requests(key TEXT PRIMARY KEY,route TEXT NOT NULL,status INTEGER NOT NULL,body TEXT NOT NULL,createdAt INTEGER NOT NULL);`);
238
+ const ins = db.prepare("INSERT OR REPLACE INTO requests(key,route,status,body,createdAt) VALUES(?,?,?,?,?)");
239
+ const samples = [];
240
+ for (let i = 0; i < N_CATALOG_COMMITS; i += 1) {
241
+ const s = performance.now();
242
+ db.exec("BEGIN");
243
+ ins.run(`ctl-${synchronous}-${i}`, "POST /v1/sessions", 201, '"ctl"', Date.now());
244
+ db.exec("COMMIT");
245
+ samples.push(performance.now() - s);
246
+ }
247
+ db.close();
248
+ return samples;
249
+ };
250
+ const full = pragmaControl(join(HOME, "ctl-full.sqlite"), "FULL");
251
+ const normal = pragmaControl(join(HOME, "ctl-normal.sqlite"), "NORMAL");
252
+ for (const [name, samples] of [
253
+ ["control.commit(sync=FULL)", full],
254
+ ["control.commit(sync=NORMAL)", normal],
255
+ ]) {
256
+ results.push({
257
+ op: name,
258
+ count: samples.length,
259
+ totalMs: r(samples.reduce((a, b) => a + b, 0)),
260
+ meanMs: r(mean(samples)),
261
+ p50: r(pct(samples, 50)),
262
+ p95: r(pct(samples, 95)),
263
+ max: r(Math.max(...samples)),
264
+ over20ms: samples.filter((x) => x > 20).length,
265
+ });
266
+ }
267
+
268
+ await store.close().catch(() => {});
269
+
270
+ // ---------------------------------------------------------------- report
271
+ const pad = (v, n) => String(v).padStart(n);
272
+ console.log(`\n[r8-bench] label=${LABEL} totalMs=${r(performance.now() - started)} load1m(end)=${loadavg()[0].toFixed(2)}`);
273
+ console.log(
274
+ `${pad("op", 26)} ${pad("count", 7)} ${pad("totalMs", 9)} ${pad("meanMs", 9)} ${pad("p50", 9)} ${pad("p95", 9)} ${pad("max", 9)} ${pad(">20ms", 7)}`,
275
+ );
276
+ for (const row of results)
277
+ console.log(
278
+ `${pad(row.op, 26)} ${pad(row.count, 7)} ${pad(row.totalMs, 9)} ${pad(row.meanMs, 9)} ${pad(row.p50, 9)} ${pad(row.p95, 9)} ${pad(row.max, 9)} ${pad(row.over20ms, 7)}`,
279
+ );
280
+ writeFileSync(join(HOME, `bench-${LABEL}.json`), JSON.stringify({ label: LABEL, home: HOME, results }, null, 2));
281
+ console.log(`[r8-bench] json → ${join(HOME, `bench-${LABEL}.json`)}`);
282
+ // The Store's watchers (awake/git/telegram timers) keep the event loop alive after
283
+ // close(); the measurements are done — exit explicitly.
284
+ process.exit(0);
@@ -40,7 +40,7 @@ const FILE_MODE = 0o600;
40
40
  const DIR_MODE = 0o700;
41
41
 
42
42
  /** `<uuid>-<archivedAtMs>`: the only identity an old bundle has. 36 uuid chars + 13 ms digits. */
43
- const BUNDLE_DIR_PATTERN = /^([0-9a-f-]{36})-(\d{13})$/;
43
+ export const BUNDLE_DIR_PATTERN = /^([0-9a-f-]{36})-(\d{13})$/;
44
44
  /** Full lowercase uuid, 8-4-4-4-12: a PREFIX of another uuid must never match a bundle. */
45
45
  const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
46
46
 
@@ -7,11 +7,17 @@
7
7
  * explicitly. `--dry-run` is the default at the CLI, following piggery's
8
8
  * `gc --closed-before DURATION [--dry-run]` shape.
9
9
  *
10
- * An archived session directory is `<archiveDir>/<sessionId>-<closedAtMs>`, so
11
- * age and size are readable without opening any database.
10
+ * An archived session directory is `<archiveDir>/<uuid>-<closedAtMs>` — parsed
11
+ * with the SAME strict `BUNDLE_DIR_PATTERN` the archive browser and restore use
12
+ * (audit 3.1: the old loose `<name>-<10+ digits>` form let gc delete operator
13
+ * directories like `nas-backup-2025010112` that the UI never listed). Any
14
+ * directory in archive/ that does not parse strictly — or whose closedAt is out
15
+ * of range — is reported as skipped and never deleted, so age and size remain
16
+ * readable without opening any database.
12
17
  */
13
18
  import { readdir, rm, stat } from "node:fs/promises";
14
19
  import { join } from "node:path";
20
+ import { BUNDLE_DIR_PATTERN } from "./archived.js";
15
21
 
16
22
  export interface ArchivedEntry {
17
23
  /** Directory name inside archive/. */
@@ -49,16 +55,25 @@ async function dirBytes(path: string): Promise<number> {
49
55
  return total;
50
56
  }
51
57
 
52
- /** Parse `<sessionId>-<closedAtMs>`; anything else is reported as skipped, never guessed at. */
58
+ /**
59
+ * Parse `<uuid>-<closedAtMs>` with the exact strict pattern the archive browser
60
+ * and restore use (`archived.ts` BUNDLE_DIR_PATTERN); anything else is reported
61
+ * as skipped, never guessed at. A shape-match with an out-of-range value (13
62
+ * zeros → closedAt 0) is refused too: skip, don't delete.
63
+ */
53
64
  export function parseArchivedName(name: string): { sessionId: string; closedAt: number } | undefined {
54
- const match = /^(.+)-(\d{10,})$/u.exec(name);
65
+ const match = BUNDLE_DIR_PATTERN.exec(name);
55
66
  if (!match) return undefined;
56
67
  const closedAt = Number(match[2]);
57
68
  if (!Number.isFinite(closedAt) || closedAt <= 0) return undefined;
58
69
  return { sessionId: match[1], closedAt };
59
70
  }
60
71
 
61
- export async function archivedEntries(archiveDir: string): Promise<{ entries: ArchivedEntry[]; skipped: GcPlan["skipped"] }> {
72
+ export async function archivedEntries(
73
+ archiveDir: string,
74
+ /** Clock for the future-closedAt guard; defaults to wall time. */
75
+ now: number = Date.now(),
76
+ ): Promise<{ entries: ArchivedEntry[]; skipped: GcPlan["skipped"] }> {
62
77
  const entries: ArchivedEntry[] = [];
63
78
  const skipped: GcPlan["skipped"] = [];
64
79
  for (const entry of await readdir(archiveDir, { withFileTypes: true }).catch(() => [])) {
@@ -68,6 +83,12 @@ export async function archivedEntries(archiveDir: string): Promise<{ entries: Ar
68
83
  skipped.push({ name: entry.name, reason: "not an archived-session directory" });
69
84
  continue;
70
85
  }
86
+ if (parsed.closedAt > now) {
87
+ // A bundle stamped in the future (bad clock, corrupted name) is reported
88
+ // and never considered for deletion.
89
+ skipped.push({ name: entry.name, reason: "closedAt is in the future — never auto-deleted" });
90
+ continue;
91
+ }
71
92
  const path = join(archiveDir, entry.name);
72
93
  entries.push({ name: entry.name, path, ...parsed, bytes: await dirBytes(path) });
73
94
  }
@@ -81,7 +102,7 @@ export async function gcPlan(archiveDir: string, options: { closedBeforeDays: nu
81
102
  // Sub-day cutoffs are legal (R5 finding 6): the CLI advertises 90m/12h and
82
103
  // parseDuration delivers them as fractional days. Only non-positive values refuse.
83
104
  if (!Number.isFinite(days) || days <= 0) throw new Error(`closedBeforeDays must be positive, got ${String(days)}`);
84
- const { entries, skipped } = await archivedEntries(archiveDir);
105
+ const { entries, skipped } = await archivedEntries(archiveDir, now);
85
106
  const cutoff = now - days * 86_400_000;
86
107
  const candidates = entries
87
108
  .filter((entry) => entry.closedAt <= cutoff)
@@ -1,11 +1,14 @@
1
1
  // REST v1. Every route requires the device token (see auth.ts). Session refs are a UUID or a
2
2
  // unique name; agent refs are a numeric id, `main`, or a unique name.
3
3
  import { Router, type Request, type Response, type NextFunction } from "express";
4
+ import { createReadStream } from "node:fs";
5
+ import { pipeline } from "node:stream/promises";
4
6
  import type { Conversation, Harness } from "@earendil-works/pi-durable";
5
7
  import { DEVICE_DOC_KINDS, type SessionRow, type Store } from "./store.js";
6
8
  import { agentStream, deviceStream, sessionStream } from "./streams.js";
7
9
  import { idempotent } from "./idempotency.js";
8
10
  import { invalid, notFound } from "./errors.js";
11
+ import { streamSessionBundle } from "./zip.js";
9
12
  import type { DevicePairing } from "./pairing.js";
10
13
 
11
14
  type Async = (req: Request, res: Response) => Promise<unknown>;
@@ -332,7 +335,27 @@ export function v1(
332
335
  res.status(201).json(await store.restoreArchivedSession(param(req, "id"))),
333
336
  ));
334
337
  // One downloadable .zip: manifest + session record + every agent's transcript/config.
335
- r.get("/sessions/:s/export", route(async (_req, res) => res.json(await store.exportSession(L(res).row))));
338
+ // R8: the bundle streams through a temp file (deflate piped to disk, never the
339
+ // whole archive in RAM) and the route pipes that file out, unlinks it in the
340
+ // finally, and speaks plain zip bytes — Content-Disposition names the download.
341
+ // Guards (256 MiB uncompressed ceiling, zip64-less limits) run during the temp
342
+ // write, so refusals surface as the usual JSON faults before any byte is sent.
343
+ r.get(
344
+ "/sessions/:s/export",
345
+ route(async (_req, res) => {
346
+ const bundle = await streamSessionBundle(store, L(res).row);
347
+ try {
348
+ res.set({
349
+ "Content-Type": bundle.mime,
350
+ "Content-Length": String(bundle.bytes),
351
+ "Content-Disposition": `attachment; filename="${bundle.filename}"`,
352
+ });
353
+ await pipeline(createReadStream(bundle.path), res);
354
+ } finally {
355
+ await bundle.cleanup();
356
+ }
357
+ }),
358
+ );
336
359
  r.get("/sessions/:s/events", route(async (_req, res) => sessionStream(store, L(res).row, res)));
337
360
  // The zcode flagship, adapted: which files has THIS session's agent touched?
338
361
  // Powers "commit session changes" in the git panel.
@@ -4,9 +4,11 @@
4
4
  *
5
5
  * A schedule is a stored intent: "every N minutes" or "daily at HH:MM", plus the
6
6
  * cwd, model and prompt a *new* session should start with. The device owns
7
- * execution — nothing here starts a session; the device loop asks `due()` and,
8
- * after the session turn finishes, reports back with `markRun()`. The hub only
9
- * displays what this file says.
7
+ * execution — nothing here starts a session; the device loop asks `due()` and
8
+ * reports back with `markRun()`: once BEFORE the dispatch (the `started` intent
9
+ * marker, so a crash mid-run cannot silently re-fire after a restart) and once
10
+ * when the session turn settles, with the real outcome. The hub only displays
11
+ * what this file says.
10
12
  *
11
13
  * Modelled on orca's `automations/service.ts:186-211` (scheduled trigger +
12
14
  * precheck + completion watcher): a stored `nextRunAt`-style slot per record, an
@@ -47,6 +49,18 @@ export const MAX_EVERY_MINUTES = 1440;
47
49
  const DAILY_AT_PATTERN = /^([01]\d|2[0-3]):([0-5]\d)$/;
48
50
  const MINUTE_MS = 60_000;
49
51
 
52
+ /**
53
+ * Outcome of the last run. Terminal states: `ok` (the session turn finished)
54
+ * and `failed` (the dispatch or the turn errored). The intermediate states keep
55
+ * a run that has not landed *visible* instead of silent: `started` is the
56
+ * pre-dispatch intent marker (R8 2.4 — written before the session is created),
57
+ * `timeout` means the run outlived its budget and may still complete later,
58
+ * and `interrupted` is what a restart turns a pending `started` into
59
+ * (`recoverInterrupted`). Registries written before R8 only ever contain
60
+ * `ok`/`failed`; both still parse and render unchanged.
61
+ */
62
+ export type ScheduleRunOutcome = "ok" | "failed" | "started" | "timeout" | "interrupted";
63
+
50
64
  /** The model a scheduled session starts on. Same shape the session API takes. */
51
65
  export interface ScheduleModel {
52
66
  provider: string;
@@ -75,12 +89,13 @@ export interface ScheduleRecord {
75
89
  dailyAt?: string;
76
90
  /** Disabled records are never due and `nextRunAt` answers `undefined`. */
77
91
  enabled: boolean;
78
- /** When the last run *finished*, epoch ms — the base the next interval counts from. */
92
+ /** Epoch ms the next interval counts from: stamped by the pre-dispatch intent
93
+ * marker (run start) and re-stamped when the outcome lands. */
79
94
  lastRunAt?: number;
80
95
  /** Session the last run created, so the UI can link to it. */
81
96
  lastSessionId?: string;
82
97
  /** Outcome of the last run; absent means "never run". */
83
- lastOutcome?: "ok" | "failed";
98
+ lastOutcome?: ScheduleRunOutcome;
84
99
  /** Why the last run failed. Cleared by the next successful run. */
85
100
  lastError?: string;
86
101
  createdAt: number;
@@ -291,7 +306,9 @@ export function computeNextRun(record: ScheduleTiming, from: number = Date.now()
291
306
  return undefined;
292
307
  }
293
308
 
294
- const isOutcome = (value: unknown): value is "ok" | "failed" => value === "ok" || value === "failed";
309
+ const RUN_OUTCOMES: readonly ScheduleRunOutcome[] = ["ok", "failed", "started", "timeout", "interrupted"];
310
+ const isOutcome = (value: unknown): value is ScheduleRunOutcome =>
311
+ typeof value === "string" && (RUN_OUTCOMES as readonly string[]).includes(value);
295
312
  const finiteNumber = (value: unknown): number | undefined =>
296
313
  typeof value === "number" && Number.isFinite(value) ? value : undefined;
297
314
 
@@ -547,13 +564,22 @@ export class ScheduleRegistry {
547
564
  }
548
565
 
549
566
  /**
550
- * Record the outcome of one run (called by the device after the session turn).
567
+ * Record one run. Two call shapes:
568
+ *
569
+ * - BEFORE the dispatch, the intent marker `{ outcome: "started" }`: it stamps
570
+ * `lastRunAt` immediately, so a crash in the create→outcome window cannot
571
+ * re-fire the same minute after a restart (the next slot is a full interval
572
+ * out) and the restart surfaces the gap via `recoverInterrupted` (R8 2.4).
573
+ * - when the run lands, `{ sessionId, outcome }` with the terminal state.
574
+ *
551
575
  * `lastRunAt` is the base the next interval counts from, so this is also what
552
- * makes an offline catch-up land once instead of in a burst.
576
+ * makes an offline catch-up land once instead of in a burst. A non-`ok`
577
+ * outcome records `error`; `ok` (and a fresh intent) clears the previous
578
+ * failure reason.
553
579
  */
554
580
  async markRun(
555
581
  id: string,
556
- result: { sessionId?: string; outcome: "ok" | "failed"; error?: string; at?: number },
582
+ result: { sessionId?: string; outcome: ScheduleRunOutcome; error?: string; at?: number },
557
583
  ): Promise<ScheduleRecord> {
558
584
  if (!isOutcome(result?.outcome)) throw invalid(`unknown run outcome ${String(result?.outcome)}`);
559
585
  const at = result.at ?? this.now();
@@ -570,14 +596,42 @@ export class ScheduleRegistry {
570
596
  if (sessionId) next.lastSessionId = sessionId;
571
597
  else delete next.lastSessionId;
572
598
  const error = nonEmptyString(result.error);
573
- if (result.outcome === "failed" && error) next.lastError = error;
574
- else delete next.lastError; // a success clears the reason the last one failed
599
+ if (result.outcome !== "ok" && error) next.lastError = error;
600
+ else delete next.lastError; // a success (or a fresh intent) clears the reason the last one failed
575
601
  staged.set(next.id, next);
576
602
  await this.commit(staged);
577
603
  return clone(next);
578
604
  });
579
605
  }
580
606
 
607
+ /**
608
+ * Boot-time recovery (R8 2.4): a run still marked `started` never recorded its
609
+ * outcome — the daemon died between the intent marker and the write-back. Flip
610
+ * it to `interrupted` so the gap is VISIBLE (the hub shows why the last run has
611
+ * no outcome) instead of silently re-firing: `lastRunAt` was already stamped
612
+ * by the intent marker, so `due()` holds the schedule until its next full
613
+ * slot. Deliberately at-most-once with a visible gap.
614
+ */
615
+ async recoverInterrupted(): Promise<ScheduleRecord[]> {
616
+ return this.run(async () => {
617
+ const staged = new Map(this.records);
618
+ const touched: ScheduleRecord[] = [];
619
+ const at = this.now();
620
+ for (const record of staged.values()) {
621
+ if (record.lastOutcome !== "started") continue;
622
+ const next = clone(record);
623
+ next.lastOutcome = "interrupted";
624
+ next.lastError =
625
+ nonEmptyString(next.lastError) ?? "run was interrupted by a device restart before it recorded an outcome";
626
+ next.updatedAt = at;
627
+ staged.set(next.id, next);
628
+ touched.push(next);
629
+ }
630
+ if (touched.length) await this.commit(staged);
631
+ return touched.map(clone);
632
+ });
633
+ }
634
+
581
635
  private async load(): Promise<void> {
582
636
  // Same guard as `Store.open`/`ProjectRegistry.open`: the data dir holds
583
637
  // credentials-adjacent state, so it is created 0700 or tightened first.