@tangle-network/agent-eval 0.189.0 → 0.190.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 (146) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/README.md +3 -2
  3. package/dist/adapters/http.d.ts +10 -1
  4. package/dist/adapters/http.d.ts.map +1 -1
  5. package/dist/adapters/http.js +75 -7
  6. package/dist/adapters/http.js.map +1 -1
  7. package/dist/analyst/index.d.ts +66 -3
  8. package/dist/analyst/index.d.ts.map +1 -1
  9. package/dist/analyst/index.js +212 -7
  10. package/dist/analyst/index.js.map +1 -1
  11. package/dist/{benchmark-command-BhhAYstU.js → benchmark-command-BXIr_k8D.js} +12 -11
  12. package/dist/benchmark-command-BXIr_k8D.js.map +1 -0
  13. package/dist/benchmarks/index.d.ts +1 -1
  14. package/dist/benchmarks/index.js +3 -3
  15. package/dist/campaign/index.d.ts +4 -4
  16. package/dist/campaign/index.js +7 -7
  17. package/dist/{campaign-BWoSQPSU.js → campaign-B7q74uIh.js} +256 -11
  18. package/dist/campaign-B7q74uIh.js.map +1 -0
  19. package/dist/{campaign-evidence-CBlGJ3kC.js → campaign-evidence-D40-LHIL.js} +6 -5
  20. package/dist/campaign-evidence-D40-LHIL.js.map +1 -0
  21. package/dist/{chat-client-C4dg7Ng_.js → chat-client-B_ItsSBw.js} +2 -2
  22. package/dist/{chat-client-C4dg7Ng_.js.map → chat-client-B_ItsSBw.js.map} +1 -1
  23. package/dist/{chat-json-call-JVGbfx95.js → chat-json-call-CXHBvUz8.js} +2 -2
  24. package/dist/{chat-json-call-JVGbfx95.js.map → chat-json-call-CXHBvUz8.js.map} +1 -1
  25. package/dist/claim-BGOUqoMq.d.ts +38 -0
  26. package/dist/claim-BGOUqoMq.d.ts.map +1 -0
  27. package/dist/cli.js +3 -3
  28. package/dist/contract/index.d.ts +4 -4
  29. package/dist/contract/index.js +8 -8
  30. package/dist/{default-registry-m2jhbG6Q.js → default-registry-16I-Bxlf.js} +2 -2
  31. package/dist/{default-registry-m2jhbG6Q.js.map → default-registry-16I-Bxlf.js.map} +1 -1
  32. package/dist/{define-agent-eval-98sgUaC1.js → define-agent-eval-DPizhHfy.js} +4 -4
  33. package/dist/{define-agent-eval-98sgUaC1.js.map → define-agent-eval-DPizhHfy.js.map} +1 -1
  34. package/dist/{define-agent-eval-q6890HU4.d.ts → define-agent-eval-DblGedQk.d.ts} +4 -3
  35. package/dist/define-agent-eval-DblGedQk.d.ts.map +1 -0
  36. package/dist/diagnosis/index.d.ts +14 -2
  37. package/dist/diagnosis/index.d.ts.map +1 -1
  38. package/dist/diagnosis/index.js +11 -4
  39. package/dist/diagnosis/index.js.map +1 -1
  40. package/dist/{dspy-rlm-engine-DLYttKBm.js → dspy-rlm-engine-Cs5LzJ-f.js} +3 -3
  41. package/dist/{dspy-rlm-engine-DLYttKBm.js.map → dspy-rlm-engine-Cs5LzJ-f.js.map} +1 -1
  42. package/dist/{eval-campaign-C0Q1Eeo_.js → eval-campaign-CwsBn0Gm.js} +2 -2
  43. package/dist/{eval-campaign-C0Q1Eeo_.js.map → eval-campaign-CwsBn0Gm.js.map} +1 -1
  44. package/dist/experiment/index.d.ts +2 -1
  45. package/dist/experiment/index.d.ts.map +1 -1
  46. package/dist/experiment/index.js +1 -1
  47. package/dist/exporters-XMCYJlqT.d.ts +161 -0
  48. package/dist/exporters-XMCYJlqT.d.ts.map +1 -0
  49. package/dist/{external-optimizer-process-C3quNeKV.js → external-optimizer-process-BnSmrkgL.js} +3 -3
  50. package/dist/{external-optimizer-process-C3quNeKV.js.map → external-optimizer-process-BnSmrkgL.js.map} +1 -1
  51. package/dist/{external-optimizer-subprocess-BDwgKLO1.js → external-optimizer-subprocess-kbcPu5po.js} +3 -3
  52. package/dist/{external-optimizer-subprocess-BDwgKLO1.js.map → external-optimizer-subprocess-kbcPu5po.js.map} +1 -1
  53. package/dist/{feedback-trajectory-B3ZSkfAq.d.ts → feedback-trajectory-BYjh7NEM.d.ts} +2 -2
  54. package/dist/{feedback-trajectory-B3ZSkfAq.d.ts.map → feedback-trajectory-BYjh7NEM.d.ts.map} +1 -1
  55. package/dist/{index-CnJOPR_E.d.ts → index-CJv56rhX.d.ts} +673 -244
  56. package/dist/index-CJv56rhX.d.ts.map +1 -0
  57. package/dist/{index-Dk1dOUfm.d.ts → index-CWoIJHmy.d.ts} +4 -4
  58. package/dist/{index-Dk1dOUfm.d.ts.map → index-CWoIJHmy.d.ts.map} +1 -1
  59. package/dist/{index-Bcc9PkOz.d.ts → index-D4pC7Tvd.d.ts} +3 -2
  60. package/dist/index-D4pC7Tvd.d.ts.map +1 -0
  61. package/dist/{index-BqDJ6fUK.d.ts → index-I4UJGRno.d.ts} +74 -2
  62. package/dist/index-I4UJGRno.d.ts.map +1 -0
  63. package/dist/index.d.ts +66 -17
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +375 -31
  66. package/dist/index.js.map +1 -1
  67. package/dist/{journal-CDP0Vhx_.js → journal-c3qY0SDP.js} +246 -5
  68. package/dist/journal-c3qY0SDP.js.map +1 -0
  69. package/dist/{kind-factory-BGwN0nE6.js → kind-factory-ByZeXDqF.js} +2 -2
  70. package/dist/{kind-factory-BGwN0nE6.js.map → kind-factory-ByZeXDqF.js.map} +1 -1
  71. package/dist/ledger-core/index.d.ts +2 -2
  72. package/dist/ledger-core/index.js +2 -2
  73. package/dist/{llm-client-DF9bPNYA.js → llm-client-KYQBh9C8.js} +2 -2
  74. package/dist/{llm-client-DF9bPNYA.js.map → llm-client-KYQBh9C8.js.map} +1 -1
  75. package/dist/{llm-judge-M_l_WXw2.js → llm-judge-BnxAv7ed.js} +1892 -1378
  76. package/dist/llm-judge-BnxAv7ed.js.map +1 -0
  77. package/dist/mint-C9Lojt1V.d.ts +147 -0
  78. package/dist/mint-C9Lojt1V.d.ts.map +1 -0
  79. package/dist/openapi.json +1 -1
  80. package/dist/pipelines/index.d.ts +1 -1
  81. package/dist/pipelines/index.js +1 -1
  82. package/dist/pipelines/index.js.map +1 -1
  83. package/dist/{produced-state-BOY98IJO.js → produced-state-BXjXJHJT.js} +4 -4
  84. package/dist/{produced-state-BOY98IJO.js.map → produced-state-BXjXJHJT.js.map} +1 -1
  85. package/dist/{raw-provider-sink-C96CcqeG.js → raw-provider-sink-DYh4Bszw.js} +2 -2
  86. package/dist/{raw-provider-sink-C96CcqeG.js.map → raw-provider-sink-DYh4Bszw.js.map} +1 -1
  87. package/dist/{redact-DxwlUAvh.js → redact-B7rt9Zot.js} +130 -10
  88. package/dist/redact-B7rt9Zot.js.map +1 -0
  89. package/dist/{redact-DPoH1-OW.d.ts → redact-CopuMxll.d.ts} +7 -5
  90. package/dist/redact-CopuMxll.d.ts.map +1 -0
  91. package/dist/rl.d.ts +3 -2
  92. package/dist/rl.d.ts.map +1 -1
  93. package/dist/rl.js +1 -1
  94. package/dist/rollout/index.d.ts +3 -2
  95. package/dist/search-ledger-types-C9anU2DX.d.ts +489 -0
  96. package/dist/search-ledger-types-C9anU2DX.d.ts.map +1 -0
  97. package/dist/{semantic-concept-judge-Cm2K2wAo.js → semantic-concept-judge-ClB73cei.js} +6 -6
  98. package/dist/{semantic-concept-judge-Cm2K2wAo.js.map → semantic-concept-judge-ClB73cei.js.map} +1 -1
  99. package/dist/{server-C8XvqCg8.js → server-DtetGGoA.js} +2 -2
  100. package/dist/{server-C8XvqCg8.js.map → server-DtetGGoA.js.map} +1 -1
  101. package/dist/{skillopt-optimization-method-BVSB676o.js → skillopt-optimization-method-l2vDBtKp.js} +363 -18
  102. package/dist/skillopt-optimization-method-l2vDBtKp.js.map +1 -0
  103. package/dist/{spans-W0o8pbEg.d.ts → spans-BWtjk_9c.d.ts} +2 -2
  104. package/dist/{spans-W0o8pbEg.d.ts.map → spans-BWtjk_9c.d.ts.map} +1 -1
  105. package/dist/{statistical-heldout-plAHG82H.d.ts → statistical-heldout-CLpjYffJ.d.ts} +2 -36
  106. package/dist/statistical-heldout-CLpjYffJ.d.ts.map +1 -0
  107. package/dist/{store-otlp-D0AV4cvB.js → store-otlp-84DH0OEH.js} +2 -2
  108. package/dist/{store-otlp-D0AV4cvB.js.map → store-otlp-84DH0OEH.js.map} +1 -1
  109. package/dist/{store-tool-spans-8PAyhRqb.d.ts → store-tool-spans-BBXs8hDP.d.ts} +2 -2
  110. package/dist/{store-tool-spans-8PAyhRqb.d.ts.map → store-tool-spans-BBXs8hDP.d.ts.map} +1 -1
  111. package/dist/{store-tool-spans-B_0mXvYl.js → store-tool-spans-DUiqyHvR.js} +5 -5
  112. package/dist/{store-tool-spans-B_0mXvYl.js.map → store-tool-spans-DUiqyHvR.js.map} +1 -1
  113. package/dist/traces.d.ts +3 -63
  114. package/dist/traces.d.ts.map +1 -1
  115. package/dist/traces.js +6 -195
  116. package/dist/traces.js.map +1 -1
  117. package/dist/wire/index.d.ts +1 -1
  118. package/dist/wire/index.js +1 -1
  119. package/docs/adapters-observability.md +31 -27
  120. package/docs/charter.md +1 -1
  121. package/docs/design/mlbenchmarks-book-review.md +1 -1
  122. package/docs/distributed-driver.md +1 -5
  123. package/docs/experiment.md +15 -0
  124. package/docs/public-api.md +181 -71
  125. package/docs/redaction.md +7 -1
  126. package/docs/search-ledger.md +174 -0
  127. package/docs/trace-contracts.md +48 -3
  128. package/package.json +1 -1
  129. package/dist/benchmark-command-BhhAYstU.js.map +0 -1
  130. package/dist/campaign-BWoSQPSU.js.map +0 -1
  131. package/dist/campaign-evidence-CBlGJ3kC.js.map +0 -1
  132. package/dist/define-agent-eval-q6890HU4.d.ts.map +0 -1
  133. package/dist/index-Bcc9PkOz.d.ts.map +0 -1
  134. package/dist/index-BqDJ6fUK.d.ts.map +0 -1
  135. package/dist/index-CnJOPR_E.d.ts.map +0 -1
  136. package/dist/journal-CDP0Vhx_.js.map +0 -1
  137. package/dist/llm-judge-M_l_WXw2.js.map +0 -1
  138. package/dist/mint-DsS38v5c.d.ts +0 -305
  139. package/dist/mint-DsS38v5c.d.ts.map +0 -1
  140. package/dist/redact-DPoH1-OW.d.ts.map +0 -1
  141. package/dist/redact-DxwlUAvh.js.map +0 -1
  142. package/dist/search-ledger-types-D7KDVg-o.d.ts +0 -302
  143. package/dist/search-ledger-types-D7KDVg-o.d.ts.map +0 -1
  144. package/dist/skillopt-optimization-method-BVSB676o.js.map +0 -1
  145. package/dist/statistical-heldout-plAHG82H.d.ts.map +0 -1
  146. package/docs/search-history-receipts.md +0 -233
@@ -479,6 +479,118 @@ function fsyncDirectory(path) {
479
479
  }
480
480
  }
481
481
  //#endregion
482
+ //#region src/ledger-core/projector-snapshot.ts
483
+ /**
484
+ * Projector snapshot — the cache that lets opening a large journal replay
485
+ * only its tail.
486
+ *
487
+ * `trusted-head.ts`'s pin proves a journal's length and prefix content
488
+ * without trusting a producer's summary; it does not make PROVING that
489
+ * cheap. Every open still walks every row from sequence 0, parses it through
490
+ * the domain codec, and applies it to a fresh projector, because that was the
491
+ * only way this module knew to rebuild `Projection`.
492
+ *
493
+ * This file adds one more sidecar: `<journal>.snapshot` holds a `Projection`
494
+ * a codec that opts in (`snapshotProjection` on its `LedgerJournalCodec`)
495
+ * serialized, alongside the `(sequence, entryHash)` it was taken after. A
496
+ * reader that finds one still verifies the generic hash chain of every row up
497
+ * to that checkpoint — self-consistency and chain linkage, the same two
498
+ * checks `journal.ts`'s `admitEntry` runs on every row — because that
499
+ * verification is what the pin's guarantee actually rests on (see
500
+ * `trusted-head.ts`'s module comment: an entry hash commits to its whole
501
+ * prefix, so there is no way to prove a prefix unchanged without touching
502
+ * every byte of it at least once). What the cache lets a reader skip is the
503
+ * codec's OWN parsing (`parseEntry`, typically zod validation) and the domain
504
+ * projector's `apply` for every row before the checkpoint: rows that already
505
+ * passed both once, at write time, and whose bytes the chain walk has just
506
+ * proven are unchanged since. Only the checkpoint row itself, and every row
507
+ * after it, go through the full domain path — exactly as an already-open
508
+ * instance that had verified up to there would already do.
509
+ *
510
+ * A snapshot that does not match the journal's actual bytes — a chain that
511
+ * does not reach the claimed hash, a wrong entry count for its byte range —
512
+ * fails loudly with the same kind of `integrityError` a full replay would
513
+ * raise for the same tampered bytes; the tampering is real regardless of
514
+ * which path found it, so it is never swallowed in favor of a fallback that
515
+ * would silently re-read the same bytes a different way. Only a MISSING
516
+ * cache file, or one this journal's current pin cannot vouch for at all
517
+ * (§`journal.ts`'s `seedFromSnapshot`), is treated as "no cache" and falls
518
+ * back to full verification.
519
+ */
520
+ /** Sibling cache file for a journal, alongside its `.head` pin. */
521
+ function projectorSnapshotPathFor(journalPath) {
522
+ return `${journalPath}.snapshot`;
523
+ }
524
+ const RECOVERY = " Restore the file, or remove it and let the journal rebuild it at its next checkpoint.";
525
+ /** The cached snapshot, or null when none has been written. Present but
526
+ * unparseable is corruption of the cache itself, not its absence, and fails
527
+ * loudly for the same reason `readTrustedHeadFile` does: silently treating it
528
+ * as "no cache" would just make the next read replay from scratch without
529
+ * ever explaining why the cache stopped working. */
530
+ function readProjectorSnapshotFile(path, context) {
531
+ let text;
532
+ try {
533
+ text = readFileSync(path, "utf8");
534
+ } catch (error) {
535
+ if (error.code === "ENOENT") return null;
536
+ throw context.integrityError(`${context.subject} projector snapshot ${path} could not be read.${RECOVERY}`, { cause: error });
537
+ }
538
+ let raw;
539
+ try {
540
+ raw = JSON.parse(text);
541
+ } catch (error) {
542
+ throw context.integrityError(`${context.subject} projector snapshot ${path} is not valid JSON.${RECOVERY}`, { cause: error });
543
+ }
544
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw context.integrityError(`${context.subject} projector snapshot ${path} is not an object.${RECOVERY}`);
545
+ const record = raw;
546
+ const keys = Object.keys(record).sort();
547
+ if (keys.length !== 3 || keys[0] !== "byteLength" || keys[1] !== "head" || keys[2] !== "projection") throw context.integrityError(`${context.subject} projector snapshot ${path} has keys [${keys.join(", ")}], expected [byteLength, head, projection].${RECOVERY}`);
548
+ const { byteLength, head, projection } = record;
549
+ if (typeof byteLength !== "number" || !Number.isSafeInteger(byteLength) || byteLength <= 0) throw context.integrityError(`${context.subject} projector snapshot ${path} byteLength is not a positive integer.${RECOVERY}`);
550
+ if (typeof head !== "object" || head === null || Array.isArray(head)) throw context.integrityError(`${context.subject} projector snapshot ${path} head is not an object.${RECOVERY}`);
551
+ const headRecord = head;
552
+ const headKeys = Object.keys(headRecord).sort();
553
+ if (headKeys.length !== 2 || headKeys[0] !== "entryHash" || headKeys[1] !== "sequence") throw context.integrityError(`${context.subject} projector snapshot ${path} head has keys [${headKeys.join(", ")}], expected [entryHash, sequence].${RECOVERY}`);
554
+ const { sequence, entryHash } = headRecord;
555
+ if (typeof sequence !== "number" || !Number.isSafeInteger(sequence) || sequence < 0) throw context.integrityError(`${context.subject} projector snapshot ${path} head.sequence is not a non-negative integer.${RECOVERY}`);
556
+ if (typeof entryHash !== "string" || !LEDGER_HASH_PATTERN.test(entryHash)) throw context.integrityError(`${context.subject} projector snapshot ${path} head.entryHash is not a sha256 digest.${RECOVERY}`);
557
+ return {
558
+ head: {
559
+ sequence,
560
+ entryHash
561
+ },
562
+ byteLength,
563
+ projection
564
+ };
565
+ }
566
+ /** Publish a snapshot by write-then-rename, so a crash leaves either the
567
+ * previous cache or the new one and never a torn file a reader would have to
568
+ * refuse. Not re-exported from the package's public surface, for the same
569
+ * reason `writeTrustedHeadFile` is not: it takes no lock and enforces no
570
+ * monotonicity against the journal it caches. `FileLedgerJournal` is the only
571
+ * writer, always immediately after its own `sync()` has verified the exact
572
+ * state it is about to cache. */
573
+ function writeProjectorSnapshotFile(path, snapshot, context) {
574
+ const body = JSON.stringify({
575
+ byteLength: snapshot.byteLength,
576
+ head: snapshot.head,
577
+ projection: snapshot.projection
578
+ });
579
+ try {
580
+ writeLedgerFileAtomically(path, `${body}\n`, context);
581
+ } catch (error) {
582
+ throw context.integrityError(`${context.subject} projector snapshot ${path} could not be written`, { cause: error });
583
+ }
584
+ }
585
+ /** Discard a journal's cached snapshot. A missing cache is not an error: this
586
+ * is how `clearTrustedHead()` keeps the two sidecars from disagreeing about
587
+ * what the journal's writer has vouched for, and it is safe to call whether
588
+ * or not a cache ever existed. */
589
+ function removeProjectorSnapshotFile(path, context) {
590
+ removeLedgerFile(path, context);
591
+ removeLedgerFile(`${path}.tmp`, context);
592
+ }
593
+ //#endregion
482
594
  //#region src/ledger-core/trusted-head.ts
483
595
  /**
484
596
  * Trusted head — the pin that makes deletion detectable.
@@ -665,6 +777,14 @@ function verifyEntriesAgainstTrustedHead(entries, head, context, naming) {
665
777
  * instance cannot see is a same-length rewrite of rows before its head; a new
666
778
  * instance verifies every row and refuses one.
667
779
  *
780
+ * That "whole file once" is still every row, however long ago it was already
781
+ * proven unchanged. A codec that opts into `snapshotProjection` lets a fresh
782
+ * instance shortcut it: `projector-snapshot.ts`'s cache still walks the whole
783
+ * hash chain up to its checkpoint — nothing is exempted from tamper detection
784
+ * — but only the checkpoint row and the true tail after it go through the
785
+ * codec's own parsing and projector; the FileLedgerJournalOptions.projectorSnapshot
786
+ * option controls how often a pinning append refreshes it.
787
+ *
668
788
  * Domain vocabulary lives entirely in the consumer's codec: entry schema
669
789
  * validation, the constant header fields stamped into every entry, the error
670
790
  * taxonomy, and the state machine replayed over verified entries.
@@ -684,16 +804,22 @@ var FileLedgerJournal = class {
684
804
  path;
685
805
  /** Sibling file holding this journal's trusted head. */
686
806
  trustedHeadPath;
807
+ /** Sibling file holding this journal's cached projector snapshot, if its
808
+ * codec opts in. */
809
+ projectorSnapshotPath;
687
810
  codec;
688
811
  mutex;
689
812
  requireTrustedHead;
813
+ snapshotEvery;
690
814
  verified = null;
691
815
  constructor(path, codec, options = {}) {
692
816
  this.path = resolve(path);
693
817
  this.trustedHeadPath = trustedHeadPathFor(this.path);
818
+ this.projectorSnapshotPath = projectorSnapshotPathFor(this.path);
694
819
  this.codec = codec;
695
820
  this.mutex = mutexFor(this.path);
696
821
  this.requireTrustedHead = options.requireTrustedHead === true;
822
+ this.snapshotEvery = codec.snapshotProjection !== void 0 && options.projectorSnapshot !== void 0 ? options.projectorSnapshot.everyEntries : null;
697
823
  }
698
824
  async replay() {
699
825
  return this.locked(() => this.sync(this.requireTrustedHead).projector.snapshot());
@@ -736,6 +862,7 @@ var FileLedgerJournal = class {
736
862
  };
737
863
  writeTrustedHeadFile(this.trustedHeadPath, head, this.codec);
738
864
  state.pin = head;
865
+ this.maybeWriteProjectorSnapshot(state);
739
866
  }
740
867
  return {
741
868
  entry,
@@ -761,6 +888,7 @@ var FileLedgerJournal = class {
761
888
  };
762
889
  writeTrustedHeadFile(this.trustedHeadPath, head, this.codec);
763
890
  state.pin = head;
891
+ if (this.snapshotEvery !== null) this.writeProjectorSnapshotNow(state);
764
892
  return head;
765
893
  });
766
894
  }
@@ -774,7 +902,11 @@ var FileLedgerJournal = class {
774
902
  async clearTrustedHead() {
775
903
  return this.locked(() => {
776
904
  const removal = clearTrustedHeadFile(this.trustedHeadPath, this.codec);
777
- if (this.verified !== null) this.verified.pin = null;
905
+ removeProjectorSnapshotFile(this.projectorSnapshotPath, this.codec);
906
+ if (this.verified !== null) {
907
+ this.verified.pin = null;
908
+ this.verified.snapshotSequence = null;
909
+ }
778
910
  return removal;
779
911
  });
780
912
  }
@@ -810,7 +942,7 @@ var FileLedgerJournal = class {
810
942
  dev: stats.dev,
811
943
  ino: stats.ino
812
944
  };
813
- if (state === null || state.identity !== null && (state.identity.dev !== identity.dev || state.identity.ino !== identity.ino) || size < state.size || !headInPlace(fd, state.size, state.head?.row ?? null)) state = emptyJournal(this.codec);
945
+ if (state === null || state.identity !== null && (state.identity.dev !== identity.dev || state.identity.ino !== identity.ino) || size < state.size || !headInPlace(fd, state.size, state.head?.row ?? null)) state = (size > 0 ? this.seedFromSnapshot(fd, size) : null) ?? emptyJournal(this.codec);
814
946
  state.identity = identity;
815
947
  this.verified = state;
816
948
  if (size > state.size) extendJournal(state, readRange(fd, state.size, size), this.path, this.codec);
@@ -861,6 +993,114 @@ var FileLedgerJournal = class {
861
993
  };
862
994
  writeTrustedHeadFile(this.trustedHeadPath, head, this.codec);
863
995
  state.pin = head;
996
+ this.maybeWriteProjectorSnapshot(state);
997
+ }
998
+ /** Refresh the cached projector snapshot once the current pin has moved at
999
+ * least `snapshotEvery` entries past the last one cached, so the write cost
1000
+ * amortizes across many appends and a fresh open's uncached tail stays
1001
+ * bounded by that interval no matter how large the journal grows. A no-op
1002
+ * when the codec does not support the cache, the option is off, or the
1003
+ * head this call just pinned is not actually new (the idempotent-append
1004
+ * path can call this after re-acknowledging an already-durable entry). */
1005
+ maybeWriteProjectorSnapshot(state) {
1006
+ if (this.codec.snapshotProjection === void 0 || this.snapshotEvery === null) return;
1007
+ if (state.pin === null || state.pin.sequence !== state.head?.entry.sequence) return;
1008
+ if (state.snapshotSequence !== null && state.pin.sequence - state.snapshotSequence < this.snapshotEvery) return;
1009
+ this.writeProjectorSnapshotNow(state);
1010
+ }
1011
+ /** Serialize the live projector and write it as the cache, unconditionally.
1012
+ * Callers have already established that `state.pin` names `state.head`, so
1013
+ * the cache and the pin agree on the checkpoint by construction. */
1014
+ writeProjectorSnapshotNow(state) {
1015
+ const head = state.pin;
1016
+ const projection = this.codec.snapshotProjection.serialize(state.projector.snapshot());
1017
+ const snapshot = {
1018
+ head,
1019
+ byteLength: state.size,
1020
+ projection
1021
+ };
1022
+ writeProjectorSnapshotFile(this.projectorSnapshotPath, snapshot, this.codec);
1023
+ state.snapshotSequence = head.sequence;
1024
+ }
1025
+ /** Seed a fresh verified state from the cached projector snapshot, or null
1026
+ * when there is none this reader can use — a missing or out-of-reach
1027
+ * cache, never something this instance found actually wrong. Everything it
1028
+ * DOES accept is checked against the real bytes: rows 0 through the
1029
+ * checkpoint are read and chain-verified exactly as `admitEntry` would
1030
+ * verify them (self-consistent hash, correct sequence, linked previousHash,
1031
+ * unique eventId), just without this codec's own `parseEntry` or
1032
+ * `apply` — the checkpoint row itself still goes through both, through the
1033
+ * ordinary `parseRow`, so it is exactly as trustworthy as any entry a full
1034
+ * replay would produce. Any mismatch found along the way throws the same
1035
+ * `integrityError` a full replay of the same bytes would raise, because it
1036
+ * is the same tampering either path would have found; this is never turned
1037
+ * into a quiet fallback that would just re-read the same bytes differently
1038
+ * and risk reporting a different, more confusing failure — or none. */
1039
+ seedFromSnapshot(fd, size) {
1040
+ const restore = this.codec.snapshotProjection;
1041
+ if (restore === void 0) return null;
1042
+ const cached = readProjectorSnapshotFile(this.projectorSnapshotPath, this.codec);
1043
+ if (cached === null) return null;
1044
+ const pin = readTrustedHeadFile(this.trustedHeadPath, this.codec);
1045
+ if (pin === null || cached.head.sequence > pin.sequence) return null;
1046
+ if (cached.byteLength <= 0 || cached.byteLength > size) return null;
1047
+ const rows = splitRows(readRange(fd, 0, cached.byteLength), this.path, this.codec);
1048
+ if (rows.length !== cached.head.sequence + 1) throw this.codec.integrityError(`${this.codec.subject} ${this.path} projector snapshot ${this.projectorSnapshotPath} expects ${cached.head.sequence + 1} entries in its first ${cached.byteLength} bytes but the journal has ${rows.length}`);
1049
+ const offsets = [];
1050
+ const sequenceByEventId = /* @__PURE__ */ new Map();
1051
+ let previousHash = null;
1052
+ for (let index = 0; index < rows.length - 1; index += 1) {
1053
+ const row = rows[index];
1054
+ offsets.push(row.start);
1055
+ let raw;
1056
+ try {
1057
+ raw = JSON.parse(row.text);
1058
+ } catch (error) {
1059
+ throw this.codec.integrityError(`${this.codec.subject} ${this.path} has invalid JSON at line ${index + 1}`, { cause: error });
1060
+ }
1061
+ if (canonicalString(raw) !== row.text) throw this.codec.integrityError(`${this.codec.subject} ${this.path} has non-canonical bytes at line ${index + 1}`);
1062
+ const fields = raw;
1063
+ if (fields.sequence !== index) throw this.codec.integrityError(`entry at line ${index + 1} has sequence ${String(fields.sequence)}, expected ${index}`);
1064
+ if ((fields.previousHash ?? null) !== previousHash) throw this.codec.integrityError(`entry at line ${index + 1} does not extend the previous hash`);
1065
+ const { entryHash, ...material } = raw;
1066
+ const expected = hashCanonical(material);
1067
+ if (entryHash !== expected) throw this.codec.integrityError(`entry at line ${index + 1} hash mismatch: expected ${expected}, got ${String(entryHash)}`);
1068
+ const eventId = fields.event?.eventId;
1069
+ if (typeof eventId !== "string" || eventId === "") throw this.codec.integrityError(`entry at line ${index + 1} has no eventId`);
1070
+ if (sequenceByEventId.has(eventId)) throw this.codec.integrityError(`duplicate eventId ${eventId} in durable ledger`);
1071
+ sequenceByEventId.set(eventId, index);
1072
+ previousHash = entryHash;
1073
+ }
1074
+ const boundary = rows[rows.length - 1];
1075
+ offsets.push(boundary.start);
1076
+ const entry = parseRow(boundary.text, {
1077
+ path: this.path,
1078
+ line: cached.head.sequence + 1
1079
+ }, this.codec);
1080
+ const { entryHash: _boundaryHash, ...boundaryMaterial } = entry;
1081
+ if (entry.sequence !== cached.head.sequence || entry.previousHash !== previousHash || entry.entryHash !== cached.head.entryHash || hashCanonical(boundaryMaterial) !== cached.head.entryHash) throw this.codec.integrityError(`${this.codec.subject} ${this.path} projector snapshot ${this.projectorSnapshotPath} does not match the journal at sequence ${cached.head.sequence}`);
1082
+ this.codec.checkEntryHeader(entry, cached.head.sequence);
1083
+ if (sequenceByEventId.has(entry.event.eventId)) throw this.codec.integrityError(`duplicate eventId ${entry.event.eventId} in durable ledger`);
1084
+ sequenceByEventId.set(entry.event.eventId, entry.sequence);
1085
+ let projector;
1086
+ try {
1087
+ projector = restore.restore(cached.projection);
1088
+ } catch (error) {
1089
+ throw this.codec.integrityError(`${this.codec.subject} ${this.path} projector snapshot ${this.projectorSnapshotPath} could not be restored`, { cause: error });
1090
+ }
1091
+ return {
1092
+ identity: null,
1093
+ size: cached.byteLength,
1094
+ offsets,
1095
+ head: {
1096
+ entry,
1097
+ row: Buffer.from(`${boundary.text}\n`, "utf8")
1098
+ },
1099
+ sequenceByEventId,
1100
+ projector,
1101
+ pin: null,
1102
+ snapshotSequence: cached.head.sequence
1103
+ };
864
1104
  }
865
1105
  /** The verified entry at `sequence`, read back from the file. The rows from
866
1106
  * it to the head are re-read and must chain to the verified head hash, which
@@ -912,7 +1152,8 @@ function emptyJournal(codec) {
912
1152
  head: null,
913
1153
  sequenceByEventId: /* @__PURE__ */ new Map(),
914
1154
  projector: codec.createProjector(),
915
- pin: null
1155
+ pin: null,
1156
+ snapshotSequence: null
916
1157
  };
917
1158
  }
918
1159
  /** Verify and apply the rows in `bytes`, which start at the state's verified
@@ -1005,6 +1246,6 @@ function readRange(fd, start, end) {
1005
1246
  return bytes;
1006
1247
  }
1007
1248
  //#endregion
1008
- export { verifyEntriesAgainstTrustedHead as a, withLedgerFileLock as c, mapConcurrent as d, mapConcurrentRange as f, tryAcquireAtomicFileLock as h, trustedHeadPathFor as i, writeLedgerFileAtomically as l, probeAtomicFileLock as m, replayLedgerText as n, appendLedgerLine as o, AtomicFileLockError as p, readTrustedHeadFile as r, tryWithLedgerFileLock as s, FileLedgerJournal as t, Mutex as u };
1249
+ export { tryAcquireAtomicFileLock as _, verifyEntriesAgainstTrustedHead as a, appendLedgerLine as c, writeLedgerFileAtomically as d, Mutex as f, probeAtomicFileLock as g, AtomicFileLockError as h, trustedHeadPathFor as i, tryWithLedgerFileLock as l, mapConcurrentRange as m, replayLedgerText as n, projectorSnapshotPathFor as o, mapConcurrent as p, readTrustedHeadFile as r, readProjectorSnapshotFile as s, FileLedgerJournal as t, withLedgerFileLock as u };
1009
1250
 
1010
- //# sourceMappingURL=journal-CDP0Vhx_.js.map
1251
+ //# sourceMappingURL=journal-c3qY0SDP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"journal-c3qY0SDP.js","names":[],"sources":["../src/ledger-core/atomic-file-lock.ts","../src/concurrency.ts","../src/ledger-core/journal-file.ts","../src/ledger-core/projector-snapshot.ts","../src/ledger-core/trusted-head.ts","../src/ledger-core/journal.ts"],"sourcesContent":["/** Crash-safe filesystem lock shared by campaign persistence and run exclusion. */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n constants,\n existsSync,\n fsyncSync,\n linkSync,\n openSync,\n readFileSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport { hostname } from 'node:os'\n\nexport interface AtomicFileLockOwner {\n readonly pid: number\n readonly host: string\n readonly nonce: string\n}\n\nexport interface AtomicFileLock {\n readonly owner: AtomicFileLockOwner\n release(): void\n}\n\nexport type AtomicFileLockUnavailable =\n | { readonly acquired: false; readonly reason: 'held'; readonly holder: AtomicFileLockOwner }\n | { readonly acquired: false; readonly reason: 'recovery' }\n\nexport type AtomicFileLockAcquisition =\n | { readonly acquired: true; readonly lock: AtomicFileLock }\n | AtomicFileLockUnavailable\n\nexport interface AtomicFileLockOptions {\n readonly lockPath: string\n readonly pid?: number\n}\n\nexport class AtomicFileLockError extends Error {\n override readonly name = 'AtomicFileLockError'\n}\n\ntype OwnerState =\n | { readonly state: 'missing' }\n | { readonly state: 'stale'; readonly owner: AtomicFileLockOwner }\n | { readonly state: 'held'; readonly owner: AtomicFileLockOwner }\n\n/** Report whether another lock path prevents acquisition without modifying it. */\nexport function probeAtomicFileLock(\n options: AtomicFileLockOptions,\n): AtomicFileLockUnavailable | null {\n if (existsSync(recoveryPath(options.lockPath))) return { acquired: false, reason: 'recovery' }\n const state = ownerState(options.lockPath)\n if (state.state === 'held') {\n return { acquired: false, reason: 'held', holder: state.owner }\n }\n return null\n}\n\n/**\n * Try to acquire a complete, uniquely-owned lock inode.\n *\n * A hard link publishes fully-written owner metadata atomically. Stale-owner\n * removal is serialized so one reclaimer cannot delete a new owner's lock.\n */\nexport function tryAcquireAtomicFileLock(\n options: AtomicFileLockOptions,\n): AtomicFileLockAcquisition {\n const pid = options.pid ?? process.pid\n if (!Number.isSafeInteger(pid) || pid <= 0) {\n throw new AtomicFileLockError('atomic file lock pid must be a positive integer')\n }\n const owner: AtomicFileLockOwner = { pid, host: hostname(), nonce: randomUUID() }\n for (let attempt = 0; attempt < 8; attempt += 1) {\n if (existsSync(recoveryPath(options.lockPath))) {\n const recovery = tryAcquireRecoveryLease(options.lockPath, owner, attempt)\n if (!recovery) return { acquired: false, reason: 'recovery' }\n try {\n return recoverLock(options.lockPath, owner, attempt)\n } finally {\n recovery.release()\n }\n }\n if (tryLinkOwner(options.lockPath, owner, `acquire.${attempt}`)) {\n return acquired(options.lockPath, owner)\n }\n\n const holder = ownerState(options.lockPath)\n if (holder.state === 'missing') continue\n if (holder.state === 'held') {\n return { acquired: false, reason: 'held', holder: holder.owner }\n }\n\n const recovery = tryAcquireRecoveryLease(options.lockPath, owner, attempt)\n if (!recovery) return { acquired: false, reason: 'recovery' }\n try {\n return recoverLock(options.lockPath, owner, attempt)\n } finally {\n recovery.release()\n }\n }\n\n throw new AtomicFileLockError(`could not acquire atomic file lock ${options.lockPath}`)\n}\n\ninterface RecoveryLease {\n release(): void\n}\n\nfunction tryAcquireRecoveryLease(\n lockPath: string,\n owner: AtomicFileLockOwner,\n attempt: number,\n): RecoveryLease | null {\n let leasePath = recoveryPath(lockPath)\n const staleOwners: Array<{ path: string; owner: AtomicFileLockOwner }> = []\n\n for (let depth = 0; depth < 64; depth += 1) {\n const state = ownerState(leasePath)\n if (state.state === 'missing') {\n if (!tryLinkOwner(leasePath, owner, `reclaim.${attempt}.${depth}`)) continue\n return {\n release: () => {\n for (const stale of staleOwners) releaseOwnedPath(stale.path, stale.owner)\n releaseOwnedPath(leasePath, owner)\n },\n }\n }\n if (state.state === 'held') return null\n staleOwners.push({ path: leasePath, owner: state.owner })\n leasePath = `${leasePath}.next.${state.owner.nonce}`\n }\n\n throw new AtomicFileLockError(`atomic file lock recovery chain is too deep (${lockPath})`)\n}\n\nfunction recoverLock(\n lockPath: string,\n owner: AtomicFileLockOwner,\n attempt: number,\n): AtomicFileLockAcquisition {\n const current = ownerState(lockPath)\n if (current.state === 'held') {\n return { acquired: false, reason: 'held', holder: current.owner }\n }\n if (current.state === 'stale') {\n const tombstone = `${lockPath}.stale.${owner.nonce}.${attempt}`\n try {\n renameSync(lockPath, tombstone)\n unlinkSync(tombstone)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n }\n if (tryLinkOwner(lockPath, owner, `recovered.${attempt}`)) {\n return acquired(lockPath, owner)\n }\n const holder = ownerState(lockPath)\n if (holder.state === 'held') {\n return { acquired: false, reason: 'held', holder: holder.owner }\n }\n return { acquired: false, reason: 'recovery' }\n}\n\nfunction acquired(lockPath: string, owner: AtomicFileLockOwner): AtomicFileLockAcquisition {\n return {\n acquired: true,\n lock: {\n owner,\n release: () => releaseOwnedPath(lockPath, owner),\n },\n }\n}\n\nfunction tryLinkOwner(lockPath: string, owner: AtomicFileLockOwner, suffix: string): boolean {\n const ownerPath = `${lockPath}.${owner.pid}.${owner.nonce}.${suffix}.owner`\n const descriptor = openSync(\n ownerPath,\n constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,\n 0o600,\n )\n try {\n writeFileSync(descriptor, `${canonicalOwner(owner)}\\n`, 'utf8')\n fsyncSync(descriptor)\n } catch (error) {\n closeSync(descriptor)\n unlinkIfExists(ownerPath)\n throw error\n }\n closeSync(descriptor)\n\n try {\n linkSync(ownerPath, lockPath)\n return true\n } catch (error) {\n if (!isAlreadyExists(error)) throw error\n return false\n } finally {\n unlinkIfExists(ownerPath)\n }\n}\n\nfunction ownerState(lockPath: string): OwnerState {\n const owner = readOwner(lockPath)\n if (!owner) return { state: 'missing' }\n if (owner.host !== hostname()) return { state: 'held', owner }\n try {\n process.kill(owner.pid, 0)\n return { state: 'held', owner }\n } catch (error) {\n if (isNoSuchProcess(error)) return { state: 'stale', owner }\n return { state: 'held', owner }\n }\n}\n\nfunction readOwner(lockPath: string): AtomicFileLockOwner | undefined {\n let contents: string\n try {\n contents = readFileSync(lockPath, 'utf8').trim()\n } catch (error) {\n if (isMissing(error)) return undefined\n throw error\n }\n\n let value: unknown\n try {\n value = JSON.parse(contents)\n } catch (error) {\n throw invalidOwner(lockPath, error)\n }\n if (!isOwner(value)) throw invalidOwner(lockPath)\n return value\n}\n\nfunction isOwner(value: unknown): value is AtomicFileLockOwner {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const record = value as Record<string, unknown>\n return (\n Object.keys(record).length === 3 &&\n Number.isSafeInteger(record.pid) &&\n Number(record.pid) > 0 &&\n typeof record.host === 'string' &&\n record.host.trim().length > 0 &&\n typeof record.nonce === 'string' &&\n record.nonce.trim().length > 0\n )\n}\n\nfunction invalidOwner(lockPath: string, cause?: unknown): AtomicFileLockError {\n const error = new AtomicFileLockError(\n `atomic file lock has an invalid owner (${lockPath}); refusing unsafe recovery`,\n )\n if (cause !== undefined) Object.defineProperty(error, 'cause', { value: cause })\n return error\n}\n\nfunction releaseOwnedPath(lockPath: string, owner: AtomicFileLockOwner): void {\n const current = readOwner(lockPath)\n if (!current) return\n if (canonicalOwner(current) !== canonicalOwner(owner)) {\n throw new AtomicFileLockError(`atomic file lock owner changed before release (${lockPath})`)\n }\n try {\n unlinkSync(lockPath)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n}\n\nfunction canonicalOwner(owner: AtomicFileLockOwner): string {\n return JSON.stringify({ host: owner.host, nonce: owner.nonce, pid: owner.pid })\n}\n\nfunction recoveryPath(lockPath: string): string {\n return `${lockPath}.reclaim`\n}\n\nfunction isAlreadyExists(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'EEXIST'\n}\n\nfunction isMissing(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'ENOENT'\n}\n\nfunction isNoSuchProcess(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'ESRCH'\n}\n\nfunction unlinkIfExists(path: string): void {\n try {\n unlinkSync(path)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n}\n","/**\n * concurrency — small primitives the evolution loop needs.\n *\n * `Mutex` is a zero-dep async lock with FIFO fairness. The evolution loop\n * uses it to serialise checkout/build/commit sequences inside a single\n * pool slot, and to gate concurrent JSONL writers (see\n * `lockedJsonlReferenceReplayStore`).\n *\n * Deliberately minimal — no priority queue, no timeouts. If you need\n * those, swap to `async-mutex` at the call site.\n */\n\nexport class Mutex {\n private locked = false\n private readonly waiters: Array<() => void> = []\n\n async acquire(): Promise<() => void> {\n if (!this.locked) {\n this.locked = true\n return () => this.release()\n }\n return new Promise<() => void>((resolve) => {\n this.waiters.push(() => {\n resolve(() => this.release())\n })\n })\n }\n\n private release(): void {\n const next = this.waiters.shift()\n if (next) {\n next()\n } else {\n this.locked = false\n }\n }\n\n async runExclusive<T>(fn: () => Promise<T> | T): Promise<T> {\n const release = await this.acquire()\n try {\n return await fn()\n } finally {\n release()\n }\n }\n\n /** True iff someone holds the lock right now. Diagnostics only. */\n get isLocked(): boolean {\n return this.locked\n }\n\n /** Pending waiter count. Diagnostics only. */\n get pending(): number {\n return this.waiters.length\n }\n}\n\nexport interface MapConcurrentRangeOptions<R> {\n count: number\n maxConcurrency: number\n label: string\n signal?: AbortSignal\n map(index: number, signal: AbortSignal): Promise<R>\n}\n\n/** Map an integer range with bounded work, cancellation, and first-error cleanup. */\nexport async function mapConcurrentRange<R>(options: MapConcurrentRangeOptions<R>): Promise<R[]> {\n if (!Number.isSafeInteger(options.count) || options.count < 0) {\n throw new Error(`${options.label} count must be a non-negative integer`)\n }\n if (!Number.isSafeInteger(options.maxConcurrency) || options.maxConcurrency < 1) {\n throw new Error(`${options.label} maxConcurrency must be a positive integer`)\n }\n\n const controller = new AbortController()\n const abortFromCaller = () => controller.abort(options.signal?.reason)\n if (options.signal?.aborted) abortFromCaller()\n else options.signal?.addEventListener('abort', abortFromCaller, { once: true })\n\n const results = new Array<R>(options.count)\n let nextIndex = 0\n let failed = false\n let firstFailure: unknown\n const workers = Array.from(\n { length: Math.min(options.maxConcurrency, options.count) },\n async () => {\n while (!controller.signal.aborted) {\n const index = nextIndex\n nextIndex += 1\n if (index >= options.count) return\n try {\n results[index] = await options.map(index, controller.signal)\n } catch (error) {\n if (!failed) {\n failed = true\n firstFailure = error\n controller.abort(error)\n }\n return\n }\n }\n },\n )\n\n try {\n await Promise.all(workers)\n if (options.signal?.aborted) throw abortError(options.signal, options.label)\n if (failed) throw firstFailure\n if (controller.signal.aborted) throw abortError(controller.signal, options.label)\n return results\n } finally {\n options.signal?.removeEventListener('abort', abortFromCaller)\n }\n}\n\n/**\n * Map independent work with a fixed worker count while preserving input order.\n * After the first rejection, no new items start; already-running work is allowed\n * to settle before the returned promise rejects. Partial results are discarded.\n */\nexport async function mapConcurrent<T, R>(\n items: readonly T[],\n concurrency: number,\n map: (item: T, index: number, signal: AbortSignal) => Promise<R>,\n signal?: AbortSignal,\n): Promise<R[]> {\n return mapConcurrentRange({\n count: items.length,\n maxConcurrency: concurrency,\n label: 'mapConcurrent',\n signal,\n map(index, signal) {\n return map(items[index]!, index, signal)\n },\n })\n}\n\nfunction abortError(signal: AbortSignal, label: string): Error {\n return signal.reason instanceof Error ? signal.reason : new Error(`${label} aborted`)\n}\n","/** Filesystem durability and cross-process exclusion for append-only journal files. */\n\nimport {\n closeSync,\n constants,\n fstatSync,\n fsyncSync,\n mkdirSync,\n openSync,\n readSync,\n renameSync,\n rmSync,\n writeSync,\n} from 'node:fs'\nimport { dirname } from 'node:path'\nimport { AtomicFileLockError, tryAcquireAtomicFileLock } from './atomic-file-lock'\n\n/** How a journal binding reports file-layer faults in its own error taxonomy. */\nexport interface LedgerFileContext {\n /** Noun used in error messages, e.g. 'search ledger'. */\n subject: string\n integrityError(message: string, options?: { cause?: unknown }): Error\n}\n\n/** Append one already-serialized line; the write is fsynced (file and directory)\n * before returning so an acknowledged append survives a crash. */\nexport function appendLedgerLine(path: string, line: string, context: LedgerFileContext): void {\n mkdirSync(dirname(path), { recursive: true })\n recoverTornFinalWrite(path, context)\n const fd = openSync(path, constants.O_CREAT | constants.O_WRONLY | constants.O_APPEND, 0o600)\n try {\n writeAll(fd, Buffer.from(line, 'utf8'), context)\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n fsyncDirectory(dirname(path))\n}\n\nfunction recoverTornFinalWrite(path: string, context: LedgerFileContext): void {\n let fd: number\n try {\n fd = openSync(path, constants.O_RDWR)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n throw context.integrityError(`${context.subject} ${path} could not be opened for recovery`, {\n cause: error,\n })\n }\n\n try {\n const size = fstatSync(fd).size\n if (size === 0 || readByte(fd, size - 1) === 0x0a) return\n const tailStart = findFinalLineStart(fd, size)\n const replacement = Buffer.alloc(size - tailStart, 0x20)\n replacement[replacement.length - 1] = 0x0a\n writeAllAt(fd, replacement, tailStart, context)\n fsyncSync(fd)\n } catch (error) {\n throw context.integrityError(\n `${context.subject} ${path} has an unrecoverable final journal write`,\n { cause: error },\n )\n } finally {\n closeSync(fd)\n }\n}\n\n/** Replace a small sidecar file whole: write a temporary sibling, fsync it,\n * then rename over the target. A reader therefore sees the previous contents\n * or the new ones, never a partial file. */\nexport function writeLedgerFileAtomically(\n path: string,\n contents: string,\n context: LedgerFileContext,\n): void {\n const directory = dirname(path)\n mkdirSync(directory, { recursive: true })\n const temporaryPath = `${path}.tmp`\n const fd = openSync(\n temporaryPath,\n constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC,\n 0o600,\n )\n try {\n writeAll(fd, Buffer.from(contents, 'utf8'), context)\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n renameSync(temporaryPath, path)\n fsyncDirectory(directory)\n}\n\n/** Remove whatever occupies a sidecar path and fsync its directory, so the\n * removal is as durable as the write that created it. False when the path was\n * already empty. Recursive because a sidecar path holding a directory is one of\n * the states this has to be able to clear, not one it can refuse. */\nexport function removeLedgerFile(path: string, context: LedgerFileContext): boolean {\n try {\n rmSync(path, { recursive: true })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false\n throw context.integrityError(`${context.subject} ${path} could not be removed`, {\n cause: error,\n })\n }\n fsyncDirectory(dirname(path))\n return true\n}\n\nexport function withLedgerFileLock<T>(path: string, context: LedgerFileContext, run: () => T): T {\n const result = tryWithLedgerFileLock(path, context, run)\n if (!result.acquired) {\n throw context.integrityError(`${context.subject} lock is held (${path})`)\n }\n return result.value\n}\n\nexport type FileLockResult<T> = { acquired: true; value: T } | { acquired: false }\n\nexport function tryWithLedgerFileLock<T>(\n path: string,\n context: LedgerFileContext,\n run: () => T,\n): FileLockResult<T> {\n mkdirSync(dirname(path), { recursive: true })\n const lockPath = `${path}.lock`\n try {\n const acquisition = tryAcquireAtomicFileLock({ lockPath })\n if (!acquisition.acquired) return { acquired: false }\n try {\n return { acquired: true, value: run() }\n } finally {\n acquisition.lock.release()\n }\n } catch (error) {\n if (error instanceof AtomicFileLockError) {\n throw context.integrityError(error.message, { cause: error })\n }\n throw error\n }\n}\n\nfunction writeAll(fd: number, bytes: Buffer, context: LedgerFileContext): void {\n let offset = 0\n while (offset < bytes.byteLength) {\n const written = writeSync(fd, bytes, offset, bytes.byteLength - offset)\n if (written <= 0) throw context.integrityError('filesystem wrote zero bytes')\n offset += written\n }\n}\n\nfunction writeAllAt(fd: number, bytes: Buffer, position: number, context: LedgerFileContext): void {\n let offset = 0\n while (offset < bytes.byteLength) {\n const written = writeSync(fd, bytes, offset, bytes.byteLength - offset, position + offset)\n if (written <= 0) throw context.integrityError('filesystem wrote zero bytes')\n offset += written\n }\n}\n\nfunction findFinalLineStart(fd: number, size: number): number {\n const chunk = Buffer.alloc(Math.min(4_096, size))\n let cursor = size\n while (cursor > 0) {\n const length = Math.min(chunk.byteLength, cursor)\n cursor -= length\n const read = readSync(fd, chunk, 0, length, cursor)\n for (let index = read - 1; index >= 0; index -= 1) {\n if (chunk[index] === 0x0a) return cursor + index + 1\n }\n }\n return 0\n}\n\nfunction readByte(fd: number, position: number): number {\n const byte = Buffer.allocUnsafe(1)\n const read = readSync(fd, byte, 0, 1, position)\n return read === 1 ? byte[0]! : -1\n}\n\nfunction fsyncDirectory(path: string): void {\n const fd = openSync(path, constants.O_RDONLY)\n try {\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n}\n","/**\n * Projector snapshot — the cache that lets opening a large journal replay\n * only its tail.\n *\n * `trusted-head.ts`'s pin proves a journal's length and prefix content\n * without trusting a producer's summary; it does not make PROVING that\n * cheap. Every open still walks every row from sequence 0, parses it through\n * the domain codec, and applies it to a fresh projector, because that was the\n * only way this module knew to rebuild `Projection`.\n *\n * This file adds one more sidecar: `<journal>.snapshot` holds a `Projection`\n * a codec that opts in (`snapshotProjection` on its `LedgerJournalCodec`)\n * serialized, alongside the `(sequence, entryHash)` it was taken after. A\n * reader that finds one still verifies the generic hash chain of every row up\n * to that checkpoint — self-consistency and chain linkage, the same two\n * checks `journal.ts`'s `admitEntry` runs on every row — because that\n * verification is what the pin's guarantee actually rests on (see\n * `trusted-head.ts`'s module comment: an entry hash commits to its whole\n * prefix, so there is no way to prove a prefix unchanged without touching\n * every byte of it at least once). What the cache lets a reader skip is the\n * codec's OWN parsing (`parseEntry`, typically zod validation) and the domain\n * projector's `apply` for every row before the checkpoint: rows that already\n * passed both once, at write time, and whose bytes the chain walk has just\n * proven are unchanged since. Only the checkpoint row itself, and every row\n * after it, go through the full domain path — exactly as an already-open\n * instance that had verified up to there would already do.\n *\n * A snapshot that does not match the journal's actual bytes — a chain that\n * does not reach the claimed hash, a wrong entry count for its byte range —\n * fails loudly with the same kind of `integrityError` a full replay would\n * raise for the same tampered bytes; the tampering is real regardless of\n * which path found it, so it is never swallowed in favor of a fallback that\n * would silently re-read the same bytes a different way. Only a MISSING\n * cache file, or one this journal's current pin cannot vouch for at all\n * (§`journal.ts`'s `seedFromSnapshot`), is treated as \"no cache\" and falls\n * back to full verification.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { LEDGER_HASH_PATTERN, type LedgerHash } from './canonical'\nimport { type LedgerFileContext, removeLedgerFile, writeLedgerFileAtomically } from './journal-file'\nimport type { LedgerTrustedHead } from './trusted-head'\n\n/** A cached projection and the pinned entry it was taken after. */\nexport interface LedgerProjectorSnapshot {\n head: LedgerTrustedHead\n /** Byte length of the journal file up to and including the pinned entry's\n * own row. Where the rows this snapshot covers end and the tail it did not\n * cover begins. */\n byteLength: number\n /** The codec's serialized projection. Opaque to this module. */\n projection: unknown\n}\n\n/** Sibling cache file for a journal, alongside its `.head` pin. */\nexport function projectorSnapshotPathFor(journalPath: string): string {\n return `${journalPath}.snapshot`\n}\n\nconst RECOVERY =\n ' Restore the file, or remove it and let the journal rebuild it at its next checkpoint.'\n\n/** The cached snapshot, or null when none has been written. Present but\n * unparseable is corruption of the cache itself, not its absence, and fails\n * loudly for the same reason `readTrustedHeadFile` does: silently treating it\n * as \"no cache\" would just make the next read replay from scratch without\n * ever explaining why the cache stopped working. */\nexport function readProjectorSnapshotFile(\n path: string,\n context: LedgerFileContext,\n): LedgerProjectorSnapshot | null {\n let text: string\n try {\n text = readFileSync(path, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} could not be read.${RECOVERY}`,\n { cause: error },\n )\n }\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch (error) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} is not valid JSON.${RECOVERY}`,\n { cause: error },\n )\n }\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} is not an object.${RECOVERY}`,\n )\n }\n const record = raw as Record<string, unknown>\n const keys = Object.keys(record).sort()\n if (\n keys.length !== 3 ||\n keys[0] !== 'byteLength' ||\n keys[1] !== 'head' ||\n keys[2] !== 'projection'\n ) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} has keys [${keys.join(', ')}], expected [byteLength, head, projection].${RECOVERY}`,\n )\n }\n const { byteLength, head, projection } = record\n if (typeof byteLength !== 'number' || !Number.isSafeInteger(byteLength) || byteLength <= 0) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} byteLength is not a positive integer.${RECOVERY}`,\n )\n }\n if (typeof head !== 'object' || head === null || Array.isArray(head)) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} head is not an object.${RECOVERY}`,\n )\n }\n const headRecord = head as Record<string, unknown>\n const headKeys = Object.keys(headRecord).sort()\n if (headKeys.length !== 2 || headKeys[0] !== 'entryHash' || headKeys[1] !== 'sequence') {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} head has keys [${headKeys.join(', ')}], expected [entryHash, sequence].${RECOVERY}`,\n )\n }\n const { sequence, entryHash } = headRecord\n if (typeof sequence !== 'number' || !Number.isSafeInteger(sequence) || sequence < 0) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} head.sequence is not a non-negative integer.${RECOVERY}`,\n )\n }\n if (typeof entryHash !== 'string' || !LEDGER_HASH_PATTERN.test(entryHash)) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} head.entryHash is not a sha256 digest.${RECOVERY}`,\n )\n }\n return {\n head: { sequence, entryHash: entryHash as LedgerHash },\n byteLength,\n projection,\n }\n}\n\n/** Publish a snapshot by write-then-rename, so a crash leaves either the\n * previous cache or the new one and never a torn file a reader would have to\n * refuse. Not re-exported from the package's public surface, for the same\n * reason `writeTrustedHeadFile` is not: it takes no lock and enforces no\n * monotonicity against the journal it caches. `FileLedgerJournal` is the only\n * writer, always immediately after its own `sync()` has verified the exact\n * state it is about to cache. */\nexport function writeProjectorSnapshotFile(\n path: string,\n snapshot: LedgerProjectorSnapshot,\n context: LedgerFileContext,\n): void {\n const body = JSON.stringify({\n byteLength: snapshot.byteLength,\n head: snapshot.head,\n projection: snapshot.projection,\n })\n try {\n writeLedgerFileAtomically(path, `${body}\\n`, context)\n } catch (error) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} could not be written`,\n { cause: error },\n )\n }\n}\n\n/** Discard a journal's cached snapshot. A missing cache is not an error: this\n * is how `clearTrustedHead()` keeps the two sidecars from disagreeing about\n * what the journal's writer has vouched for, and it is safe to call whether\n * or not a cache ever existed. */\nexport function removeProjectorSnapshotFile(path: string, context: LedgerFileContext): void {\n removeLedgerFile(path, context)\n removeLedgerFile(`${path}.tmp`, context)\n}\n","/**\n * Trusted head — the pin that makes deletion detectable.\n *\n * ## What the chain binds\n *\n * Every entry hashes the journal header, its sequence, the previous entry's\n * hash, and its event, so editing, reordering, or removing an entry in the\n * middle of a journal invalidates every hash after it. What a hash chain\n * cannot bind is its own length. Dropping entries off the END leaves a shorter\n * journal that is internally perfect, and rebuilding a journal from sequence 0\n * with recomputed hashes produces a different, equally perfect chain. For an\n * audit log of candidate registrations and promotion decisions that is the\n * difference between a record of a search that happened and a record of one\n * that did not.\n *\n * ## What the pin binds\n *\n * `<journal>.head` holds `{sequence, entryHash}` for one entry a writer\n * actually appended, in a file separate from the journal it attests. Each\n * entry hash commits to the entire prefix before it, so checking that the\n * entry at exactly `sequence` still carries `entryHash` proves two things at\n * once: the journal is at least `sequence + 1` entries long, and those entries\n * are byte-for-byte the ones the writer saw. A journal that merely grew past\n * the pin still verifies; a truncated, rolled-back, or wholesale-rewritten one\n * cannot.\n *\n * ## What the pin does NOT defend against\n *\n * The pin is a second file, not a signature. A writer with access to BOTH the\n * journal and its pin can rewrite both consistently, and the result verifies.\n * Pinning raises the cost of undetected tampering from one file to two and\n * nothing more; defending against a writer who holds both requires an anchor\n * outside this store entirely — a signed head, or a digest published to an\n * append-only service the tamperer does not control.\n *\n * Deleting the pin file downgrades a pinned journal to an unpinned one, which\n * cannot be distinguished from a journal written before pinning existed. That\n * is what `requireTrustedHead` is for: a journal opened under it refuses to\n * read at all once a non-empty journal has no pin.\n *\n * ## Abandoning a pin\n *\n * A pin outlives the journal it attests: deleting or rebuilding the journal\n * leaves a pin naming history the file no longer carries, and every read is\n * refused because that is precisely the deletion the pin exists to catch. The\n * refusal names the pin file, and `clearTrustedHeadFile` is the explicit way to\n * discard it — the same downgrade a writer with filesystem access could already\n * perform with `rm`, made reachable through the API so it is a decision in the\n * code rather than an undocumented manual step. It returns the guarantee it\n * gave up and writes no record of its own; a caller that needs the discard on\n * the record has to write one.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { canonicalString, LEDGER_HASH_PATTERN, type LedgerHash } from './canonical'\nimport { type LedgerFileContext, removeLedgerFile, writeLedgerFileAtomically } from './journal-file'\n\n/** A `(sequence, entryHash)` pair a writer pinned outside the journal. */\nexport interface LedgerTrustedHead {\n sequence: number\n entryHash: LedgerHash\n}\n\n/** Minimum entry shape the anchor check needs. */\nexport interface LedgerAnchoredEntry {\n sequence: number\n entryHash: LedgerHash\n}\n\n/** Sibling pin file for a journal — deliberately NOT the journal, so rewriting\n * the log is not enough to rewrite the trust recorded about it. */\nexport function trustedHeadPathFor(journalPath: string): string {\n return `${journalPath}.head`\n}\n\nconst TRUSTED_HEAD_RECOVERY =\n ' Restore the file, or discard the pin it held with clearTrustedHead().'\n\n/** The pin, or null when this journal has never been pinned. A pin that exists\n * but does not parse is corruption or tamper of the trust record itself and\n * fails loudly: reporting it as \"no pin\" would silently downgrade what the\n * journal can prove. */\nexport function readTrustedHeadFile(\n path: string,\n context: LedgerFileContext,\n): LedgerTrustedHead | null {\n let text: string\n try {\n text = readFileSync(path, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null\n throw context.integrityError(\n `${context.subject} trusted head ${path} could not be read.${TRUSTED_HEAD_RECOVERY}`,\n { cause: error },\n )\n }\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch (error) {\n throw context.integrityError(\n `${context.subject} trusted head ${path} is not valid JSON.${TRUSTED_HEAD_RECOVERY}`,\n { cause: error },\n )\n }\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n throw context.integrityError(\n `${context.subject} trusted head ${path} is not an object.${TRUSTED_HEAD_RECOVERY}`,\n )\n }\n const record = raw as Record<string, unknown>\n const keys = Object.keys(record).sort()\n if (keys.length !== 2 || keys[0] !== 'entryHash' || keys[1] !== 'sequence') {\n throw context.integrityError(\n `${context.subject} trusted head ${path} has keys [${keys.join(', ')}], expected [entryHash, sequence].${TRUSTED_HEAD_RECOVERY}`,\n )\n }\n const { sequence, entryHash } = record\n if (typeof sequence !== 'number' || !Number.isSafeInteger(sequence) || sequence < 0) {\n throw context.integrityError(\n `${context.subject} trusted head ${path} sequence is not a non-negative integer.${TRUSTED_HEAD_RECOVERY}`,\n )\n }\n if (typeof entryHash !== 'string' || !LEDGER_HASH_PATTERN.test(entryHash)) {\n throw context.integrityError(\n `${context.subject} trusted head ${path} entryHash is not a sha256 digest.${TRUSTED_HEAD_RECOVERY}`,\n )\n }\n return { sequence, entryHash: entryHash as LedgerHash }\n}\n\n/** Publish a pin by write-then-rename, so a crash leaves either the previous\n * pin or the new one and never a torn file that would lock a journal out of\n * its own trust record.\n *\n * Not re-exported from the package's public surface. It takes no lock, checks no\n * chain, and enforces no monotonicity, so a public form would be the one call\n * able to move a pin BACKWARD onto a journal it never read — which is the\n * truncation the pin exists to refuse. `FileLedgerJournal.pinTrustedHead` is\n * the public writer: locked, chain-verified, forward-only. */\nexport function writeTrustedHeadFile(\n path: string,\n head: LedgerTrustedHead,\n context: LedgerFileContext,\n): void {\n try {\n writeLedgerFileAtomically(path, `${canonicalString(head)}\\n`, context)\n } catch (error) {\n throw context.integrityError(`${context.subject} trusted head ${path} could not be written`, {\n cause: error,\n })\n }\n}\n\n/** Outcome of discarding a pin: the guarantee that was given up. `unreadable`\n * carries why the discarded pin could not be named — corruption, a permission\n * fault, a wrong file type — so a caller recording the decision never has to\n * treat \"no pin was there\" and \"the pin could not be read\" as one state.\n * `cleanupError` reports a stale atomic-write sibling that remains after the\n * actual pin was cleared. */\nexport type LedgerTrustedHeadRemoval =\n | { removed: true; head: LedgerTrustedHead; cleanupError?: string }\n | { removed: true; head: null; unreadable: string; cleanupError?: string }\n | { removed: false; cleanupError?: string }\n\n/** Discard a journal's pin, reporting what was discarded. The journal file is\n * untouched and reads as unpinned afterwards, so the next pinning append opens\n * a new pin at the entry it writes. This gives up the deletion guarantee for\n * every entry the pin covered; it is the recovery for a pin whose journal was\n * deliberately deleted or rebuilt, and the only way past a pin file that can no\n * longer be read at all. */\nexport function clearTrustedHeadFile(\n path: string,\n context: LedgerFileContext,\n): LedgerTrustedHeadRemoval {\n let head: LedgerTrustedHead | null = null\n let unreadable = ''\n try {\n head = readTrustedHeadFile(path, context)\n } catch (error) {\n // A pin nobody can read is precisely what clearing has to get past, so the\n // fault is reported on a removal that still happens rather than raised —\n // but it is reported, never flattened into \"there was no pin\".\n unreadable = error instanceof Error ? error.message : String(error)\n }\n const removed = removeLedgerFile(path, context)\n let cleanupError: string | undefined\n try {\n // Cleanup cannot block the requested trust-state change. Report a stale\n // atomic-write sibling so the caller can repair it before the next write.\n removeLedgerFile(`${path}.tmp`, context)\n } catch (error) {\n cleanupError = error instanceof Error ? error.message : String(error)\n }\n const cleanup = cleanupError === undefined ? {} : { cleanupError }\n if (!removed) return { removed: false, ...cleanup }\n if (head === null) return { removed: true, head: null, unreadable, ...cleanup }\n return { removed: true, head, ...cleanup }\n}\n\n/** How a journal is named when a trusted-head check refuses it. */\nexport interface LedgerTrustedHeadSubject {\n /** The journal in error messages, e.g. `search ledger /runs/a/ledger.jsonl`. */\n subject: string\n /** The sibling pin file, named in every refusal so the operator can see which\n * of the two files carries the claim being enforced. */\n trustedHeadPath: string\n}\n\n/** The entry at exactly `head.sequence` must still carry `head.entryHash`.\n * Entries must already have passed chain verification, which is what makes\n * index and sequence interchangeable here. An array serves as `entries`; a\n * journal that keeps no entries in memory passes a reader with the same\n * `length` and `at`. */\nexport function verifyEntriesAgainstTrustedHead(\n entries: Pick<readonly LedgerAnchoredEntry[], 'length' | 'at'>,\n head: LedgerTrustedHead,\n context: LedgerFileContext,\n naming: LedgerTrustedHeadSubject,\n): void {\n // A caller passing the bare subject string an untyped build would accept\n // destructures into two undefineds, which would corrupt the text of a\n // security refusal rather than fail. Refuse instead.\n if (typeof naming !== 'object' || naming === null) {\n throw new TypeError(\n 'verifyEntriesAgainstTrustedHead expects { subject, trustedHeadPath } as its fourth argument',\n )\n }\n const { subject, trustedHeadPath } = naming\n const pinned = entries.at(head.sequence)\n if (pinned === undefined) {\n throw context.integrityError(\n `${subject} trusted head ${trustedHeadPath} pins sequence ${head.sequence} (${head.entryHash}) but the journal has ${entries.length} entries — pinned history is missing (truncation, rollback, or rewrite). Restore the journal, or abandon the pinned history on purpose with clearTrustedHead().`,\n )\n }\n if (pinned.sequence !== head.sequence) {\n throw context.integrityError(\n `${subject} entry at index ${head.sequence} carries sequence ${pinned.sequence}; the chain was not verified before the trusted head ${trustedHeadPath}`,\n )\n }\n if (pinned.entryHash !== head.entryHash) {\n throw context.integrityError(\n `${subject} entry at pinned sequence ${head.sequence} carries ${pinned.entryHash} but the trusted head ${trustedHeadPath} recorded ${head.entryHash} — the journal was rewritten. Restore the journal, or abandon the pinned history on purpose with clearTrustedHead().`,\n )\n }\n}\n","/**\n * Generic durable append-only journal with a SHA-256 hash chain.\n *\n * The file format is canonical JSONL: every row is the canonical JSON encoding\n * (RFC 8785, object keys sorted recursively) of one entry, and every entry\n * hashes the previous entry's hash so the log is tamper-evident. Appends are\n * serialized in-process per path and across processes via a lock file, fsynced\n * before acknowledgement, and idempotent by `eventId`. A malformed,\n * non-canonical, truncated, reordered, or conflicting log fails loudly; a bad\n * row is never skipped.\n *\n * A hash chain binds each entry to its predecessor, which cannot prove that no\n * entry was removed from the end: a valid shorter prefix is still a valid\n * chain. `pinHead` records the appended entry in a sibling `<journal>.head`\n * file and every read re-verifies the journal against a pin that is present,\n * so truncation and wholesale rewrite are refused. `trusted-head.ts` carries\n * the full threat model, including what a pin does not defend against.\n *\n * Verification is incremental. A journal instance verifies its whole file once,\n * on its first call, and keeps the verified head, the live projector, and an\n * eventId index. Every later call checks that the head line it verified is\n * still in place, then reads, verifies, and projects only the bytes past it, so\n * an append reads one entry however long the journal is. Rows another writer\n * appended are verified as that tail. A file that was replaced, shrank, or no\n * longer carries the verified head is verified whole again. What an open\n * instance cannot see is a same-length rewrite of rows before its head; a new\n * instance verifies every row and refuses one.\n *\n * That \"whole file once\" is still every row, however long ago it was already\n * proven unchanged. A codec that opts into `snapshotProjection` lets a fresh\n * instance shortcut it: `projector-snapshot.ts`'s cache still walks the whole\n * hash chain up to its checkpoint — nothing is exempted from tamper detection\n * — but only the checkpoint row and the true tail after it go through the\n * codec's own parsing and projector; the FileLedgerJournalOptions.projectorSnapshot\n * option controls how often a pinning append refreshes it.\n *\n * Domain vocabulary lives entirely in the consumer's codec: entry schema\n * validation, the constant header fields stamped into every entry, the error\n * taxonomy, and the state machine replayed over verified entries.\n */\n\nimport { closeSync, constants, fstatSync, openSync, readSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { Mutex } from '../concurrency'\nimport { canonicalString, hashCanonical, type LedgerHash } from './canonical'\nimport { deepFreezeCanonicalJson } from './deep-freeze'\nimport { appendLedgerLine, type LedgerFileContext, withLedgerFileLock } from './journal-file'\nimport {\n type LedgerProjectorSnapshot,\n projectorSnapshotPathFor,\n readProjectorSnapshotFile,\n removeProjectorSnapshotFile,\n writeProjectorSnapshotFile,\n} from './projector-snapshot'\nimport {\n clearTrustedHeadFile,\n type LedgerTrustedHead,\n type LedgerTrustedHeadRemoval,\n readTrustedHeadFile,\n trustedHeadPathFor,\n verifyEntriesAgainstTrustedHead,\n writeTrustedHeadFile,\n} from './trusted-head'\n\n/** Minimum shape of a journal event: the idempotency key. */\nexport interface LedgerEventBase {\n eventId: string\n}\n\n/** Chain envelope every entry carries in addition to the journal's constant\n * header fields. `entryHash` covers the header, sequence, previous hash, and\n * event, so any rewrite of history invalidates every later entry. */\nexport interface LedgerChainFields<Event extends LedgerEventBase> {\n sequence: number\n previousHash: LedgerHash | null\n event: Event\n entryHash: LedgerHash\n}\n\nexport type LedgerEntryOf<Header extends object, Event extends LedgerEventBase> = Header &\n LedgerChainFields<Event>\n\nexport interface LedgerLineContext {\n path: string\n line: number\n}\n\n/** Domain state machine applied to chain-verified entries in order.\n *\n * One projector lives as long as its journal instance's verified state: the\n * journal applies each entry once, including entries appended later, and asks\n * for `snapshot()` after any number of them. `apply` throws (via the codec's\n * error taxonomy) on an invalid transition; after a throw the journal discards\n * the projector and replays the file into a new one, so `apply` need not undo\n * a partial update. Entries are deep-frozen before `apply` sees them. */\nexport interface LedgerProjector<Entry, Projection> {\n apply(entry: Entry, index: number): void\n /** The projection of every entry applied so far. A later `apply` must not\n * change a projection already returned, so a snapshot copies any state the\n * projector keeps mutating. */\n snapshot(): Projection\n}\n\n/** Serialize a projection into JSON-safe cache data, and rebuild a projector\n * from it whose next `apply` continues right after the entry it was taken\n * after — as if that projector had been live since sequence 0. Supplying\n * both opts a codec into the projector snapshot cache (`projector-snapshot.ts`):\n * a fresh journal open can then verify the generic hash chain of the rows\n * before a cached checkpoint without parsing or applying any of them through\n * this codec. Omit to disable the cache for this codec; every open then\n * fully replays through `createProjector`, exactly as before. */\nexport interface LedgerProjectorSnapshotCodec<Entry, Projection> {\n serialize(projection: Projection): unknown\n restore(serialized: unknown): LedgerProjector<Entry, Projection>\n}\n\nexport interface LedgerJournalCodec<\n Header extends object,\n Event extends LedgerEventBase,\n Projection,\n> extends LedgerFileContext {\n /** Constant fields stamped into every entry and covered by its hash. */\n header: Header\n conflictError(message: string): Error\n /** Validate one parsed JSON row into a typed entry. Must reject malformed\n * rows and non-canonical event encodings with the binding's own errors;\n * the journal itself verifies the stored bytes and the hash chain. A new\n * entry passes through the same parse before it is written, so the journal\n * never writes a row it would refuse to read. */\n parseEntry(raw: unknown, context: LedgerLineContext): LedgerEntryOf<Header, Event>\n /** Reject an entry whose constant header fields do not match this journal. */\n checkEntryHeader(entry: LedgerEntryOf<Header, Event>, index: number): void\n createProjector(): LedgerProjector<LedgerEntryOf<Header, Event>, Projection>\n snapshotProjection?: LedgerProjectorSnapshotCodec<LedgerEntryOf<Header, Event>, Projection>\n}\n\nexport interface LedgerAppendResult<Entry, Projection> {\n entry: Entry\n /** False when the exact event was already durably present. */\n appended: boolean\n projection: Projection\n}\n\nexport interface LedgerAppendOptions {\n /** Record the appended entry as this journal's trusted head, so a later read\n * can prove nothing was deleted from the end.\n *\n * On the idempotent path — the event is already durable — the pin moves up to\n * that entry only when the entry is ahead of it, along a chain this call has\n * just verified. So a pin write that failed after its row was fsynced is\n * repaired by the retry that idempotency already asks the caller for, and the\n * pin still only ever moves forward over history it has checked.\n *\n * A strict journal whose first pin write failed still refuses the retry\n * because it cannot distinguish that failure from a deleted pin. Recover it\n * explicitly with `pinTrustedHead()`; silently adopting the current file\n * would defeat `requireTrustedHead`. */\n pinHead?: boolean\n}\n\nexport interface FileLedgerJournalOptions {\n /** Refuse to read a non-empty journal that has no trusted head.\n *\n * Off by default because journals written before pinning have no pin and\n * must keep opening. Turn it on for a journal this process pins: without it,\n * deleting the sibling pin file silently downgrades the journal back to a\n * chain that cannot detect deletion. */\n requireTrustedHead?: boolean\n /** Cache a projector snapshot at the trusted head, refreshed once at least\n * this many entries have appended past the last cached one, so the cost\n * amortizes and a fresh open's tail stays bounded by this interval however\n * large the journal grows. Requires the codec's `snapshotProjection`; a\n * codec without it ignores this option and every open fully replays. */\n projectorSnapshot?: { everyEntries: number }\n}\n\n/** The part of a journal file one instance has verified. It is valid only\n * between successful locked calls: any failure discards it, and the next call\n * verifies the whole file again. */\ninterface VerifiedJournal<Entry, Projection> {\n /** Device and inode of the verified file; null until the file exists. */\n identity: { dev: bigint; ino: bigint } | null\n /** Verified byte length, which is where the next entry starts. */\n size: number\n /** Byte offset of each entry's row, indexed by sequence. */\n offsets: number[]\n /** The last entry and its row bytes, newline included. Finding these bytes\n * at the end of the verified length is what lets a call trust every row\n * before them without reading them. */\n head: { entry: Entry; row: Buffer } | null\n sequenceByEventId: Map<string, number>\n projector: LedgerProjector<Entry, Projection>\n /** The pin last verified against this chain, or null when there was none. */\n pin: LedgerTrustedHead | null\n /** Sequence of the last projector snapshot this instance wrote or seeded\n * from, or null when it has not cached one. Tracked in memory so a run of\n * pinning appends checks whether a refresh is due without re-reading the\n * cache file on every one of them. */\n snapshotSequence: number | null\n}\n\n// One async mutex per resolved journal path so concurrent appends from a single\n// process queue up instead of failing on the held cross-process lock file.\nconst journalMutexes = new Map<string, Mutex>()\n\nfunction mutexFor(path: string): Mutex {\n const existing = journalMutexes.get(path)\n if (existing) return existing\n const mutex = new Mutex()\n journalMutexes.set(path, mutex)\n return mutex\n}\n\n/** Durable filesystem journal. Construction performs no I/O. The first call\n * verifies the complete file under the locks; later calls verify the retained\n * head and only the bytes past it (see the module comment). */\nexport class FileLedgerJournal<Header extends object, Event extends LedgerEventBase, Projection> {\n readonly path: string\n /** Sibling file holding this journal's trusted head. */\n readonly trustedHeadPath: string\n /** Sibling file holding this journal's cached projector snapshot, if its\n * codec opts in. */\n readonly projectorSnapshotPath: string\n private readonly codec: LedgerJournalCodec<Header, Event, Projection>\n private readonly mutex: Mutex\n private readonly requireTrustedHead: boolean\n private readonly snapshotEvery: number | null\n private verified: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection> | null = null\n\n constructor(\n path: string,\n codec: LedgerJournalCodec<Header, Event, Projection>,\n options: FileLedgerJournalOptions = {},\n ) {\n this.path = resolve(path)\n this.trustedHeadPath = trustedHeadPathFor(this.path)\n this.projectorSnapshotPath = projectorSnapshotPathFor(this.path)\n this.codec = codec\n this.mutex = mutexFor(this.path)\n this.requireTrustedHead = options.requireTrustedHead === true\n this.snapshotEvery =\n codec.snapshotProjection !== undefined && options.projectorSnapshot !== undefined\n ? options.projectorSnapshot.everyEntries\n : null\n }\n\n async replay(): Promise<Projection> {\n return this.locked(() => this.sync(this.requireTrustedHead).projector.snapshot())\n }\n\n async append(\n event: Event,\n options: LedgerAppendOptions = {},\n ): Promise<LedgerAppendResult<LedgerEntryOf<Header, Event>, Projection>> {\n return this.locked(() => {\n const state = this.sync(this.requireTrustedHead)\n const existingSequence = state.sequenceByEventId.get(event.eventId)\n if (existingSequence !== undefined) {\n const existing = this.entryAt(state, existingSequence)!\n if (canonicalString(existing.event) !== canonicalString(event)) {\n throw this.codec.conflictError(\n `eventId ${event.eventId} already exists with different content`,\n )\n }\n if (options.pinHead === true) this.pinAcknowledged(state, existing)\n return { entry: existing, appended: false, projection: state.projector.snapshot() }\n }\n\n const sequence = state.offsets.length\n const material = {\n ...this.codec.header,\n sequence,\n previousHash: state.head?.entry.entryHash ?? null,\n event,\n }\n const text = canonicalString({ ...material, entryHash: hashCanonical(material) })\n // The new row goes through the reader's own parse and the projector's\n // transition before it is written: a row the journal would refuse to\n // read, or an entry the projector rejects, never reaches the file.\n const entry = parseRow(text, { path: this.path, line: sequence + 1 }, this.codec)\n const row = Buffer.from(`${text}\\n`, 'utf8')\n admitEntry(state, entry, row, this.codec)\n appendLedgerLine(this.path, `${text}\\n`, this.codec)\n if (options.pinHead === true) {\n // Journal first, pin second: a crash or a failed pin write between\n // them leaves the pin one entry behind, which still verifies and is\n // repaired by the next pinning append, including the idempotent\n // retry of this same event. The reverse order would leave a pin\n // naming an entry the journal does not carry, locking the journal\n // out of its own history.\n const head = { sequence: entry.sequence, entryHash: entry.entryHash }\n writeTrustedHeadFile(this.trustedHeadPath, head, this.codec)\n state.pin = head\n this.maybeWriteProjectorSnapshot(state)\n }\n return { entry, appended: true, projection: state.projector.snapshot() }\n })\n }\n\n /** The pinned head, or null when this journal has never been pinned. */\n async trustedHead(): Promise<LedgerTrustedHead | null> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () =>\n readTrustedHeadFile(this.trustedHeadPath, this.codec),\n ),\n )\n }\n\n /** Pin the current verified head. The chain and any existing pin are checked\n * first, so the pin only ever moves forward along a journal that still\n * carries the history it already recorded. */\n async pinTrustedHead(): Promise<LedgerTrustedHead> {\n return this.locked(() => {\n // `requireTrustedHead` is deliberately not applied here: pinning is how\n // a journal that lacks a pin acquires one.\n const state = this.sync(false)\n if (state.head === null) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} is empty; there is no head to pin`,\n )\n }\n const head: LedgerTrustedHead = {\n sequence: state.head.entry.sequence,\n entryHash: state.head.entry.entryHash,\n }\n writeTrustedHeadFile(this.trustedHeadPath, head, this.codec)\n state.pin = head\n // An explicit pin is already a deliberate, infrequent checkpoint call,\n // so — when the caller opted into the cache at all — it always\n // refreshes it rather than waiting for the interval. Gated on\n // `snapshotEvery`, not just the codec's support, so a journal that\n // never asked for `projectorSnapshot` never gets a cache file from\n // this path either; caching stays one on/off decision, not two.\n if (this.snapshotEvery !== null) this.writeProjectorSnapshotNow(state)\n return head\n })\n }\n\n /** Discard this journal's pin, reporting what was discarded. The journal file\n * is untouched and reads as unpinned afterwards, so the next pinning append\n * opens a new pin at the entry it writes. It is the way out of a pin whose\n * journal was deliberately deleted or rebuilt — every read of such a path is\n * refused, correctly, because a pin naming history the file no longer carries\n * is indistinguishable from a deletion. Clearing removes the deletion\n * guarantee for every entry the pin covered. */\n async clearTrustedHead(): Promise<LedgerTrustedHeadRemoval> {\n return this.locked(() => {\n const removal = clearTrustedHeadFile(this.trustedHeadPath, this.codec)\n // A cached snapshot that survived would be pinned to a head this\n // journal no longer vouches for, indistinguishable from a stale one a\n // future re-pin could seed from without earning it. It is not\n // security-critical to remove it — a reader only ever trusts a cached\n // checkpoint the current pin can vouch for — but keeping the sidecars\n // in agreement about what has been given up is the honest state to\n // leave on disk.\n removeProjectorSnapshotFile(this.projectorSnapshotPath, this.codec)\n if (this.verified !== null) {\n this.verified.pin = null\n this.verified.snapshotSequence = null\n }\n return removal\n })\n }\n\n /** Run under both locks. Any failure discards the verified state, because a\n * throw can leave it describing bytes the file does not hold: a projector\n * half way through a rejected transition, or a row whose write failed. */\n private locked<T>(run: () => T): Promise<T> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () => {\n try {\n return run()\n } catch (error) {\n this.verified = null\n throw error\n }\n }),\n )\n }\n\n /** Bring the verified state up to the file: keep it when its head row is\n * still where it was verified, else start over from byte 0; then verify and\n * apply every row past it, and check the pin. */\n private sync(requirePin: boolean): VerifiedJournal<LedgerEntryOf<Header, Event>, Projection> {\n let state = this.verified\n const fd = openForReading(this.path, this.codec)\n if (fd === null) {\n // A missing file is an empty journal, whatever this instance saw before.\n if (state === null || state.size > 0) state = emptyJournal(this.codec)\n this.verified = state\n this.verifyPin(state, requirePin)\n return state\n }\n try {\n const stats = fstatSync(fd, { bigint: true })\n const size = Number(stats.size)\n const identity = { dev: stats.dev, ino: stats.ino }\n if (\n state === null ||\n (state.identity !== null &&\n (state.identity.dev !== identity.dev || state.identity.ino !== identity.ino)) ||\n size < state.size ||\n !headInPlace(fd, state.size, state.head?.row ?? null)\n ) {\n // This is the case a full verification exists to catch — a fresh\n // instance, or one whose retained head is no longer where it was\n // verified — so a cached checkpoint is only ever a shortcut to the\n // SAME conclusion a full replay would reach, never a substitute for\n // reaching it.\n state = (size > 0 ? this.seedFromSnapshot(fd, size) : null) ?? emptyJournal(this.codec)\n }\n state.identity = identity\n this.verified = state\n if (size > state.size) {\n extendJournal(state, readRange(fd, state.size, size), this.path, this.codec)\n }\n } finally {\n closeSync(fd)\n }\n this.verifyPin(state, requirePin)\n return state\n }\n\n private verifyPin(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n requirePin: boolean,\n ): void {\n const pinned = readTrustedHeadFile(this.trustedHeadPath, this.codec)\n const count = state.offsets.length\n if (pinned === null) {\n state.pin = null\n if (requirePin && count > 0) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has ${count} entries but no trusted head at ${this.trustedHeadPath} — without its pin the journal cannot prove nothing was deleted. Restore the pin file, or adopt the current head with pinTrustedHead().`,\n )\n }\n return\n }\n // A pin already verified against this chain stays verified while the\n // chain's head is in place; sync has just checked that.\n if (state.pin?.sequence === pinned.sequence && state.pin.entryHash === pinned.entryHash) {\n return\n }\n // The anchor is meaningful only over a chain that already verified, so it\n // is checked after sync — and on every call, so a violated pin is refused\n // before an append can extend the journal over it.\n const chain = { length: count, at: (sequence: number) => this.entryAt(state, sequence) }\n verifyEntriesAgainstTrustedHead(chain, pinned, this.codec, {\n subject: `${this.codec.subject} ${this.path}`,\n trustedHeadPath: this.trustedHeadPath,\n })\n state.pin = pinned\n }\n\n /** Move the pin up to an entry this caller just acknowledged on the\n * idempotent path, when a pin write that failed after its row was already\n * fsynced left the pin behind. The move is safe because it is forward-only\n * along a chain `sync` has just verified: every entry up to this one is bound\n * to it by hash, so the pin can only ever come to name more history than it\n * did, never different history.\n *\n * With no pin at all this only pins the journal's current head. An entry in\n * the middle would publish a pin that reads as protection while leaving every\n * later entry silently truncatable, which is a worse state to hand an auditor\n * than the honest absence of a pin; `pinTrustedHead()` is the way to pin an\n * unpinned journal on purpose. */\n private pinAcknowledged(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n entry: LedgerEntryOf<Header, Event>,\n ): void {\n const pinned = state.pin\n if (pinned === null) {\n if (entry.sequence !== state.offsets.length - 1) return\n } else if (pinned.sequence >= entry.sequence) {\n return\n }\n const head = { sequence: entry.sequence, entryHash: entry.entryHash }\n writeTrustedHeadFile(this.trustedHeadPath, head, this.codec)\n state.pin = head\n this.maybeWriteProjectorSnapshot(state)\n }\n\n /** Refresh the cached projector snapshot once the current pin has moved at\n * least `snapshotEvery` entries past the last one cached, so the write cost\n * amortizes across many appends and a fresh open's uncached tail stays\n * bounded by that interval no matter how large the journal grows. A no-op\n * when the codec does not support the cache, the option is off, or the\n * head this call just pinned is not actually new (the idempotent-append\n * path can call this after re-acknowledging an already-durable entry). */\n private maybeWriteProjectorSnapshot(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n ): void {\n if (this.codec.snapshotProjection === undefined || this.snapshotEvery === null) return\n if (state.pin === null || state.pin.sequence !== state.head?.entry.sequence) return\n if (\n state.snapshotSequence !== null &&\n state.pin.sequence - state.snapshotSequence < this.snapshotEvery\n ) {\n return\n }\n this.writeProjectorSnapshotNow(state)\n }\n\n /** Serialize the live projector and write it as the cache, unconditionally.\n * Callers have already established that `state.pin` names `state.head`, so\n * the cache and the pin agree on the checkpoint by construction. */\n private writeProjectorSnapshotNow(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n ): void {\n const head = state.pin!\n const projection = this.codec.snapshotProjection!.serialize(state.projector.snapshot())\n const snapshot: LedgerProjectorSnapshot = { head, byteLength: state.size, projection }\n writeProjectorSnapshotFile(this.projectorSnapshotPath, snapshot, this.codec)\n state.snapshotSequence = head.sequence\n }\n\n /** Seed a fresh verified state from the cached projector snapshot, or null\n * when there is none this reader can use — a missing or out-of-reach\n * cache, never something this instance found actually wrong. Everything it\n * DOES accept is checked against the real bytes: rows 0 through the\n * checkpoint are read and chain-verified exactly as `admitEntry` would\n * verify them (self-consistent hash, correct sequence, linked previousHash,\n * unique eventId), just without this codec's own `parseEntry` or\n * `apply` — the checkpoint row itself still goes through both, through the\n * ordinary `parseRow`, so it is exactly as trustworthy as any entry a full\n * replay would produce. Any mismatch found along the way throws the same\n * `integrityError` a full replay of the same bytes would raise, because it\n * is the same tampering either path would have found; this is never turned\n * into a quiet fallback that would just re-read the same bytes differently\n * and risk reporting a different, more confusing failure — or none. */\n private seedFromSnapshot(\n fd: number,\n size: number,\n ): VerifiedJournal<LedgerEntryOf<Header, Event>, Projection> | null {\n const restore = this.codec.snapshotProjection\n if (restore === undefined) return null\n const cached = readProjectorSnapshotFile(this.projectorSnapshotPath, this.codec)\n if (cached === null) return null\n // Only a cache the CURRENT pin can vouch for is trusted. A pin moves\n // forward only past history that has already chain-verified (sync\n // verifies every appended row before a pinning append can move it), so a\n // cache at or behind the pin names a real, already-proven checkpoint; one\n // ahead of it — or present with no pin at all — names history nothing\n // external currently vouches for, and is ignored rather than trusted.\n const pin = readTrustedHeadFile(this.trustedHeadPath, this.codec)\n if (pin === null || cached.head.sequence > pin.sequence) return null\n if (cached.byteLength <= 0 || cached.byteLength > size) return null\n\n const prefix = readRange(fd, 0, cached.byteLength)\n const rows = splitRows(prefix, this.path, this.codec)\n if (rows.length !== cached.head.sequence + 1) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} projector snapshot ${this.projectorSnapshotPath} expects ${cached.head.sequence + 1} entries in its first ${cached.byteLength} bytes but the journal has ${rows.length}`,\n )\n }\n\n const offsets: number[] = []\n const sequenceByEventId = new Map<string, number>()\n let previousHash: LedgerHash | null = null\n for (let index = 0; index < rows.length - 1; index += 1) {\n const row = rows[index]!\n offsets.push(row.start)\n let raw: unknown\n try {\n raw = JSON.parse(row.text)\n } catch (error) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has invalid JSON at line ${index + 1}`,\n { cause: error },\n )\n }\n if (canonicalString(raw) !== row.text) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has non-canonical bytes at line ${index + 1}`,\n )\n }\n const fields = raw as {\n sequence?: unknown\n previousHash?: unknown\n entryHash?: unknown\n event?: { eventId?: unknown }\n }\n if (fields.sequence !== index) {\n throw this.codec.integrityError(\n `entry at line ${index + 1} has sequence ${String(fields.sequence)}, expected ${index}`,\n )\n }\n if ((fields.previousHash ?? null) !== previousHash) {\n throw this.codec.integrityError(\n `entry at line ${index + 1} does not extend the previous hash`,\n )\n }\n const { entryHash, ...material } = raw as Record<string, unknown>\n const expected = hashCanonical(material)\n if (entryHash !== expected) {\n throw this.codec.integrityError(\n `entry at line ${index + 1} hash mismatch: expected ${expected}, got ${String(entryHash)}`,\n )\n }\n const eventId = fields.event?.eventId\n if (typeof eventId !== 'string' || eventId === '') {\n throw this.codec.integrityError(`entry at line ${index + 1} has no eventId`)\n }\n if (sequenceByEventId.has(eventId)) {\n throw this.codec.integrityError(`duplicate eventId ${eventId} in durable ledger`)\n }\n sequenceByEventId.set(eventId, index)\n previousHash = entryHash as LedgerHash\n }\n\n // The checkpoint row itself carries this codec's own validation, exactly\n // like any other entry — the cache never substitutes for parsing it.\n const boundary = rows[rows.length - 1]!\n offsets.push(boundary.start)\n const entry = parseRow(\n boundary.text,\n { path: this.path, line: cached.head.sequence + 1 },\n this.codec,\n )\n const { entryHash: _boundaryHash, ...boundaryMaterial } = entry\n if (\n entry.sequence !== cached.head.sequence ||\n entry.previousHash !== previousHash ||\n entry.entryHash !== cached.head.entryHash ||\n hashCanonical(boundaryMaterial) !== cached.head.entryHash\n ) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} projector snapshot ${this.projectorSnapshotPath} does not match the journal at sequence ${cached.head.sequence}`,\n )\n }\n this.codec.checkEntryHeader(entry, cached.head.sequence)\n if (sequenceByEventId.has(entry.event.eventId)) {\n throw this.codec.integrityError(`duplicate eventId ${entry.event.eventId} in durable ledger`)\n }\n sequenceByEventId.set(entry.event.eventId, entry.sequence)\n\n let projector: LedgerProjector<LedgerEntryOf<Header, Event>, Projection>\n try {\n projector = restore.restore(cached.projection)\n } catch (error) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} projector snapshot ${this.projectorSnapshotPath} could not be restored`,\n { cause: error },\n )\n }\n\n return {\n identity: null,\n size: cached.byteLength,\n offsets,\n head: { entry, row: Buffer.from(`${boundary.text}\\n`, 'utf8') },\n sequenceByEventId,\n projector,\n pin: null,\n snapshotSequence: cached.head.sequence,\n }\n }\n\n /** The verified entry at `sequence`, read back from the file. The rows from\n * it to the head are re-read and must chain to the verified head hash, which\n * binds the returned entry to the history this instance verified. Callers ask\n * for recent entries — an idempotent retry, a pin one entry behind — so this\n * usually reads nothing or one row. */\n private entryAt(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n sequence: number,\n ): LedgerEntryOf<Header, Event> | undefined {\n const count = state.offsets.length\n if (!Number.isSafeInteger(sequence) || sequence < 0 || sequence >= count) return undefined\n if (sequence === count - 1) return state.head!.entry\n const changed = () =>\n this.codec.integrityError(\n `${this.codec.subject} ${this.path} changed at or after sequence ${sequence} since this reader verified it`,\n )\n const fd = openForReading(this.path, this.codec)\n if (fd === null) throw changed()\n let bytes: Buffer\n try {\n bytes = readRange(fd, state.offsets[sequence]!, state.size)\n } finally {\n closeSync(fd)\n }\n const rows = splitRows(bytes, this.path, this.codec)\n if (rows.length !== count - sequence) throw changed()\n let first: LedgerEntryOf<Header, Event> | undefined\n let previous: LedgerEntryOf<Header, Event> | undefined\n for (let index = 0; index < rows.length; index += 1) {\n const entry = parseRow(\n rows[index]!.text,\n { path: this.path, line: sequence + index + 1 },\n this.codec,\n )\n const { entryHash, ...material } = entry\n if (\n entry.sequence !== sequence + index ||\n hashCanonical(material) !== entryHash ||\n (previous !== undefined && entry.previousHash !== previous.entryHash)\n ) {\n throw changed()\n }\n first ??= entry\n previous = entry\n }\n if (previous?.entryHash !== state.head!.entry.entryHash) throw changed()\n return first\n }\n}\n\n/** Verify and replay resolved immutable journal bytes without filesystem I/O. */\nexport function replayLedgerText<Header extends object, Event extends LedgerEventBase, Projection>(\n text: string,\n path: string,\n codec: LedgerJournalCodec<Header, Event, Projection>,\n): Projection {\n const state = emptyJournal(codec)\n extendJournal(state, Buffer.from(text, 'utf8'), path, codec)\n return state.projector.snapshot()\n}\n\nfunction emptyJournal<Header extends object, Event extends LedgerEventBase, Projection>(\n codec: LedgerJournalCodec<Header, Event, Projection>,\n): VerifiedJournal<LedgerEntryOf<Header, Event>, Projection> {\n return {\n identity: null,\n size: 0,\n offsets: [],\n head: null,\n sequenceByEventId: new Map(),\n projector: codec.createProjector(),\n pin: null,\n snapshotSequence: null,\n }\n}\n\n/** Verify and apply the rows in `bytes`, which start at the state's verified\n * length. */\nfunction extendJournal<Header extends object, Event extends LedgerEventBase, Projection>(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n bytes: Buffer,\n path: string,\n codec: LedgerJournalCodec<Header, Event, Projection>,\n): void {\n const rows = splitRows(bytes, path, codec)\n for (const { text, start, end } of rows) {\n const entry = parseRow(text, { path, line: state.offsets.length + 1 }, codec)\n // Copy the row: a view would keep the whole read buffer alive.\n admitEntry(state, entry, Buffer.from(bytes.subarray(start, end)), codec)\n }\n}\n\n/** Check one parsed entry against the chain and apply it. Every row, read or\n * about to be written, enters the verified state here. */\nfunction admitEntry<Header extends object, Event extends LedgerEventBase, Projection>(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n entry: LedgerEntryOf<Header, Event>,\n row: Buffer,\n codec: LedgerJournalCodec<Header, Event, Projection>,\n): void {\n const index = state.offsets.length\n codec.checkEntryHeader(entry, index)\n if (entry.sequence !== index) {\n throw codec.integrityError(\n `entry ${entry.event.eventId} has sequence ${entry.sequence}, expected ${index}`,\n )\n }\n if (entry.previousHash !== (state.head?.entry.entryHash ?? null)) {\n throw codec.integrityError(`entry ${entry.event.eventId} does not extend the previous hash`)\n }\n const { entryHash: _entryHash, ...material } = entry\n const expectedHash = hashCanonical(material)\n if (entry.entryHash !== expectedHash) {\n throw codec.integrityError(\n `entry ${entry.event.eventId} hash mismatch: expected ${expectedHash}, got ${entry.entryHash}`,\n )\n }\n if (state.sequenceByEventId.has(entry.event.eventId)) {\n throw codec.integrityError(`duplicate eventId ${entry.event.eventId} in durable ledger`)\n }\n state.projector.apply(entry, index)\n state.sequenceByEventId.set(entry.event.eventId, index)\n state.offsets.push(state.size)\n state.size += row.byteLength\n state.head = { entry, row }\n}\n\n/** Parse one canonical row into a frozen entry. The projector and every caller\n * share entries, so none of them can change what the journal verified. */\nfunction parseRow<Header extends object, Event extends LedgerEventBase, Projection>(\n text: string,\n context: LedgerLineContext,\n codec: LedgerJournalCodec<Header, Event, Projection>,\n): LedgerEntryOf<Header, Event> {\n const { path, line } = context\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch (error) {\n throw codec.integrityError(`${codec.subject} ${path} has invalid JSON at line ${line}`, {\n cause: error,\n })\n }\n const entry = codec.parseEntry(raw, context)\n let canonical: string\n try {\n canonical = canonicalString(entry)\n } catch (error) {\n throw codec.integrityError(\n `${codec.subject} ${path} has a row with no canonical JSON form at line ${line}`,\n { cause: error },\n )\n }\n if (text !== canonical) {\n throw codec.integrityError(`${codec.subject} ${path} has non-canonical bytes at line ${line}`)\n }\n return deepFreezeCanonicalJson(entry)\n}\n\ninterface JournalRow {\n text: string\n /** Byte range of the row in the buffer, newline included. */\n start: number\n end: number\n}\n\nfunction splitRows(bytes: Buffer, path: string, context: LedgerFileContext): JournalRow[] {\n if (bytes.byteLength === 0) return []\n if (bytes[bytes.byteLength - 1] !== 0x0a) {\n throw context.integrityError(\n `${context.subject} ${path} has a truncated final record (missing newline)`,\n )\n }\n const rows: JournalRow[] = []\n let start = 0\n while (start < bytes.byteLength) {\n const newline = bytes.indexOf(0x0a, start)\n if (newline === start) {\n throw context.integrityError(\n `${context.subject} ${path} has a blank row at line ${rows.length + 1}`,\n )\n }\n rows.push({ text: bytes.toString('utf8', start, newline), start, end: newline + 1 })\n start = newline + 1\n }\n return rows\n}\n\n/** True when the verified head row still ends the verified length of the file. */\nfunction headInPlace(fd: number, size: number, row: Buffer | null): boolean {\n return row === null || readRange(fd, size - row.byteLength, size).equals(row)\n}\n\n/** A read-only descriptor, or null when the file does not exist. */\nfunction openForReading(path: string, context: LedgerFileContext): number | null {\n try {\n return openSync(path, constants.O_RDONLY)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null\n throw context.integrityError(`${context.subject} ${path} could not be opened for reading`, {\n cause: error,\n })\n }\n}\n\nfunction readRange(fd: number, start: number, end: number): Buffer {\n const bytes = Buffer.allocUnsafe(end - start)\n let offset = 0\n while (offset < bytes.byteLength) {\n const read = readSync(fd, bytes, offset, bytes.byteLength - offset, start + offset)\n if (read === 0) return bytes.subarray(0, offset)\n offset += read\n }\n return bytes\n}\n"],"mappings":";;;;;;;;AAyCA,IAAa,sBAAb,cAAyC,MAAM;CAC7C,OAAyB;AAC3B;;AAQA,SAAgB,oBACd,SACkC;CAClC,IAAI,WAAW,aAAa,QAAQ,QAAQ,CAAC,GAAG,OAAO;EAAE,UAAU;EAAO,QAAQ;CAAW;CAC7F,MAAM,QAAQ,WAAW,QAAQ,QAAQ;CACzC,IAAI,MAAM,UAAU,QAClB,OAAO;EAAE,UAAU;EAAO,QAAQ;EAAQ,QAAQ,MAAM;CAAM;CAEhE,OAAO;AACT;;;;;;;AAQA,SAAgB,yBACd,SAC2B;CAC3B,MAAM,MAAM,QAAQ,OAAO,QAAQ;CACnC,IAAI,CAAC,OAAO,cAAc,GAAG,KAAK,OAAO,GACvC,MAAM,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GAAG,KAAK,gDAC7B;CAEF,MAAM,OAAqB,CAAC;CAC5B,IAAI,QAAQ;CACZ,OAAO,QAAQ,MAAM,YAAY;EAC/B,MAAM,UAAU,MAAM,QAAQ,IAAM,KAAK;EACzC,IAAI,YAAY,OACd,MAAM,QAAQ,eACZ,GAAG,QAAQ,QAAQ,GAAG,KAAK,2BAA2B,KAAK,SAAS,GACtE;EAEF,KAAK,KAAK;GAAE,MAAM,MAAM,SAAS,QAAQ,OAAO,OAAO;GAAG;GAAO,KAAK,UAAU;EAAE,CAAC;EACnF,QAAQ,UAAU;CACpB;CACA,OAAO;AACT;;AAGA,SAAS,YAAY,IAAY,MAAc,KAA6B;CAC1E,OAAO,QAAQ,QAAQ,UAAU,IAAI,OAAO,IAAI,YAAY,IAAI,CAAC,CAAC,OAAO,GAAG;AAC9E;;AAGA,SAAS,eAAe,MAAc,SAA2C;CAC/E,IAAI;EACF,OAAO,SAAS,MAAM,UAAU,QAAQ;CAC1C,SAAS,OAAO;EACd,IAAK,MAAgC,SAAS,UAAU,OAAO;EAC/D,MAAM,QAAQ,eAAe,GAAG,QAAQ,QAAQ,GAAG,KAAK,mCAAmC,EACzF,OAAO,MACT,CAAC;CACH;AACF;AAEA,SAAS,UAAU,IAAY,OAAe,KAAqB;CACjE,MAAM,QAAQ,OAAO,YAAY,MAAM,KAAK;CAC5C,IAAI,SAAS;CACb,OAAO,SAAS,MAAM,YAAY;EAChC,MAAM,OAAO,SAAS,IAAI,OAAO,QAAQ,MAAM,aAAa,QAAQ,QAAQ,MAAM;EAClF,IAAI,SAAS,GAAG,OAAO,MAAM,SAAS,GAAG,MAAM;EAC/C,UAAU;CACZ;CACA,OAAO;AACT"}
@@ -2104,6 +2104,6 @@ function truncateForContext(value, max) {
2104
2104
  return `${value.slice(0, max - 3).trimEnd()}...`;
2105
2105
  }
2106
2106
  //#endregion
2107
- export { spanEpochMillis as A, KIND_EXPECTED_SUBJECTS as B, TraceFileTooLargeError as C, extractOtlpAttributes as D, compareSpanTime as E, parseRawFinding as F, resolveTraceAnalystLimits as G, parseFindingSubject as H, coerceJson as I, snapshotExactExecutionComponentIdentity as K, stripCodeFences as L, RAW_FINDING_SCHEMA_PROMPT as M, RawAnalystFindingSchema as N, firstStringAttr as O, evidenceRefsFromRawFinding as P, FINDING_SUBJECT_KINDS as R, TraceFileMissingError as S, asString as T, renderFindingSubject as U, findingSubjectGrammarPromptFor as V, DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS as W, SpanNotFoundError as _, TRACE_ANALYST_TOOL_NAMESPACE as a, TraceAnalysisValidationError as b, traceAnalystFunctionGroup as c, compileSearchRegex as d, truncateForBudget as f, TRACE_ANALYSIS_LIMITS as g, TRACE_ANALYST_TRUNCATION_MARKER_PREFIX as h, buildTraceToolsForGroup as i, stringField as j, projectOtlpFlatLine as k, bindSpanSourceReader as l, DEFAULT_TRACE_ANALYST_BUDGETS as m, renderPriorFindings as n, UNTRUSTED_TRACE_TEXT as o, validateInteger as p, snapshotExactExecutionPlan as q, runTraceAnalyst as r, buildTraceAnalysisToolDescriptors as s, createTraceAnalyst as t, createBoundedTraceAnalysisStore as u, TraceAnalysisLimitError as v, TraceNotFoundError as w, TraceFileMalformedError as x, TraceAnalysisStoreContractError as y, FINDING_SUBJECT_SYNTAX as z };
2107
+ export { spanEpochMillis as A, FINDING_SUBJECT_SYNTAX as B, TraceFileTooLargeError as C, extractOtlpAttributes as D, compareSpanTime as E, parseRawFinding as F, DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS as G, findingSubjectGrammarPromptFor as H, parseTraceSpanEvidenceUri as I, snapshotExactExecutionPlan as J, resolveTraceAnalystLimits as K, coerceJson as L, RAW_FINDING_SCHEMA_PROMPT as M, RawAnalystFindingSchema as N, firstStringAttr as O, evidenceRefsFromRawFinding as P, stripCodeFences as R, TraceFileMissingError as S, asString as T, parseFindingSubject as U, KIND_EXPECTED_SUBJECTS as V, renderFindingSubject as W, SpanNotFoundError as _, TRACE_ANALYST_TOOL_NAMESPACE as a, TraceAnalysisValidationError as b, traceAnalystFunctionGroup as c, compileSearchRegex as d, truncateForBudget as f, TRACE_ANALYSIS_LIMITS as g, TRACE_ANALYST_TRUNCATION_MARKER_PREFIX as h, buildTraceToolsForGroup as i, stringField as j, projectOtlpFlatLine as k, bindSpanSourceReader as l, DEFAULT_TRACE_ANALYST_BUDGETS as m, renderPriorFindings as n, UNTRUSTED_TRACE_TEXT as o, validateInteger as p, snapshotExactExecutionComponentIdentity as q, runTraceAnalyst as r, buildTraceAnalysisToolDescriptors as s, createTraceAnalyst as t, createBoundedTraceAnalysisStore as u, TraceAnalysisLimitError as v, TraceNotFoundError as w, TraceFileMalformedError as x, TraceAnalysisStoreContractError as y, FINDING_SUBJECT_KINDS as z };
2108
2108
 
2109
- //# sourceMappingURL=kind-factory-BGwN0nE6.js.map
2109
+ //# sourceMappingURL=kind-factory-ByZeXDqF.js.map