@flyingrobots/parley-read 0.0.0-stage → 0.1.0

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.
package/src/load.ts ADDED
@@ -0,0 +1,711 @@
1
+ // The loader: every run in a working directory's two receipt locations, as validated records.
2
+ //
3
+ // The rules it is held to are the ones the specification binds a *reader* to, and they exist
4
+ // because the cases §6 names as unconstrainable will happen:
5
+ //
6
+ // §1.4 buffer to the newline; quarantine a complete line that is not a JSON object, keep it,
7
+ // report it, and never treat it as evidence of anything but its own existence.
8
+ // §5.4 ignore a final line that is not newline-terminated, including an otherwise parseable
9
+ // `end`; a newline-terminated `end` establishes that the run reported termination.
10
+ // §1.3 `(run, seq)` identifies an event. Copies are one event; a copy may carry a field another
11
+ // omits; copies must agree on every field they share.
12
+ // §4.5 full validation is against the schema for the exact advertised `(id, version)` pair.
13
+ // §4.6 a line whose id this reader ships no schema for is passed through, not validated.
14
+ // §5 a sidecar stands in a record's place; its path is relative to the receipt's directory and
15
+ // must not leave it; `bytes` and `sha256` describe the stored bytes; a sidecar found missing
16
+ // or mismatched makes the bundle unavailable for replay.
17
+ // §8 a copy of a run on the shared history stream may be a projection of the receipt copy, and
18
+ // a reader that finds the same record in more than one copy prefers the least-projected one,
19
+ // because the receipt copy is the record and a projection is a view of it.
20
+ //
21
+ // What this module does not do: query, rank, or recompute `inv`. It hands back what the receipts
22
+ // say, with each claim labelled by how well it is established (§1.2a).
23
+ import { readFileSync, readdirSync } from "node:fs";
24
+ import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
25
+ import { sha256 } from "@flyingrobots/parley-emit";
26
+ import { readFileLines } from "./lines.ts";
27
+ import { isFile, receiptLocations, type LocateOptions, type ReceiptLocation, type Where } from "./locate.ts";
28
+ import { ENVELOPE, validator, type Validation, type Validator } from "./validate.ts";
29
+
30
+ // ---- what a load reports ------------------------------------------------------------------
31
+
32
+ export type DefectCode =
33
+ | "line.quarantined" | "line.blank" | "line.no_envelope" | "line.unterminated"
34
+ | "record.invalid" | "record.unknown_pair" | "copies.disagree" | "copies.projected_disagree"
35
+ | "sidecar.missing" | "sidecar.unreadable" | "sidecar.digest_mismatch"
36
+ | "sidecar.bytes_mismatch" | "sidecar.escapes_bundle" | "sidecar.unparseable"
37
+ | "receipt.unreadable" | "history.unreadable";
38
+
39
+ /** The quarantine codes: a kept line that is not a record (§1.4, §5.4). */
40
+ export const QUARANTINE_CODES: ReadonlySet<DefectCode> = new Set<DefectCode>([
41
+ "line.quarantined", "line.blank", "line.no_envelope", "line.unterminated",
42
+ ]);
43
+
44
+ export interface Defect {
45
+ readonly code: DefectCode;
46
+ /** The section of the specification the defect is measured against. */
47
+ readonly section: string;
48
+ readonly file: string;
49
+ /** 1-based line in that file; `0` when the defect is the bundle's rather than a line's. */
50
+ readonly line: number;
51
+ readonly problem: string;
52
+ /** The run the defect is attributed to, when it can be (§1.4), else null. */
53
+ readonly run: string | null;
54
+ /** The quarantined bytes, kept verbatim, for a quarantine code. */
55
+ readonly raw?: string;
56
+ /** The `seq` of the record a sidecar holds, for a sidecar code. */
57
+ readonly source?: number;
58
+ }
59
+
60
+ export type SidecarState =
61
+ | "intact" | "missing" | "unreadable" | "digest_mismatch" | "bytes_mismatch"
62
+ | "escapes_bundle" | "unparseable"
63
+ /** Resolution was switched off, so nothing about the stored bytes was established either way. */
64
+ | "unchecked";
65
+
66
+ export interface SidecarResolution {
67
+ /** The `seq` of the record the sidecar holds. */
68
+ readonly source: number;
69
+ /** The `seq` of the `sidecar` event itself, which is a record in its own right (§5). */
70
+ readonly seq: number;
71
+ /** The path as declared: relative to the receipt's directory. */
72
+ readonly path: string;
73
+ /** The absolute path it resolved to, or null when it would leave the bundle and was never read. */
74
+ readonly resolved: string | null;
75
+ readonly state: SidecarState;
76
+ readonly declared: { readonly bytes: number | null; readonly sha256: string | null };
77
+ /** What the stored bytes actually are, when they could be read. */
78
+ readonly actual?: { readonly bytes: number; readonly sha256: string };
79
+ }
80
+
81
+ /**
82
+ * A copy of this run that says it is a **projection** of the receipt copy (§8): the source it came
83
+ * from opened that run with a `parley.history.transform` line naming the transform that wrote it.
84
+ * One note per source, whether or not any body differed — that a copy you read is a view of the
85
+ * record is worth knowing either way.
86
+ */
87
+ export interface Projection {
88
+ /** The file whose copy of this run is a projection. */
89
+ readonly file: string;
90
+ readonly where: Where;
91
+ /** What the transform is called, as its `parley.history.transform` line states it. */
92
+ readonly name: string;
93
+ /** SHA-256 of the transform's source text, as that line states it. */
94
+ readonly sha256: string;
95
+ /** The `seq` the transform line itself took; it reaches no other sink, so no other copy has it (§8). */
96
+ readonly seq: number;
97
+ /** The `seq` values where this copy's body differed from the record and the record was returned instead. */
98
+ readonly superseded: readonly number[];
99
+ /**
100
+ * The `seq` values a copy of this run read elsewhere carries and this copy does not: lines this
101
+ * transform withheld, rather than a gap of unknown cause. A `seq` the copy accounted for with a
102
+ * `sidecar` event is carried, not withheld (§5).
103
+ */
104
+ readonly withheld: readonly number[];
105
+ /** True when no unprojected copy of this run was read, so the records returned are this projection's. */
106
+ readonly sole: boolean;
107
+ }
108
+
109
+ export interface LoadedRecord {
110
+ readonly run: string;
111
+ readonly seq: number;
112
+ readonly event: string | null;
113
+ readonly t: number | null;
114
+ /** The file the first copy of this event was read from. */
115
+ readonly file: string;
116
+ /** 1-based line of that copy; for a record restored from a sidecar, the line of its `sidecar` event. */
117
+ readonly line: number;
118
+ /** How many lines carried this `(run, seq)`. More than one is a copy, not a second event (§1.3). */
119
+ readonly copies: number;
120
+ /** True when the record was stored beside the receipt and restored from there (§5). */
121
+ readonly fromSidecar: boolean;
122
+ /**
123
+ * True when every copy of this event came from a source carrying a `parley.history.transform`
124
+ * line for this run, so the body is a projection's and no whole copy was read (§8).
125
+ */
126
+ readonly projected: boolean;
127
+ /** The transforms whose copies this body came from, named; empty when the body is an unprojected copy's. */
128
+ readonly projectedBy: readonly string[];
129
+ readonly record: Record<string, unknown>;
130
+ readonly validation: Validation;
131
+ }
132
+
133
+ export interface BundleSource {
134
+ readonly where: Where;
135
+ readonly receipt: string;
136
+ }
137
+
138
+ export interface Replay {
139
+ /**
140
+ * True when something about this bundle rules replay out. False means only that nothing in the
141
+ * bundle rules it out: eligibility under §2.3 and §5.3 for the invocation at hand is the
142
+ * caller's to decide, and this reader does not know it.
143
+ */
144
+ readonly unavailable: boolean;
145
+ readonly reasons: readonly string[];
146
+ }
147
+
148
+ export interface Bundle {
149
+ readonly run: string;
150
+ /** Every receipt file this run's records were read from, in the order the locations were read. */
151
+ readonly sources: readonly BundleSource[];
152
+ /** One record per `(run, seq)`, ascending by `seq`. */
153
+ readonly records: readonly LoadedRecord[];
154
+ readonly sidecars: readonly SidecarResolution[];
155
+ /** The copies of this run that said they were projections, one note per source (§8). */
156
+ readonly projections: readonly Projection[];
157
+ /** The kept lines that are not records, attributed to this run (§1.4). */
158
+ readonly quarantined: readonly Defect[];
159
+ /** Everything wrong that was found, quarantines included. */
160
+ readonly defects: readonly Defect[];
161
+ /** How many extra copies of an event were seen and folded into one record. */
162
+ readonly duplicates: number;
163
+ /** A newline-terminated `end` was read: the run reported termination (§5.4). */
164
+ readonly terminated: boolean;
165
+ /** `end.status`, when there is one. */
166
+ readonly status: number | null;
167
+ /** The receipt is partial: the head carries `redacted`, a `redaction` event was emitted, or `end.redacted` is true (§3.3, §5.3). */
168
+ readonly redacted: boolean;
169
+ readonly replay: Replay;
170
+ }
171
+
172
+ export interface FileSummary {
173
+ readonly file: string;
174
+ readonly where: Where;
175
+ /** The run the file name names, which is how a quarantined line is attributed (§5: `<run>.jsonl`). */
176
+ readonly run: string | null;
177
+ /** Complete lines; the unterminated tail is not one (§5.4). */
178
+ readonly lines: number;
179
+ readonly runs: readonly string[];
180
+ readonly quarantined: readonly Defect[];
181
+ }
182
+
183
+ export interface FileRead extends FileSummary {
184
+ readonly bundles: readonly Bundle[];
185
+ }
186
+
187
+ export interface Load {
188
+ readonly locations: readonly ReceiptLocation[];
189
+ readonly files: readonly FileSummary[];
190
+ /** Every run found, ascending by run id. */
191
+ readonly bundles: readonly Bundle[];
192
+ /** Every kept line that is not a record, across every file. */
193
+ readonly quarantined: readonly Defect[];
194
+ /** Defects that belong to no bundle, such as a receipt file that could not be read at all. */
195
+ readonly defects: readonly Defect[];
196
+ readonly counts: {
197
+ readonly bundles: number;
198
+ readonly records: number;
199
+ readonly validated: number;
200
+ readonly invalid: number;
201
+ readonly partial: number;
202
+ readonly unvalidated: number;
203
+ readonly quarantined: number;
204
+ readonly duplicates: number;
205
+ };
206
+ }
207
+
208
+ export interface ReadOptions {
209
+ readonly where?: Where;
210
+ /** Resolve and check sidecars; on by default. Off reports the `sidecar` events and restores no record. */
211
+ readonly sidecars?: boolean;
212
+ readonly validate?: Validator;
213
+ }
214
+
215
+ export interface LoadOptions extends LocateOptions, ReadOptions {
216
+ /**
217
+ * Segments of the shared history stream to read beside the receipts (§8). The stream is opt-in
218
+ * and this reader never goes looking for it: a caller that has one names it, and a segment it
219
+ * names but cannot open is a `history.unreadable` defect rather than a throw.
220
+ */
221
+ readonly history?: readonly string[];
222
+ }
223
+
224
+ // ---- scanning one file --------------------------------------------------------------------
225
+
226
+ interface Raw {
227
+ readonly file: string;
228
+ readonly line: number;
229
+ readonly run: string;
230
+ readonly seq: number;
231
+ readonly obj: Record<string, unknown>;
232
+ /** Set when the source this line came from is a projection of this line's run (§8). */
233
+ readonly projection?: Transform;
234
+ }
235
+
236
+ /** What a source's `parley.history.transform` line says about one run's copy in it (§8). */
237
+ type Transform = Pick<Projection, "file" | "where" | "name" | "sha256" | "seq">;
238
+
239
+ interface Note extends Transform { superseded: number[]; withheld: number[]; sole: boolean }
240
+
241
+ interface Scan {
242
+ readonly raw: Raw[];
243
+ readonly lines: number;
244
+ readonly quarantined: Defect[];
245
+ }
246
+
247
+ function defect(code: DefectCode, section: string, file: string, line: number, problem: string, extra: Partial<Defect> = {}): Defect {
248
+ return { code, section, file, line, problem, run: null, ...extra };
249
+ }
250
+
251
+ /** Lines in, records and quarantine out. Nothing here interprets a record; that is §1.3's job below. */
252
+ function scan(file: string): Scan {
253
+ const { lines, unterminated } = readFileLines(file);
254
+ const raw: Raw[] = [];
255
+ const quarantined: Defect[] = [];
256
+ for (const line of lines) {
257
+ if (line.raw.trim() === "") {
258
+ quarantined.push(defect("line.blank", "§1.4", file, line.n, "a blank line is not a JSON object; quarantined, never a record", { raw: line.raw }));
259
+ continue;
260
+ }
261
+ let parsed: unknown;
262
+ try { parsed = JSON.parse(line.raw); } catch {
263
+ quarantined.push(defect("line.quarantined", "§1.4", file, line.n, "not JSON; quarantined and kept, and evidence of nothing but the fact that something wrote it", { raw: line.raw }));
264
+ continue;
265
+ }
266
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
267
+ quarantined.push(defect("line.quarantined", "§1.4", file, line.n, "JSON, but not an object; quarantined, never a record", { raw: line.raw }));
268
+ continue;
269
+ }
270
+ const obj = parsed as Record<string, unknown>;
271
+ const run = typeof obj.run === "string" && obj.run.length > 0 ? obj.run : null;
272
+ const seq = Number.isInteger(obj.seq) && (obj.seq as number) >= 0 ? (obj.seq as number) : null;
273
+ if (run === null || seq === null) {
274
+ quarantined.push(defect("line.no_envelope", "§1.3", file, line.n, "no usable run and seq, so the line cannot be placed in a run or deduplicated; quarantined", { raw: line.raw }));
275
+ continue;
276
+ }
277
+ raw.push({ file, line: line.n, run, seq, obj });
278
+ }
279
+ if (unterminated !== null) {
280
+ quarantined.push(defect("line.unterminated", "§5.4", file, unterminated.n, "the final line is not newline-terminated, so it is not a line and is ignored, parseable or not", { raw: unterminated.raw }));
281
+ }
282
+ return { raw, lines: lines.length, quarantined };
283
+ }
284
+
285
+ const text = (v: unknown): string => (typeof v === "string" ? v : "");
286
+ const cmp = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
287
+
288
+ /**
289
+ * Mark the lines of every run this source opened with a `parley.history.transform` line (§8).
290
+ *
291
+ * The line is **per run**, so one segment can hold a projected copy of one run beside a whole copy
292
+ * of another, and the mark is read out of the source's own content rather than from where the file
293
+ * is, so the preference below never depends on which file was read first. A second such line for
294
+ * one run in one source is not a second projection: the first names the copy, and the second is a
295
+ * copy of a `(run, seq)` like any other line.
296
+ */
297
+ function markProjections(raw: readonly Raw[], file: string, where: Where): readonly Raw[] {
298
+ const found = new Map<string, Transform>();
299
+ for (const r of raw) {
300
+ if (r.obj.event !== "history.transform" || found.has(r.run)) continue;
301
+ found.set(r.run, { file, where, name: text(r.obj.name), sha256: text(r.obj.sha256), seq: r.seq });
302
+ }
303
+ if (found.size === 0) return raw;
304
+ return raw.map((r) => {
305
+ const projection = found.get(r.run);
306
+ return projection === undefined ? r : { ...r, projection };
307
+ });
308
+ }
309
+
310
+ /** The run a receipt's file name names (§5: `<run>.jsonl`). A stream segment's name names a date, not a run. */
311
+ function runOfFileName(file: string): string | null {
312
+ const name = basename(file);
313
+ return name.endsWith(".jsonl") ? name.slice(0, -".jsonl".length) || null : null;
314
+ }
315
+
316
+ /**
317
+ * §1.4 asks that a quarantined line be "attributed to the run". A receipt file is one run's by
318
+ * name, so that is the attribution; a file holding more than one run, with a name that names
319
+ * neither, leaves the line unattributed rather than guessed at.
320
+ */
321
+ function attribute(quarantined: Defect[], runs: readonly string[], fileRun: string | null): Defect[] {
322
+ const target = fileRun !== null && runs.includes(fileRun) ? fileRun : runs.length === 1 ? runs[0]! : null;
323
+ return target === null ? quarantined : quarantined.map((q) => ({ ...q, run: target }));
324
+ }
325
+
326
+ // ---- assembling one run -------------------------------------------------------------------
327
+
328
+ interface Held {
329
+ base: Record<string, unknown>;
330
+ file: string;
331
+ line: number;
332
+ copies: number;
333
+ fromSidecar: boolean;
334
+ /** The transforms whose copies this body came from; empty while a copy from an unprojected source is held. */
335
+ projectedBy: string[];
336
+ }
337
+
338
+ /**
339
+ * Fold a line into the event at its `seq` (§1.3): the first copy is the record, a later copy
340
+ * contributes the fields it alone carries, and a disagreement on a shared field is a defect in the
341
+ * writer rather than a second event.
342
+ */
343
+ function fold(held: Map<number, Held>, seq: number, obj: Record<string, unknown>, file: string, line: number, run: string, defects: Defect[], fromSidecar: boolean, projectedBy: readonly string[] = []): void {
344
+ const seen = held.get(seq);
345
+ if (!seen) {
346
+ held.set(seq, { base: { ...obj }, file, line, copies: 1, fromSidecar, projectedBy: [...projectedBy] });
347
+ return;
348
+ }
349
+ seen.copies += 1;
350
+ seen.fromSidecar = seen.fromSidecar || fromSidecar;
351
+ for (const [key, value] of Object.entries(obj)) {
352
+ if (!(key in seen.base)) { seen.base[key] = value; continue; }
353
+ if (JSON.stringify(seen.base[key]) !== JSON.stringify(value)) {
354
+ defects.push(defect("copies.disagree", "§1.3", file, line, `seq ${seq}: copies of one event disagree on ${key}`, { run }));
355
+ }
356
+ }
357
+ }
358
+
359
+ /**
360
+ * Two copies are the same record when they carry the same keys with the same values. Key order is
361
+ * not part of a record, and a projection is rebuilt key by key before the writer reattaches the
362
+ * envelope, so a difference in order must not be read as a difference in the record (§1.3).
363
+ */
364
+ function same(a: Record<string, unknown>, b: Record<string, unknown>): boolean {
365
+ const keys = Object.keys(a);
366
+ if (keys.length !== Object.keys(b).length) return false;
367
+ return keys.every((k) => k in b && stable(a[k]) === stable(b[k]));
368
+ }
369
+
370
+ /** JSON with every object's keys in order, so two values compare by what they hold. */
371
+ function stable(v: unknown): string {
372
+ if (v === null || typeof v !== "object") return JSON.stringify(v) ?? "null";
373
+ if (Array.isArray(v)) return `[${v.map(stable).join(",")}]`;
374
+ const entries = Object.entries(v as Record<string, unknown>).sort(([x], [y]) => cmp(x, y));
375
+ return `{${entries.map(([k, x]) => `${JSON.stringify(k)}:${stable(x)}`).join(",")}}`;
376
+ }
377
+
378
+ function within(dir: string, path: string): string | null {
379
+ if (isAbsolute(path)) return null;
380
+ const base = resolve(dir);
381
+ const target = resolve(base, path);
382
+ const prefix = base.endsWith(sep) ? base : base + sep;
383
+ return target !== base && target.startsWith(prefix) ? target : null;
384
+ }
385
+
386
+ /** Resolve one `sidecar` event against the bytes beside the receipt (§5). */
387
+ function resolveSidecar(seq: number, held: Held, read: boolean): { resolution: SidecarResolution; stored?: Record<string, unknown> } {
388
+ const obj = held.base;
389
+ const source = Number.isInteger(obj.source) ? (obj.source as number) : null;
390
+ const path = typeof obj.path === "string" && obj.path.length > 0 ? obj.path : null;
391
+ const declared = {
392
+ bytes: Number.isInteger(obj.bytes) ? (obj.bytes as number) : null,
393
+ sha256: typeof obj.sha256 === "string" ? obj.sha256 : null,
394
+ };
395
+ const at = (state: SidecarState, extra: Partial<SidecarResolution> = {}) =>
396
+ ({ resolution: { source: source ?? -1, seq, path: path ?? "", resolved: null, state, declared, ...extra } satisfies SidecarResolution });
397
+
398
+ if (source === null || path === null || declared.sha256 === null || declared.bytes === null) {
399
+ return at("unreadable");
400
+ }
401
+ const target = within(dirname(held.file), path);
402
+ if (target === null) return at("escapes_bundle");
403
+ // Resolution off: say nothing was established, rather than calling an unread sidecar intact.
404
+ // §1.2a — a reader must not take one kind of evidence for another.
405
+ if (!read) return { resolution: { source, seq, path, resolved: target, state: "unchecked", declared } };
406
+
407
+ let bytes: Buffer;
408
+ try { bytes = readFileSync(target); } catch (e) {
409
+ const missing = (e as NodeJS.ErrnoException).code === "ENOENT";
410
+ return at(missing ? "missing" : "unreadable", { resolved: target });
411
+ }
412
+ const actual = { bytes: bytes.length, sha256: sha256(bytes) };
413
+ if (actual.sha256 !== declared.sha256) return at("digest_mismatch", { resolved: target, actual });
414
+ if (actual.bytes !== declared.bytes) return at("bytes_mismatch", { resolved: target, actual });
415
+ let parsed: unknown;
416
+ try { parsed = JSON.parse(bytes.toString("utf8")); } catch {
417
+ return at("unparseable", { resolved: target, actual });
418
+ }
419
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
420
+ return at("unparseable", { resolved: target, actual });
421
+ }
422
+ return {
423
+ resolution: { source, seq, path, resolved: target, state: "intact", declared, actual },
424
+ stored: parsed as Record<string, unknown>,
425
+ };
426
+ }
427
+
428
+ const SIDECAR_SECTION = "§5";
429
+
430
+ const ENVELOPE_KEYS: ReadonlySet<string> = new Set<string>(ENVELOPE);
431
+
432
+ function envelopeDefect(key: string, r: Raw, run: string): Defect {
433
+ return defect("copies.disagree", "§1.3", r.file, r.line, `seq ${r.seq}: a projected copy disagrees with the record on ${key}, which a projection never changes`, { run });
434
+ }
435
+
436
+ /**
437
+ * Fold the projected copies over the records already held, and return one note per source (§8).
438
+ *
439
+ * The preference: where a copy from an unprojected source is already held, that body is the record
440
+ * and a projected copy that differs from it is **superseded** — recorded as the projection it is,
441
+ * by the transform that wrote it, rather than reported as a writer's disagreement under §1.3. A
442
+ * `seq` no unprojected copy carries is taken from the projected copies and marked as theirs, so a
443
+ * reader that can see only a projection still gets the record and is told what it is.
444
+ *
445
+ * Two projected copies of one `(run, seq)` are the edge the rule cannot settle: neither is the
446
+ * less projected one. They are folded under §1.3 as copies, in an order stated by the transform's
447
+ * name, its digest and the file — never the order the files were read in, which is the failure
448
+ * mode this rule exists to remove — and a disagreement between them on a body field is reported
449
+ * under its own code, because two views of one record were never required to agree.
450
+ *
451
+ * §8 lets a projection narrow the **body**. It never changes the envelope, so a projected copy
452
+ * that disagrees on `event`, `t` or `_schema` is §1.3's defect in whatever wrote it and is
453
+ * reported as one, whichever copy the preference returned.
454
+ */
455
+ function foldProjections(run: string, raw: readonly Raw[], held: Map<number, Held>, defects: Defect[], sole: boolean): Note[] {
456
+ const projected = raw
457
+ .filter((r): r is Raw & { projection: Transform } => r.projection !== undefined)
458
+ .sort((a, b) =>
459
+ cmp(a.projection.name, b.projection.name) || cmp(a.projection.sha256, b.projection.sha256) ||
460
+ cmp(a.projection.file, b.projection.file) || a.line - b.line);
461
+ const notes = new Map<string, Note>();
462
+ for (const r of projected) {
463
+ let note = notes.get(r.projection.file);
464
+ if (note === undefined) {
465
+ note = { ...r.projection, superseded: [], withheld: [], sole };
466
+ notes.set(r.projection.file, note);
467
+ }
468
+ const seen = held.get(r.seq);
469
+ if (seen === undefined) {
470
+ held.set(r.seq, { base: { ...r.obj }, file: r.file, line: r.line, copies: 1, fromSidecar: false, projectedBy: [r.projection.name] });
471
+ continue;
472
+ }
473
+ seen.copies += 1;
474
+ if (seen.projectedBy.length === 0) {
475
+ for (const key of ENVELOPE) {
476
+ if (!(key in r.obj) || !(key in seen.base) || stable(seen.base[key]) === stable(r.obj[key])) continue;
477
+ defects.push(envelopeDefect(key, r, run));
478
+ }
479
+ if (!same(seen.base, r.obj) && !note.superseded.includes(r.seq)) note.superseded.push(r.seq);
480
+ continue;
481
+ }
482
+ if (!seen.projectedBy.includes(r.projection.name)) seen.projectedBy.push(r.projection.name);
483
+ for (const [key, value] of Object.entries(r.obj)) {
484
+ if (!(key in seen.base)) { seen.base[key] = value; continue; }
485
+ if (stable(seen.base[key]) === stable(value)) continue;
486
+ defects.push(ENVELOPE_KEYS.has(key)
487
+ ? envelopeDefect(key, r, run)
488
+ : defect("copies.projected_disagree", "§8", r.file, r.line, `seq ${r.seq}: two projections of one event disagree on ${key}, and neither copy is the less projected one, so neither is preferred`, { run }));
489
+ }
490
+ }
491
+ return [...notes.values()];
492
+ }
493
+
494
+ function buildBundle(run: string, raw: readonly Raw[], sources: readonly BundleSource[], quarantined: readonly Defect[], opts: Required<Pick<ReadOptions, "sidecars" | "validate">>): Bundle {
495
+ const defects: Defect[] = [...quarantined];
496
+ const held = new Map<number, Held>();
497
+
498
+ // §8: the receipt copy is the record and a projection is a view of it. So the copies from the
499
+ // sources that say nothing about a transform are folded first and alone, under §1.3 as before,
500
+ // and a projected copy never contributes a field to them — a view of a record cannot add to it.
501
+ const whole = raw.filter((r) => r.projection === undefined);
502
+ for (const r of whole) fold(held, r.seq, r.obj, r.file, r.line, run, defects, false);
503
+
504
+ const notes = foldProjections(run, raw, held, defects, whole.length === 0);
505
+
506
+ // Sidecars stand in a record's place: resolve them, then fold the record each one holds back in
507
+ // at the `seq` it names, so a caller reading the records does not have to know where a record
508
+ // was stored (§5).
509
+ const sidecars: SidecarResolution[] = [];
510
+ for (const [seq, entry] of [...held.entries()].sort((a, b) => a[0] - b[0])) {
511
+ if (entry.base.event !== "sidecar") continue;
512
+ const { resolution, stored } = resolveSidecar(seq, entry, opts.sidecars);
513
+ sidecars.push(resolution);
514
+ if (resolution.state === "unchecked") continue; // nothing was looked at, so nothing is a defect
515
+ if (resolution.state !== "intact") {
516
+ defects.push(defect(`sidecar.${resolution.state}` as DefectCode, SIDECAR_SECTION, entry.file, entry.line, sidecarProblem(resolution), { run, source: resolution.source >= 0 ? resolution.source : undefined }));
517
+ continue;
518
+ }
519
+ if (stored) fold(held, resolution.source, stored, entry.file, entry.line, run, defects, true, entry.projectedBy);
520
+ }
521
+
522
+ // Which `seq` values this run is known by at all, the projections' own opening lines aside: a
523
+ // line that reaches the stream alone is not one any other copy could be withholding (§8).
524
+ const known = [...held.entries()]
525
+ .filter(([, e]) => e.base.event !== "history.transform")
526
+ .map(([seq]) => seq);
527
+ for (const note of notes) {
528
+ const own = raw.filter((r) => r.projection?.file === note.file);
529
+ const carried = new Set(own.map((r) => r.seq));
530
+ const stored = new Set(own.filter((r) => r.obj.event === "sidecar" && Number.isInteger(r.obj.source)).map((r) => r.obj.source as number));
531
+ note.withheld = known.filter((seq) => !carried.has(seq) && !stored.has(seq)).sort((a, b) => a - b);
532
+ note.superseded.sort((a, b) => a - b);
533
+ }
534
+
535
+ const records: LoadedRecord[] = [...held.entries()]
536
+ .sort((a, b) => a[0] - b[0])
537
+ .map(([seq, entry]) => {
538
+ const validation = opts.validate.validate(entry.base);
539
+ if (validation.state === "invalid") {
540
+ defects.push(defect("record.invalid", "§4.5", entry.file, entry.line, `${validation.schema.id}@${validation.schema.version}: ${validation.errors.join("; ")}`, { run }));
541
+ } else if (validation.state === "partial") {
542
+ defects.push(defect("record.unknown_pair", "§4.5", entry.file, entry.line, `no schema for ${validation.schema.id}@${validation.schema.version}; reported as partial, never as validated`, { run }));
543
+ }
544
+ return {
545
+ run, seq,
546
+ event: typeof entry.base.event === "string" ? entry.base.event : null,
547
+ t: Number.isInteger(entry.base.t) ? (entry.base.t as number) : null,
548
+ file: entry.file, line: entry.line, copies: entry.copies, fromSidecar: entry.fromSidecar,
549
+ projected: entry.projectedBy.length > 0, projectedBy: [...entry.projectedBy],
550
+ record: entry.base, validation,
551
+ };
552
+ });
553
+
554
+ const end = records.find((r) => r.event === "end");
555
+ const head = records.find((r) => r.event === "receipt.head");
556
+ const terminated = end !== undefined;
557
+ const status = end && Number.isInteger(end.record.status) ? (end.record.status as number) : null;
558
+ const redacted =
559
+ (end?.record.redacted === true) ||
560
+ (head !== undefined && head.record.redacted !== undefined) ||
561
+ records.some((r) => r.event === "redaction");
562
+
563
+ const reasons = new Set<string>();
564
+ for (const s of sidecars) if (s.state !== "intact") reasons.add(`sidecar.${s.state}`);
565
+ if (!terminated) reasons.add("receipt.no_end");
566
+ if (status !== null && status !== 0) reasons.add("end.status_nonzero");
567
+ if (redacted) reasons.add("receipt.redacted");
568
+
569
+ const duplicates = raw.length + sidecars.filter((s) => s.state === "intact" && opts.sidecars).length - records.length;
570
+
571
+ return {
572
+ run, sources, records, sidecars, projections: notes,
573
+ quarantined: defects.filter((d) => QUARANTINE_CODES.has(d.code)),
574
+ defects,
575
+ duplicates: duplicates < 0 ? 0 : duplicates,
576
+ terminated, status, redacted,
577
+ replay: { unavailable: reasons.size > 0, reasons: [...reasons] },
578
+ };
579
+ }
580
+
581
+ function sidecarProblem(s: SidecarResolution): string {
582
+ switch (s.state) {
583
+ case "missing": return `the sidecar holding seq ${s.source} is not at ${s.path}; the bundle is unavailable for replay`;
584
+ case "digest_mismatch": return `the sidecar at ${s.path} does not match its declared sha256; the bundle is unavailable for replay`;
585
+ case "bytes_mismatch": return `the sidecar at ${s.path} is ${String(s.actual?.bytes)} bytes, not the declared ${String(s.declared.bytes)}`;
586
+ case "escapes_bundle": return `the sidecar path ${s.path} is absolute or leaves the receipt's directory and was not read`;
587
+ case "unparseable": return `the sidecar at ${s.path} is not a JSON object, so it holds no record`;
588
+ case "unreadable": return `the sidecar event does not name a source, path, bytes and sha256, or its file could not be read`;
589
+ case "unchecked": return `the sidecar at ${s.path} was not resolved, so nothing about its stored bytes is established`;
590
+ case "intact": return "intact";
591
+ }
592
+ }
593
+
594
+ // ---- the entry points ---------------------------------------------------------------------
595
+
596
+ function settle(opts: ReadOptions): Required<Pick<ReadOptions, "sidecars" | "validate">> {
597
+ return { sidecars: opts.sidecars !== false, validate: opts.validate ?? validator() };
598
+ }
599
+
600
+ /** Read one receipt file. A file holding the lines of more than one run yields one bundle per run. */
601
+ export function readReceiptFile(file: string, opts: ReadOptions = {}): FileRead {
602
+ const settled = settle(opts);
603
+ const where = opts.where ?? "other";
604
+ const path = resolve(file);
605
+ const scanned = scan(path);
606
+ const raw = markProjections(scanned.raw, path, where);
607
+ const fileRun = where === "history" ? null : runOfFileName(path);
608
+ const runs = [...new Set(raw.map((r) => r.run))].sort();
609
+ const quarantined = attribute(scanned.quarantined, runs, fileRun);
610
+ const bundles = runs.map((run) =>
611
+ buildBundle(
612
+ run,
613
+ raw.filter((r) => r.run === run),
614
+ [{ where, receipt: path }],
615
+ quarantined.filter((q) => q.run === run),
616
+ settled,
617
+ ),
618
+ );
619
+ return { file: path, where, run: fileRun, lines: scanned.lines, runs, quarantined, bundles };
620
+ }
621
+
622
+ /**
623
+ * Read one segment of the shared history stream (§8): a file holding whole runs from every tool
624
+ * that wrote to it, so it yields one bundle per run, and a copy in it may be a projection of the
625
+ * receipt copy. It is `readReceiptFile` under the `history` label, because a segment is the same
626
+ * bytes under the same reader rules; what differs is that its name names a date rather than a run.
627
+ */
628
+ export function readHistorySegment(file: string, opts: ReadOptions = {}): FileRead {
629
+ return readReceiptFile(file, { ...opts, where: "history" });
630
+ }
631
+
632
+ /**
633
+ * Every run in both receipt locations for a working directory. A run found in more than one
634
+ * location is one bundle naming both files, with its records deduplicated by `(run, seq)` (§1.3).
635
+ */
636
+ export function loadReceipts(opts: LoadOptions = {}): Load {
637
+ const settled = settle(opts);
638
+ const locations = receiptLocations(opts);
639
+ const files: FileSummary[] = [];
640
+ const rawByRun = new Map<string, Raw[]>();
641
+ const sourcesByRun = new Map<string, BundleSource[]>();
642
+ const quarantinedByRun = new Map<string, Defect[]>();
643
+ const quarantined: Defect[] = [];
644
+ const loose: Defect[] = [];
645
+
646
+ // One file that cannot be opened is reported, not thrown: a load over a repository's history
647
+ // should not lose the other bundles to it.
648
+ const take = (file: string, where: Where): void => {
649
+ const fileRun = where === "history" ? null : runOfFileName(file);
650
+ let scanned: Scan;
651
+ try { scanned = scan(file); } catch (e) {
652
+ const what = where === "history" ? "the history segment" : "the receipt";
653
+ const code: DefectCode = where === "history" ? "history.unreadable" : "receipt.unreadable";
654
+ const problem = `${what} could not be read: ${e instanceof Error ? e.message : String(e)}`;
655
+ loose.push(defect(code, where === "history" ? "§8" : "§5", file, 0, problem, { run: fileRun }));
656
+ files.push({ file, where, run: fileRun, lines: 0, runs: [], quarantined: [] });
657
+ return;
658
+ }
659
+ const raw = markProjections(scanned.raw, file, where);
660
+ const runs = [...new Set(raw.map((r) => r.run))].sort();
661
+ const attributed = attribute(scanned.quarantined, runs, fileRun);
662
+ files.push({ file, where, run: fileRun, lines: scanned.lines, runs, quarantined: attributed });
663
+ quarantined.push(...attributed);
664
+ for (const run of runs) {
665
+ push(rawByRun, run, raw.filter((r) => r.run === run));
666
+ push(sourcesByRun, run, [{ where, receipt: file }]);
667
+ push(quarantinedByRun, run, attributed.filter((q) => q.run === run));
668
+ }
669
+ };
670
+
671
+ for (const location of locations) {
672
+ if (!location.present) continue;
673
+ for (const name of readdirSync(location.dir).sort()) {
674
+ if (!name.endsWith(".jsonl")) continue;
675
+ const file = join(location.dir, name);
676
+ if (!isFile(file)) continue;
677
+ take(file, location.where);
678
+ }
679
+ }
680
+
681
+ // The shared stream is opt-in and this reader never goes looking for it (§8): a caller that has
682
+ // a segment names it, and it is read after the receipts, so a projected copy is folded over the
683
+ // record rather than the other way round. Which copy wins does not depend on that order — the
684
+ // preference is by the transform line — but the order is stated rather than incidental.
685
+ for (const named of opts.history ?? []) take(resolve(named), "history");
686
+
687
+ const bundles = [...rawByRun.keys()].sort().map((run) =>
688
+ buildBundle(run, rawByRun.get(run)!, sourcesByRun.get(run)!, quarantinedByRun.get(run) ?? [], settled),
689
+ );
690
+
691
+ const records = bundles.flatMap((b) => b.records);
692
+ const state = (s: Validation["state"]) => records.filter((r) => r.validation.state === s).length;
693
+ return {
694
+ locations, files, bundles, quarantined, defects: loose,
695
+ counts: {
696
+ bundles: bundles.length,
697
+ records: records.length,
698
+ validated: state("validated"),
699
+ invalid: state("invalid"),
700
+ partial: state("partial"),
701
+ unvalidated: state("unvalidated"),
702
+ quarantined: quarantined.length,
703
+ duplicates: bundles.reduce((n, b) => n + b.duplicates, 0),
704
+ },
705
+ };
706
+ }
707
+
708
+ function push<T>(map: Map<string, T[]>, key: string, values: T[]): void {
709
+ const held = map.get(key);
710
+ if (held) held.push(...values); else map.set(key, [...values]);
711
+ }