@deepseek-ai/dsh-session-persistence-jsonl 0.2.2-alpha.3 → 0.2.2-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/lib/types/catalog-migration.d.ts.map +1 -0
  2. package/lib/types/catalog-migration.js.map +1 -0
  3. package/lib/types/format.d.ts.map +1 -0
  4. package/lib/types/format.js.map +1 -0
  5. package/lib/types/generation.d.ts.map +1 -0
  6. package/lib/types/generation.js.map +1 -0
  7. package/lib/types/index.d.ts.map +1 -0
  8. package/lib/types/index.js.map +1 -0
  9. package/lib/types/lease.d.ts.map +1 -0
  10. package/lib/types/lease.js.map +1 -0
  11. package/lib/types/migration-verifier.d.ts.map +1 -0
  12. package/lib/types/migration-verifier.js.map +1 -0
  13. package/lib/types/storage.d.ts.map +1 -0
  14. package/lib/types/storage.js.map +1 -0
  15. package/lib/types/testing/generation.d.ts.map +1 -0
  16. package/lib/types/testing/generation.js.map +1 -0
  17. package/lib/types/win32.d.ts.map +1 -0
  18. package/lib/types/win32.js.map +1 -0
  19. package/lib/types/worker.d.ts.map +1 -0
  20. package/lib/types/worker.js.map +1 -0
  21. package/lib/types/zstd-private-decoder.d.ts.map +1 -0
  22. package/lib/types/zstd-private-decoder.js.map +1 -0
  23. package/lib/types/zstd-public-decoder.d.ts.map +1 -0
  24. package/lib/types/zstd-public-decoder.js.map +1 -0
  25. package/lib/types/zstd.d.ts.map +1 -0
  26. package/lib/types/zstd.js.map +1 -0
  27. package/lib/worker.cjs +300 -103
  28. package/package.json +17 -14
  29. package/src/catalog-migration.ts +92 -0
  30. package/src/format.ts +538 -0
  31. package/src/generation.ts +1059 -0
  32. package/src/index.ts +1839 -0
  33. package/src/lease.ts +135 -0
  34. package/src/migration-verifier.ts +198 -0
  35. package/src/storage.ts +571 -0
  36. package/src/testing/generation.ts +16 -0
  37. package/src/win32.ts +208 -0
  38. package/src/worker.ts +56 -0
  39. package/src/zstd-private-decoder.ts +178 -0
  40. package/src/zstd-public-decoder.ts +40 -0
  41. package/src/zstd.ts +156 -0
package/src/index.ts ADDED
@@ -0,0 +1,1839 @@
1
+ /**
2
+ * JSONL durable session-persistence backend. It stores a header and contiguous
3
+ * events in immutable generation files under one directory per session and serves the handle-based
4
+ * `SessionPersistence` API: `create`/`open` return per-session handles, and
5
+ * every read validates the same fail-closed storage contract.
6
+ * @module @deepseek-ai/dsh-session-persistence-jsonl
7
+ */
8
+
9
+ import { Context, type Fiber } from '@deepseek-ai/cordis'
10
+ import z from '@deepseek-ai/schemastery'
11
+ import {
12
+ createSessionFormatCatalogWithChildren,
13
+ SessionFormatUnsupportedMigrationError,
14
+ sessionFormatCatalog,
15
+ } from '@deepseek-ai/dsh-session-format-catalog'
16
+ import { readdirSync, type Dirent } from 'node:fs'
17
+ import { open, mkdir, readdir, realpath, link, rm, stat, truncate } from 'node:fs/promises'
18
+ import { dirname, join, resolve } from 'node:path'
19
+ import { performance } from 'node:perf_hooks'
20
+ import { scheduler } from 'node:timers/promises'
21
+ import { createHash, randomBytes } from 'node:crypto'
22
+ import pLimit, { type LimitFunction } from 'p-limit'
23
+ import {
24
+ SessionPersistence, SessionPersistenceRevision, SessionFormatUnsupportedError,
25
+ SessionPersistenceCorruptionError,
26
+ SessionAlreadyExistsError, SessionPersistenceNotFoundError,
27
+ assertStoredId, materializeCreateHeader, sessionFormatVersionRefusal, validateStoredEvents,
28
+ type SessionAccess, type SessionHandle,
29
+ type SessionHandleReadResult,
30
+ type SessionLocation, type SessionPersistenceCreateOptions,
31
+ type SessionPersistenceListOptions, type SessionPersistenceOpenOptions,
32
+ type SessionPersistenceSnapshot, type SessionPersistenceStatOptions,
33
+ type SessionPersistenceRevision as PersistenceRevision,
34
+ } from '@deepseek-ai/dsh-session-persistence'
35
+ import { JsonlBackendTracker, JsonlSessionHandle, type StorageHandleState } from './storage.ts'
36
+ import { SessionWriteLease } from './lease.ts'
37
+ import { SESSION_FORMAT_VERSION, SessionId as makeSessionId, SessionLogOffset } from '@deepseek-ai/dsh-session'
38
+ import type { SessionEvent, SessionId, SessionHeader, SessionLogOffset as SessionLogOffsetType } from '@deepseek-ai/dsh-session'
39
+ import {
40
+ assertNoRetiredHeaderFields, encodeSegment, eventLines, generationLogFilename, generationLogPath, logPath, logSuffix,
41
+ parseGenerationLogFilename, projectDir, scanLog, sessionDir, SessionLogScanner, toHeaderLine,
42
+ type JsonlCompression,
43
+ } from './format.ts'
44
+ import {
45
+ compressZstdFrame, createZstdFrameDecoder, decompressZstdFrame, decompressZstdPrefix, scanZstdFrames,
46
+ } from './zstd.ts'
47
+ import { ensureDurableDirectoryWin32, publishNewFileWin32 } from './win32.ts'
48
+ import { verifyCurrentGenerationInWorker } from './migration-verifier.ts'
49
+ import { prepareCatalogFacts } from './catalog-migration.ts'
50
+ import {
51
+ JsonlGenerationSourceChangedError,
52
+ JsonlGenerationUnsupportedMigrationError,
53
+ prepareJsonlMigration,
54
+ readStableJsonlFile,
55
+ type JsonlGenerationFormatAdapter,
56
+ type JsonlPhysicalIdentity,
57
+ type PreparedJsonlMigration,
58
+ } from './generation.ts'
59
+
60
+ export type { JsonlCompression } from './format.ts'
61
+
62
+ /**
63
+ * Internal handoff-reuse policy, not deployment configuration: a cold
64
+ * observation and the resume that immediately follows it reuse one parsed
65
+ * log, so the memo only needs the sessions in flight between those steps.
66
+ */
67
+ const COLD_LOG_MEMO_MAX_ENTRIES = 2
68
+
69
+ const DEFAULT_COMPRESSION: JsonlCompression = 'zstd'
70
+ /**
71
+ * Internal scheduling constant, not deployment configuration: balance
72
+ * frame-boundary event-loop yields against `setImmediate` overhead. One frame
73
+ * remains an indivisible synchronous decode.
74
+ */
75
+ const ZSTD_DECODE_YIELD_INTERVAL_MS = 500
76
+
77
+ /** Assert that the independently decodable first frame contains only the header record. */
78
+ function assertZstdHeaderFrame(plaintext: Buffer): void {
79
+ if (plaintext.length === 0 || plaintext.indexOf(0x0A) !== plaintext.length - 1) {
80
+ throw new Error('corrupt Zstandard session log: first frame is not exactly one header line')
81
+ }
82
+ }
83
+
84
+ /** Loader schema for the JSONL artifact's physical encoding. */
85
+ export const JsonlCompressionSchema: z<JsonlCompression> = z.union([
86
+ z.const('zstd'),
87
+ z.const('none'),
88
+ ]).default(DEFAULT_COMPRESSION)
89
+
90
+ /** Default maximum listing filesystem operations in flight per backend. */
91
+ const DEFAULT_LIST_CONCURRENCY = 3
92
+
93
+ /** Plugin config for the JSONL backend's root, physical encoding, and listing concurrency. */
94
+ export interface Config {
95
+ /**
96
+ * Root directory for all session files. Required (no default): a default of
97
+ * `process.cwd()` would scatter session files as the process's cwd changes
98
+ * (bash calls, subprocesses). Sessions group under human-readable project
99
+ * directories, then per-session directories. An existing root must be a
100
+ * readable directory; an absent root is created on first materialization.
101
+ */
102
+ root: string
103
+ /** Physical encoding; defaults to checksummed Zstandard frames. */
104
+ compression?: JsonlCompression
105
+ /**
106
+ * Maximum directory, header, and stat reads in flight across all concurrent
107
+ * listings of this backend (`list()`, the root encoding check, and historical
108
+ * fingerprints). Defaults to 3.
109
+ */
110
+ listConcurrency?: number
111
+ }
112
+
113
+ /** Logical header paired with the catalog's selected physical-generation classification. */
114
+ interface GenerationHeader {
115
+ readonly header: SessionHeader
116
+ readonly formatStatus: NonNullable<SessionPersistenceSnapshot['formatStatus']>
117
+ }
118
+
119
+ /** One stored event graph whose producer has established immutable sharing. */
120
+ interface FrozenStoredEvents extends SessionHandleReadResult {
121
+ readonly eventState: 'shared-frozen'
122
+ }
123
+
124
+ /** State shared by prepared historical and published current logs. */
125
+ interface StoredLogBase extends FrozenStoredEvents {
126
+ readonly meta: SessionHeader
127
+ readonly tornTruncateTo: number | undefined
128
+ /** Complete events recovered from the torn final frame; the write path rewrites them durably. */
129
+ readonly recoveredTail: SessionEvent[]
130
+ /** Exact fork-inherited prefix length stored in the header line. */
131
+ readonly inheritedEventCount: SessionLogOffsetType
132
+ readonly revision: PersistenceRevision
133
+ }
134
+
135
+ /** A decoded current generation that is already durable. */
136
+ interface CurrentStoredLog extends StoredLogBase {
137
+ readonly status: 'current'
138
+ }
139
+
140
+ /** A migrated historical generation retained until an explicit write open publishes it. */
141
+ interface PreparedStoredLog extends StoredLogBase {
142
+ readonly status: 'prepared'
143
+ readonly validateRelatedSources: () => Promise<void>
144
+ readonly publication: {
145
+ readonly source: ResolvedJsonlGeneration
146
+ readonly value: PreparedJsonlMigration
147
+ }
148
+ }
149
+
150
+ /** A validated logical log, either durable current state or prepared historical state. */
151
+ type StoredLog = CurrentStoredLog | PreparedStoredLog
152
+
153
+ /** Deep-freeze acyclic stored JSON; its arrays contain only indexed JSON values. */
154
+ function freezeStoredEvent(event: SessionEvent): void {
155
+ const pending: object[] = [event]
156
+ while (pending.length > 0) {
157
+ // The non-empty check proves an object remains to visit.
158
+ // oxlint-disable-next-line typescript/no-non-null-assertion
159
+ const current = pending.pop()!
160
+ Object.freeze(current)
161
+ if (Array.isArray(current)) {
162
+ for (let index = 0; index < current.length; index += 1) {
163
+ const child: unknown = current[index]
164
+ if (child !== null && typeof child === 'object') pending.push(child)
165
+ }
166
+ } else {
167
+ for (const key in current) {
168
+ const child = (current as Record<string, unknown>)[key]
169
+ if (child !== null && typeof child === 'object') pending.push(child)
170
+ }
171
+ }
172
+ }
173
+ }
174
+
175
+ /** Establish immutable sharing for one decoded event graph and report that state. */
176
+ function freezeStoredEvents(events: SessionEvent[]): FrozenStoredEvents {
177
+ for (const event of events) freezeStoredEvent(event)
178
+ Object.freeze(events)
179
+ return { eventState: 'shared-frozen', events }
180
+ }
181
+
182
+ /** One authoritative immutable generation selected from a Session directory. */
183
+ interface ResolvedJsonlGeneration {
184
+ readonly sourcePath: string
185
+ readonly sourceVersion: number
186
+ readonly currentPath: string
187
+ }
188
+
189
+ /** One backend-owned historical preparation shared by its current callers. */
190
+ interface MigrationPreparation {
191
+ readonly sourcePath: string
192
+ readonly sourceRevision: PersistenceRevision
193
+ readonly controller: AbortController
194
+ readonly promise: Promise<PreparedStoredLog>
195
+ settled: boolean
196
+ waiters: number
197
+ }
198
+
199
+ /** Build the stat-derived best-effort change token shared by full and lightweight reads. */
200
+ function fileRevision(identity: JsonlPhysicalIdentity): PersistenceRevision {
201
+ return SessionPersistenceRevision([
202
+ identity.dev,
203
+ identity.ino,
204
+ identity.size,
205
+ identity.mtimeNs,
206
+ identity.ctimeNs,
207
+ ].join(':'))
208
+ }
209
+
210
+ /** Whether a filesystem error means absence; every non-ENOENT failure must surface. */
211
+ function isENOENT(error: unknown): boolean {
212
+ return (error as NodeJS.ErrnoException | null)?.code === 'ENOENT'
213
+ }
214
+
215
+ /**
216
+ * Run `task` over `items` through the backend's shared listing limiter and
217
+ * settle every call. Callers consume the outcomes in input order, so the first
218
+ * failure they report matches a sequential loop whatever the completion order.
219
+ * A limited task must never wait on the same limiter.
220
+ * @param limit - the backend's shared listing limiter.
221
+ * @param items - inputs in their sequential order.
222
+ * @param task - per-item operation.
223
+ * @returns one outcome per item, in input order.
224
+ */
225
+ function settleLimited<T, R>(
226
+ limit: LimitFunction,
227
+ items: readonly T[],
228
+ task: (item: T) => Promise<R>,
229
+ ): Promise<PromiseSettledResult<R>[]> {
230
+ return Promise.allSettled(items.map(item => limit(() => task(item))))
231
+ }
232
+
233
+ /**
234
+ * Unwrap outcomes from {@link settleLimited}, rethrowing the first rejection in input order.
235
+ * @param outcomes - outcomes in input order.
236
+ * @returns the fulfilled values in input order.
237
+ */
238
+ function settledValues<R>(outcomes: readonly PromiseSettledResult<R>[]): R[] {
239
+ return outcomes.map((outcome) => {
240
+ if (outcome.status === 'rejected') throw outcome.reason
241
+ return outcome.value
242
+ })
243
+ }
244
+
245
+ /** Whether a filesystem-owned failure should retain its original errno and path. */
246
+ function isErrnoException(error: unknown): error is NodeJS.ErrnoException {
247
+ return typeof (error as NodeJS.ErrnoException | null)?.code === 'string'
248
+ }
249
+
250
+ /** Preserve an Error abort reason and normalize hostile non-Error reasons. */
251
+ function abortError(signal: AbortSignal): Error {
252
+ return signal.reason instanceof Error
253
+ ? signal.reason
254
+ : new Error('session migration preparation aborted', { cause: signal.reason })
255
+ }
256
+
257
+ /** Let one caller stop waiting without transferring cancellation ownership to shared work. */
258
+ function waitWithAbort<T>(operation: Promise<T>, signal?: AbortSignal): Promise<T> {
259
+ if (signal === undefined) return operation
260
+ /* v8 ignore next -- requireStoredLog synchronously rechecks the signal immediately before waiting. */
261
+ if (signal.aborted) return Promise.reject(abortError(signal))
262
+ return new Promise<T>((resolve, reject) => {
263
+ const stopWaiting = (): void => {
264
+ reject(abortError(signal))
265
+ }
266
+ signal.addEventListener('abort', stopWaiting, { once: true })
267
+ void operation.then(
268
+ (value) => {
269
+ signal.removeEventListener('abort', stopWaiting)
270
+ resolve(value)
271
+ },
272
+ (error: unknown) => {
273
+ signal.removeEventListener('abort', stopWaiting)
274
+ /* v8 ignore else -- the preparation owner normalizes every rejection before this waiter sees it. */
275
+ if (error instanceof Error) {
276
+ reject(error)
277
+ } else {
278
+ reject(new Error('session migration preparation failed', { cause: error }))
279
+ }
280
+ },
281
+ )
282
+ })
283
+ }
284
+
285
+ /**
286
+ * The JSONL backend registered as `ctx.sessionPersistence` by the plugin.
287
+ * Sessions materialize lazily: a created session is
288
+ * visible to this process immediately, reaches disk on its first append or
289
+ * flush, and never existed if the process crashes before that.
290
+ */
291
+ class JsonlSessionPersistence extends SessionPersistence {
292
+ /** Backend label for diagnostics and effects; shadows `Service.name` without changing the service key. */
293
+ override readonly name = 'session-persistence-jsonl'
294
+
295
+ private root: string
296
+ private compression: JsonlCompression
297
+ /**
298
+ * Bounds directory, header, and stat I/O across every concurrent listing of
299
+ * this backend (`list()`, the root encoding check, historical fingerprints).
300
+ * Queued tasks of a cancelled listing run and reject at their signal check.
301
+ */
302
+ private readonly listLimit: LimitFunction
303
+ private rootEncodingCheck: Promise<void> | undefined
304
+ private readonly generationFormat: Omit<JsonlGenerationFormatAdapter, 'createRestore'>
305
+ /**
306
+ * Bounded LRU of parsed, validated stored logs keyed by session id and
307
+ * guarded by the stat-derived revision, so an immediate cold-read handoff
308
+ * (observation then resume) parses the artifact once. Every local mutation
309
+ * for an id invalidates its entry; a foreign write misses through the
310
+ * revision guard.
311
+ */
312
+ private readonly coldLogMemo = new Map<SessionId, StoredLog>()
313
+ /** One joinable decode/migration operation per selected historical Session file revision. */
314
+ private readonly migrationPreparations = new Map<SessionId, MigrationPreparation>()
315
+
316
+ constructor(ctx: Context, public config: Config, private readonly tracker: JsonlBackendTracker) {
317
+ super(ctx)
318
+ /* v8 ignore next 5 -- generated catalog and Session source share one build-time version owner. */
319
+ if (sessionFormatCatalog.currentVersion !== SESSION_FORMAT_VERSION) {
320
+ throw new Error(
321
+ `session-persistence-jsonl: format catalog v${sessionFormatCatalog.currentVersion} `
322
+ + `does not match Session v${SESSION_FORMAT_VERSION}`,
323
+ )
324
+ }
325
+ // Resolve once so later process.cwd() changes cannot split one backend across roots.
326
+ this.root = resolve(config.root)
327
+ this.compression = config.compression ?? DEFAULT_COMPRESSION
328
+ this.listLimit = pLimit(config.listConcurrency ?? DEFAULT_LIST_CONCURRENCY)
329
+ this.generationFormat = {
330
+ currentVersion: sessionFormatCatalog.currentVersion,
331
+ encodeHeader: (header, inheritedEventCount) =>
332
+ sessionFormatCatalog.encodeCurrentHeader(header, inheritedEventCount),
333
+ encodeEvent: event => sessionFormatCatalog.encodeCurrentEvent(event),
334
+ isUnsupportedMigrationError: (error): error is SessionFormatUnsupportedMigrationError =>
335
+ error instanceof SessionFormatUnsupportedMigrationError,
336
+ }
337
+ this.assertUsableRoot()
338
+ }
339
+
340
+ /**
341
+ * Refusal-diagnostics hook: the absolute target path, without touching the filesystem.
342
+ * @param meta - the stored header naming the session and its cwd.
343
+ * @returns the artifact kind and absolute path.
344
+ */
345
+ private locate(meta: SessionHeader): SessionLocation {
346
+ return { kind: 'jsonl', path: logPath(this.root, meta.cwd, meta.id, this.compression) }
347
+ }
348
+
349
+ // --- SessionPersistence service API ---
350
+
351
+ /**
352
+ * Create a new stored session and take its write ownership. The session is
353
+ * visible to this process immediately; the physical artifact appears on the
354
+ * first append or flush.
355
+ * @param header - the immutable header to store; must be losslessly
356
+ * JSON-serializable with a non-negative safe-integer `createdAt`.
357
+ * @param options - optional cancellation.
358
+ * @returns the owned write handle.
359
+ */
360
+ async create(header: SessionHeader, options?: SessionPersistenceCreateOptions): Promise<SessionHandle> {
361
+ options?.signal?.throwIfAborted()
362
+ const snapshot = materializeCreateHeader(header)
363
+ // Fail fast on a seeded/cut mismatch with the exact refusal the header
364
+ // line encoder enforces at materialization.
365
+ toHeaderLine(snapshot, options?.inheritedEventCount)
366
+ const inheritedEventCount = SessionLogOffset(options?.inheritedEventCount ?? 0)
367
+ await this.ensureRootEncoding()
368
+ options?.signal?.throwIfAborted()
369
+ if (this.tracker.hasPending(snapshot.id) || await this.findLog(snapshot.id, options?.signal) !== undefined) {
370
+ throw new SessionAlreadyExistsError(snapshot.id)
371
+ }
372
+ options?.signal?.throwIfAborted()
373
+ // No lock yet: before materialization there is no durable artifact for
374
+ // another process to contend over, so the handle acquires the lock right
375
+ // before its first log bytes publish (ensureLease); an unmaterialized
376
+ // session leaves no filesystem footprint at all.
377
+ this.tracker.registerCreated(snapshot, inheritedEventCount)
378
+ return this.tracker.adopt(new JsonlSessionHandle(this, snapshot.id, snapshot, 'write', { cursor: 0, materialized: false, inheritedEventCount }))
379
+ }
380
+
381
+ /**
382
+ * Open an existing stored session for `read` or single-writer `write`.
383
+ * @param id - the stored session to open.
384
+ * @param access - `read` (no ownership) or `write` (atomic in-process claim).
385
+ * @param options - optional cancellation.
386
+ * @returns the open handle.
387
+ */
388
+ async open(id: SessionId, access: SessionAccess, options?: SessionPersistenceOpenOptions): Promise<SessionHandle> {
389
+ options?.signal?.throwIfAborted()
390
+ await this.ensureRootEncoding()
391
+ options?.signal?.throwIfAborted()
392
+ const pending = this.tracker.pendingOf(id)
393
+ if (access === 'read') {
394
+ if (pending !== undefined) {
395
+ return this.tracker.adopt(new JsonlSessionHandle(this, id, pending.header, 'read', { cursor: 0, materialized: false, inheritedEventCount: pending.inheritedEventCount }))
396
+ }
397
+ let stored: StoredLog
398
+ try {
399
+ stored = await this.requireStoredLog(id, options?.signal)
400
+ } catch (error: unknown) {
401
+ if (!(error instanceof JsonlGenerationSourceChangedError)) throw error
402
+ stored = await this.requireStoredLog(id, options?.signal)
403
+ }
404
+ let state: StorageHandleState
405
+ if (stored.status === 'prepared') {
406
+ state = {
407
+ cursor: 0,
408
+ materialized: true,
409
+ inheritedEventCount: stored.inheritedEventCount,
410
+ primed: stored,
411
+ }
412
+ } else {
413
+ state = {
414
+ cursor: 0,
415
+ materialized: true,
416
+ inheritedEventCount: stored.inheritedEventCount,
417
+ }
418
+ }
419
+ return this.tracker.adopt(new JsonlSessionHandle(this, id, stored.meta, 'read', state))
420
+ }
421
+ // A pending entry always belongs to an ACTIVE creator handle (close erases
422
+ // it), so the claim below rejects that case as already owned.
423
+ this.tracker.claimWrite(id)
424
+ let lease: SessionWriteLease | undefined
425
+ try {
426
+ const resolved = await this.findLog(id, options?.signal)
427
+ if (resolved === undefined) throw new SessionPersistenceNotFoundError(id)
428
+ lease = await this.acquireLease(id, undefined, dirname(resolved.currentPath))
429
+ const prepared = await this.requireStoredLog(id, options?.signal)
430
+ options?.signal?.throwIfAborted()
431
+ let stored: CurrentStoredLog
432
+ if (prepared.status === 'prepared') {
433
+ stored = await this.publishStoredMigration(id, prepared)
434
+ } else {
435
+ stored = prepared
436
+ }
437
+ options?.signal?.throwIfAborted()
438
+ return this.tracker.adopt(new JsonlSessionHandle(this, id, stored.meta, 'write', {
439
+ cursor: stored.events.length,
440
+ materialized: true,
441
+ tornTruncateTo: stored.tornTruncateTo,
442
+ recoveredTail: stored.recoveredTail,
443
+ inheritedEventCount: stored.inheritedEventCount,
444
+ primed: stored,
445
+ }, lease))
446
+ } catch (error) {
447
+ // Free the in-process claim no matter how the kernel-lock release
448
+ // fares, and keep the original diagnostic: a release failure joins it
449
+ // instead of replacing it.
450
+ /* v8 ignore next -- typed backends and fs reject with Error */
451
+ const failure = error instanceof Error ? error : new Error(String(error))
452
+ let releaseFailure: Error | undefined
453
+ try {
454
+ await lease?.release()
455
+ } catch (raw: unknown) {
456
+ /* v8 ignore next -- lock releases reject with Error */
457
+ releaseFailure = raw instanceof Error ? raw : new Error(String(raw))
458
+ }
459
+ this.tracker.releaseClaim(id)
460
+ if (releaseFailure !== undefined) {
461
+ throw new AggregateError([failure, releaseFailure], `session "${id}": write open failed and its lock release failed`)
462
+ }
463
+ throw failure
464
+ }
465
+ }
466
+
467
+ /**
468
+ * Flush every active write handle in one durability barrier; see the seam
469
+ * contract.
470
+ * @returns resolution once every write handle active at the call has flushed.
471
+ */
472
+ flush(): Promise<void> {
473
+ return this.tracker.flushAll()
474
+ }
475
+
476
+ /**
477
+ * Observe one stored session without reading its event log.
478
+ * @param id - the stored session to observe.
479
+ * @param options - optional cancellation.
480
+ * @returns the snapshot (`sizeBytes` carries the physical artifact size), or
481
+ * `undefined` when the session does not exist.
482
+ */
483
+ async stat(
484
+ id: SessionId,
485
+ options?: SessionPersistenceStatOptions,
486
+ ): Promise<SessionPersistenceSnapshot | undefined> {
487
+ options?.signal?.throwIfAborted()
488
+ await this.ensureRootEncoding()
489
+ options?.signal?.throwIfAborted()
490
+ const pending = this.tracker.pendingOf(id)
491
+ if (pending !== undefined) {
492
+ return { header: pending.header, revision: pending.revision }
493
+ }
494
+ const selected = await this.findLog(id, options?.signal)
495
+ if (selected === undefined) return undefined
496
+ const metadata = await this.readGenerationHeader(selected, id, options?.signal)
497
+ if (metadata === undefined) return undefined
498
+ try {
499
+ const identity = await stat(selected.sourcePath, { bigint: true })
500
+ options?.signal?.throwIfAborted()
501
+ return {
502
+ ...metadata,
503
+ revision: selected.sourceVersion < SESSION_FORMAT_VERSION
504
+ ? SessionPersistenceRevision(`${fileRevision(identity)}:${await this.historicalCorpusRevision(options?.signal)}`)
505
+ : fileRevision(identity),
506
+ sizeBytes: Number(identity.size),
507
+ location: { kind: 'jsonl', path: selected.sourcePath },
508
+ }
509
+ } catch (error: unknown) {
510
+ options?.signal?.throwIfAborted()
511
+ if (isENOENT(error)) return undefined
512
+ throw error
513
+ }
514
+ }
515
+
516
+ /**
517
+ * List every stored session visible to this process: materialized artifacts
518
+ * plus this process's created-but-unmaterialized sessions.
519
+ * @param options - optional cancellation.
520
+ * @returns one snapshot per session, in no promised order.
521
+ */
522
+ async list(options?: SessionPersistenceListOptions): Promise<readonly SessionPersistenceSnapshot[]> {
523
+ const signal = options?.signal
524
+ const snapshots: SessionPersistenceSnapshot[] = []
525
+ const listed = new Set<SessionId>()
526
+ // Snapshot pending entries BEFORE scanning storage: a session whose first
527
+ // append lands mid-scan is then still in this snapshot (its artifact may
528
+ // predate the scan), so create-to-list visibility never has a hole.
529
+ const pending = [...this.tracker.pendingEntries()]
530
+ const artifacts = await this.listArtifacts(signal)
531
+ const corpusRevision = artifacts.some(artifact => artifact.sourceVersion < SESSION_FORMAT_VERSION)
532
+ ? await this.historicalCorpusRevision(signal) : undefined
533
+ const statted = settledValues(await settleLimited(this.listLimit, artifacts, async (artifact) => {
534
+ signal?.throwIfAborted()
535
+ try {
536
+ const identity = await stat(artifact.path, { bigint: true })
537
+ signal?.throwIfAborted()
538
+ return { artifact, identity }
539
+ } catch (error: unknown) {
540
+ signal?.throwIfAborted()
541
+ if (!isENOENT(error)) throw error
542
+ return undefined
543
+ }
544
+ }))
545
+ for (const entry of statted) {
546
+ if (entry === undefined) continue
547
+ const { artifact, identity } = entry
548
+ listed.add(artifact.header.id)
549
+ snapshots.push({
550
+ header: artifact.header,
551
+ formatStatus: artifact.formatStatus,
552
+ revision: artifact.sourceVersion < SESSION_FORMAT_VERSION
553
+ ? SessionPersistenceRevision(`${fileRevision(identity)}:${corpusRevision}`)
554
+ : fileRevision(identity),
555
+ sizeBytes: Number(identity.size),
556
+ location: { kind: 'jsonl', path: artifact.path },
557
+ })
558
+ }
559
+ for (const [id, entry] of pending) {
560
+ if (!listed.has(id)) snapshots.push({ header: entry.header, revision: entry.revision })
561
+ }
562
+ signal?.throwIfAborted()
563
+ return snapshots
564
+ }
565
+
566
+ // --- handle-facing storage internals (package-private via the handle class below) ---
567
+
568
+ /** Resolve and read one stored log, refusing loudly when the artifact is absent. */
569
+ private async requireStoredLog(id: SessionId, signal?: AbortSignal): Promise<StoredLog> {
570
+ const selected = await this.findLog(id, signal)
571
+ if (selected === undefined) throw new SessionPersistenceNotFoundError(id)
572
+ if (selected.sourceVersion < SESSION_FORMAT_VERSION) {
573
+ const sourceRevision = fileRevision(await stat(selected.sourcePath, { bigint: true }))
574
+ signal?.throwIfAborted()
575
+ let preparation = this.migrationPreparations.get(id)
576
+ if (preparation === undefined
577
+ || preparation.sourcePath !== selected.sourcePath
578
+ || preparation.sourceRevision !== sourceRevision) {
579
+ const controller = new AbortController()
580
+ const promise = this.loadStoredMigration(id, selected, sourceRevision, controller.signal)
581
+ preparation = {
582
+ sourcePath: selected.sourcePath,
583
+ sourceRevision,
584
+ controller,
585
+ promise,
586
+ settled: false,
587
+ waiters: 0,
588
+ }
589
+ this.migrationPreparations.set(id, preparation)
590
+ const created = preparation
591
+ const release = (): void => {
592
+ created.settled = true
593
+ if (this.migrationPreparations.get(id) === created) {
594
+ this.migrationPreparations.delete(id)
595
+ }
596
+ }
597
+ void promise.then(release, release)
598
+ }
599
+ signal?.throwIfAborted()
600
+ return this.waitForPreparation(id, preparation, signal)
601
+ }
602
+ if (selected.sourceVersion > SESSION_FORMAT_VERSION) {
603
+ const header = await this.readGenerationHeader(selected, id, signal)
604
+ /* v8 ignore else -- a readable future header is rejected inside readGenerationHeader. */
605
+ if (header === undefined) {
606
+ throw new SessionPersistenceCorruptionError(
607
+ `session "${id}": stored log has a malformed header (raw log: ${selected.sourcePath})`,
608
+ { cause: new Error('malformed Session header') },
609
+ )
610
+ }
611
+ /* v8 ignore next -- readGenerationHeader rejects every future version. */
612
+ throw new SessionFormatUnsupportedError(
613
+ `${sessionFormatVersionRefusal(id, selected.sourceVersion)} (raw log: ${selected.sourcePath})`,
614
+ { kind: 'jsonl', path: selected.sourcePath },
615
+ )
616
+ }
617
+ const probe = fileRevision(await stat(selected.sourcePath, { bigint: true }))
618
+ const memoized = this.coldLogMemo.get(id)
619
+ if (memoized?.status === 'current' && memoized.revision === probe) {
620
+ this.coldLogMemo.delete(id)
621
+ this.coldLogMemo.set(id, memoized)
622
+ return memoized
623
+ }
624
+ const current = await readStableJsonlFile(selected.sourcePath, signal)
625
+ return this.decodeStoredLog(
626
+ selected.sourcePath,
627
+ id,
628
+ current.bytes,
629
+ fileRevision(current.identity),
630
+ signal,
631
+ )
632
+ }
633
+
634
+ /** Probe the memo and otherwise decode one historical generation under backend cancellation. */
635
+ private async loadStoredMigration(
636
+ id: SessionId,
637
+ selected: ResolvedJsonlGeneration,
638
+ sourceRevision: PersistenceRevision,
639
+ signal: AbortSignal,
640
+ ): Promise<PreparedStoredLog> {
641
+ signal.throwIfAborted()
642
+ const memoized = this.coldLogMemo.get(id)
643
+ if (memoized?.status === 'prepared' && memoized.revision === sourceRevision) {
644
+ try {
645
+ await memoized.validateRelatedSources()
646
+ } catch (error: unknown) {
647
+ this.coldLogMemo.delete(id)
648
+ throw this.generationFailure(id, selected, error)
649
+ }
650
+ this.coldLogMemo.delete(id)
651
+ this.coldLogMemo.set(id, memoized)
652
+ return memoized
653
+ }
654
+ return this.prepareStoredMigration(id, selected, signal)
655
+ }
656
+
657
+ /** Await shared preparation for one caller and abort it only after its last waiter leaves. */
658
+ private async waitForPreparation(
659
+ id: SessionId,
660
+ preparation: MigrationPreparation,
661
+ signal?: AbortSignal,
662
+ ): Promise<PreparedStoredLog> {
663
+ preparation.waiters += 1
664
+ try {
665
+ return await waitWithAbort(preparation.promise, signal)
666
+ } finally {
667
+ preparation.waiters -= 1
668
+ if (preparation.waiters === 0 && !preparation.settled) {
669
+ /* v8 ignore else -- a newer selected source may already own this id's preparation slot. */
670
+ if (this.migrationPreparations.get(id) === preparation) {
671
+ this.migrationPreparations.delete(id)
672
+ }
673
+ preparation.controller.abort()
674
+ }
675
+ }
676
+ }
677
+
678
+ /** Decode one historical generation without publishing a successor. */
679
+ private async prepareStoredMigration(
680
+ id: SessionId,
681
+ selected: ResolvedJsonlGeneration,
682
+ signal: AbortSignal,
683
+ ): Promise<PreparedStoredLog> {
684
+ let prepared: Awaited<ReturnType<typeof prepareJsonlMigration>>
685
+ let validateRelatedSources: () => Promise<void>
686
+ try {
687
+ const children = async () => (await this.listArtifacts(signal))
688
+ .filter(source => source.header.origin === 'subagent' && source.header.parentSession === id)
689
+ const sources = await children()
690
+ const related = await prepareCatalogFacts(id, sources, this.compression, signal)
691
+ for (const failure of related.failures) {
692
+ this.ctx.logger.warn(`${this.name}: session "${id}" catalog retained a child with unknown descriptor (raw log: ${failure.path}): ${String(failure.error)}`)
693
+ }
694
+ const membership = sources.map(source => source.path).sort()
695
+ validateRelatedSources = async () => {
696
+ const current = (await children()).map(source => source.path).sort()
697
+ const before = new Set(membership)
698
+ const after = new Set(current)
699
+ const changed = current.find(path => !before.has(path)) ?? membership.find(path => !after.has(path))
700
+ if (changed !== undefined) throw new JsonlGenerationSourceChangedError(changed)
701
+ await related.validate()
702
+ }
703
+ prepared = await prepareJsonlMigration({
704
+ sourcePath: selected.sourcePath,
705
+ sourceVersion: selected.sourceVersion,
706
+ currentPath: selected.currentPath,
707
+ compression: this.compression,
708
+ format: {
709
+ ...this.generationFormat,
710
+ createRestore: header => createSessionFormatCatalogWithChildren(related.facts).createRestore(header, {
711
+ recovery: 'recoverable', validation: 'transformed',
712
+ }),
713
+ },
714
+ validateRelatedSources,
715
+ verifyCurrentFile: verifyCurrentGenerationInWorker,
716
+ validateHistoricalHeader: headerValue => this.validateSourceIdentity(
717
+ selected,
718
+ headerValue,
719
+ id,
720
+ signal,
721
+ ),
722
+ signal,
723
+ })
724
+ } catch (error: unknown) {
725
+ throw this.generationFailure(id, selected, error)
726
+ }
727
+ const meta = this.currentHeader(prepared.artifact.header)
728
+ assertStoredId(id, meta)
729
+ const events = prepared.artifact.events as SessionEvent[]
730
+ validateStoredEvents(meta, events, { kind: 'jsonl', path: selected.sourcePath })
731
+ const stored: PreparedStoredLog = {
732
+ status: 'prepared',
733
+ validateRelatedSources,
734
+ meta,
735
+ ...freezeStoredEvents(events),
736
+ tornTruncateTo: undefined,
737
+ recoveredTail: [],
738
+ inheritedEventCount: SessionLogOffset(prepared.artifact.inheritedEventCount),
739
+ revision: fileRevision(prepared.sourceIdentity),
740
+ publication: { source: selected, value: prepared },
741
+ }
742
+ this.memoizeStoredLog(id, stored)
743
+ return stored
744
+ }
745
+
746
+ /** Publish a prepared historical log before granting write access. */
747
+ private async publishStoredMigration(id: SessionId, stored: PreparedStoredLog): Promise<CurrentStoredLog> {
748
+ const migration = stored.publication
749
+ let identity: JsonlPhysicalIdentity
750
+ try {
751
+ identity = await migration.value.publish()
752
+ } catch (error: unknown) {
753
+ /* v8 ignore else -- a newer preparation may have replaced this stale cache entry. */
754
+ if (this.coldLogMemo.get(id) === stored) this.coldLogMemo.delete(id)
755
+ throw this.generationFailure(id, migration.source, error)
756
+ }
757
+ const published: CurrentStoredLog = {
758
+ status: 'current',
759
+ meta: stored.meta,
760
+ eventState: stored.eventState,
761
+ events: stored.events,
762
+ tornTruncateTo: stored.tornTruncateTo,
763
+ recoveredTail: stored.recoveredTail,
764
+ inheritedEventCount: stored.inheritedEventCount,
765
+ revision: fileRevision(identity),
766
+ }
767
+ this.memoizeStoredLog(id, published)
768
+ return published
769
+ }
770
+
771
+ /** Translate generation-layer failures into the persistence seam's error vocabulary. */
772
+ private generationFailure(
773
+ id: SessionId,
774
+ selected: ResolvedJsonlGeneration,
775
+ error: unknown,
776
+ ): Error {
777
+ if (error instanceof JsonlGenerationUnsupportedMigrationError) {
778
+ return new SessionFormatUnsupportedError(
779
+ `${error.message}; source v${error.fromVersion} artifact remains unchanged (raw log: ${selected.sourcePath})`,
780
+ { kind: 'jsonl', path: selected.sourcePath },
781
+ )
782
+ }
783
+ if (error instanceof JsonlGenerationSourceChangedError) return error
784
+ if (error instanceof SessionFormatUnsupportedError
785
+ || error instanceof SessionPersistenceCorruptionError
786
+ || isErrnoException(error)
787
+ || error instanceof DOMException && error.name === 'AbortError') return error
788
+ return new SessionPersistenceCorruptionError(
789
+ `session "${id}": stored log is corrupt: ${String(error)} (raw log: ${selected.sourcePath})`,
790
+ { cause: error },
791
+ )
792
+ }
793
+
794
+ /**
795
+ * Read, parse, and validate one stored log as the current logical prefix.
796
+ * @param path - the artifact file to read.
797
+ * @param expectedId - the session identity the artifact must carry.
798
+ * @param signal - optional cancellation for the stat/read/decode work.
799
+ * @returns the validated stored log with any torn-tail truncation point.
800
+ */
801
+ async readStoredLog(path: string, expectedId: SessionId, signal?: AbortSignal): Promise<CurrentStoredLog> {
802
+ signal?.throwIfAborted()
803
+ const probe = fileRevision(await stat(path, { bigint: true }))
804
+ const memoized = this.coldLogMemo.get(expectedId)
805
+ if (memoized?.status === 'current' && memoized.revision === probe) {
806
+ this.coldLogMemo.delete(expectedId)
807
+ this.coldLogMemo.set(expectedId, memoized)
808
+ return memoized
809
+ }
810
+ const { bytes, identity } = await readStableJsonlFile(path, signal)
811
+ return this.decodeStoredLog(path, expectedId, bytes, fileRevision(identity), signal)
812
+ }
813
+
814
+ /** Decode and memoize one already-stable current physical snapshot. */
815
+ private async decodeStoredLog(
816
+ path: string,
817
+ expectedId: SessionId,
818
+ buffer: Buffer,
819
+ revision: PersistenceRevision,
820
+ signal?: AbortSignal,
821
+ ): Promise<CurrentStoredLog> {
822
+ let parsed: {
823
+ meta: SessionHeader
824
+ inheritedEventCount: SessionLogOffsetType
825
+ events: SessionEvent[]
826
+ tornTruncateTo: number | undefined
827
+ recoveredTail: SessionEvent[]
828
+ }
829
+ try {
830
+ if (this.compression === 'zstd') {
831
+ parsed = await this.readZstdPrefix(buffer, signal)
832
+ } else {
833
+ signal?.throwIfAborted()
834
+ const { meta, inheritedEventCount, events, committedBytes } = scanLog(buffer)
835
+ signal?.throwIfAborted()
836
+ parsed = {
837
+ meta,
838
+ inheritedEventCount,
839
+ events,
840
+ tornTruncateTo: committedBytes < buffer.byteLength ? committedBytes : undefined,
841
+ // A torn raw tail is one incomplete JSONL line; it holds no complete
842
+ // record to recover.
843
+ recoveredTail: [],
844
+ }
845
+ }
846
+ } catch (error: unknown) {
847
+ signal?.throwIfAborted()
848
+ // A parse-time format refusal predates any SessionHeader, so attach the
849
+ // artifact this read actually refused; every other parse failure is
850
+ // committed bytes the decoder cannot interpret — damage, classified for
851
+ // the seam's stable error vocabulary.
852
+ if (error instanceof SessionFormatUnsupportedError) {
853
+ throw new SessionFormatUnsupportedError(`${error.message} (raw log: ${path})`, { kind: 'jsonl', path })
854
+ }
855
+ throw new SessionPersistenceCorruptionError(`session "${expectedId}": stored log is corrupt: ${String(error)} (raw log: ${path})`, { cause: error })
856
+ }
857
+ signal?.throwIfAborted()
858
+ await this.assertStoredIdentity(path, SESSION_FORMAT_VERSION, parsed.meta, expectedId, signal)
859
+ signal?.throwIfAborted()
860
+ assertStoredId(expectedId, parsed.meta)
861
+ const location = this.locate(parsed.meta)
862
+ validateStoredEvents(parsed.meta, parsed.events, location)
863
+ const { events, ...rest } = parsed
864
+ const stored: CurrentStoredLog = {
865
+ status: 'current',
866
+ ...rest,
867
+ ...freezeStoredEvents(events),
868
+ revision,
869
+ }
870
+ this.memoizeStoredLog(expectedId, stored)
871
+ return stored
872
+ }
873
+
874
+ /** Insert one parsed log into the bounded handoff cache. */
875
+ private memoizeStoredLog(id: SessionId, stored: StoredLog): void {
876
+ this.coldLogMemo.delete(id)
877
+ this.coldLogMemo.set(id, stored)
878
+ for (const oldest of this.coldLogMemo.keys()) {
879
+ if (this.coldLogMemo.size <= COLD_LOG_MEMO_MAX_ENTRIES) break
880
+ this.coldLogMemo.delete(oldest)
881
+ }
882
+ }
883
+
884
+ /**
885
+ * Resolve a session's current-generation log path.
886
+ * @param id - the stored session to locate.
887
+ * @param signal - optional cancellation for the directory scans.
888
+ * @returns the current artifact path, or `undefined` while only a historical generation exists.
889
+ */
890
+ async resolveCurrentLog(id: SessionId, signal?: AbortSignal): Promise<string | undefined> {
891
+ await this.ensureRootEncoding()
892
+ signal?.throwIfAborted()
893
+ const selected = await this.findLog(id, signal)
894
+ if (selected === undefined) return undefined
895
+ if (selected.sourceVersion === SESSION_FORMAT_VERSION) return selected.sourcePath
896
+ if (selected.sourceVersion < SESSION_FORMAT_VERSION) return undefined
897
+ const reason = sessionFormatVersionRefusal(id, selected.sourceVersion)
898
+ throw new SessionFormatUnsupportedError(
899
+ `${reason} (raw log: ${selected.sourcePath})`,
900
+ { kind: 'jsonl', path: selected.sourcePath },
901
+ )
902
+ }
903
+
904
+ /**
905
+ * Durably append one validated batch; lazily materializes on the first write.
906
+ * @param header - the session's stored header.
907
+ * @param events - the validated contiguous batch, in seq order.
908
+ * @param isMaterialized - whether the session already has a durable artifact.
909
+ * @param inheritedEventCount - the exact fork-inherited prefix length written into a materializing header line.
910
+ */
911
+ async persistBatch(
912
+ header: SessionHeader,
913
+ events: readonly SessionEvent[],
914
+ isMaterialized: boolean,
915
+ inheritedEventCount: SessionLogOffsetType,
916
+ ): Promise<void> {
917
+ this.coldLogMemo.delete(header.id)
918
+ await this.ensureRootEncoding()
919
+ if (isMaterialized) {
920
+ await this.appendLines(header, events)
921
+ } else {
922
+ await this.materialize(header, inheritedEventCount, events)
923
+ this.tracker.materialized(header.id)
924
+ }
925
+ }
926
+
927
+ /**
928
+ * Materialize a header-only artifact for an explicitly durable empty session.
929
+ * @param header - the session's stored header.
930
+ * @param inheritedEventCount - the exact fork-inherited prefix length written into the header line.
931
+ */
932
+ async persistHeader(header: SessionHeader, inheritedEventCount: SessionLogOffsetType): Promise<void> {
933
+ this.coldLogMemo.delete(header.id)
934
+ await this.ensureRootEncoding()
935
+ await this.materialize(header, inheritedEventCount, [])
936
+ this.tracker.materialized(header.id)
937
+ }
938
+
939
+ /**
940
+ * Truncate a torn physical tail durably before this session's first new append.
941
+ * @param header - the session's stored header.
942
+ * @param truncateTo - the byte offset the artifact is truncated to.
943
+ */
944
+ async truncateTornTail(header: SessionHeader, truncateTo: number): Promise<void> {
945
+ this.coldLogMemo.delete(header.id)
946
+ await this.repair(header, truncateTo)
947
+ this.ctx.logger.warn(`${this.name}: session "${header.id}" recovered from a torn tail; incomplete tail bytes were discarded`)
948
+ }
949
+
950
+ /**
951
+ * Whether this process still tracks a created-but-unmaterialized session.
952
+ * @param id - the session to test.
953
+ * @returns true while the pending entry exists.
954
+ */
955
+ hasPendingSession(id: SessionId): boolean {
956
+ return this.tracker.hasPending(id)
957
+ }
958
+
959
+ /**
960
+ * Release one handle's backend bookkeeping on close.
961
+ * @param handle - the closing handle.
962
+ * @param materialized - whether the session reached durable storage.
963
+ */
964
+ releaseHandle(handle: JsonlSessionHandle, materialized: boolean): void {
965
+ this.tracker.release(handle, materialized)
966
+ }
967
+
968
+ /**
969
+ * Acquire the session directory's kernel write lock; the kernel holds it
970
+ * until the handle's close releases the descriptor, including on process death.
971
+ * @param id - the session the lock guards.
972
+ * @param cwd - header cwd used to derive the directory for a fresh session.
973
+ * @param dir - the resolved directory of an existing artifact, when known.
974
+ * @returns the held lock.
975
+ */
976
+ private acquireLease(id: SessionId, cwd: string | undefined, dir = sessionDir(this.root, cwd, id)): Promise<SessionWriteLease> {
977
+ return SessionWriteLease.acquire(dir, id)
978
+ }
979
+
980
+ /**
981
+ * Acquire the cross-process write lock for a materializing created session,
982
+ * called by its handle immediately before the first log bytes publish.
983
+ * @param header - the session's stored header (its cwd derives the directory).
984
+ * @returns the held lock.
985
+ */
986
+ async acquireWriteLease(header: SessionHeader): Promise<SessionWriteLease> {
987
+ // Refuse an opposite-encoding artifact before the lock's mkdir publishes
988
+ // the session directory — the last moment the directory can be absent.
989
+ await this.rejectOppositeArtifact(header.cwd, header.id)
990
+ return this.acquireLease(header.id, header.cwd)
991
+ }
992
+
993
+ /** Decode complete frames and retain complete JSONL records from a torn final frame. */
994
+ private async readZstdPrefix(
995
+ buffer: Buffer,
996
+ signal?: AbortSignal,
997
+ ): Promise<{
998
+ meta: SessionHeader
999
+ inheritedEventCount: SessionLogOffsetType
1000
+ events: SessionEvent[]
1001
+ tornTruncateTo: number | undefined
1002
+ recoveredTail: SessionEvent[]
1003
+ }> {
1004
+ signal?.throwIfAborted()
1005
+ const { frames, tornStart } = scanZstdFrames(buffer)
1006
+ signal?.throwIfAborted()
1007
+ if (frames.length === 0) throw new Error('empty or header-less Zstandard session log')
1008
+
1009
+ const decoder = createZstdFrameDecoder()
1010
+ let yieldDeadline = performance.now() + ZSTD_DECODE_YIELD_INTERVAL_MS
1011
+ try {
1012
+ const decodedFrames = decoder.decode(buffer, frames)
1013
+ signal?.throwIfAborted()
1014
+ const headerFrame = decodedFrames.next()
1015
+ signal?.throwIfAborted()
1016
+ /* v8 ignore next -- a non-empty structural frame list makes the decoder yield its first frame or throw. */
1017
+ if (headerFrame.done) throw new Error('empty or header-less Zstandard session log')
1018
+ assertZstdHeaderFrame(headerFrame.value)
1019
+ const scanner = new SessionLogScanner(headerFrame.value)
1020
+
1021
+ let remainingFrames = frames.length - 1
1022
+ for (const plaintext of decodedFrames) {
1023
+ signal?.throwIfAborted()
1024
+ scanner.write(plaintext)
1025
+ remainingFrames -= 1
1026
+ if (remainingFrames > 0 && performance.now() >= yieldDeadline) {
1027
+ await scheduler.yield()
1028
+ signal?.throwIfAborted()
1029
+ yieldDeadline = performance.now() + ZSTD_DECODE_YIELD_INTERVAL_MS
1030
+ }
1031
+ }
1032
+ signal?.throwIfAborted()
1033
+ const complete = scanner.checkpoint()
1034
+ if (complete.committedBytes !== complete.inputBytes) {
1035
+ throw new Error('corrupt Zstandard session log: complete frame contains a torn JSONL record')
1036
+ }
1037
+ if (tornStart === undefined) {
1038
+ const prefix = scanner.finish()
1039
+ return {
1040
+ meta: prefix.meta,
1041
+ inheritedEventCount: prefix.inheritedEventCount,
1042
+ events: prefix.events,
1043
+ tornTruncateTo: undefined,
1044
+ recoveredTail: [],
1045
+ }
1046
+ }
1047
+ // A torn final frame's append never resolved, but complete JSONL records
1048
+ // already flushed into it are real emitted events: recover them, and let
1049
+ // the write path truncate the torn bytes and rewrite them durably.
1050
+ let recoveredPlaintext: Buffer = Buffer.alloc(0)
1051
+ try {
1052
+ signal?.throwIfAborted()
1053
+ recoveredPlaintext = await decompressZstdPrefix(buffer.subarray(tornStart))
1054
+ } catch {
1055
+ /* v8 ignore next -- decoder failure plus concurrent abort is timing-dependent */
1056
+ if (signal?.aborted) signal.throwIfAborted()
1057
+ // A structurally incomplete final frame may end before Node's decoder
1058
+ // can emit any plaintext; the complete prior frames remain recoverable.
1059
+ }
1060
+ signal?.throwIfAborted()
1061
+ scanner.write(recoveredPlaintext)
1062
+ const prefix = scanner.finish()
1063
+ return {
1064
+ meta: prefix.meta,
1065
+ inheritedEventCount: prefix.inheritedEventCount,
1066
+ events: prefix.events,
1067
+ tornTruncateTo: tornStart,
1068
+ recoveredTail: prefix.events.slice(complete.eventCount),
1069
+ }
1070
+ } catch (error) {
1071
+ /* v8 ignore next -- decoder failure plus concurrent abort is timing-dependent */
1072
+ if (signal?.aborted) signal.throwIfAborted()
1073
+ throw error
1074
+ } finally {
1075
+ decoder.close()
1076
+ }
1077
+ }
1078
+
1079
+ /** Enumerate selected physical generations without interpreting their headers or bodies. */
1080
+ private async listGenerations(signal?: AbortSignal): Promise<ResolvedJsonlGeneration[]> {
1081
+ const selected = await this.mapSessionDirectories((dir) => {
1082
+ signal?.throwIfAborted()
1083
+ return this.resolveGenerationInDirectory(dir, signal)
1084
+ }, signal)
1085
+ return selected.filter(source => source !== undefined)
1086
+ }
1087
+
1088
+ /**
1089
+ * Apply `task` to every Session directory through the shared listing
1090
+ * limiter. Results and the first failure follow the sequential
1091
+ * project-then-directory order; a project whose listing fails ends the
1092
+ * traversal after the directories of the projects before it.
1093
+ * @param task - per-directory operation; must not wait on the listing limiter.
1094
+ * @param signal - optional cancellation for directory listings.
1095
+ * @returns per-directory results in traversal order.
1096
+ */
1097
+ private async mapSessionDirectories<R>(
1098
+ task: (dir: string) => Promise<R>,
1099
+ signal?: AbortSignal,
1100
+ ): Promise<R[]> {
1101
+ const limit = this.listLimit
1102
+ // The root read counts against the same bound as every other listing read.
1103
+ const projectDirs = await limit(() => this.listProjectDirs(signal))
1104
+ const projects = await settleLimited(limit, projectDirs, project => this.listSessionDirs(project, signal))
1105
+ const dirs: string[] = []
1106
+ let projectFailure: PromiseRejectedResult | undefined
1107
+ for (const outcome of projects) {
1108
+ if (outcome.status === 'rejected') {
1109
+ projectFailure = outcome
1110
+ break
1111
+ }
1112
+ // Appended one by one: spreading a large project as call arguments exceeds the engine's argument limit.
1113
+ for (const dir of outcome.value) dirs.push(dir)
1114
+ }
1115
+ const results = settledValues(await settleLimited(limit, dirs, task))
1116
+ if (projectFailure !== undefined) throw projectFailure.reason
1117
+ return results
1118
+ }
1119
+
1120
+ /** Historical logical events depend on the corpus, including members with unreadable headers. */
1121
+ private async historicalCorpusRevision(signal?: AbortSignal): Promise<string> {
1122
+ const paths = (await this.listGenerations(signal)).map(source => source.sourcePath).sort()
1123
+ const entries = settledValues(await settleLimited(this.listLimit, paths, async (path) => {
1124
+ signal?.throwIfAborted()
1125
+ try {
1126
+ return { path, revision: fileRevision(await stat(path, { bigint: true })) }
1127
+ } catch (error: unknown) {
1128
+ if (!isENOENT(error)) throw error
1129
+ return { path, revision: 'missing' }
1130
+ }
1131
+ }))
1132
+ const hash = createHash('sha256')
1133
+ for (const { path, revision } of entries) hash.update(JSON.stringify([path, revision]))
1134
+ signal?.throwIfAborted()
1135
+ return hash.digest('hex')
1136
+ }
1137
+
1138
+ private async listArtifacts(
1139
+ signal?: AbortSignal,
1140
+ ): Promise<Array<GenerationHeader & { path: string; sourceVersion: number }>> {
1141
+ signal?.throwIfAborted()
1142
+ await this.ensureRootEncoding()
1143
+ signal?.throwIfAborted()
1144
+ const generations = await this.listGenerations(signal)
1145
+ const headers = await settleLimited(this.listLimit, generations, async (selected) => {
1146
+ signal?.throwIfAborted()
1147
+ try {
1148
+ return { selected, metadata: await this.readGenerationHeader(selected, undefined, signal) }
1149
+ } catch (error: unknown) {
1150
+ if (error instanceof SessionFormatUnsupportedError || error instanceof SessionPersistenceCorruptionError) {
1151
+ return { selected, metadata: undefined }
1152
+ }
1153
+ throw error
1154
+ }
1155
+ })
1156
+ const artifacts: Array<GenerationHeader & { path: string; sourceVersion: number }> = []
1157
+ const ids = new Set<SessionId>()
1158
+ for (const outcome of headers) {
1159
+ if (outcome.status === 'rejected') throw outcome.reason
1160
+ const { selected, metadata } = outcome.value
1161
+ if (metadata === undefined) continue
1162
+ if (ids.has(metadata.header.id)) {
1163
+ throw new Error(`duplicate JSONL session id "${metadata.header.id}" appears in multiple project directories`)
1164
+ }
1165
+ ids.add(metadata.header.id)
1166
+ artifacts.push({ ...metadata, path: selected.sourcePath, sourceVersion: selected.sourceVersion })
1167
+ }
1168
+ signal?.throwIfAborted()
1169
+ return artifacts
1170
+ }
1171
+
1172
+ /** Read and translate one selected generation header without inspecting its body. */
1173
+ private async readGenerationHeader(
1174
+ selected: ResolvedJsonlGeneration,
1175
+ expectedId?: SessionId,
1176
+ signal?: AbortSignal,
1177
+ ): Promise<GenerationHeader | undefined> {
1178
+ let first: string | undefined
1179
+ try {
1180
+ first = this.compression === 'zstd'
1181
+ ? await this.readFirstZstdLine(selected.sourcePath, signal)
1182
+ : await this.readFirstLine(selected.sourcePath, signal)
1183
+ } catch (error: unknown) {
1184
+ signal?.throwIfAborted()
1185
+ if (isENOENT(error)) return undefined
1186
+ throw error
1187
+ }
1188
+ signal?.throwIfAborted()
1189
+ if (first === undefined) return undefined
1190
+ let value: unknown
1191
+ try {
1192
+ value = JSON.parse(first)
1193
+ } catch {
1194
+ return undefined
1195
+ }
1196
+ assertNoRetiredHeaderFields(value)
1197
+ const result = sessionFormatCatalog.readHeader(value)
1198
+ if ('storedVersion' in result && result.storedVersion !== selected.sourceVersion) {
1199
+ throw new Error(
1200
+ `session generation filename identifies v${selected.sourceVersion}, `
1201
+ + `but its header identifies v${result.storedVersion}`,
1202
+ )
1203
+ }
1204
+ if (result.status === 'unsupported') {
1205
+ const physicalId = String((value as { id?: unknown }).id)
1206
+ let reason = result.reason
1207
+ /* v8 ignore else -- released historical header migrations cannot refuse after physical decoding. */
1208
+ if (result.storedVersion > SESSION_FORMAT_VERSION) {
1209
+ reason = sessionFormatVersionRefusal(physicalId, result.storedVersion)
1210
+ }
1211
+ throw new SessionFormatUnsupportedError(
1212
+ `${reason} (raw log: ${selected.sourcePath})`,
1213
+ { kind: 'jsonl', path: selected.sourcePath },
1214
+ )
1215
+ }
1216
+ if (result.status === 'malformed') return undefined
1217
+ const header = this.currentHeader(result.header)
1218
+ await this.assertStoredIdentity(
1219
+ selected.sourcePath,
1220
+ selected.sourceVersion,
1221
+ header,
1222
+ expectedId,
1223
+ signal,
1224
+ )
1225
+ return {
1226
+ header,
1227
+ formatStatus: result.status,
1228
+ }
1229
+ }
1230
+
1231
+ /** Convert format-catalog string identities to current branded Session metadata. */
1232
+ private currentHeader(header: {
1233
+ readonly version: number
1234
+ readonly id: string
1235
+ readonly createdAt: number
1236
+ readonly cwd?: string
1237
+ readonly parentSession?: string
1238
+ readonly isSeeded: boolean
1239
+ readonly origin?: 'subagent'
1240
+ readonly delegationDepth: number
1241
+ readonly agentPreset?: string
1242
+ }): SessionHeader {
1243
+ /* v8 ignore next 3 -- readable catalog results are restored to its configured current version. */
1244
+ if (header.version !== SESSION_FORMAT_VERSION) {
1245
+ throw new Error(`format catalog returned non-current logical header v${header.version}`)
1246
+ }
1247
+ return {
1248
+ version: SESSION_FORMAT_VERSION,
1249
+ id: makeSessionId(header.id),
1250
+ createdAt: header.createdAt,
1251
+ ...(header.cwd === undefined ? {} : { cwd: header.cwd }),
1252
+ ...(header.parentSession === undefined
1253
+ ? {}
1254
+ : { parentSession: makeSessionId(header.parentSession) }),
1255
+ isSeeded: header.isSeeded,
1256
+ ...(header.origin === undefined ? {} : { origin: header.origin }),
1257
+ delegationDepth: header.delegationDepth,
1258
+ ...(header.agentPreset === undefined ? {} : { agentPreset: header.agentPreset }),
1259
+ }
1260
+ }
1261
+
1262
+ // --- materialization / append / repair (file mechanics) ---
1263
+
1264
+ /** Atomically write the header line + first batch (temp-write, fsync, publish). */
1265
+ private async materialize(
1266
+ meta: SessionHeader,
1267
+ inheritedEventCount: SessionLogOffsetType,
1268
+ events: readonly SessionEvent[],
1269
+ ): Promise<void> {
1270
+ const project = projectDir(this.root, meta.cwd)
1271
+ const dir = sessionDir(this.root, meta.cwd, meta.id)
1272
+ const finalPath = logPath(this.root, meta.cwd, meta.id, this.compression)
1273
+ await this.rejectOppositeArtifact(meta.cwd, meta.id)
1274
+ const content = await this.encodeMaterialization(meta, inheritedEventCount, events)
1275
+ /* v8 ignore next -- native Windows coverage exercises this platform dispatch; Linux covers the POSIX peer */
1276
+ if (process.platform === 'win32') {
1277
+ await this.materializeWin32(project, dir, finalPath, meta.id, content)
1278
+ } else {
1279
+ await this.materializePosix(project, dir, finalPath, meta.id, content)
1280
+ }
1281
+ }
1282
+
1283
+ /* v8 ignore start -- Windows uses the Win32 durable-publish path; POSIX coverage exercises this peer. */
1284
+ private async materializePosix(
1285
+ project: string,
1286
+ dir: string,
1287
+ finalPath: string,
1288
+ id: SessionId,
1289
+ content: Buffer | string,
1290
+ ): Promise<void> {
1291
+ await mkdir(this.root, { recursive: true, mode: 0o700 })
1292
+ await this.syncDirPosix(dirname(this.root))
1293
+ await mkdir(project, { recursive: true, mode: 0o700 })
1294
+ await this.syncDirPosix(this.root)
1295
+ await mkdir(dir, { recursive: true, mode: 0o700 })
1296
+ await this.syncDirPosix(project)
1297
+ await this.rejectExistingLog(finalPath, id)
1298
+ const tmp = await this.writeSyncedTempFile(finalPath, content)
1299
+ // Publish via link()+unlink(), NOT rename(): link fails with EEXIST if the
1300
+ // final path already exists, so two processes materializing the same id
1301
+ // concurrently cannot clobber each other. rename() would silently overwrite.
1302
+ let linked = false
1303
+ try {
1304
+ await link(tmp, finalPath)
1305
+ linked = true
1306
+ } finally {
1307
+ // Remove an unpublished temp on failure. After publication, defer cleanup
1308
+ // until the directory entry is durable so cleanup cannot reject a live log.
1309
+ /* v8 ignore next -- link failure is the TOCTOU/IO race guarded above; not reachable in test */
1310
+ if (!linked) await rm(tmp, { force: true })
1311
+ }
1312
+ // link() succeeded — the log is published. fsync the directory so the new
1313
+ // entry survives a power loss: the new link is not crash-durable until the
1314
+ // parent directory's metadata is synced.
1315
+ await this.syncDirPosix(dir)
1316
+ // Best-effort temp cleanup: the log is already published and durable, so a
1317
+ // failure to remove the redundant temp hard link must NOT reject the
1318
+ // append. Swallow only the rm failure; nothing else of consequence runs here.
1319
+ try {
1320
+ await rm(tmp, { force: true })
1321
+ } catch {
1322
+ /* v8 ignore next -- redundant temp link; publish already durable, rm failure is an unreachable IO edge */
1323
+ }
1324
+ }
1325
+ /* v8 ignore stop */
1326
+
1327
+ /* v8 ignore start -- native Windows coverage exercises this integration path */
1328
+ private async materializeWin32(
1329
+ project: string,
1330
+ dir: string,
1331
+ finalPath: string,
1332
+ id: SessionId,
1333
+ content: Buffer | string,
1334
+ ): Promise<void> {
1335
+ await ensureDurableDirectoryWin32(this.root)
1336
+ await ensureDurableDirectoryWin32(project)
1337
+ await ensureDurableDirectoryWin32(dir)
1338
+ await this.rejectExistingLog(finalPath, id)
1339
+ const tmp = await this.writeSyncedTempFile(finalPath, content)
1340
+ try {
1341
+ await publishNewFileWin32(tmp, finalPath)
1342
+ } catch (error) {
1343
+ await rm(tmp, { force: true })
1344
+ throw error
1345
+ }
1346
+ }
1347
+ /* v8 ignore stop */
1348
+
1349
+ private async rejectExistingLog(finalPath: string, id: SessionId): Promise<void> {
1350
+ // Never publish over an existing committed log: materialize is the first
1351
+ // write of a session the backend believes is new. A file here means a
1352
+ // different session shares this id on disk — reject loudly. (create already
1353
+ // guards the create path, so this is unreachable-in-practice TOCTOU
1354
+ // defense.)
1355
+ /* v8 ignore next 3 -- create guards collisions before materialize; this is a TOCTOU backstop */
1356
+ if (await this.resolveGenerationInDirectory(dirname(finalPath)) !== undefined) {
1357
+ throw new Error(`refusing to materialize "${id}": a log already exists on disk (open it instead)`)
1358
+ }
1359
+ }
1360
+
1361
+ private async writeSyncedTempFile(finalPath: string, content: Buffer | string): Promise<string> {
1362
+ const tmp = `${finalPath}.${randomBytes(6).toString('hex')}.tmp`
1363
+ const handle = await open(tmp, 'wx', 0o600)
1364
+ try {
1365
+ await handle.writeFile(content)
1366
+ await handle.sync()
1367
+ } finally {
1368
+ await handle.close()
1369
+ }
1370
+ return tmp
1371
+ }
1372
+
1373
+ /** Encode the header and first batch without combining their frame boundaries. */
1374
+ private async encodeMaterialization(
1375
+ meta: SessionHeader,
1376
+ inheritedEventCount: SessionLogOffsetType,
1377
+ events: readonly SessionEvent[],
1378
+ ): Promise<Buffer | string> {
1379
+ const header = JSON.stringify(toHeaderLine(meta, meta.isSeeded ? inheritedEventCount : undefined)) + '\n'
1380
+ if (events.length === 0) {
1381
+ return this.compression === 'none' ? header : compressZstdFrame(header)
1382
+ }
1383
+ const body = eventLines(events) + '\n'
1384
+ if (this.compression === 'none') return header + body
1385
+ const headerFrame = await compressZstdFrame(header)
1386
+ const eventFrame = await compressZstdFrame(body)
1387
+ return Buffer.concat([headerFrame, eventFrame])
1388
+ }
1389
+
1390
+ /** Encode one durable append batch in the configured physical representation. */
1391
+ private async encodeEventBatch(events: readonly SessionEvent[]): Promise<Buffer | string> {
1392
+ const body = eventLines(events) + '\n'
1393
+ return this.compression === 'zstd' ? compressZstdFrame(body) : body
1394
+ }
1395
+
1396
+ /** fsync a POSIX directory so a just-created/renamed entry is crash-durable. */
1397
+ /* v8 ignore start -- Windows uses write-through namespace operations; POSIX coverage exercises directory fsync. */
1398
+ private async syncDirPosix(dir: string): Promise<void> {
1399
+ const handle = await open(dir, 'r')
1400
+ try {
1401
+ await handle.sync()
1402
+ } finally {
1403
+ await handle.close()
1404
+ }
1405
+ }
1406
+ /* v8 ignore stop */
1407
+
1408
+ /**
1409
+ * Append and fsync event lines. On a partial write or sync failure, restore the
1410
+ * previous size before rethrowing because the unchanged cursor will retry the
1411
+ * batch; leaving partial bytes would create duplicate sequence numbers.
1412
+ */
1413
+ private async appendLines(meta: SessionHeader, events: readonly SessionEvent[]): Promise<void> {
1414
+ const content = await this.encodeEventBatch(events)
1415
+ const path = logPath(this.root, meta.cwd, meta.id, this.compression)
1416
+ const handle = await open(path, 'a')
1417
+ let closed = false
1418
+ const closeAppendHandle = async (): Promise<void> => {
1419
+ if (closed) return
1420
+ closed = true
1421
+ await handle.close()
1422
+ }
1423
+
1424
+ try {
1425
+ const { size: before } = await handle.stat()
1426
+ try {
1427
+ await handle.writeFile(content)
1428
+ await handle.sync()
1429
+ } catch (error) {
1430
+ try {
1431
+ await closeAppendHandle()
1432
+ await this.rollbackAppend(path, before)
1433
+ } catch (rollbackError) {
1434
+ throw new AggregateError([error, rollbackError], `failed to roll back append to "${path}"`)
1435
+ }
1436
+ throw error
1437
+ }
1438
+ } finally {
1439
+ await closeAppendHandle()
1440
+ }
1441
+ }
1442
+
1443
+ private async rollbackAppend(path: string, size: number): Promise<void> {
1444
+ const handle = await open(path, 'r+')
1445
+ try {
1446
+ await handle.truncate(size)
1447
+ await handle.sync()
1448
+ } finally {
1449
+ await handle.close()
1450
+ }
1451
+ }
1452
+
1453
+ /** Truncate the log file to `offset` bytes and fsync (discard the crash tail). */
1454
+ private async repair(meta: SessionHeader, offset: number): Promise<void> {
1455
+ const path = logPath(this.root, meta.cwd, meta.id, this.compression)
1456
+ await truncate(path, offset)
1457
+ const handle = await open(path, 'r+')
1458
+ try {
1459
+ await handle.sync()
1460
+ } finally {
1461
+ await handle.close()
1462
+ }
1463
+ }
1464
+
1465
+ // --- discovery helpers ---
1466
+
1467
+ /**
1468
+ * Read the first newline-terminated line of a file without loading the whole
1469
+ * file. Returns undefined if the file is empty or has no complete first line.
1470
+ * Reads in bounded chunks so a huge log costs only the header read.
1471
+ */
1472
+ private async readFirstLine(path: string, signal?: AbortSignal): Promise<string | undefined> {
1473
+ signal?.throwIfAborted()
1474
+ const handle = await open(path, 'r')
1475
+ try {
1476
+ signal?.throwIfAborted()
1477
+ const chunks: Buffer[] = []
1478
+ const buf = Buffer.alloc(8192)
1479
+ for (;;) {
1480
+ signal?.throwIfAborted()
1481
+ const { bytesRead } = await handle.read(buf, 0, buf.length, null)
1482
+ signal?.throwIfAborted()
1483
+ if (bytesRead === 0) return undefined // EOF with no newline → no complete line
1484
+ const slice = buf.subarray(0, bytesRead)
1485
+ const nl = slice.indexOf(0x0a)
1486
+ if (nl !== -1) {
1487
+ chunks.push(slice.subarray(0, nl))
1488
+ signal?.throwIfAborted()
1489
+ return Buffer.concat(chunks).toString('utf8')
1490
+ }
1491
+ chunks.push(Buffer.from(slice))
1492
+ }
1493
+ } finally {
1494
+ await handle.close()
1495
+ }
1496
+ }
1497
+
1498
+ /** Read only the header frame; compression failures reject as corruption, while I/O and cancellation propagate. */
1499
+ private async readFirstZstdLine(path: string, signal?: AbortSignal): Promise<string | undefined> {
1500
+ signal?.throwIfAborted()
1501
+ const handle = await open(path, 'r')
1502
+ try {
1503
+ signal?.throwIfAborted()
1504
+ let content = Buffer.alloc(0)
1505
+ const chunk = Buffer.alloc(8192)
1506
+ for (;;) {
1507
+ signal?.throwIfAborted()
1508
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null)
1509
+ signal?.throwIfAborted()
1510
+ if (bytesRead === 0) return undefined
1511
+ signal?.throwIfAborted()
1512
+ content = Buffer.concat([content, chunk.subarray(0, bytesRead)])
1513
+ signal?.throwIfAborted()
1514
+ try {
1515
+ const first = scanZstdFrames(content, 1).frames[0]
1516
+ if (first === undefined) continue
1517
+ const plaintext = await decompressZstdFrame(content.subarray(first.start, first.end))
1518
+ signal?.throwIfAborted()
1519
+ assertZstdHeaderFrame(plaintext)
1520
+ return plaintext.subarray(0, -1).toString('utf8')
1521
+ } catch (error) {
1522
+ /* v8 ignore next -- decoder failure plus concurrent abort is timing-dependent */
1523
+ if (signal?.aborted) signal.throwIfAborted()
1524
+ throw new SessionPersistenceCorruptionError(
1525
+ `corrupt Zstandard session log: header frame failed validation: ${String(error)} (raw log: ${path})`,
1526
+ { cause: error },
1527
+ )
1528
+ }
1529
+ }
1530
+ } finally {
1531
+ await handle.close()
1532
+ }
1533
+ }
1534
+
1535
+ /** Select the numerically highest canonical generation in one Session directory. */
1536
+ private async resolveGenerationInDirectory(
1537
+ dir: string,
1538
+ signal?: AbortSignal,
1539
+ ): Promise<ResolvedJsonlGeneration | undefined> {
1540
+ signal?.throwIfAborted()
1541
+ let entries: Dirent[]
1542
+ try {
1543
+ entries = await readdir(dir, { withFileTypes: true })
1544
+ } catch (error: unknown) {
1545
+ if (isENOENT(error)) return undefined
1546
+ throw error
1547
+ }
1548
+ signal?.throwIfAborted()
1549
+ const generations: Array<{ readonly path: string; readonly version: number }> = []
1550
+ const opposite: string[] = []
1551
+ for (const entry of entries) {
1552
+ const version = parseGenerationLogFilename(entry.name, this.compression)
1553
+ if (version !== undefined) {
1554
+ generations.push({ path: join(dir, entry.name), version })
1555
+ continue
1556
+ }
1557
+ if (parseGenerationLogFilename(entry.name, this.oppositeCompression()) !== undefined) {
1558
+ opposite.push(join(dir, entry.name))
1559
+ }
1560
+ }
1561
+ if (opposite.length > 0) throw this.encodingMismatch(opposite[0] as string)
1562
+ const latest = generations.sort((left, right) => right.version - left.version)[0]
1563
+ if (latest === undefined) return undefined
1564
+ return {
1565
+ sourcePath: latest.path,
1566
+ sourceVersion: latest.version,
1567
+ currentPath: join(
1568
+ dir,
1569
+ generationLogFilename(sessionFormatCatalog.currentVersion, this.compression),
1570
+ ),
1571
+ }
1572
+ }
1573
+
1574
+ /** Find the unique authoritative generation for an id across project directories. */
1575
+ private async findLog(id: SessionId, signal?: AbortSignal): Promise<ResolvedJsonlGeneration | undefined> {
1576
+ const matches: ResolvedJsonlGeneration[] = []
1577
+ for (const project of await this.listProjectDirs(signal)) {
1578
+ signal?.throwIfAborted()
1579
+ await this.rejectLegacyFlatArtifact(project, id, signal)
1580
+ signal?.throwIfAborted()
1581
+ const dir = join(project, encodeSegment(id))
1582
+ const selected = await this.resolveGenerationInDirectory(dir, signal)
1583
+ if (selected !== undefined) matches.push(selected)
1584
+ }
1585
+ if (matches.length > 1) {
1586
+ throw new Error(`duplicate JSONL session id "${id}" appears in multiple project directories`)
1587
+ }
1588
+ signal?.throwIfAborted()
1589
+ return matches[0]
1590
+ }
1591
+
1592
+ /** Require an existing configured root to be a readable directory. */
1593
+ private assertUsableRoot(): void {
1594
+ try {
1595
+ readdirSync(this.root)
1596
+ } catch (error) {
1597
+ if (isENOENT(error)) return
1598
+ throw error
1599
+ }
1600
+ }
1601
+
1602
+ /** Reject metadata that does not identify the selected physical log. */
1603
+ private async assertStoredIdentity(
1604
+ path: string,
1605
+ storedVersion: number,
1606
+ meta: SessionHeader,
1607
+ expectedId?: SessionId,
1608
+ signal?: AbortSignal,
1609
+ ): Promise<void> {
1610
+ signal?.throwIfAborted()
1611
+ if (expectedId !== undefined && meta.id !== expectedId) {
1612
+ throw new Error(`corrupt session log "${path}": requested id "${expectedId}" does not match header id "${meta.id}"`)
1613
+ }
1614
+ let expectedPath: string
1615
+ try {
1616
+ expectedPath = generationLogPath(
1617
+ this.root,
1618
+ meta.cwd,
1619
+ meta.id,
1620
+ storedVersion,
1621
+ this.compression,
1622
+ )
1623
+ } catch (error) {
1624
+ throw new Error(`corrupt session log "${path}": header id cannot name a storage path`, { cause: error })
1625
+ }
1626
+ if (path !== expectedPath && !await this.sameFile(path, expectedPath, signal)) {
1627
+ throw new Error(`corrupt session log "${path}": header id "${meta.id}" and cwd identify "${expectedPath}"`)
1628
+ }
1629
+ signal?.throwIfAborted()
1630
+ }
1631
+
1632
+ /** Validate a supported historical header against the selected source path. */
1633
+ private validateSourceIdentity(
1634
+ selected: ResolvedJsonlGeneration,
1635
+ headerValue: Readonly<Record<string, unknown>>,
1636
+ expectedId: SessionId,
1637
+ signal?: AbortSignal,
1638
+ ): void | Promise<void> {
1639
+ const result = sessionFormatCatalog.readHeader(headerValue)
1640
+ if (result.status !== 'current' && result.status !== 'migration-required') return
1641
+ return this.assertStoredIdentity(
1642
+ selected.sourcePath,
1643
+ selected.sourceVersion,
1644
+ this.currentHeader(result.header),
1645
+ expectedId,
1646
+ signal,
1647
+ )
1648
+ }
1649
+
1650
+ /**
1651
+ * Whether two path spellings resolve to the same physical file. This admits
1652
+ * case aliases on case-insensitive filesystems without weakening identity
1653
+ * checks on case-sensitive stores.
1654
+ */
1655
+ private async sameFile(path: string, expectedPath: string, signal?: AbortSignal): Promise<boolean> {
1656
+ signal?.throwIfAborted()
1657
+ try {
1658
+ const [actual, expected] = await Promise.all([realpath(path), realpath(expectedPath)])
1659
+ signal?.throwIfAborted()
1660
+ return actual === expected
1661
+ } catch (error) {
1662
+ signal?.throwIfAborted()
1663
+ /* v8 ignore else -- non-ENOENT realpath failures require an external permission or I/O fault */
1664
+ if (isENOENT(error)) return false
1665
+ /* v8 ignore next -- non-ENOENT realpath failures are external I/O faults, propagated unchanged */
1666
+ throw error
1667
+ }
1668
+ }
1669
+
1670
+ /** The human-readable project directories under the configured root. */
1671
+ private async listProjectDirs(signal?: AbortSignal): Promise<string[]> {
1672
+ try {
1673
+ signal?.throwIfAborted()
1674
+ const entries = await readdir(this.root, { withFileTypes: true })
1675
+ signal?.throwIfAborted()
1676
+ return entries.filter(e => e.isDirectory()).map(e => join(this.root, e.name))
1677
+ } catch (error) {
1678
+ // Only an absent root means no sessions; rethrow every other I/O failure.
1679
+ if (isENOENT(error)) return []
1680
+ throw error
1681
+ }
1682
+ }
1683
+
1684
+ /** List session-owned directories and reject the obsolete flat-file layout. */
1685
+ private async listSessionDirs(project: string, signal?: AbortSignal): Promise<string[]> {
1686
+ signal?.throwIfAborted()
1687
+ const entries = await readdir(project, { withFileTypes: true })
1688
+ signal?.throwIfAborted()
1689
+ const legacy = entries.find(entry =>
1690
+ entry.isFile() && (entry.name.endsWith('.jsonl') || entry.name.endsWith('.jsonl.zstd')))
1691
+ if (legacy !== undefined) throw this.legacyLayout(join(project, legacy.name))
1692
+ return entries.filter(entry => entry.isDirectory()).map(entry => join(project, entry.name))
1693
+ }
1694
+
1695
+ /** Reject a root that already belongs to the other physical encoding. */
1696
+ private ensureRootEncoding(): Promise<void> {
1697
+ this.rootEncodingCheck ??= this.checkRootEncoding()
1698
+ return this.rootEncodingCheck
1699
+ }
1700
+
1701
+ private async checkRootEncoding(): Promise<void> {
1702
+ await this.mapSessionDirectories(async (dir) => {
1703
+ const incompatible = await this.findOppositeGenerationInDirectory(dir)
1704
+ if (incompatible !== undefined) throw this.encodingMismatch(incompatible)
1705
+ })
1706
+ }
1707
+
1708
+ private async rejectLegacyFlatArtifact(
1709
+ project: string,
1710
+ id: SessionId,
1711
+ signal?: AbortSignal,
1712
+ ): Promise<void> {
1713
+ signal?.throwIfAborted()
1714
+ const encoded = encodeSegment(id)
1715
+ for (const compression of ['zstd', 'none'] as const) {
1716
+ const path = join(project, encoded + logSuffix(compression))
1717
+ const artifactExists = await this.exists(path)
1718
+ signal?.throwIfAborted()
1719
+ if (artifactExists) throw this.legacyLayout(path)
1720
+ }
1721
+ }
1722
+
1723
+ private async rejectOppositeArtifact(cwd: string | undefined, id: SessionId): Promise<void> {
1724
+ const path = await this.findOppositeGenerationInDirectory(sessionDir(this.root, cwd, id))
1725
+ if (path !== undefined) throw this.encodingMismatch(path)
1726
+ }
1727
+
1728
+ /** Return the highest canonical generation encoded with the other configured suffix. */
1729
+ private async findOppositeGenerationInDirectory(dir: string): Promise<string | undefined> {
1730
+ let entries: Dirent[]
1731
+ try {
1732
+ entries = await readdir(dir, { withFileTypes: true })
1733
+ } catch (error: unknown) {
1734
+ if (isENOENT(error)) return undefined
1735
+ throw error
1736
+ }
1737
+ const generations: Array<{ readonly name: string; readonly version: number }> = []
1738
+ for (const entry of entries) {
1739
+ const version = parseGenerationLogFilename(entry.name, this.oppositeCompression())
1740
+ if (version !== undefined) generations.push({ name: entry.name, version })
1741
+ }
1742
+ const latest = generations.sort((left, right) => right.version - left.version)[0]
1743
+ return latest === undefined ? undefined : join(dir, latest.name)
1744
+ }
1745
+
1746
+ private oppositeCompression(): JsonlCompression {
1747
+ return this.compression === 'zstd' ? 'none' : 'zstd'
1748
+ }
1749
+
1750
+ private encodingMismatch(path: string): Error {
1751
+ return new Error(
1752
+ `session artifact ${JSON.stringify(path)} uses ${logSuffix(this.oppositeCompression())}, `
1753
+ + `but this backend is configured for compression ${JSON.stringify(this.compression)}; `
1754
+ + 'use a separate root or select the matching compression mode',
1755
+ )
1756
+ }
1757
+
1758
+ private legacyLayout(path: string): Error {
1759
+ return new Error(
1760
+ `session artifact ${JSON.stringify(path)} uses the unsupported flat-file layout; `
1761
+ + 'use a separate root or move it into a project/session directory before loading',
1762
+ )
1763
+ }
1764
+
1765
+ private async exists(path: string): Promise<boolean> {
1766
+ try {
1767
+ const handle = await open(path, 'r')
1768
+ await handle.close()
1769
+ return true
1770
+ } catch (error) {
1771
+ // Only ENOENT means absent. A permission/I/O error must surface rather
1772
+ // than letting load or collision checks proceed under false absence.
1773
+ /* v8 ignore else -- Windows reports file-valued parents as ENOENT; POSIX covers direct ENOTDIR. */
1774
+ if (isENOENT(error)) {
1775
+ // Windows reports ENOENT, not ENOTDIR, for `regular-file/child`, so it
1776
+ // alone verifies the immediate parent to keep a blocked session
1777
+ // directory a storage fault. POSIX open already reported ENOTDIR before
1778
+ // this point, where the extra stat would only cost a syscall per probe.
1779
+ /* v8 ignore next -- native Windows coverage exercises this platform dispatch; POSIX reports ENOTDIR from open */
1780
+ if (process.platform === 'win32') await this.assertLogParentAllowsAbsence(path)
1781
+ return false
1782
+ }
1783
+ /* v8 ignore next -- Windows repairs ENOTDIR from ENOENT above; POSIX covers direct ENOTDIR. */
1784
+ throw error
1785
+ }
1786
+ }
1787
+
1788
+ /* v8 ignore start -- native Windows coverage exercises this repair; POSIX open reports ENOTDIR before this point. */
1789
+ private async assertLogParentAllowsAbsence(path: string): Promise<void> {
1790
+ try {
1791
+ const parent = dirname(path)
1792
+ const info = await stat(parent)
1793
+ if (info.isDirectory()) return
1794
+ const error = new Error(`ENOTDIR: parent path exists but is not a directory: ${parent}`) as NodeJS.ErrnoException
1795
+ error.code = 'ENOTDIR'
1796
+ error.path = parent
1797
+ throw error
1798
+ } catch (error) {
1799
+ if (isENOENT(error)) return
1800
+ throw error
1801
+ }
1802
+ }
1803
+ /* v8 ignore stop */
1804
+ }
1805
+
1806
+ /** JSONL persistence plugin label. */
1807
+ export const name = 'session-persistence-jsonl'
1808
+
1809
+ /** Loader schema for the backend's root, physical encoding, and listing concurrency. */
1810
+ export const Config: z<Config> = z.object({
1811
+ root: z.string().required(),
1812
+ compression: JsonlCompressionSchema,
1813
+ listConcurrency: z.natural().min(1).default(DEFAULT_LIST_CONCURRENCY),
1814
+ })
1815
+
1816
+ /**
1817
+ * Mount persistence with live routing and handles retained through the
1818
+ * consumer unloads triggered by removing this provider. Consumers must own
1819
+ * cleanup in their injecting scope; concurrent root disposal is not ordered.
1820
+ * @param ctx - the owning plugin context.
1821
+ * @param config - the storage root, physical encoding, and listing concurrency.
1822
+ * @returns resolves when the service is ready.
1823
+ */
1824
+ export async function apply(ctx: Context, config: Config): Promise<void> {
1825
+ let service!: Fiber
1826
+ // Keep this generator synchronous so thenable disposers are registered as functions, not awaited.
1827
+ ctx.effect(function* () {
1828
+ const tracker = new JsonlBackendTracker(name)
1829
+ yield tracker.install(ctx)
1830
+ service = ctx.plugin({
1831
+ name: 'session-persistence-jsonl-service',
1832
+ apply(serviceCtx: Context) {
1833
+ new JsonlSessionPersistence(serviceCtx, config, tracker)
1834
+ },
1835
+ })
1836
+ yield service.dispose
1837
+ }, 'session-persistence-jsonl resources')
1838
+ await service.await()
1839
+ }