@deepseek-ai/dsh-session-persistence-jsonl 0.2.2-rc.1 → 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 +14 -11
  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
@@ -0,0 +1,92 @@
1
+ /** Collect historical discovery facts without recursively preparing related current generations. */
2
+
3
+ import { stat } from 'node:fs/promises'
4
+ import { basename } from 'node:path'
5
+ import { historicalSessionFormatCatalog, sessionFormatCatalog } from '@deepseek-ai/dsh-session-format-catalog'
6
+ import { historicalChildCatalogSource } from '@deepseek-ai/dsh-session-format-v3-to-v4'
7
+ import { SessionFormatUnsupportedMigrationError } from '@deepseek-ai/dsh-session-format'
8
+ import type { SessionFormatJsonObject } from '@deepseek-ai/dsh-session-format'
9
+ import type { SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
10
+ import { parseGenerationLogFilename } from './format.ts'
11
+ import type { JsonlCompression } from './format.ts'
12
+ import { JsonlGenerationSourceChangedError, readDecodedJsonlSource } from './generation.ts'
13
+ import type { JsonlPhysicalIdentity } from './generation.ts'
14
+
15
+ /** Per-parent supplemental facts and the source checks required before serving or publishing them. */
16
+ interface PreparedCatalogFacts {
17
+ readonly facts: readonly SessionFormatJsonObject[]
18
+ readonly failures: readonly { readonly path: string; readonly error: unknown }[]
19
+ /** @returns resolves while every inspected child still has the captured physical revision. */
20
+ validate(): Promise<void>
21
+ }
22
+
23
+ /**
24
+ * Collect each related child's own descriptor through existing historical codecs.
25
+ * @param parentId - parent whose incoming migration consumes these facts.
26
+ * @param sources - header-indexed direct children in the selected source corpus.
27
+ * @param compression - configured source encoding.
28
+ * @param signal - cancellation forwarded through each source read.
29
+ * @returns compact facts and child-local failures; complete child event arrays are released after extraction.
30
+ */
31
+ export async function prepareCatalogFacts(
32
+ parentId: SessionId,
33
+ sources: readonly { readonly header: SessionHeader; readonly path: string }[],
34
+ compression: JsonlCompression,
35
+ signal: AbortSignal,
36
+ ): Promise<PreparedCatalogFacts> {
37
+ const facts: SessionFormatJsonObject[] = []
38
+ const failures: { path: string; error: unknown }[] = []
39
+ const witnesses: { path: string; identity: JsonlPhysicalIdentity }[] = []
40
+ for (const source of sources) {
41
+ signal.throwIfAborted()
42
+ const version = parseGenerationLogFilename(basename(source.path), compression)
43
+ if (version === undefined) throw new SessionFormatUnsupportedMigrationError(`unrecognized historical child generation ${source.path}`)
44
+ const witness: { path: string; identity: JsonlPhysicalIdentity } = {
45
+ path: source.path, identity: await stat(source.path, { bigint: true }),
46
+ }
47
+ witnesses.push(witness)
48
+ const unavailable = { childId: source.header.id, childCreatedAt: source.header.createdAt,
49
+ descriptorCount: 0, descriptor: null, sourcePath: source.path }
50
+ let restored: Awaited<ReturnType<typeof readDecodedJsonlSource>>
51
+ try {
52
+ restored = await readDecodedJsonlSource(source.path, version, compression, {
53
+ createRestore: header => (version <= 3 ? historicalSessionFormatCatalog : sessionFormatCatalog).createRestore(header, {
54
+ recovery: 'recoverable', validation: 'current',
55
+ }),
56
+ }, signal)
57
+ } catch (error: unknown) {
58
+ signal.throwIfAborted()
59
+ failures.push({ path: source.path, error })
60
+ facts.push(unavailable)
61
+ continue
62
+ }
63
+ witness.identity = restored.identity
64
+ const header = restored.artifact.header
65
+ if (header.id !== source.header.id || header.createdAt !== source.header.createdAt
66
+ || header.parentSession !== parentId || header.origin !== 'subagent'
67
+ || ['cwd', 'isSeeded', 'delegationDepth', 'agentPreset'].some(key => header[key] !== source.header[key as keyof SessionHeader])) {
68
+ throw new JsonlGenerationSourceChangedError(source.path)
69
+ }
70
+ let fact: SessionFormatJsonObject
71
+ try {
72
+ fact = historicalChildCatalogSource(restored.artifact)
73
+ } catch (error: unknown) {
74
+ failures.push({ path: source.path, error })
75
+ facts.push(unavailable)
76
+ continue
77
+ }
78
+ facts.push({ ...fact, sourcePath: source.path })
79
+ }
80
+ return {
81
+ facts,
82
+ failures,
83
+ async validate() {
84
+ for (const witness of witnesses) {
85
+ const current = await stat(witness.path, { bigint: true })
86
+ if (current.dev !== witness.identity.dev || current.ino !== witness.identity.ino
87
+ || current.size !== witness.identity.size || current.mtimeNs !== witness.identity.mtimeNs
88
+ || current.ctimeNs !== witness.identity.ctimeNs) throw new JsonlGenerationSourceChangedError(witness.path)
89
+ }
90
+ },
91
+ }
92
+ }
package/src/format.ts ADDED
@@ -0,0 +1,538 @@
1
+ /**
2
+ * On-disk format helpers for the JSONL session-persistence backend: path
3
+ * sanitization (a {@link SessionId} is an unvalidated branded string, so it
4
+ * MUST be encoded before use in a path — no traversal, no collision), the
5
+ * per-project/session directory layout, header-line (de)serialization, and the
6
+ * truncation-repair offset computation.
7
+ *
8
+ * @module dsh-session-persistence-jsonl/format
9
+ */
10
+
11
+ import { isAbsolute, join } from 'node:path'
12
+ import {
13
+ SESSION_FORMAT_VERSION,
14
+ KNOWN_SESSION_EVENT_TYPES,
15
+ SessionLogOffset,
16
+ } from '@deepseek-ai/dsh-session'
17
+ import type {
18
+ SessionEvent,
19
+ SessionHeader,
20
+ SessionId,
21
+ SessionLogOffset as SessionLogOffsetType,
22
+ } from '@deepseek-ai/dsh-session'
23
+ import { parseSessionFormatLogFilename, sessionFormatLogFilename, SessionFormatUnsupportedMigrationError } from '@deepseek-ai/dsh-session-format'
24
+ import type { SessionFormatEvent } from '@deepseek-ai/dsh-session-format'
25
+ import type { SessionFormatRecovery, SessionFormatRestore } from '@deepseek-ai/dsh-session-format'
26
+ import { sessionFormatCatalog } from '@deepseek-ai/dsh-session-format-catalog'
27
+ import { assertV4RowAdmission, assertReleasedV4Relationships } from '@deepseek-ai/dsh-session-format-v3-to-v4'
28
+ import {
29
+ SessionFormatUnsupportedError,
30
+ sessionFormatVersionRefusal,
31
+ type SessionStorageMetadata,
32
+ } from '@deepseek-ai/dsh-session-persistence'
33
+
34
+ /** Physical encoding selected for JSONL session artifacts. */
35
+ export type JsonlCompression = 'zstd' | 'none'
36
+
37
+ /**
38
+ * Return the artifact suffix for one physical encoding.
39
+ * @param compression - configured JSONL artifact encoding.
40
+ * @returns `.jsonl.zstd` for Zstandard or `.jsonl` for plaintext.
41
+ */
42
+ export function logSuffix(compression: JsonlCompression): '.jsonl.zstd' | '.jsonl' {
43
+ return `.jsonl${compressionSuffix(compression)}`
44
+ }
45
+
46
+ function compressionSuffix(compression: JsonlCompression): '.zstd' | '' {
47
+ return compression === 'zstd' ? '.zstd' : ''
48
+ }
49
+
50
+ /**
51
+ * Return the canonical filename for one immutable Session format generation.
52
+ * Version zero retains the original suffix-only name; every later generation
53
+ * carries a lowercase numeric `vN` component.
54
+ * @param version - non-negative safe Session format version.
55
+ * @param compression - configured JSONL artifact encoding.
56
+ * @returns the generation filename inside one Session directory.
57
+ */
58
+ export function generationLogFilename(version: number, compression: JsonlCompression): string {
59
+ return `${sessionFormatLogFilename(version)}${compressionSuffix(compression)}`
60
+ }
61
+
62
+ /**
63
+ * Parse one canonical generation filename for the selected physical encoding.
64
+ * Noncanonical, temporary, uppercase, leading-zero, and version-zero-tagged names do
65
+ * not identify committed generations.
66
+ * @param filename - one entry from a Session directory.
67
+ * @param compression - configured JSONL artifact encoding.
68
+ * @returns its format version, or `undefined` when the name is not canonical.
69
+ */
70
+ export function parseGenerationLogFilename(
71
+ filename: string,
72
+ compression: JsonlCompression,
73
+ ): number | undefined {
74
+ const suffix = compressionSuffix(compression)
75
+ if (!filename.endsWith(suffix)) return undefined
76
+ return parseSessionFormatLogFilename(filename.slice(0, filename.length - suffix.length))
77
+ }
78
+
79
+ /**
80
+ * The current physical header stored as the first JSONL record. The exact
81
+ * inherited cut lives on the last tagged `session/end-seed` event.
82
+ */
83
+ interface HeaderLine {
84
+ type: 'session'
85
+ version: number
86
+ id: SessionId
87
+ createdAt: number
88
+ cwd?: string
89
+ parentSession?: SessionId
90
+ isSeeded: boolean
91
+ origin?: 'subagent'
92
+ delegationDepth: number
93
+ agentPreset?: string
94
+ }
95
+
96
+ const HEADER_REQUIRED_KEYS = ['type', 'version', 'id', 'createdAt', 'isSeeded', 'delegationDepth'] as const
97
+ const HEADER_OPTIONAL_KEYS = ['cwd', 'parentSession', 'origin', 'agentPreset'] as const
98
+ const HEADER_KEYS = new Set<string>([...HEADER_REQUIRED_KEYS, ...HEADER_OPTIONAL_KEYS])
99
+
100
+ /**
101
+ * Refuse policy fields that never belong to a released Session header.
102
+ * @param value - parsed physical header candidate.
103
+ * @returns nothing after successful validation.
104
+ */
105
+ export function assertNoRetiredHeaderFields(value: unknown): void {
106
+ if (typeof value !== 'object' || value === null) return
107
+ if (Object.hasOwn(value, 'sandboxMode') || Object.hasOwn(value, 'approvalPolicy')) {
108
+ throw new Error('session header uses retired policy baseline fields')
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Build the header line object from a {@link SessionHeader}.
114
+ * @param header - the immutable session metadata to serialize.
115
+ * @param inheritedEventCount - exact inherited prefix length; required for a
116
+ * seeded header and omitted only for an unseeded header.
117
+ * @returns the `type: 'session'`-tagged line object, absent optional fields omitted (never null).
118
+ */
119
+ export function toHeaderLine(
120
+ header: SessionHeader,
121
+ inheritedEventCount?: SessionLogOffsetType,
122
+ ): HeaderLine {
123
+ if (header.isSeeded && inheritedEventCount === undefined) {
124
+ throw new Error('seeded session header requires an inherited event count')
125
+ }
126
+ const cut = SessionLogOffset(inheritedEventCount ?? 0)
127
+ if (!header.isSeeded && cut !== 0) {
128
+ throw new Error('unseeded session header inherited event count must be 0')
129
+ }
130
+ return sessionFormatCatalog.encodeCurrentHeader({
131
+ ...header,
132
+ delegationDepth: header.delegationDepth ?? 0,
133
+ }, cut) as unknown as HeaderLine
134
+ }
135
+
136
+ /**
137
+ * Translate one current physical header into logical metadata and its cut.
138
+ * @param line - the shape-checked first line of a log (see the `isHeaderLine` guard).
139
+ * @returns logical Session metadata paired with the exact inherited prefix length.
140
+ */
141
+ function fromHeaderLine(line: HeaderLine): SessionStorageMetadata {
142
+ return {
143
+ meta: {
144
+ version: SESSION_FORMAT_VERSION,
145
+ id: line.id,
146
+ createdAt: line.createdAt,
147
+ ...line.cwd !== undefined ? { cwd: line.cwd } : {},
148
+ ...line.parentSession !== undefined ? { parentSession: line.parentSession } : {},
149
+ isSeeded: line.isSeeded,
150
+ ...line.origin !== undefined ? { origin: line.origin } : {},
151
+ delegationDepth: line.delegationDepth,
152
+ ...line.agentPreset !== undefined ? { agentPreset: line.agentPreset } : {},
153
+ },
154
+ inheritedEventCount: SessionLogOffset(0),
155
+ }
156
+ }
157
+
158
+ /** Type guard: a parsed first line is a well-formed session header. */
159
+ function isHeaderLine(value: unknown): value is HeaderLine {
160
+ return (
161
+ typeof value === 'object' && value !== null && !Array.isArray(value)
162
+ && HEADER_REQUIRED_KEYS.every(key => Object.hasOwn(value, key))
163
+ && Object.keys(value).every(key => HEADER_KEYS.has(key))
164
+ && (value as { type?: unknown }).type === 'session'
165
+ && typeof (value as { version?: unknown }).version === 'number'
166
+ && typeof (value as { id?: unknown }).id === 'string'
167
+ && typeof (value as { createdAt?: unknown }).createdAt === 'number'
168
+ && Number.isSafeInteger((value as { createdAt: number }).createdAt)
169
+ && (value as { createdAt: number }).createdAt >= 0
170
+ && !Object.is((value as { createdAt: number }).createdAt, -0)
171
+ && typeof (value as { delegationDepth?: unknown }).delegationDepth === 'number'
172
+ && Number.isSafeInteger((value as { delegationDepth: number }).delegationDepth)
173
+ && (value as { delegationDepth: number }).delegationDepth >= 0
174
+ && !Object.is((value as { delegationDepth: number }).delegationDepth, -0)
175
+ && ((value as { cwd?: unknown }).cwd === undefined
176
+ || (typeof (value as { cwd?: unknown }).cwd === 'string'
177
+ && isAbsolute((value as { cwd: string }).cwd)))
178
+ && ((value as { parentSession?: unknown }).parentSession === undefined
179
+ || typeof (value as { parentSession?: unknown }).parentSession === 'string')
180
+ && typeof (value as { isSeeded?: unknown }).isSeeded === 'boolean'
181
+ && ((value as { origin?: unknown }).origin === undefined
182
+ || (value as { origin?: unknown }).origin === 'subagent')
183
+ && ((value as { agentPreset?: unknown }).agentPreset === undefined
184
+ || typeof (value as { agentPreset?: unknown }).agentPreset === 'string')
185
+ )
186
+ }
187
+
188
+ /**
189
+ * Encode an arbitrary string as a single safe path segment, injectively over ALL JS (UTF-16)
190
+ * strings — including lone surrogates. A {@link SessionId} is an unvalidated branded string,
191
+ * so this neutralizes `../`, absolute paths, NUL, and separators before any filesystem use.
192
+ * Safe code units remain literal; every other unit, including `~`, becomes
193
+ * `~XXXX`. Operating on code units preserves lone surrogates, while special-
194
+ * casing `.` and `..` prevents traversal by an otherwise safe whole segment.
195
+ *
196
+ * @param raw - the string to encode; must be non-empty (throws on `''`).
197
+ * @returns the escaped single path segment, decodable back to `raw`.
198
+ */
199
+ export function encodeSegment(raw: string): string {
200
+ if (raw.length === 0) throw new Error('cannot encode an empty path segment')
201
+ if (raw === '.') return '~002E'
202
+ if (raw === '..') return '~002E~002E'
203
+ let out = ''
204
+ for (let i = 0; i < raw.length; i++) {
205
+ const code = raw.charCodeAt(i)
206
+ const ch = String.fromCharCode(code)
207
+ if (ch !== '~' && /^[A-Za-z0-9._-]$/.test(ch)) {
208
+ out += ch
209
+ } else {
210
+ out += '~' + code.toString(16).toUpperCase().padStart(4, '0')
211
+ }
212
+ }
213
+ return out
214
+ }
215
+
216
+ /**
217
+ * Build the readable directory key for a project path.
218
+ * Filesystem separators and drive separators become `-`; unsafe code units use
219
+ * the same `~XXXX` escape as session ids. The key is bounded for filesystem
220
+ * component limits. Separator replacement and truncation are intentionally
221
+ * lossy, following the common human-navigable project-directory convention.
222
+ * @param cwd - the session's project directory.
223
+ * @returns a single filesystem-safe project directory name.
224
+ */
225
+ export function projectKey(cwd: string): string {
226
+ if (cwd.length === 0) throw new Error('cannot encode an empty project path')
227
+ let readable = ''
228
+ let separatorRun = false
229
+ for (let i = 0; i < cwd.length; i++) {
230
+ const code = cwd.charCodeAt(i)
231
+ const ch = String.fromCharCode(code)
232
+ if (ch === '/' || ch === '\\' || ch === ':') {
233
+ if (!separatorRun) readable += '-'
234
+ separatorRun = true
235
+ } else if (ch !== '~' && /^[A-Za-z0-9._-]$/.test(ch)) {
236
+ readable += ch
237
+ separatorRun = false
238
+ } else {
239
+ readable += '~' + code.toString(16).toUpperCase().padStart(4, '0')
240
+ separatorRun = false
241
+ }
242
+ }
243
+ const slug = readable.replace(/^-+/, '') || 'root'
244
+ return `--${slug.slice(0, 251)}--`
245
+ }
246
+
247
+ /**
248
+ * The configured root's human-navigable project directory. A configured root
249
+ * may be local or shared; this grouping does not prescribe its deployment.
250
+ * @param root - the backend's session root directory.
251
+ * @param cwd - the session's project directory; `undefined` selects `_no-cwd`.
252
+ * @returns the project directory path under `root`.
253
+ */
254
+ export function projectDir(root: string, cwd: string | undefined): string {
255
+ if (cwd === undefined) return join(root, '_no-cwd')
256
+ return join(root, projectKey(cwd))
257
+ }
258
+
259
+ /**
260
+ * The directory owned by one session and available for future session-local
261
+ * artifacts.
262
+ * @param root - the backend's session root directory.
263
+ * @param cwd - the session's project directory.
264
+ * @param id - the session id, encoded to one safe path segment.
265
+ * @returns the session directory beneath its project directory.
266
+ */
267
+ export function sessionDir(root: string, cwd: string | undefined, id: SessionId): string {
268
+ return join(projectDir(root, cwd), encodeSegment(id))
269
+ }
270
+
271
+ /**
272
+ * Build one immutable Session format generation path.
273
+ * @param root - the backend's session root directory.
274
+ * @param cwd - the session's project directory (`undefined` → `_no-cwd`).
275
+ * @param id - the session id, path-encoded via {@link encodeSegment} before filesystem use.
276
+ * @param version - physical Session format generation.
277
+ * @param compression - physical artifact encoding and filename suffix.
278
+ * @returns the selected generation's configured JSONL artifact path.
279
+ */
280
+ export function generationLogPath(
281
+ root: string,
282
+ cwd: string | undefined,
283
+ id: SessionId,
284
+ version: number,
285
+ compression: JsonlCompression,
286
+ ): string {
287
+ return join(sessionDir(root, cwd, id), generationLogFilename(version, compression))
288
+ }
289
+
290
+ /**
291
+ * Build the current generation's append target path for a Session.
292
+ * @param root - the backend's session root directory.
293
+ * @param cwd - the session's project directory (`undefined` → `_no-cwd`).
294
+ * @param id - the session id, path-encoded via {@link encodeSegment} before filesystem use.
295
+ * @param compression - physical artifact encoding and filename suffix.
296
+ * @returns the current Session format generation path.
297
+ */
298
+ export function logPath(
299
+ root: string,
300
+ cwd: string | undefined,
301
+ id: SessionId,
302
+ compression: JsonlCompression,
303
+ ): string {
304
+ return generationLogPath(root, cwd, id, SESSION_FORMAT_VERSION, compression)
305
+ }
306
+
307
+ /**
308
+ * Serialize a current event batch as JSONL lines (no trailing newline). Compact
309
+ * Assistant streams are nested event data; every event occupies one row.
310
+ * @param events - the batch to serialize, in log order.
311
+ * @returns the batch's JSONL text; the writer adds the final newline.
312
+ */
313
+ export function eventLines(events: readonly SessionEvent[]): string {
314
+ return events.map(eventLine).join('\n')
315
+ }
316
+
317
+ /**
318
+ * Serialize one current event as one JSONL record without its trailing newline.
319
+ * @param event - current event to encode.
320
+ * @returns one physical JSON record.
321
+ */
322
+ export function eventLine(event: SessionEvent): string {
323
+ return JSON.stringify(sessionFormatCatalog.encodeCurrentEvent(event as unknown as SessionFormatEvent))
324
+ }
325
+
326
+ interface SessionLogScan {
327
+ meta: SessionHeader
328
+ inheritedEventCount: SessionLogOffsetType
329
+ events: SessionEvent[]
330
+ committedBytes: number
331
+ }
332
+
333
+ /**
334
+ * Refuse a header carrying a format version this build does not read BEFORE
335
+ * validating the current header shape or decoding any event row: a future
336
+ * format need not satisfy this build's structural checks at all, and its user
337
+ * must see "upgrade the harness", never "corrupt session log".
338
+ * @param parsed - the JSON-parsed first line of a session artifact.
339
+ */
340
+ function refuseForeignFormatVersion(parsed: object): void {
341
+ const { version, id } = parsed as { version?: unknown; id?: unknown }
342
+ if (typeof version !== 'number' || version === SESSION_FORMAT_VERSION) return
343
+ throw new SessionFormatUnsupportedError(
344
+ sessionFormatVersionRefusal(typeof id === 'string' ? id : String(id), version),
345
+ )
346
+ }
347
+
348
+ /** Parse one complete header record supplied independently from event rows. */
349
+ function parseHeaderRecord(record: Buffer): { readonly meta: SessionHeader; readonly restore: SessionFormatRestore } {
350
+ if (record.length === 0 || record.at(-1) !== 0x0A || record.indexOf(0x0A) !== record.length - 1) {
351
+ throw new Error('empty or header-less session log')
352
+ }
353
+ let parsed: unknown
354
+ try {
355
+ parsed = JSON.parse(record.subarray(0, -1).toString('utf8'))
356
+ } catch {
357
+ throw new Error('corrupt session log: header line is not valid JSON')
358
+ }
359
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
360
+ throw new Error('corrupt session log: first line is not a JSON object')
361
+ }
362
+ refuseForeignFormatVersion(parsed)
363
+ assertNoRetiredHeaderFields(parsed)
364
+ if (!isHeaderLine(parsed)) {
365
+ throw new Error('corrupt session log: first line is not a session header')
366
+ }
367
+ let restore: SessionFormatRestore
368
+ try {
369
+ restore = sessionFormatCatalog.createRestore(parsed, {
370
+ recovery: 'strict',
371
+ validation: 'transformed',
372
+ })
373
+ } catch {
374
+ /* v8 ignore next -- isHeaderLine matches the current codec; this preserves classification if it tightens. */
375
+ throw new Error('corrupt session log: first line is not a session header')
376
+ }
377
+ return { meta: fromHeaderLine(parsed).meta, restore }
378
+ }
379
+
380
+ /**
381
+ * Incrementally scan complete JSONL event records after an independently
382
+ * supplied header record. Newline search and byte offsets stay on raw buffers;
383
+ * only complete records are decoded to UTF-8. A fragment crossing writes is
384
+ * copied because a decoder may reuse its output buffer after `write()` returns.
385
+ */
386
+ export class SessionLogScanner {
387
+ private readonly meta: SessionHeader
388
+ private readonly restore: SessionFormatRestore
389
+ private eventCount = 0
390
+ private fragments: Buffer[] = []
391
+ private fragmentBytes = 0
392
+ private inputBytes: number
393
+ private committedBytes: number
394
+ private eventLine = 0
395
+ private issue: Error | undefined
396
+ private finished = false
397
+
398
+ /**
399
+ * Create an event scanner from exactly one newline-terminated header record.
400
+ * @param headerRecord - the complete first JSONL record, including its newline.
401
+ */
402
+ constructor(
403
+ headerRecord: Buffer,
404
+ private readonly recovery: SessionFormatRecovery = 'recoverable',
405
+ ) {
406
+ const parsed = parseHeaderRecord(headerRecord)
407
+ this.meta = parsed.meta
408
+ this.restore = parsed.restore
409
+ this.inputBytes = headerRecord.length
410
+ this.committedBytes = headerRecord.length
411
+ }
412
+
413
+ /**
414
+ * Consume the next raw plaintext chunk, retaining only an incomplete final record.
415
+ * @param chunk - bytes immediately following all previously supplied bytes.
416
+ */
417
+ write(chunk: Buffer): void {
418
+ if (this.finished) throw new Error('cannot write to a finished session log scanner')
419
+ const chunkStart = this.inputBytes
420
+ this.inputBytes += chunk.length
421
+ let lineStart = 0
422
+ for (
423
+ let newline = chunk.indexOf(0x0A);
424
+ newline !== -1;
425
+ newline = chunk.indexOf(0x0A, lineStart)
426
+ ) {
427
+ const fragment = chunk.subarray(lineStart, newline)
428
+ let line = fragment
429
+ if (this.fragments.length > 0) {
430
+ if (fragment.length > 0) this.fragments.push(fragment)
431
+ line = Buffer.concat(this.fragments, this.fragmentBytes + fragment.length)
432
+ this.fragments = []
433
+ this.fragmentBytes = 0
434
+ }
435
+ this.consumeEventLine(line, chunkStart + newline + 1)
436
+ lineStart = newline + 1
437
+ }
438
+ if (lineStart < chunk.length) {
439
+ const fragment = Buffer.from(chunk.subarray(lineStart))
440
+ this.fragments.push(fragment)
441
+ this.fragmentBytes += fragment.length
442
+ }
443
+ }
444
+
445
+ /**
446
+ * Snapshot progress before appending a recoverable torn-frame prefix.
447
+ * @returns byte, committed-prefix, and expanded-event cursors.
448
+ */
449
+ checkpoint(): {
450
+ inputBytes: number
451
+ committedBytes: number
452
+ eventCount: SessionLogOffsetType
453
+ } {
454
+ return {
455
+ inputBytes: this.inputBytes,
456
+ committedBytes: this.committedBytes,
457
+ eventCount: SessionLogOffset(this.eventCount),
458
+ }
459
+ }
460
+
461
+ /**
462
+ * Finish scanning, ignoring a final record without a newline as a torn tail.
463
+ * @returns the header, contiguous event prefix, and safe truncation offset.
464
+ */
465
+ finish(): SessionLogScan {
466
+ this.finished = true
467
+ const artifact = this.restore.finish()
468
+ assertReleasedV4Relationships(artifact, KNOWN_SESSION_EVENT_TYPES)
469
+ return {
470
+ meta: this.meta,
471
+ inheritedEventCount: SessionLogOffset(artifact.inheritedEventCount),
472
+ events: artifact.events as unknown as SessionEvent[],
473
+ committedBytes: this.committedBytes,
474
+ }
475
+ }
476
+
477
+ /** Decode one complete event row and update the contiguous prefix. */
478
+ private consumeEventLine(line: Buffer, endByte: number): void {
479
+ this.eventLine += 1
480
+ let decoded: unknown
481
+ try {
482
+ decoded = JSON.parse(line.toString('utf8')) as unknown
483
+ } catch {
484
+ const issue = new Error(`corrupt session log: unparsable committed event at line ${this.eventLine}`)
485
+ if (this.recovery === 'strict') throw issue
486
+ this.issue ??= issue
487
+ return
488
+ }
489
+
490
+ // This scanner accepts only current-generation files. Owned structural refusal must
491
+ // precede its recoverable-tail suppression, independently of the strict decoder state.
492
+ try {
493
+ assertV4RowAdmission(decoded, KNOWN_SESSION_EVENT_TYPES)
494
+ } catch (error: unknown) {
495
+ if (error instanceof SessionFormatUnsupportedMigrationError) throw new SessionFormatUnsupportedError(error.message)
496
+ throw error
497
+ }
498
+
499
+ if (this.issue !== undefined) {
500
+ if (typeof decoded === 'object' && decoded !== null
501
+ && (decoded as { type?: unknown }).type === 'turn/end') throw this.issue
502
+ return
503
+ }
504
+ try {
505
+ this.restore.decodeRow(decoded)
506
+ } catch (error: unknown) {
507
+ // Unsupported current-format rows have already been refused before recovery.
508
+ /* v8 ignore next -- every production Session format decoder rejects with Error. */
509
+ const detail = error instanceof Error ? error.message : String(error)
510
+ const issue = new Error(`corrupt session log: invalid committed event at line ${this.eventLine}: ${detail}`, {
511
+ cause: error,
512
+ })
513
+ if (this.recovery === 'strict') throw issue
514
+ this.issue = issue
515
+ if (typeof decoded === 'object' && decoded !== null
516
+ && (decoded as { type?: unknown }).type === 'turn/end') throw issue
517
+ return
518
+ }
519
+ this.eventCount += 1
520
+ this.committedBytes = endByte
521
+ }
522
+ }
523
+
524
+ /**
525
+ * Parse a complete or torn JSONL buffer into its preserved event prefix. This
526
+ * compatibility wrapper supplies the first record separately, then delegates
527
+ * event rows to {@link SessionLogScanner}.
528
+ *
529
+ * @param buffer - the raw bytes of the log file (header line first).
530
+ * @returns the header, preserved event prefix, and byte offset safe to append at.
531
+ */
532
+ export function scanLog(buffer: Buffer): SessionLogScan {
533
+ const headerEnd = buffer.indexOf(0x0A)
534
+ if (headerEnd === -1) throw new Error('empty or header-less session log')
535
+ const scanner = new SessionLogScanner(buffer.subarray(0, headerEnd + 1))
536
+ scanner.write(buffer.subarray(headerEnd + 1))
537
+ return scanner.finish()
538
+ }