@kabxx/dsh-session-move 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,468 @@
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import { cp, lstat, mkdir, open, readFile, readdir, realpath, rm, unlink } from 'node:fs/promises'
3
+ import { basename, dirname, join, resolve } from 'node:path'
4
+ import { constants, zstdCompressSync } from 'node:zlib'
5
+ import { readMoveEvents } from './inbox.js'
6
+ import { encodeSegment, LOCK_FILENAME, LOG_FILENAME, sessionDir } from './paths.js'
7
+ import { fail } from './plan.js'
8
+ import { acquirePathLock, acquireWindowsLock, assertPlainWindowsPath, publishPath, restorePath, syncDirectory } from './platform-fs.js'
9
+ import { readHeader, rewriteHeaderCwd, scanFrames } from './zstd-frame.js'
10
+
11
+ const windows = process.platform === 'win32'
12
+ const journalName = 'move-intent.json'
13
+ const checksum = { params: { [constants.ZSTD_c_checksumFlag]: 1 } }
14
+ const digest = (bytes) => createHash('sha256').update(bytes).digest('hex')
15
+ const isTicket = (value) => typeof value === 'string' && /^[\da-f]{8}-(?:[\da-f]{4}-){3}[\da-f]{12}$/u.test(value)
16
+ const isHash = (value) => typeof value === 'string' && /^[\da-f]{64}$/u.test(value)
17
+
18
+ export async function lookup(path) {
19
+ try { return await lstat(path) } catch (error) {
20
+ if (error.code !== 'ENOENT') throw error
21
+ }
22
+ }
23
+
24
+ async function directory(path, create = false) {
25
+ if (create) await mkdir(path, { recursive: true, mode: 0o700 })
26
+ const info = await lookup(path)
27
+ const actual = info?.isDirectory() && await realpath(path)
28
+ const normalize = (value) => windows ? value.toLowerCase() : value
29
+ if (!actual || normalize(actual) !== normalize(resolve(path))) throw fail('unsafe-path')
30
+ assertPlainWindowsPath(path)
31
+ return info
32
+ }
33
+
34
+ async function plainFile(path) {
35
+ const info = await lookup(path)
36
+ if (!info?.isFile() || info.nlink !== 1) throw fail('unsafe-path')
37
+ assertPlainWindowsPath(path)
38
+ }
39
+
40
+ async function writeDurably(path, bytes) {
41
+ const temporary = `${path}.${randomUUID()}.tmp`
42
+ try {
43
+ const file = await open(temporary, 'wx', 0o600)
44
+ try { await file.writeFile(bytes); await file.sync() } finally { await file.close() }
45
+ await publishPath(temporary, path, { replace: true })
46
+ await syncDirectory(dirname(path))
47
+ } catch (error) {
48
+ await unlink(temporary).catch(() => {})
49
+ throw error
50
+ }
51
+ }
52
+
53
+ async function renameDurably(from, to) {
54
+ try { await restorePath(from, to) } catch (error) {
55
+ if (error.code === 'EXDEV') throw fail('cross-device', error)
56
+ throw error
57
+ }
58
+ await syncDirectory(dirname(from))
59
+ if (dirname(to) !== dirname(from)) await syncDirectory(dirname(to))
60
+ }
61
+
62
+ // Match DSH's canonical positive version numbers and untagged generation zero.
63
+ function generation(name) {
64
+ const match = /^session(?:\.v([1-9][0-9]*))?\.jsonl(\.zstd)?$/u.exec(name)
65
+ if (!match) return
66
+ const version = Number(match[1] ?? 0)
67
+ if (Number.isSafeInteger(version)) return { version, compressed: Boolean(match[2]) }
68
+ }
69
+
70
+ function isShadow(name) {
71
+ const log = generation(name)
72
+ return log?.compressed && log.version < 4
73
+ }
74
+
75
+ // The native reader selects v4 in a directory with older compressed generations.
76
+ // Preserve the historical artifacts but reject unsafe files and unsupported encodings.
77
+ async function validateTree(path, shadows = undefined) {
78
+ await directory(path)
79
+ for (const entry of await readdir(path, { withFileTypes: true })) {
80
+ const child = join(path, entry.name)
81
+ if (shadows && generation(entry.name)) {
82
+ if (entry.name !== LOG_FILENAME && !isShadow(entry.name)) throw fail('unsupported')
83
+ await plainFile(child)
84
+ if (entry.name !== LOG_FILENAME) shadows.push(entry.name)
85
+ } else if (entry.isDirectory()) await validateTree(child)
86
+ else await plainFile(child)
87
+ }
88
+ }
89
+
90
+ function hasPublishedPrefix(bytes, member) {
91
+ if (member.nextBytes !== undefined) {
92
+ return bytes.length >= member.nextBytes && digest(bytes.subarray(0, member.nextBytes)) === member.nextHash
93
+ }
94
+ if (digest(bytes) === member.nextHash) return true
95
+ // Older journals recorded only the hash. Native appends start a new frame, so
96
+ // one of the complete frame boundaries must match the published transcript.
97
+ const hash = createHash('sha256')
98
+ for (const { start, end } of scanFrames(bytes).frames) {
99
+ hash.update(bytes.subarray(start, end))
100
+ if (hash.copy().digest('hex') === member.nextHash) return true
101
+ }
102
+ return false
103
+ }
104
+
105
+ async function syncTree(path) {
106
+ for (const entry of await readdir(path, { withFileTypes: true })) {
107
+ const child = join(path, entry.name)
108
+ if (entry.isDirectory()) await syncTree(child)
109
+ else if (entry.name !== LOCK_FILENAME) {
110
+ const file = await open(child, 'r+')
111
+ try { await file.sync() } finally { await file.close() }
112
+ }
113
+ }
114
+ await syncDirectory(path)
115
+ }
116
+
117
+ export function moveStorage(root, base, { checkpoint = async () => {} } = {}) {
118
+ const journal = join(base, journalName)
119
+ const backups = join(base, 'backups')
120
+
121
+ function ticketDir(ticket) {
122
+ if (!isTicket(ticket)) throw fail('unsafe-path')
123
+ return join(backups, ticket)
124
+ }
125
+
126
+ function paths(state, member) {
127
+ if (typeof member?.id !== 'string' || !member.id || typeof member.oldCwd !== 'string' || !member.oldCwd
128
+ || typeof state.targetCwd !== 'string' || !state.targetCwd) throw fail('unsafe-path')
129
+ const ticket = ticketDir(state.ticket)
130
+ const name = encodeSegment(member.id)
131
+ const oldDir = sessionDir(root, member.oldCwd, member.id)
132
+ const nextDir = sessionDir(root, state.targetCwd, member.id)
133
+ const unchanged = member.oldCwd === state.targetCwd
134
+ const inPlace = !unchanged && oldDir === nextDir
135
+ const shadows = member.shadows ?? []
136
+ if (member.oldDir !== oldDir || member.nextDir !== nextDir || (!unchanged && !isHash(member.nextHash))
137
+ || (inPlace && !isHash(member.oldHash)) || (member.oldHash !== undefined && !isHash(member.oldHash))
138
+ || (member.nextBytes !== undefined && (!Number.isSafeInteger(member.nextBytes) || member.nextBytes <= 0))
139
+ || (member.cwdChangeSeq !== undefined && (!Number.isSafeInteger(member.cwdChangeSeq) || member.cwdChangeSeq < 0))
140
+ || !Array.isArray(shadows) || shadows.some((file) => typeof file !== 'string' || !isShadow(file))
141
+ || new Set(shadows).size !== shadows.length || ((inPlace || unchanged) && shadows.length)) throw fail('unsafe-path')
142
+ const stage = join(ticket, 'staged', name)
143
+ return {
144
+ id: member.id, oldDir, nextDir, unchanged, inPlace, shadows,
145
+ oldFile: join(oldDir, LOG_FILENAME), nextFile: join(nextDir, LOG_FILENAME),
146
+ stage, stageFile: join(stage, LOG_FILENAME), held: join(ticket, 'held', name),
147
+ originalFile: join(ticket, 'original', name, LOG_FILENAME),
148
+ heldShadows: join(ticket, 'held-shadows', name),
149
+ }
150
+ }
151
+
152
+ async function hasJournal() {
153
+ return Boolean(await lookup(journal))
154
+ }
155
+
156
+ async function readState() {
157
+ if (!await hasJournal()) return
158
+ await plainFile(journal)
159
+ const state = JSON.parse(await readFile(journal, 'utf8'))
160
+ if (state?.version !== 2 || !isTicket(state.ticket) || !['prepared', 'committed', 'rolled-back'].includes(state.phase)
161
+ || !Array.isArray(state.members) || state.members.length === 0
162
+ || new Set(state.members.map((member) => member?.id)).size !== state.members.length || !state.ledger) throw fail('restore-pending')
163
+ state.members.forEach((member) => paths(state, member))
164
+ return state
165
+ }
166
+
167
+ async function hasHeld(state) {
168
+ for (const member of state.members) {
169
+ const p = paths(state, member)
170
+ if (p.unchanged) continue
171
+ if (p.inPlace) {
172
+ if (!await lookup(p.stageFile)) return true
173
+ } else {
174
+ if (await lookup(p.held)) return true
175
+ for (const name of p.shadows) {
176
+ if (await lookup(join(p.heldShadows, name))) return true
177
+ }
178
+ }
179
+ }
180
+ return false
181
+ }
182
+
183
+ async function withLock(run) {
184
+ await directory(base, true)
185
+ const { handle } = await acquirePathLock(join(base, 'move.lock'))
186
+ try { return await run() } finally { await handle.close() }
187
+ }
188
+
189
+ async function save(state) {
190
+ await writeDurably(journal, JSON.stringify(state))
191
+ }
192
+
193
+ async function removeTicket(ticket) {
194
+ const target = ticketDir(ticket)
195
+ if (await lookup(target)) {
196
+ await directory(target)
197
+ await rm(target, { recursive: true })
198
+ await syncDirectory(backups)
199
+ }
200
+ }
201
+
202
+ async function finish(state) {
203
+ await removeTicket(state.ticket)
204
+ await unlink(journal)
205
+ await syncDirectory(base)
206
+ }
207
+
208
+ async function withSessionLocks(plan, run, { recovery = false } = {}) {
209
+ const handles = []
210
+ const lock = async (path, future = false) => {
211
+ const result = future && windows ? acquireWindowsLock(path) : await acquirePathLock(path)
212
+ handles.push(result.handle)
213
+ }
214
+ try {
215
+ // Keep the source directory (including its lock inode) in place while we
216
+ // hide and restore its log. A queued writer therefore cannot reopen it.
217
+ for (const member of plan.members) {
218
+ const { oldDir, nextDir } = member
219
+ if (await lookup(oldDir)) {
220
+ await directory(oldDir)
221
+ await lock(join(oldDir, LOCK_FILENAME))
222
+ } else if (!recovery) throw fail('changed')
223
+ if (oldDir === nextDir) continue
224
+ if (await lookup(nextDir)) {
225
+ if (!recovery) throw fail('collision')
226
+ await directory(nextDir)
227
+ await lock(join(nextDir, LOCK_FILENAME))
228
+ } else if (windows) {
229
+ await lock(join(nextDir, LOCK_FILENAME), true)
230
+ }
231
+ }
232
+ return await run(async (stage) => {
233
+ if (!windows) await lock(join(stage, LOCK_FILENAME))
234
+ })
235
+ } finally {
236
+ for (const handle of handles.reverse()) await handle.close()
237
+ }
238
+ }
239
+
240
+ async function prepare(ctx, plan, ledger, lockStage) {
241
+ // Check every family member under the native write leases before making
242
+ // any backup. The event snapshots also determine the next sequence number.
243
+ const cwdChangeSeqs = new Map()
244
+ for (const member of plan.members) {
245
+ const events = await readMoveEvents(ctx, member)
246
+ if (member.oldCwd !== plan.targetCwd) cwdChangeSeqs.set(member.id, (events.at(-1)?.seq ?? -1) + 1)
247
+ }
248
+
249
+ const ticket = randomUUID()
250
+ const home = ticketDir(ticket)
251
+ const state = { version: 2, ticket, phase: 'prepared', ...plan, ledger, members: [] }
252
+ const privateDirectories = ['original', 'staged', 'held', 'held-shadows']
253
+ await directory(root)
254
+ await directory(backups, true)
255
+ await mkdir(home, { mode: 0o700 })
256
+ try {
257
+ for (const sub of privateDirectories) await directory(join(home, sub), true)
258
+ for (const member of plan.members) {
259
+ const { id, oldCwd, oldDir, oldFile, nextDir } = member
260
+ if (oldDir !== sessionDir(root, oldCwd, id) || oldFile !== join(oldDir, LOG_FILENAME)
261
+ || nextDir !== sessionDir(root, plan.targetCwd, id)) throw fail('unsupported')
262
+ const entry = { id, oldCwd, oldDir, nextDir }
263
+ if (oldCwd === plan.targetCwd) {
264
+ state.members.push(entry)
265
+ continue
266
+ }
267
+ const inPlace = oldDir === nextDir
268
+ await directory(dirname(nextDir), true)
269
+ await syncDirectory(root)
270
+ if ((await directory(oldDir)).dev !== (await directory(home)).dev
271
+ || (await directory(dirname(nextDir))).dev !== (await directory(home)).dev) throw fail('cross-device')
272
+ if (!inPlace && await lookup(nextDir)) throw fail('collision')
273
+ const shadows = []
274
+ await validateTree(oldDir, shadows)
275
+ const name = encodeSegment(id)
276
+ const original = join(home, 'original', name)
277
+ const stage = join(home, 'staged', name)
278
+ const copyOptions = { recursive: true, force: false, errorOnExist: true, filter: (source) => source !== join(oldDir, LOCK_FILENAME) }
279
+ await cp(oldDir, original, copyOptions)
280
+ await syncTree(original)
281
+ if (inPlace) await directory(stage, true)
282
+ else await cp(original, stage, { recursive: true, force: false, errorOnExist: true })
283
+ const bytes = await readFile(join(original, LOG_FILENAME))
284
+ const scan = scanFrames(bytes)
285
+ const header = readHeader(bytes)
286
+ if (scan.tornStart !== undefined || header.id !== id || header.cwd !== oldCwd) throw fail('unsupported')
287
+ const cwdChangeSeq = cwdChangeSeqs.get(id)
288
+ // DSH turns this event into native runtime context on the next request.
289
+ const cwdChange = {
290
+ type: 'working-directory/change', seq: cwdChangeSeq, time: Date.now(), data: { cwd: plan.targetCwd },
291
+ }
292
+ const next = Buffer.concat([rewriteHeaderCwd(bytes, plan.targetCwd), zstdCompressSync(
293
+ JSON.stringify(cwdChange) + '\n', checksum,
294
+ )])
295
+ await writeDurably(join(stage, LOG_FILENAME), next)
296
+ if (!inPlace) {
297
+ await lockStage(stage)
298
+ if (shadows.length) {
299
+ const holding = join(home, 'held-shadows', name)
300
+ await directory(holding, true)
301
+ await syncDirectory(holding)
302
+ }
303
+ }
304
+ await syncTree(stage)
305
+ state.members.push({
306
+ ...entry, oldHash: digest(bytes), nextHash: digest(next), nextBytes: next.length,
307
+ cwdChangeSeq, ...(!inPlace && shadows.length ? { shadows } : {}),
308
+ })
309
+ }
310
+ for (const path of privateDirectories) await syncDirectory(join(home, path))
311
+ await syncDirectory(home)
312
+ await syncDirectory(backups)
313
+ return state
314
+ } catch (error) {
315
+ await removeTicket(ticket).catch(() => {})
316
+ throw error
317
+ }
318
+ }
319
+
320
+ async function publish(state) {
321
+ for (const member of state.members) {
322
+ const p = paths(state, member)
323
+ if (p.unchanged) continue
324
+ await plainFile(p.oldFile)
325
+ if (p.inPlace) {
326
+ if (digest(await readFile(p.oldFile)) !== member.oldHash) throw fail('changed')
327
+ // The original remains visible until a single replace publishes the new
328
+ // log. Both headers derive the same physical path, and the lease stays put.
329
+ await publishPath(p.stageFile, p.oldFile, { replace: true })
330
+ await syncDirectory(p.stage)
331
+ await syncDirectory(p.oldDir)
332
+ } else {
333
+ if (await lookup(p.nextDir)) throw fail('collision')
334
+ // Keep the selected generation visible until its shadows are hidden.
335
+ // Otherwise native lookup might select a historical source generation.
336
+ for (const name of p.shadows) {
337
+ await renameDurably(join(p.oldDir, name), join(p.heldShadows, name))
338
+ await checkpoint('shadow-hidden', member)
339
+ }
340
+ await renameDurably(p.oldFile, p.held)
341
+ await checkpoint('source-hidden', member)
342
+ if ((await readdir(p.oldDir)).some(generation)) throw fail('changed')
343
+ await renameDurably(p.stage, p.nextDir)
344
+ }
345
+ await checkpoint('destination-published', member)
346
+ }
347
+ }
348
+
349
+ async function rollback(state) {
350
+ const actions = []
351
+ // Preflight under all native leases. A changed log in one member must not
352
+ // leave the family split by undoing a different member first.
353
+ for (const member of [...state.members].reverse()) {
354
+ const p = paths(state, member)
355
+ if (p.unchanged) continue
356
+ if (p.inPlace) {
357
+ await plainFile(p.oldFile)
358
+ if (await lookup(p.stageFile)) continue
359
+ const current = digest(await readFile(p.oldFile))
360
+ if (current === member.oldHash) continue
361
+ // Do not overwrite a log that acquired additional entries after publish.
362
+ if (current !== member.nextHash) throw fail('changed')
363
+ await plainFile(p.originalFile)
364
+ const original = await readFile(p.originalFile)
365
+ if (digest(original) !== member.oldHash) throw fail('changed')
366
+ actions.push(() => writeDurably(p.oldFile, original))
367
+ continue
368
+ }
369
+ if (await lookup(p.held)) {
370
+ if (await lookup(p.oldFile)) throw fail('restore-pending')
371
+ if (!await lookup(p.stage)) {
372
+ await directory(p.nextDir)
373
+ await plainFile(p.nextFile)
374
+ if (digest(await readFile(p.nextFile)) !== member.nextHash) throw fail('changed')
375
+ actions.push(() => renameDurably(p.nextDir, p.stage))
376
+ }
377
+ await plainFile(p.held)
378
+ if (member.oldHash && digest(await readFile(p.held)) !== member.oldHash) throw fail('changed')
379
+ actions.push(() => renameDurably(p.held, p.oldFile))
380
+ } else {
381
+ // The source was never hidden, or a prior recovery put it back.
382
+ await plainFile(p.oldFile)
383
+ }
384
+ for (const name of p.shadows) {
385
+ const shadow = join(p.heldShadows, name)
386
+ const original = join(p.oldDir, name)
387
+ if (await lookup(shadow)) {
388
+ await plainFile(shadow)
389
+ if (await lookup(original)) throw fail('changed')
390
+ actions.push(() => renameDurably(shadow, original))
391
+ }
392
+ }
393
+ }
394
+ for (const action of actions) await action()
395
+ }
396
+
397
+ async function verifyPublished(state) {
398
+ for (const member of state.members) {
399
+ const p = paths(state, member)
400
+ if (p.unchanged) continue
401
+ if (await lookup(p.inPlace ? p.stageFile : p.stage)) throw fail('changed')
402
+ await directory(p.nextDir)
403
+ await plainFile(p.nextFile)
404
+ if (!hasPublishedPrefix(await readFile(p.nextFile), member)) throw fail('changed')
405
+ }
406
+ }
407
+
408
+ async function cleanCommitted(state) {
409
+ for (const member of state.members) {
410
+ const p = paths(state, member)
411
+ await directory(p.nextDir)
412
+ await plainFile(p.nextFile)
413
+ if (p.unchanged || p.inPlace || !await lookup(p.oldDir)) continue
414
+ await directory(p.oldDir)
415
+ if ((await readdir(p.oldDir)).some(generation)) throw fail('changed')
416
+ await rm(p.oldDir, { recursive: true })
417
+ await syncDirectory(dirname(p.oldDir))
418
+ }
419
+ await finish(state)
420
+ }
421
+
422
+ return {
423
+ hasJournal, readState, hasHeld, withLock, save, finish, withSessionLocks, prepare, publish, rollback, verifyPublished, cleanCommitted,
424
+ }
425
+ }
426
+
427
+ /** Recover v0.1.0's incorrectly located log using the newest live file. */
428
+ export async function recoverLegacyDisk(root, base) {
429
+ const journal = join(base, journalName)
430
+ if (!await lookup(journal)) return
431
+ await directory(base)
432
+ await plainFile(journal)
433
+ const state = JSON.parse(await readFile(journal, 'utf8'))
434
+ if (state?.version !== 1 || !isTicket(state.ticket)) throw fail('restore-pending')
435
+ if (state.phase === 'committed') return
436
+ if (state.phase !== 'prepared' || !Array.isArray(state.members) || !state.members.length) throw fail('restore-pending')
437
+ const holding = join(base, 'backups', state.ticket, 'legacy-recovery')
438
+ await directory(holding, true)
439
+ await syncDirectory(dirname(holding))
440
+ for (const { id, oldCwd, oldDir, nextDir, oldFile, nextFile } of state.members) {
441
+ if (typeof id !== 'string' || typeof oldCwd !== 'string' || typeof nextDir !== 'string') throw fail('unsafe-path')
442
+ const escaped = encodeSegment(id)
443
+ if (oldDir !== sessionDir(root, oldCwd, id) || oldFile !== join(oldDir, LOG_FILENAME)
444
+ || dirname(dirname(nextDir)) !== root || !/^--.+--$/u.test(basename(dirname(nextDir)))
445
+ || basename(nextDir) !== escaped || nextFile !== join(nextDir, LOG_FILENAME) || oldDir === nextDir) throw fail('unsafe-path')
446
+ const held = join(holding, escaped)
447
+ if (await lookup(oldDir)) {
448
+ if (await lookup(nextDir) || await lookup(held)) throw fail('restore-pending')
449
+ await plainFile(oldFile)
450
+ continue
451
+ }
452
+ await directory(dirname(oldDir), true)
453
+ if (!await lookup(held)) {
454
+ await directory(nextDir)
455
+ await plainFile(nextFile)
456
+ await renameDurably(nextDir, held)
457
+ }
458
+ const file = join(held, LOG_FILENAME)
459
+ await directory(held)
460
+ await plainFile(file)
461
+ const bytes = await readFile(file)
462
+ if (readHeader(bytes).id !== id) throw fail('changed')
463
+ await writeDurably(file, rewriteHeaderCwd(bytes, oldCwd))
464
+ await renameDurably(held, oldDir)
465
+ }
466
+ // Keep the v0.1.0 backup for manual inspection. Its ledger order was not journaled.
467
+ await renameDurably(journal, join(base, `recovered-${state.ticket}.json`))
468
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Zstandard frame surgery for the JSONL session container.
3
+ *
4
+ * DSH stores a session as a concatenation of independently decodable
5
+ * Zstandard frames; the first frame holds exactly the session header line.
6
+ * Rewriting `cwd` therefore only needs that frame: the remaining frames are
7
+ * copied byte-for-byte, so a multi-megabyte transcript is never recompressed
8
+ * and its event payloads are never re-encoded.
9
+ *
10
+ * The frame scanner mirrors `dsh-session-persistence-jsonl/src/zstd.ts`
11
+ * (`scanZstdFrames`) — see `test/zstd-frame.test.js`, which checks this copy
12
+ * against real session files.
13
+ *
14
+ * @module dsh-session-move/zstd-frame
15
+ */
16
+
17
+ import { constants, zstdCompressSync, zstdDecompressSync } from 'node:zlib'
18
+
19
+ const ZSTD_MAGIC = 0xFD2FB528
20
+ const CHECKSUM_OPTIONS = { params: { [constants.ZSTD_c_checksumFlag]: 1 } }
21
+
22
+ /**
23
+ * Locate complete frames without decompressing their blocks.
24
+ * @param buffer - complete bytes currently present in the session artifact.
25
+ * @returns complete frame ranges and an optional incomplete-final-frame start.
26
+ */
27
+ export function scanFrames(buffer) {
28
+ const frames = []
29
+ let offset = 0
30
+
31
+ while (offset < buffer.length) {
32
+ const start = offset
33
+ if (buffer.length - offset < 4) return { frames, tornStart: start }
34
+ if (buffer.readUInt32LE(offset) !== ZSTD_MAGIC) {
35
+ throw new Error(`corrupt Zstandard session log: invalid frame magic at byte ${offset}`)
36
+ }
37
+ offset += 4
38
+
39
+ if (offset === buffer.length) return { frames, tornStart: start }
40
+ const descriptor = buffer.readUInt8(offset)
41
+ offset += 1
42
+ if ((descriptor & 0x18) !== 0) {
43
+ throw new Error(`corrupt Zstandard session log: reserved frame-header bit at byte ${offset - 1}`)
44
+ }
45
+
46
+ const contentSizeFlag = descriptor >>> 6
47
+ const singleSegment = (descriptor & 0x20) !== 0
48
+ const checksum = (descriptor & 0x04) !== 0
49
+ const dictionaryFlag = descriptor & 0x03
50
+ const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag
51
+ const contentSizeBytes = contentSizeFlag === 0
52
+ ? (singleSegment ? 1 : 0)
53
+ : 1 << contentSizeFlag
54
+ const remainingHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes
55
+ if (buffer.length - offset < remainingHeaderBytes) return { frames, tornStart: start }
56
+ offset += remainingHeaderBytes
57
+
58
+ for (;;) {
59
+ if (buffer.length - offset < 3) return { frames, tornStart: start }
60
+ const blockHeader = buffer.readUIntLE(offset, 3)
61
+ offset += 3
62
+ const lastBlock = (blockHeader & 1) !== 0
63
+ const blockType = (blockHeader >>> 1) & 0x03
64
+ const blockSize = blockHeader >>> 3
65
+ if (blockType === 0x03) {
66
+ throw new Error(`corrupt Zstandard session log: reserved block type at byte ${offset - 3}`)
67
+ }
68
+ const payloadBytes = blockType === 0x01 ? 1 : blockSize
69
+ if (buffer.length - offset < payloadBytes) return { frames, tornStart: start }
70
+ offset += payloadBytes
71
+ if (lastBlock) break
72
+ }
73
+
74
+ if (checksum) {
75
+ if (buffer.length - offset < 4) return { frames, tornStart: start }
76
+ offset += 4
77
+ }
78
+ frames.push({ start, end: offset })
79
+ }
80
+
81
+ return { frames }
82
+ }
83
+
84
+ /**
85
+ * Read the session header out of the first frame.
86
+ * @param buffer - complete session artifact bytes.
87
+ * @returns the parsed header object.
88
+ */
89
+ export function readHeader(buffer) {
90
+ const { frames } = scanFrames(buffer)
91
+ if (frames.length === 0) throw new Error('corrupt Zstandard session log: no complete frame')
92
+ const plain = zstdDecompressSync(buffer.subarray(frames[0].start, frames[0].end)).toString('utf8')
93
+ const newline = plain.indexOf('\n')
94
+ const line = newline === -1 ? plain : plain.slice(0, newline)
95
+ const header = JSON.parse(line)
96
+ if (header === null || typeof header !== 'object' || header.type !== 'session') {
97
+ throw new Error('session log does not begin with a session header')
98
+ }
99
+ return header
100
+ }
101
+
102
+ /**
103
+ * Rewrite the header's `cwd`, recompressing only the first frame.
104
+ *
105
+ * Returns the input buffer unchanged when the header already carries `cwd`,
106
+ * so the caller can treat "nothing to do" without a second parse.
107
+ * @param buffer - complete session artifact bytes.
108
+ * @param cwd - the new project path, verbatim as stored by the workspace record.
109
+ * @returns the new artifact bytes.
110
+ */
111
+ export function rewriteHeaderCwd(buffer, cwd) {
112
+ const { frames } = scanFrames(buffer)
113
+ if (frames.length === 0) throw new Error('corrupt Zstandard session log: no complete frame')
114
+ const first = frames[0]
115
+ const plain = zstdDecompressSync(buffer.subarray(first.start, first.end)).toString('utf8')
116
+ const newline = plain.indexOf('\n')
117
+ const line = newline === -1 ? plain : plain.slice(0, newline)
118
+ const header = JSON.parse(line)
119
+ if (header === null || typeof header !== 'object' || header.type !== 'session') {
120
+ throw new Error('session log does not begin with a session header')
121
+ }
122
+ if (header.cwd === cwd) return buffer
123
+
124
+ header.cwd = cwd
125
+ // Preserve key order and the original line ending by rebuilding the same
126
+ // text layout around the mutated header object.
127
+ const rebuilt = JSON.stringify(header) + (newline === -1 ? '' : plain.slice(newline))
128
+ const frame = zstdCompressSync(Buffer.from(rebuilt, 'utf8'), CHECKSUM_OPTIONS)
129
+ return Buffer.concat([frame, buffer.subarray(first.end)])
130
+ }
131
+
132
+ /**
133
+ * Decompress every frame of a session artifact.
134
+ * @param buffer - complete session artifact bytes.
135
+ * @returns the concatenated plaintext.
136
+ */
137
+ export function decodeAll(buffer) {
138
+ const { frames } = scanFrames(buffer)
139
+ return Buffer.concat(frames.map(({ start, end }) => zstdDecompressSync(buffer.subarray(start, end))))
140
+ }