@sorbetai/runtime 0.0.0-stage → 0.1.0-alpha.16
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/LICENSE +21 -0
- package/README.md +87 -2
- package/dist/contracts-CFmBr0LI.d.ts +12107 -0
- package/dist/index.d.ts +4230 -0
- package/dist/index.js +12915 -0
- package/dist/index.js.map +1 -0
- package/dist/node.d.ts +200 -0
- package/dist/node.js +1878 -0
- package/dist/node.js.map +1 -0
- package/dist/observation-DyvvxD35.js +2713 -0
- package/dist/observation-DyvvxD35.js.map +1 -0
- package/package.json +52 -3
package/dist/node.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node.js","names":["handle: FileHandle","openFile","resolvePath","properties: Record<string, s.Schema | s.Optional>","pickFields","PersistedEnvelopeValidator","InlineStringBytesSchema","#factCount","#readFrame","#onClose","readFrame","#nextIndex","#waiting","#closed","#failure","#nextPending","#next","#decodedFrame","encoded: unknown","frame: PersistedJournalFrame","journal: ScannedJournal","openFile","fragments: Buffer[]","facts: readonly FactPosition[]","scanned: ScannedJournal","facts: JournalFact[]","#filePath","#options","#maxIndexedFacts","#maxIndexedBytes","resolvePath","#reading","#read","#readRecovery","facts: JournalRecoveryFact[]","#scanned","#observation","#readHandle","#appendHandle","#frames","#factLocators","#cursorIndexes","#subscriptions","#activeReads","#artifactStore","#inlineStringBytes","#writerLease","#sessionId","#needsSeparator","#fileSize","#open","appendHandle: FileHandle","#acceptingAppends","#unavailableError","#serialize","bytes: number | undefined","#assertOperational","#assertSession","#bindSession","#fault","#indexAfter","#trackRead","#readFacts","subscription: JsonlSubscription","#decodeFrameAt","#closing","#close","failures: unknown[]","#tail","facts: readonly JournalFact[]","CommittedSessionFact: s.Schema<JournalFact>","CommittedUnitFact: s.Schema<UnitFact>","unitFacts: UnitInspectionPage['unitFacts'][number][]","sessionFacts: UnitInspectionPage['sessionFacts'][number][]","records: UnitRecord[]","pending: Promise<void>[]","pending: Buffer[]","chunk","#directory","#positions","#frames","#decoded","#cacheOrder","file: UnitScanSource","transactions: UnitTransactions","artifacts?: ArtifactStore","#cacheBytes","#cacheFrames","inFlight: {\n readonly offset: number;\n readonly length: number;\n readonly records: readonly UnitRecord[] | Promise<readonly UnitRecord[]>;\n }[]","ranges: { offset: number; end: number; frames: number[] }[]","#remember","#transactions","#stringReuse","options: JsonlUnitStoreOptions","file: FileHandle","lease: JournalWriterLease","json: string","file: ReadableUnitSource","frames: UnitFrames","history: UnitHistory","incompleteTail: boolean","#closing","#queue","#options","#readLifecycle"],"sources":["../src/journal/journal-file.ts","../src/journal/writer-lease.ts","../src/journal/recovery-fact.ts","../src/journal/jsonl-store.ts","../src/journal/unit/frame.ts","../src/journal/unit/scan.ts","../src/journal/unit/transactions.ts","../src/journal/unit/seal.ts","../src/journal/unit/jsonl.ts"],"sourcesContent":["import { open as openFile, realpath, unlink, type FileHandle } from 'node:fs/promises';\nimport { basename, dirname, resolve as resolvePath } from 'node:path';\nimport { isError } from 'es-toolkit';\n\nexport async function createJournalFile(filePath: string): Promise<void> {\n let handle: FileHandle;\n try {\n handle = await openFile(filePath, 'ax', 0o600);\n } catch (cause) {\n if (isError(cause) && Reflect.get(cause, 'code') === 'EEXIST') return;\n throw cause;\n }\n await handle.close();\n try {\n await syncDirectory(dirname(filePath));\n } catch (cause) {\n await unlink(filePath);\n throw cause;\n }\n}\n\nexport async function canonicalJournalPath(filePath: string): Promise<string> {\n const absoluteFilePath = resolvePath(filePath);\n try {\n return await realpath(absoluteFilePath);\n } catch (cause) {\n if (!isError(cause) || Reflect.get(cause, 'code') !== 'ENOENT') throw cause;\n const canonicalDirectory = await realpath(dirname(absoluteFilePath));\n return resolvePath(canonicalDirectory, basename(absoluteFilePath));\n }\n}\n\nexport async function syncDirectory(directory: string): Promise<void> {\n // Node cannot open a Windows directory with the write access required by fsync.\n if (process.platform === 'win32') return;\n const handle = await openFile(directory, 'r');\n try {\n await handle.sync();\n } finally {\n await handle.close();\n }\n}\n","import { JournalWriterBusyError } from './errors.js';\nexport { JournalWriterBusyError } from './errors.js';\nimport { isError } from 'es-toolkit';\nimport { canonicalJournalPath } from './journal-file.js';\n\nconst SQLITE_BUSY = 5;\n\nexport interface JournalWriterLease {\n release(): void;\n}\n\n/**\n * Excludes legacy writers while an offline importer reads their immutable prefix.\n * Acquiring creates only the mutex file; it never repairs or creates the Journal.\n * The parent directory must exist. Release after all source reads have completed.\n */\nexport async function acquireJournalWriterLease(\n journalFilePath: string\n): Promise<JournalWriterLease> {\n journalFilePath = await canonicalJournalPath(journalFilePath);\n const { DatabaseSync } = await import('node:sqlite');\n const database = new DatabaseSync(`${journalFilePath}.writer-lock`, { timeout: 0 });\n try {\n // This empty database is only a mutex. Keep its rollback journal off disk and\n // drop the page cache it would never use; one stays open per writer.\n database.exec('PRAGMA cache_size=0; PRAGMA journal_mode=MEMORY; BEGIN IMMEDIATE');\n } catch (cause) {\n database.close();\n if (isError(cause) && Reflect.get(cause, 'errcode') === SQLITE_BUSY) {\n throw new JournalWriterBusyError(journalFilePath, { cause });\n }\n throw cause;\n }\n\n let released = false;\n return {\n release: () => {\n if (released) return;\n database.close();\n released = true;\n },\n };\n}\n","import { compile, objectProperties } from '@sorbetai/schema';\nimport { pick as pickFields } from 'es-toolkit';\nimport * as s from '@earendil-works/pi-schema';\nimport { decode } from '@sorbetai/schema';\nimport { JournalFactDefinitions, type JournalFact, type JournalFactKind } from './contracts.js';\nimport type { JsonValue } from '../serialization.js';\nimport { utf8ByteLength } from '../serialization.js';\n\ntype RecoveryHeaderKeys =\n 'id' | 'sessionId' | 'sequence' | 'cursor' | 'recordedAt' | 'kind' | 'schemaVersion';\ntype ModelRecoveryKind = 'model.requested' | 'model.response.committed' | 'model.request.unknown';\ntype ModelInvocationRecoveryKind =\n 'model.invocation.requested' | 'model.invocation.response.committed' | 'model.invocation.unknown';\ntype CompactionModelRecoveryKind =\n 'compaction.model.requested' | 'compaction.model.response.committed' | 'compaction.model.failed';\ntype EffectRecoveryKind =\n 'effect.requested' | 'effect.succeeded' | 'effect.failed' | 'effect.unknown';\n\n/** Lifecycle identity only. This does not assert content/schema health or artifact availability. */\nexport type JournalRecoveryFact = {\n [Kind in JournalFactKind]: Pick<Extract<JournalFact, { kind: Kind }>, RecoveryHeaderKeys> &\n (Extract<JournalFact, { kind: Kind }> extends { runId: string }\n ? { readonly runId: string }\n : { readonly operationId: string }) &\n (Kind extends ModelRecoveryKind\n ? { readonly payload: { readonly modelRequestId: string } }\n : Kind extends ModelInvocationRecoveryKind\n ? { readonly payload: { readonly requestId: string } }\n : Kind extends EffectRecoveryKind\n ? { readonly payload: { readonly effectAttemptId: string } }\n : Kind extends CompactionModelRecoveryKind\n ? { readonly payload: { readonly attemptId: string } }\n : object);\n}[JournalFactKind];\n\nconst HeaderKeys = [\n 'id',\n 'sessionId',\n 'sequence',\n 'cursor',\n 'recordedAt',\n 'kind',\n 'schemaVersion',\n] as const;\nconst ModelKinds = new Set<JournalFactKind>([\n 'model.requested',\n 'model.response.committed',\n 'model.request.unknown',\n]);\nconst EffectKinds = new Set<JournalFactKind>([\n 'effect.requested',\n 'effect.succeeded',\n 'effect.failed',\n 'effect.unknown',\n]);\nconst ModelInvocationKinds = new Set<JournalFactKind>([\n 'model.invocation.requested',\n 'model.invocation.response.committed',\n 'model.invocation.unknown',\n]);\nconst CompactionModelKinds = new Set<JournalFactKind>([\n 'compaction.model.requested',\n 'compaction.model.response.committed',\n 'compaction.model.failed',\n]);\nconst CorrelationId = s.str({ minLength: 1 });\n\n// The kind/identity vocabulary comes from the authoritative fact schemas. Only\n// recovery correlation fields are checked; unrelated payloads stay unmaterialized.\nconst RecoveryFactSchema = s.union(\n JournalFactDefinitions.map((definition) => {\n const { schema, kind } = definition;\n const properties: Record<string, s.Schema | s.Optional> = {\n ...pickFields(objectProperties(schema), HeaderKeys),\n };\n\n if (definition.scope === 'session')\n properties.operationId = objectProperties(definition.schema).operationId;\n else properties.runId = objectProperties(definition.schema).runId;\n if (ModelKinds.has(kind))\n properties.payload = s.obj({ modelRequestId: CorrelationId }, { open: true });\n if (ModelInvocationKinds.has(kind))\n properties.payload = s.obj({ requestId: CorrelationId }, { open: true });\n if (EffectKinds.has(kind))\n properties.payload = s.obj({ effectAttemptId: CorrelationId }, { open: true });\n if (CompactionModelKinds.has(kind))\n properties.payload = s.obj({ attemptId: CorrelationId }, { open: true });\n return s.obj(properties, { open: true });\n })\n) as s.Schema<JournalRecoveryFact>;\nconst RecoveryFactValidator = compile(RecoveryFactSchema);\n\nexport function decodeJournalRecoveryFact(value: JsonValue): JournalRecoveryFact {\n const fact = RecoveryFactValidator.check(value) ? value : decode(RecoveryFactSchema, value);\n const identity = {\n id: fact.id,\n sessionId: fact.sessionId,\n sequence: fact.sequence,\n cursor: fact.cursor,\n recordedAt: fact.recordedAt,\n schemaVersion: fact.schemaVersion,\n };\n switch (fact.kind) {\n case 'model.invocation.requested':\n case 'model.invocation.response.committed':\n case 'model.invocation.unknown':\n return {\n ...identity,\n kind: fact.kind,\n operationId: fact.operationId,\n payload: { requestId: fact.payload.requestId },\n };\n case 'model.requested':\n case 'model.response.committed':\n case 'model.request.unknown':\n return {\n ...identity,\n kind: fact.kind,\n runId: fact.runId,\n payload: { modelRequestId: fact.payload.modelRequestId },\n };\n case 'effect.requested':\n case 'effect.succeeded':\n case 'effect.failed':\n case 'effect.unknown':\n return {\n ...identity,\n kind: fact.kind,\n runId: fact.runId,\n payload: { effectAttemptId: fact.payload.effectAttemptId },\n };\n case 'compaction.model.requested':\n case 'compaction.model.response.committed':\n case 'compaction.model.failed':\n return {\n ...identity,\n kind: fact.kind,\n operationId: fact.operationId,\n payload: { attemptId: fact.payload.attemptId },\n };\n case 'submission.accepted':\n case 'submission.applied':\n case 'submission.placed':\n return { ...identity, kind: fact.kind, operationId: fact.operationId };\n case 'submission.withdrawn':\n case 'submission.settled':\n return { ...identity, kind: fact.kind, operationId: fact.operationId };\n case 'permission.grant.revoked':\n case 'plugin.record.committed':\n case 'session.forked':\n case 'model.request.base.committed':\n case 'goal.created':\n case 'goal.status.changed':\n case 'goal.continuation.requested':\n case 'goal.removed':\n case 'session.behavior.changed':\n case 'compaction.requested':\n case 'compaction.committed':\n case 'compaction.failed':\n case 'compaction.skipped':\n case 'tool.operation.accepted':\n case 'tool.operation.approval.requested':\n case 'tool.operation.approval.resolved':\n case 'tool.operation.permission.decided':\n case 'tool.operation.permission.failed':\n case 'tool.operation.effect.requested':\n case 'tool.operation.effect.succeeded':\n case 'tool.operation.effect.failed':\n case 'tool.operation.effect.unknown':\n case 'tool.operation.terminal':\n return { ...identity, kind: fact.kind, operationId: fact.operationId };\n default:\n return { ...identity, kind: fact.kind, runId: fact.runId };\n }\n}\n\nexport function journalRecoveryIdentityBytes(\n fact: Pick<JournalRecoveryFact, RecoveryHeaderKeys> & {\n readonly runId?: string;\n readonly operationId?: string;\n readonly payload?: {\n readonly modelRequestId?: string;\n readonly requestId?: string;\n readonly effectAttemptId?: string;\n readonly attemptId?: string;\n };\n }\n): number {\n const identities = [\n fact.id,\n fact.sessionId,\n fact.cursor,\n fact.recordedAt,\n fact.runId,\n fact.operationId,\n fact.payload?.modelRequestId,\n fact.payload?.requestId,\n fact.payload?.effectAttemptId,\n fact.payload?.attemptId,\n ];\n return identities.reduce(\n (bytes, value) => (value === undefined ? bytes : bytes + utf8ByteLength(value)),\n 0\n );\n}\n","import * as s from '@earendil-works/pi-schema';\nimport { compile, decode } from '@sorbetai/schema';\nimport {\n JournalCorruptionError,\n JournalReaderCapacityError,\n JournalReaderResetRequiredError,\n} from './errors.js';\nexport {\n JournalCorruptionError,\n JournalReaderCapacityError,\n JournalReaderResetRequiredError,\n} from './errors.js';\nimport { canonicalJournalPath, createJournalFile } from './journal-file.js';\nimport { mkdir, open as openFile, truncate, type FileHandle } from 'node:fs/promises';\nimport { dirname, resolve as resolvePath } from 'node:path';\n\nimport type { ArtifactStore } from '@sorbetai/artifacts';\nimport { isError, isPromise } from 'es-toolkit';\n\nimport { JsonValueSchema, type JsonValue } from '../serialization.js';\nimport {\n JOURNAL_FACT_SCHEMA_VERSION,\n JOURNAL_APPEND_BATCH_MAX_BYTES,\n JOURNAL_APPEND_BATCH_MAX_FACTS,\n JOURNAL_READ_DEFAULT_LIMIT,\n JOURNAL_READ_MAX_LIMIT,\n JournalConflictError,\n JournalCursorGapError,\n JournalCursorSchema,\n JournalFactSchema,\n JournalStoreFaultError,\n isDurableSubmissionFactKind,\n type JournalAppendOptions,\n type JournalCursor,\n type JournalFact,\n type JournalPage,\n type JournalReadOptions,\n type JournalStore,\n type JournalSubscription,\n type JournalSubscriptionOptions,\n type JournalWrite,\n} from './contracts.js';\nimport {\n decodeJournalEnvelope,\n encodeJournalFact,\n encodeJournalPayload,\n PersistedJournalEnvelopeSchema,\n} from './offloaded-fact.js';\nimport { acquireJournalWriterLease, type JournalWriterLease } from './writer-lease.js';\nimport { observeRuntime, type RuntimeObservationPort } from '../observation/index.js';\nimport {\n decodeJournalRecoveryFact,\n journalRecoveryIdentityBytes,\n type JournalRecoveryFact,\n} from './recovery-fact.js';\n\nconst PersistedEnvelopeValidator = compile(PersistedJournalEnvelopeSchema);\n\nconst DEFAULT_INLINE_STRING_BYTES = 64 * 1024;\nconst JOURNAL_SCAN_BUFFER_BYTES = 1024 * 1024;\nconst InlineStringBytesSchema = s.int({ minimum: 1 });\nconst JournalReadLimitSchema = s.int({ minimum: 1, maximum: JOURNAL_READ_MAX_LIMIT });\nconst PersistedJournalFrameSchema = s.obj(\n {\n storageVersion: s.lit(4),\n facts: s.arr(JsonValueSchema, {\n minItems: 1,\n maxItems: JOURNAL_APPEND_BATCH_MAX_FACTS,\n }),\n },\n { open: false }\n);\ntype PersistedJournalFrame = s.Static<typeof PersistedJournalFrameSchema>;\nconst PersistedJournalFrameValidator = compile(PersistedJournalFrameSchema);\n\nexport interface JsonlJournalStoreOptions {\n readonly observation?: RuntimeObservationPort;\n readonly artifactStore?: ArtifactStore;\n readonly inlineStringBytes?: number;\n}\n\ninterface WaitingReader {\n readonly resolve: () => void;\n readonly reject: (cause: Error) => void;\n}\n\ninterface DecodedJournalFrame {\n readonly firstFactIndex: number;\n readonly facts: readonly JournalFact[];\n}\n\nclass JsonlSubscription implements JournalSubscription {\n readonly #factCount: () => number;\n readonly #readFrame: (factIndex: number) => Promise<DecodedJournalFrame>;\n readonly #onClose: () => void;\n #nextIndex: number;\n #decodedFrame: DecodedJournalFrame | undefined;\n #waiting: WaitingReader | undefined;\n #failure: Error | undefined;\n #nextPending = false;\n #closed = false;\n\n constructor(\n factCount: () => number,\n readFrame: (factIndex: number) => Promise<DecodedJournalFrame>,\n nextIndex: number,\n onClose: () => void\n ) {\n this.#factCount = factCount;\n this.#readFrame = readFrame;\n this.#nextIndex = nextIndex;\n this.#onClose = onClose;\n }\n\n notify(): void {\n const waiting = this.#waiting;\n if (waiting === undefined) return;\n this.#waiting = undefined;\n waiting.resolve();\n }\n\n fail(failure: Error): void {\n if (this.#closed || this.#failure !== undefined) return;\n this.#failure = failure;\n const waiting = this.#waiting;\n this.#waiting = undefined;\n waiting?.reject(failure);\n }\n\n close(): void {\n if (this.#closed) return;\n this.#closed = true;\n this.#onClose();\n this.notify();\n }\n\n [Symbol.asyncIterator](): AsyncIterator<JournalFact> {\n return {\n next: async () => {\n if (this.#nextPending) {\n throw new Error('Journal subscription does not support concurrent next() calls');\n }\n this.#nextPending = true;\n try {\n return await this.#next();\n } finally {\n this.#nextPending = false;\n }\n },\n return: async () => {\n this.close();\n return { done: true, value: undefined };\n },\n };\n }\n\n async #next(): Promise<IteratorResult<JournalFact>> {\n // A Journal subscription is open-ended; each pass yields, fails, closes, or waits for append.\n // ast-grep-ignore: no-unbounded-loop\n while (true) {\n if (this.#failure !== undefined) throw this.#failure;\n if (this.#closed) return { done: true, value: undefined };\n if (this.#nextIndex < this.#factCount()) {\n const decoded = this.#decodedFrame;\n if (\n decoded === undefined ||\n this.#nextIndex < decoded.firstFactIndex ||\n this.#nextIndex >= decoded.firstFactIndex + decoded.facts.length\n ) {\n this.#decodedFrame = await this.#readFrame(this.#nextIndex);\n }\n const frame = this.#decodedFrame;\n const fact = frame?.facts[this.#nextIndex - frame.firstFactIndex];\n if (fact === undefined)\n throw new JournalCorruptionError('Journal index points outside its frame');\n this.#nextIndex += 1;\n return { done: false, value: fact };\n }\n await new Promise<void>((resolve, reject) => {\n this.#waiting = { resolve, reject };\n });\n }\n }\n}\n\ninterface JournalFrameLocator {\n readonly offset: number;\n readonly length: number;\n readonly lineNumber: number;\n readonly firstFactIndex: number;\n readonly factCount: number;\n}\n\ninterface JournalFactLocator {\n readonly cursor: JournalCursor;\n readonly frameIndex: number;\n readonly factIndex: number;\n}\n\ninterface ScannedJournal {\n frames: JournalFrameLocator[];\n factLocators: JournalFactLocator[];\n cursorIndexes: Map<JournalCursor, number>;\n indexedBytes?: number;\n throughSequence: number;\n lastCursor: JournalCursor | undefined;\n lastLineNumber: number;\n sessionId: string | undefined;\n readonly needsSeparator: boolean;\n readonly fileSize: number;\n readonly observedFileSize?: number;\n readonly hasMore?: boolean;\n readonly fileIdentity?: { readonly dev: number; readonly ino: number };\n readonly truncateAt?: number;\n}\n\nasync function parsePersistedFact(\n value: JsonValue,\n lineNumber: number,\n factNumber: number,\n artifactStore: ArtifactStore | undefined\n): Promise<JournalFact> {\n try {\n const decoded = await decodeJournalEnvelope(value, artifactStore);\n return decode(JournalFactSchema, decoded);\n } catch (cause) {\n throw new JournalCorruptionError(\n `Journal frame ${lineNumber} fact ${factNumber} does not match its schema`,\n { cause }\n );\n }\n}\n\nasync function parseFrame(\n frame: PersistedJournalFrame,\n lineNumber: number,\n artifactStore: ArtifactStore | undefined\n): Promise<readonly JournalFact[]> {\n return await Promise.all(\n frame.facts.map(\n async (fact, index) => await parsePersistedFact(fact, lineNumber, index + 1, artifactStore)\n )\n );\n}\n\nclass JournalLineSyntaxError extends Error {\n constructor(lineNumber: number, cause: Error) {\n super(`Journal line ${lineNumber} is not valid JSON`, { cause });\n this.name = 'JournalLineSyntaxError';\n }\n}\n\nfunction parseLineFrame(line: string, lineNumber: number): PersistedJournalFrame {\n let encoded: unknown;\n try {\n encoded = JSON.parse(line);\n } catch (cause) {\n throw new JournalLineSyntaxError(lineNumber, isError(cause) ? cause : new Error(String(cause)));\n }\n let frame: PersistedJournalFrame;\n try {\n frame = PersistedJournalFrameValidator.check(encoded)\n ? encoded\n : decode(PersistedJournalFrameSchema, encoded);\n } catch (cause) {\n throw new JournalCorruptionError(\n `Journal line ${lineNumber} uses an unsupported Journal format; original file was preserved`,\n {\n cause,\n }\n );\n }\n return frame;\n}\n\nasync function parseLine(\n line: string,\n lineNumber: number,\n artifactStore: ArtifactStore | undefined\n): Promise<readonly JournalFact[]> {\n return parseFrame(parseLineFrame(line, lineNumber), lineNumber, artifactStore);\n}\n\nconst FactPositionSchema = s.obj(\n {\n schemaVersion: s.lit(JOURNAL_FACT_SCHEMA_VERSION),\n id: s.str(),\n cursor: JournalCursorSchema,\n sessionId: s.str(),\n sequence: s.int({ minimum: 1 }),\n },\n { open: true }\n);\ntype FactPosition = s.Static<typeof FactPositionSchema>;\nconst FactPositionValidator = compile(FactPositionSchema);\n\nasync function scanFrame(\n line: string,\n lineNumber: number,\n artifactStore: ArtifactStore | undefined,\n retainFrame?: (facts: readonly JournalFact[]) => void,\n retainRecoveryFrame?: (facts: readonly JournalRecoveryFact[]) => void,\n recoveryLimits?: {\n readonly maxIndexedFacts: number;\n readonly maxIndexedBytes: number;\n readonly maxFrameBytes?: number;\n readonly maxIdentityBytes?: number;\n }\n): Promise<readonly FactPosition[]> {\n const frame = parseLineFrame(line, lineNumber);\n if (retainRecoveryFrame !== undefined) {\n const facts = frame.facts.map((value, index) => {\n try {\n return decodeJournalRecoveryFact(\n PersistedEnvelopeValidator.check(value) ? value.fact : value\n );\n } catch (cause) {\n throw new JournalCorruptionError(\n `Journal frame ${lineNumber} fact ${index + 1} has unavailable lifecycle metadata`,\n { cause }\n );\n }\n });\n for (const fact of facts)\n if (\n recoveryLimits?.maxIdentityBytes !== undefined &&\n journalRecoveryIdentityBytes(fact) > recoveryLimits.maxIdentityBytes\n )\n throw new JournalReaderCapacityError(\n recoveryLimits.maxIndexedFacts,\n recoveryLimits.maxIndexedBytes,\n recoveryLimits.maxFrameBytes,\n recoveryLimits.maxIdentityBytes\n );\n retainRecoveryFrame(facts);\n return facts;\n }\n if (retainFrame !== undefined) {\n const facts = await parseFrame(frame, lineNumber, artifactStore);\n retainFrame(facts);\n return facts;\n }\n return frame.facts.map((value) => {\n const raw = PersistedEnvelopeValidator.check(value) ? value.fact : value;\n return FactPositionValidator.check(raw) ? raw : decode(FactPositionSchema, raw);\n });\n}\n\nfunction indexFrame(\n facts: readonly FactPosition[],\n offset: number,\n length: number,\n lineNumber: number,\n journal: ScannedJournal,\n limits?: { readonly maxIndexedFacts: number; readonly maxIndexedBytes: number }\n): void {\n const frameIndex = journal.frames.length;\n const firstFactIndex = journal.factLocators.length;\n if (limits !== undefined) journal.indexedBytes = (journal.indexedBytes ?? 0) + 64;\n for (const [factIndex, fact] of facts.entries()) {\n if (limits !== undefined) {\n journal.indexedBytes = (journal.indexedBytes ?? 0) + 64 + Buffer.byteLength(fact.cursor);\n if (journal.indexedBytes > limits.maxIndexedBytes)\n throw new JournalReaderCapacityError(limits.maxIndexedFacts, limits.maxIndexedBytes);\n }\n const expectedSequence = journal.throughSequence + 1;\n if (fact.sequence !== expectedSequence) {\n throw new JournalCorruptionError(\n `Journal sequence ${fact.sequence} does not match expected sequence ${expectedSequence}`\n );\n }\n if (journal.sessionId === undefined) journal.sessionId = fact.sessionId;\n else if (fact.sessionId !== journal.sessionId) {\n throw new JournalCorruptionError('One JSONL Journal file cannot contain multiple sessions');\n }\n if (fact.cursor !== fact.id) {\n throw new JournalCorruptionError('JSONL Journal cursor must equal its stable fact identity');\n }\n if (journal.cursorIndexes.has(fact.cursor)) {\n throw new JournalCorruptionError(`Journal fact identity is duplicated: ${fact.id}`);\n }\n journal.cursorIndexes.set(fact.cursor, journal.factLocators.length);\n journal.factLocators.push({ cursor: fact.cursor, frameIndex, factIndex });\n journal.throughSequence = fact.sequence;\n journal.lastCursor = fact.cursor;\n }\n journal.frames.push({ offset, length, lineNumber, firstFactIndex, factCount: facts.length });\n journal.lastLineNumber = lineNumber;\n}\n\nasync function scanJournal(\n filePath: string,\n artifactStore: ArtifactStore | undefined,\n retainFrame?: (facts: readonly JournalFact[]) => void,\n synchronize = false,\n incremental?: {\n readonly previous?: ScannedJournal;\n readonly indexRetention?: 'history' | 'page';\n readonly limit: number;\n readonly maxIndexedFacts: number;\n readonly maxIndexedBytes: number;\n readonly maxFrameBytes?: number;\n readonly maxIdentityBytes?: number;\n readonly signal?: AbortSignal;\n },\n retainRecoveryFrame?: (facts: readonly JournalRecoveryFact[]) => void\n): Promise<ScannedJournal> {\n const previous = incremental?.previous;\n const journal: ScannedJournal =\n previous === undefined\n ? {\n frames: [],\n factLocators: [],\n cursorIndexes: new Map(),\n throughSequence: 0,\n lastCursor: undefined,\n lastLineNumber: 0,\n sessionId: undefined,\n needsSeparator: false,\n fileSize: 0,\n }\n : { ...previous, needsSeparator: false, truncateAt: undefined };\n if (incremental?.indexRetention === 'page') {\n // Keep the committed byte/sequence position, but charge only this page's index.\n // Copying the containers leaves the previous page intact if this scan fails.\n journal.frames = [];\n journal.factLocators = [];\n journal.cursorIndexes = new Map();\n journal.indexedBytes = 0;\n }\n const originalFrames = journal.frames.length;\n const originalFacts = journal.factLocators.length;\n incremental?.signal?.throwIfAborted();\n // Windows requires write access to flush a file. This handle never writes or repairs it.\n const handle = await openFile(filePath, synchronize ? 'r+' : 'r');\n const buffer = Buffer.allocUnsafe(JOURNAL_SCAN_BUFFER_BYTES);\n const fragments: Buffer[] = [];\n let fragmentBytes = 0;\n let position = previous?.fileSize ?? 0;\n let lineOffset = position;\n let lineNumber = (previous?.lastLineNumber ?? 0) + 1;\n let separatorPending = previous?.needsSeparator ?? false;\n let stoppedEarly = false;\n try {\n const { size: fileSize, dev, ino } = await handle.stat();\n if (\n previous !== undefined &&\n (fileSize < previous.fileSize ||\n previous.fileIdentity?.dev !== dev ||\n previous.fileIdentity?.ino !== ino)\n )\n throw new JournalReaderResetRequiredError();\n while (position < fileSize) {\n incremental?.signal?.throwIfAborted();\n const bytesRemaining = fileSize - position;\n const readLength = Math.min(buffer.byteLength, bytesRemaining);\n const { bytesRead } = await handle.read(buffer, 0, readLength, position);\n if (bytesRead === 0) {\n throw new JournalCorruptionError(\n `Journal ended at byte ${position} before its expected size of ${fileSize} bytes`\n );\n }\n if (separatorPending && buffer[0] !== 0x0a)\n throw new JournalCorruptionError(\n 'A complete unterminated Journal frame requires a separator before appended frames'\n );\n let segmentStart = 0;\n for (let index = 0; index < bytesRead; index += 1) {\n if (buffer[index] !== 0x0a) continue;\n const segment = buffer.subarray(segmentStart, index);\n const line =\n fragments.length === 0\n ? segment\n : Buffer.concat([...fragments, segment], fragmentBytes + segment.byteLength);\n if (separatorPending && line.byteLength === 0) {\n separatorPending = false;\n segmentStart = index + 1;\n lineOffset = position + segmentStart;\n continue;\n }\n separatorPending = false;\n if (line.byteLength === 0) {\n throw new JournalCorruptionError(`Journal line ${lineNumber} is empty`);\n }\n if (incremental?.maxFrameBytes !== undefined && line.byteLength > incremental.maxFrameBytes)\n throw new JournalReaderCapacityError(\n incremental.maxIndexedFacts,\n incremental.maxIndexedBytes,\n incremental.maxFrameBytes\n );\n if (line.byteLength > JOURNAL_APPEND_BATCH_MAX_BYTES)\n throw new JournalCorruptionError(\n `Journal line ${lineNumber} exceeds the maximum frame size`\n );\n let facts: readonly FactPosition[];\n try {\n incremental?.signal?.throwIfAborted();\n const text = line.toString('utf8');\n facts = await scanFrame(\n text,\n lineNumber,\n artifactStore,\n retainFrame,\n retainRecoveryFrame,\n incremental\n );\n } catch (cause) {\n if (cause instanceof JournalLineSyntaxError) {\n throw new JournalCorruptionError(cause.message, { cause: cause.cause });\n }\n throw cause;\n }\n incremental?.signal?.throwIfAborted();\n if (\n incremental !== undefined &&\n journal.factLocators.length + facts.length > incremental.maxIndexedFacts\n )\n throw new JournalReaderCapacityError(incremental.maxIndexedFacts);\n indexFrame(facts, lineOffset, line.byteLength, lineNumber, journal, incremental);\n fragments.length = 0;\n fragmentBytes = 0;\n segmentStart = index + 1;\n lineOffset = position + segmentStart;\n lineNumber += 1;\n if (\n incremental !== undefined &&\n journal.factLocators.length - originalFacts >= incremental.limit &&\n lineOffset < fileSize\n ) {\n position = lineOffset;\n stoppedEarly = true;\n break;\n }\n }\n if (stoppedEarly) break;\n const trailing = buffer.subarray(segmentStart, bytesRead);\n if (trailing.byteLength > 0) {\n const copied = Buffer.from(trailing);\n fragments.push(copied);\n fragmentBytes += copied.byteLength;\n if (incremental?.maxFrameBytes !== undefined && fragmentBytes > incremental.maxFrameBytes)\n throw new JournalReaderCapacityError(\n incremental.maxIndexedFacts,\n incremental.maxIndexedBytes,\n incremental.maxFrameBytes\n );\n if (fragmentBytes > JOURNAL_APPEND_BATCH_MAX_BYTES)\n throw new JournalCorruptionError(\n `Journal line ${lineNumber} exceeds the maximum frame size`\n );\n }\n position += bytesRead;\n }\n\n let scanned: ScannedJournal = {\n ...journal,\n needsSeparator: separatorPending,\n fileSize: position,\n observedFileSize: fileSize,\n hasMore: stoppedEarly,\n fileIdentity: { dev, ino },\n };\n if (fragmentBytes > 0) {\n incremental?.signal?.throwIfAborted();\n const trailing = Buffer.concat(fragments, fragmentBytes);\n try {\n const text = trailing.toString('utf8');\n const facts = await scanFrame(\n text,\n lineNumber,\n artifactStore,\n retainFrame,\n retainRecoveryFrame,\n incremental\n );\n if (\n incremental !== undefined &&\n journal.factLocators.length + facts.length > incremental.maxIndexedFacts\n )\n throw new JournalReaderCapacityError(incremental.maxIndexedFacts);\n indexFrame(facts, lineOffset, trailing.byteLength, lineNumber, journal, incremental);\n scanned = {\n ...scanned,\n indexedBytes: journal.indexedBytes,\n throughSequence: journal.throughSequence,\n lastCursor: journal.lastCursor,\n lastLineNumber: journal.lastLineNumber,\n needsSeparator: true,\n fileSize: position,\n };\n } catch (cause) {\n if (!(cause instanceof JournalLineSyntaxError)) throw cause;\n scanned = {\n ...scanned,\n needsSeparator: false,\n fileSize: lineOffset,\n truncateAt: lineOffset,\n };\n }\n }\n // Flush after reading: recovery can replace an incomplete tail during the\n // scan. Complete frames are immutable under cooperating writers.\n // No facts reach the caller if synchronization fails.\n if (synchronize) await handle.sync();\n incremental?.signal?.throwIfAborted();\n return scanned;\n } catch (cause) {\n if (previous !== undefined) {\n const removed = journal.factLocators.splice(originalFacts);\n for (const fact of removed) journal.cursorIndexes.delete(fact.cursor);\n journal.frames.splice(originalFrames);\n }\n throw cause;\n } finally {\n await handle.close();\n }\n}\n\n/**\n * Reads a synchronized complete-frame prefix without acquiring writer ownership or\n * repairing a torn tail. By default, visibility does not imply durability.\n * `sync` flushes the same open file after reading its fixed byte prefix and fails if\n * flushing is unavailable. It requires write access but never changes file bytes.\n * This establishes file durability, not acknowledgement by the source writer;\n * directory durability and filesystem guarantees remain platform-dependent.\n */\nexport async function readJsonlJournal(\n filePath: string,\n options: Pick<JsonlJournalStoreOptions, 'artifactStore'> & {\n readonly durability?: 'observed' | 'sync';\n } = {}\n): Promise<readonly JournalFact[]> {\n const facts: JournalFact[] = [];\n await scanJournal(\n filePath,\n options.artifactStore,\n (frame) => facts.push(...frame),\n options.durability === 'sync'\n );\n return facts;\n}\n\nexport interface JsonlJournalReaderOptions extends Pick<JsonlJournalStoreOptions, 'artifactStore'> {\n readonly durability?: 'observed' | 'sync';\n /** History (default) detects duplicate fact IDs across the whole prefix. Page retention\n * bounds forward-only diagnostic memory independently of history length; it detects\n * duplicates only within each page and does not certify global identity uniqueness. */\n readonly indexRetention?: 'history' | 'page';\n /** Bounds the retained identity/offset index; exceeding it fails without advancing the cursor. */\n readonly maxIndexedFacts?: number;\n /** UTF-8 cursor bytes plus 64 charged bytes per locator/frame; not an OS heap measurement. */\n readonly maxIndexedBytes?: number;\n}\n\nexport interface JsonlJournalIncrementalPage extends JournalPage {\n readonly sessionId?: string;\n readonly throughSequence: number;\n readonly fileBytes: number;\n readonly indexedFacts: number;\n readonly indexedBytes: number;\n readonly incompleteTail: boolean;\n readonly durability: 'observed' | 'sync';\n}\n\nexport interface JsonlJournalRecoveryPage extends Omit<JsonlJournalIncrementalPage, 'facts'> {\n /** Validated lifecycle identities; payload content and artifact availability are unverified. */\n readonly facts: readonly JournalRecoveryFact[];\n}\n\n/**\n * Incremental read-only observer of an append-only file. Complete historical frames\n * must remain immutable. No writer lease, tail repair or execution recovery occurs.\n * Atomic frames may exceed the requested fact limit by at most one frame. Call close()\n * to release its bounded identity/offset index. Replacement/truncation requires a new\n * reader; an incomplete tail remains unread until it forms a complete valid frame.\n */\nexport class JsonlJournalReader {\n readonly #filePath: string;\n readonly #options: JsonlJournalReaderOptions;\n readonly #maxIndexedFacts: number;\n readonly #maxIndexedBytes: number;\n #scanned: ScannedJournal | undefined;\n #reading: Promise<JsonlJournalIncrementalPage | JsonlJournalRecoveryPage> | undefined;\n #closed = false;\n\n private constructor(filePath: string, options: JsonlJournalReaderOptions) {\n this.#filePath = resolvePath(filePath);\n this.#options = options;\n this.#maxIndexedFacts = decode(s.int({ minimum: 1 }), options.maxIndexedFacts ?? 100_000);\n this.#maxIndexedBytes = decode(\n s.int({ minimum: 1 }),\n options.maxIndexedBytes ?? 16 * 1024 * 1024\n );\n }\n\n static async open(\n filePath: string,\n options: JsonlJournalReaderOptions = {}\n ): Promise<JsonlJournalReader> {\n const handle = await openFile(filePath, options.durability === 'sync' ? 'r+' : 'r');\n await handle.close();\n return new JsonlJournalReader(filePath, options);\n }\n\n read(options: { readonly limit?: number } = {}): Promise<JsonlJournalIncrementalPage> {\n if (this.#closed) return Promise.reject(new Error('Read-only Journal reader is closed'));\n if (this.#reading !== undefined)\n return Promise.reject(\n new Error('Read-only Journal reader does not support concurrent reads')\n );\n const limit = decode(JournalReadLimitSchema, options.limit ?? JOURNAL_READ_DEFAULT_LIMIT);\n const reading = this.#read(limit).finally(() => {\n this.#reading = undefined;\n });\n this.#reading = reading;\n return reading;\n }\n\n /** Reads lifecycle identities without hydrating any externalized content. This\n * validates frames, positions and required recovery IDs, not full payload health.\n * Externalized correlation IDs are unavailable rather than guessed. The frame\n * ceiling bounds inline JSON before decoding and preserves bytes/cursor on failure. */\n readRecovery(\n options: {\n readonly limit?: number;\n readonly maxFrameBytes?: number;\n /** Aggregate UTF-8 lifecycle identities per fact; defaults to 1 KiB. */\n readonly maxIdentityBytes?: number;\n readonly signal?: AbortSignal;\n } = {}\n ): Promise<JsonlJournalRecoveryPage> {\n if (this.#closed) return Promise.reject(new Error('Read-only Journal reader is closed'));\n if (this.#reading !== undefined)\n return Promise.reject(\n new Error('Read-only Journal reader does not support concurrent reads')\n );\n const limit = decode(JournalReadLimitSchema, options.limit ?? JOURNAL_READ_DEFAULT_LIMIT);\n const maxFrameBytes = decode(\n s.int({ minimum: 1, maximum: JOURNAL_APPEND_BATCH_MAX_BYTES }),\n options.maxFrameBytes ?? JOURNAL_APPEND_BATCH_MAX_BYTES\n );\n const maxIdentityBytes = decode(\n s.int({ minimum: 1, maximum: JOURNAL_APPEND_BATCH_MAX_BYTES }),\n options.maxIdentityBytes ?? 1024\n );\n const reading = this.#readRecovery(\n limit,\n maxFrameBytes,\n maxIdentityBytes,\n options.signal\n ).finally(() => {\n this.#reading = undefined;\n });\n this.#reading = reading;\n return reading;\n }\n\n async #readRecovery(\n limit: number,\n maxFrameBytes: number,\n maxIdentityBytes: number,\n signal?: AbortSignal\n ): Promise<JsonlJournalRecoveryPage> {\n const facts: JournalRecoveryFact[] = [];\n const scanned = await scanJournal(\n this.#filePath,\n undefined,\n undefined,\n this.#options.durability === 'sync',\n {\n previous: this.#scanned,\n indexRetention: this.#options.indexRetention,\n limit,\n maxIndexedFacts: this.#maxIndexedFacts,\n maxIndexedBytes: this.#maxIndexedBytes,\n maxFrameBytes,\n maxIdentityBytes,\n signal,\n },\n (frame) => facts.push(...frame)\n );\n this.#scanned = scanned;\n return {\n facts,\n cursor: scanned.lastCursor,\n hasMore: scanned.hasMore ?? false,\n sessionId: scanned.sessionId,\n throughSequence: scanned.throughSequence,\n fileBytes: scanned.observedFileSize ?? scanned.fileSize,\n indexedFacts: scanned.factLocators.length,\n indexedBytes: scanned.indexedBytes ?? 0,\n incompleteTail: scanned.truncateAt !== undefined,\n durability: this.#options.durability ?? 'observed',\n };\n }\n\n async #read(limit: number): Promise<JsonlJournalIncrementalPage> {\n const facts: JournalFact[] = [];\n const scanned = await scanJournal(\n this.#filePath,\n this.#options.artifactStore,\n (frame) => facts.push(...frame),\n this.#options.durability === 'sync',\n {\n previous: this.#scanned,\n indexRetention: this.#options.indexRetention,\n limit,\n maxIndexedFacts: this.#maxIndexedFacts,\n maxIndexedBytes: this.#maxIndexedBytes,\n }\n );\n this.#scanned = scanned;\n return {\n facts,\n cursor: scanned.lastCursor,\n hasMore: scanned.hasMore ?? false,\n sessionId: scanned.sessionId,\n throughSequence: scanned.throughSequence,\n fileBytes: scanned.observedFileSize ?? scanned.fileSize,\n indexedFacts: scanned.factLocators.length,\n indexedBytes: scanned.indexedBytes ?? 0,\n incompleteTail: scanned.truncateAt !== undefined,\n durability: this.#options.durability ?? 'observed',\n };\n }\n\n async close(): Promise<void> {\n this.#closed = true;\n await this.#reading?.catch(() => {});\n this.#scanned = undefined;\n }\n}\n\n/**\n * File-backed, single-session Journal with durable append-before-apply semantics.\n * The store holds exclusive writer ownership from open through close. Reopen\n * validates physical frames and rebuilds an offset ledger; reads decode typed\n * payloads from their source frames.\n */\nexport class JsonlJournalStore implements JournalStore {\n readonly #observation: RuntimeObservationPort | undefined;\n readonly #filePath: string;\n readonly #readHandle: FileHandle;\n readonly #appendHandle: FileHandle;\n readonly #frames: JournalFrameLocator[];\n readonly #factLocators: JournalFactLocator[];\n readonly #cursorIndexes: Map<JournalCursor, number>;\n readonly #subscriptions = new Set<JsonlSubscription>();\n readonly #activeReads = new Set<Promise<unknown>>();\n readonly #artifactStore: ArtifactStore | undefined;\n readonly #inlineStringBytes: number;\n readonly #writerLease: JournalWriterLease;\n #sessionId: string | undefined;\n #tail: Promise<void> = Promise.resolve();\n #acceptingAppends = true;\n #failure: Error | undefined;\n #closed = false;\n #closing: Promise<void> | undefined;\n #needsSeparator: boolean;\n #fileSize: number;\n\n private constructor(\n filePath: string,\n readHandle: FileHandle,\n appendHandle: FileHandle,\n writerLease: JournalWriterLease,\n loaded: ScannedJournal,\n options: JsonlJournalStoreOptions\n ) {\n this.#observation = options.observation;\n this.#filePath = filePath;\n this.#readHandle = readHandle;\n this.#appendHandle = appendHandle;\n this.#writerLease = writerLease;\n this.#frames = loaded.frames;\n this.#factLocators = loaded.factLocators;\n this.#cursorIndexes = loaded.cursorIndexes;\n this.#sessionId = loaded.sessionId;\n this.#needsSeparator = loaded.needsSeparator;\n this.#fileSize = loaded.fileSize;\n this.#artifactStore = options.artifactStore;\n this.#inlineStringBytes = decode(\n InlineStringBytesSchema,\n options.inlineStringBytes ?? DEFAULT_INLINE_STRING_BYTES\n );\n }\n\n static async open(\n filePath: string,\n options: JsonlJournalStoreOptions = {}\n ): Promise<JsonlJournalStore> {\n const startedAt = options.observation === undefined ? undefined : performance.now();\n const startedAtUnixMs = options.observation === undefined ? undefined : Date.now();\n try {\n const store = await JsonlJournalStore.#open(filePath, options);\n if (options.observation !== undefined && startedAt !== undefined)\n observeRuntime(() =>\n options.observation?.journalReopened?.({\n sessionId: store.sessionId,\n backend: 'jsonl',\n outcome: 'opened',\n durationSeconds: (performance.now() - startedAt) / 1000,\n startedAtUnixMs,\n endedAtUnixMs: Date.now(),\n factCount: store.#factLocators.length,\n fileBytes: store.#fileSize,\n })\n );\n return store;\n } catch (cause) {\n if (options.observation !== undefined && startedAt !== undefined)\n observeRuntime(() =>\n options.observation?.journalReopened?.({\n backend: 'jsonl',\n outcome: 'failed',\n durationSeconds: (performance.now() - startedAt) / 1000,\n startedAtUnixMs,\n endedAtUnixMs: Date.now(),\n })\n );\n throw cause;\n }\n }\n\n static async #open(\n filePath: string,\n options: JsonlJournalStoreOptions\n ): Promise<JsonlJournalStore> {\n const inlineStringBytes = decode(\n InlineStringBytesSchema,\n options.inlineStringBytes ?? DEFAULT_INLINE_STRING_BYTES\n );\n if (options.inlineStringBytes !== undefined && options.artifactStore === undefined) {\n throw new TypeError('An inline string threshold requires an Artifact Store');\n }\n const normalizedOptions = { ...options, inlineStringBytes };\n const absoluteFilePath = resolvePath(filePath);\n await mkdir(dirname(absoluteFilePath), { recursive: true });\n const storagePath = await canonicalJournalPath(absoluteFilePath);\n const writerLease = await acquireJournalWriterLease(storagePath);\n try {\n await createJournalFile(storagePath);\n const loaded = await scanJournal(storagePath, options.artifactStore);\n if (loaded.truncateAt !== undefined) await truncate(storagePath, loaded.truncateAt);\n const readHandle = await openFile(storagePath, 'r');\n let appendHandle: FileHandle;\n try {\n appendHandle = await openFile(storagePath, 'a');\n } catch (cause) {\n await readHandle.close();\n throw cause;\n }\n return new JsonlJournalStore(\n storagePath,\n readHandle,\n appendHandle,\n writerLease,\n loaded,\n normalizedOptions\n );\n } catch (cause) {\n writerLease.release();\n throw cause;\n }\n }\n\n get filePath(): string {\n return this.#filePath;\n }\n\n get sessionId(): string | undefined {\n return this.#sessionId;\n }\n\n appendBatch(\n inputs: readonly [JournalWrite, ...JournalWrite[]],\n options: JournalAppendOptions\n ): Promise<void> {\n if (!this.#acceptingAppends) return Promise.reject(this.#unavailableError());\n if (inputs.some(({ fact }) => isDurableSubmissionFactKind(fact.kind)))\n return Promise.reject(new Error('Durable Submissions require a Unit store'));\n return this.#serialize(async () => {\n const startedAt = this.#observation === undefined ? undefined : performance.now();\n const startedAtUnixMs = this.#observation === undefined ? undefined : Date.now();\n let bytes: number | undefined;\n try {\n this.#assertOperational();\n if (inputs.length > JOURNAL_APPEND_BATCH_MAX_FACTS) {\n throw new RangeError(`Journal batch exceeds ${JOURNAL_APPEND_BATCH_MAX_FACTS} facts`);\n }\n const first = inputs[0].fact;\n this.#assertSession(first.sessionId);\n if (options.expectedSequence !== this.#factLocators.length) {\n throw new JournalConflictError(options.expectedSequence, this.#factLocators.length);\n }\n for (const [index, { fact }] of inputs.entries()) {\n if (fact.sequence !== this.#factLocators.length + index + 1) {\n throw new JournalConflictError(fact.sequence - index - 1, this.#factLocators.length);\n }\n }\n const serializeFrame = (facts: readonly string[]) =>\n `{\"storageVersion\":4,\"facts\":[${facts.join(',')}]}`;\n let serialized = serializeFrame(inputs.map(({ json }) => json));\n const artifacts = this.#artifactStore;\n if (artifacts !== undefined) {\n const payloads = Buffer.byteLength(serialized) > JOURNAL_APPEND_BATCH_MAX_BYTES;\n const encode = (wholePayload: boolean) =>\n Promise.all(\n inputs.map(async ({ json }) => {\n if (!wholePayload && json.length < this.#inlineStringBytes / 3) return json;\n const value = decode(s.map(JsonValueSchema), JSON.parse(json));\n if (wholePayload)\n return JSON.stringify(await encodeJournalPayload(value, artifacts));\n const encoded = encodeJournalFact(value, artifacts, this.#inlineStringBytes);\n return isPromise(encoded) ? JSON.stringify(await encoded) : json;\n })\n );\n serialized = serializeFrame(await encode(payloads));\n if (!payloads && Buffer.byteLength(serialized) > JOURNAL_APPEND_BATCH_MAX_BYTES)\n serialized = serializeFrame(await encode(true));\n }\n const serializedBytes = Buffer.byteLength(serialized);\n bytes = serializedBytes;\n if (serializedBytes > JOURNAL_APPEND_BATCH_MAX_BYTES) {\n throw new RangeError(\n `Journal frame is ${serializedBytes} bytes; maximum is ${JOURNAL_APPEND_BATCH_MAX_BYTES}`\n );\n }\n this.#bindSession(first.sessionId);\n const prefix = this.#needsSeparator ? '\\n' : '';\n const frameOffset = this.#fileSize + Buffer.byteLength(prefix);\n const encodedFrame = `${prefix}${serialized}\\n`;\n try {\n await this.#appendHandle.writeFile(encodedFrame, 'utf8');\n await this.#appendHandle.sync();\n } catch (cause) {\n throw this.#fault(isError(cause) ? cause : new Error(String(cause)));\n }\n this.#needsSeparator = false;\n const frameIndex = this.#frames.length;\n const firstFactIndex = this.#factLocators.length;\n for (const [factIndex, { fact }] of inputs.entries()) {\n this.#cursorIndexes.set(fact.cursor, this.#factLocators.length);\n this.#factLocators.push({ cursor: fact.cursor, frameIndex, factIndex });\n }\n this.#frames.push({\n offset: frameOffset,\n length: serializedBytes,\n lineNumber: frameIndex + 1,\n firstFactIndex,\n factCount: inputs.length,\n });\n this.#fileSize += Buffer.byteLength(encodedFrame);\n for (const subscription of this.#subscriptions) subscription.notify();\n if (this.#observation !== undefined && startedAt !== undefined)\n observeRuntime(() =>\n this.#observation?.journalBatchCompleted?.({\n sessionId: first.sessionId,\n backend: 'jsonl',\n outcome: 'committed',\n durationSeconds: (performance.now() - startedAt) / 1000,\n startedAtUnixMs,\n endedAtUnixMs: Date.now(),\n factCount: inputs.length,\n bytes,\n throughSequence: this.#factLocators.length,\n })\n );\n } catch (cause) {\n if (this.#observation !== undefined && startedAt !== undefined)\n observeRuntime(() =>\n this.#observation?.journalBatchCompleted?.({\n sessionId: inputs[0].fact.sessionId,\n backend: 'jsonl',\n outcome: 'failed',\n durationSeconds: (performance.now() - startedAt) / 1000,\n startedAtUnixMs,\n endedAtUnixMs: Date.now(),\n factCount: inputs.length,\n bytes,\n })\n );\n throw cause;\n }\n });\n }\n\n append(input: JournalWrite, options: JournalAppendOptions): Promise<void> {\n return this.appendBatch([input], options);\n }\n\n async read(sessionId: string, options: JournalReadOptions = {}): Promise<JournalPage> {\n this.#assertOperational();\n this.#assertSession(sessionId);\n const limit = decode(JournalReadLimitSchema, options.limit ?? JOURNAL_READ_DEFAULT_LIMIT);\n const start = this.#indexAfter(options.after);\n const facts = await this.#trackRead(this.#readFacts(start, limit));\n const cursor = facts.at(-1)?.cursor ?? options.after;\n const page = { facts, hasMore: start + facts.length < this.#factLocators.length };\n return cursor === undefined ? page : { ...page, cursor };\n }\n\n subscribe(sessionId: string, options: JournalSubscriptionOptions = {}): JournalSubscription {\n this.#assertOperational();\n this.#bindSession(sessionId);\n const start = this.#indexAfter(options.after);\n let subscription: JsonlSubscription;\n subscription = new JsonlSubscription(\n () => this.#factLocators.length,\n async (factIndex) => await this.#trackRead(this.#decodeFrameAt(factIndex)),\n start,\n () => {\n this.#subscriptions.delete(subscription);\n }\n );\n this.#subscriptions.add(subscription);\n return subscription;\n }\n\n close(): Promise<void> {\n this.#closing ??= this.#close();\n return this.#closing;\n }\n\n async #close(): Promise<void> {\n this.#acceptingAppends = false;\n const failures: unknown[] = [];\n try {\n const tailResult = await Promise.allSettled([this.#tail]);\n if (tailResult[0]?.status === 'rejected') failures.push(tailResult[0].reason);\n this.#closed = true;\n for (const subscription of this.#subscriptions) {\n try {\n subscription.close();\n } catch (cause) {\n failures.push(cause);\n }\n }\n const readResults = await Promise.allSettled([...this.#activeReads]);\n for (const result of readResults) {\n if (result.status === 'rejected') failures.push(result.reason);\n }\n const handleResults = await Promise.allSettled([\n this.#readHandle.close(),\n this.#appendHandle.close(),\n ]);\n for (const result of handleResults) {\n if (result.status === 'rejected') failures.push(result.reason);\n }\n } finally {\n try {\n this.#writerLease.release();\n } catch (cause) {\n failures.push(cause);\n }\n }\n if (failures.length === 1) throw failures[0];\n if (failures.length > 1) throw new AggregateError(failures, 'Journal close failed');\n }\n\n async #readFacts(start: number, limit: number): Promise<readonly JournalFact[]> {\n const facts: JournalFact[] = [];\n const end = Math.min(start + limit, this.#factLocators.length);\n let index = start;\n while (index < end) {\n const frame = await this.#decodeFrameAt(index);\n const localStart = index - frame.firstFactIndex;\n const available = Math.min(frame.facts.length - localStart, end - index);\n if (available <= 0)\n throw new JournalCorruptionError('Journal index points outside its frame');\n facts.push(...frame.facts.slice(localStart, localStart + available));\n index += available;\n }\n return facts;\n }\n\n async #decodeFrameAt(factIndex: number): Promise<DecodedJournalFrame> {\n const factLocator = this.#factLocators[factIndex];\n if (factLocator === undefined) {\n throw new JournalCorruptionError('Journal fact index is outside the durable ledger');\n }\n const frame = this.#frames[factLocator.frameIndex];\n if (frame === undefined) {\n throw new JournalCorruptionError('Journal frame index is outside the durable ledger');\n }\n const buffer = Buffer.allocUnsafe(frame.length);\n let bytesRead = 0;\n while (bytesRead < buffer.byteLength) {\n const result = await this.#readHandle.read(\n buffer,\n bytesRead,\n buffer.byteLength - bytesRead,\n frame.offset + bytesRead\n );\n if (result.bytesRead === 0) {\n throw new JournalCorruptionError(`Journal frame ${frame.lineNumber} ended unexpectedly`);\n }\n bytesRead += result.bytesRead;\n }\n let facts: readonly JournalFact[];\n try {\n facts = await parseLine(buffer.toString('utf8'), frame.lineNumber, this.#artifactStore);\n } catch (cause) {\n if (cause instanceof JournalLineSyntaxError) {\n throw new JournalCorruptionError(cause.message, { cause: cause.cause });\n }\n throw cause;\n }\n if (facts.length !== frame.factCount) {\n throw new JournalCorruptionError(`Journal frame ${frame.lineNumber} fact count changed`);\n }\n for (const [index, fact] of facts.entries()) {\n const locator = this.#factLocators[frame.firstFactIndex + index];\n if (locator === undefined || fact.cursor !== locator.cursor) {\n throw new JournalCorruptionError(`Journal frame ${frame.lineNumber} identity changed`);\n }\n }\n return { firstFactIndex: frame.firstFactIndex, facts };\n }\n\n #trackRead<Result>(operation: Promise<Result>): Promise<Result> {\n this.#activeReads.add(operation);\n operation.then(\n () => this.#activeReads.delete(operation),\n () => this.#activeReads.delete(operation)\n );\n return operation;\n }\n\n #serialize<Result>(operation: () => Promise<Result>): Promise<Result> {\n const result = this.#tail.then(operation);\n this.#tail = result.then(\n () => undefined,\n () => undefined\n );\n return result;\n }\n\n #bindSession(sessionId: string): void {\n this.#assertOperational();\n if (this.#sessionId === undefined) this.#sessionId = sessionId;\n else this.#assertSession(sessionId);\n }\n\n #assertSession(sessionId: string): void {\n if (this.#sessionId === undefined) return;\n if (this.#sessionId !== sessionId) {\n throw new TypeError('Journal session does not belong to this JSONL file');\n }\n }\n\n #assertOperational(): void {\n if (this.#closed) throw new Error('Journal store is closed');\n if (this.#failure !== undefined) throw this.#unavailableError();\n }\n\n #unavailableError(): Error {\n if (this.#failure !== undefined) {\n return new Error('Journal store is faulted; close and reopen it before continuing', {\n cause: this.#failure,\n });\n }\n return new Error('Journal store is closed');\n }\n\n #fault(cause: Error): Error {\n const failure = new JournalStoreFaultError(\n 'Journal write failed with an unknown durable outcome; close and reopen the Store',\n { cause }\n );\n this.#failure = failure;\n this.#acceptingAppends = false;\n for (const subscription of this.#subscriptions) subscription.fail(failure);\n return failure;\n }\n\n #indexAfter(cursor: JournalCursor | undefined): number {\n if (cursor === undefined) return 0;\n const index = this.#cursorIndexes.get(cursor);\n if (index === undefined) throw new JournalCursorGapError(cursor);\n return index + 1;\n }\n}\n","import type { JournalFact } from '../contracts.js';\nimport * as s from '@earendil-works/pi-schema';\nimport { compile, decode, decodeWith } from '@sorbetai/schema';\nimport type { ArtifactStore } from '@sorbetai/artifacts';\nimport { isEqual, isPromise, isString } from 'es-toolkit';\n\nimport { JOURNAL_APPEND_BATCH_MAX_BYTES, JOURNAL_APPEND_BATCH_MAX_FACTS } from '../contracts.js';\nimport {\n decodeJournalEnvelope,\n encodeJournalFact,\n encodeJournalPayload,\n PersistedJournalEnvelopeSchema,\n type ExternalizedStringReuse,\n} from '../offloaded-fact.js';\nimport { decodeJournalRecoveryFact } from '../recovery-fact.js';\nimport { JsonValueSchema, utf8ByteLength, type JsonValue } from '../../serialization.js';\nimport {\n UnitFactSchema,\n UnitStoreError,\n type UnitFact,\n type UnitRecord,\n type UnitInspectionPage,\n} from './contracts.js';\nimport type { UnitStorageWrite } from './opened.js';\nimport type { UnitTransactions } from './transactions.js';\n\n/**\n * Measured on a 24 MiB Unit: 8 KiB already deduplicates Tool previews, and 4 KiB additionally\n * captures the state messages repeated by every model request. Halving again gains under 2%\n * while roughly doubling the Artifact count, so this is the knee rather than the extreme.\n */\nconst DEFAULT_UNIT_INLINE_STRING_BYTES = 4 * 1024;\nconst InlineStringBytesSchema = s.int({ minimum: 1 });\nconst Utf8Decoder = new TextDecoder('utf-8', { fatal: true });\n\nconst FrameIdentity = {\n format: s.lit('sorbet.unit'),\n unitId: s.str({ minLength: 1 }),\n epochId: s.str({ minLength: 1 }),\n commitId: s.str({ minLength: 1 }),\n firstSequence: s.int({ minimum: 1 }),\n};\n/**\n * JSON.parse output is a JsonValue by construction. Walking every payload again cost more\n * than parsing it, so frames check their structure and leave fact content to the fact owner.\n */\nconst ParsedJson: s.Schema<JsonValue> = {};\nconst EncodedEntrySchema = s.obj(\n {\n scope: s.union([s.lit('session'), s.lit('unit')]),\n fact: ParsedJson,\n },\n { open: true }\n);\nconst LogicalFrameProperties = {\n ...FrameIdentity,\n storageVersion: s.lit(1),\n entries: s.arr(EncodedEntrySchema, { minItems: 1 }),\n};\nconst LogicalFrameSchema = s.obj(LogicalFrameProperties, { open: false });\nconst InlineFrameSchema = s.obj(\n {\n ...LogicalFrameProperties,\n entries: s.arr(EncodedEntrySchema, {\n minItems: 1,\n maxItems: JOURNAL_APPEND_BATCH_MAX_FACTS,\n }),\n },\n { open: false }\n);\nconst ReferenceFrameSchema = s.obj(\n {\n ...FrameIdentity,\n storageVersion: s.lit(2),\n transaction: s.obj(\n {\n id: s.str({\n pattern: '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$',\n }),\n count: s.int({ minimum: 1 }),\n byteLength: s.int({ minimum: 1 }),\n },\n { open: false }\n ),\n },\n { open: false }\n);\nconst FrameValidator = compile(s.union([InlineFrameSchema, ReferenceFrameSchema]));\nconst LogicalFrameValidator = compile(LogicalFrameSchema);\n\n/** Version 1 remains readable; only version 2 can refer to an oversized atomic batch. */\nfunction readFrame(input: string, transactions: UnitTransactions, inspection = false) {\n try {\n const frame = decodeWith(FrameValidator, JSON.parse(input));\n if (frame.storageVersion === 1) return frame;\n return readReferencedFrame(frame, transactions, inspection);\n } catch (cause) {\n if (cause instanceof UnitStoreError) throw cause;\n throw new UnitStoreError('unit_corrupt', 'Cannot decode a unit frame', { cause });\n }\n}\n\nasync function readReferencedFrame(\n frame: s.Static<typeof ReferenceFrameSchema>,\n transactions: UnitTransactions,\n inspection: boolean\n) {\n try {\n const { transaction, storageVersion: _version, ...identity } = frame;\n if (inspection && transaction.byteLength > JOURNAL_APPEND_BATCH_MAX_BYTES)\n throw new UnitStoreError(\n 'unit_inspection_capacity',\n 'Transaction exceeds the diagnostic decoding budget'\n );\n const text = await transactions.read(\n transaction.id,\n inspection ? JOURNAL_APPEND_BATCH_MAX_BYTES : undefined\n );\n const {\n entries,\n storageVersion: _bodyVersion,\n ...bodyIdentity\n } = decodeWith(LogicalFrameValidator, JSON.parse(text));\n if (\n utf8ByteLength(text) !== transaction.byteLength ||\n entries.length !== transaction.count ||\n transaction.id !== identity.commitId ||\n !isEqual(identity, bodyIdentity)\n )\n throw new UnitStoreError('unit_corrupt', 'Transaction does not match its committed marker');\n return { ...identity, storageVersion: 1 as const, entries };\n } catch (cause) {\n if (cause instanceof UnitStoreError) throw cause;\n throw new UnitStoreError('unit_corrupt', 'Cannot read a committed Unit transaction', { cause });\n }\n}\nconst UnitFactValidator = compile(UnitFactSchema);\n/**\n * The staging writer validated every fact before its commit, so a complete committed frame\n * is trusted on read. Rechecking each fact against the full fact unions on every reopen\n * doubled decode time without finding anything the framing checks miss.\n */\nconst CommittedSessionFact: s.Schema<JournalFact> = {};\nconst CommittedUnitFact: s.Schema<UnitFact> = {};\nconst FactObjectValidator = compile(s.map(JsonValueSchema));\nconst PersistedEnvelopeValidator = compile(PersistedJournalEnvelopeSchema);\nconst UnitFactKindValidator = compile(s.obj({ kind: s.str() }, { open: true }));\nconst SessionHeader = s.obj({ sessionId: s.str() }, { open: true });\nconst SessionHeaderValidator = compile(SessionHeader);\n\nexport async function decodeUnitInspectionFrame(\n input: Uint8Array,\n artifacts: ArtifactStore | undefined,\n transactions: UnitTransactions,\n sessionId?: string,\n diagnostic = true,\n unitKinds?: ReadonlySet<string>\n) {\n const frame = await readFrame(Utf8Decoder.decode(input), transactions, diagnostic);\n const unitFacts: UnitInspectionPage['unitFacts'][number][] = [];\n const sessionFacts: UnitInspectionPage['sessionFacts'][number][] = [];\n for (const entry of frame.entries) {\n const envelope = PersistedEnvelopeValidator.check(entry.fact) ? entry.fact : undefined;\n const raw = envelope === undefined ? entry.fact : envelope.fact;\n if (entry.scope === 'unit') {\n if (unitKinds !== undefined) {\n if (!UnitFactKindValidator.check(raw))\n throw new UnitStoreError('unit_corrupt', 'Unit fact has no kind');\n if (!unitKinds.has(raw.kind)) continue;\n }\n const fact = envelope === undefined ? raw : await decodeJournalEnvelope(envelope, artifacts);\n unitFacts.push(UnitFactValidator.check(fact) ? fact : decodeWith(UnitFactValidator, fact));\n } else if (sessionId !== undefined) {\n if (!SessionHeaderValidator.check(raw))\n throw new UnitStoreError('unit_corrupt', 'Unit fact has no Session identity');\n if (raw.sessionId !== sessionId) continue;\n const fact = decodeJournalRecoveryFact(raw);\n sessionFacts.push(fact);\n }\n }\n return {\n unitId: frame.unitId,\n firstSequence: frame.firstSequence,\n count: frame.entries.length,\n unitFacts,\n sessionFacts,\n };\n}\n\nexport interface UnitEncodingOptions {\n readonly artifactStore?: ArtifactStore;\n readonly inlineStringBytes?: number;\n readonly stringReuse?: ExternalizedStringReuse;\n}\n\nexport async function encodeUnitFrame(\n writes: readonly UnitStorageWrite[],\n options: UnitEncodingOptions,\n transactions: UnitTransactions\n): Promise<string> {\n const first = writes[0]?.record;\n if (first === undefined) throw new RangeError('Unit batches require at least one fact');\n const header = JSON.stringify({\n format: 'sorbet.unit',\n storageVersion: 1,\n unitId: first.unitId,\n epochId: first.epochId,\n commitId: first.commitId,\n firstSequence: first.unitSequence,\n });\n const frame = (entries: readonly string[]) =>\n `${header.slice(0, -1)},\"entries\":[${entries.join(',')}]}`;\n let json = frame(\n writes.map(\n ({ record, json: fact }) => `{\"scope\":${JSON.stringify(record.entry.scope)},\"fact\":${fact}}`\n )\n );\n const store = options.artifactStore;\n if (store !== undefined) {\n const threshold = decode(\n InlineStringBytesSchema,\n options.inlineStringBytes ?? DEFAULT_UNIT_INLINE_STRING_BYTES\n );\n // Typed facts can contain optional undefined fields; offload traverses their JSON form.\n const entries = writes.map(({ record, json: fact }) => ({\n scope: record.entry.scope,\n fact: decodeWith(FactObjectValidator, JSON.parse(fact)),\n }));\n const encode = async (payload: boolean) => {\n const offloaded = await Promise.all(\n entries.map(async ({ scope, fact }) => {\n const encoded = await (payload\n ? encodeJournalPayload(fact, store)\n : encodeJournalFact(fact, store, threshold, options.stringReuse));\n return JSON.stringify({ scope, fact: encoded });\n })\n );\n return frame(offloaded);\n };\n json = await encode(utf8ByteLength(json) > JOURNAL_APPEND_BATCH_MAX_BYTES);\n if (utf8ByteLength(json) > JOURNAL_APPEND_BATCH_MAX_BYTES) json = await encode(true);\n }\n if (\n writes.length <= JOURNAL_APPEND_BATCH_MAX_FACTS &&\n utf8ByteLength(json) <= JOURNAL_APPEND_BATCH_MAX_BYTES\n )\n return json;\n const reference = decode(ReferenceFrameSchema, {\n format: 'sorbet.unit',\n storageVersion: 2,\n unitId: first.unitId,\n epochId: first.epochId,\n commitId: first.commitId,\n firstSequence: first.unitSequence,\n transaction: { id: first.commitId, count: writes.length, byteLength: utf8ByteLength(json) },\n });\n const committed = JSON.stringify(reference);\n if (utf8ByteLength(committed) > JOURNAL_APPEND_BATCH_MAX_BYTES)\n throw new RangeError('Unit commit identity exceeds the physical frame byte limit');\n await transactions.write(reference.transaction.id, json);\n return committed;\n}\n\n/** The unit format is deliberately independent of the single-Session JSONL v4 decoder. */\nexport function decodeUnitFrame(\n input: string | Uint8Array,\n artifacts: ArtifactStore | undefined,\n transactions: UnitTransactions\n): readonly UnitRecord[] | Promise<readonly UnitRecord[]> {\n try {\n const json = isString(input) ? input : Utf8Decoder.decode(input);\n const frame = readFrame(json, transactions);\n const records = isPromise(frame)\n ? frame.then((decoded) => decodeFrameRecords(decoded, artifacts))\n : decodeFrameRecords(frame, artifacts);\n return isPromise(records) ? records.catch(failFrameDecode) : records;\n } catch (cause) {\n return failFrameDecode(cause);\n }\n}\n\nfunction decodeFrameRecords(\n frame: s.Static<typeof LogicalFrameSchema>,\n artifacts: ArtifactStore | undefined\n): readonly UnitRecord[] | Promise<readonly UnitRecord[]> {\n const records: UnitRecord[] = [];\n const pending: Promise<void>[] = [];\n for (const [index, entry] of frame.entries.entries()) {\n const decoded = decodeJournalEnvelope(entry.fact, artifacts);\n const store = (fact: JsonValue) => {\n records[index] = {\n unitId: frame.unitId,\n epochId: frame.epochId,\n commitId: frame.commitId,\n unitSequence: frame.firstSequence + index,\n entry:\n entry.scope === 'session'\n ? { scope: entry.scope, fact: decode(CommittedSessionFact, fact) }\n : { scope: entry.scope, fact: decode(CommittedUnitFact, fact) },\n };\n };\n if (isPromise(decoded)) pending.push(decoded.then(store));\n else store(decoded);\n }\n return pending.length === 0 ? records : Promise.all(pending).then(() => records);\n}\n\n// Decoding is an external byte boundary; preserve its stable corruption error.\n// ast-grep-ignore: no-unknown-parameter\nfunction failFrameDecode(cause: unknown): never {\n throw new UnitStoreError(\n 'unit_corrupt',\n 'Cannot decode a complete unit frame or its referenced payload',\n { cause }\n );\n}\n","import { JOURNAL_APPEND_BATCH_MAX_BYTES } from '../contracts.js';\nimport { UnitStoreError } from './contracts.js';\n\n/**\n * The committed byte prefix of one Unit. A plain Journal reads it from disk; a sealed Unit\n * serves the same bytes from its decompressed archive so reading never restores the file.\n */\nexport interface UnitScanSource {\n stat(): Promise<{ size: number }>;\n read(\n buffer: Buffer,\n offset: number,\n length: number,\n position: number\n ): Promise<{ bytesRead: number }>;\n}\n\n/**\n * Reopen reads the whole Journal, so chunks are large: each read is a thread-pool round trip,\n * and 64 KiB chunks left the open path mostly waiting on them.\n */\nconst SCAN_CHUNK_BYTES = 4 * 1024 * 1024;\n\n/** Pins the observed file length. The final unterminated bytes are evidence, never a commit. */\nexport async function* scanUnitFrames(file: UnitScanSource, signal?: AbortSignal) {\n const { size } = await file.stat();\n let pending: Buffer[] = [];\n let pendingLength = 0;\n let position = 0;\n let offset = 0;\n while (position < size) {\n signal?.throwIfAborted();\n // A fresh chunk per read: yielded frames are views into it and must outlive the next read.\n const buffer = Buffer.allocUnsafe(Math.min(SCAN_CHUNK_BYTES, size - position));\n const { bytesRead } = await file.read(buffer, 0, buffer.length, position);\n if (bytesRead === 0)\n throw new UnitStoreError('unit_corrupt', 'Unit file was truncated during scan');\n position += bytesRead;\n let start = 0;\n let newline = buffer.indexOf(10, start);\n while (newline !== -1 && newline < bytesRead) {\n const length = pendingLength + newline - start;\n if (length > JOURNAL_APPEND_BATCH_MAX_BYTES)\n throw new UnitStoreError('unit_corrupt', 'Unit frame exceeds its format byte limit');\n const chunk = buffer.subarray(start, newline);\n const bytes = pendingLength === 0 ? chunk : Buffer.concat([...pending, chunk], length);\n yield { offset, bytes, complete: true };\n offset += length + 1;\n pending = [];\n pendingLength = 0;\n start = newline + 1;\n newline = buffer.indexOf(10, start);\n }\n if (start < bytesRead) {\n pendingLength += bytesRead - start;\n if (pendingLength > JOURNAL_APPEND_BATCH_MAX_BYTES)\n throw new UnitStoreError('unit_corrupt', 'Unit frame exceeds its format byte limit');\n pending.push(buffer.subarray(start, bytesRead));\n }\n }\n if (pendingLength > 0)\n yield { offset, bytes: Buffer.concat(pending, pendingLength), complete: false };\n}\n","import { mkdir, open } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\n\nimport { syncDirectory } from '../journal-file.js';\nimport { UnitStoreError } from './contracts.js';\n\n/** Published before the main marker; unreferenced files are never replayed. */\nexport interface UnitTransactions {\n write(id: string, text: string): Promise<void>;\n read(id: string, maxBytes?: number): Promise<string>;\n}\n\nexport class FileUnitTransactions implements UnitTransactions {\n readonly #directory: string;\n\n constructor(filePath: string) {\n this.#directory = `${filePath}.transactions`;\n }\n\n async write(id: string, text: string): Promise<void> {\n await mkdir(this.#directory, { recursive: true, mode: 0o700 });\n const file = await open(join(this.#directory, `${id}.json`), 'wx', 0o600);\n try {\n await file.writeFile(text, 'utf8');\n await file.sync();\n } finally {\n await file.close();\n }\n await syncDirectory(this.#directory);\n await syncDirectory(dirname(this.#directory));\n }\n\n async read(id: string, maxBytes?: number): Promise<string> {\n const file = await open(join(this.#directory, `${id}.json`), 'r');\n try {\n if (maxBytes !== undefined && (await file.stat()).size > maxBytes)\n throw new UnitStoreError(\n 'unit_inspection_capacity',\n 'Transaction exceeds the diagnostic decoding budget'\n );\n return new TextDecoder('utf-8', { fatal: true }).decode(await file.readFile());\n } finally {\n await file.close();\n }\n }\n}\n","import * as s from '@earendil-works/pi-schema';\nimport { decode } from '@sorbetai/schema';\nimport { open, readFile, rename, rm, stat } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { brotliCompress, brotliDecompress, constants } from 'node:zlib';\nimport { promisify } from 'node:util';\n\nimport { syncDirectory } from '../journal-file.js';\nimport { acquireJournalWriterLease, JournalWriterBusyError } from '../writer-lease.js';\nimport { UnitStoreError } from './contracts.js';\n\nconst compress = promisify(brotliCompress);\nconst decompress = promisify(brotliDecompress);\n\nconst SealedUnitManifestSchema = s.obj(\n {\n format: s.lit('sorbet.unit.sealed'),\n storageVersion: s.lit(1),\n codec: s.lit('brotli'),\n journalBytes: s.int({ minimum: 1 }),\n sealedBytes: s.int({ minimum: 1 }),\n sealedAt: s.str({ minLength: 1 }),\n },\n { open: false }\n);\n\nexport type SealedUnitManifest = s.Static<typeof SealedUnitManifestSchema>;\n\n/**\n * A sealed Unit keeps the complete committed Journal in one irreversible encoding. Nothing is\n * dropped: sealing compresses the exact committed bytes, and unsealing restores them byte for\n * byte. `unit.jsonl` stays authoritative while it exists, so an interrupted seal is repaired by\n * discarding the incomplete seal rather than by trusting it.\n */\nexport interface SealedUnitLayout {\n readonly journalPath: string;\n readonly sealedPath: string;\n readonly manifestPath: string;\n}\n\nexport function sealedUnitLayout(journalPath: string): SealedUnitLayout {\n return {\n journalPath,\n sealedPath: `${journalPath}.sealed`,\n manifestPath: `${journalPath}.sealed.json`,\n };\n}\n\nexport async function readSealedUnitManifest(\n journalPath: string\n): Promise<SealedUnitManifest | undefined> {\n const { manifestPath } = sealedUnitLayout(journalPath);\n const text = await readFile(manifestPath, 'utf8').catch(() => undefined);\n if (text === undefined) return undefined;\n try {\n return decode(SealedUnitManifestSchema, JSON.parse(text));\n } catch (cause) {\n throw new UnitStoreError('unit_corrupt', 'Sealed Unit manifest is invalid', { cause });\n }\n}\n\nexport async function isUnitSealed(journalPath: string): Promise<boolean> {\n const manifest = await readSealedUnitManifest(journalPath);\n if (manifest === undefined) return false;\n return (await exists(journalPath)) === false;\n}\n\n/**\n * Reads the committed bytes of a sealed Unit without restoring the plain Journal. Readers use\n * this so an archived Unit stays compressed until something actually needs to append to it.\n */\nexport async function readSealedUnitJournal(\n journalPath: string\n): Promise<{ readonly bytes: Buffer; readonly manifest: SealedUnitManifest } | undefined> {\n const manifest = await readSealedUnitManifest(journalPath);\n if (manifest === undefined) return undefined;\n if (await exists(journalPath)) return undefined;\n const { sealedPath } = sealedUnitLayout(journalPath);\n const sealed = await readFile(sealedPath).catch(() => undefined);\n if (sealed === undefined)\n throw new UnitStoreError('unit_corrupt', 'Sealed Unit payload is missing');\n const bytes = await decompress(sealed);\n if (bytes.byteLength !== manifest.journalBytes)\n throw new UnitStoreError('unit_corrupt', 'Sealed Unit payload does not match its manifest');\n return { bytes, manifest };\n}\n\nexport interface SealUnitResult {\n readonly manifest: SealedUnitManifest;\n readonly journalBytes: number;\n readonly sealedBytes: number;\n}\n\n/** Compresses a closed Unit's committed Journal and verifies the result before replacing it. */\nexport async function sealUnit(\n journalPath: string,\n options: { readonly now?: () => Date } = {}\n): Promise<SealUnitResult> {\n const { sealedPath, manifestPath } = sealedUnitLayout(journalPath);\n // The lease, not the mutex file, decides whether a writer is live.\n const lease = await acquireJournalWriterLease(journalPath).catch((cause: unknown) => {\n if (cause instanceof JournalWriterBusyError)\n throw new UnitStoreError('unit_locked', 'A sealed Unit must not have a live writer', {\n cause,\n });\n throw cause;\n });\n try {\n return await sealWithLease(journalPath, sealedPath, manifestPath, options);\n } finally {\n lease.release();\n }\n}\n\nasync function sealWithLease(\n journalPath: string,\n sealedPath: string,\n manifestPath: string,\n options: { readonly now?: () => Date }\n): Promise<SealUnitResult> {\n if ((await exists(journalPath)) === false) {\n const existing = await readSealedUnitManifest(journalPath);\n if (existing === undefined)\n throw new UnitStoreError('unit_corrupt', 'Unit Journal is missing and no seal records it');\n return {\n manifest: existing,\n journalBytes: existing.journalBytes,\n sealedBytes: existing.sealedBytes,\n };\n }\n\n const journal = await readFile(journalPath);\n if (journal.byteLength === 0)\n throw new UnitStoreError('unit_corrupt', 'An empty Unit Journal cannot be sealed');\n const sealed = await compress(journal, {\n params: {\n [constants.BROTLI_PARAM_QUALITY]: 5,\n [constants.BROTLI_PARAM_SIZE_HINT]: journal.byteLength,\n },\n });\n\n await writeAtomically(sealedPath, sealed);\n const restored = await decompress(await readFile(sealedPath));\n if (restored.equals(journal) === false) {\n await rm(sealedPath, { force: true });\n throw new UnitStoreError('unit_corrupt', 'Sealed Unit does not reproduce the Journal');\n }\n\n const manifest = decode(SealedUnitManifestSchema, {\n format: 'sorbet.unit.sealed',\n storageVersion: 1,\n codec: 'brotli',\n journalBytes: journal.byteLength,\n sealedBytes: sealed.byteLength,\n sealedAt: (options.now?.() ?? new Date()).toISOString(),\n });\n // The manifest is durable before the source disappears, so a crash at any point either\n // leaves the Journal authoritative or leaves a verified seal recorded in the manifest.\n await writeAtomically(manifestPath, Buffer.from(`${JSON.stringify(manifest)}\\n`, 'utf8'));\n await rm(journalPath);\n await syncDirectory(dirname(journalPath));\n return { manifest, journalBytes: journal.byteLength, sealedBytes: sealed.byteLength };\n}\n\n/** Restores a sealed Unit to its exact committed bytes. A present Journal wins over any seal. */\nexport async function unsealUnit(\n journalPath: string,\n options: { readonly discardJournal?: boolean } = {}\n): Promise<{ readonly restored: boolean }> {\n const { sealedPath, manifestPath } = sealedUnitLayout(journalPath);\n const manifest = await readSealedUnitManifest(journalPath);\n if (await exists(journalPath)) {\n if (options.discardJournal === true) await rm(journalPath);\n else {\n if (manifest !== undefined) await discardSeal(sealedPath, manifestPath);\n return { restored: false };\n }\n }\n if (manifest === undefined) {\n // A Unit that has never been written has neither Journal nor seal.\n if ((await exists(journalPath)) === false) return { restored: false };\n throw new UnitStoreError('unit_corrupt', 'Sealed Unit Journal is missing and unrecorded');\n }\n\n const sealed = await readSealedUnitJournal(journalPath).catch(async (cause: unknown) => {\n await rm(sealedPath, { force: true });\n await rm(manifestPath, { force: true });\n throw cause;\n });\n if (sealed === undefined)\n throw new UnitStoreError('unit_corrupt', 'Sealed Unit payload is missing');\n await writeAtomically(journalPath, sealed.bytes);\n await discardSeal(sealedPath, manifestPath);\n return { restored: true };\n}\n\n/** Removes a seal that cannot be trusted because the Journal it describes is still present. */\nexport async function discardIncompleteSeal(journalPath: string): Promise<void> {\n const { sealedPath, manifestPath } = sealedUnitLayout(journalPath);\n if (await exists(journalPath)) await discardSeal(sealedPath, manifestPath);\n}\n\nasync function discardSeal(sealedPath: string, manifestPath: string): Promise<void> {\n await rm(sealedPath, { force: true });\n await rm(manifestPath, { force: true });\n await syncDirectory(dirname(manifestPath));\n}\n\nasync function writeAtomically(path: string, bytes: Buffer): Promise<void> {\n const staging = `${path}.tmp`;\n const handle = await open(staging, 'w', 0o600);\n try {\n await handle.writeFile(bytes);\n await handle.sync();\n } finally {\n await handle.close();\n }\n await rename(staging, path);\n await syncDirectory(dirname(path));\n}\n\nasync function exists(path: string): Promise<boolean> {\n return await stat(path).then(\n () => true,\n () => false\n );\n}\n","import { isPromise } from 'es-toolkit';\nimport { mkdir, open, type FileHandle } from 'node:fs/promises';\nimport { dirname, resolve } from 'node:path';\nimport type { ArtifactStore } from '@sorbetai/artifacts';\nimport ensureError from 'ensure-error';\n\nimport {\n acquireJournalWriterLease,\n JournalWriterBusyError,\n type JournalWriterLease,\n} from '../writer-lease.js';\nimport { canonicalJournalPath, createJournalFile, syncDirectory } from '../journal-file.js';\nimport {\n UnitStoreError,\n type OpenedUnitStore,\n type UnitCommitOutcome,\n type UnitPage,\n type UnitReader,\n type UnitReadOptions,\n type UnitRecord,\n type UnitInspectionPage,\n type UnitFact,\n type UnitOpenOptions,\n type UnitStore,\n} from './contracts.js';\nimport {\n decodeUnitFrame,\n decodeUnitInspectionFrame,\n encodeUnitFrame,\n type UnitEncodingOptions,\n} from './frame.js';\nimport { scanUnitFrames, type UnitScanSource } from './scan.js';\nimport { FileUnitTransactions, type UnitTransactions } from './transactions.js';\nimport { ExternalizedStringReuse } from '../offloaded-fact.js';\nimport { type UnitStorageWrite, openUnitStorage, type UnitStorage } from './opened.js';\nimport { UnitHistory, assertUnitHistory, unitRecordCursor } from './history.js';\nimport { discardIncompleteSeal, isUnitSealed, readSealedUnitJournal } from './seal.js';\n\nexport interface JsonlUnitStoreOptions extends UnitEncodingOptions {\n readonly filePath: string;\n readonly unitId: string;\n}\n\ninterface FramePosition {\n readonly offset: number;\n readonly length: number;\n}\n\n/**\n * Readers scan a sealed Unit's decompressed bytes instead of restoring its Journal, so listing\n * or inspecting an archive never gives the space back.\n */\ntype ReadableUnitSource = UnitScanSource & {\n close(): Promise<void>;\n sync?(): Promise<void>;\n};\n\nfunction sealedScanSource(bytes: Buffer): ReadableUnitSource {\n return {\n stat: async () => ({ size: bytes.byteLength }),\n read: async (buffer, offset, length, position) => {\n const end = Math.min(position + length, bytes.byteLength);\n if (end <= position) return { bytesRead: 0 };\n bytes.copy(buffer, offset, position, end);\n return { bytesRead: end - position };\n },\n close: async () => {},\n };\n}\n\nasync function openUnitScanSource(\n path: string,\n mode: 'r' | 'r+'\n): Promise<{ source: ReadableUnitSource; sealed: boolean }> {\n const sealed = await readSealedUnitJournal(path);\n if (sealed !== undefined) return { source: sealedScanSource(sealed.bytes), sealed: true };\n return { source: await open(path, mode), sealed: false };\n}\n\n/**\n * Sealing is an offline archive step: a sealed Unit has no readable Journal until it is\n * unsealed, so opening one must fail loudly instead of looking like an empty Session.\n */\nasync function assertNotSealed(filePath: string): Promise<void> {\n if (await isUnitSealed(filePath))\n throw new UnitStoreError(\n 'unit_sealed',\n 'Unit Journal is sealed; unseal it before opening the Unit'\n );\n await discardIncompleteSeal(filePath);\n}\n\n/**\n * Bounded reuse for the several Journal passes made while opening one Unit\n * (history, Session participants, command coverage, replay labels). Above the\n * bound the raw records would cost more memory than the repeated decode saves.\n */\nconst DECODED_FRAME_CACHE_MAX_BYTES = 16 * 1024 * 1024;\n/** Repeat-read cache budget in raw frame bytes; the decoded records are several times larger. */\nconst DECODED_FRAME_READ_CACHE_BYTES = 4 * 1024 * 1024;\n\nfunction sharedPrefix(values: readonly string[]): string {\n const [first = '', ...rest] = values;\n let length = first.length;\n for (const value of rest) {\n let index = 0;\n while (index < length && value[index] === first[index]) index++;\n length = index;\n }\n return first.slice(0, length);\n}\n\n/** Version 2 frames are markers whose facts live in a transaction side file. */\nconst ReferenceFrameMarker = Buffer.from('\"storageVersion\":2');\n\nclass UnitFrames {\n readonly #positions: { frame: number; index: number }[] = [];\n readonly #frames: FramePosition[] = [];\n readonly #decoded: (readonly UnitRecord[] | undefined)[] = [];\n readonly #cacheOrder: number[] = [];\n #cacheFrames = false;\n #cacheBytes = 0;\n completeBytes = 0;\n incompleteTail = false;\n\n constructor(\n readonly file: UnitScanSource,\n readonly transactions: UnitTransactions,\n readonly artifacts?: ArtifactStore,\n readonly cacheDecoded = false\n ) {}\n\n async scan(visit: (records: readonly UnitRecord[]) => void): Promise<void> {\n this.#positions.length = 0;\n this.#frames.length = 0;\n this.#decoded.length = 0;\n this.#cacheOrder.length = 0;\n this.#cacheBytes = 0;\n this.completeBytes = 0;\n this.incompleteTail = false;\n const cache =\n this.cacheDecoded && (await this.file.stat()).size <= DECODED_FRAME_CACHE_MAX_BYTES;\n this.#cacheFrames = cache;\n // Frames with offloaded strings decode through Artifact reads. Awaiting each before scanning\n // the next serialized hundreds of small reads, so decodes overlap and still apply in order.\n const inFlight: {\n readonly offset: number;\n readonly length: number;\n readonly records: readonly UnitRecord[] | Promise<readonly UnitRecord[]>;\n }[] = [];\n const settle = async () => {\n const next = inFlight.shift();\n if (next === undefined) return;\n const records = isPromise(next.records) ? await next.records : next.records;\n visit(records);\n if (cache) this.#decoded[this.#frames.length] = records;\n this.add({ offset: next.offset, length: next.length }, records.length);\n this.completeBytes = next.offset + next.length + 1;\n };\n try {\n for await (const frame of scanUnitFrames(this.file)) {\n if (!frame.complete) {\n this.incompleteTail = true;\n break;\n }\n const records = decodeUnitFrame(frame.bytes, this.artifacts, this.transactions);\n // An abandoned decode must not surface as an unhandled rejection.\n if (isPromise(records)) records.catch(() => {});\n inFlight.push({ offset: frame.offset, length: frame.bytes.length, records });\n while (inFlight.length > 0 && (inFlight.length >= 64 || !isPromise(inFlight[0]?.records)))\n await settle();\n }\n while (inFlight.length > 0) await settle();\n } finally {\n inFlight.length = 0;\n }\n }\n\n add(position: FramePosition, count: number): void {\n const frame = this.#frames.length;\n this.#frames.push(position);\n for (let index = 0; index < count; index++) this.#positions.push({ frame, index });\n }\n\n /**\n * Readers that refresh after every append asked for the same frames repeatedly. Keep the\n * most recent decodes so an unchanged frame costs nothing on the next read, bounded by the\n * raw bytes it came from: decoded records are several times larger than their frame.\n */\n #remember(frameIndex: number, records: readonly UnitRecord[]): void {\n if (!this.#cacheFrames || this.#decoded[frameIndex] !== undefined) return;\n const frame = this.#frames[frameIndex];\n if (frame === undefined) return;\n this.#decoded[frameIndex] = records;\n this.#cacheOrder.push(frameIndex);\n this.#cacheBytes += frame.length;\n while (this.#cacheBytes > DECODED_FRAME_READ_CACHE_BYTES) {\n const evicted = this.#cacheOrder.shift();\n if (evicted === undefined) break;\n this.#cacheBytes -= this.#frames[evicted]?.length ?? 0;\n this.#decoded[evicted] = undefined;\n }\n }\n\n async read(positions: readonly number[]): Promise<readonly UnitRecord[]> {\n const decoded = new Map<number, readonly UnitRecord[]>();\n const needed = new Set<number>();\n for (const position of positions) {\n const locator = this.#positions[position];\n if (locator === undefined)\n throw new UnitStoreError('unit_corrupt', 'Missing unit record locator');\n const cached = this.#decoded[locator.frame];\n if (cached === undefined) needed.add(locator.frame);\n else decoded.set(locator.frame, cached);\n }\n const ranges: { offset: number; end: number; frames: number[] }[] = [];\n for (const index of [...needed].sort((a, b) => a - b)) {\n const frame = this.#frames[index];\n if (frame === undefined)\n throw new UnitStoreError('unit_corrupt', 'Missing unit frame locator');\n const previous = ranges.at(-1);\n const end = frame.offset + frame.length;\n if (previous !== undefined && end - previous.offset <= 64 * 1024) {\n previous.end = end;\n previous.frames.push(index);\n } else ranges.push({ offset: frame.offset, end, frames: [index] });\n }\n for (let index = 0; index < ranges.length; index += 2) {\n const loaded = await Promise.allSettled(\n ranges.slice(index, index + 2).map(async (range) => {\n const buffer = Buffer.alloc(range.end - range.offset);\n let read = 0;\n while (read < buffer.length) {\n const { bytesRead } = await this.file.read(\n buffer,\n read,\n buffer.length - read,\n range.offset + read\n );\n if (bytesRead === 0)\n throw new UnitStoreError('unit_corrupt', 'Committed unit frame disappeared');\n read += bytesRead;\n }\n // Frames with offloaded strings wait on Artifact reads; decode them concurrently.\n await Promise.all(\n range.frames.map(async (frameIndex) => {\n const frame = this.#frames[frameIndex];\n if (frame === undefined)\n throw new UnitStoreError('unit_corrupt', 'Missing unit frame locator');\n const start = frame.offset - range.offset;\n const records = decodeUnitFrame(\n buffer.subarray(start, start + frame.length),\n this.artifacts,\n this.transactions\n );\n const settled = isPromise(records) ? await records : records;\n decoded.set(frameIndex, settled);\n this.#remember(frameIndex, settled);\n })\n );\n })\n );\n for (const result of loaded) if (result.status === 'rejected') throw result.reason;\n }\n return positions.map((position) => {\n const locator = this.#positions[position];\n const record =\n locator === undefined ? undefined : decoded.get(locator.frame)?.[locator.index];\n if (record === undefined)\n throw new UnitStoreError('unit_corrupt', 'Committed unit record disappeared');\n return record;\n });\n }\n}\n\nclass JsonlUnitStorage implements UnitStorage {\n readonly durability = 'sync';\n readonly #frames: UnitFrames;\n readonly #transactions: FileUnitTransactions;\n readonly #stringReuse = new ExternalizedStringReuse();\n constructor(\n readonly options: JsonlUnitStoreOptions,\n readonly file: FileHandle,\n readonly lease: JournalWriterLease\n ) {\n this.#transactions = new FileUnitTransactions(options.filePath);\n this.#frames = new UnitFrames(file, this.#transactions, options.artifactStore, true);\n }\n get unitId(): string {\n return this.options.unitId;\n }\n async load(visit: (records: readonly UnitRecord[]) => void): Promise<void> {\n await this.#frames.scan(visit);\n if ((await this.file.stat()).size !== this.#frames.completeBytes) {\n await this.file.truncate(this.#frames.completeBytes);\n await this.file.sync();\n }\n }\n read(positions: readonly number[]): Promise<readonly UnitRecord[]> {\n return this.#frames.read(positions);\n }\n async append(writes: readonly UnitStorageWrite[]): Promise<UnitCommitOutcome> {\n let json: string;\n try {\n json = await encodeUnitFrame(\n writes,\n { ...this.options, stringReuse: this.#stringReuse },\n this.#transactions\n );\n } catch (cause) {\n return { status: 'not-committed', error: ensureError(cause) };\n }\n const offset = this.#frames.completeBytes;\n const bytes = Buffer.from(`${json}\\n`);\n try {\n let written = 0;\n while (written < bytes.length) {\n const { bytesWritten } = await this.file.write(\n bytes,\n written,\n bytes.length - written,\n offset + written\n );\n if (bytesWritten === 0) throw new Error('Unit file write made no progress');\n written += bytesWritten;\n }\n await this.file.sync();\n this.#frames.add({ offset, length: bytes.length - 1 }, writes.length);\n this.#frames.completeBytes += bytes.length;\n return { status: 'committed' };\n } catch (cause) {\n return { status: 'unknown', error: ensureError(cause) };\n }\n }\n async close(): Promise<void> {\n try {\n await this.file.close();\n } finally {\n this.lease.release();\n }\n }\n}\n\nclass JsonlUnitReader implements UnitReader {\n #closing: Promise<void> | undefined;\n #queue: Promise<void> = Promise.resolve();\n constructor(\n readonly file: ReadableUnitSource,\n readonly frames: UnitFrames,\n readonly history: UnitHistory,\n readonly incompleteTail: boolean\n ) {}\n get unitId(): string {\n return this.history.unitId;\n }\n get tail(): number {\n return this.history.tail;\n }\n read(options: UnitReadOptions = {}): Promise<UnitPage> {\n if (this.#closing !== undefined)\n return Promise.reject(new UnitStoreError('unit_closed', 'Unit reader is closed'));\n const { positions, hasMore } = this.history.positions(options);\n const work = this.#queue.then(async () => {\n const records = await this.frames.read(positions);\n const last = records.at(-1);\n return {\n records,\n cursor: last === undefined ? options.after : unitRecordCursor(last),\n hasMore,\n };\n });\n this.#queue = work.then(\n () => {},\n () => {}\n );\n return work;\n }\n close(): Promise<void> {\n this.#closing ??= this.#queue.then(() => this.file.close());\n return this.#closing;\n }\n}\n\n/** One tree per file. Fact bodies stay on disk; the opened store indexes frame positions. */\nexport class JsonlUnitStore implements UnitStore {\n readonly #options: JsonlUnitStoreOptions;\n constructor(options: JsonlUnitStoreOptions) {\n this.#options = { ...options };\n }\n\n /** Diagnostic scan with a transaction decoding budget; never claims a writer. */\n inspect(\n options: {\n readonly sessionId?: string;\n readonly signal?: AbortSignal;\n readonly unitKinds?: readonly UnitFact['kind'][];\n } = {}\n ): AsyncGenerator<UnitInspectionPage> {\n return this.#readLifecycle(options, true);\n }\n\n /** Complete lifecycle scan without diagnostic budgets or historical content hydration. */\n readRecovery(options: {\n readonly sessionId: string;\n readonly signal?: AbortSignal;\n }): AsyncGenerator<UnitInspectionPage> {\n return this.#readLifecycle(options, false);\n }\n\n async *#readLifecycle(\n options: {\n readonly sessionId?: string;\n readonly signal?: AbortSignal;\n readonly unitKinds?: readonly UnitFact['kind'][];\n },\n diagnostic: boolean\n ): AsyncGenerator<UnitInspectionPage> {\n const unitKinds = diagnostic ? options.unitKinds : [];\n // A kind-filtered scan without Session facts parses only frames that can match. Writers\n // emit JSON.stringify output, so a kind literal cannot appear escaped inside a string;\n // transaction markers keep their facts in a side file and are always read.\n // One shared-prefix search per frame; a false match only costs a parse.\n const needle =\n options.sessionId === undefined && unitKinds !== undefined\n ? Buffer.from(sharedPrefix(unitKinds.map((kind) => `\"kind\":${JSON.stringify(kind)}`)))\n : undefined;\n const path = await canonicalJournalPath(this.#options.filePath);\n const { source: file } = await openUnitScanSource(path, 'r');\n const transactions = new FileUnitTransactions(path);\n let sequence = 1;\n let sessionSequence = 1;\n let frames = 0;\n let skipped = false;\n try {\n for await (const raw of scanUnitFrames(file, options.signal)) {\n if (!raw.complete) {\n yield { unitFacts: [], sessionFacts: [], incompleteTail: true };\n return;\n }\n frames++;\n if (\n needle !== undefined &&\n !raw.bytes.subarray(0, 64).includes(ReferenceFrameMarker) &&\n !raw.bytes.includes(needle)\n ) {\n skipped = true;\n continue;\n }\n const frame = await decodeUnitInspectionFrame(\n raw.bytes,\n this.#options.artifactStore,\n transactions,\n options.sessionId,\n diagnostic,\n unitKinds === undefined ? undefined : new Set(unitKinds)\n );\n // Skipped frames have unknown sizes, so ordering past them is checked as monotonic.\n if (\n frame.unitId !== this.#options.unitId ||\n (skipped ? frame.firstSequence < sequence : frame.firstSequence !== sequence)\n )\n throw new UnitStoreError('unit_corrupt', 'Unit inspection identity or ordering differs');\n skipped = false;\n sequence = frame.firstSequence + frame.count;\n for (const fact of frame.sessionFacts) {\n if (fact.sequence !== sessionSequence++ || fact.cursor !== fact.id)\n throw new UnitStoreError('unit_corrupt', 'Session inspection ordering differs');\n }\n yield {\n unitFacts: frame.unitFacts,\n sessionFacts: frame.sessionFacts,\n incompleteTail: false,\n };\n }\n if (frames === 0)\n throw new UnitStoreError('unit_corrupt', 'Published unit has no committed catalog');\n } finally {\n await file.close();\n }\n }\n\n async open(options: UnitOpenOptions = {}): Promise<OpenedUnitStore> {\n await assertNotSealed(this.#options.filePath);\n const directory = dirname(resolve(this.#options.filePath));\n const created = await mkdir(directory, { recursive: true, mode: 0o700 });\n if (created !== undefined) {\n // Persist every newly created path component before acknowledging a unit below it.\n let current = directory;\n while (current !== dirname(created)) {\n await syncDirectory(current);\n current = dirname(current);\n }\n await syncDirectory(dirname(created));\n }\n const path = await canonicalJournalPath(this.#options.filePath);\n let lease: JournalWriterLease;\n try {\n lease = await acquireJournalWriterLease(path);\n } catch (cause) {\n if (cause instanceof JournalWriterBusyError)\n throw new UnitStoreError(\n 'unit_locked',\n `Unit ${this.#options.unitId} already has a writer`,\n { cause }\n );\n throw cause;\n }\n try {\n await createJournalFile(path);\n const file = await open(path, 'r+');\n return await openUnitStorage(\n new JsonlUnitStorage({ ...this.#options, filePath: path }, file, lease),\n options\n );\n } catch (cause) {\n lease.release();\n throw cause;\n }\n }\n\n /**\n * Pins a complete observed prefix without writer ownership or tail repair.\n * `sync` persists that prefix before returning, for forks that must outlive source loss.\n */\n async openReader(\n options: { readonly durability?: 'observed' | 'sync' } = {}\n ): Promise<UnitReader> {\n const path = await canonicalJournalPath(this.#options.filePath);\n const { source: file, sealed } = await openUnitScanSource(\n path,\n options.durability === 'sync' ? 'r+' : 'r'\n );\n try {\n const frames = new UnitFrames(\n file,\n new FileUnitTransactions(path),\n this.#options.artifactStore\n );\n const history = new UnitHistory(this.#options.unitId);\n await frames.scan((records) => assertUnitHistory(history, records));\n // A sealed archive is already durable; there is no plain prefix to persist.\n if (options.durability === 'sync' && !sealed) await file.sync?.();\n return new JsonlUnitReader(file, frames, history, frames.incompleteTail);\n } catch (cause) {\n await file.close();\n throw cause;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAIA,eAAsB,kBAAkB,UAAiC;CACvE,IAAIA;AACJ,KAAI;AACF,WAAS,MAAMC,KAAS,UAAU,MAAM,IAAM;UACvC,OAAO;AACd,MAAI,QAAQ,MAAM,IAAI,QAAQ,IAAI,OAAO,OAAO,KAAK,SAAU;AAC/D,QAAM;;AAER,OAAM,OAAO,OAAO;AACpB,KAAI;AACF,QAAM,cAAc,QAAQ,SAAS,CAAC;UAC/B,OAAO;AACd,QAAM,OAAO,SAAS;AACtB,QAAM;;;AAIV,eAAsB,qBAAqB,UAAmC;CAC5E,MAAM,mBAAmBC,QAAY,SAAS;AAC9C,KAAI;AACF,SAAO,MAAM,SAAS,iBAAiB;UAChC,OAAO;AACd,MAAI,CAAC,QAAQ,MAAM,IAAI,QAAQ,IAAI,OAAO,OAAO,KAAK,SAAU,OAAM;AAEtE,SAAOA,QADoB,MAAM,SAAS,QAAQ,iBAAiB,CAAC,EAC7B,SAAS,iBAAiB,CAAC;;;AAItE,eAAsB,cAA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