my-durable 0.0.43 → 0.0.45

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,960 @@
1
+ /**
2
+ * Device-side task-graph registry — "Task-graph orchestration", the last Wave 3
3
+ * SHOULD of docs/host-project-checklist.md (modelled on paseo's
4
+ * `packages/server/src/server/tasks/task-graph.ts` + `execution-order`).
5
+ *
6
+ * A graph is a named DAG of prompt-tasks. Each task, once EVERY dependency
7
+ * reached ok, runs as a fresh session on the device — the schedules-proven "a
8
+ * run = a fresh session" rule. This module owns records, validation, pure
9
+ * planning (`topoOrder`/`readyTasks`/`cascadeSkips`/`runComplete`) and run-state
10
+ * bookkeeping (`beginRun`/`markTask`/`recoverInterrupted`). It deliberately does
11
+ * NOT execute anything: the store drives a run through these methods, one
12
+ * session per task, because a task that reuses a session would inherit the
13
+ * previous task's context and the DAG would no longer be a DAG of independent
14
+ * steps.
15
+ *
16
+ * The file handling is lifted from `schedules.ts`/`projects.ts` on purpose —
17
+ * same atomic temp+rename, same `.bak` rolling backup, same "unreadable file is
18
+ * moved aside, never overwritten" rule, same 0600/0700 perms, same serialised
19
+ * mutation queue and the same typed errors (`invalid` → 400, `not_found` → 404).
20
+ * A registry must never lose records silently.
21
+ *
22
+ * Everything here is Node builtins only: `node:fs/promises`, `node:crypto`,
23
+ * `node:path`. No shell, no zod, no SDK imports beyond the shared private-dir guard.
24
+ */
25
+ import { randomBytes } from "node:crypto";
26
+ import { chmod, copyFile, readFile, rename, unlink, writeFile } from "node:fs/promises";
27
+ import { dirname, isAbsolute, resolve } from "node:path";
28
+ import { ensurePrivateDir } from "../../dpi-sdk/src/node/private-dir.js";
29
+
30
+ /** Bumped only when the on-disk shape changes; `migrate` owns the upgrade path. */
31
+ export const GRAPH_REGISTRY_VERSION = 1;
32
+
33
+ /** A label a human reads in a list — not a description. */
34
+ export const MAX_GRAPH_NAME_LENGTH = 80;
35
+ /** Task display names share the graph-name budget: a chip, not a paragraph. */
36
+ export const MAX_TASK_NAME_LENGTH = 80;
37
+ /** A prompt is a message, not a document; graphs get more headroom than schedules (20k vs 8k). */
38
+ export const MAX_TASK_PROMPT_LENGTH = 20_000;
39
+ /** A DAG a human can still reason about on one screen. */
40
+ export const MAX_TASKS = 32;
41
+ /** Run history per graph: enough to debug a week of runs, small enough to keep the file quick. */
42
+ export const MAX_RUNS_PER_GRAPH = 20;
43
+ /** Run summaries are read by humans in a list; the full trace lives in the session. */
44
+ export const MAX_TASK_ERROR_LENGTH = 300;
45
+
46
+ /** Lowercase slug: stable enough to type, reference in dependsOn and read in logs. */
47
+ const TASK_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;
48
+
49
+ /** One node of the DAG. Runs as a fresh session once every dependency reached ok. */
50
+ export interface GraphTask {
51
+ /** Stable id inside the graph: lowercase slug, unique, ≤32 chars. */
52
+ id: string;
53
+ /** Display name, ≤80 chars. */
54
+ name: string;
55
+ /** What the session is asked; non-empty, ≤20_000 chars. Kept verbatim. */
56
+ prompt: string;
57
+ /** Task ids this task waits on; `[]` = root task. */
58
+ dependsOn: string[];
59
+ /** Optional model override; project/apply rules belong to the store, not here. */
60
+ model?: { provider: string; modelId: string };
61
+ }
62
+
63
+ /** A named DAG plus the human-typed cwd its sessions start in. */
64
+ export interface GraphRecord {
65
+ /** `grp_<10 hex>`; stable across edits of the graph. */
66
+ id: string;
67
+ /** Human label, ≤80 characters. */
68
+ name: string;
69
+ /** Human-typed path (the store resolves it like schedules' `normaliseCwd`). */
70
+ cwd: string;
71
+ tasks: GraphTask[];
72
+ createdAt: string;
73
+ updatedAt: string;
74
+ archivedAt: string | null;
75
+ }
76
+
77
+ export type TaskRunStatus = "pending" | "running" | "ok" | "failed" | "skipped";
78
+
79
+ /** What `markTask` accepts: present keys only, like every patch in this codebase. */
80
+ export interface TaskRunPatch {
81
+ status?: TaskRunStatus;
82
+ sessionId?: string;
83
+ error?: string;
84
+ }
85
+
86
+ /** The state of one task inside one run. Every task has an entry from run start. */
87
+ export interface TaskRunState {
88
+ status: TaskRunStatus;
89
+ /** The session this task ran as (a run = a fresh session per task). */
90
+ sessionId?: string;
91
+ /** ≤300 chars, truncated by this module — the session holds the full trace. */
92
+ error?: string;
93
+ startedAt?: string;
94
+ endedAt?: string;
95
+ }
96
+
97
+ export type GraphRunStatus = "running" | "ok" | "failed" | "interrupted";
98
+
99
+ /** One execution of a whole graph. */
100
+ export interface GraphRunRecord {
101
+ /** `run_<startedAt-ms>_<4hex>` — sortable, unique per graph. */
102
+ id: string;
103
+ graphId: string;
104
+ startedAt: string;
105
+ finishedAt: string | null;
106
+ /** "running" while work remains; "ok" | "failed" | "interrupted" once terminal. */
107
+ status: GraphRunStatus;
108
+ /** Keyed by task id; every task has an entry from run start. */
109
+ tasks: Record<string, TaskRunState>;
110
+ }
111
+
112
+ /** What `create` accepts. */
113
+ export interface GraphInput {
114
+ name: string;
115
+ cwd: string;
116
+ tasks: GraphTask[];
117
+ }
118
+
119
+ /** What `update` accepts: name/cwd/tasks replace-whole when present; absent keys untouched. */
120
+ export type GraphPatch = Partial<GraphInput>;
121
+
122
+ /** The on-disk document. `version` exists so a future shape can be migrated instead of discarded. */
123
+ export interface GraphRegistryFile {
124
+ version: 1;
125
+ graphs: GraphRecord[];
126
+ runs: GraphRunRecord[];
127
+ }
128
+
129
+ export type GraphErrorCode = "invalid" | "not_found";
130
+
131
+ /** Typed failure so routes can answer 400 (`invalid`) or 404 (`not_found`) without string matching. */
132
+ export class GraphError extends Error {
133
+ readonly code: GraphErrorCode;
134
+
135
+ constructor(code: GraphErrorCode, message: string) {
136
+ super(message);
137
+ this.name = "GraphError";
138
+ this.code = code;
139
+ }
140
+ }
141
+
142
+ export interface GraphRegistryOptions {
143
+ /** Where unreadable-file / recovery notices go. Defaults to `console.warn`. */
144
+ warn?: (message: string, error?: unknown) => void;
145
+ /** Injectable clock (ISO string) — tests pin timestamps instead of sleeping. */
146
+ now?: () => string;
147
+ }
148
+
149
+ const invalid = (message: string) => new GraphError("invalid", message);
150
+ const notFound = (id: string) => new GraphError("not_found", `no graph ${id}`);
151
+ const describeError = (error: unknown) => (error instanceof Error ? error.message : String(error));
152
+ const defaultWarn = (message: string, error?: unknown) =>
153
+ console.warn(`[graphs] ${message}`, error === undefined ? "" : describeError(error));
154
+
155
+ const nonEmptyString = (value: unknown): string | undefined =>
156
+ typeof value === "string" && value.trim() ? value.trim() : undefined;
157
+
158
+ const cloneTask = (task: GraphTask): GraphTask => ({
159
+ ...task,
160
+ dependsOn: [...task.dependsOn],
161
+ ...(task.model ? { model: { ...task.model } } : {}),
162
+ });
163
+
164
+ /** Records are handed out as deep copies: `tasks`/`model` are nested and must not alias the cache. */
165
+ const cloneGraph = (record: GraphRecord): GraphRecord => ({
166
+ ...record,
167
+ tasks: record.tasks.map(cloneTask),
168
+ });
169
+
170
+ /** Runs are handed out as deep copies too (`tasks` is a nested record). */
171
+ const cloneRun = (run: GraphRunRecord): GraphRunRecord => ({
172
+ ...run,
173
+ tasks: Object.fromEntries(Object.entries(run.tasks).map(([id, state]) => [id, { ...state }])),
174
+ });
175
+
176
+ /** `grp_` + 10 hex: short enough to type as a prefix, wide enough that collisions are not a real risk. */
177
+ export function newGraphId(): string {
178
+ return `grp_${randomBytes(5).toString("hex")}`;
179
+ }
180
+
181
+ /** `run_<startedAt-ms>_<4hex>` — the ms prefix makes the list sortable, the hex breaks same-ms ties. */
182
+ export function newRunId(startedAtMs: number): string {
183
+ return `run_${startedAtMs}_${randomBytes(2).toString("hex")}`;
184
+ }
185
+
186
+ /**
187
+ * Keep the path the human typed: the device resolves a relative cwd against its
188
+ * start dirs when the run creates the session (`Store.create`), so resolving it
189
+ * here — against the daemon's own cwd — would point at a folder that does not
190
+ * exist on the device. Same rule as schedules' `normaliseCwd` (this copy throws
191
+ * `GraphError`, not `ScheduleRegistryError`).
192
+ */
193
+ export function normaliseGraphCwd(cwd: string): string {
194
+ const trimmed = typeof cwd === "string" ? cwd.trim() : "";
195
+ if (!trimmed) throw invalid("cwd is required");
196
+ if (trimmed === "~" || trimmed.startsWith("~/")) return trimmed; // home is expanded by the device
197
+ return isAbsolute(trimmed) ? resolve(trimmed) : trimmed.replace(/[\\/]+$/, "");
198
+ }
199
+
200
+ function normaliseName(value: unknown): string {
201
+ const name = nonEmptyString(value);
202
+ if (!name) throw invalid("name is required");
203
+ if (name.length > MAX_GRAPH_NAME_LENGTH) {
204
+ throw invalid(`name is ${name.length} characters; the limit is ${MAX_GRAPH_NAME_LENGTH}`);
205
+ }
206
+ return name;
207
+ }
208
+
209
+ function normaliseTaskName(id: string, value: unknown): string {
210
+ const name = nonEmptyString(value);
211
+ if (!name) throw invalid(`task "${id}" needs a name`);
212
+ if (name.length > MAX_TASK_NAME_LENGTH) {
213
+ throw invalid(`task "${id}" name is ${name.length} characters; the limit is ${MAX_TASK_NAME_LENGTH}`);
214
+ }
215
+ return name;
216
+ }
217
+
218
+ function normaliseTaskPrompt(id: string, value: unknown): string {
219
+ if (typeof value !== "string" || !value.trim()) throw invalid(`task "${id}" needs a prompt`);
220
+ if (value.length > MAX_TASK_PROMPT_LENGTH) {
221
+ throw invalid(`task "${id}" prompt is ${value.length} characters; the limit is ${MAX_TASK_PROMPT_LENGTH}`);
222
+ }
223
+ // Kept verbatim: the prompt is the user's words, and re-indenting it would change it.
224
+ return value;
225
+ }
226
+
227
+ function normaliseTaskModel(id: string, value: unknown): { provider: string; modelId: string } | undefined {
228
+ if (value === undefined || value === null) return undefined;
229
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
230
+ throw invalid(`task "${id}" model must be { provider, modelId }`);
231
+ }
232
+ const source = value as Record<string, unknown>;
233
+ const provider = nonEmptyString(source.provider);
234
+ const modelId = nonEmptyString(source.modelId);
235
+ if (!provider) throw invalid(`task "${id}" model.provider is required`);
236
+ if (!modelId) throw invalid(`task "${id}" model.modelId is required`);
237
+ return { provider, modelId };
238
+ }
239
+
240
+ // ---------------------------------------------------------------- cycle + order
241
+
242
+ /**
243
+ * Build the cycle error, naming the tasks stuck in the ring. `stuck` is what
244
+ * Kahn could not emit: every task in it has at least one dependency that is
245
+ * also stuck, so walking dependencies inside the set must revisit a node — that
246
+ * walk IS the ring, and the closing edge is the "… depends on …" the message quotes.
247
+ */
248
+ function cycleError(tasks: readonly GraphTask[], stuck: ReadonlySet<string>): GraphError {
249
+ const byId = new Map(tasks.map((task) => [task.id, task]));
250
+ const start = [...stuck].sort()[0] ?? "";
251
+ const path: string[] = [];
252
+ const firstSeen = new Map<string, number>();
253
+ let current = start;
254
+ while (current !== undefined && !firstSeen.has(current)) {
255
+ firstSeen.set(current, path.length);
256
+ path.push(current);
257
+ current = (byId.get(current)?.dependsOn ?? []).filter((dep) => stuck.has(dep)).sort()[0];
258
+ }
259
+ if (current === undefined || path.length < 2) {
260
+ // Unreachable while `dependsOn ⊆ ids` holds (validated first); kept honest anyway.
261
+ return invalid(`the graph has a cycle (${[...stuck].sort().join(", ")})`);
262
+ }
263
+ const ring = path.slice(firstSeen.get(current)!);
264
+ const closed = [...ring, ring[0]].join(" → ");
265
+ return invalid(`task "${path[path.length - 1]}" depends on "${current}": the graph has a cycle (${closed})`);
266
+ }
267
+
268
+ /**
269
+ * A topological order of the task ids — what the store runs in. Deterministic:
270
+ * among the tasks whose dependencies are all placed, the smallest id goes next,
271
+ * so two runs of the same graph execute in the same order.
272
+ *
273
+ * Pure: no fs, no clock. Throws `GraphError` (`invalid`) on an unknown
274
+ * dependency or a cycle.
275
+ */
276
+ export function topoOrder(tasks: readonly GraphTask[]): string[] {
277
+ if (!Array.isArray(tasks)) throw invalid("tasks must be a list");
278
+ const byId = new Map(tasks.map((task) => [task.id, task]));
279
+ for (const task of tasks) {
280
+ for (const dep of task.dependsOn) {
281
+ if (!byId.has(dep)) throw invalid(`task "${task.id}" depends on unknown task "${dep}"`);
282
+ }
283
+ }
284
+ const remaining = new Set(byId.keys());
285
+ const order: string[] = [];
286
+ while (remaining.size) {
287
+ const next = [...remaining]
288
+ .filter((id) => (byId.get(id)?.dependsOn ?? []).every((dep: string) => !remaining.has(dep)))
289
+ .sort()[0];
290
+ if (next === undefined) throw cycleError(tasks, remaining);
291
+ order.push(next);
292
+ remaining.delete(next);
293
+ }
294
+ return order;
295
+ }
296
+
297
+ /**
298
+ * Strict task-list validation for `create`/`update` (1–32 tasks, slug ids,
299
+ * unique, deps ⊆ ids, no self-reference, no duplicate dep, acyclic). Throws
300
+ * rather than coercing, so the human who typed a broken graph is told about it.
301
+ */
302
+ export function normaliseTasks(tasks: readonly GraphTask[]): GraphTask[] {
303
+ if (!Array.isArray(tasks)) throw invalid("tasks must be a list");
304
+ if (tasks.length < 1 || tasks.length > MAX_TASKS) {
305
+ throw invalid(`a graph needs 1–${MAX_TASKS} tasks, got ${tasks.length}`);
306
+ }
307
+ const out: GraphTask[] = [];
308
+ const ids = new Set<string>();
309
+ for (const raw of tasks) {
310
+ if (!raw || typeof raw !== "object") throw invalid("each task must be an object");
311
+ const source = raw as Record<string, unknown>;
312
+ const id = typeof source.id === "string" ? source.id.trim() : "";
313
+ if (!TASK_ID_PATTERN.test(id)) {
314
+ throw invalid(
315
+ `task id "${String(source.id)}" must be a lowercase slug: a-z, 0-9 and "-", at most 32 characters, starting with a letter or digit`,
316
+ );
317
+ }
318
+ if (ids.has(id)) throw invalid(`task id "${id}" is used twice`);
319
+ ids.add(id);
320
+ if (source.dependsOn !== undefined && source.dependsOn !== null && !Array.isArray(source.dependsOn)) {
321
+ throw invalid(`task "${id}" dependsOn must be a list of task ids`);
322
+ }
323
+ const dependsOn = (Array.isArray(source.dependsOn) ? source.dependsOn : []) as unknown[];
324
+ const deps: string[] = [];
325
+ for (const dep of dependsOn) {
326
+ if (typeof dep !== "string") throw invalid(`task "${id}" dependsOn must be a list of task ids`);
327
+ const name = dep.trim();
328
+ if (!name) continue; // a trailing comma is not an error worth a 400
329
+ if (name === id) throw invalid(`task "${id}" cannot depend on itself`);
330
+ if (deps.includes(name)) throw invalid(`task "${id}" lists dependency "${name}" twice`);
331
+ deps.push(name);
332
+ }
333
+ const model = normaliseTaskModel(id, source.model);
334
+ out.push({
335
+ id,
336
+ name: normaliseTaskName(id, source.name),
337
+ prompt: normaliseTaskPrompt(id, source.prompt),
338
+ dependsOn: deps,
339
+ ...(model ? { model } : {}),
340
+ });
341
+ }
342
+ for (const task of out) {
343
+ for (const dep of task.dependsOn) {
344
+ if (!ids.has(dep)) throw invalid(`task "${task.id}" depends on unknown task "${dep}"`);
345
+ }
346
+ }
347
+ topoOrder(out); // throws invalid("… depends on …: the graph has a cycle") naming the ring
348
+ return out;
349
+ }
350
+
351
+ // ---------------------------------------------------------------- pure planning
352
+
353
+ /**
354
+ * Which pending tasks have every dependency ok right now — the store's pick
355
+ * list. Order follows the task list, so it is stable per graph shape.
356
+ */
357
+ export function readyTasks(tasks: readonly GraphTask[], runs: Record<string, TaskRunState>): string[] {
358
+ return tasks
359
+ .filter(
360
+ (task) =>
361
+ runs[task.id]?.status === "pending" && task.dependsOn.every((dep) => runs[dep]?.status === "ok"),
362
+ )
363
+ .map((task) => task.id);
364
+ }
365
+
366
+ /**
367
+ * Cascade: mark every pending task whose dependencies can never all be ok as
368
+ * skipped, recursively. A dep in {failed, skipped} can never become ok; a dep in
369
+ * {pending, running} still can, so its dependents are neither ready nor skipped.
370
+ *
371
+ * Mutates `runs` in place (it is the live run record) and returns the
372
+ * newly-skipped ids in topological order, so the caller logs them causally.
373
+ */
374
+ export function cascadeSkips(tasks: readonly GraphTask[], runs: Record<string, TaskRunState>): string[] {
375
+ const skipped: string[] = [];
376
+ const byId = new Map(tasks.map((task) => [task.id, task]));
377
+ for (const id of topoOrder(tasks)) {
378
+ const state = runs[id];
379
+ if (!state || state.status !== "pending") continue;
380
+ const doomed = (byId.get(id)?.dependsOn ?? []).some((dep) => {
381
+ const depState = runs[dep];
382
+ return depState?.status === "failed" || depState?.status === "skipped";
383
+ });
384
+ if (doomed) {
385
+ state.status = "skipped";
386
+ skipped.push(id);
387
+ }
388
+ }
389
+ return skipped;
390
+ }
391
+
392
+ /** Terminal when no task is pending or running. An empty record is vacuously complete. */
393
+ export function runComplete(runs: Record<string, TaskRunState>): boolean {
394
+ return Object.values(runs).every(
395
+ (state) => state.status === "ok" || state.status === "failed" || state.status === "skipped",
396
+ );
397
+ }
398
+
399
+ /** "ok" only when every task reached ok; any failed OR skipped task is a failed outcome for the run. */
400
+ function runOutcome(runs: Record<string, TaskRunState>): "ok" | "failed" {
401
+ return Object.values(runs).every((state) => state.status === "ok") ? "ok" : "failed";
402
+ }
403
+
404
+ // ------------------------------------------------------------------ load path
405
+
406
+ const isTaskRunStatus = (value: unknown): value is TaskRunStatus =>
407
+ value === "pending" || value === "running" || value === "ok" || value === "failed" || value === "skipped";
408
+ const isRunStatus = (value: unknown): value is GraphRunStatus =>
409
+ value === "running" || value === "ok" || value === "failed" || value === "interrupted";
410
+
411
+ /**
412
+ * Lenient task read for the load path: drop tasks whose ids are unusable, keep
413
+ * the rest with repaired names/prompts, filter deps to known ids (no self, no
414
+ * duplicates). A hand-edited file must not wipe the registry — but a graph that
415
+ * became CYCLIC by hand cannot be run at all, so it fails the file, which is
416
+ * then moved aside (with `.bak` tried) instead of silently forgotten.
417
+ */
418
+ function coerceTasks(raw: unknown): GraphTask[] {
419
+ if (!Array.isArray(raw)) return [];
420
+ const tasks: GraphTask[] = [];
421
+ const ids = new Set<string>();
422
+ for (const entry of raw) {
423
+ if (!entry || typeof entry !== "object") continue;
424
+ const source = entry as Record<string, unknown>;
425
+ const id = typeof source.id === "string" ? source.id.trim() : "";
426
+ if (!TASK_ID_PATTERN.test(id) || ids.has(id)) continue;
427
+ ids.add(id);
428
+ const model =
429
+ source.model && typeof source.model === "object" && !Array.isArray(source.model)
430
+ ? (source.model as { provider?: unknown; modelId?: unknown })
431
+ : undefined;
432
+ const provider = nonEmptyString(model?.provider);
433
+ const modelId = nonEmptyString(model?.modelId);
434
+ tasks.push({
435
+ id,
436
+ name: (nonEmptyString(source.name) ?? id).slice(0, MAX_TASK_NAME_LENGTH),
437
+ prompt:
438
+ typeof source.prompt === "string" && source.prompt.trim()
439
+ ? source.prompt.slice(0, MAX_TASK_PROMPT_LENGTH)
440
+ : `Run task ${id}.`,
441
+ dependsOn: [],
442
+ ...(provider && modelId ? { model: { provider, modelId } } : {}),
443
+ });
444
+ }
445
+ for (const task of tasks) {
446
+ const source = (raw as Record<string, unknown>[]).find((entry) => entry && entry.id === task.id) ?? {};
447
+ const deps = Array.isArray(source.dependsOn) ? source.dependsOn : [];
448
+ for (const dep of deps) {
449
+ if (typeof dep !== "string") continue;
450
+ const name = dep.trim();
451
+ if (!name || name === task.id || !ids.has(name) || task.dependsOn.includes(name)) continue;
452
+ task.dependsOn.push(name);
453
+ }
454
+ }
455
+ if (tasks.length) topoOrder(tasks); // a cyclic hand-edit fails the file, not the whole registry silently
456
+ return tasks;
457
+ }
458
+
459
+ /**
460
+ * One stored graph → a record we can trust. Missing `id`/timestamps are repaired
461
+ * rather than fatal; a record with no `cwd` is unusable and fails the file,
462
+ * which is then moved aside instead of silently forgotten.
463
+ */
464
+ function coerceRecord(raw: unknown, now: string): GraphRecord {
465
+ if (!raw || typeof raw !== "object") throw invalid("graph record is not an object");
466
+ const source = raw as Record<string, unknown>;
467
+ const cwd = nonEmptyString(source.cwd);
468
+ if (!cwd) throw invalid("graph record has no cwd");
469
+ return {
470
+ id: nonEmptyString(source.id) ?? newGraphId(),
471
+ name: (nonEmptyString(source.name) ?? "Graph").slice(0, MAX_GRAPH_NAME_LENGTH),
472
+ cwd: normaliseGraphCwd(cwd),
473
+ tasks: coerceTasks(source.tasks),
474
+ createdAt: nonEmptyString(source.createdAt) ?? now,
475
+ updatedAt: nonEmptyString(source.updatedAt) ?? now,
476
+ archivedAt: nonEmptyString(source.archivedAt) ?? null,
477
+ };
478
+ }
479
+
480
+ function coerceTaskState(raw: unknown): TaskRunState {
481
+ const source = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
482
+ const state: TaskRunState = { status: isTaskRunStatus(source.status) ? source.status : "pending" };
483
+ const sessionId = nonEmptyString(source.sessionId);
484
+ if (sessionId) state.sessionId = sessionId;
485
+ const error = nonEmptyString(source.error);
486
+ if (error) state.error = error.slice(0, MAX_TASK_ERROR_LENGTH);
487
+ const startedAt = nonEmptyString(source.startedAt);
488
+ if (startedAt) state.startedAt = startedAt;
489
+ const endedAt = nonEmptyString(source.endedAt);
490
+ if (endedAt) state.endedAt = endedAt;
491
+ return state;
492
+ }
493
+
494
+ /** Lenient run read: an unknown run status is coerced to "interrupted" (the safe terminal state). */
495
+ function coerceRun(raw: unknown, now: string): GraphRunRecord {
496
+ if (!raw || typeof raw !== "object") throw invalid("run record is not an object");
497
+ const source = raw as Record<string, unknown>;
498
+ const graphId = nonEmptyString(source.graphId);
499
+ if (!graphId) throw invalid("run record has no graphId");
500
+ const startedAt = nonEmptyString(source.startedAt) ?? now;
501
+ const tasksSource =
502
+ source.tasks && typeof source.tasks === "object" && !Array.isArray(source.tasks)
503
+ ? (source.tasks as Record<string, unknown>)
504
+ : {};
505
+ const tasks: Record<string, TaskRunState> = {};
506
+ for (const [id, value] of Object.entries(tasksSource)) tasks[id] = coerceTaskState(value);
507
+ return {
508
+ id: nonEmptyString(source.id) ?? newRunId(Date.parse(startedAt) || Date.now()),
509
+ graphId,
510
+ startedAt,
511
+ finishedAt: nonEmptyString(source.finishedAt) ?? null,
512
+ status: isRunStatus(source.status) ? source.status : "interrupted",
513
+ tasks,
514
+ };
515
+ }
516
+
517
+ const listOf = (value: unknown, label: string): unknown[] => {
518
+ if (value === undefined || value === null) return [];
519
+ if (!Array.isArray(value)) throw invalid(`registry \`${label}\` is not a list`);
520
+ return value;
521
+ };
522
+
523
+ /** Oldest-first ordering (startedAt, then id): the eviction order and the "newest first" inverse. */
524
+ const byStartedAsc = (left: GraphRunRecord, right: GraphRunRecord) =>
525
+ left.startedAt.localeCompare(right.startedAt) || left.id.localeCompare(right.id);
526
+
527
+ /** Keep at most `MAX_RUNS_PER_GRAPH` runs per graph, dropping the oldest. */
528
+ function capRuns(runs: readonly GraphRunRecord[]): GraphRunRecord[] {
529
+ const kept = [...runs];
530
+ const perGraph = new Map<string, GraphRunRecord[]>();
531
+ for (const run of kept) {
532
+ const list = perGraph.get(run.graphId) ?? [];
533
+ list.push(run);
534
+ perGraph.set(run.graphId, list);
535
+ }
536
+ for (const list of perGraph.values()) {
537
+ list.sort(byStartedAsc);
538
+ while (list.length > MAX_RUNS_PER_GRAPH) {
539
+ const oldest = list.shift()!;
540
+ kept.splice(kept.indexOf(oldest), 1);
541
+ }
542
+ }
543
+ return kept;
544
+ }
545
+
546
+ /**
547
+ * Turn whatever is on disk into v1 graphs + runs. v0 is the same documents
548
+ * without a `version` field (and, defensively, a bare graph array); an unknown
549
+ * `version` is refused so a newer build's file is not read as garbage.
550
+ */
551
+ export function migrate(raw: unknown, options: { now?: string } = {}): { graphs: GraphRecord[]; runs: GraphRunRecord[] } {
552
+ const now = options.now ?? new Date().toISOString();
553
+ if (raw === null || raw === undefined) return { graphs: [], runs: [] };
554
+ if (Array.isArray(raw)) return { graphs: raw.map((entry) => coerceRecord(entry, now)), runs: [] };
555
+ if (typeof raw !== "object") throw invalid("registry file is not a JSON object");
556
+ const file = raw as Record<string, unknown>;
557
+ const version = file.version;
558
+ if (version !== undefined && version !== null && version !== 0 && version !== GRAPH_REGISTRY_VERSION) {
559
+ throw invalid(`unsupported registry version ${String(version)}`);
560
+ }
561
+ const graphs = listOf(file.graphs, "graphs").map((entry) => coerceRecord(entry, now));
562
+ const runs = capRuns(listOf(file.runs, "runs").map((entry) => coerceRun(entry, now)));
563
+ return { graphs, runs };
564
+ }
565
+
566
+ type ReadResult =
567
+ | { ok: true; graphs: GraphRecord[]; runs: GraphRunRecord[] }
568
+ | { ok: false; missing: boolean; error: unknown };
569
+
570
+ /** Read + migrate one file, folding ENOENT (a fresh device) apart from "unusable". */
571
+ async function readRegistryFile(filePath: string, now: string): Promise<ReadResult> {
572
+ let text: string;
573
+ try {
574
+ text = await readFile(filePath, "utf8");
575
+ } catch (error) {
576
+ const code = (error as NodeJS.ErrnoException).code;
577
+ return { ok: false, missing: code === "ENOENT", error };
578
+ }
579
+ try {
580
+ return { ok: true, ...migrate(JSON.parse(text), { now }) };
581
+ } catch (error) {
582
+ return { ok: false, missing: false, error };
583
+ }
584
+ }
585
+
586
+ // ------------------------------------------------------------------- registry
587
+
588
+ /**
589
+ * The graph registry: one JSON file, loaded once at `open`, mutated through
590
+ * in-memory state that is only committed after the file write lands.
591
+ *
592
+ * Writes are serialised (`run`) so two concurrent `beginRun` calls cannot
593
+ * interleave: each stages a copy, persists it, then swaps it in.
594
+ */
595
+ export class GraphRegistry {
596
+ /** Absolute path of the main JSON file. */
597
+ readonly filePath: string;
598
+ /** The rolling backup restored by `open` when `filePath` is unusable. */
599
+ readonly backupPath: string;
600
+
601
+ private readonly warn: (message: string, error?: unknown) => void;
602
+ private readonly now: () => string;
603
+ private graphs = new Map<string, GraphRecord>();
604
+ private runRecords: GraphRunRecord[] = [];
605
+ /** False until a good file is read or written: while false we must not overwrite `.bak` with junk. */
606
+ private mainIsGood = false;
607
+ private queue: Promise<unknown> = Promise.resolve();
608
+
609
+ private constructor(filePath: string, options: GraphRegistryOptions) {
610
+ this.filePath = resolve(filePath);
611
+ this.backupPath = `${this.filePath}.bak`;
612
+ this.warn = options.warn ?? defaultWarn;
613
+ this.now = options.now ?? (() => new Date().toISOString());
614
+ }
615
+
616
+ /**
617
+ * Load the registry, or start from an empty one. A missing file is normal
618
+ * (fresh device). An unreadable one is moved to `<file>.corrupt-<ts>` and the
619
+ * `.bak` is tried before giving up, because the alternative — carrying on with
620
+ * an empty registry over a file we could not parse — loses the user's graphs
621
+ * on the next write.
622
+ */
623
+ static async open(filePath: string, options: GraphRegistryOptions = {}): Promise<GraphRegistry> {
624
+ const registry = new GraphRegistry(filePath, options);
625
+ await registry.load();
626
+ return registry;
627
+ }
628
+
629
+ /** Active graphs by default — archived ones are out of the way until asked for. Sorted by name. */
630
+ list(options: { includeArchived?: boolean } = {}): GraphRecord[] {
631
+ const includeArchived = options.includeArchived === true;
632
+ return [...this.graphs.values()]
633
+ .filter((record) => includeArchived || record.archivedAt === null)
634
+ .map(cloneGraph)
635
+ .sort(
636
+ (left, right) =>
637
+ left.name.localeCompare(right.name, undefined, { sensitivity: "base" }) ||
638
+ left.id.localeCompare(right.id),
639
+ );
640
+ }
641
+
642
+ /** One record by id (archived included), or undefined when it does not exist. */
643
+ get(id: string): GraphRecord | undefined {
644
+ const record = this.graphs.get(id);
645
+ return record ? cloneGraph(record) : undefined;
646
+ }
647
+
648
+ /** Store a new graph. Validation throws (`GraphError` `invalid`) rather than coercing. */
649
+ async create(input: GraphInput): Promise<GraphRecord> {
650
+ const name = normaliseName(input?.name);
651
+ const cwd = normaliseGraphCwd(input?.cwd);
652
+ const tasks = normaliseTasks(input?.tasks ?? []);
653
+ return this.run(async () => {
654
+ const staged = new Map(this.graphs);
655
+ let id = newGraphId();
656
+ while (staged.has(id)) id = newGraphId();
657
+ const now = this.now();
658
+ const created: GraphRecord = { id, name, cwd, tasks, createdAt: now, updatedAt: now, archivedAt: null };
659
+ staged.set(created.id, created);
660
+ await this.commit(staged, this.runRecords.map(cloneRun));
661
+ return cloneGraph(created);
662
+ });
663
+ }
664
+
665
+ /**
666
+ * Patch what the user owns: name/cwd/tasks replace-whole when present
667
+ * (present-keys semantics; absent keys untouched), with full re-validation.
668
+ */
669
+ async update(id: string, patch: GraphPatch): Promise<GraphRecord> {
670
+ return this.run(async () => {
671
+ const staged = new Map(this.graphs);
672
+ const existing = staged.get(id);
673
+ if (!existing) throw notFound(id);
674
+ const next = cloneGraph(existing);
675
+ if ("name" in patch) next.name = normaliseName(patch.name);
676
+ if ("cwd" in patch) next.cwd = normaliseGraphCwd(patch.cwd as string);
677
+ if ("tasks" in patch) next.tasks = normaliseTasks(patch.tasks ?? []);
678
+ next.updatedAt = this.now();
679
+ staged.set(next.id, next);
680
+ await this.commit(staged, this.runRecords.map(cloneRun));
681
+ return cloneGraph(next);
682
+ });
683
+ }
684
+
685
+ /**
686
+ * Soft delete. Archiving an already-archived graph keeps the original stamp —
687
+ * the first archive is the fact, a second one is a double click.
688
+ */
689
+ async archive(id: string): Promise<GraphRecord> {
690
+ return this.run(async () => {
691
+ const staged = new Map(this.graphs);
692
+ const existing = staged.get(id);
693
+ if (!existing) throw notFound(id);
694
+ if (existing.archivedAt) return cloneGraph(existing);
695
+ const now = this.now();
696
+ const next = { ...existing, archivedAt: now, updatedAt: now };
697
+ staged.set(next.id, next);
698
+ await this.commit(staged, this.runRecords.map(cloneRun));
699
+ return cloneGraph(next);
700
+ });
701
+ }
702
+
703
+ /** Undo `archive`. Tasks and the run history survived, which is the whole point of a soft delete. */
704
+ async unarchive(id: string): Promise<GraphRecord> {
705
+ return this.run(async () => {
706
+ const staged = new Map(this.graphs);
707
+ const existing = staged.get(id);
708
+ if (!existing) throw notFound(id);
709
+ if (existing.archivedAt === null) return cloneGraph(existing);
710
+ const next = { ...existing, archivedAt: null, updatedAt: this.now() };
711
+ staged.set(next.id, next);
712
+ await this.commit(staged, this.runRecords.map(cloneRun));
713
+ return cloneGraph(next);
714
+ });
715
+ }
716
+
717
+ /** Hard delete (also drops the graph's run history — no orphan runs). False when already gone. */
718
+ async remove(id: string): Promise<boolean> {
719
+ return this.run(async () => {
720
+ if (!this.graphs.has(id)) return false;
721
+ const staged = new Map(this.graphs);
722
+ staged.delete(id);
723
+ const runs = this.runRecords.filter((run) => run.graphId !== id).map(cloneRun);
724
+ await this.commit(staged, runs);
725
+ return true;
726
+ });
727
+ }
728
+
729
+ // ------------------------------------------------------------ run bookkeeping
730
+
731
+ /**
732
+ * Snapshot every task to pending and open a run: the honest starting state,
733
+ * because nothing has executed yet. Evicts this graph's runs beyond
734
+ * `MAX_RUNS_PER_GRAPH` (oldest first) so the file stays bounded.
735
+ */
736
+ async beginRun(graphId: string): Promise<GraphRunRecord> {
737
+ return this.run(async () => {
738
+ const stagedGraphs = new Map(this.graphs);
739
+ const graph = stagedGraphs.get(graphId);
740
+ if (!graph) throw notFound(graphId);
741
+ const startedAt = this.now();
742
+ const tasks: Record<string, TaskRunState> = {};
743
+ for (const task of graph.tasks) tasks[task.id] = { status: "pending" };
744
+ const stagedRuns = this.runRecords.map(cloneRun);
745
+ let id = newRunId(Date.parse(startedAt));
746
+ while (stagedRuns.some((run) => run.id === id)) id = newRunId(Date.parse(startedAt));
747
+ const record: GraphRunRecord = {
748
+ id,
749
+ graphId,
750
+ startedAt,
751
+ finishedAt: null,
752
+ status: "running",
753
+ tasks,
754
+ };
755
+ stagedRuns.push(cloneRun(record));
756
+ await this.commit(stagedGraphs, capRuns(stagedRuns));
757
+ return record;
758
+ });
759
+ }
760
+
761
+ /**
762
+ * Record one task's progress. Terminal statuses stamp `endedAt`; a transition
763
+ * to "running" stamps `startedAt`. After each mark the cascade runs (a failed
764
+ * task skips its dependents) and, once no task is pending or running, the run
765
+ * closes: "ok" only when every task reached ok, "failed" when any failed or
766
+ * was skipped.
767
+ */
768
+ async markTask(graphId: string, runId: string, taskId: string, patch: TaskRunPatch): Promise<GraphRunRecord> {
769
+ if (patch?.status !== undefined && !isTaskRunStatus(patch.status)) {
770
+ throw invalid(`unknown task status ${String(patch.status)}`);
771
+ }
772
+ if (patch?.sessionId !== undefined && typeof patch.sessionId !== "string") {
773
+ throw invalid("sessionId must be a string");
774
+ }
775
+ if (patch?.error !== undefined && typeof patch.error !== "string") {
776
+ throw invalid("error must be a string");
777
+ }
778
+ return this.run(async () => {
779
+ const stagedGraphs = new Map(this.graphs);
780
+ const graph = stagedGraphs.get(graphId);
781
+ if (!graph) throw notFound(graphId);
782
+ const stagedRuns = this.runRecords.map(cloneRun);
783
+ const run = stagedRuns.find((entry) => entry.id === runId && entry.graphId === graphId);
784
+ if (!run) throw new GraphError("not_found", `no run ${runId}`);
785
+ const state = run.tasks[taskId];
786
+ if (!state) throw invalid(`graph ${graphId} has no task ${taskId}`);
787
+ const now = this.now();
788
+ if (patch.status !== undefined) {
789
+ state.status = patch.status;
790
+ if (patch.status === "running") {
791
+ state.startedAt = now; // a re-run re-stamps: the fresh session is a new attempt
792
+ delete state.endedAt;
793
+ } else if (patch.status === "ok" || patch.status === "failed" || patch.status === "skipped") {
794
+ state.endedAt = now;
795
+ }
796
+ }
797
+ if (patch.sessionId !== undefined) {
798
+ const sessionId = patch.sessionId.trim();
799
+ if (sessionId) state.sessionId = sessionId;
800
+ else delete state.sessionId;
801
+ }
802
+ if (patch.error !== undefined) {
803
+ const error = patch.error.trim();
804
+ if (error) state.error = error.slice(0, MAX_TASK_ERROR_LENGTH); // ≤300: the session holds the trace
805
+ else delete state.error;
806
+ }
807
+ for (const skipped of cascadeSkips(graph.tasks, run.tasks)) {
808
+ run.tasks[skipped].endedAt = now; // a skipped task is terminal the moment its fate is known
809
+ }
810
+ // Only a live run closes; an "interrupted" (recovered) run stays closed.
811
+ if (run.status === "running" && runComplete(run.tasks)) {
812
+ run.status = runOutcome(run.tasks);
813
+ run.finishedAt = now;
814
+ }
815
+ await this.commit(stagedGraphs, stagedRuns);
816
+ return cloneRun(run);
817
+ });
818
+ }
819
+
820
+ /**
821
+ * At boot: every run still marked "running" belongs to a process that died.
822
+ * Its running tasks go back to pending (error cleared — the attempt never
823
+ * finished, so it has no verdict), and the run closes as "interrupted". The
824
+ * leader logs/notifications these; re-running is the human's call.
825
+ */
826
+ async recoverInterrupted(): Promise<GraphRunRecord[]> {
827
+ return this.run(async () => {
828
+ const stagedRuns = this.runRecords.map(cloneRun);
829
+ const touched: GraphRunRecord[] = [];
830
+ for (const run of stagedRuns) {
831
+ if (run.status !== "running") continue;
832
+ for (const state of Object.values(run.tasks)) {
833
+ if (state.status === "running") {
834
+ state.status = "pending";
835
+ delete state.error;
836
+ delete state.startedAt; // re-stamped when the task runs again
837
+ }
838
+ }
839
+ run.status = "interrupted";
840
+ run.finishedAt = this.now();
841
+ touched.push(run);
842
+ }
843
+ if (touched.length) await this.commit(new Map(this.graphs), stagedRuns);
844
+ return touched.map(cloneRun);
845
+ });
846
+ }
847
+
848
+ /** A graph's runs, newest first (the order a history list renders). */
849
+ runs(graphId: string): GraphRunRecord[] {
850
+ return this.runRecords
851
+ .filter((run) => run.graphId === graphId)
852
+ .sort((left, right) => byStartedAsc(right, left))
853
+ .map(cloneRun);
854
+ }
855
+
856
+ /** The newest run of a graph, or undefined when it never ran. */
857
+ lastRun(graphId: string): GraphRunRecord | undefined {
858
+ return this.runs(graphId)[0];
859
+ }
860
+
861
+ // ------------------------------------------------------------------ plumbing
862
+
863
+ private async load(): Promise<void> {
864
+ // Same guard as `Store.open`/`ScheduleRegistry.open`: the data dir holds
865
+ // credentials-adjacent state, so it is created 0700 or tightened first.
866
+ ensurePrivateDir(dirname(this.filePath));
867
+ const now = this.now();
868
+
869
+ const main = await readRegistryFile(this.filePath, now);
870
+ if (main.ok) {
871
+ this.adopt(main.graphs, main.runs);
872
+ this.mainIsGood = true;
873
+ return;
874
+ }
875
+ if (main.missing) return; // fresh device: nothing to load, nothing to complain about
876
+
877
+ this.warn(`${this.filePath} is unusable (${describeError(main.error)}); moving it aside`);
878
+ await this.setAside();
879
+
880
+ const backup = await readRegistryFile(this.backupPath, now);
881
+ if (backup.ok) {
882
+ this.adopt(backup.graphs, backup.runs);
883
+ this.warn(`recovered ${backup.graphs.length} graph(s) from ${this.backupPath}`);
884
+ return;
885
+ }
886
+ if (!backup.missing) this.warn(`${this.backupPath} is unusable too; starting with an empty registry`);
887
+ }
888
+
889
+ /** Rename an unreadable file out of the way instead of deleting it: it is the only copy of that data. */
890
+ private async setAside(): Promise<void> {
891
+ const aside = `${this.filePath}.corrupt-${Date.now()}`;
892
+ try {
893
+ await rename(this.filePath, aside);
894
+ this.warn(`kept the unreadable registry as ${aside}`);
895
+ } catch (error) {
896
+ this.warn(`could not move ${this.filePath} aside; nothing was written over it`, error);
897
+ }
898
+ }
899
+
900
+ private adopt(graphs: readonly GraphRecord[], runs: readonly GraphRunRecord[]): void {
901
+ this.graphs.clear();
902
+ for (const record of graphs) this.graphs.set(record.id, record);
903
+ this.runRecords = runs.map(cloneRun);
904
+ }
905
+
906
+ /** Stage → persist → swap. A failed write leaves memory exactly as it was. */
907
+ private async commit(staged: Map<string, GraphRecord>, runs: readonly GraphRunRecord[]): Promise<void> {
908
+ await this.persist([...staged.values()], runs);
909
+ this.graphs = staged;
910
+ this.runRecords = runs.map(cloneRun);
911
+ }
912
+
913
+ private run<T>(task: () => Promise<T>): Promise<T> {
914
+ const started = this.queue.then(task, task);
915
+ // Swallow the rejection on the chain only; the caller still sees it.
916
+ this.queue = started.then(
917
+ () => undefined,
918
+ () => undefined,
919
+ );
920
+ return started;
921
+ }
922
+
923
+ /**
924
+ * temp (0600) → rename → chmod, with the previous good file copied to `.bak`
925
+ * first. Rename is atomic within a directory, so a reader sees either the old
926
+ * bytes or the complete new ones — never a torn registry.
927
+ */
928
+ private async persist(graphs: readonly GraphRecord[], runs: readonly GraphRunRecord[]): Promise<void> {
929
+ const dir = dirname(this.filePath);
930
+ ensurePrivateDir(dir); // re-tightened on every write, like the pairing files
931
+ if (this.mainIsGood) await this.backUpMain();
932
+
933
+ const payload = `${JSON.stringify(
934
+ { version: GRAPH_REGISTRY_VERSION, graphs: [...graphs], runs: [...runs] } satisfies GraphRegistryFile,
935
+ null,
936
+ 2,
937
+ )}\n`;
938
+ const temp = `${this.filePath}.tmp-${process.pid}-${randomBytes(4).toString("hex")}`;
939
+ try {
940
+ await writeFile(temp, payload, { encoding: "utf8", mode: 0o600 });
941
+ await chmod(temp, 0o600); // umask can only make this stricter, but be explicit
942
+ await rename(temp, this.filePath);
943
+ await chmod(this.filePath, 0o600);
944
+ this.mainIsGood = true;
945
+ } catch (error) {
946
+ await unlink(temp).catch(() => undefined);
947
+ throw error;
948
+ }
949
+ }
950
+
951
+ /** Best effort: a failed backup must not fail the mutation that good file still protects. */
952
+ private async backUpMain(): Promise<void> {
953
+ try {
954
+ await copyFile(this.filePath, this.backupPath);
955
+ await chmod(this.backupPath, 0o600);
956
+ } catch (error) {
957
+ this.warn(`could not refresh ${this.backupPath}`, error);
958
+ }
959
+ }
960
+ }