opencode-model-router 2.8.0 → 2.9.1

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 (91) hide show
  1. package/CHANGELOG.md +372 -0
  2. package/README.md +22 -2
  3. package/package.json +5 -1
  4. package/src/commands/output.ts +23 -1
  5. package/src/compat/background.ts +2439 -0
  6. package/src/compat/child-session.ts +6 -0
  7. package/src/compat/turn-state.ts +215 -0
  8. package/src/compat/v2-client.ts +136 -17
  9. package/src/compat/v2-hooks.ts +2656 -114
  10. package/src/compat/v2-observations.ts +328 -0
  11. package/src/executor/capacity.ts +362 -0
  12. package/src/executor/child-guards.ts +40 -0
  13. package/src/executor/command.ts +265 -0
  14. package/src/executor/compile/edges.ts +809 -0
  15. package/src/executor/compile/estimate.ts +158 -0
  16. package/src/executor/compile/footprint.ts +829 -0
  17. package/src/executor/compile/index.ts +1080 -0
  18. package/src/executor/compile/parse.ts +1492 -0
  19. package/src/executor/compile/residue.ts +706 -0
  20. package/src/executor/compile/validate.ts +280 -0
  21. package/src/executor/create.ts +672 -0
  22. package/src/executor/expand.ts +551 -0
  23. package/src/executor/git.ts +1214 -0
  24. package/src/executor/host-preamble.ts +17 -0
  25. package/src/executor/instructions.ts +35 -0
  26. package/src/executor/integrate/bisect.ts +73 -0
  27. package/src/executor/integrate/checks.ts +1086 -0
  28. package/src/executor/integrate/land.ts +177 -0
  29. package/src/executor/integrate/phase-suite.ts +407 -0
  30. package/src/executor/integrate/queue.ts +3083 -0
  31. package/src/executor/integrate/run-resolver.ts +19 -0
  32. package/src/executor/launch.ts +652 -0
  33. package/src/executor/ledger.ts +2208 -0
  34. package/src/executor/observations.ts +212 -0
  35. package/src/executor/paths.ts +159 -0
  36. package/src/executor/platform.ts +39 -0
  37. package/src/executor/process-identity.ts +19 -0
  38. package/src/executor/qa-loop.ts +470 -0
  39. package/src/executor/recovery.ts +403 -0
  40. package/src/executor/runtime.ts +6233 -0
  41. package/src/executor/schedule.ts +246 -0
  42. package/src/executor/slots/env.ts +145 -0
  43. package/src/executor/slots/pool.ts +1564 -0
  44. package/src/executor/slots/provision.ts +853 -0
  45. package/src/executor/tool.ts +534 -0
  46. package/src/executor/types.ts +2064 -0
  47. package/src/executor/unattended.ts +488 -0
  48. package/src/guard/store.ts +3 -1
  49. package/src/index.ts +1498 -288
  50. package/src/router/config.ts +776 -25
  51. package/src/router/git-tools.ts +106 -15
  52. package/src/router/leases.ts +1469 -0
  53. package/src/router/logger.ts +44 -32
  54. package/src/router/protocol.ts +40 -10
  55. package/src/router/role-agents.ts +224 -17
  56. package/src/router/roles-config.ts +10 -1
  57. package/src/router/roles.ts +1 -1
  58. package/src/router/run-tools.ts +56 -4
  59. package/src/router/tool-paths.ts +308 -0
  60. package/src/router/work-roots.ts +86 -0
  61. package/src/routing/advisor/findings.ts +25 -5
  62. package/src/routing/classify/index.ts +7 -1
  63. package/src/routing/classify/rules.ts +11 -0
  64. package/src/routing/commands/stats.ts +2 -2
  65. package/src/routing/outcomes/durations.ts +225 -0
  66. package/src/routing/outcomes/index.ts +59 -2
  67. package/src/routing/outcomes/persist.ts +409 -0
  68. package/src/routing/outcomes/stats.ts +170 -11
  69. package/src/routing/outcomes/timings.ts +836 -0
  70. package/src/routing/outcomes/types.ts +98 -0
  71. package/src/routing/roles/approvals.ts +86 -5
  72. package/src/routing/roles/binding.ts +99 -9
  73. package/src/routing/roles/orphans.ts +68 -0
  74. package/src/routing/roles/policy.ts +21 -3
  75. package/src/routing/roles/work-root.ts +3 -1
  76. package/src/routing/wire/dispatch.ts +86 -12
  77. package/src/routing/wire/hint.ts +56 -8
  78. package/src/v2.ts +94 -49
  79. package/src/verify/branch.ts +8 -2
  80. package/src/verify/canonical-path.ts +35 -0
  81. package/src/verify/deterministic.ts +38 -9
  82. package/src/verify/dispatch.ts +64 -28
  83. package/src/verify/exec.ts +52 -9
  84. package/src/verify/pending.ts +1691 -10
  85. package/src/verify/perimeter.ts +12 -6
  86. package/src/verify/plan-task.ts +729 -0
  87. package/src/verify/reference.ts +216 -3
  88. package/src/verify/tree.ts +30 -13
  89. package/src/verify/types.ts +9 -2
  90. package/src/verify/wiring.ts +290 -31
  91. package/tiers.json +5 -5
@@ -0,0 +1,2208 @@
1
+ // Durable ledger store (plan task 2.2.2): snapshot + journal + history under one writer lock, all I/O through the `FileSystem` seam.
2
+ // Nothing here touches the filesystem, the clock or the process at module load.
3
+ import { randomBytes } from "node:crypto";
4
+ import * as nodeFsp from "node:fs/promises";
5
+ import { constants as nodeFsConstants } from "node:fs";
6
+
7
+ /** `appendText` options as the ledger passes them: `create: false` means "the file must already exist" (ENOENT = fenced). */
8
+ type AppendOptions = { fsync: boolean; create?: boolean };
9
+ import { hostname } from "node:os";
10
+ import { join } from "node:path";
11
+ import { observeSchedulerLedger } from "./observations.js";
12
+ import { isPlanId, planDir, SLOT_MARKERS_DIRNAME } from "./paths.js";
13
+ import {
14
+ GATE_TRANSITION_TRIGGERS,
15
+ INBOX_ID_PATTERN,
16
+ INBOX_ID_PREFIX,
17
+ LEDGER_SCHEMA,
18
+ RESERVED_TASK_IDS,
19
+ TRANSITION_TRIGGERS,
20
+ ExecutorError,
21
+ canGateTransition,
22
+ canStatusTransition,
23
+ canTransition,
24
+ isAttemptResumedEvent,
25
+ isDurableEvent,
26
+ isHistoryEvent,
27
+ isLedgerV1,
28
+ ledgerSchemaOf,
29
+ ledgerViolations,
30
+ type Attempt,
31
+ type BatchBuilder,
32
+ type Clock,
33
+ type ExecutorEvent,
34
+ type ExecutorEventInput,
35
+ type FileSystem,
36
+ type FsStat,
37
+ type GateRef,
38
+ type GateTransitionKey,
39
+ type IntegrationEntry,
40
+ type IntegrationStep,
41
+ type IntegrationStepResult,
42
+ type JsonValue,
43
+ type LedgerStatus,
44
+ type LedgerStore,
45
+ type LedgerV1,
46
+ type LedgerWriter,
47
+ type LockHolder,
48
+ type OpenIntegrationEntry,
49
+ type PlanId,
50
+ type TaskNode,
51
+ type TransitionKey,
52
+ } from "./types.js";
53
+
54
+ type Rec = Record<string, unknown>;
55
+
56
+ function isRec(v: unknown): v is Rec {
57
+ return typeof v === "object" && v !== null && !Array.isArray(v);
58
+ }
59
+ function hasOwn(o: object, k: string): boolean {
60
+ return Object.prototype.hasOwnProperty.call(o, k);
61
+ }
62
+ function errMessage(e: unknown): string {
63
+ return e instanceof Error ? e.message : String(e);
64
+ }
65
+
66
+ /** One parsed journal line: the event and its exact original text (history copies are byte-identical). */
67
+ interface JournalLine {
68
+ event: ExecutorEvent;
69
+ text: string;
70
+ }
71
+
72
+ interface ParsedJournal {
73
+ lines: JournalLine[];
74
+ /** A torn (unparsable / unterminated) last line was dropped. */
75
+ torn: boolean;
76
+ }
77
+
78
+ /** Shape check of the envelope only; payload checks happen in replay (per-event preconditions). */
79
+ function isEnvelope(v: unknown): v is ExecutorEvent {
80
+ return isRec(v) && Number.isInteger(v.seq) && typeof v.at === "string" && Number.isInteger(v.batch) &&
81
+ typeof v.last === "boolean" && typeof v.type === "string";
82
+ }
83
+
84
+ /**
85
+ * Splits a journal file into events. A last line without a terminating newline, or one that fails to parse, is torn
86
+ * and dropped (A1-2 rule 1). An unparsable line anywhere else is corruption (E_SEQ_GAP).
87
+ */
88
+ function parseJournal(text: string, file: string): ParsedJournal {
89
+ const lines: JournalLine[] = [];
90
+ if (text === "") return { lines, torn: false };
91
+ const parts = text.split("\n");
92
+ // `split` leaves "" after a trailing newline; anything else after the last "\n" is an unterminated (torn) line.
93
+ const tail = parts.pop() ?? "";
94
+ let torn = tail !== "";
95
+ for (let i = 0; i < parts.length; i++) {
96
+ const raw = parts[i] ?? "";
97
+ let parsed: unknown;
98
+ try {
99
+ parsed = JSON.parse(raw);
100
+ } catch (e) {
101
+ if (i === parts.length - 1 && tail === "") {
102
+ // A last terminated line that does not parse: the write was cut after the newline of a garbled block.
103
+ torn = true;
104
+ break;
105
+ }
106
+ throw new ExecutorError("E_SEQ_GAP", `unparsable journal line ${i + 1} in ${file}: ${errMessage(e)}`, { file, line: i + 1 });
107
+ }
108
+ if (!isEnvelope(parsed)) {
109
+ if (i === parts.length - 1 && tail === "") {
110
+ torn = true;
111
+ break;
112
+ }
113
+ throw new ExecutorError("E_SEQ_GAP", `malformed journal line ${i + 1} in ${file}`, { file, line: i + 1 });
114
+ }
115
+ lines.push({ event: parsed, text: raw });
116
+ }
117
+ return { lines, torn };
118
+ }
119
+
120
+ /** Result of framing validation over one journal file. */
121
+ interface FramedJournal {
122
+ /** Complete batches only, in order. */
123
+ lines: JournalLine[];
124
+ /** Number of events of a trailing incomplete batch that were dropped. */
125
+ droppedIncomplete: number;
126
+ }
127
+
128
+ /**
129
+ * A1-2 rules (2) and (3), main journal only: `seq` +1; the first event of a file and any event after `last: true` has `batch === seq`;
130
+ * the others share the previous `batch`. A trailing batch without `last: true` is dropped. `firstSeq` is the file's expected first seq
131
+ * (null: any, used for the first-seq of the file name check by the caller).
132
+ */
133
+ function frameJournal(lines: readonly JournalLine[], file: string, expectedFirst: number | null): FramedJournal {
134
+ let prev: ExecutorEvent | null = null;
135
+ let completeEnd = 0;
136
+ for (let i = 0; i < lines.length; i++) {
137
+ const e = (lines[i] as JournalLine).event;
138
+ const where = { file, seq: e.seq, type: e.type };
139
+ if (prev === null) {
140
+ if (expectedFirst !== null && e.seq !== expectedFirst) {
141
+ throw new ExecutorError("E_SEQ_GAP", `journal ${file} starts at seq ${e.seq}, expected ${expectedFirst}`, where);
142
+ }
143
+ if (e.batch !== e.seq) {
144
+ throw new ExecutorError("E_SEQ_GAP", `journal ${file}: first event seq ${e.seq} has batch ${e.batch}`, where);
145
+ }
146
+ } else {
147
+ if (e.seq !== prev.seq + 1) {
148
+ throw new ExecutorError("E_SEQ_GAP", `journal ${file}: seq ${e.seq} follows ${prev.seq}`, where);
149
+ }
150
+ const expectedBatch = prev.last ? e.seq : prev.batch;
151
+ if (e.batch !== expectedBatch) {
152
+ throw new ExecutorError("E_SEQ_GAP", `journal ${file}: seq ${e.seq} has batch ${e.batch}, expected ${expectedBatch}`, where);
153
+ }
154
+ }
155
+ if (e.last) completeEnd = i + 1;
156
+ prev = e;
157
+ }
158
+ return { lines: lines.slice(0, completeEnd), droppedIncomplete: lines.length - completeEnd };
159
+ }
160
+
161
+ function jsonDetail(v: unknown): JsonValue {
162
+ return JSON.parse(JSON.stringify(v ?? null)) as JsonValue;
163
+ }
164
+
165
+ // ---------------------------------------------------------------------------------------------------------------
166
+ // History tracker (A1-3): open integration entries and wake keys, derived from history-class events.
167
+ // ---------------------------------------------------------------------------------------------------------------
168
+
169
+ /** Mutable view of one open integration entry. */
170
+ interface OpenEntryState {
171
+ entry: IntegrationEntry;
172
+ startSeq: number;
173
+ step: IntegrationStep;
174
+ edge: "start" | "end";
175
+ result: IntegrationStepResult | null;
176
+ }
177
+
178
+ class HistoryTracker {
179
+ private open = new Map<string, OpenEntryState>();
180
+ private keys = new Set<string>();
181
+ /** Tasks whose most recent integration entry closed `rolled-back` (A1-3a: they may be `integrating` with no open entry). */
182
+ private rolledBack = new Set<string>();
183
+ lastSeq = 0;
184
+
185
+ clone(): HistoryTracker {
186
+ const t = new HistoryTracker();
187
+ for (const [id, s] of this.open) t.open.set(id, { ...s, entry: { ...s.entry, taskIds: [...s.entry.taskIds] } });
188
+ t.keys = new Set(this.keys);
189
+ t.rolledBack = new Set(this.rolledBack);
190
+ t.lastSeq = this.lastSeq;
191
+ return t;
192
+ }
193
+
194
+ /** Tasks that are `integrating` while no entry is open for them and their last entry did not close rolled-back (A1-3a), in plan order. */
195
+ integratingWithoutEntry(l: LedgerV1): string[] {
196
+ const open = new Set<string>();
197
+ for (const s of this.open.values()) for (const id of s.entry.taskIds) open.add(id);
198
+ return Object.values(l.tasks)
199
+ .filter((t) => t.state === "integrating" && !open.has(t.id) && !this.rolledBack.has(t.id))
200
+ .map((t) => t.id);
201
+ }
202
+
203
+ openEntries(): readonly OpenIntegrationEntry[] {
204
+ return [...this.open.values()].map((s) => ({
205
+ entry: { ...s.entry, taskIds: [...s.entry.taskIds] },
206
+ startSeq: s.startSeq,
207
+ step: s.step,
208
+ edge: s.edge,
209
+ result: s.result,
210
+ }));
211
+ }
212
+
213
+ wakeKeys(): ReadonlySet<string> {
214
+ return this.keys;
215
+ }
216
+
217
+ /** Applies a history-class event; returns a violation code (state unchanged) or null. Non-history events are ignored. */
218
+ apply(e: ExecutorEvent): string | null {
219
+ if (e.type === "wake") {
220
+ this.keys.add(e.stateKey);
221
+ this.lastSeq = e.seq;
222
+ return null;
223
+ }
224
+ if (e.type !== "integration-step") {
225
+ if (isHistoryEvent(e)) this.lastSeq = e.seq;
226
+ return null;
227
+ }
228
+ const cur = this.open.get(e.entry.id);
229
+ if (cur === undefined) {
230
+ if (e.edge !== "start") return "entry-not-open";
231
+ if (e.entry.id !== `i-${e.seq}`) return "entry-id-mismatch";
232
+ if (e.closes) return "closes-on-start";
233
+ this.open.set(e.entry.id, {
234
+ entry: { ...e.entry, taskIds: [...e.entry.taskIds] },
235
+ startSeq: e.seq,
236
+ step: e.step,
237
+ edge: "start",
238
+ result: null,
239
+ });
240
+ this.lastSeq = e.seq;
241
+ return null;
242
+ }
243
+ if (e.entry.kind !== cur.entry.kind || e.entry.phaseId !== cur.entry.phaseId || e.entry.baseHead !== cur.entry.baseHead) {
244
+ return "entry-fixed-field-changed";
245
+ }
246
+ if (e.edge === "start") {
247
+ if (cur.edge !== "end") return "step-start-before-end";
248
+ if (e.closes) return "closes-on-start";
249
+ } else {
250
+ if (cur.edge !== "start" || cur.step !== e.step) return "end-without-matching-start";
251
+ }
252
+ cur.entry = { ...e.entry, taskIds: [...e.entry.taskIds] };
253
+ cur.step = e.step;
254
+ cur.edge = e.edge;
255
+ cur.result = e.edge === "end" ? e.result : null;
256
+ if (e.edge === "end" && e.closes) {
257
+ this.open.delete(e.entry.id);
258
+ for (const id of e.entry.taskIds) {
259
+ if (e.result === "rolled-back") this.rolledBack.add(id);
260
+ else this.rolledBack.delete(id);
261
+ }
262
+ }
263
+ this.lastSeq = e.seq;
264
+ return null;
265
+ }
266
+ }
267
+
268
+ // ---------------------------------------------------------------------------------------------------------------
269
+ // Replay: per-event preconditions (A1-2) and the ledger reducer.
270
+ // ---------------------------------------------------------------------------------------------------------------
271
+
272
+ /** Per-batch bookkeeping for rules that span events of one batch. */
273
+ interface BatchCtx {
274
+ /** `plan-approved` was applied and no `status-changed -> running` has followed yet. */
275
+ approvalPending: boolean;
276
+ }
277
+
278
+ function newBatchCtx(): BatchCtx {
279
+ return { approvalPending: false };
280
+ }
281
+
282
+ const PRE_APPROVAL_STATUSES: readonly LedgerStatus[] = ["compiling", "awaiting-residue", "awaiting-approval"];
283
+
284
+ function taskOf(l: LedgerV1, id: string): TaskNode | null {
285
+ return hasOwn(l.tasks, id) ? (l.tasks[id] as TaskNode) : null;
286
+ }
287
+
288
+ function latestAttempt(t: TaskNode): Attempt | null {
289
+ return t.attempts.length === 0 ? null : (t.attempts[t.attempts.length - 1] as Attempt);
290
+ }
291
+
292
+ function isOpenAttemptShape(a: Attempt): boolean {
293
+ return a.endedAt === null && a.outcome === null && a.verdict === null && a.childSessionID === null && a.context === "";
294
+ }
295
+
296
+ function edgeEndpointExists(l: LedgerV1, id: string): boolean {
297
+ if (id.startsWith("gate:")) {
298
+ const phaseId = (id as GateRef).slice("gate:".length);
299
+ return l.phases.some((p) => p.id === phaseId);
300
+ }
301
+ return taskOf(l, id) !== null;
302
+ }
303
+
304
+ function sameStrings(a: readonly string[], b: readonly string[]): boolean {
305
+ return a.length === b.length && a.every((x, i) => x === b[i]);
306
+ }
307
+
308
+ function isSuperset(next: readonly string[], prev: readonly string[]): boolean {
309
+ return prev.every((p) => next.includes(p));
310
+ }
311
+
312
+ /**
313
+ * Checks the per-event precondition of `e` against `l` (the state just before `e`) and, when it holds, applies `e` to `l` in place.
314
+ * Returns a violation code or null. On a non-null return `l` may be partly changed: callers work on a copy.
315
+ */
316
+ function applyEvent(l: LedgerV1, e: ExecutorEvent, ctx: BatchCtx): string | null {
317
+ switch (e.type) {
318
+ case "ledger-init":
319
+ return "ledger-init-not-first"; // handled by the caller at the start of a journal; never mid-journal
320
+ case "draft-replaced": {
321
+ if (!PRE_APPROVAL_STATUSES.includes(l.status)) return "draft-replaced-status";
322
+ const d = e.draft;
323
+ l.planDigest = d.planDigest;
324
+ l.sharedContext = d.sharedContext;
325
+ l.waves = d.waves;
326
+ l.phases = d.phases;
327
+ l.tasks = d.tasks;
328
+ l.edges = d.edges;
329
+ break;
330
+ }
331
+ case "status-changed":
332
+ if (e.from !== l.status) return "status-from-mismatch";
333
+ if (!canStatusTransition(e.from, e.to)) return "status-illegal";
334
+ l.status = e.to;
335
+ if (e.to === "running") ctx.approvalPending = false;
336
+ break;
337
+ case "plan-approved":
338
+ if (l.status !== "awaiting-approval") return "approve-status";
339
+ if (e.config.slotsDir === null) return "approve-slots-dir";
340
+ l.config = e.config;
341
+ ctx.approvalPending = true;
342
+ break;
343
+ case "orchestrator-bound":
344
+ l.orchestrator = { sessionID: e.sessionID, boundAt: e.at };
345
+ break;
346
+ case "lock-takeover":
347
+ break;
348
+ case "task-created": {
349
+ const t = e.task;
350
+ if (typeof t.id !== "string" || RESERVED_TASK_IDS.has(t.id) || hasOwn(l.tasks, t.id)) return "task-exists";
351
+ if (t.state !== "pending" && t.state !== "done") return "task-created-state";
352
+ if (!Array.isArray(t.attempts) || t.attempts.length !== 0) return "task-created-attempts";
353
+ if (t.slot !== null) return "task-created-slot";
354
+ l.tasks[t.id] = t;
355
+ break;
356
+ }
357
+ case "edge-added":
358
+ if (!edgeEndpointExists(l, e.edge.from) || !edgeEndpointExists(l, e.edge.to)) return "edge-endpoint";
359
+ l.edges.push(e.edge);
360
+ break;
361
+ case "task-transition": {
362
+ const t = taskOf(l, e.taskId);
363
+ if (t === null) return "task-missing";
364
+ if (e.from !== t.state) return "transition-from-mismatch";
365
+ if (!canTransition(e.from, e.to)) return "transition-illegal";
366
+ const triggers = TRANSITION_TRIGGERS[`${e.from}>${e.to}` as TransitionKey];
367
+ if (triggers === undefined || !triggers.includes(e.trigger)) return "transition-trigger";
368
+ t.state = e.to;
369
+ break;
370
+ }
371
+ case "attempt-started": {
372
+ const t = taskOf(l, e.taskId);
373
+ if (t === null) return "task-missing";
374
+ const a = e.attempt;
375
+ if (t.state !== "ready") return "attempt-started-state";
376
+ if (t.attempts.some((x) => x.outcome === null)) return "attempt-open-exists";
377
+ if (a.n !== t.attempts.length + 1) return "attempt-n";
378
+ if (!isOpenAttemptShape(a)) return "attempt-open-shape";
379
+ if (t.attempts.some((x) => x.nonce === a.nonce)) return "attempt-nonce-reused";
380
+ t.attempts.push(a);
381
+ break;
382
+ }
383
+ case "attempt-child": {
384
+ const t = taskOf(l, e.taskId);
385
+ if (t === null) return "task-missing";
386
+ const a = latestAttempt(t);
387
+ if (t.state !== "dispatched") return "attempt-child-state";
388
+ if (a === null || a.n !== e.n || a.outcome !== null || a.childSessionID !== null) return "attempt-child-target";
389
+ a.childSessionID = e.childSessionID;
390
+ break;
391
+ }
392
+ case "attempt-adopted": {
393
+ const t = taskOf(l, e.taskId);
394
+ if (t === null) return "task-missing";
395
+ const a = latestAttempt(t);
396
+ if (t.state !== "ready") return "attempt-adopted-state";
397
+ if (a === null || a.n !== e.n || a.outcome !== "lost") return "attempt-adopted-target";
398
+ // The late child continues this attempt: it is open again (the row-7 transition to running follows in the batch).
399
+ a.childSessionID = e.childSessionID;
400
+ a.outcome = null;
401
+ a.endedAt = null;
402
+ break;
403
+ }
404
+ case "attempt-resumed": {
405
+ const t = taskOf(l, e.taskId);
406
+ if (t === null) return "task-missing";
407
+ const a = latestAttempt(t);
408
+ if (t.state !== "running") return "attempt-resumed-state";
409
+ if (a === null || a.n !== e.n || a.outcome !== null) return "attempt-resumed-target";
410
+ if (!isAttemptResumedEvent(e)) return "attempt-resumed-shape";
411
+ if (e.resumes !== (a.resumes ?? 0) + 1) return "attempt-resumed-count";
412
+ a.resumes = e.resumes;
413
+ break;
414
+ }
415
+ case "attempt-ended": {
416
+ const t = taskOf(l, e.taskId);
417
+ if (t === null) return "task-missing";
418
+ const a = latestAttempt(t);
419
+ if (t.state !== "dispatched" && t.state !== "running") return "attempt-ended-state";
420
+ if (a === null || a.n !== e.n || a.outcome !== null) return "attempt-ended-target";
421
+ a.outcome = e.outcome;
422
+ a.endedAt = e.endedAt;
423
+ break;
424
+ }
425
+ case "attempt-verdict": {
426
+ const t = taskOf(l, e.taskId);
427
+ if (t === null) return "task-missing";
428
+ const a = latestAttempt(t);
429
+ if (t.state !== "verifying") return "attempt-verdict-state";
430
+ if (a === null || a.n !== e.n || a.outcome !== "succeeded" || a.verdict !== null) return "attempt-verdict-target";
431
+ a.verdict = e.verdict;
432
+ break;
433
+ }
434
+ case "attempt-context": {
435
+ const t = taskOf(l, e.taskId);
436
+ if (t === null) return "task-missing";
437
+ if (e.n !== t.attempts.length || e.n < 1) return "attempt-context-target";
438
+ (t.attempts[e.n - 1] as Attempt).context = e.context;
439
+ break;
440
+ }
441
+ case "task-slot": {
442
+ const t = taskOf(l, e.taskId);
443
+ if (t === null) return "task-missing";
444
+ t.slot = e.slot;
445
+ t.branch = e.branch;
446
+ break;
447
+ }
448
+ case "task-footprint": {
449
+ const t = taskOf(l, e.taskId);
450
+ if (t === null) return "task-missing";
451
+ const o = t.footprint;
452
+ const n = e.footprint;
453
+ if (!isSuperset(n.writes, o.writes) || !isSuperset(n.reads, o.reads) || !isSuperset(n.sources, o.sources)) {
454
+ return "footprint-not-monotone";
455
+ }
456
+ t.footprint = n;
457
+ break;
458
+ }
459
+ case "task-integrated": {
460
+ const t = taskOf(l, e.taskId);
461
+ if (t === null) return "task-missing";
462
+ if (t.state !== "integrating") return "task-integrated-state";
463
+ t.integrated = { from: e.from, to: e.to };
464
+ break;
465
+ }
466
+ case "integration-head":
467
+ l.integration.head = e.head;
468
+ break;
469
+ case "gate-changed": {
470
+ const p = l.phases.find((x) => x.id === e.phaseId);
471
+ if (p === undefined) return "phase-missing";
472
+ if (e.from !== p.gate) return "gate-from-mismatch";
473
+ if (!canGateTransition(e.from, e.to)) return "gate-illegal";
474
+ const triggers = GATE_TRANSITION_TRIGGERS[`${e.from}>${e.to}` as GateTransitionKey];
475
+ if (triggers === undefined || !triggers.includes(e.trigger)) return "gate-trigger";
476
+ const bump = e.trigger === "qa-next-round" || e.trigger === "cap-fix" ? 1 : 0;
477
+ if (e.qaRound !== p.qaRound + bump) return "gate-qa-round";
478
+ p.gate = e.to;
479
+ p.qaRound = e.qaRound;
480
+ break;
481
+ }
482
+ case "phase-paused": {
483
+ const p = l.phases.find((x) => x.id === e.phaseId);
484
+ if (p === undefined) return "phase-missing";
485
+ if (p.paused === e.paused) return "phase-paused-unchanged";
486
+ p.paused = e.paused;
487
+ break;
488
+ }
489
+ case "phase-tagged": {
490
+ const p = l.phases.find((x) => x.id === e.phaseId);
491
+ if (p === undefined) return "phase-missing";
492
+ p.tag = e.tag;
493
+ break;
494
+ }
495
+ case "inbox-added": {
496
+ const m = INBOX_ID_PATTERN.exec(e.item.id);
497
+ if (m === null || m[1] !== INBOX_ID_PREFIX[e.item.kind]) return "inbox-id";
498
+ const n = Number(m[2]);
499
+ if (l.inbox.some((x) => {
500
+ const mx = INBOX_ID_PATTERN.exec(x.id);
501
+ return mx !== null && Number(mx[2]) >= n;
502
+ })) return "inbox-id-not-increasing";
503
+ l.inbox.push(e.item);
504
+ break;
505
+ }
506
+ case "inbox-answered": {
507
+ const item = l.inbox.find((x) => x.id === e.id);
508
+ if (item === undefined) return "inbox-missing";
509
+ if (item.answer !== null) return "inbox-already-answered";
510
+ if (item.kind === "qa-cap" && item.severity === "critical" && !item.options.includes(e.answer)) return "inbox-answer-option";
511
+ item.answer = e.answer;
512
+ break;
513
+ }
514
+ case "integration-step":
515
+ case "wake":
516
+ case "metric":
517
+ break;
518
+ default:
519
+ return "unknown-event-type";
520
+ }
521
+ l.seq = e.seq;
522
+ return null;
523
+ }
524
+
525
+ /** Whole-ledger invariants, checked at batch end only (A1-2 rule 4), plus the batch-spanning rule of `plan-approved`. */
526
+ function batchEndViolation(l: LedgerV1, ctx: BatchCtx): { code: string; codes: string[] } | null {
527
+ const codes: string[] = [];
528
+ if (ctx.approvalPending) codes.push("plan-approved-without-running");
529
+ for (const v of ledgerViolations(l)) codes.push(`${v.code}@${v.at}`);
530
+ return codes.length === 0 ? null : { code: codes[0] as string, codes };
531
+ }
532
+
533
+ /** Event reference carried in error details (names the offending event). */
534
+ function eventRef(e: ExecutorEvent): JsonValue {
535
+ return { seq: e.seq, batch: e.batch, type: e.type };
536
+ }
537
+
538
+ /** Starting ledger of a journal: the `ledger-init` event's ledger, checked for shape. */
539
+ function initLedger(e: ExecutorEvent): LedgerV1 {
540
+ if (e.type !== "ledger-init") throw new ExecutorError("E_SCHEMA_INVALID", "journal does not start with ledger-init", eventRef(e));
541
+ return checkLedger(e.ledger, `ledger-init seq ${e.seq}`);
542
+ }
543
+
544
+ /** Schema gate shared by snapshot and ledger-init: newer is refused, older migrates through the table, anything else must be a LedgerV1. */
545
+ const MIGRATIONS: Readonly<Record<number, (old: unknown) => unknown>> = {};
546
+
547
+ function checkLedger(v: unknown, what: string): LedgerV1 {
548
+ let cur: unknown = v;
549
+ const schema = ledgerSchemaOf(cur);
550
+ if (schema !== null && schema > LEDGER_SCHEMA) {
551
+ throw new ExecutorError("E_SCHEMA_NEWER", `${what}: ledger schema ${schema} is newer than supported ${LEDGER_SCHEMA}`, { schema });
552
+ }
553
+ let s = schema;
554
+ while (s !== null && s < LEDGER_SCHEMA) {
555
+ const step = hasOwn(MIGRATIONS, String(s)) ? MIGRATIONS[s] : undefined;
556
+ if (step === undefined) throw new ExecutorError("E_SCHEMA_INVALID", `${what}: no migration from schema ${s}`, { schema: s });
557
+ cur = step(cur);
558
+ const migrated = ledgerSchemaOf(cur);
559
+ if (migrated === null || migrated <= s) {
560
+ throw new ExecutorError("E_SCHEMA_INVALID", `${what}: migration from schema ${s} did not advance the schema`, { schema: s });
561
+ }
562
+ s = migrated;
563
+ }
564
+ if (!isLedgerV1(cur)) {
565
+ const viol = ledgerViolations(cur);
566
+ throw new ExecutorError("E_SCHEMA_INVALID", `${what}: not a valid ledger`, jsonDetail(viol.slice(0, 20)));
567
+ }
568
+ return cur;
569
+ }
570
+
571
+ function illegal(e: ExecutorEvent, code: string, codes: string[] = [code]): ExecutorError {
572
+ return new ExecutorError("E_ILLEGAL_TRANSITION", `event seq ${e.seq} (${e.type}) is illegal: ${codes.join(", ")}`, {
573
+ event: eventRef(e),
574
+ codes,
575
+ });
576
+ }
577
+
578
+ // ---------------------------------------------------------------------------------------------------------------
579
+ // Files, retry, locks.
580
+ // ---------------------------------------------------------------------------------------------------------------
581
+
582
+ /** `ledger.<writerEpoch>.json`: one snapshot per writer epoch; the loader takes the highest epoch (see `snapshotName`). */
583
+ const SNAPSHOT_PATTERN = /^ledger\.(\d+)\.json$/;
584
+ const LOCK_FILE = "writer.lock";
585
+ const LOCK_GUARD_FILE = "writer.lock.guard";
586
+ const LOCK_GUARD_BREAK_FILE = "writer.lock.guard.break";
587
+ const HISTORY_FILE = "history.jsonl";
588
+ /** `events.<firstSeq>.<writerEpoch>.jsonl`: the epoch fences a takeover's predecessor (see `trustedChain`). */
589
+ const JOURNAL_PATTERN = /^events\.(\d+)\.(\d+)\.jsonl$/;
590
+ const TMP_PATTERN = /^(?:ledger\.\d+\.json|writer\.lock|history\.jsonl|writer\.[A-Za-z0-9_-]+\.beat)\.tmp-/;
591
+ const BEAT_PATTERN = /^writer\.([A-Za-z0-9_-]+)\.beat$/;
592
+ const TOKEN_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
593
+
594
+ /**
595
+ * The only takeover `reason` that may replace a LIVE holder, matched exactly. It applies only when the live holder is this same
596
+ * process (same pid and host), until fencing proves an older writer out; any other live holder is refused with E_LOCK_HELD.
597
+ */
598
+ export const ADOPT_TAKEOVER_REASON = "adopt";
599
+
600
+ function beatFileName(token: string): string {
601
+ return `writer.${token}.beat`;
602
+ }
603
+
604
+ /** The lock file's content: the public holder plus the store-stamped token (identity) and the writer epoch (fencing). */
605
+ interface LockRecord extends LockHolder {
606
+ token: string;
607
+ epoch: number;
608
+ }
609
+
610
+ /** What a reader of `writer.lock` learns: the raw text (for a content re-check), the parsed record and the freshness facts. */
611
+ interface LockRead {
612
+ exists: boolean;
613
+ text: string | null;
614
+ holder: LockRecord | null;
615
+ mtimeMs: number | null;
616
+ /** The holder's own beat file stamp, when present. */
617
+ beatMs: number | null;
618
+ }
619
+
620
+ /** The holder as recorded in events and error details (no store-private fields). */
621
+ function publicHolder(r: LockHolder): LockHolder {
622
+ return { pid: r.pid, hostname: r.hostname, sessionID: r.sessionID, startedAt: r.startedAt, heartbeatAt: r.heartbeatAt };
623
+ }
624
+
625
+ /** Defaults (2.2.2.b, .e). */
626
+ const SNAPSHOT_EVERY_EVENTS = 200;
627
+ const HEARTBEAT_MS = 10_000;
628
+ const LOCK_STALE_MS = 60_000;
629
+ const RETRY_BUDGET_MS = 2_000;
630
+ const READ_RETRIES = 8;
631
+ const GUARD_STALE_MS = 15_000;
632
+
633
+ /** Pid/host facts the lock needs; a `Spawner` satisfies it. */
634
+ export interface LedgerProcessInfo {
635
+ readonly pid: number;
636
+ readonly hostname: string;
637
+ isAlive(pid: number): boolean;
638
+ }
639
+
640
+ export interface LedgerStoreDeps {
641
+ /** v2 diagnostic seam, never enabled by the store itself. */
642
+ observations?: import("../compat/v2-observations").V2Observations;
643
+ /** The executor home (`resolveExecutorHome`); plans live in `planDir(home, planId)`. */
644
+ home: string;
645
+ /** Default: {@link createNodeFileSystem}. */
646
+ fs?: FileSystem;
647
+ /** Default: {@link createNodeClock}. */
648
+ clock?: Clock;
649
+ /** Default: this process. */
650
+ proc?: LedgerProcessInfo;
651
+ /** Receives warnings (torn last line, dropped incomplete batch, failed cleanup). Default: dropped. */
652
+ warn?: (message: string) => void;
653
+ /** Lock heartbeat period; default 10 s. */
654
+ heartbeatMs?: number;
655
+ /** A heartbeat older than this is stale; default 60 s. */
656
+ staleMs?: number;
657
+ /** Events between snapshots; default 200. */
658
+ snapshotEvery?: number;
659
+ }
660
+
661
+ /** Production `Clock`. Timers are unref'd so a pending heartbeat never keeps the process alive. */
662
+ export function createNodeClock(): Clock {
663
+ const timers = new Map<number, ReturnType<typeof setTimeout>>();
664
+ let nextId = 1;
665
+ return {
666
+ now: () => Date.now(),
667
+ iso: (ms) => new Date(ms ?? Date.now()).toISOString(),
668
+ setTimer(ms, fn) {
669
+ const id = nextId++;
670
+ const h = setTimeout(() => {
671
+ timers.delete(id);
672
+ fn();
673
+ }, ms);
674
+ h.unref();
675
+ timers.set(id, h);
676
+ return { id };
677
+ },
678
+ clearTimer(h) {
679
+ const t = timers.get(h.id);
680
+ if (t !== undefined) {
681
+ clearTimeout(t);
682
+ timers.delete(h.id);
683
+ }
684
+ },
685
+ randomHex: (bytes) => randomBytes(bytes).toString("hex"),
686
+ };
687
+ }
688
+
689
+ function createNodeProcessInfo(): LedgerProcessInfo {
690
+ return {
691
+ pid: process.pid,
692
+ hostname: hostname(),
693
+ isAlive(pid) {
694
+ try {
695
+ process.kill(pid, 0);
696
+ return true;
697
+ } catch (e) {
698
+ return fsErrorCode(e) === "EPERM"; // exists, owned by someone else
699
+ }
700
+ },
701
+ };
702
+ }
703
+
704
+ function sleep(clock: Clock, ms: number): Promise<void> {
705
+ return new Promise<void>((resolve) => {
706
+ clock.setTimer(ms, resolve);
707
+ });
708
+ }
709
+
710
+ /** Retries `op` while it fails with EPERM/EBUSY (antivirus, indexers, a reader holding the file), within the 2 s budget (2.2.2.b). */
711
+ async function retryBusy<T>(clock: Clock, op: () => Promise<T>): Promise<T> {
712
+ const start = clock.now();
713
+ let delay = 10;
714
+ for (let attempt = 0; ; attempt++) {
715
+ try {
716
+ return await op();
717
+ } catch (e) {
718
+ const code = fsErrorCode(e);
719
+ if ((code !== "EPERM" && code !== "EBUSY") || clock.now() - start >= RETRY_BUDGET_MS || attempt >= 100) throw e;
720
+ await sleep(clock, delay);
721
+ delay = Math.min(delay * 2, 200);
722
+ }
723
+ }
724
+ }
725
+
726
+ async function readOptional(fs: FileSystem, path: string): Promise<string | null> {
727
+ try {
728
+ return await fs.readText(path);
729
+ } catch (e) {
730
+ if (fsErrorCode(e) === "ENOENT") return null;
731
+ throw e;
732
+ }
733
+ }
734
+
735
+ /** Removes a file that may already be gone. */
736
+ async function rmQuiet(fs: FileSystem, path: string, recursive = false): Promise<void> {
737
+ try {
738
+ await fs.rm(path, { recursive });
739
+ } catch (e) {
740
+ if (fsErrorCode(e) !== "ENOENT") throw e;
741
+ }
742
+ }
743
+
744
+ function parseLockText(text: string): LockRecord | null {
745
+ let v: unknown;
746
+ try {
747
+ v = JSON.parse(text);
748
+ } catch {
749
+ return null; // torn lock file: no holder can be named
750
+ }
751
+ if (!isRec(v)) return null;
752
+ const { pid, hostname: host, sessionID, startedAt, heartbeatAt, token, epoch } = v;
753
+ if (typeof pid !== "number" || typeof host !== "string" || typeof sessionID !== "string") return null;
754
+ if (typeof startedAt !== "string" || typeof heartbeatAt !== "string") return null;
755
+ if (typeof token !== "string" || !TOKEN_PATTERN.test(token)) return null;
756
+ if (typeof epoch !== "number" || !Number.isInteger(epoch) || epoch < 1) return null;
757
+ return { pid, hostname: host, sessionID, startedAt, heartbeatAt, token, epoch };
758
+ }
759
+
760
+ /** Identity is the store-stamped random token (two holders never share one); pid and host are compared as a sanity check. */
761
+ function sameLockIdentity(a: LockRecord, b: LockRecord): boolean {
762
+ return a.token === b.token && a.pid === b.pid && a.hostname === b.hostname;
763
+ }
764
+
765
+ function parseBeatText(text: string): number | null {
766
+ try {
767
+ const v: unknown = JSON.parse(text);
768
+ if (!isRec(v) || typeof v.heartbeatAt !== "string") return null;
769
+ const ms = Date.parse(v.heartbeatAt);
770
+ return Number.isFinite(ms) ? ms : null;
771
+ } catch {
772
+ return null; // torn beat file: the lock's own heartbeat stands
773
+ }
774
+ }
775
+
776
+ /** Fails with E_LOCK_LOST unless `writer.lock` names `lock`. Used before every destructive step, by writers and by the open path. */
777
+ async function assertLockHeld(env: { fs: FileSystem; dir: string; planId: PlanId }, lock: LockRecord): Promise<void> {
778
+ const text = await readOptional(env.fs, join(env.dir, LOCK_FILE));
779
+ const holder = text === null ? null : parseLockText(text);
780
+ if (holder === null || !sameLockIdentity(holder, lock)) {
781
+ throw new ExecutorError("E_LOCK_LOST", `writer lock for ${env.planId} is held by another writer`, jsonDetail(holder === null ? null : publicHolder(holder)));
782
+ }
783
+ }
784
+
785
+ // ---------------------------------------------------------------------------------------------------------------
786
+ // Load (snapshot + journal replay).
787
+ // ---------------------------------------------------------------------------------------------------------------
788
+
789
+ /** The snapshot and the journal listing disagree; a reader retries (2.2.2.b). */
790
+ class SnapshotMismatch extends Error {}
791
+
792
+ interface JournalFile {
793
+ name: string;
794
+ first: number;
795
+ epoch: number;
796
+ }
797
+
798
+ function journalName(first: number, epoch: number): string {
799
+ return `events.${first}.${epoch}.jsonl`;
800
+ }
801
+
802
+ interface MainState {
803
+ ledger: LedgerV1;
804
+ /** 0 when there is no snapshot file (a plan whose first snapshot was never renamed into place). */
805
+ snapshotSeq: number;
806
+ /** The writer epoch stamped in the snapshot (0 when there is no snapshot). */
807
+ snapshotEpoch: number;
808
+ /** The trusted journal chain, ascending. */
809
+ files: JournalFile[];
810
+ /** Every complete, framed line of the relevant journal files, ascending (may include seq <= snapshotSeq). */
811
+ events: JournalLine[];
812
+ /** The last journal file ends in a torn line or an incomplete batch: appending to it is unsafe. */
813
+ dirty: boolean;
814
+ warnings: string[];
815
+ }
816
+
817
+ function parseSnapshot(text: string, file: string): unknown {
818
+ try {
819
+ return JSON.parse(text);
820
+ } catch (e) {
821
+ throw new ExecutorError("E_SCHEMA_INVALID", `${file} is not valid JSON: ${errMessage(e)}`);
822
+ }
823
+ }
824
+
825
+ function snapshotName(epoch: number): string {
826
+ return `ledger.${epoch}.json`;
827
+ }
828
+
829
+ /** The journal files among directory `names`, ascending by first seq. */
830
+ function journalsOf(names: readonly string[]): JournalFile[] {
831
+ const files: JournalFile[] = [];
832
+ for (const name of names) {
833
+ const m = JOURNAL_PATTERN.exec(name);
834
+ if (m !== null) files.push({ name, first: Number(m[1]), epoch: Number(m[2]) });
835
+ }
836
+ // Same first seq: the higher epoch sorts first, so `trustedChain` drops the superseded lower-epoch file.
837
+ return files.sort((a, b) => a.first - b.first || b.epoch - a.epoch);
838
+ }
839
+
840
+ /** The highest writer epoch among the snapshot files in `names`, or null when there is none. */
841
+ function newestSnapshotEpoch(names: readonly string[]): number | null {
842
+ let max: number | null = null;
843
+ for (const name of names) {
844
+ const m = SNAPSHOT_PATTERN.exec(name);
845
+ if (m !== null && (max === null || Number(m[1]) > max)) max = Number(m[1]);
846
+ }
847
+ return max;
848
+ }
849
+
850
+ async function listPlanDir(fs: FileSystem, dir: string): Promise<string[]> {
851
+ try {
852
+ return await fs.readdir(dir);
853
+ } catch (e) {
854
+ if (fsErrorCode(e) === "ENOENT") throw new ExecutorError("E_LEDGER_NOT_FOUND", `no plan directory ${dir}`);
855
+ throw e;
856
+ }
857
+ }
858
+
859
+ /**
860
+ * Splits the listed journals into the trusted chain and the rest. A file is dropped when a file with a higher writer epoch starts at or
861
+ * before it: a takeover's new epoch is authoritative from its first seq, so whatever an older-epoch writer wrote at or after that point
862
+ * (late appends, a late rotation) is never read.
863
+ */
864
+ function trustedChain(files: readonly JournalFile[]): { chain: JournalFile[] } {
865
+ const chain: JournalFile[] = [];
866
+ let maxEpoch = 0;
867
+ for (const f of files) {
868
+ if (f.epoch >= maxEpoch) {
869
+ chain.push(f);
870
+ maxEpoch = f.epoch;
871
+ }
872
+ }
873
+ return { chain };
874
+ }
875
+
876
+ /** Highest writer epoch visible on disk (journal names, snapshot stamp); a new writer takes the next one. */
877
+ async function maxEpochOnDisk(fs: FileSystem, dir: string): Promise<number> {
878
+ let max = 0;
879
+ for (const name of await fs.readdir(dir)) {
880
+ const m = JOURNAL_PATTERN.exec(name) ?? SNAPSHOT_PATTERN.exec(name);
881
+ if (m !== null) max = Math.max(max, Number(m[m.length - 1]));
882
+ }
883
+ return max;
884
+ }
885
+
886
+ /**
887
+ * Snapshot plus replay of the events with a greater `seq` (2.2.2.c). A journal file is authoritative only for `seq` below the next
888
+ * file's first `seq`: that is what makes rotation (and a takeover's rotation) fence a slow old writer.
889
+ */
890
+ async function loadMain(fs: FileSystem, dir: string, mode: "reader" | "writer"): Promise<MainState> {
891
+ const names = await listPlanDir(fs, dir);
892
+ const listed = journalsOf(names);
893
+ const { chain: files } = trustedChain(listed);
894
+ // The snapshot of the highest writer epoch wins: a fenced writer's late rename can only touch its own (lower) epoch's file.
895
+ const newest = newestSnapshotEpoch(names);
896
+ if (newest === null && listed.length === 0) throw new ExecutorError("E_LEDGER_NOT_FOUND", `no ledger in ${dir}`);
897
+ const snapFile = newest === null ? null : snapshotName(newest);
898
+ const snapText = snapFile === null ? null : await readOptional(fs, join(dir, snapFile));
899
+ const snapshotEpoch = newest ?? 0;
900
+ let snapshot: LedgerV1 | null = null;
901
+ if (snapFile !== null) {
902
+ // A listed snapshot that is gone was superseded (and deleted) by a newer writer's while this load ran.
903
+ if (snapText === null) {
904
+ const msg = `${snapFile} vanished while loading`;
905
+ throw mode === "reader" ? new SnapshotMismatch(msg) : new ExecutorError("E_SEQ_GAP", msg, { dir });
906
+ }
907
+ snapshot = checkLedger(parseSnapshot(snapText, snapFile), snapFile);
908
+ }
909
+ const S = snapshot === null ? 0 : snapshot.seq;
910
+ const mismatch = (msg: string): Error =>
911
+ mode === "reader" ? new SnapshotMismatch(msg) : new ExecutorError("E_SEQ_GAP", msg, { snapshotSeq: S });
912
+ if (snapshot === null && (files[0] === undefined || files[0].first !== 1)) {
913
+ throw new ExecutorError("E_SEQ_GAP", `no snapshot file and the journal does not start at seq 1`, { dir });
914
+ }
915
+ for (const f of files) {
916
+ // A journal that starts beyond the next seq the snapshot needs (even an empty one) means the snapshot is behind: a rotation race.
917
+ if (snapshot !== null && f.first > S + 1) throw mismatch(`snapshot is at seq ${S} but ${f.name} starts at seq ${f.first}`);
918
+ // A snapshot written by an older epoch than a journal that starts at or before it came from a fenced writer.
919
+ if (snapshot !== null && f.first <= S && f.epoch > snapshotEpoch) {
920
+ throw mismatch(`snapshot at seq ${S} (epoch ${snapshotEpoch}) is older than ${f.name}`);
921
+ }
922
+ }
923
+
924
+ const events: JournalLine[] = [];
925
+ const warnings: string[] = [];
926
+ let dirty = false;
927
+ for (let i = 0; i < files.length; i++) {
928
+ const f = files[i] as JournalFile;
929
+ const next = files[i + 1];
930
+ if (next !== undefined && next.first <= S + 1) continue; // only seq <= S: covered by the snapshot
931
+ const text = await readOptional(fs, join(dir, f.name));
932
+ if (text === null) throw mismatch(`journal ${f.name} vanished while loading`);
933
+ const parsed = parseJournal(text, f.name);
934
+ // A file of an older writer epoch than the snapshot is trusted only up to the snapshot's seq: anything a fenced writer appended
935
+ // after the newer writer's snapshot is ignored, even before the newer writer's own journal file exists.
936
+ const fenced = f.epoch < snapshotEpoch;
937
+ const kept = parsed.lines.filter((l) => (next === undefined || l.event.seq < next.first) && (!fenced || l.event.seq <= S));
938
+ const framed = frameJournal(kept, f.name, f.first);
939
+ if (next !== undefined) {
940
+ if (framed.droppedIncomplete > 0) {
941
+ throw new ExecutorError("E_SEQ_GAP", `journal ${f.name} ends inside a batch before the next journal starts`, { file: f.name });
942
+ }
943
+ } else {
944
+ if (parsed.torn) {
945
+ dirty = true;
946
+ warnings.push(`${f.name}: torn last line dropped`);
947
+ }
948
+ if (framed.droppedIncomplete > 0) {
949
+ dirty = true;
950
+ warnings.push(`${f.name}: incomplete trailing batch dropped (${framed.droppedIncomplete} events, incomplete-batch)`);
951
+ }
952
+ }
953
+ let fileStart = true;
954
+ for (const l of framed.lines) {
955
+ const prev = events[events.length - 1];
956
+ // Only the first line of a file is checked against the previous file's tail; inside a file `frameJournal` decides.
957
+ if (fileStart && prev !== undefined && (l.event.seq !== prev.event.seq + 1 || !prev.event.last)) {
958
+ throw new ExecutorError("E_SEQ_GAP", `seq ${l.event.seq} follows ${prev.event.seq} across journal files`, { file: f.name });
959
+ }
960
+ fileStart = false;
961
+ events.push(l);
962
+ }
963
+ }
964
+
965
+ const after = events.filter((l) => l.event.seq > S);
966
+ const first = after[0];
967
+ let ledger: LedgerV1;
968
+ let rest: JournalLine[];
969
+ if (snapshot === null) {
970
+ if (first === undefined) throw new ExecutorError("E_LEDGER_NOT_FOUND", `no complete ledger-init in ${dir}`);
971
+ const e = first.event;
972
+ if (e.type !== "ledger-init" || e.seq !== 1 || e.batch !== 1 || !e.last) {
973
+ throw new ExecutorError("E_SEQ_GAP", "journal does not start with a lone ledger-init at seq 1", eventRef(e));
974
+ }
975
+ ledger = initLedger(e);
976
+ if (ledger.seq !== 1) throw illegal(e, "ledger-init-seq");
977
+ rest = after.slice(1);
978
+ } else {
979
+ if (first !== undefined && first.event.seq !== S + 1) {
980
+ throw mismatch(`snapshot is at seq ${S} but the journal continues at seq ${first.event.seq}`);
981
+ }
982
+ ledger = snapshot;
983
+ rest = after;
984
+ }
985
+ let ctx = newBatchCtx();
986
+ for (const l of rest) {
987
+ const e = l.event;
988
+ if (e.batch === e.seq) ctx = newBatchCtx();
989
+ const code = applyEvent(ledger, e, ctx);
990
+ if (code !== null) throw illegal(e, code);
991
+ if (e.last) {
992
+ const v = batchEndViolation(ledger, ctx);
993
+ if (v !== null) throw illegal(e, v.code, v.codes);
994
+ }
995
+ }
996
+ return { ledger, snapshotSeq: S, snapshotEpoch, files, events, dirty, warnings };
997
+ }
998
+
999
+ /** Retries `loadMain` while the snapshot and the journal listing disagree (a reader racing a rotation). */
1000
+ async function loadMainConsistent(fs: FileSystem, clock: Clock, dir: string): Promise<MainState> {
1001
+ let last = "";
1002
+ for (let attempt = 0; attempt < READ_RETRIES; attempt++) {
1003
+ try {
1004
+ return await loadMain(fs, dir, "reader");
1005
+ } catch (e) {
1006
+ if (!(e instanceof SnapshotMismatch)) throw e;
1007
+ last = e.message;
1008
+ await sleep(clock, 5 * (attempt + 1));
1009
+ }
1010
+ }
1011
+ throw new ExecutorError("E_SEQ_GAP", `snapshot and journal never agreed: ${last}`);
1012
+ }
1013
+
1014
+ // ---------------------------------------------------------------------------------------------------------------
1015
+ // History journal (A1-3).
1016
+ // ---------------------------------------------------------------------------------------------------------------
1017
+
1018
+ interface HistoryLoad {
1019
+ /** Valid lines to keep (seq <= the ledger's seq), then the lines repaired from the main journal. */
1020
+ kept: JournalLine[];
1021
+ added: JournalLine[];
1022
+ /** The file has torn bytes or events beyond the main journal: it must be rewritten, not appended to. */
1023
+ rewrite: boolean;
1024
+ }
1025
+
1026
+ async function loadHistory(fs: FileSystem, dir: string, ledgerSeq: number, main: readonly JournalLine[]): Promise<HistoryLoad> {
1027
+ const text = (await readOptional(fs, join(dir, HISTORY_FILE))) ?? "";
1028
+ const parsed = parseJournal(text, HISTORY_FILE);
1029
+ const { kept, repaired } = repairHistory(parsed.lines, ledgerSeq, main);
1030
+ const have = new Set(kept.map((l) => l.event.seq));
1031
+ const lastSeq = kept.length === 0 ? 0 : (kept[kept.length - 1] as JournalLine).event.seq;
1032
+ const added = main.filter((l) => isHistoryEvent(l.event) && l.event.seq <= ledgerSeq && !have.has(l.event.seq));
1033
+ const appendOnly = added.every((l) => l.event.seq > lastSeq);
1034
+ return { kept, added, rewrite: parsed.torn || repaired || !appendOnly };
1035
+ }
1036
+
1037
+ /**
1038
+ * Validates history lines against the main journal (A1-3, QA-2.2-2). Lines must strictly increase; a line beyond `ledgerSeq`, or an exact
1039
+ * duplicate of a kept line (a fenced writer's late copy of an event the new writer copied too), is dropped. At or after the main
1040
+ * journal's last `lock-takeover`, a line that does not match the main journal's event at its seq, or that is out of order, is a fenced
1041
+ * writer's late copy and is dropped too. Any other out-of-order line is corruption (E_SEQ_GAP). Pure: readers use it as well.
1042
+ */
1043
+ function repairHistory(
1044
+ lines: readonly JournalLine[],
1045
+ ledgerSeq: number,
1046
+ main: readonly JournalLine[],
1047
+ ): { kept: JournalLine[]; repaired: boolean } {
1048
+ const mainBySeq = new Map<number, JournalLine>();
1049
+ let takeoverSeq = 0;
1050
+ for (const l of main) {
1051
+ if (l.event.seq > ledgerSeq) continue;
1052
+ mainBySeq.set(l.event.seq, l);
1053
+ if (l.event.type === "lock-takeover") takeoverSeq = Math.max(takeoverSeq, l.event.seq);
1054
+ }
1055
+ const kept: JournalLine[] = [];
1056
+ const keptText = new Map<number, string>();
1057
+ let repaired = false;
1058
+ for (const l of lines) {
1059
+ const seq = l.event.seq;
1060
+ if (seq > ledgerSeq || keptText.get(seq) === l.text) {
1061
+ repaired = true;
1062
+ continue;
1063
+ }
1064
+ const afterTakeover = takeoverSeq > 0 && seq >= takeoverSeq;
1065
+ const m = mainBySeq.get(seq);
1066
+ if (afterTakeover && m !== undefined && (m.text !== l.text || !isHistoryEvent(m.event))) {
1067
+ repaired = true;
1068
+ continue;
1069
+ }
1070
+ const prev = kept[kept.length - 1];
1071
+ if (prev !== undefined && seq <= prev.event.seq) {
1072
+ if (afterTakeover) {
1073
+ repaired = true;
1074
+ continue;
1075
+ }
1076
+ throw new ExecutorError("E_SEQ_GAP", `history ${HISTORY_FILE}: seq ${seq} follows ${prev.event.seq}`, { file: HISTORY_FILE, seq });
1077
+ }
1078
+ kept.push(l);
1079
+ keptText.set(seq, l.text);
1080
+ }
1081
+ return { kept, repaired };
1082
+ }
1083
+
1084
+ function trackerOf(lines: readonly JournalLine[]): HistoryTracker {
1085
+ const t = new HistoryTracker();
1086
+ for (const l of lines) {
1087
+ const code = t.apply(l.event);
1088
+ if (code !== null) throw illegal(l.event, code);
1089
+ }
1090
+ return t;
1091
+ }
1092
+
1093
+ // ---------------------------------------------------------------------------------------------------------------
1094
+ // The writer.
1095
+ // ---------------------------------------------------------------------------------------------------------------
1096
+
1097
+ interface WriterEnv {
1098
+ observations?: import("../compat/v2-observations").V2Observations;
1099
+ fs: FileSystem;
1100
+ clock: Clock;
1101
+ proc: LedgerProcessInfo;
1102
+ warn: (message: string) => void;
1103
+ dir: string;
1104
+ heartbeatMs: number;
1105
+ staleMs: number;
1106
+ snapshotEvery: number;
1107
+ }
1108
+
1109
+ interface WriterInit {
1110
+ planId: PlanId;
1111
+ ledger: LedgerV1;
1112
+ tracker: HistoryTracker;
1113
+ lock: LockRecord;
1114
+ /** The snapshot file holds this seq. */
1115
+ snapshotSeq: number;
1116
+ /** The writer epoch of that snapshot file (0 when there is none). */
1117
+ snapshotEpoch: number;
1118
+ /** Journal file to append to, and its first seq. */
1119
+ journal: JournalFile | null;
1120
+ /** The journal file cannot be appended to (torn tail) and must be replaced by a rotation. */
1121
+ needsRotate: boolean;
1122
+ /** The journal was created and fsynced by this call and holds exactly the events up to the snapshot (a plan just created). */
1123
+ journalFresh?: boolean;
1124
+ }
1125
+
1126
+ class StoreWriter implements LedgerWriter {
1127
+ readonly planId: PlanId;
1128
+ private current: LedgerV1;
1129
+ private tracker: HistoryTracker;
1130
+ private readonly lock: LockRecord;
1131
+ private lastSnapshotSeq: number;
1132
+ /** Epoch of the newest snapshot file on disk; below this writer's epoch until it writes its own. */
1133
+ private lastSnapshotEpoch: number;
1134
+ private journal: JournalFile | null;
1135
+ private needsRotate: boolean;
1136
+ private journalFresh: boolean;
1137
+ /** Appends since the last fsync of the active journal (a snapshot must not outrun the journal on disk). */
1138
+ private journalUnsynced = false;
1139
+ /** Live view returned by `wakeKeys()`: updated in place on every commit. */
1140
+ private readonly wakeView: Set<string>;
1141
+ private eventsSince = 0;
1142
+ private pendingHistory: string[] = [];
1143
+ private historyDirty = false;
1144
+ private historyUnsynced = true;
1145
+ private lost = false;
1146
+ private closed = false;
1147
+ private chain: Promise<void> = Promise.resolve();
1148
+ private timer: { readonly id: number } | null = null;
1149
+
1150
+ constructor(private readonly env: WriterEnv, init: WriterInit) {
1151
+ this.planId = init.planId;
1152
+ this.current = init.ledger;
1153
+ this.tracker = init.tracker;
1154
+ this.lock = init.lock;
1155
+ this.lastSnapshotSeq = init.snapshotSeq;
1156
+ this.lastSnapshotEpoch = init.snapshotEpoch;
1157
+ this.journal = init.journal;
1158
+ this.needsRotate = init.needsRotate;
1159
+ this.journalFresh = init.journalFresh === true;
1160
+ this.wakeView = new Set(init.tracker.wakeKeys());
1161
+ }
1162
+
1163
+ get ledger(): Readonly<LedgerV1> {
1164
+ return this.current;
1165
+ }
1166
+
1167
+ /** Stops the heartbeat and refuses further use without touching the files or the lock (a failed open/takeover). */
1168
+ abandon(): void {
1169
+ this.closed = true;
1170
+ this.disarmHeartbeat();
1171
+ }
1172
+
1173
+ openIntegration(): readonly OpenIntegrationEntry[] {
1174
+ return this.tracker.openEntries();
1175
+ }
1176
+
1177
+ /** A live view: the same set is returned every time and keys are added to it in place when a batch commits. */
1178
+ wakeKeys(): ReadonlySet<string> {
1179
+ return this.wakeView;
1180
+ }
1181
+
1182
+ /** Serialises `fn` after every earlier call; a failure does not poison the chain. */
1183
+ private serial<T>(fn: () => Promise<T>): Promise<T> {
1184
+ const run = this.chain.then(fn);
1185
+ this.chain = run.then(() => undefined, () => undefined);
1186
+ return run;
1187
+ }
1188
+
1189
+ /** Brings a freshly built writer to a clean state (snapshot + rotation when the journal tail is unusable) and starts the heartbeat. */
1190
+ start(): Promise<void> {
1191
+ return this.serial(async () => {
1192
+ // Before any snapshot, rotation, deletion or history rewrite: a writer that was taken over while loading must not touch anything.
1193
+ await this.verifyLock();
1194
+ if (this.rotationNeeded()) await this.snapshotNow();
1195
+ this.armHeartbeat();
1196
+ });
1197
+ }
1198
+
1199
+ /** The snapshot is behind, the journal tail is unusable, or the active file is not this epoch's `events.(S+1).*` (QA-2.2-6). */
1200
+ private rotationNeeded(): boolean {
1201
+ const j = this.journal;
1202
+ if (this.needsRotate || j === null || this.lastSnapshotSeq !== this.current.seq || j.epoch !== this.lock.epoch) return true;
1203
+ if (this.lastSnapshotEpoch !== this.lock.epoch) return true;
1204
+ return j.first !== this.lastSnapshotSeq + 1 && !this.journalFresh;
1205
+ }
1206
+
1207
+ /**
1208
+ * Appends one batch. A rejection with `E_LOCK_LOST` means the OUTCOME IS UNKNOWN: the batch may or may not be visible to the next writer
1209
+ * (it is fenced only when the takeover happened before that writer loaded the journal), so the caller reads the ledger back from the new
1210
+ * owner instead of retrying. Any other rejection from the post-write lock check leaves the batch on disk and the writer rotates past it.
1211
+ */
1212
+ append(batch: readonly ExecutorEventInput[] | BatchBuilder): Promise<Readonly<LedgerV1>> {
1213
+ return this.serial(() => this.appendNow(batch));
1214
+ }
1215
+
1216
+ snapshot(): Promise<void> {
1217
+ return this.serial(async () => {
1218
+ this.assertUsable();
1219
+ await this.verifyLock();
1220
+ await this.snapshotNow();
1221
+ });
1222
+ }
1223
+
1224
+ close(): Promise<void> {
1225
+ return this.serial(async () => {
1226
+ if (this.closed) return;
1227
+ let failure: unknown = null;
1228
+ if (!this.lost) {
1229
+ try {
1230
+ await this.verifyLock();
1231
+ await this.snapshotNow();
1232
+ } catch (e) {
1233
+ failure = e;
1234
+ }
1235
+ }
1236
+ this.closed = true;
1237
+ this.disarmHeartbeat();
1238
+ if (!this.lost) await this.releaseLock();
1239
+ if (failure !== null && !(failure instanceof ExecutorError && failure.code === "E_LOCK_LOST")) throw failure;
1240
+ });
1241
+ }
1242
+
1243
+ // -- append ------------------------------------------------------------------------------------------------
1244
+
1245
+ private assertUsable(): void {
1246
+ if (this.closed) throw new ExecutorError("E_DISPOSED", `ledger writer for ${this.planId} is closed`);
1247
+ if (this.lost) throw new ExecutorError("E_LOCK_LOST", `writer lock for ${this.planId} was lost`);
1248
+ }
1249
+
1250
+ private async appendNow(input: readonly ExecutorEventInput[] | BatchBuilder): Promise<Readonly<LedgerV1>> {
1251
+ this.assertUsable();
1252
+ await this.verifyLock();
1253
+ if (this.needsRotate) await this.snapshotNow();
1254
+ const inputs = typeof input === "function" ? input(this.current) : input;
1255
+ if (inputs.length === 0) return this.current;
1256
+
1257
+ const first = this.current.seq + 1;
1258
+ const at = this.env.clock.iso();
1259
+ // What is validated and applied is exactly what is written: serialise first, then parse the text back.
1260
+ const lines: string[] = [];
1261
+ const events: ExecutorEvent[] = [];
1262
+ inputs.forEach((inp, i) => {
1263
+ const draft = { ...inp, seq: first + i, at, batch: first, last: i === inputs.length - 1 };
1264
+ let text: string;
1265
+ try {
1266
+ text = JSON.stringify(draft);
1267
+ } catch (e) {
1268
+ throw new ExecutorError("E_INVALID_INPUT", `event ${i} of the batch is not serialisable: ${errMessage(e)}`, { eventIndex: i });
1269
+ }
1270
+ lines.push(text);
1271
+ events.push(JSON.parse(text) as ExecutorEvent);
1272
+ });
1273
+
1274
+ const work = structuredClone(this.current);
1275
+ const tracker = this.tracker.clone();
1276
+ const ctx = newBatchCtx();
1277
+ for (let i = 0; i < events.length; i++) {
1278
+ const ev = events[i] as ExecutorEvent;
1279
+ const code = applyEvent(work, ev, ctx) ?? (isHistoryEvent(ev) ? tracker.apply(ev) : null);
1280
+ if (code !== null) {
1281
+ throw new ExecutorError("E_ILLEGAL_TRANSITION", `batch ${first}: event ${i} (${ev.type}) is illegal: ${code}`, {
1282
+ batchIndex: first,
1283
+ eventIndex: i,
1284
+ codes: [code],
1285
+ });
1286
+ }
1287
+ }
1288
+ const end = batchEndViolation(work, ctx);
1289
+ if (end !== null) {
1290
+ throw new ExecutorError("E_ILLEGAL_TRANSITION", `batch ${first} leaves the ledger invalid: ${end.codes.join(", ")}`, {
1291
+ batchIndex: first,
1292
+ eventIndex: null,
1293
+ codes: end.codes,
1294
+ });
1295
+ }
1296
+ // A1-3a: `integrating` needs an open entry unless the task's last entry closed rolled-back. A batch must not create such a task; one
1297
+ // that already was (only a hand-made draft can start that way, and open refuses it) does not block unrelated batches.
1298
+ const before = new Set(this.tracker.integratingWithoutEntry(this.current));
1299
+ const orphan = tracker.integratingWithoutEntry(work).find((id) => !before.has(id));
1300
+ if (orphan !== undefined) {
1301
+ throw new ExecutorError("E_ILLEGAL_TRANSITION", `batch ${first} leaves task ${orphan} integrating with no open integration entry`, {
1302
+ batchIndex: first,
1303
+ eventIndex: null,
1304
+ codes: ["integrating-without-entry"],
1305
+ taskId: orphan,
1306
+ });
1307
+ }
1308
+
1309
+ const durable = inputs.some(isDurableEvent);
1310
+ const journal = await this.ensureJournal();
1311
+ try {
1312
+ // Never create the journal here: a missing file means a takeover rotated it away, so this writer is fenced (QA-2.2-24).
1313
+ const opts: AppendOptions = { fsync: durable, create: false };
1314
+ await this.env.fs.appendText(join(this.env.dir, journal.name), `${lines.join("\n")}\n`, opts);
1315
+ this.journalUnsynced = !durable;
1316
+ } catch (e) {
1317
+ // The file may now end in a partial batch: never append to it again.
1318
+ this.needsRotate = true;
1319
+ if (fsErrorCode(e) === "ENOENT") {
1320
+ throw new ExecutorError("E_LOCK_LOST", `journal ${journal.name} no longer exists: the writer lock was taken over`);
1321
+ }
1322
+ throw e;
1323
+ }
1324
+ // A takeover between the lock check and the write fences this batch, but the new owner may have loaded before or after the write: the
1325
+ // outcome of a batch that fails with E_LOCK_LOST is unknown (it may or may not be visible), and the caller must not believe it committed.
1326
+ // Any other failure of this check leaves the batch on disk while `current` stays behind: the next append must rotate past it.
1327
+ try {
1328
+ await this.verifyLock();
1329
+ } catch (e) {
1330
+ this.needsRotate = true;
1331
+ throw e;
1332
+ }
1333
+ this.current = work;
1334
+ if (this.env.observations !== undefined) {
1335
+ observeSchedulerLedger(this.env.observations, work, "ledger");
1336
+ }
1337
+ this.tracker = tracker;
1338
+ this.eventsSince += events.length;
1339
+ for (const k of tracker.wakeKeys()) this.wakeView.add(k);
1340
+
1341
+ events.forEach((ev, i) => {
1342
+ if (isHistoryEvent(ev)) this.pendingHistory.push(lines[i] as string);
1343
+ });
1344
+ await this.flushHistory(durable, false);
1345
+
1346
+ if (this.eventsSince >= this.env.snapshotEvery) {
1347
+ try {
1348
+ await this.snapshotNow();
1349
+ } catch (e) {
1350
+ this.env.warn(`snapshot of ${this.planId} at seq ${this.current.seq} failed, will retry: ${errMessage(e)}`);
1351
+ }
1352
+ }
1353
+ return this.current;
1354
+ }
1355
+
1356
+ private async ensureJournal(): Promise<JournalFile> {
1357
+ if (this.journal === null) await this.snapshotNow();
1358
+ if (this.journal === null) throw new ExecutorError("E_LEDGER_NOT_FOUND", `no journal file for ${this.planId}`);
1359
+ return this.journal;
1360
+ }
1361
+
1362
+ // -- history ------------------------------------------------------------------------------------------------
1363
+
1364
+ /** Writes pending history copies after the main journal. A failure is remembered (main is the authority) and retried by a rewrite. */
1365
+ private async flushHistory(fsync: boolean, strict: boolean): Promise<void> {
1366
+ const path = join(this.env.dir, HISTORY_FILE);
1367
+ try {
1368
+ // Every caller verified the lock just before; the rewrite re-checks it again immediately before its rename.
1369
+ if (this.historyDirty) {
1370
+ await this.rewriteHistory();
1371
+ this.historyDirty = false;
1372
+ this.historyUnsynced = false;
1373
+ return;
1374
+ }
1375
+ if (this.pendingHistory.length > 0) {
1376
+ await this.env.fs.appendText(path, `${this.pendingHistory.join("\n")}\n`, { fsync });
1377
+ this.pendingHistory = [];
1378
+ this.historyUnsynced = !fsync;
1379
+ } else if (fsync && this.historyUnsynced) {
1380
+ await this.env.fs.appendText(path, "", { fsync: true });
1381
+ this.historyUnsynced = false;
1382
+ }
1383
+ } catch (e) {
1384
+ if (e instanceof ExecutorError && e.code === "E_LOCK_LOST") throw e; // fenced: never repair history from a lost lock
1385
+ this.historyDirty = true;
1386
+ if (strict) throw e;
1387
+ this.env.warn(`history copy for ${this.planId} failed, will be repaired: ${errMessage(e)}`);
1388
+ }
1389
+ }
1390
+
1391
+ /** Rebuilds history.jsonl from what it holds (minus a torn tail) plus the pending copies, through a temp file. */
1392
+ private async rewriteHistory(): Promise<void> {
1393
+ const { fs, dir } = this.env;
1394
+ const text = (await readOptional(fs, join(dir, HISTORY_FILE))) ?? "";
1395
+ const parsed = parseJournal(text, HISTORY_FILE);
1396
+ const have = parsed.lines.filter((l) => l.event.seq <= this.current.seq);
1397
+ const lastSeq = have.length === 0 ? 0 : (have[have.length - 1] as JournalLine).event.seq;
1398
+ const pending = this.pendingHistory.filter((t) => (JSON.parse(t) as { seq: number }).seq > lastSeq);
1399
+ await writeHistoryFile(this.env, [...have.map((l) => l.text), ...pending], () => this.verifyLock());
1400
+ this.pendingHistory = [];
1401
+ }
1402
+
1403
+ // -- snapshot and rotation --------------------------------------------------------------------------------
1404
+
1405
+ private makeJournal(first: number): JournalFile {
1406
+ return { name: journalName(first, this.lock.epoch), first, epoch: this.lock.epoch };
1407
+ }
1408
+
1409
+ /**
1410
+ * Snapshot at the current seq (a batch boundary), then rotate: the new journal file exists before the old ones are deleted, and a
1411
+ * journal file is only authoritative below the next file's first seq, so a late write to an old file is never read.
1412
+ */
1413
+ private async snapshotNow(): Promise<void> {
1414
+ const { fs, dir, clock } = this.env;
1415
+ const N = this.current.seq;
1416
+ if (!this.rotationNeeded()) return;
1417
+ await this.flushHistory(true, true);
1418
+ // A writer always writes its own epoch's snapshot, even when nothing was appended since the previous one: the loader takes the highest
1419
+ // epoch, and a fenced writer's late rename can only land on its own (lower) epoch's name.
1420
+ if (N !== this.lastSnapshotSeq || this.lastSnapshotEpoch !== this.lock.epoch) {
1421
+ if (this.journalUnsynced && this.journal !== null) {
1422
+ // The snapshot must not outrun the journal on disk: a crash would leave a snapshot ahead of a journal that lost its tail.
1423
+ await this.verifyLock();
1424
+ await fs.appendText(join(dir, this.journal.name), "", { fsync: true });
1425
+ this.journalUnsynced = false;
1426
+ }
1427
+ const name = snapshotName(this.lock.epoch);
1428
+ const tmp = join(dir, `${name}.tmp-${this.env.proc.pid}-${clock.randomHex(4)}`);
1429
+ try {
1430
+ await fs.writeText(tmp, JSON.stringify(this.current), { fsync: true });
1431
+ await this.verifyLock(); // immediately before the rename that publishes the snapshot
1432
+ await retryBusy(clock, () => fs.rename(tmp, join(dir, name)));
1433
+ } catch (e) {
1434
+ await this.discardTemp(tmp);
1435
+ throw e;
1436
+ }
1437
+ await fs.fsyncDir(dir);
1438
+ this.lastSnapshotSeq = N;
1439
+ this.lastSnapshotEpoch = this.lock.epoch;
1440
+ await this.deleteLowerSnapshots();
1441
+ }
1442
+ const next = this.makeJournal(N + 1);
1443
+ await this.createJournal(next);
1444
+ await fs.fsyncDir(dir);
1445
+ this.journal = next;
1446
+ this.journalFresh = false;
1447
+ this.journalUnsynced = false;
1448
+ this.needsRotate = false;
1449
+ this.eventsSince = 0;
1450
+ await this.deleteOldJournals(next);
1451
+ }
1452
+
1453
+ /**
1454
+ * Creates the next journal file exclusively. An existing file is reused only when it is empty, or when it is this writer's own active file
1455
+ * after a failed append (then it is replaced); any other content under this epoch's name is foreign and refused.
1456
+ */
1457
+ private async createJournal(next: JournalFile): Promise<void> {
1458
+ const { fs, dir } = this.env;
1459
+ const path = join(dir, next.name);
1460
+ await this.verifyLock();
1461
+ try {
1462
+ await fs.writeText(path, "", { exclusive: true, fsync: true });
1463
+ return;
1464
+ } catch (e) {
1465
+ if (fsErrorCode(e) !== "EEXIST") throw e;
1466
+ }
1467
+ const existing = await readOptional(fs, path);
1468
+ if (existing === "") return;
1469
+ if (this.journal === null || this.journal.name !== next.name) {
1470
+ throw new ExecutorError("E_SEQ_GAP", `journal ${next.name} already exists with content`, { file: next.name });
1471
+ }
1472
+ await this.verifyLock();
1473
+ await rmQuiet(fs, path);
1474
+ await fs.writeText(path, "", { exclusive: true, fsync: true });
1475
+ }
1476
+
1477
+ private async discardTemp(path: string): Promise<void> {
1478
+ try {
1479
+ await rmQuiet(this.env.fs, path);
1480
+ } catch (e) {
1481
+ this.env.warn(`could not remove temp file ${path}: ${errMessage(e)}`);
1482
+ }
1483
+ }
1484
+
1485
+ /**
1486
+ * Deletes journal files superseded by `keep` (an earlier first seq, or an older epoch, which includes a fenced writer's late files); only
1487
+ * after a successful snapshot. The lock is re-checked before every delete. A failure only leaves superseded files behind.
1488
+ */
1489
+ private async deleteOldJournals(keep: JournalFile): Promise<void> {
1490
+ const { fs, dir } = this.env;
1491
+ let names: string[];
1492
+ try {
1493
+ names = await fs.readdir(dir);
1494
+ } catch (e) {
1495
+ this.env.warn(`could not list ${dir}: ${errMessage(e)}`);
1496
+ return;
1497
+ }
1498
+ const doomed: string[] = [];
1499
+ for (const name of names) {
1500
+ const m = JOURNAL_PATTERN.exec(name);
1501
+ if (m === null || name === keep.name) continue;
1502
+ if (Number(m[1]) >= keep.first && Number(m[2]) >= keep.epoch) continue;
1503
+ doomed.push(name);
1504
+ }
1505
+ if (doomed.length === 0) return;
1506
+ // The journals are the authority for history: a fenced writer's late history rewrite may have dropped lines that only these files
1507
+ // still hold. Repair history from them first; when that cannot be done, the files stay.
1508
+ try {
1509
+ await this.repairHistoryFromJournals(names, keep);
1510
+ } catch (e) {
1511
+ if (e instanceof ExecutorError && e.code === "E_LOCK_LOST") throw e;
1512
+ this.env.warn(`history of ${this.planId} could not be verified, old journals kept: ${errMessage(e)}`);
1513
+ return;
1514
+ }
1515
+ for (const name of doomed) {
1516
+ await this.verifyLock();
1517
+ try {
1518
+ await rmQuiet(fs, join(dir, name));
1519
+ } catch (e) {
1520
+ this.env.warn(`could not delete old journal ${name}: ${errMessage(e)}`);
1521
+ }
1522
+ }
1523
+ }
1524
+
1525
+ /** Re-runs the history repair over the trusted journal files about to be deleted and rewrites `history.jsonl` when anything is missing. */
1526
+ private async repairHistoryFromJournals(names: readonly string[], keep: JournalFile): Promise<void> {
1527
+ const { fs, dir } = this.env;
1528
+ const N = this.current.seq;
1529
+ const { chain } = trustedChain(journalsOf(names));
1530
+ // Same trust rules as `loadMain`: a file of an older epoch than the newest snapshot counts only up to that snapshot's seq.
1531
+ const newest = newestSnapshotEpoch(names);
1532
+ let snapshotSeq = N;
1533
+ if (newest !== null) {
1534
+ const snapName = snapshotName(newest);
1535
+ const snapText = await readOptional(fs, join(dir, snapName));
1536
+ if (snapText !== null) snapshotSeq = Math.min(N, checkLedger(parseSnapshot(snapText, snapName), snapName).seq);
1537
+ }
1538
+ const snapshotEpoch = newest ?? 0;
1539
+ const lines: JournalLine[] = [];
1540
+ for (let i = 0; i < chain.length; i++) {
1541
+ const f = chain[i] as JournalFile;
1542
+ if (f.name === keep.name) continue;
1543
+ const next = chain[i + 1];
1544
+ const text = await readOptional(fs, join(dir, f.name));
1545
+ if (text === null) continue;
1546
+ const fenced = f.epoch < snapshotEpoch;
1547
+ const kept = parseJournal(text, f.name).lines.filter(
1548
+ (l) => l.event.seq <= N && (next === undefined || l.event.seq < next.first) && (!fenced || l.event.seq <= snapshotSeq),
1549
+ );
1550
+ // Framing per file against the first seq in its name; an incomplete trailing batch is never history.
1551
+ for (const l of frameJournal(kept, f.name, f.first).lines) lines.push(l);
1552
+ }
1553
+ const hl = await loadHistory(fs, dir, N, lines);
1554
+ if (!hl.rewrite && hl.added.length === 0) return;
1555
+ const all = [...hl.kept, ...hl.added].sort((x, y) => x.event.seq - y.event.seq);
1556
+ await writeHistoryFile(this.env, all.map((l) => l.text), () => this.verifyLock());
1557
+ }
1558
+
1559
+ /** Deletes the snapshot files of lower epochs; only called once this writer's own snapshot is renamed into place and the directory synced. */
1560
+ private async deleteLowerSnapshots(): Promise<void> {
1561
+ const { fs, dir } = this.env;
1562
+ let names: string[];
1563
+ try {
1564
+ names = await fs.readdir(dir);
1565
+ } catch (e) {
1566
+ this.env.warn(`could not list ${dir}: ${errMessage(e)}`);
1567
+ return;
1568
+ }
1569
+ for (const name of names) {
1570
+ const m = SNAPSHOT_PATTERN.exec(name);
1571
+ if (m === null || Number(m[1]) >= this.lock.epoch) continue;
1572
+ await this.verifyLock();
1573
+ try {
1574
+ await rmQuiet(fs, join(dir, name));
1575
+ } catch (e) {
1576
+ this.env.warn(`could not delete old snapshot ${name}: ${errMessage(e)}`);
1577
+ }
1578
+ }
1579
+ }
1580
+
1581
+ // -- lock ---------------------------------------------------------------------------------------------------
1582
+
1583
+ /** Fails with E_LOCK_LOST (and stays failed) when the lock file no longer names this writer. */
1584
+ private async verifyLock(): Promise<void> {
1585
+ try {
1586
+ await assertLockHeld({ fs: this.env.fs, dir: this.env.dir, planId: this.planId }, this.lock);
1587
+ } catch (e) {
1588
+ if (e instanceof ExecutorError && e.code === "E_LOCK_LOST") {
1589
+ this.lost = true;
1590
+ this.disarmHeartbeat();
1591
+ }
1592
+ throw e;
1593
+ }
1594
+ }
1595
+
1596
+ /** Removes `writer.lock` only while it still names this writer (a foreign lock is never deleted), and this writer's beat file. */
1597
+ private async releaseLock(): Promise<void> {
1598
+ const { fs, dir } = this.env;
1599
+ try {
1600
+ const text = await readOptional(fs, join(dir, LOCK_FILE));
1601
+ const holder = text === null ? null : parseLockText(text);
1602
+ if (holder !== null && sameLockIdentity(holder, this.lock)) await rmQuiet(fs, join(dir, LOCK_FILE));
1603
+ await rmQuiet(fs, join(dir, beatFileName(this.lock.token)));
1604
+ } catch (e) {
1605
+ this.env.warn(`could not release the lock of ${this.planId}: ${errMessage(e)}`);
1606
+ }
1607
+ }
1608
+
1609
+ private armHeartbeat(): void {
1610
+ if (this.closed || this.lost || this.timer !== null) return;
1611
+ this.timer = this.env.clock.setTimer(this.env.heartbeatMs, () => {
1612
+ this.timer = null;
1613
+ this.serial(() => this.beat()).then(
1614
+ () => this.armHeartbeat(),
1615
+ (e: unknown) => {
1616
+ this.env.warn(`heartbeat of ${this.planId} failed: ${errMessage(e)}`);
1617
+ this.armHeartbeat();
1618
+ },
1619
+ );
1620
+ });
1621
+ }
1622
+
1623
+ private disarmHeartbeat(): void {
1624
+ if (this.timer !== null) {
1625
+ this.env.clock.clearTimer(this.timer);
1626
+ this.timer = null;
1627
+ }
1628
+ }
1629
+
1630
+ private async beat(): Promise<void> {
1631
+ if (this.closed || this.lost) return;
1632
+ await this.verifyLock();
1633
+ // The heartbeat never rewrites writer.lock (a late rename could restore a lock a takeover replaced): it stamps this holder's own
1634
+ // beat file, which only this holder writes and which `isStale` reads.
1635
+ await writeBeatFile(this.env, this.lock);
1636
+ }
1637
+ }
1638
+
1639
+ /** Atomically (temp + rename) stamps `writer.<token>.beat` with the current time. Only the holder named by `lock` writes this file. */
1640
+ async function writeBeatFile(env: WriterEnv, lock: LockRecord): Promise<void> {
1641
+ const { fs, clock, dir } = env;
1642
+ const path = join(dir, beatFileName(lock.token));
1643
+ const tmp = `${path}.tmp-${env.proc.pid}-${clock.randomHex(4)}`;
1644
+ try {
1645
+ await fs.writeText(tmp, JSON.stringify({ heartbeatAt: clock.iso() }), { fsync: true });
1646
+ await retryBusy(clock, () => fs.rename(tmp, path));
1647
+ } catch (e) {
1648
+ try {
1649
+ await rmQuiet(fs, tmp);
1650
+ } catch (cleanup) {
1651
+ env.warn(`could not remove temp beat ${tmp}: ${errMessage(cleanup)}`);
1652
+ }
1653
+ throw e;
1654
+ }
1655
+ }
1656
+
1657
+ /**
1658
+ * Replaces history.jsonl with exactly `texts` (one event per entry), through a temp file. `beforeRename` runs immediately before the
1659
+ * rename (the caller re-checks its lock there).
1660
+ */
1661
+ async function writeHistoryFile(env: WriterEnv, texts: readonly string[], beforeRename: () => Promise<void>): Promise<void> {
1662
+ const { fs, clock, dir } = env;
1663
+ const tmp = join(dir, `${HISTORY_FILE}.tmp-${env.proc.pid}-${clock.randomHex(4)}`);
1664
+ try {
1665
+ await fs.writeText(tmp, texts.length === 0 ? "" : `${texts.join("\n")}\n`, { fsync: true });
1666
+ await beforeRename();
1667
+ await retryBusy(clock, () => fs.rename(tmp, join(dir, HISTORY_FILE)));
1668
+ } catch (e) {
1669
+ try {
1670
+ await rmQuiet(fs, tmp);
1671
+ } catch (cleanup) {
1672
+ env.warn(`could not remove temp history ${tmp}: ${errMessage(cleanup)}`);
1673
+ }
1674
+ throw e;
1675
+ }
1676
+ await fs.fsyncDir(dir);
1677
+ }
1678
+
1679
+ // ---------------------------------------------------------------------------------------------------------------
1680
+ // The store.
1681
+ // ---------------------------------------------------------------------------------------------------------------
1682
+
1683
+ function noWarn(): void {
1684
+ // Warnings are dropped unless the caller supplies a sink.
1685
+ }
1686
+
1687
+ /**
1688
+ * `LedgerStore` over the injected seams (2.2.2). One writer per plan holds `writer.lock` (pid, host, session, heartbeat); readers
1689
+ * (`read`, `list`, `exportPlan`) never take it. All files of a plan live in `planDir(home, planId)`:
1690
+ * `ledger.<epoch>.json` (snapshot, one per writer epoch: the loader takes the highest, so a fenced writer's late rename lands on its
1691
+ * own older name; a writer deletes lower-epoch snapshots only after its own is in place), `events.<firstSeq>.<epoch>.jsonl` (journal, rotated at snapshots; every writer, takeovers included, starts a
1692
+ * new file under a new writer epoch and only the newest epoch's files are trusted), `history.jsonl` (never rotated), `writer.lock`
1693
+ * (written once per holder: pid, host, session, store-stamped token and epoch) and `writer.<token>.beat` (the holder's heartbeat).
1694
+ *
1695
+ * `takeover` replaces a stale lock. A live holder is refused (E_LOCK_HELD) unless `reason` is exactly {@link ADOPT_TAKEOVER_REASON} and
1696
+ * the live holder is this same process (pid and host); that exception stands until fencing proves an older writer out.
1697
+ */
1698
+ export function createLedgerStore(deps: LedgerStoreDeps): LedgerStore {
1699
+ const fs = deps.fs ?? createNodeFileSystem();
1700
+ const clock = deps.clock ?? createNodeClock();
1701
+ const proc = deps.proc ?? createNodeProcessInfo();
1702
+ const warn = deps.warn ?? noWarn;
1703
+ const heartbeatMs = deps.heartbeatMs ?? HEARTBEAT_MS;
1704
+ const staleMs = deps.staleMs ?? LOCK_STALE_MS;
1705
+ const snapshotEvery = deps.snapshotEvery ?? SNAPSHOT_EVERY_EVENTS;
1706
+
1707
+ const dirOf = (planId: PlanId): string => {
1708
+ if (!isPlanId(planId)) throw new ExecutorError("E_INVALID_INPUT", `invalid plan id ${JSON.stringify(planId)}`, { planId });
1709
+ return planDir(deps.home, planId);
1710
+ };
1711
+ const envOf = (dir: string): WriterEnv => ({ fs, clock, proc, warn, dir, heartbeatMs, staleMs, snapshotEvery, observations: deps.observations });
1712
+ const emit = (warnings: readonly string[]): void => {
1713
+ for (const w of warnings) warn(w);
1714
+ };
1715
+
1716
+ /**
1717
+ * Dead pid on this host, or a heartbeat older than `staleMs`; a torn lock file is stale once its mtime is that old. The heartbeat is the
1718
+ * later of the lock's own stamp (its acquisition) and the holder's beat file (`writer.<token>.beat`).
1719
+ */
1720
+ const isStale = (cur: LockRead): boolean => {
1721
+ const h = cur.holder;
1722
+ if (h === null) return cur.mtimeMs !== null && clock.now() - cur.mtimeMs > staleMs;
1723
+ if (h.hostname === proc.hostname && !proc.isAlive(h.pid)) return true;
1724
+ const own = Date.parse(h.heartbeatAt);
1725
+ const beat = Math.max(Number.isFinite(own) ? own : Number.NEGATIVE_INFINITY, cur.beatMs ?? Number.NEGATIVE_INFINITY);
1726
+ return !Number.isFinite(beat) || clock.now() - beat > staleMs;
1727
+ };
1728
+
1729
+ const readLock = async (dir: string): Promise<LockRead> => {
1730
+ const path = join(dir, LOCK_FILE);
1731
+ const text = await readOptional(fs, path);
1732
+ if (text === null) return { exists: false, text: null, holder: null, mtimeMs: null, beatMs: null };
1733
+ const st = await fs.lstat(path);
1734
+ const holder = parseLockText(text);
1735
+ const beatText = holder === null ? null : await readOptional(fs, join(dir, beatFileName(holder.token)));
1736
+ return { exists: true, text, holder, mtimeMs: st === null ? null : st.mtimeMs, beatMs: beatText === null ? null : parseBeatText(beatText) };
1737
+ };
1738
+
1739
+ /** Stamps a lock record: the store, not the caller, chooses the token, the start time and the epoch. */
1740
+ const stampLock = (holder: LockHolder, epoch: number): LockRecord => {
1741
+ const now = clock.iso();
1742
+ // The pid prefix keeps tokens of two processes apart even if their random sources collide.
1743
+ const token = `${holder.pid.toString(16)}-${clock.randomHex(8)}`;
1744
+ return { pid: holder.pid, hostname: holder.hostname, sessionID: holder.sessionID, startedAt: now, heartbeatAt: now, token, epoch };
1745
+ };
1746
+
1747
+ const lockHeld = async (dir: string): Promise<ExecutorError> => {
1748
+ const cur = await readLock(dir);
1749
+ const stale = cur.exists && isStale(cur);
1750
+ const who = cur.holder === null ? "unknown holder" : `pid ${cur.holder.pid} on ${cur.holder.hostname} (session ${cur.holder.sessionID})`;
1751
+ return new ExecutorError(
1752
+ "E_LOCK_HELD",
1753
+ `ledger writer lock is held by ${who}${stale ? "; it is stale, use takeover" : ""}`,
1754
+ jsonDetail(cur.holder === null ? null : publicHolder(cur.holder)),
1755
+ );
1756
+ };
1757
+
1758
+ /** Creates the lock file exclusively; EEXIST means another writer (stale or not) holds it. The store stamps token, start time and epoch. */
1759
+ const acquireExclusive = async (dir: string, holder: LockHolder): Promise<LockRecord> => {
1760
+ const mine = stampLock(holder, (await maxEpochOnDisk(fs, dir)) + 1);
1761
+ try {
1762
+ await fs.writeText(join(dir, LOCK_FILE), JSON.stringify(mine), { exclusive: true, fsync: true });
1763
+ } catch (e) {
1764
+ if (fsErrorCode(e) === "EEXIST") throw await lockHeld(dir);
1765
+ throw e;
1766
+ }
1767
+ return mine;
1768
+ };
1769
+
1770
+ /** Removes the lock (and its beat file) only while it still names `mine`. */
1771
+ const releaseLockQuietly = async (dir: string, mine: LockRecord): Promise<void> => {
1772
+ try {
1773
+ const cur = await readLock(dir);
1774
+ if (cur.holder !== null && sameLockIdentity(cur.holder, mine)) await rmQuiet(fs, join(dir, LOCK_FILE));
1775
+ await rmQuiet(fs, join(dir, beatFileName(mine.token)));
1776
+ } catch (e) {
1777
+ warn(`could not release the lock in ${dir}: ${errMessage(e)}`);
1778
+ }
1779
+ };
1780
+
1781
+ /** Creates `path` exclusively with `content`; false when it already exists. */
1782
+ const createExclusive = async (path: string, content: string): Promise<boolean> => {
1783
+ try {
1784
+ await fs.writeText(path, content, { exclusive: true, fsync: true });
1785
+ return true;
1786
+ } catch (e) {
1787
+ if (fsErrorCode(e) === "EEXIST") return false;
1788
+ throw e;
1789
+ }
1790
+ };
1791
+
1792
+ /**
1793
+ * Breaks a stale guard. The break itself is serialised under its own exclusive file, and the guard is deleted only if its content is
1794
+ * still what was judged stale (a guard another taker re-created in between is left alone). True when the guard is gone.
1795
+ */
1796
+ const breakStaleGuard = async (dir: string, guard: string, ticket: string): Promise<boolean> => {
1797
+ // A guard that vanished meanwhile belonged to a taker that just finished: report a takeover in progress rather than race it.
1798
+ const seen = await readOptional(fs, guard);
1799
+ if (seen === null) return false;
1800
+ const st = await fs.lstat(guard);
1801
+ if (st === null || clock.now() - st.mtimeMs <= GUARD_STALE_MS) return false;
1802
+ const brk = join(dir, LOCK_GUARD_BREAK_FILE);
1803
+ if (!(await createExclusive(brk, ticket))) {
1804
+ const bst = await fs.lstat(brk);
1805
+ if (bst !== null && clock.now() - bst.mtimeMs > GUARD_STALE_MS) await rmQuiet(fs, brk); // a dead breaker; the next attempt wins
1806
+ return false;
1807
+ }
1808
+ try {
1809
+ // Content re-check under the break file: delete only the guard that was judged stale, never one re-created since.
1810
+ if ((await readOptional(fs, guard)) !== seen) return false;
1811
+ await rmQuiet(fs, guard);
1812
+ return true;
1813
+ } finally {
1814
+ // Only this breaker's own file: a stale-break cleanup by another taker may have replaced it meanwhile.
1815
+ if ((await readOptional(fs, brk)) === ticket) await rmQuiet(fs, brk);
1816
+ }
1817
+ };
1818
+
1819
+ /**
1820
+ * Replaces a stale lock (or none) under a short-lived guard file so two takers cannot both win. A LIVE holder is refused with
1821
+ * E_LOCK_HELD, except that reason {@link ADOPT_TAKEOVER_REASON} (matched exactly) replaces it when the holder is this same process
1822
+ * (same pid and host), until fencing proves an older writer out.
1823
+ */
1824
+ const takeLock = async (
1825
+ dir: string,
1826
+ holder: LockHolder,
1827
+ reason: string,
1828
+ ): Promise<{ mine: LockRecord; previous: LockRecord | null }> => {
1829
+ const guard = join(dir, LOCK_GUARD_FILE);
1830
+ const ticket = JSON.stringify({ pid: proc.pid, token: clock.randomHex(8), at: clock.iso() });
1831
+ if (!(await createExclusive(guard, ticket))) {
1832
+ if (!(await breakStaleGuard(dir, guard, ticket)) || !(await createExclusive(guard, ticket))) {
1833
+ throw new ExecutorError("E_LOCK_HELD", "another takeover of this ledger is in progress", null);
1834
+ }
1835
+ }
1836
+ try {
1837
+ return await takeLockGuarded(dir, holder, reason);
1838
+ } finally {
1839
+ try {
1840
+ if ((await readOptional(fs, guard)) === ticket) await rmQuiet(fs, guard);
1841
+ } catch (e) {
1842
+ warn(`could not remove ${guard}: ${errMessage(e)}`);
1843
+ }
1844
+ }
1845
+ };
1846
+
1847
+ const takeLockGuarded = async (
1848
+ dir: string,
1849
+ holder: LockHolder,
1850
+ reason: string,
1851
+ ): Promise<{ mine: LockRecord; previous: LockRecord | null }> => {
1852
+ const cur = await readLock(dir);
1853
+ const sameProcess = cur.holder !== null && cur.holder.pid === proc.pid && cur.holder.hostname === proc.hostname;
1854
+ const adopting = reason === ADOPT_TAKEOVER_REASON && sameProcess;
1855
+ if (cur.exists && !adopting && !isStale(cur)) throw await lockHeld(dir);
1856
+ const epoch = Math.max(cur.holder === null ? 0 : cur.holder.epoch, await maxEpochOnDisk(fs, dir)) + 1;
1857
+ const mine = stampLock(holder, epoch);
1858
+ const lockPath = join(dir, LOCK_FILE);
1859
+ if (!cur.exists) {
1860
+ if (!(await createExclusive(lockPath, JSON.stringify(mine)))) throw await lockHeld(dir);
1861
+ } else {
1862
+ if ((await readOptional(fs, lockPath)) !== cur.text) throw await lockHeld(dir); // changed since it was judged
1863
+ const tmp = join(dir, `${LOCK_FILE}.tmp-${proc.pid}-${clock.randomHex(4)}`);
1864
+ try {
1865
+ await fs.writeText(tmp, JSON.stringify(mine), { fsync: true });
1866
+ await retryBusy(clock, () => fs.rename(tmp, lockPath));
1867
+ } catch (e) {
1868
+ try {
1869
+ await rmQuiet(fs, tmp);
1870
+ } catch (cleanup) {
1871
+ warn(`could not remove temp lock ${tmp}: ${errMessage(cleanup)}`);
1872
+ }
1873
+ throw e;
1874
+ }
1875
+ }
1876
+ await fs.fsyncDir(dir);
1877
+ return { mine, previous: cur.holder };
1878
+ };
1879
+
1880
+ /** Removes leftover temp files and the beat files of earlier holders; the caller holds the lock `mine`. */
1881
+ const cleanupTemps = async (dir: string, mine: LockRecord): Promise<void> => {
1882
+ for (const name of await fs.readdir(dir)) {
1883
+ const beat = BEAT_PATTERN.exec(name);
1884
+ if (!TMP_PATTERN.test(name) && (beat === null || beat[1] === mine.token)) continue;
1885
+ try {
1886
+ await rmQuiet(fs, join(dir, name));
1887
+ } catch (e) {
1888
+ warn(`could not remove leftover ${name}: ${errMessage(e)}`);
1889
+ }
1890
+ }
1891
+ };
1892
+
1893
+ /** Loads the plan under the lock `mine`, repairs history, takes a snapshot when the journal tail is unusable, and starts the heartbeat. */
1894
+ const buildWriter = async (
1895
+ planId: PlanId,
1896
+ dir: string,
1897
+ mine: LockRecord,
1898
+ takeover: { reason: string; previous: LockRecord | null } | null,
1899
+ ): Promise<LedgerWriter> => {
1900
+ const env = envOf(dir);
1901
+ let writer: StoreWriter | null = null;
1902
+ try {
1903
+ const lockEnv = { fs, dir, planId };
1904
+ await assertLockHeld(lockEnv, mine); // before anything on disk is touched
1905
+ await cleanupTemps(dir, mine);
1906
+ const st = await loadMain(fs, dir, "writer");
1907
+ emit(st.warnings);
1908
+ const hl = await loadHistory(fs, dir, st.ledger.seq, st.events);
1909
+ const all = [...hl.kept, ...hl.added].sort((x, y) => x.event.seq - y.event.seq);
1910
+ const tracker = trackerOf(all);
1911
+ // A1-3a: `integrating` needs an open entry unless the task's last entry closed rolled-back.
1912
+ const orphan = tracker.integratingWithoutEntry(st.ledger)[0];
1913
+ if (orphan !== undefined) {
1914
+ throw new ExecutorError("E_ILLEGAL_TRANSITION", `task ${orphan} is integrating but no integration entry is open`, {
1915
+ taskId: orphan,
1916
+ codes: ["integrating-without-entry"],
1917
+ });
1918
+ }
1919
+ if (hl.rewrite) {
1920
+ await writeHistoryFile(env, all.map((l) => l.text), () => assertLockHeld(lockEnv, mine));
1921
+ } else if (hl.added.length > 0) {
1922
+ await assertLockHeld(lockEnv, mine);
1923
+ await fs.appendText(join(dir, HISTORY_FILE), `${hl.added.map((l) => l.text).join("\n")}\n`, { fsync: true });
1924
+ }
1925
+ writer = new StoreWriter(env, {
1926
+ planId,
1927
+ ledger: st.ledger,
1928
+ tracker,
1929
+ lock: mine,
1930
+ snapshotSeq: st.snapshotSeq,
1931
+ snapshotEpoch: st.snapshotEpoch,
1932
+ journal: st.files[st.files.length - 1] ?? null,
1933
+ needsRotate: st.dirty,
1934
+ });
1935
+ await writer.start();
1936
+ if (takeover !== null) {
1937
+ await writer.append([
1938
+ {
1939
+ type: "lock-takeover",
1940
+ reason: takeover.reason,
1941
+ previous: takeover.previous === null ? null : publicHolder(takeover.previous),
1942
+ holder: publicHolder(mine),
1943
+ },
1944
+ ]);
1945
+ }
1946
+ return writer;
1947
+ } catch (e) {
1948
+ if (writer !== null) writer.abandon();
1949
+ await releaseLockQuietly(dir, mine);
1950
+ throw e;
1951
+ }
1952
+ };
1953
+
1954
+ const requireDir = async (planId: PlanId): Promise<string> => {
1955
+ const dir = dirOf(planId);
1956
+ if ((await fs.lstat(dir)) === null) throw new ExecutorError("E_LEDGER_NOT_FOUND", `no ledger for plan ${planId}`, { planId });
1957
+ return dir;
1958
+ };
1959
+
1960
+ const read = async (planId: PlanId): Promise<LedgerV1> => {
1961
+ const dir = await requireDir(planId);
1962
+ const st = await loadMainConsistent(fs, clock, dir);
1963
+ emit(st.warnings);
1964
+ return st.ledger;
1965
+ };
1966
+
1967
+ return {
1968
+ async create(draft, holder) {
1969
+ if (!isLedgerV1(draft) || draft.seq !== 1) {
1970
+ throw new ExecutorError("E_SCHEMA_INVALID", "create needs a valid LedgerV1 draft with seq 1", jsonDetail(ledgerViolations(draft).slice(0, 20)));
1971
+ }
1972
+ const planId = draft.planId;
1973
+ // A1-3a: a fresh plan has no integration entry, so a draft with an `integrating` task could never be opened again.
1974
+ const orphan = new HistoryTracker().integratingWithoutEntry(draft)[0];
1975
+ if (orphan !== undefined) {
1976
+ throw new ExecutorError("E_ILLEGAL_TRANSITION", `draft has task ${orphan} integrating with no open integration entry`, {
1977
+ taskId: orphan,
1978
+ codes: ["integrating-without-entry"],
1979
+ });
1980
+ }
1981
+ const dir = dirOf(planId);
1982
+ if ((await fs.lstat(dir)) !== null) throw new ExecutorError("E_EXISTS", `plan ${planId} already exists`, { planId });
1983
+ await fs.mkdir(dir);
1984
+ let mine: LockRecord;
1985
+ try {
1986
+ mine = await acquireExclusive(dir, holder);
1987
+ } catch (e) {
1988
+ if (e instanceof ExecutorError && e.code === "E_LOCK_HELD") {
1989
+ throw new ExecutorError("E_EXISTS", `plan ${planId} is being created elsewhere`, { planId });
1990
+ }
1991
+ try {
1992
+ // Remove the directory this call created, but only while it is still empty.
1993
+ if ((await fs.readdir(dir)).length === 0) await rmQuiet(fs, dir, true);
1994
+ } catch (cleanup) {
1995
+ warn(`could not remove the empty plan directory ${dir}: ${errMessage(cleanup)}`);
1996
+ }
1997
+ throw e;
1998
+ }
1999
+ try {
2000
+ const ledger = JSON.parse(JSON.stringify(draft)) as LedgerV1;
2001
+ const init: ExecutorEvent = { seq: 1, at: clock.iso(), batch: 1, last: true, type: "ledger-init", ledger };
2002
+ const journal: JournalFile = { name: journalName(1, mine.epoch), first: 1, epoch: mine.epoch };
2003
+ await fs.writeText(join(dir, journal.name), `${JSON.stringify(init)}\n`, { exclusive: true, fsync: true });
2004
+ const snapName = snapshotName(mine.epoch);
2005
+ const tmp = join(dir, `${snapName}.tmp-${proc.pid}-${clock.randomHex(4)}`);
2006
+ await fs.writeText(tmp, JSON.stringify(ledger), { fsync: true });
2007
+ await assertLockHeld({ fs, dir, planId }, mine); // immediately before the rename that publishes the snapshot
2008
+ await retryBusy(clock, () => fs.rename(tmp, join(dir, snapName)));
2009
+ await fs.fsyncDir(dir);
2010
+ const writer = new StoreWriter(envOf(dir), {
2011
+ planId,
2012
+ ledger,
2013
+ tracker: new HistoryTracker(),
2014
+ lock: mine,
2015
+ snapshotSeq: 1,
2016
+ snapshotEpoch: mine.epoch,
2017
+ journal,
2018
+ needsRotate: false,
2019
+ journalFresh: true,
2020
+ });
2021
+ await writer.start();
2022
+ return writer;
2023
+ } catch (e) {
2024
+ // A lost lock means another writer owns the directory now: it is not ours to delete. Otherwise the lock is re-checked right
2025
+ // before the recursive delete.
2026
+ if (!(e instanceof ExecutorError && e.code === "E_LOCK_LOST")) {
2027
+ try {
2028
+ await assertLockHeld({ fs, dir, planId }, mine);
2029
+ await rmQuiet(fs, dir, true);
2030
+ } catch (cleanup) {
2031
+ warn(`could not remove the half-created plan directory ${dir}: ${errMessage(cleanup)}`);
2032
+ }
2033
+ }
2034
+ throw e;
2035
+ }
2036
+ },
2037
+
2038
+ async open(planId, holder) {
2039
+ const dir = await requireDir(planId);
2040
+ const mine = await acquireExclusive(dir, holder);
2041
+ return buildWriter(planId, dir, mine, null);
2042
+ },
2043
+
2044
+ async takeover(planId, holder, reason) {
2045
+ const dir = await requireDir(planId);
2046
+ const { mine, previous } = await takeLock(dir, holder, reason);
2047
+ return buildWriter(planId, dir, mine, { reason, previous });
2048
+ },
2049
+
2050
+ read,
2051
+
2052
+ async list() {
2053
+ let names: string[];
2054
+ try {
2055
+ names = await fs.readdir(deps.home);
2056
+ } catch (e) {
2057
+ if (fsErrorCode(e) === "ENOENT") return [];
2058
+ throw e;
2059
+ }
2060
+ const out: Array<{ planId: PlanId; status: LedgerStatus; toplevel: string; orchestratorSessionID: string; seq: number }> = [];
2061
+ for (const name of names.sort()) {
2062
+ if (name === SLOT_MARKERS_DIRNAME || !isPlanId(name)) continue;
2063
+ try {
2064
+ const l = await read(name);
2065
+ out.push({ planId: l.planId, status: l.status, toplevel: l.repo.toplevel, orchestratorSessionID: l.orchestrator.sessionID, seq: l.seq });
2066
+ } catch (e) {
2067
+ if (e instanceof ExecutorError && e.code === "E_LEDGER_NOT_FOUND") continue;
2068
+ warn(`plan ${name} is unreadable and skipped: ${errMessage(e)}`);
2069
+ }
2070
+ }
2071
+ return out;
2072
+ },
2073
+
2074
+ async exportPlan(planId) {
2075
+ const dir = await requireDir(planId);
2076
+ const st = await loadMainConsistent(fs, clock, dir);
2077
+ emit(st.warnings);
2078
+ const hist = parseJournal((await readOptional(fs, join(dir, HISTORY_FILE))) ?? "", HISTORY_FILE);
2079
+ const bySeq = new Map<number, ExecutorEvent>();
2080
+ for (const l of repairHistory(hist.lines, st.ledger.seq, st.events).kept) bySeq.set(l.event.seq, l.event);
2081
+ for (const l of st.events) if (l.event.seq <= st.ledger.seq) bySeq.set(l.event.seq, l.event);
2082
+ const events = [...bySeq.values()].sort((a, b) => a.seq - b.seq);
2083
+ return { snapshot: st.ledger, events };
2084
+ },
2085
+
2086
+ async remove(planId) {
2087
+ const dir = dirOf(planId);
2088
+ if ((await fs.lstat(dir)) === null) return false;
2089
+ const me: LockHolder = { pid: proc.pid, hostname: proc.hostname, sessionID: "remove", startedAt: clock.iso(), heartbeatAt: clock.iso() };
2090
+ // The guarded path: a free lock is created exclusively, a stale one is replaced under the takeover guard, a live one is refused.
2091
+ const { mine } = await takeLock(dir, me, "remove");
2092
+ try {
2093
+ let status: LedgerStatus | null = null;
2094
+ try {
2095
+ status = (await loadMain(fs, dir, "writer")).ledger.status;
2096
+ } catch (e) {
2097
+ // A directory that never got a ledger (a create that died early) holds nothing worth keeping.
2098
+ if (!(e instanceof ExecutorError) || e.code !== "E_LEDGER_NOT_FOUND") throw e;
2099
+ }
2100
+ if (status !== null && status !== "completed" && status !== "aborted") {
2101
+ throw new ExecutorError("E_PLAN_STATE", `plan ${planId} is ${status}; only completed or aborted plans can be removed`, { planId, status });
2102
+ }
2103
+ } catch (e) {
2104
+ await releaseLockQuietly(dir, mine);
2105
+ throw e;
2106
+ }
2107
+ // The delete is irreversible: re-check the lock, then move the directory aside in one rename (a takeover after the check finds no
2108
+ // plan instead of a half-deleted one) and delete the tombstone.
2109
+ const tomb = `${dir}.removing-${mine.token}`;
2110
+ try {
2111
+ await assertLockHeld({ fs, dir, planId }, mine);
2112
+ await retryBusy(clock, () => fs.rename(dir, tomb));
2113
+ } catch (e) {
2114
+ await releaseLockQuietly(dir, mine); // a no-op when the lock is no longer ours
2115
+ throw e;
2116
+ }
2117
+ try {
2118
+ await retryBusy(clock, () => fs.rm(tomb, { recursive: true }));
2119
+ } catch (e) {
2120
+ warn(`plan ${planId} was removed but its tombstone ${tomb} could not be deleted: ${errMessage(e)}`);
2121
+ }
2122
+ return true;
2123
+ },
2124
+ };
2125
+ }
2126
+
2127
+ function fsErrorCode(e: unknown): string | undefined {
2128
+ if (typeof e === "object" && e !== null && "code" in e) {
2129
+ const c = (e as { code?: unknown }).code;
2130
+ return typeof c === "string" ? c : undefined;
2131
+ }
2132
+ return undefined;
2133
+ }
2134
+
2135
+ /** Production `FileSystem` over node:fs. Nothing runs at module load; every call is made on demand. */
2136
+ export function createNodeFileSystem(): FileSystem {
2137
+ return {
2138
+ readText: (p) => nodeFsp.readFile(p, "utf8"),
2139
+ async writeText(p, data, o) {
2140
+ const fh = await nodeFsp.open(p, o?.exclusive === true ? "wx" : "w");
2141
+ try {
2142
+ await fh.writeFile(data, "utf8");
2143
+ if (o?.fsync === true) await fh.sync();
2144
+ } finally {
2145
+ await fh.close();
2146
+ }
2147
+ },
2148
+ async appendText(p, data, o) {
2149
+ // `create: false` (journal appends): O_APPEND without O_CREAT, so a fenced writer whose file was deleted cannot re-create it.
2150
+ const noCreate = (o as AppendOptions).create === false;
2151
+ const fh = await nodeFsp.open(p, noCreate ? nodeFsConstants.O_WRONLY | nodeFsConstants.O_APPEND : "a");
2152
+ try {
2153
+ await fh.appendFile(data, "utf8");
2154
+ if (o.fsync) await fh.sync();
2155
+ } finally {
2156
+ await fh.close();
2157
+ }
2158
+ },
2159
+ rename: (a, b) => nodeFsp.rename(a, b),
2160
+ async rm(p, o) {
2161
+ try {
2162
+ await nodeFsp.rm(p, { recursive: o.recursive, force: true });
2163
+ } catch (error) {
2164
+ // A non-recursive rm of a directory removes it only when empty (rmdir); node's rm refuses every directory.
2165
+ const code = (error as NodeJS.ErrnoException).code;
2166
+ if (o.recursive || (code !== "ERR_FS_EISDIR" && code !== "EISDIR")) throw error;
2167
+ await nodeFsp.rmdir(p);
2168
+ }
2169
+ },
2170
+ async mkdir(p) {
2171
+ await nodeFsp.mkdir(p, { recursive: true });
2172
+ },
2173
+ readdir: (p) => nodeFsp.readdir(p),
2174
+ async lstat(p): Promise<FsStat | null> {
2175
+ try {
2176
+ const s = await nodeFsp.lstat(p);
2177
+ const kind: FsStat["kind"] = s.isSymbolicLink() ? "symlink" : s.isDirectory() ? "dir" : s.isFile() ? "file" : "other";
2178
+ return { kind, size: s.size, mtimeMs: s.mtimeMs };
2179
+ } catch (e) {
2180
+ if (fsErrorCode(e) === "ENOENT") return null;
2181
+ throw e;
2182
+ }
2183
+ },
2184
+ realpath: (p) => nodeFsp.realpath(p),
2185
+ async fsyncDir(p) {
2186
+ // Windows cannot open a directory for fsync (EPERM/EACCES/EISDIR); NTFS journals the directory entry itself.
2187
+ const ignorable = (e: unknown): boolean => {
2188
+ if (process.platform !== "win32") return false;
2189
+ const c = fsErrorCode(e);
2190
+ return c === "EPERM" || c === "EACCES" || c === "EISDIR";
2191
+ };
2192
+ let fh: nodeFsp.FileHandle;
2193
+ try {
2194
+ fh = await nodeFsp.open(p, "r");
2195
+ } catch (e) {
2196
+ if (ignorable(e)) return;
2197
+ throw e;
2198
+ }
2199
+ try {
2200
+ await fh.sync();
2201
+ } catch (e) {
2202
+ if (!ignorable(e)) throw e;
2203
+ } finally {
2204
+ await fh.close();
2205
+ }
2206
+ },
2207
+ };
2208
+ }