my-durable 0.0.39 → 0.0.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/apps/dpi-backend/src/doctor.ts +29 -9
  2. package/apps/dpi-backend/src/gc-cli.ts +113 -0
  3. package/apps/dpi-backend/src/gc.ts +142 -0
  4. package/apps/dpi-backend/src/notify-cli.ts +211 -0
  5. package/apps/dpi-backend/src/notify-sinks.ts +947 -0
  6. package/apps/dpi-backend/src/routes.ts +17 -0
  7. package/apps/dpi-backend/src/schedule-cli.ts +211 -0
  8. package/apps/dpi-backend/src/schedules.ts +676 -0
  9. package/apps/dpi-backend/src/store.ts +275 -7
  10. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-D6ClJqd8.css +1 -0
  11. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DMb-n4O-.js +81 -0
  12. package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
  13. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/hub.ts +2 -0
  14. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/store.ts +4 -0
  15. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +8 -0
  16. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/NotifyPanel.vue +292 -0
  17. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/SchedulesPanel.vue +289 -0
  18. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/TreeRow.vue +13 -1
  19. package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +20 -1
  20. package/apps/dpi-sdk/src/api.ts +100 -0
  21. package/apps/dpi-sdk/src/client.ts +38 -0
  22. package/apps/dpi-sdk/src/protocol/rest-routes.ts +12 -0
  23. package/bin/dpi.mjs +22 -0
  24. package/docs/host-project-checklist.md +6 -6
  25. package/package.json +1 -1
  26. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-CYZxCPDU.js +0 -81
  27. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-v7IQ7Jg5.css +0 -1
@@ -0,0 +1,676 @@
1
+ /**
2
+ * Device-side schedule registry — "Scheduled sessions (device-side)", Wave 2 of
3
+ * docs/host-project-checklist.md.
4
+ *
5
+ * A schedule is a stored intent: "every N minutes" or "daily at HH:MM", plus the
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.
10
+ *
11
+ * Modelled on orca's `automations/service.ts:186-211` (scheduled trigger +
12
+ * precheck + completion watcher): a stored `nextRunAt`-style slot per record, an
13
+ * enabled bit, and the outcome of the last run written back once the run is
14
+ * done. Two deliberate adaptations: the "next slot" is *computed* from
15
+ * `lastRunAt ?? createdAt` instead of being persisted (a device that was off for
16
+ * a week must not fire seven times on boot — see `computeNextRun`), and the
17
+ * scheduling precheck stays with the caller, because a device that cannot reach
18
+ * its model should say so on the run it records, not by silently editing the
19
+ * registry.
20
+ *
21
+ * The file handling is lifted from `projects.ts` on purpose — same atomic
22
+ * temp+rename, same `.bak` rolling backup, same "unreadable file is moved aside,
23
+ * never overwritten" rule, same 0600/0700 perms, same serialised mutation queue
24
+ * and the same typed errors. A registry must never lose records silently.
25
+ *
26
+ * Everything here is Node builtins only: `node:fs/promises`, `node:crypto`,
27
+ * `node:path`. No shell, no zod, no SDK imports beyond the shared private-dir guard.
28
+ */
29
+ import { randomBytes } from "node:crypto";
30
+ import { chmod, copyFile, readFile, rename, unlink, writeFile } from "node:fs/promises";
31
+ import { dirname, isAbsolute, resolve } from "node:path";
32
+ import { ensurePrivateDir } from "../../dpi-sdk/src/node/private-dir.js";
33
+
34
+ /** Bumped only when the on-disk shape changes; `migrate` owns the upgrade path. */
35
+ export const SCHEDULE_REGISTRY_VERSION = 1;
36
+
37
+ /** A label a human reads in a list — not a description. */
38
+ export const MAX_SCHEDULE_NAME_LENGTH = 80;
39
+ /** A prompt is a message, not a document; past this the agent gets a wall of text instead of a task. */
40
+ export const MAX_PROMPT_LENGTH = 8000;
41
+ /** Five minutes is the shortest interval a session turn reliably fits inside. */
42
+ export const MIN_EVERY_MINUTES = 5;
43
+ /** A day: longer than this and `dailyAt` is the better trigger anyway. */
44
+ export const MAX_EVERY_MINUTES = 1440;
45
+
46
+ /** `HH:MM`, 24-hour, local time. Strict two digits so the file has one spelling per time. */
47
+ const DAILY_AT_PATTERN = /^([01]\d|2[0-3]):([0-5]\d)$/;
48
+ const MINUTE_MS = 60_000;
49
+
50
+ /** The model a scheduled session starts on. Same shape the session API takes. */
51
+ export interface ScheduleModel {
52
+ provider: string;
53
+ modelId: string;
54
+ }
55
+
56
+ /**
57
+ * One schedule. `everyMinutes` / `dailyAt` are the trigger and exactly one of
58
+ * them is present; `lastRunAt` is the only thing the device writes back, and it
59
+ * is what makes "next run" mean "next run after the last one" rather than "every
60
+ * N minutes since the epoch".
61
+ */
62
+ export interface ScheduleRecord {
63
+ /** `sch_<12 hex>`; stable across renames of the schedule. */
64
+ id: string;
65
+ /** Human label, ≤ 80 characters. */
66
+ name: string;
67
+ /** Absolute directory the new session starts in. Not probed: the device may be offline from that mount. */
68
+ cwd: string;
69
+ model: ScheduleModel;
70
+ /** The message sent to the new session's root agent. */
71
+ prompt: string;
72
+ /** Interval trigger in minutes (5–1440); mutually exclusive with `dailyAt`. */
73
+ everyMinutes?: number;
74
+ /** `"HH:MM"` 24-hour local time trigger; mutually exclusive with `everyMinutes`. */
75
+ dailyAt?: string;
76
+ /** Disabled records are never due and `nextRunAt` answers `undefined`. */
77
+ enabled: boolean;
78
+ /** When the last run *finished*, epoch ms — the base the next interval counts from. */
79
+ lastRunAt?: number;
80
+ /** Session the last run created, so the UI can link to it. */
81
+ lastSessionId?: string;
82
+ /** Outcome of the last run; absent means "never run". */
83
+ lastOutcome?: "ok" | "failed";
84
+ /** Why the last run failed. Cleared by the next successful run. */
85
+ lastError?: string;
86
+ createdAt: number;
87
+ updatedAt: number;
88
+ }
89
+
90
+ /** What `create` accepts. `enabled` is optional there and defaults to `true`. */
91
+ export interface ScheduleInput {
92
+ name: string;
93
+ cwd: string;
94
+ model: ScheduleModel;
95
+ prompt: string;
96
+ everyMinutes?: number;
97
+ dailyAt?: string;
98
+ }
99
+
100
+ /** `create` also takes the initial `enabled` bit, so a schedule can be staged switched-off. */
101
+ export type ScheduleCreateInput = ScheduleInput & { enabled?: boolean };
102
+
103
+ /** What `update` accepts: everything a user owns, plus the switch. */
104
+ export type SchedulePatch = Partial<ScheduleInput> & { enabled?: boolean };
105
+
106
+ /** The fields `computeNextRun` reads. Narrowed so callers can pass a bare object in tests. */
107
+ export type ScheduleTiming = Pick<
108
+ ScheduleRecord,
109
+ "enabled" | "createdAt" | "lastRunAt" | "everyMinutes" | "dailyAt"
110
+ >;
111
+
112
+ /** The on-disk document. `version` exists so a future shape can be migrated instead of discarded. */
113
+ export interface ScheduleRegistryFile {
114
+ version: number;
115
+ schedules: ScheduleRecord[];
116
+ }
117
+
118
+ export type ScheduleRegistryErrorCode = "invalid" | "not_found";
119
+
120
+ /** Typed failure so routes can answer 400 (`invalid`) or 404 (`not_found`) without string matching. */
121
+ export class ScheduleRegistryError extends Error {
122
+ readonly code: ScheduleRegistryErrorCode;
123
+
124
+ constructor(code: ScheduleRegistryErrorCode, message: string) {
125
+ super(message);
126
+ this.name = "ScheduleRegistryError";
127
+ this.code = code;
128
+ }
129
+ }
130
+
131
+ export interface ScheduleRegistryOptions {
132
+ /** Where unreadable-file / recovery notices go. Defaults to `console.warn`. */
133
+ warn?: (message: string, error?: unknown) => void;
134
+ /** Injectable clock (epoch ms) — tests pin timestamps instead of sleeping. */
135
+ now?: () => number;
136
+ }
137
+
138
+ const invalid = (message: string) => new ScheduleRegistryError("invalid", message);
139
+ const notFound = (id: string) => new ScheduleRegistryError("not_found", `no schedule ${id}`);
140
+ const describeError = (error: unknown) => (error instanceof Error ? error.message : String(error));
141
+ const defaultWarn = (message: string, error?: unknown) =>
142
+ console.warn(`[schedules] ${message}`, error === undefined ? "" : describeError(error));
143
+
144
+ const clone = (record: ScheduleRecord): ScheduleRecord => ({ ...record, model: { ...record.model } });
145
+ const nonEmptyString = (value: unknown): string | undefined =>
146
+ typeof value === "string" && value.trim() ? value.trim() : undefined;
147
+
148
+ /** `sch_` + 12 hex: short enough to type, wide enough that collisions are not a real risk. */
149
+ export function newScheduleId(): string {
150
+ return `sch_${randomBytes(6).toString("hex")}`;
151
+ }
152
+
153
+ /**
154
+ * Absolute-ise and strip the trailing separator so `/a/b/` and `/a/b` are the
155
+ * same directory. Deliberately does **not** stat the path: the device may be
156
+ * offline from that mount right now, and a schedule that refuses to save because
157
+ * a network share is down would be useless on the morning it is needed.
158
+ */
159
+ /**
160
+ * Keep the path the human typed: the device resolves a relative cwd against its
161
+ * first start dir when the run creates the session (`Store.create`), so
162
+ * resolving it here — against the daemon's own cwd — would point at a folder
163
+ * that does not exist on the device.
164
+ */
165
+ export function normaliseCwd(cwd: string): string {
166
+ const trimmed = typeof cwd === "string" ? cwd.trim() : "";
167
+ if (!trimmed) throw invalid("cwd is required");
168
+ if (trimmed === "~" || trimmed.startsWith("~/")) return trimmed; // home is expanded by the device
169
+ return isAbsolute(trimmed) ? resolve(trimmed) : trimmed.replace(/[\\/]+$/, "");
170
+ }
171
+
172
+ /** `hour`/`minute` → the stored `"HH:MM"` spelling; also what error messages quote back. */
173
+ export function formatDailyAt(hour: number, minute: number): string {
174
+ if (!Number.isInteger(hour) || hour < 0 || hour > 23) throw invalid(`hour must be 0–23, got ${String(hour)}`);
175
+ if (!Number.isInteger(minute) || minute < 0 || minute > 59) {
176
+ throw invalid(`minute must be 0–59, got ${String(minute)}`);
177
+ }
178
+ return `${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")}`;
179
+ }
180
+
181
+ function normaliseName(value: unknown): string {
182
+ const name = nonEmptyString(value);
183
+ if (!name) throw invalid("name is required");
184
+ if (name.length > MAX_SCHEDULE_NAME_LENGTH) {
185
+ throw invalid(`name is ${name.length} characters; the limit is ${MAX_SCHEDULE_NAME_LENGTH}`);
186
+ }
187
+ return name;
188
+ }
189
+
190
+ function normalisePrompt(value: unknown): string {
191
+ if (typeof value !== "string" || !value.trim()) throw invalid("prompt is required");
192
+ if (value.length > MAX_PROMPT_LENGTH) {
193
+ throw invalid(`prompt is ${value.length} characters; the limit is ${MAX_PROMPT_LENGTH}`);
194
+ }
195
+ // Kept verbatim: the prompt is the user's words, and re-indenting it would change it.
196
+ return value;
197
+ }
198
+
199
+ function normaliseModel(value: unknown): ScheduleModel {
200
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
201
+ throw invalid("model must be { provider, modelId }");
202
+ }
203
+ const source = value as Record<string, unknown>;
204
+ const provider = nonEmptyString(source.provider);
205
+ const modelId = nonEmptyString(source.modelId);
206
+ if (!provider) throw invalid("model.provider is required");
207
+ if (!modelId) throw invalid("model.modelId is required");
208
+ return { provider, modelId };
209
+ }
210
+
211
+ function normaliseEveryMinutes(value: unknown): number {
212
+ if (typeof value !== "number" || !Number.isInteger(value)) {
213
+ throw invalid("everyMinutes must be a whole number of minutes");
214
+ }
215
+ if (value < MIN_EVERY_MINUTES || value > MAX_EVERY_MINUTES) {
216
+ throw invalid(
217
+ `everyMinutes must be between ${MIN_EVERY_MINUTES} and ${MAX_EVERY_MINUTES}, got ${value}`,
218
+ );
219
+ }
220
+ return value;
221
+ }
222
+
223
+ function normaliseDailyAt(value: unknown): string {
224
+ const dailyAt = typeof value === "string" ? value.trim() : "";
225
+ if (!DAILY_AT_PATTERN.test(dailyAt)) {
226
+ throw invalid(`dailyAt must be "HH:MM" in 24-hour local time (00:00–23:59), got "${String(value)}"`);
227
+ }
228
+ return dailyAt;
229
+ }
230
+
231
+ /**
232
+ * Exactly one trigger, never both, never neither. A blank/absent `dailyAt` counts
233
+ * as "not set" so a UI can clear the field by sending `""`.
234
+ */
235
+ export function normaliseTrigger(input: { everyMinutes?: unknown; dailyAt?: unknown }): {
236
+ everyMinutes?: number;
237
+ dailyAt?: string;
238
+ } {
239
+ const dailyRaw = typeof input.dailyAt === "string" ? input.dailyAt.trim() : input.dailyAt;
240
+ const hasEvery = input.everyMinutes !== undefined && input.everyMinutes !== null;
241
+ const hasDaily = dailyRaw !== undefined && dailyRaw !== null && dailyRaw !== "";
242
+ if (hasEvery && hasDaily) {
243
+ throw invalid("everyMinutes and dailyAt are mutually exclusive; set exactly one trigger");
244
+ }
245
+ if (!hasEvery && !hasDaily) {
246
+ throw invalid("a schedule needs one trigger: everyMinutes or dailyAt");
247
+ }
248
+ if (hasEvery) return { everyMinutes: normaliseEveryMinutes(input.everyMinutes) };
249
+ return { dailyAt: normaliseDailyAt(dailyRaw) };
250
+ }
251
+
252
+ function parseDailyAt(dailyAt: string): { hour: number; minute: number } {
253
+ const match = DAILY_AT_PATTERN.exec(dailyAt);
254
+ if (!match) throw invalid(`dailyAt must be "HH:MM", got "${dailyAt}"`);
255
+ return { hour: Number(match[1]), minute: Number(match[2]) };
256
+ }
257
+
258
+ /**
259
+ * The next local `HH:MM` strictly after `from`, on the host's own clock — no
260
+ * timezone library, because "daily at 09:00" means 09:00 where the device is.
261
+ * `setDate(+1)` handles month ends, DST shifts and the midnight wrap for free.
262
+ */
263
+ function nextDailyOccurrence(dailyAt: string, from: number): number {
264
+ const { hour, minute } = parseDailyAt(dailyAt);
265
+ const anchor = new Date(from);
266
+ const candidate = new Date(anchor.getFullYear(), anchor.getMonth(), anchor.getDate(), hour, minute, 0, 0);
267
+ if (candidate.getTime() <= from) candidate.setDate(candidate.getDate() + 1);
268
+ return candidate.getTime();
269
+ }
270
+
271
+ /**
272
+ * When this record should run next, or `undefined` when it never will (disabled,
273
+ * or a hand-edited record with no usable trigger).
274
+ *
275
+ * Interval triggers count from `lastRunAt ?? createdAt`, then roll forward by
276
+ * whole intervals until the answer is strictly after `from`. That roll-forward is
277
+ * the anti-stampede rule: a device that was off for a week reports one due run
278
+ * (see `due`), and once `markRun` stamps `lastRunAt` the following slot is in the
279
+ * future — it does not replay seven missed runs.
280
+ */
281
+ export function computeNextRun(record: ScheduleTiming, from: number = Date.now()): number | undefined {
282
+ if (!record.enabled) return undefined;
283
+ if (typeof record.everyMinutes === "number") {
284
+ const interval = record.everyMinutes * MINUTE_MS;
285
+ const base = record.lastRunAt ?? record.createdAt;
286
+ const elapsed = from - base;
287
+ const steps = elapsed < 0 ? 1 : Math.floor(elapsed / interval) + 1;
288
+ return base + steps * interval;
289
+ }
290
+ if (typeof record.dailyAt === "string") return nextDailyOccurrence(record.dailyAt, from);
291
+ return undefined;
292
+ }
293
+
294
+ const isOutcome = (value: unknown): value is "ok" | "failed" => value === "ok" || value === "failed";
295
+ const finiteNumber = (value: unknown): number | undefined =>
296
+ typeof value === "number" && Number.isFinite(value) ? value : undefined;
297
+
298
+ /** Lenient model read for the load path: a hand-edited file must not wipe the registry. */
299
+ function coerceModel(raw: unknown): ScheduleModel {
300
+ const source = (raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {}) as Record<string, unknown>;
301
+ return { provider: nonEmptyString(source.provider) ?? "", modelId: nonEmptyString(source.modelId) ?? "" };
302
+ }
303
+
304
+ /**
305
+ * Lenient trigger read for the load path: keep the first trigger that is still
306
+ * valid, drop what today's rules reject, and let a record with none stay inert
307
+ * (`computeNextRun` answers `undefined`) rather than discarding the whole file.
308
+ */
309
+ function coerceTrigger(source: Record<string, unknown>): { everyMinutes?: number; dailyAt?: string } {
310
+ const every = source.everyMinutes;
311
+ if (typeof every === "number" && Number.isInteger(every) && every >= MIN_EVERY_MINUTES && every <= MAX_EVERY_MINUTES) {
312
+ return { everyMinutes: every };
313
+ }
314
+ const daily = typeof source.dailyAt === "string" ? source.dailyAt.trim() : "";
315
+ if (DAILY_AT_PATTERN.test(daily)) return { dailyAt: daily };
316
+ return {};
317
+ }
318
+
319
+ /**
320
+ * One stored record → a record we can trust. Missing `id`/`name`/timestamps are
321
+ * repaired rather than fatal (a hand-edited file should not wipe the registry);
322
+ * a record with no `cwd` is unusable and fails the file, which is then moved
323
+ * aside instead of silently forgotten.
324
+ */
325
+ function coerceRecord(raw: unknown, now: number): ScheduleRecord {
326
+ if (!raw || typeof raw !== "object") throw invalid("schedule record is not an object");
327
+ const source = raw as Record<string, unknown>;
328
+ const cwd = nonEmptyString(source.cwd);
329
+ if (!cwd) throw invalid("schedule record has no cwd");
330
+ const record: ScheduleRecord = {
331
+ id: nonEmptyString(source.id) ?? newScheduleId(),
332
+ name: (nonEmptyString(source.name) ?? "Schedule").slice(0, MAX_SCHEDULE_NAME_LENGTH),
333
+ cwd: normaliseCwd(cwd),
334
+ model: coerceModel(source.model),
335
+ prompt: typeof source.prompt === "string" ? source.prompt.slice(0, MAX_PROMPT_LENGTH) : "",
336
+ enabled: source.enabled !== false,
337
+ createdAt: finiteNumber(source.createdAt) ?? now,
338
+ updatedAt: finiteNumber(source.updatedAt) ?? now,
339
+ };
340
+ const trigger = coerceTrigger(source);
341
+ if (trigger.everyMinutes !== undefined) record.everyMinutes = trigger.everyMinutes;
342
+ if (trigger.dailyAt !== undefined) record.dailyAt = trigger.dailyAt;
343
+ const lastRunAt = finiteNumber(source.lastRunAt);
344
+ if (lastRunAt !== undefined) record.lastRunAt = lastRunAt;
345
+ const lastSessionId = nonEmptyString(source.lastSessionId);
346
+ if (lastSessionId) record.lastSessionId = lastSessionId;
347
+ if (isOutcome(source.lastOutcome)) record.lastOutcome = source.lastOutcome;
348
+ const lastError = nonEmptyString(source.lastError);
349
+ if (lastError) record.lastError = lastError;
350
+ return record;
351
+ }
352
+
353
+ /**
354
+ * Turn whatever is on disk into v1 records. v0 is the same document without a
355
+ * `version` field (and, defensively, a bare record array); an unknown `version`
356
+ * is refused so a newer build's file is not read as garbage.
357
+ */
358
+ export function migrate(raw: unknown, options: { now?: number } = {}): ScheduleRecord[] {
359
+ const now = options.now ?? Date.now();
360
+ if (raw === null || raw === undefined) return [];
361
+ if (Array.isArray(raw)) return raw.map((entry) => coerceRecord(entry, now));
362
+ if (typeof raw !== "object") throw invalid("registry file is not a JSON object");
363
+ const file = raw as Record<string, unknown>;
364
+ const version = file.version;
365
+ if (version !== undefined && version !== null && version !== 0 && version !== SCHEDULE_REGISTRY_VERSION) {
366
+ throw invalid(`unsupported registry version ${String(version)}`);
367
+ }
368
+ const schedules = file.schedules;
369
+ if (schedules === undefined || schedules === null) return [];
370
+ if (!Array.isArray(schedules)) throw invalid("registry `schedules` is not a list");
371
+ return schedules.map((entry) => coerceRecord(entry, now));
372
+ }
373
+
374
+ type ReadResult = { ok: true; records: ScheduleRecord[] } | { ok: false; missing: boolean; error: unknown };
375
+
376
+ /** Read + migrate one file, folding ENOENT (a fresh device) apart from "unusable". */
377
+ async function readRegistryFile(filePath: string, now: number): Promise<ReadResult> {
378
+ let text: string;
379
+ try {
380
+ text = await readFile(filePath, "utf8");
381
+ } catch (error) {
382
+ const code = (error as NodeJS.ErrnoException).code;
383
+ return { ok: false, missing: code === "ENOENT", error };
384
+ }
385
+ try {
386
+ return { ok: true, records: migrate(JSON.parse(text), { now }) };
387
+ } catch (error) {
388
+ return { ok: false, missing: false, error };
389
+ }
390
+ }
391
+
392
+ /**
393
+ * The schedule registry: one JSON file, loaded once at `open`, mutated through an
394
+ * in-memory map that is only committed after the file write lands.
395
+ *
396
+ * Writes are serialised (`run`) so two concurrent `create` calls cannot
397
+ * interleave: each stages a copy of the map, persists it, then swaps it in.
398
+ */
399
+ export class ScheduleRegistry {
400
+ /** Absolute path of the main JSON file. */
401
+ readonly filePath: string;
402
+ /** The rolling backup restored by `open` when `filePath` is unusable. */
403
+ readonly backupPath: string;
404
+
405
+ private readonly warn: (message: string, error?: unknown) => void;
406
+ private readonly now: () => number;
407
+ private records = new Map<string, ScheduleRecord>();
408
+ /** False until a good file is read or written: while false we must not overwrite `.bak` with junk. */
409
+ private mainIsGood = false;
410
+ private queue: Promise<unknown> = Promise.resolve();
411
+
412
+ private constructor(filePath: string, options: ScheduleRegistryOptions) {
413
+ this.filePath = resolve(filePath);
414
+ this.backupPath = `${this.filePath}.bak`;
415
+ this.warn = options.warn ?? defaultWarn;
416
+ this.now = options.now ?? (() => Date.now());
417
+ }
418
+
419
+ /**
420
+ * Load the registry, or start from an empty one. A missing file is normal
421
+ * (fresh device). An unreadable one is moved to `<file>.corrupt-<ts>` and the
422
+ * `.bak` is tried before giving up, because the alternative — carrying on with
423
+ * an empty map over a file we could not parse — loses the user's schedules on
424
+ * the next write.
425
+ */
426
+ static async open(filePath: string, options: ScheduleRegistryOptions = {}): Promise<ScheduleRegistry> {
427
+ const registry = new ScheduleRegistry(filePath, options);
428
+ await registry.load();
429
+ return registry;
430
+ }
431
+
432
+ /** Every schedule, sorted by the name a human reads (ties broken by id, so the order is stable). */
433
+ list(): ScheduleRecord[] {
434
+ return [...this.records.values()]
435
+ .map(clone)
436
+ .sort(
437
+ (left, right) =>
438
+ left.name.localeCompare(right.name, undefined, { sensitivity: "base" }) ||
439
+ left.id.localeCompare(right.id),
440
+ );
441
+ }
442
+
443
+ /** One record by id, or undefined when it does not exist. */
444
+ get(id: string): ScheduleRecord | undefined {
445
+ const record = this.records.get(id);
446
+ return record ? clone(record) : undefined;
447
+ }
448
+
449
+ /**
450
+ * Store a new schedule. Validation throws (`ScheduleRegistryError` `invalid`)
451
+ * rather than coercing, so a UI can show the reason the user typed.
452
+ */
453
+ async create(input: ScheduleCreateInput): Promise<ScheduleRecord> {
454
+ const name = normaliseName(input?.name);
455
+ const cwd = normaliseCwd(input?.cwd);
456
+ const model = normaliseModel(input?.model);
457
+ const prompt = normalisePrompt(input?.prompt);
458
+ const trigger = normaliseTrigger({ everyMinutes: input?.everyMinutes, dailyAt: input?.dailyAt });
459
+ if (input?.enabled !== undefined && typeof input.enabled !== "boolean") {
460
+ throw invalid("enabled must be a boolean");
461
+ }
462
+ const enabled = input?.enabled ?? true;
463
+ return this.run(async () => {
464
+ const staged = new Map(this.records);
465
+ let id = newScheduleId();
466
+ while (staged.has(id)) id = newScheduleId();
467
+ const now = this.now();
468
+ const created: ScheduleRecord = { id, name, cwd, model, prompt, enabled, createdAt: now, updatedAt: now };
469
+ if (trigger.everyMinutes !== undefined) created.everyMinutes = trigger.everyMinutes;
470
+ if (trigger.dailyAt !== undefined) created.dailyAt = trigger.dailyAt;
471
+ staged.set(created.id, created);
472
+ await this.commit(staged);
473
+ return clone(created);
474
+ });
475
+ }
476
+
477
+ /**
478
+ * Patch what the user owns. A trigger switch must say what it is replacing:
479
+ * `update(id, { everyMinutes: 30 })` on a daily record is rejected as "both
480
+ * set", and `{ everyMinutes: 30, dailyAt: undefined }` is the switch. Run state
481
+ * (`lastRunAt`, `lastOutcome`, …) is not patchable — that is `markRun`'s job.
482
+ */
483
+ async update(id: string, patch: SchedulePatch): Promise<ScheduleRecord> {
484
+ if (patch?.enabled !== undefined && typeof patch.enabled !== "boolean") {
485
+ throw invalid("enabled must be a boolean");
486
+ }
487
+ return this.run(async () => {
488
+ const staged = new Map(this.records);
489
+ const existing = staged.get(id);
490
+ if (!existing) throw notFound(id);
491
+ const next = clone(existing);
492
+ if ("name" in patch) next.name = normaliseName(patch.name);
493
+ if ("cwd" in patch) next.cwd = normaliseCwd(patch.cwd as string);
494
+ if ("model" in patch) next.model = normaliseModel(patch.model);
495
+ if ("prompt" in patch) next.prompt = normalisePrompt(patch.prompt);
496
+ if ("enabled" in patch) next.enabled = patch.enabled as boolean;
497
+ if ("everyMinutes" in patch || "dailyAt" in patch) {
498
+ const trigger = normaliseTrigger({
499
+ everyMinutes: "everyMinutes" in patch ? patch.everyMinutes : existing.everyMinutes,
500
+ dailyAt: "dailyAt" in patch ? patch.dailyAt : existing.dailyAt,
501
+ });
502
+ delete next.everyMinutes;
503
+ delete next.dailyAt;
504
+ if (trigger.everyMinutes !== undefined) next.everyMinutes = trigger.everyMinutes;
505
+ if (trigger.dailyAt !== undefined) next.dailyAt = trigger.dailyAt;
506
+ }
507
+ next.updatedAt = this.now();
508
+ staged.set(next.id, next);
509
+ await this.commit(staged);
510
+ return clone(next);
511
+ });
512
+ }
513
+
514
+ /** Hard delete. False when the schedule was already gone. */
515
+ async remove(id: string): Promise<boolean> {
516
+ return this.run(async () => {
517
+ if (!this.records.has(id)) return false;
518
+ const staged = new Map(this.records);
519
+ staged.delete(id);
520
+ await this.commit(staged);
521
+ return true;
522
+ });
523
+ }
524
+
525
+ /** Next due time (epoch ms) or `undefined` when disabled. See `computeNextRun` for the roll-forward. */
526
+ nextRunAt(record: ScheduleTiming, from?: number): number | undefined {
527
+ return computeNextRun(record, from ?? this.now());
528
+ }
529
+
530
+ /**
531
+ * Records whose next run is at or before `at` — what the device loop asks for.
532
+ *
533
+ * The slot is measured from the record's own base (`lastRunAt ?? createdAt`),
534
+ * not from `at`: a device that was off for a week sees the missed slot once,
535
+ * runs it, and `markRun` pushes the next slot into the future. Using
536
+ * `nextRunAt(at)` here instead would roll the slot past `at` and the schedule
537
+ * would never fire at all.
538
+ */
539
+ due(at?: number): ScheduleRecord[] {
540
+ const now = at ?? this.now();
541
+ return this.list().filter((record) => {
542
+ if (!record.enabled) return false;
543
+ const base = record.lastRunAt ?? record.createdAt;
544
+ const next = computeNextRun(record, base);
545
+ return next !== undefined && next <= now;
546
+ });
547
+ }
548
+
549
+ /**
550
+ * Record the outcome of one run (called by the device after the session turn).
551
+ * `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.
553
+ */
554
+ async markRun(
555
+ id: string,
556
+ result: { sessionId?: string; outcome: "ok" | "failed"; error?: string; at?: number },
557
+ ): Promise<ScheduleRecord> {
558
+ if (!isOutcome(result?.outcome)) throw invalid(`unknown run outcome ${String(result?.outcome)}`);
559
+ const at = result.at ?? this.now();
560
+ if (!Number.isFinite(at)) throw invalid("at must be an epoch-millisecond timestamp");
561
+ return this.run(async () => {
562
+ const staged = new Map(this.records);
563
+ const existing = staged.get(id);
564
+ if (!existing) throw notFound(id);
565
+ const next = clone(existing);
566
+ next.lastRunAt = at;
567
+ next.lastOutcome = result.outcome;
568
+ next.updatedAt = this.now();
569
+ const sessionId = nonEmptyString(result.sessionId);
570
+ if (sessionId) next.lastSessionId = sessionId;
571
+ else delete next.lastSessionId;
572
+ 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
575
+ staged.set(next.id, next);
576
+ await this.commit(staged);
577
+ return clone(next);
578
+ });
579
+ }
580
+
581
+ private async load(): Promise<void> {
582
+ // Same guard as `Store.open`/`ProjectRegistry.open`: the data dir holds
583
+ // credentials-adjacent state, so it is created 0700 or tightened first.
584
+ ensurePrivateDir(dirname(this.filePath));
585
+ const now = this.now();
586
+
587
+ const main = await readRegistryFile(this.filePath, now);
588
+ if (main.ok) {
589
+ this.adopt(main.records);
590
+ this.mainIsGood = true;
591
+ return;
592
+ }
593
+ if (main.missing) return; // fresh device: nothing to load, nothing to complain about
594
+
595
+ this.warn(`${this.filePath} is unusable (${describeError(main.error)}); moving it aside`);
596
+ await this.setAside();
597
+
598
+ const backup = await readRegistryFile(this.backupPath, now);
599
+ if (backup.ok) {
600
+ this.adopt(backup.records);
601
+ this.warn(`recovered ${backup.records.length} schedule(s) from ${this.backupPath}`);
602
+ return;
603
+ }
604
+ if (!backup.missing) this.warn(`${this.backupPath} is unusable too; starting with an empty registry`);
605
+ }
606
+
607
+ /** Rename an unreadable file out of the way instead of deleting it: it is the only copy of that data. */
608
+ private async setAside(): Promise<void> {
609
+ const aside = `${this.filePath}.corrupt-${Date.now()}`;
610
+ try {
611
+ await rename(this.filePath, aside);
612
+ this.warn(`kept the unreadable registry as ${aside}`);
613
+ } catch (error) {
614
+ this.warn(`could not move ${this.filePath} aside; nothing was written over it`, error);
615
+ }
616
+ }
617
+
618
+ private adopt(records: readonly ScheduleRecord[]): void {
619
+ this.records.clear();
620
+ for (const record of records) this.records.set(record.id, record);
621
+ }
622
+
623
+ /** Stage → persist → swap. A failed write leaves memory exactly as it was. */
624
+ private async commit(staged: Map<string, ScheduleRecord>): Promise<void> {
625
+ await this.persist([...staged.values()]);
626
+ this.records = staged;
627
+ }
628
+
629
+ private run<T>(task: () => Promise<T>): Promise<T> {
630
+ const started = this.queue.then(task, task);
631
+ // Swallow the rejection on the chain only; the caller still sees it.
632
+ this.queue = started.then(
633
+ () => undefined,
634
+ () => undefined,
635
+ );
636
+ return started;
637
+ }
638
+
639
+ /**
640
+ * temp (0600) → rename → chmod, with the previous good file copied to `.bak`
641
+ * first. Rename is atomic within a directory, so a reader sees either the old
642
+ * bytes or the complete new ones — never a torn registry.
643
+ */
644
+ private async persist(records: readonly ScheduleRecord[]): Promise<void> {
645
+ const dir = dirname(this.filePath);
646
+ ensurePrivateDir(dir); // re-tightened on every write, like the pairing files
647
+ if (this.mainIsGood) await this.backUpMain();
648
+
649
+ const payload = `${JSON.stringify(
650
+ { version: SCHEDULE_REGISTRY_VERSION, schedules: [...records] } satisfies ScheduleRegistryFile,
651
+ null,
652
+ 2,
653
+ )}\n`;
654
+ const temp = `${this.filePath}.tmp-${process.pid}-${randomBytes(4).toString("hex")}`;
655
+ try {
656
+ await writeFile(temp, payload, { encoding: "utf8", mode: 0o600 });
657
+ await chmod(temp, 0o600); // umask can only make this stricter, but be explicit
658
+ await rename(temp, this.filePath);
659
+ await chmod(this.filePath, 0o600);
660
+ this.mainIsGood = true;
661
+ } catch (error) {
662
+ await unlink(temp).catch(() => undefined);
663
+ throw error;
664
+ }
665
+ }
666
+
667
+ /** Best effort: a failed backup must not fail the mutation that good file still protects. */
668
+ private async backUpMain(): Promise<void> {
669
+ try {
670
+ await copyFile(this.filePath, this.backupPath);
671
+ await chmod(this.backupPath, 0o600);
672
+ } catch (error) {
673
+ this.warn(`could not refresh ${this.backupPath}`, error);
674
+ }
675
+ }
676
+ }