@tangle-network/agent-eval 0.217.1 → 0.218.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.
- package/CHANGELOG.md +36 -1
- package/dist/adapters/http.d.ts +2 -2
- package/dist/analyst/index.d.ts +1 -1
- package/dist/analyst/index.d.ts.map +1 -1
- package/dist/analyst/index.js +9 -9
- package/dist/analyst/index.js.map +1 -1
- package/dist/{analyze-runs-DyeNcenW.d.ts → analyze-runs-DjlZOVXx.d.ts} +2 -2
- package/dist/{analyze-runs-DyeNcenW.d.ts.map → analyze-runs-DjlZOVXx.d.ts.map} +1 -1
- package/dist/{benchmark-command-xQK8nOI6.js → benchmark-command-BupdHRyf.js} +661 -562
- package/dist/benchmark-command-BupdHRyf.js.map +1 -0
- package/dist/benchmarks/index.d.ts +4 -4
- package/dist/benchmarks/index.js +3 -3
- package/dist/campaign/index.d.ts +4 -4
- package/dist/campaign/index.js +10 -10
- package/dist/{campaign-CJGkxAQ6.js → campaign-CGvUTnmc.js} +312 -281
- package/dist/{campaign-CJGkxAQ6.js.map → campaign-CGvUTnmc.js.map} +1 -1
- package/dist/{campaign-evidence-CQYw8_0H.js → campaign-evidence-DunzcJGv.js} +2 -2
- package/dist/{campaign-evidence-CQYw8_0H.js.map → campaign-evidence-DunzcJGv.js.map} +1 -1
- package/dist/{chat-client-ldqxYYTN.js → chat-client-B2pXlPdx.js} +2 -2
- package/dist/{chat-client-ldqxYYTN.js.map → chat-client-B2pXlPdx.js.map} +1 -1
- package/dist/{chat-json-call-DavzexSp.js → chat-json-call-Dm9c-b41.js} +2 -2
- package/dist/{chat-json-call-DavzexSp.js.map → chat-json-call-Dm9c-b41.js.map} +1 -1
- package/dist/cli.js +10 -10
- package/dist/{completion-verifier-B_jw6C9p.js → completion-verifier-DbLVf3i8.js} +4 -4
- package/dist/{completion-verifier-B_jw6C9p.js.map → completion-verifier-DbLVf3i8.js.map} +1 -1
- package/dist/contract/index.d.ts +7 -7
- package/dist/contract/index.js +90 -10
- package/dist/contract/index.js.map +1 -1
- package/dist/{default-registry-ClYjq3QE.js → default-registry-BJ-Pq6yL.js} +309 -277
- package/dist/{default-registry-ClYjq3QE.js.map → default-registry-BJ-Pq6yL.js.map} +1 -1
- package/dist/{define-agent-eval-BDxNlP3D.js → define-agent-eval-BGdFKlrc.js} +165 -105
- package/dist/define-agent-eval-BGdFKlrc.js.map +1 -0
- package/dist/{define-agent-eval-BIkH_gAR.d.ts → define-agent-eval-BlH10zEw.d.ts} +6 -6
- package/dist/{define-agent-eval-BIkH_gAR.d.ts.map → define-agent-eval-BlH10zEw.d.ts.map} +1 -1
- package/dist/diagnosis/index.d.ts +1 -1
- package/dist/{dspy-rlm-engine-DhdCr1Dc.js → dspy-rlm-engine-CSMwudLO.js} +2 -2
- package/dist/{dspy-rlm-engine-DhdCr1Dc.js.map → dspy-rlm-engine-CSMwudLO.js.map} +1 -1
- package/dist/eval-campaign-BUMIxKTE.js +393 -0
- package/dist/eval-campaign-BUMIxKTE.js.map +1 -0
- package/dist/{evaluation-jTjC_QQD.d.ts → evaluation-BOZ38vOH.d.ts} +2 -2
- package/dist/{evaluation-jTjC_QQD.d.ts.map → evaluation-BOZ38vOH.d.ts.map} +1 -1
- package/dist/evaluation.d.ts +1 -1
- package/dist/experiment/index.d.ts +1 -1
- package/dist/experiment/index.d.ts.map +1 -1
- package/dist/experiment/index.js +110 -71
- package/dist/experiment/index.js.map +1 -1
- package/dist/{exporters-Cl6IeNAu.js → exporters-DWvM16LE.js} +2 -2
- package/dist/{exporters-Cl6IeNAu.js.map → exporters-DWvM16LE.js.map} +1 -1
- package/dist/{external-optimizer-process-KVFGvYX1.js → external-optimizer-process-C3Wm7Vhn.js} +2 -2
- package/dist/{external-optimizer-process-KVFGvYX1.js.map → external-optimizer-process-C3Wm7Vhn.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-XIHBOSKt.js → external-optimizer-subprocess-B5gdLRZv.js} +3 -3
- package/dist/{external-optimizer-subprocess-XIHBOSKt.js.map → external-optimizer-subprocess-B5gdLRZv.js.map} +1 -1
- package/dist/{findings-store-BMVQtEsm.js → findings-store-BtTzPL0d.js} +5 -5
- package/dist/{findings-store-BMVQtEsm.js.map → findings-store-BtTzPL0d.js.map} +1 -1
- package/dist/{hf-dataset-D9f7-oX7.js → hf-dataset-CKxIJQba.js} +3 -3
- package/dist/{hf-dataset-D9f7-oX7.js.map → hf-dataset-CKxIJQba.js.map} +1 -1
- package/dist/hosted/index.js +1 -1
- package/dist/{index-ZuWx52WG.d.ts → index-B16FNdW5.d.ts} +34 -17
- package/dist/index-B16FNdW5.d.ts.map +1 -0
- package/dist/{index-9jJ2fKSX.d.ts → index-CalAsXMR.d.ts} +7 -5
- package/dist/index-CalAsXMR.d.ts.map +1 -0
- package/dist/{index-BiT6RtNH.d.ts → index-DbMOXYnP.d.ts} +6 -6
- package/dist/{index-BiT6RtNH.d.ts.map → index-DbMOXYnP.d.ts.map} +1 -1
- package/dist/index.d.ts +9 -9
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +611 -688
- package/dist/index.js.map +1 -1
- package/dist/{integrity-DOd9Q86O.js → integrity-C8oUeB0g.js} +322 -197
- package/dist/integrity-C8oUeB0g.js.map +1 -0
- package/dist/{journal-CR4QikYp.js → journal-C7om8Gum.js} +48 -38
- package/dist/journal-C7om8Gum.js.map +1 -0
- package/dist/ledger-core/index.d.ts +1 -1
- package/dist/ledger-core/index.js +2 -2
- package/dist/ledger-core/lock-holder.d.ts +2 -0
- package/dist/ledger-core/lock-holder.js +181 -0
- package/dist/ledger-core/lock-holder.js.map +1 -0
- package/dist/{ledger-core-DrJhbms9.js → ledger-core-CAxUdDk0.js} +2 -2
- package/dist/{ledger-core-DrJhbms9.js.map → ledger-core-CAxUdDk0.js.map} +1 -1
- package/dist/{llm-client-BshCREn6.js → llm-client-_Y6ic-tf.js} +238 -248
- package/dist/llm-client-_Y6ic-tf.js.map +1 -0
- package/dist/{llm-judge-C8jMTNNG.js → llm-judge-Djxh-Uhs.js} +646 -458
- package/dist/llm-judge-Djxh-Uhs.js.map +1 -0
- package/dist/lock-holder-DaJbfpci.d.ts +86 -0
- package/dist/lock-holder-DaJbfpci.d.ts.map +1 -0
- package/dist/{matrix-DHe-dwVJ.d.ts → matrix-CCSBna4q.d.ts} +2 -2
- package/dist/{matrix-DHe-dwVJ.d.ts.map → matrix-CCSBna4q.d.ts.map} +1 -1
- package/dist/{mint-zszyYlpA.js → mint-CbdwjTPW.js} +2 -2
- package/dist/{mint-zszyYlpA.js.map → mint-CbdwjTPW.js.map} +1 -1
- package/dist/multishot/golden/index.d.ts +1 -1
- package/dist/multishot/index.d.ts +2 -2
- package/dist/openapi.json +1 -1
- package/dist/{pareto-BzsxidFD.js → pareto-CTv8vozZ.js} +4 -4
- package/dist/{pareto-BzsxidFD.js.map → pareto-CTv8vozZ.js.map} +1 -1
- package/dist/{promotion-gate-DaY95yU6.d.ts → promotion-gate-CxEHRsZW.d.ts} +2 -2
- package/dist/{promotion-gate-DaY95yU6.d.ts.map → promotion-gate-CxEHRsZW.d.ts.map} +1 -1
- package/dist/{proposal-findings-BbWidvUk.js → proposal-findings-n-5WBbEx.js} +2 -2
- package/dist/{proposal-findings-BbWidvUk.js.map → proposal-findings-n-5WBbEx.js.map} +1 -1
- package/dist/{render-C-w2EZ6p.js → render-Cs34y0iX.js} +404 -208
- package/dist/render-Cs34y0iX.js.map +1 -0
- package/dist/reporting.d.ts +2 -2
- package/dist/{researcher-0ABVIdGa.d.ts → researcher-GU1tV4dn.d.ts} +2 -2
- package/dist/{researcher-0ABVIdGa.d.ts.map → researcher-GU1tV4dn.d.ts.map} +1 -1
- package/dist/rl.d.ts +2 -2
- package/dist/rl.js +4 -4
- package/dist/rollout/index.js +5 -5
- package/dist/{rollout-D6C50mfA.js → rollout-Dd1ucT_M.js} +5 -5
- package/dist/{rollout-D6C50mfA.js.map → rollout-Dd1ucT_M.js.map} +1 -1
- package/dist/schema-C-ziyJD7.d.ts.map +1 -1
- package/dist/{schema-DxcKTzbi.js → schema-CvhfLjtZ.js} +77 -47
- package/dist/schema-CvhfLjtZ.js.map +1 -0
- package/dist/search/index.d.ts +2 -2
- package/dist/search/index.d.ts.map +1 -1
- package/dist/search/index.js +2 -2
- package/dist/{search-kernel-DxqjBxA-.d.ts → search-kernel-p9JB3SmL.d.ts} +3 -3
- package/dist/{search-kernel-DxqjBxA-.d.ts.map → search-kernel-p9JB3SmL.d.ts.map} +1 -1
- package/dist/{search-ledger-TUvB5gWH.js → search-ledger-ClpN4I3e.js} +4 -4
- package/dist/{search-ledger-TUvB5gWH.js.map → search-ledger-ClpN4I3e.js.map} +1 -1
- package/dist/{search-ledger-file-UKCO2r8a.js → search-ledger-file-Bd5Tioq6.js} +3 -3
- package/dist/{search-ledger-file-UKCO2r8a.js.map → search-ledger-file-Bd5Tioq6.js.map} +1 -1
- package/dist/{search-shipper-Cw2z3-td.js → search-shipper-Bg2HW3Uv.js} +3 -3
- package/dist/{search-shipper-Cw2z3-td.js.map → search-shipper-Bg2HW3Uv.js.map} +1 -1
- package/dist/{search-summary-DQIvJsSB.js → search-summary-CrBuvVnf.js} +3 -3
- package/dist/{search-summary-DQIvJsSB.js.map → search-summary-CrBuvVnf.js.map} +1 -1
- package/dist/{server-DoVbqqtJ.js → server-C6M0qR8h.js} +2 -2
- package/dist/{server-DoVbqqtJ.js.map → server-C6M0qR8h.js.map} +1 -1
- package/dist/{single-run-lock-U58yf8N6.js → single-run-lock-Dekd8_Wv.js} +7 -7
- package/dist/single-run-lock-Dekd8_Wv.js.map +1 -0
- package/dist/{skillopt-optimization-method-kyL94-ri.js → skillopt-optimization-method-5dlex7MJ.js} +1339 -1059
- package/dist/skillopt-optimization-method-5dlex7MJ.js.map +1 -0
- package/dist/{statistical-heldout-C9AbgREN.d.ts → statistical-heldout-BHfLZHrm.d.ts} +2 -2
- package/dist/{statistical-heldout-C9AbgREN.d.ts.map → statistical-heldout-BHfLZHrm.d.ts.map} +1 -1
- package/dist/{summary-report-DM7tlml1.d.ts → summary-report-CkbRcSuu.d.ts} +16 -1
- package/dist/summary-report-CkbRcSuu.d.ts.map +1 -0
- package/dist/supervisor-run/index.d.ts.map +1 -1
- package/dist/supervisor-run/index.js +3 -3
- package/dist/{systemone-Bp_Ac0p1.d.ts → systemone-BMzDJb1i.d.ts} +3 -3
- package/dist/{systemone-Bp_Ac0p1.d.ts.map → systemone-BMzDJb1i.d.ts.map} +1 -1
- package/dist/systemone.d.ts +2 -2
- package/dist/{terminal-record-78g6E4vh.js → terminal-record-D4Rv-j1W.js} +241 -193
- package/dist/{terminal-record-78g6E4vh.js.map → terminal-record-D4Rv-j1W.js.map} +1 -1
- package/dist/trajectory-replay/index.d.ts +4 -1
- package/dist/trajectory-replay/index.d.ts.map +1 -1
- package/dist/trajectory-replay/index.js +834 -824
- package/dist/trajectory-replay/index.js.map +1 -1
- package/dist/{tree-BGRglkKd.js → tree-B5e1uAeL.js} +122 -14
- package/dist/tree-B5e1uAeL.js.map +1 -0
- package/dist/{types-DtMbFw6U.d.ts → types-BKCzzmit.d.ts} +2 -2
- package/dist/{types-DtMbFw6U.d.ts.map → types-BKCzzmit.d.ts.map} +1 -1
- package/dist/{types-D8GhJoHk.d.ts → types-DtkO1G9L.d.ts} +2 -2
- package/dist/{types-D8GhJoHk.d.ts.map → types-DtkO1G9L.d.ts.map} +1 -1
- package/dist/wire/index.js +1 -1
- package/docs/design/statistics-decisions.md +1 -1
- package/docs/eval-surface-map.md +1 -0
- package/docs/profile-json-identity.md +1 -2
- package/docs/public-api.md +27 -16
- package/package.json +7 -2
- package/dist/benchmark-command-xQK8nOI6.js.map +0 -1
- package/dist/define-agent-eval-BDxNlP3D.js.map +0 -1
- package/dist/eval-campaign-BLEfBGbA.js +0 -343
- package/dist/eval-campaign-BLEfBGbA.js.map +0 -1
- package/dist/index-9jJ2fKSX.d.ts.map +0 -1
- package/dist/index-ZuWx52WG.d.ts.map +0 -1
- package/dist/integrity-DOd9Q86O.js.map +0 -1
- package/dist/journal-CR4QikYp.js.map +0 -1
- package/dist/llm-client-BshCREn6.js.map +0 -1
- package/dist/llm-judge-C8jMTNNG.js.map +0 -1
- package/dist/render-C-w2EZ6p.js.map +0 -1
- package/dist/schema-DxcKTzbi.js.map +0 -1
- package/dist/single-run-lock-U58yf8N6.js.map +0 -1
- package/dist/skillopt-optimization-method-kyL94-ri.js.map +0 -1
- package/dist/summary-report-DM7tlml1.d.ts.map +0 -1
- package/dist/tree-BGRglkKd.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"journal-C7om8Gum.js","names":[],"sources":["../src/ledger-core/atomic-file-lock.ts","../src/ledger-core/journal-file.ts","../src/concurrency.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 fstatSync,\n fsyncSync,\n linkSync,\n openSync,\n readFileSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport {\n type LockHolderIdentity,\n type LockHolderRecord,\n type LockIdentity,\n lockHolderVerdict,\n lockIdentity,\n parseLockHolderRecord,\n readLockHolderIdentity,\n} from './lock-holder'\n\n/**\n * The holder of a lock path. The lock file holds this record plus the identity\n * of its own inode, so `lockHolderVerdict` can prove a crashed holder dead.\n */\nexport interface AtomicFileLockOwner extends LockHolderIdentity {\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 = { ...readLockHolderIdentity(pid), 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 // A hard link keeps the inode, so this identity is the lock path's once linked.\n const lock = lockIdentity(fstatSync(descriptor, { bigint: true }))\n writeFileSync(descriptor, `${JSON.stringify({ ...owner, lock })}\\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\n/** Only a holder proved dead is stale; an alive or unknown holder keeps the lock. */\nfunction ownerState(lockPath: string): OwnerState {\n const current = readOwner(lockPath)\n if (!current) return { state: 'missing' }\n const verdict = lockHolderVerdict(current.record, current.identity)\n return { state: verdict.liveness === 'dead' ? 'stale' : 'held', owner: current.owner }\n}\n\ninterface LockFileOwner {\n readonly owner: AtomicFileLockOwner\n readonly record: LockHolderRecord & { readonly nonce: string }\n /** The inode the record was read from, so a verdict compares it with the recorded lock. */\n readonly identity: LockIdentity\n}\n\nfunction readOwner(lockPath: string): LockFileOwner | undefined {\n let descriptor: number\n try {\n descriptor = openSync(lockPath, 'r')\n } catch (error) {\n if (isMissing(error)) return undefined\n throw error\n }\n let contents: string\n let identity: LockIdentity\n try {\n identity = lockIdentity(fstatSync(descriptor, { bigint: true }))\n contents = readFileSync(descriptor, 'utf8').trim()\n } finally {\n closeSync(descriptor)\n }\n\n let value: unknown\n try {\n value = JSON.parse(contents)\n } catch (error) {\n throw invalidOwner(lockPath, error)\n }\n const record = parseOwnerRecord(value)\n if (!record) throw invalidOwner(lockPath)\n const { lock: _lock, ...owner } = record\n return { owner, record, identity }\n}\n\n/**\n * Accept exactly the fields a lock owner writes: a holder record that parses\n * whole, plus the nonce. A record from before holder identity carried only pid,\n * host and nonce; it still parses, and its holder is never proved dead.\n */\nfunction parseOwnerRecord(value: unknown): LockFileOwner['record'] | undefined {\n const holder = parseLockHolderRecord(value)\n if (!holder) return undefined\n const { nonce, ...rest } = value as Record<string, unknown>\n if (typeof nonce !== 'string' || nonce.trim().length === 0) return undefined\n // A field the holder parse dropped is malformed; refuse it instead of guessing.\n if (Object.keys(rest).length !== Object.keys(holder).length) return undefined\n return { ...holder, nonce }\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.owner) !== 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 unlinkIfExists(path: string): void {\n try {\n unlinkSync(path)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\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 * 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\ninterface 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","/**\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/** Where a memory journal keeps its text: an in-process store keyed by path,\n * such as an in-memory `CampaignStorage`. */\nexport interface LedgerTextStore {\n read(path: string): string | undefined\n write(path: string, text: string): void\n}\n\n/**\n * A journal for runs without a filesystem. It keeps its rows as text in a\n * store and applies the file journal's rules: the same row parse, hash chain,\n * idempotent append by `eventId`, and projector transition before a row is\n * kept. It has no lock, fsync or trusted head, because its rows live and die\n * with the process that holds the store.\n */\nexport class MemoryLedgerJournal<Header extends object, Event extends LedgerEventBase, Projection> {\n readonly path: string\n private readonly codec: LedgerJournalCodec<Header, Event, Projection>\n private readonly store: LedgerTextStore\n private verified: {\n text: string\n journal: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>\n entries: LedgerEntryOf<Header, Event>[]\n } | null = null\n\n constructor(\n path: string,\n codec: LedgerJournalCodec<Header, Event, Projection>,\n store: LedgerTextStore,\n ) {\n this.path = path\n this.codec = codec\n this.store = store\n }\n\n async replay(): Promise<Projection> {\n return this.guarded(() => this.sync().journal.projector.snapshot())\n }\n\n async append(\n event: Event,\n ): Promise<LedgerAppendResult<LedgerEntryOf<Header, Event>, Projection>> {\n return this.guarded(() => {\n const verified = this.sync()\n const { journal, entries } = verified\n const existingSequence = journal.sequenceByEventId.get(event.eventId)\n if (existingSequence !== undefined) {\n const existing = entries[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 return { entry: existing, appended: false, projection: journal.projector.snapshot() }\n }\n const sequence = entries.length\n const material = {\n ...this.codec.header,\n sequence,\n previousHash: journal.head?.entry.entryHash ?? null,\n event,\n }\n const text = canonicalString({ ...material, entryHash: hashCanonical(material) })\n const entry = parseRow(text, { path: this.path, line: sequence + 1 }, this.codec)\n admitEntry(journal, entry, Buffer.from(`${text}\\n`, 'utf8'), this.codec)\n entries.push(entry)\n verified.text = `${verified.text}${text}\\n`\n this.store.write(this.path, verified.text)\n return { entry, appended: true, projection: journal.projector.snapshot() }\n })\n }\n\n /** Verify the stored text again whenever it is not the text this instance wrote. */\n private sync(): NonNullable<MemoryLedgerJournal<Header, Event, Projection>['verified']> {\n const text = this.store.read(this.path) ?? ''\n if (this.verified?.text === text) return this.verified\n const journal = emptyJournal(this.codec)\n const entries: LedgerEntryOf<Header, Event>[] = []\n const bytes = Buffer.from(text, 'utf8')\n for (const row of splitRows(bytes, this.path, this.codec)) {\n const entry = parseRow(row.text, { path: this.path, line: entries.length + 1 }, this.codec)\n admitEntry(journal, entry, Buffer.from(bytes.subarray(row.start, row.end)), this.codec)\n entries.push(entry)\n }\n this.verified = { text, journal, entries }\n return this.verified\n }\n\n /** A refused transition can leave the projector half applied; discard it. */\n private async guarded<T>(run: () => T): Promise<T> {\n try {\n return run()\n } catch (error) {\n this.verified = null\n throw error\n }\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":";;;;;;;;AAoDA,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,IAAI,oBAAoB,iDAAiD;CAEjF,MAAM,QAA6B;EAAE,GAAG,uBAAuB,GAAG;EAAG,OAAO,WAAW;CAAE;CACzF,KAAK,IAAI,UAAU,GAAG,UAAU,GAAG,WAAW,GAAG;EAC/C,IAAI,WAAW,aAAa,QAAQ,QAAQ,CAAC,GAAG;GAC9C,MAAM,WAAW,wBAAwB,QAAQ,UAAU,OAAO,OAAO;GACzE,IAAI,CAAC,UAAU,OAAO;IAAE,UAAU;IAAO,QAAQ;GAAW;GAC5D,IAAI;IACF,OAAO,YAAY,QAAQ,UAAU,OAAO,OAAO;GACrD,UAAU;IACR,SAAS,QAAQ;GACnB;EACF;EACA,IAAI,aAAa,QAAQ,UAAU,OAAO,WAAW,SAAS,GAC5D,OAAO,SAAS,QAAQ,UAAU,KAAK;EAGzC,MAAM,SAAS,WAAW,QAAQ,QAAQ;EAC1C,IAAI,OAAO,UAAU,WAAW;EAChC,IAAI,OAAO,UAAU,QACnB,OAAO;GAAE,UAAU;GAAO,QAAQ;GAAQ,QAAQ,OAAO;EAAM;EA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A as AtomicFileLock, C as LedgerTrustedHead, D as LedgerFileContext, E as FileLockResult, F as tryAcquireAtomicFileLock, M as AtomicFileLockOptions, N as AtomicFileLockOwner, O as tryWithLedgerFileLock, P as AtomicFileLockUnavailable, S as LedgerAnchoredEntry, T as LedgerTrustedHeadSubject, _ as LedgerJournalCodec, a as merkleInclusionProof, b as LedgerProjectorSnapshotCodec, c as merkleSalt, d as FileLedgerJournalOptions, f as LedgerAppendOptions, g as LedgerEventBase, h as LedgerEntryOf, i as MerkleVerification, j as AtomicFileLockAcquisition, k as writeLedgerFileAtomically, l as verifyMerkleInclusion, m as LedgerChainFields, n as MerkleConsistencyProof, o as merkleLeafHash, p as LedgerAppendResult, r as MerkleInclusionProof, s as merkleRoot, t as LedgerProjectorSnapshot, u as FileLedgerJournal, v as LedgerLineContext, w as LedgerTrustedHeadRemoval, x as LedgerTextStore, y as LedgerProjector } from "../index-
|
|
1
|
+
import { A as AtomicFileLock, C as LedgerTrustedHead, D as LedgerFileContext, E as FileLockResult, F as tryAcquireAtomicFileLock, M as AtomicFileLockOptions, N as AtomicFileLockOwner, O as tryWithLedgerFileLock, P as AtomicFileLockUnavailable, S as LedgerAnchoredEntry, T as LedgerTrustedHeadSubject, _ as LedgerJournalCodec, a as merkleInclusionProof, b as LedgerProjectorSnapshotCodec, c as merkleSalt, d as FileLedgerJournalOptions, f as LedgerAppendOptions, g as LedgerEventBase, h as LedgerEntryOf, i as MerkleVerification, j as AtomicFileLockAcquisition, k as writeLedgerFileAtomically, l as verifyMerkleInclusion, m as LedgerChainFields, n as MerkleConsistencyProof, o as merkleLeafHash, p as LedgerAppendResult, r as MerkleInclusionProof, s as merkleRoot, t as LedgerProjectorSnapshot, u as FileLedgerJournal, v as LedgerLineContext, w as LedgerTrustedHeadRemoval, x as LedgerTextStore, y as LedgerProjector } from "../index-CalAsXMR.js";
|
|
2
2
|
import { a as hashCanonical, i as canonicalString, n as LedgerCanonicalizationError, o as jsonDocument, r as LedgerHash, t as LEDGER_HASH_PATTERN } from "../canonical-CFpojCN5.js";
|
|
3
3
|
export { type AtomicFileLock, type AtomicFileLockAcquisition, type AtomicFileLockOptions, type AtomicFileLockOwner, type AtomicFileLockUnavailable, FileLedgerJournal, type FileLedgerJournalOptions, type FileLockResult, LEDGER_HASH_PATTERN, type LedgerAnchoredEntry, type LedgerAppendOptions, type LedgerAppendResult, LedgerCanonicalizationError, type LedgerChainFields, type LedgerEntryOf, type LedgerEventBase, type LedgerFileContext, type LedgerHash, type LedgerJournalCodec, type LedgerLineContext, type LedgerProjector, type LedgerProjectorSnapshot, type LedgerProjectorSnapshotCodec, type LedgerTextStore, type LedgerTrustedHead, type LedgerTrustedHeadRemoval, type LedgerTrustedHeadSubject, type MerkleConsistencyProof, type MerkleInclusionProof, type MerkleVerification, canonicalString, hashCanonical, jsonDocument, merkleInclusionProof, merkleLeafHash, merkleRoot, merkleSalt, tryAcquireAtomicFileLock, tryWithLedgerFileLock, verifyMerkleInclusion, writeLedgerFileAtomically };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { a as hashCanonical, n as LedgerCanonicalizationError, o as jsonDocument, r as canonicalString, t as LEDGER_HASH_PATTERN } from "../canonical-Dq2hOQ8L.js";
|
|
2
|
-
import { c as tryWithLedgerFileLock, f as tryAcquireAtomicFileLock, t as FileLedgerJournal, u as writeLedgerFileAtomically } from "../journal-
|
|
3
|
-
import { a as verifyMerkleInclusion, i as merkleSalt, n as merkleLeafHash, r as merkleRoot, t as merkleInclusionProof } from "../ledger-core-
|
|
2
|
+
import { c as tryWithLedgerFileLock, f as tryAcquireAtomicFileLock, t as FileLedgerJournal, u as writeLedgerFileAtomically } from "../journal-C7om8Gum.js";
|
|
3
|
+
import { a as verifyMerkleInclusion, i as merkleSalt, n as merkleLeafHash, r as merkleRoot, t as merkleInclusionProof } from "../ledger-core-CAxUdDk0.js";
|
|
4
4
|
export { FileLedgerJournal, LEDGER_HASH_PATTERN, LedgerCanonicalizationError, canonicalString, hashCanonical, jsonDocument, merkleInclusionProof, merkleLeafHash, merkleRoot, merkleSalt, tryAcquireAtomicFileLock, tryWithLedgerFileLock, verifyMerkleInclusion, writeLedgerFileAtomically };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as LockHolderVerdict, c as lockHolderVerdict, d as readLockHolderIdentity, i as LockHolderUnknownReason, l as lockIdentity, n as LockHolderIdentity, o as LockIdentity, r as LockHolderRecord, s as LockIdentityStats, t as LockHolderDeathReason, u as parseLockHolderRecord } from "../lock-holder-DaJbfpci.js";
|
|
2
|
+
export { LockHolderDeathReason, LockHolderIdentity, LockHolderRecord, LockHolderUnknownReason, LockHolderVerdict, LockIdentity, LockIdentityStats, lockHolderVerdict, lockIdentity, parseLockHolderRecord, readLockHolderIdentity };
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { readFileSync, readlinkSync } from "node:fs";
|
|
2
|
+
import { hostname } from "node:os";
|
|
3
|
+
//#region src/ledger-core/lock-holder.ts
|
|
4
|
+
/**
|
|
5
|
+
* The one dead-owner rule: whether a lock's recorded holder is provably dead.
|
|
6
|
+
*
|
|
7
|
+
* A lock is safe to take over only when its holder is proved dead. A pid alone
|
|
8
|
+
* proves nothing: the OS hands a dead holder's pid to a later process, and a
|
|
9
|
+
* filesystem hands a removed lock's inode to the next lock. So a holder record
|
|
10
|
+
* carries the pid's OS start token, the boot id, the pid namespace, the host,
|
|
11
|
+
* and the identity of the lock it was written for, and the verdict is `dead`
|
|
12
|
+
* only when those facts prove it. Anything the record or this host cannot
|
|
13
|
+
* settle is `unknown`, and a caller keeps treating the lock as held.
|
|
14
|
+
*
|
|
15
|
+
* This module imports only Node built-ins, so lock owners in other packages can
|
|
16
|
+
* import `@tangle-network/agent-eval/lock-holder` without loading the rest of
|
|
17
|
+
* the package.
|
|
18
|
+
*/
|
|
19
|
+
function lockIdentity(stats) {
|
|
20
|
+
return {
|
|
21
|
+
dev: stats.dev.toString(),
|
|
22
|
+
ino: stats.ino.toString(),
|
|
23
|
+
birthtimeNs: stats.birthtimeNs.toString()
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The identity to record for `pid` on this host. The start token is read for
|
|
28
|
+
* `pid` itself, so a lock taken on behalf of another live process records that
|
|
29
|
+
* process. Fields the host cannot report are omitted, which leaves a later
|
|
30
|
+
* verdict on the record `unknown` rather than wrong.
|
|
31
|
+
*/
|
|
32
|
+
function readLockHolderIdentity(pid = process.pid) {
|
|
33
|
+
const processStart = readProcessStart(pid);
|
|
34
|
+
const { bootId, pidNamespace } = ownHostIdentity();
|
|
35
|
+
return {
|
|
36
|
+
pid,
|
|
37
|
+
host: hostname(),
|
|
38
|
+
...processStart ? { processStart } : {},
|
|
39
|
+
...bootId ? { bootId } : {},
|
|
40
|
+
...pidNamespace ? { pidNamespace } : {}
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Decide whether `record`'s holder is dead, alive, or unknown.
|
|
45
|
+
*
|
|
46
|
+
* `currentLock` is the identity of the lock as it is now. `dead` needs a record
|
|
47
|
+
* with a start token and a lock identity, written for this very lock (equal dev,
|
|
48
|
+
* ino and a nonzero birthtime), on this host and pid namespace, and then a
|
|
49
|
+
* rebooted host, a gone pid, or a pid whose start token changed. `alive` needs
|
|
50
|
+
* the pid present with the recorded start token. Everything else is `unknown`,
|
|
51
|
+
* so a live holder's lock is never taken.
|
|
52
|
+
*/
|
|
53
|
+
function lockHolderVerdict(record, currentLock) {
|
|
54
|
+
if (!record || !Number.isSafeInteger(record.pid) || record.pid <= 0) return unknown("unreadable record");
|
|
55
|
+
if (record.host !== hostname()) return unknown("other host");
|
|
56
|
+
if (!record.processStart || !record.lock) return unknown("incomplete record");
|
|
57
|
+
if (!currentLock || currentLock.birthtimeNs === "0" || currentLock.dev !== record.lock.dev || currentLock.ino !== record.lock.ino || currentLock.birthtimeNs !== record.lock.birthtimeNs) return unknown("lock changed");
|
|
58
|
+
const own = ownHostIdentity();
|
|
59
|
+
if (record.pidNamespace !== own.pidNamespace) return unknown("other pid namespace");
|
|
60
|
+
if (record.bootId === void 0 !== (own.bootId === void 0)) return unknown("boot id unavailable");
|
|
61
|
+
if (record.bootId !== own.bootId) return {
|
|
62
|
+
liveness: "dead",
|
|
63
|
+
reason: "host rebooted"
|
|
64
|
+
};
|
|
65
|
+
if (pidIsGone(record.pid)) return {
|
|
66
|
+
liveness: "dead",
|
|
67
|
+
reason: "pid gone"
|
|
68
|
+
};
|
|
69
|
+
const start = readProcessStart(record.pid);
|
|
70
|
+
if (start === void 0) return unknown("start token unavailable");
|
|
71
|
+
if (start !== record.processStart) return {
|
|
72
|
+
liveness: "dead",
|
|
73
|
+
reason: "pid reused"
|
|
74
|
+
};
|
|
75
|
+
return { liveness: "alive" };
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Read a holder record from parsed JSON. The required fields are `pid` and
|
|
79
|
+
* `host`; an identity field that is missing or malformed is dropped, which
|
|
80
|
+
* leaves the holder named but never provably dead.
|
|
81
|
+
*/
|
|
82
|
+
function parseLockHolderRecord(value) {
|
|
83
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
84
|
+
const record = value;
|
|
85
|
+
if (!Number.isSafeInteger(record.pid) || record.pid <= 0) return void 0;
|
|
86
|
+
if (typeof record.host !== "string" || record.host.length === 0) return void 0;
|
|
87
|
+
const processStart = text(record.processStart);
|
|
88
|
+
const bootId = text(record.bootId);
|
|
89
|
+
const pidNamespace = text(record.pidNamespace);
|
|
90
|
+
const lock = parseLockIdentity(record.lock);
|
|
91
|
+
return {
|
|
92
|
+
pid: record.pid,
|
|
93
|
+
host: record.host,
|
|
94
|
+
...processStart ? { processStart } : {},
|
|
95
|
+
...bootId ? { bootId } : {},
|
|
96
|
+
...pidNamespace ? { pidNamespace } : {},
|
|
97
|
+
...lock ? { lock } : {}
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function parseLockIdentity(value) {
|
|
101
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
102
|
+
const lock = value;
|
|
103
|
+
if (!decimal(lock.dev) || !decimal(lock.ino) || !decimal(lock.birthtimeNs)) return void 0;
|
|
104
|
+
return {
|
|
105
|
+
dev: lock.dev,
|
|
106
|
+
ino: lock.ino,
|
|
107
|
+
birthtimeNs: lock.birthtimeNs
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
function unknown(reason) {
|
|
111
|
+
return {
|
|
112
|
+
liveness: "unknown",
|
|
113
|
+
reason
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
function text(field) {
|
|
117
|
+
return typeof field === "string" && field.length > 0 ? field : void 0;
|
|
118
|
+
}
|
|
119
|
+
function decimal(field) {
|
|
120
|
+
return typeof field === "string" && /^\d+$/u.test(field);
|
|
121
|
+
}
|
|
122
|
+
/** Only ESRCH proves a pid gone; EPERM means it exists under another user. */
|
|
123
|
+
function pidIsGone(pid) {
|
|
124
|
+
try {
|
|
125
|
+
process.kill(pid, 0);
|
|
126
|
+
return false;
|
|
127
|
+
} catch (error) {
|
|
128
|
+
return error instanceof Error && "code" in error && error.code === "ESRCH";
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
let hostIdentity;
|
|
132
|
+
function ownHostIdentity() {
|
|
133
|
+
if (hostIdentity) return hostIdentity;
|
|
134
|
+
const bootId = readOptional(() => readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim());
|
|
135
|
+
const pidNamespace = readOptional(() => readlinkSync("/proc/self/ns/pid"));
|
|
136
|
+
hostIdentity = {
|
|
137
|
+
...bootId ? { bootId } : {},
|
|
138
|
+
...pidNamespace ? { pidNamespace } : {}
|
|
139
|
+
};
|
|
140
|
+
return hostIdentity;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* The OS start token of a live pid: the same for a process's whole life and
|
|
144
|
+
* different for every later holder of its pid. `undefined` when the host cannot
|
|
145
|
+
* report one.
|
|
146
|
+
*/
|
|
147
|
+
function readProcessStart(pid) {
|
|
148
|
+
if (!Number.isSafeInteger(pid) || pid <= 0 || process.platform === "win32") return void 0;
|
|
149
|
+
if (process.platform === "linux") {
|
|
150
|
+
const stat = readOptional(() => readFileSync(`/proc/${pid}/stat`, "utf8"));
|
|
151
|
+
if (stat === void 0) return void 0;
|
|
152
|
+
const startTime = stat.slice(stat.lastIndexOf(")") + 1).trim().split(/\s+/u)[19];
|
|
153
|
+
return startTime !== void 0 && /^\d+$/u.test(startTime) ? startTime : void 0;
|
|
154
|
+
}
|
|
155
|
+
const childProcess = process.getBuiltinModule?.("node:child_process");
|
|
156
|
+
if (!childProcess) return void 0;
|
|
157
|
+
return readOptional(() => childProcess.execFileSync("ps", [
|
|
158
|
+
"-o",
|
|
159
|
+
"lstart=",
|
|
160
|
+
"-p",
|
|
161
|
+
String(pid)
|
|
162
|
+
], {
|
|
163
|
+
encoding: "utf8",
|
|
164
|
+
stdio: [
|
|
165
|
+
"ignore",
|
|
166
|
+
"pipe",
|
|
167
|
+
"ignore"
|
|
168
|
+
]
|
|
169
|
+
}).trim());
|
|
170
|
+
}
|
|
171
|
+
function readOptional(read) {
|
|
172
|
+
try {
|
|
173
|
+
return read() || void 0;
|
|
174
|
+
} catch {
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
//#endregion
|
|
179
|
+
export { lockHolderVerdict, lockIdentity, parseLockHolderRecord, readLockHolderIdentity };
|
|
180
|
+
|
|
181
|
+
//# sourceMappingURL=lock-holder.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lock-holder.js","names":[],"sources":["../../src/ledger-core/lock-holder.ts"],"sourcesContent":["/**\n * The one dead-owner rule: whether a lock's recorded holder is provably dead.\n *\n * A lock is safe to take over only when its holder is proved dead. A pid alone\n * proves nothing: the OS hands a dead holder's pid to a later process, and a\n * filesystem hands a removed lock's inode to the next lock. So a holder record\n * carries the pid's OS start token, the boot id, the pid namespace, the host,\n * and the identity of the lock it was written for, and the verdict is `dead`\n * only when those facts prove it. Anything the record or this host cannot\n * settle is `unknown`, and a caller keeps treating the lock as held.\n *\n * This module imports only Node built-ins, so lock owners in other packages can\n * import `@tangle-network/agent-eval/lock-holder` without loading the rest of\n * the package.\n */\n\nimport { readFileSync, readlinkSync } from 'node:fs'\nimport { hostname } from 'node:os'\n\n/**\n * Identity of one lock path's inode, as decimal strings from a bigint `stat`.\n * ext4 hands a removed directory's inode to the next one at once (two\n * directories created 1.4 ms apart got the same inode on drew-gtr-pro), so dev\n * and ino alone can match a stale record to a live holder's new lock; the\n * nanosecond birthtime tells them apart.\n */\nexport interface LockIdentity {\n readonly dev: string\n readonly ino: string\n readonly birthtimeNs: string\n}\n\n/** Who holds a lock: the process and the facts that tell it from a later holder of its pid. */\nexport interface LockHolderIdentity {\n readonly pid: number\n readonly host: string\n /** OS start token of `pid`: Linux `/proc/<pid>/stat` starttime, elsewhere `ps` lstart. */\n readonly processStart?: string\n readonly bootId?: string\n readonly pidNamespace?: string\n}\n\n/** A holder record as a lock owner writes it: the holder and the lock it was written for. */\nexport interface LockHolderRecord extends LockHolderIdentity {\n readonly lock?: LockIdentity\n}\n\nexport type LockHolderDeathReason = 'pid gone' | 'pid reused' | 'host rebooted'\n\nexport type LockHolderUnknownReason =\n | 'unreadable record'\n | 'other host'\n | 'incomplete record'\n | 'lock changed'\n | 'other pid namespace'\n | 'boot id unavailable'\n | 'start token unavailable'\n\nexport type LockHolderVerdict =\n | { readonly liveness: 'dead'; readonly reason: LockHolderDeathReason }\n | { readonly liveness: 'alive' }\n | { readonly liveness: 'unknown'; readonly reason: LockHolderUnknownReason }\n\n/** Stat fields `lockIdentity` reads; pass `statSync(path, { bigint: true })` or its fstat/lstat. */\nexport interface LockIdentityStats {\n readonly dev: bigint\n readonly ino: bigint\n readonly birthtimeNs: bigint\n}\n\nexport function lockIdentity(stats: LockIdentityStats): LockIdentity {\n return {\n dev: stats.dev.toString(),\n ino: stats.ino.toString(),\n birthtimeNs: stats.birthtimeNs.toString(),\n }\n}\n\n/**\n * The identity to record for `pid` on this host. The start token is read for\n * `pid` itself, so a lock taken on behalf of another live process records that\n * process. Fields the host cannot report are omitted, which leaves a later\n * verdict on the record `unknown` rather than wrong.\n */\nexport function readLockHolderIdentity(pid: number = process.pid): LockHolderIdentity {\n const processStart = readProcessStart(pid)\n const { bootId, pidNamespace } = ownHostIdentity()\n return {\n pid,\n host: hostname(),\n ...(processStart ? { processStart } : {}),\n ...(bootId ? { bootId } : {}),\n ...(pidNamespace ? { pidNamespace } : {}),\n }\n}\n\n/**\n * Decide whether `record`'s holder is dead, alive, or unknown.\n *\n * `currentLock` is the identity of the lock as it is now. `dead` needs a record\n * with a start token and a lock identity, written for this very lock (equal dev,\n * ino and a nonzero birthtime), on this host and pid namespace, and then a\n * rebooted host, a gone pid, or a pid whose start token changed. `alive` needs\n * the pid present with the recorded start token. Everything else is `unknown`,\n * so a live holder's lock is never taken.\n */\nexport function lockHolderVerdict(\n record: LockHolderRecord | undefined,\n currentLock: LockIdentity | undefined,\n): LockHolderVerdict {\n if (!record || !Number.isSafeInteger(record.pid) || record.pid <= 0) {\n return unknown('unreadable record')\n }\n if (record.host !== hostname()) return unknown('other host')\n if (!record.processStart || !record.lock) return unknown('incomplete record')\n if (\n !currentLock ||\n currentLock.birthtimeNs === '0' ||\n currentLock.dev !== record.lock.dev ||\n currentLock.ino !== record.lock.ino ||\n currentLock.birthtimeNs !== record.lock.birthtimeNs\n ) {\n return unknown('lock changed')\n }\n const own = ownHostIdentity()\n if (record.pidNamespace !== own.pidNamespace) return unknown('other pid namespace')\n if ((record.bootId === undefined) !== (own.bootId === undefined)) {\n return unknown('boot id unavailable')\n }\n if (record.bootId !== own.bootId) return { liveness: 'dead', reason: 'host rebooted' }\n if (pidIsGone(record.pid)) return { liveness: 'dead', reason: 'pid gone' }\n const start = readProcessStart(record.pid)\n if (start === undefined) return unknown('start token unavailable')\n if (start !== record.processStart) return { liveness: 'dead', reason: 'pid reused' }\n return { liveness: 'alive' }\n}\n\n/**\n * Read a holder record from parsed JSON. The required fields are `pid` and\n * `host`; an identity field that is missing or malformed is dropped, which\n * leaves the holder named but never provably dead.\n */\nexport function parseLockHolderRecord(value: unknown): LockHolderRecord | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined\n const record = value as Record<string, unknown>\n if (!Number.isSafeInteger(record.pid) || (record.pid as number) <= 0) return undefined\n if (typeof record.host !== 'string' || record.host.length === 0) return undefined\n const processStart = text(record.processStart)\n const bootId = text(record.bootId)\n const pidNamespace = text(record.pidNamespace)\n const lock = parseLockIdentity(record.lock)\n return {\n pid: record.pid as number,\n host: record.host,\n ...(processStart ? { processStart } : {}),\n ...(bootId ? { bootId } : {}),\n ...(pidNamespace ? { pidNamespace } : {}),\n ...(lock ? { lock } : {}),\n }\n}\n\nfunction parseLockIdentity(value: unknown): LockIdentity | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined\n const lock = value as Record<string, unknown>\n if (!decimal(lock.dev) || !decimal(lock.ino) || !decimal(lock.birthtimeNs)) return undefined\n return { dev: lock.dev, ino: lock.ino, birthtimeNs: lock.birthtimeNs }\n}\n\nfunction unknown(reason: LockHolderUnknownReason): LockHolderVerdict {\n return { liveness: 'unknown', reason }\n}\n\nfunction text(field: unknown): string | undefined {\n return typeof field === 'string' && field.length > 0 ? field : undefined\n}\n\nfunction decimal(field: unknown): field is string {\n return typeof field === 'string' && /^\\d+$/u.test(field)\n}\n\n/** Only ESRCH proves a pid gone; EPERM means it exists under another user. */\nfunction pidIsGone(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return false\n } catch (error) {\n return error instanceof Error && 'code' in error && error.code === 'ESRCH'\n }\n}\n\ninterface HostIdentity {\n readonly bootId?: string\n readonly pidNamespace?: string\n}\n\nlet hostIdentity: HostIdentity | undefined\n\nfunction ownHostIdentity(): HostIdentity {\n if (hostIdentity) return hostIdentity\n const bootId = readOptional(() => readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim())\n const pidNamespace = readOptional(() => readlinkSync('/proc/self/ns/pid'))\n hostIdentity = {\n ...(bootId ? { bootId } : {}),\n ...(pidNamespace ? { pidNamespace } : {}),\n }\n return hostIdentity\n}\n\n/**\n * The OS start token of a live pid: the same for a process's whole life and\n * different for every later holder of its pid. `undefined` when the host cannot\n * report one.\n */\nfunction readProcessStart(pid: number): string | undefined {\n if (!Number.isSafeInteger(pid) || pid <= 0 || process.platform === 'win32') return undefined\n if (process.platform === 'linux') {\n const stat = readOptional(() => readFileSync(`/proc/${pid}/stat`, 'utf8'))\n if (stat === undefined) return undefined\n // The comm field is parenthesized and may hold spaces, so fields are counted after its close.\n const startTime = stat\n .slice(stat.lastIndexOf(')') + 1)\n .trim()\n .split(/\\s+/u)[19]\n return startTime !== undefined && /^\\d+$/u.test(startTime) ? startTime : undefined\n }\n // `ps` lstart has 1 s resolution, so a pid reused within the same second reads\n // as alive and keeps the lock: the safe direction. child_process is resolved\n // on use so bundles that import this module never load it at startup.\n const childProcess = process.getBuiltinModule?.('node:child_process') as\n | typeof import('node:child_process')\n | undefined\n if (!childProcess) return undefined\n return readOptional(() =>\n childProcess\n .execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)], {\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n })\n .trim(),\n )\n}\n\nfunction readOptional(read: () => string): string | undefined {\n try {\n return read() || undefined\n } catch {\n return undefined\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsEA,SAAgB,aAAa,OAAwC;CACnE,OAAO;EACL,KAAK,MAAM,IAAI,SAAS;EACxB,KAAK,MAAM,IAAI,SAAS;EACxB,aAAa,MAAM,YAAY,SAAS;CAC1C;AACF;;;;;;;AAQA,SAAgB,uBAAuB,MAAc,QAAQ,KAAyB;CACpF,MAAM,eAAe,iBAAiB,GAAG;CACzC,MAAM,EAAE,QAAQ,iBAAiB,gBAAgB;CACjD,OAAO;EACL;EACA,MAAM,SAA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
|
3
|
-
import "./journal-
|
|
3
|
+
import "./journal-C7om8Gum.js";
|
|
4
4
|
import { sha256Bytes } from "@tangle-network/agent-interface";
|
|
5
5
|
//#region src/ledger-core/merkle.ts
|
|
6
6
|
/**
|
|
@@ -166,4 +166,4 @@ function fromHex(hex) {
|
|
|
166
166
|
//#endregion
|
|
167
167
|
export { verifyMerkleInclusion as a, merkleSalt as i, merkleLeafHash as n, merkleRoot as r, merkleInclusionProof as t };
|
|
168
168
|
|
|
169
|
-
//# sourceMappingURL=ledger-core-
|
|
169
|
+
//# sourceMappingURL=ledger-core-CAxUdDk0.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ledger-core-DrJhbms9.js","names":[],"sources":["../src/ledger-core/merkle.ts"],"sourcesContent":["/**\n * Merkle proofs over an append-only list of leaves (RFC 9162 §2.1, the\n * Certificate Transparency tree).\n *\n * A hash chain proves a whole log against its head, but proving one entry means\n * replaying everything before it. This tree proves any one leaf against a root\n * with ⌈log₂ n⌉ hashes (inclusion), and proves that a larger tree only appended\n * to a smaller one (consistency). A verifier holding a root can therefore check\n * a single event, or that a later checkpoint extends an earlier one, without\n * reading the rest of the log.\n *\n * Leaves and interior nodes are domain-separated (0x00 and 0x01 prefixes), so a\n * leaf can never be presented as an interior node. Content that may later be\n * redacted takes a random 32-byte salt: a verifier then needs only the leaf's\n * hash, and short content cannot be guessed back from that hash. The salt must\n * be stored apart from anything that is shared after redaction.\n *\n * Builders refuse malformed input by throwing; verifiers never throw and return\n * a typed outcome, because a proof is external evidence and a bad one is a\n * finding, not a crash.\n */\nimport { sha256Bytes } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../errors'\nimport { LEDGER_HASH_PATTERN, type LedgerHash } from './canonical'\n\n/** Proof that one leaf is at `leafIndex` in a tree of `treeSize` leaves. */\nexport interface MerkleInclusionProof {\n readonly leafIndex: number\n readonly treeSize: number\n readonly path: readonly LedgerHash[]\n}\n\n/** Proof that the first `oldSize` leaves of a `newSize` tree are unchanged. */\nexport interface MerkleConsistencyProof {\n readonly oldSize: number\n readonly newSize: number\n readonly path: readonly LedgerHash[]\n}\n\nexport type MerkleVerification =\n | { readonly verified: true }\n | { readonly verified: false; readonly reason: string }\n\nconst SALT_PATTERN = /^[a-f0-9]{64}$/\nconst LEAF_PREFIX = 0x00\nconst NODE_PREFIX = 0x01\nconst encoder = new TextEncoder()\n\n/** Root of the empty tree: SHA-256 of no bytes. */\nconst MERKLE_EMPTY_ROOT: LedgerHash = sha256Bytes(new Uint8Array(0)) as LedgerHash\n\n/** A fresh random salt for {@link merkleLeafHash}: 32 bytes as 64 lowercase hex characters. */\nexport function merkleSalt(): string {\n return toHex(globalThis.crypto.getRandomValues(new Uint8Array(32)))\n}\n\n/**\n * Leaf hash of `content`: SHA-256(0x00 ‖ salt ‖ content). Without a salt this is\n * exactly the RFC 9162 leaf hash. Strings are hashed as UTF-8.\n */\nexport function merkleLeafHash(content: Uint8Array | string, salt?: string): LedgerHash {\n const bytes = typeof content === 'string' ? encoder.encode(content) : content\n if (salt === undefined) return digest(LEAF_PREFIX, bytes)\n if (!SALT_PATTERN.test(salt)) {\n throw new ValidationError('merkle salt must be 32 bytes as 64 lowercase hex characters')\n }\n return digest(LEAF_PREFIX, fromHex(salt), bytes)\n}\n\n/** Root over leaf hashes, in order. The empty list has {@link MERKLE_EMPTY_ROOT}. */\nexport function merkleRoot(leaves: readonly LedgerHash[]): LedgerHash {\n const nodes = decodeLeaves(leaves)\n return nodes.length === 0 ? MERKLE_EMPTY_ROOT : toLedgerHash(subtreeRoot(nodes, 0, nodes.length))\n}\n\n/** Inclusion proof for the leaf at `leafIndex` (RFC 9162 §2.1.3.1). */\nexport function merkleInclusionProof(\n leaves: readonly LedgerHash[],\n leafIndex: number,\n): MerkleInclusionProof {\n const nodes = decodeLeaves(leaves)\n if (!Number.isSafeInteger(leafIndex) || leafIndex < 0 || leafIndex >= nodes.length) {\n throw new ValidationError(\n `merkle leaf index ${leafIndex} is outside a tree of ${nodes.length} leaves`,\n )\n }\n const path: Uint8Array[] = []\n inclusionPath(nodes, leafIndex, 0, nodes.length, path)\n return { leafIndex, treeSize: nodes.length, path: path.map(toLedgerHash) }\n}\n\n\n\n/** Check that `leaf` is in the tree with `root` at the proof's index (RFC 9162 §2.1.3.2). */\nexport function verifyMerkleInclusion(\n leaf: LedgerHash,\n proof: MerkleInclusionProof,\n root: LedgerHash,\n): MerkleVerification {\n const { leafIndex, treeSize } = proof\n if (!isSize(treeSize) || !isSize(leafIndex) || leafIndex >= treeSize) {\n return refused(`leaf index ${leafIndex} is outside a tree of ${treeSize} leaves`)\n }\n const decoded = decodeAll([leaf, root, ...proof.path])\n if (decoded === undefined) return refused('proof carries a malformed hash')\n const [leafBytes, rootBytes, ...path] = decoded as [Uint8Array, Uint8Array, ...Uint8Array[]]\n let fn = leafIndex\n let sn = treeSize - 1\n let r = leafBytes\n for (const p of path) {\n if (sn === 0) return refused('proof path is longer than the tree is deep')\n if (fn % 2 === 1 || fn === sn) {\n r = node(p, r)\n if (fn % 2 === 0) {\n while (fn % 2 === 0 && fn !== 0) {\n fn = Math.floor(fn / 2)\n sn = Math.floor(sn / 2)\n }\n }\n } else {\n r = node(r, p)\n }\n fn = Math.floor(fn / 2)\n sn = Math.floor(sn / 2)\n }\n if (sn !== 0) return refused('proof path is shorter than the tree is deep')\n return equal(r, rootBytes) ? { verified: true } : refused('leaf does not hash to the root')\n}\n\n\n\nfunction subtreeRoot(nodes: readonly Uint8Array[], start: number, end: number): Uint8Array {\n if (end - start === 1) return nodes[start] as Uint8Array\n const k = largestPowerOfTwoBelow(end - start)\n return node(subtreeRoot(nodes, start, start + k), subtreeRoot(nodes, start + k, end))\n}\n\nfunction inclusionPath(\n nodes: readonly Uint8Array[],\n index: number,\n start: number,\n end: number,\n path: Uint8Array[],\n): void {\n if (end - start === 1) return\n const k = largestPowerOfTwoBelow(end - start)\n if (index < start + k) {\n inclusionPath(nodes, index, start, start + k, path)\n path.push(subtreeRoot(nodes, start + k, end))\n } else {\n inclusionPath(nodes, index, start + k, end, path)\n path.push(subtreeRoot(nodes, start, start + k))\n }\n}\n\n\n\nfunction node(left: Uint8Array, right: Uint8Array): Uint8Array {\n return fromHex(digest(NODE_PREFIX, left, right).slice('sha256:'.length))\n}\n\nfunction digest(prefix: number, ...parts: Uint8Array[]): LedgerHash {\n const length = parts.reduce((total, part) => total + part.length, 1)\n const bytes = new Uint8Array(length)\n bytes[0] = prefix\n let offset = 1\n for (const part of parts) {\n bytes.set(part, offset)\n offset += part.length\n }\n return sha256Bytes(bytes) as LedgerHash\n}\n\nfunction decodeLeaves(leaves: readonly LedgerHash[]): Uint8Array[] {\n const decoded = decodeAll(leaves)\n if (decoded === undefined) {\n throw new ValidationError('merkle leaves must be sha256:<64 lowercase hex> hashes')\n }\n return decoded\n}\n\nfunction decodeAll(hashes: readonly string[]): Uint8Array[] | undefined {\n const out: Uint8Array[] = []\n for (const hash of hashes) {\n if (typeof hash !== 'string' || !LEDGER_HASH_PATTERN.test(hash)) return undefined\n out.push(fromHex(hash.slice('sha256:'.length)))\n }\n return out\n}\n\nfunction toLedgerHash(bytes: Uint8Array): LedgerHash {\n return `sha256:${toHex(bytes)}`\n}\n\nfunction largestPowerOfTwoBelow(n: number): number {\n let k = 1\n while (k * 2 < n) k *= 2\n return k\n}\n\n\n\nfunction isSize(n: number): boolean {\n return Number.isSafeInteger(n) && n >= 0\n}\n\nfunction equal(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false\n return true\n}\n\nfunction refused(reason: string): MerkleVerification {\n return { verified: false, reason }\n}\n\nfunction toHex(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n\nfunction fromHex(hex: string): Uint8Array {\n const bytes = new Uint8Array(hex.length / 2)\n for (let i = 0; i < bytes.length; i++) bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16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C,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK,IAAI,EAAE,OAAO,EAAE,IAAI,OAAO;CAC7D,OAAO;AACT;AAEA,SAAS,QAAQ,QAAoC;CACnD,OAAO;EAAE,UAAU;EAAO;CAAO;AACnC;AAEA,SAAS,MAAM,OAA2B;CACxC,OAAO,MAAM,KAAK,QAAQ,SAAS,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;AAChF;AAEA,SAAS,QAAQ,KAAyB;CACxC,MAAM,QAAQ,IAAI,WAAW,IAAI,SAAS,CAAC;CAC3C,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,MAAM,KAAK,OAAO,SAAS,IAAI,MAAM,IAAI,GAAG,IAAI,IAAI,CAAC,GAAG,EAAE;CACjG,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"ledger-core-CAxUdDk0.js","names":[],"sources":["../src/ledger-core/merkle.ts"],"sourcesContent":["/**\n * Merkle proofs over an append-only list of leaves (RFC 9162 §2.1, the\n * Certificate Transparency tree).\n *\n * A hash chain proves a whole log against its head, but proving one entry means\n * replaying everything before it. This tree proves any one leaf against a root\n * with ⌈log₂ n⌉ hashes (inclusion), and proves that a larger tree only appended\n * to a smaller one (consistency). A verifier holding a root can therefore check\n * a single event, or that a later checkpoint extends an earlier one, without\n * reading the rest of the log.\n *\n * Leaves and interior nodes are domain-separated (0x00 and 0x01 prefixes), so a\n * leaf can never be presented as an interior node. Content that may later be\n * redacted takes a random 32-byte salt: a verifier then needs only the leaf's\n * hash, and short content cannot be guessed back from that hash. The salt must\n * be stored apart from anything that is shared after redaction.\n *\n * Builders refuse malformed input by throwing; verifiers never throw and return\n * a typed outcome, because a proof is external evidence and a bad one is a\n * finding, not a crash.\n */\nimport { sha256Bytes } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../errors'\nimport { LEDGER_HASH_PATTERN, type LedgerHash } from './canonical'\n\n/** Proof that one leaf is at `leafIndex` in a tree of `treeSize` leaves. */\nexport interface MerkleInclusionProof {\n readonly leafIndex: number\n readonly treeSize: number\n readonly path: readonly LedgerHash[]\n}\n\n/** Proof that the first `oldSize` leaves of a `newSize` tree are unchanged. */\nexport interface MerkleConsistencyProof {\n readonly oldSize: number\n readonly newSize: number\n readonly path: readonly LedgerHash[]\n}\n\nexport type MerkleVerification =\n | { readonly verified: true }\n | { readonly verified: false; readonly reason: string }\n\nconst SALT_PATTERN = /^[a-f0-9]{64}$/\nconst LEAF_PREFIX = 0x00\nconst NODE_PREFIX = 0x01\nconst encoder = new TextEncoder()\n\n/** Root of the empty tree: SHA-256 of no bytes. */\nconst MERKLE_EMPTY_ROOT: LedgerHash = sha256Bytes(new Uint8Array(0)) as LedgerHash\n\n/** A fresh random salt for {@link merkleLeafHash}: 32 bytes as 64 lowercase hex characters. */\nexport function merkleSalt(): string {\n return toHex(globalThis.crypto.getRandomValues(new Uint8Array(32)))\n}\n\n/**\n * Leaf hash of `content`: SHA-256(0x00 ‖ salt ‖ content). Without a salt this is\n * exactly the RFC 9162 leaf hash. Strings are hashed as UTF-8.\n */\nexport function merkleLeafHash(content: Uint8Array | string, salt?: string): LedgerHash {\n const bytes = typeof content === 'string' ? encoder.encode(content) : content\n if (salt === undefined) return digest(LEAF_PREFIX, bytes)\n if (!SALT_PATTERN.test(salt)) {\n throw new ValidationError('merkle salt must be 32 bytes as 64 lowercase hex characters')\n }\n return digest(LEAF_PREFIX, fromHex(salt), bytes)\n}\n\n/** Root over leaf hashes, in order. The empty list has {@link MERKLE_EMPTY_ROOT}. */\nexport function merkleRoot(leaves: readonly LedgerHash[]): LedgerHash {\n const nodes = decodeLeaves(leaves)\n return nodes.length === 0 ? MERKLE_EMPTY_ROOT : toLedgerHash(subtreeRoot(nodes, 0, nodes.length))\n}\n\n/** Inclusion proof for the leaf at `leafIndex` (RFC 9162 §2.1.3.1). */\nexport function merkleInclusionProof(\n leaves: readonly LedgerHash[],\n leafIndex: number,\n): MerkleInclusionProof {\n const nodes = decodeLeaves(leaves)\n if (!Number.isSafeInteger(leafIndex) || leafIndex < 0 || leafIndex >= nodes.length) {\n throw new ValidationError(\n `merkle leaf index ${leafIndex} is outside a tree of ${nodes.length} leaves`,\n )\n }\n const path: Uint8Array[] = []\n inclusionPath(nodes, leafIndex, 0, nodes.length, path)\n return { leafIndex, treeSize: nodes.length, path: path.map(toLedgerHash) }\n}\n\n\n\n/** Check that `leaf` is in the tree with `root` at the proof's index (RFC 9162 §2.1.3.2). */\nexport function verifyMerkleInclusion(\n leaf: LedgerHash,\n proof: MerkleInclusionProof,\n root: LedgerHash,\n): MerkleVerification {\n const { leafIndex, treeSize } = proof\n if (!isSize(treeSize) || !isSize(leafIndex) || leafIndex >= treeSize) {\n return refused(`leaf index ${leafIndex} is outside a tree of ${treeSize} leaves`)\n }\n const decoded = decodeAll([leaf, root, ...proof.path])\n if (decoded === undefined) return refused('proof carries a malformed hash')\n const [leafBytes, rootBytes, ...path] = decoded as [Uint8Array, Uint8Array, ...Uint8Array[]]\n let fn = leafIndex\n let sn = treeSize - 1\n let r = leafBytes\n for (const p of path) {\n if (sn === 0) return refused('proof path is longer than the tree is deep')\n if (fn % 2 === 1 || fn === sn) {\n r = node(p, r)\n if (fn % 2 === 0) {\n while (fn % 2 === 0 && fn !== 0) {\n fn = Math.floor(fn / 2)\n sn = Math.floor(sn / 2)\n }\n }\n } else {\n r = node(r, p)\n }\n fn = Math.floor(fn / 2)\n sn = Math.floor(sn / 2)\n }\n if (sn !== 0) return refused('proof path is shorter than the tree is deep')\n return equal(r, rootBytes) ? { verified: true } : refused('leaf does not hash to the root')\n}\n\n\n\nfunction subtreeRoot(nodes: readonly Uint8Array[], start: number, end: number): Uint8Array {\n if (end - start === 1) return nodes[start] as Uint8Array\n const k = largestPowerOfTwoBelow(end - start)\n return node(subtreeRoot(nodes, start, start + k), subtreeRoot(nodes, start + k, end))\n}\n\nfunction inclusionPath(\n nodes: readonly Uint8Array[],\n index: number,\n start: number,\n end: number,\n path: Uint8Array[],\n): void {\n if (end - start === 1) return\n const k = largestPowerOfTwoBelow(end - start)\n if (index < start + k) {\n inclusionPath(nodes, index, start, start + k, path)\n path.push(subtreeRoot(nodes, start + k, end))\n } else {\n inclusionPath(nodes, index, start + k, end, path)\n path.push(subtreeRoot(nodes, start, start + k))\n }\n}\n\n\n\nfunction node(left: Uint8Array, right: Uint8Array): Uint8Array {\n return fromHex(digest(NODE_PREFIX, left, right).slice('sha256:'.length))\n}\n\nfunction digest(prefix: number, ...parts: Uint8Array[]): LedgerHash {\n const length = parts.reduce((total, part) => total + part.length, 1)\n const bytes = new Uint8Array(length)\n bytes[0] = prefix\n let offset = 1\n for (const part of parts) {\n bytes.set(part, offset)\n offset += part.length\n }\n return sha256Bytes(bytes) as LedgerHash\n}\n\nfunction decodeLeaves(leaves: readonly LedgerHash[]): Uint8Array[] {\n const decoded = decodeAll(leaves)\n if (decoded === undefined) {\n throw new ValidationError('merkle leaves must be sha256:<64 lowercase hex> hashes')\n }\n return decoded\n}\n\nfunction decodeAll(hashes: readonly string[]): Uint8Array[] | undefined {\n const out: Uint8Array[] = []\n for (const hash of hashes) {\n if (typeof hash !== 'string' || !LEDGER_HASH_PATTERN.test(hash)) return undefined\n out.push(fromHex(hash.slice('sha256:'.length)))\n }\n return out\n}\n\nfunction toLedgerHash(bytes: Uint8Array): LedgerHash {\n return `sha256:${toHex(bytes)}`\n}\n\nfunction largestPowerOfTwoBelow(n: number): number {\n let k = 1\n while (k * 2 < n) k *= 2\n return k\n}\n\n\n\nfunction isSize(n: number): boolean {\n return Number.isSafeInteger(n) && n >= 0\n}\n\nfunction equal(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false\n return true\n}\n\nfunction refused(reason: string): MerkleVerification {\n return { verified: false, reason }\n}\n\nfunction toHex(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n\nfunction fromHex(hex: string): Uint8Array {\n const bytes = new Uint8Array(hex.length / 2)\n for (let i = 0; i < bytes.length; i++) bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)\n return bytes\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,MAAM,eAAe;AACrB,MAAM,cAAc;AACpB,MAAM,cAAc;AACpB,MAAM,UAAU,IAAI,YAAY;;AAGhC,MAAM,oBAAgC,4BAAY,IAAI,WAAW,CAAC,CAAC;;AAGnE,SAAgB,aAAqB;CACnC,OAAO,MAAM,WAAW,OAAO,gCAAgB,IAAI,WAAW,EAAE,CAAC,CAAC;AACpE;;;;;AAMA,SAAgB,eAAe,SAA8B,MAA2B;CACtF,MAAM,QAAQ,OAAO,YAAY,WAAW,QAAQ,OAAO,OAAO,IAAI;CACtE,IAAI,SAAS,KAAA,GAAW,OAAO,OAAO,aAAa,KAAK;CACxD,IAAI,CAAC,aAAa,KAAK,IAAI,GACzB,MAAM,IAAI,gBAAgB,6DAA6D;CAEzF,OAAO,OAAO,aAAa,QAAQ,IAAI,GAAG,KAAK;AACjD;;AAGA,SAAgB,WAAW,QAA2C;CACpE,MAAM,QAAQ,aAAa,MAAM;CACjC,OAAO,MAAM,WAAW,IAAI,oBAAoB,aAAa,YAAY,OAAO,GAAG,MAAM,MAAM,CAAC;AAClG;;AAGA,SAAgB,qBACd,QACA,WACsB;CACtB,MAAM,QAAQ,aAAa,MAAM;CACjC,IAAI,CAAC,OAAO,cAAc,SAAS,KAAK,YAAY,KAAK,aAAa,MAAM,QAC1E,MAAM,IAAI,gBACR,qBAAqB,UAAU,wBAAwB,MAAM,OAAO,QACtE;CAEF,MAAM,OAAqB,CAAC;CAC5B,cAAc,OAAO,WAAW,GAAG,MAAM,QAAQ,IAAI;CACrD,OAAO;EAAE;EAAW,UAAU,MAAM;EAAQ,MAAM,KAAK,IAAI,YAAY;CAAE;AAC3E;;AAKA,SA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