@kabxx/dsh-session-move 0.1.0 → 0.1.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.
@@ -1,17 +1,21 @@
1
1
  import { createHash, randomUUID } from 'node:crypto'
2
- import { cp, lstat, mkdir, open, readFile, readdir, realpath, rm, unlink } from 'node:fs/promises'
2
+ import { constants as fsFlags } from 'node:fs'
3
+ import { chmod, lstat, mkdir, open, readFile, readdir, realpath, rm, statfs, unlink } from 'node:fs/promises'
3
4
  import { basename, dirname, join, resolve } from 'node:path'
4
- import { constants, zstdCompressSync } from 'node:zlib'
5
- import { readMoveEvents } from './inbox.js'
5
+ import { pipeline } from 'node:stream/promises'
6
+ import { constants, createZstdDecompress, zstdCompressSync, zstdDecompressSync } from 'node:zlib'
7
+ import { assertPreparing, inspectMoveHistory } from './history.js'
6
8
  import { encodeSegment, LOCK_FILENAME, LOG_FILENAME, sessionDir } from './paths.js'
7
9
  import { fail } from './plan.js'
8
10
  import { acquirePathLock, acquireWindowsLock, assertPlainWindowsPath, publishPath, restorePath, syncDirectory } from './platform-fs.js'
9
- import { readHeader, rewriteHeaderCwd, scanFrames } from './zstd-frame.js'
11
+ import { createFrameScanner } from './zstd-frame.js'
10
12
 
11
13
  const windows = process.platform === 'win32'
12
14
  const journalName = 'move-intent.json'
13
15
  const checksum = { params: { [constants.ZSTD_c_checksumFlag]: 1 } }
14
- const digest = (bytes) => createHash('sha256').update(bytes).digest('hex')
16
+ const chunkBytes = 128 * 1024
17
+ const tornBatchBytes = 512 * 1024
18
+ const maxHeaderBytes = 16 * 1024 * 1024
15
19
  const isTicket = (value) => typeof value === 'string' && /^[\da-f]{8}-(?:[\da-f]{4}-){3}[\da-f]{12}$/u.test(value)
16
20
  const isHash = (value) => typeof value === 'string' && /^[\da-f]{64}$/u.test(value)
17
21
 
@@ -32,24 +36,298 @@ async function directory(path, create = false) {
32
36
  }
33
37
 
34
38
  async function plainFile(path) {
35
- const info = await lookup(path)
36
- if (!info?.isFile() || info.nlink !== 1) throw fail('unsafe-path')
39
+ const info = await lstat(path, { bigint: true }).catch((error) => {
40
+ if (error.code !== 'ENOENT') throw error
41
+ })
42
+ if (!info?.isFile() || info.nlink !== 1n) throw fail('unsafe-path')
37
43
  assertPlainWindowsPath(path)
44
+ return info
45
+ }
46
+
47
+ function sameRevision(left, right) {
48
+ return ['dev', 'ino', 'size', 'mtimeNs', 'ctimeNs'].every((key) => left[key] === right[key])
49
+ }
50
+
51
+ async function withPlainInput(path, run) {
52
+ const before = await plainFile(path)
53
+ const file = await open(path, fsFlags.O_RDONLY | (fsFlags.O_NOFOLLOW ?? 0) | (fsFlags.O_NONBLOCK ?? 0))
54
+ try {
55
+ const opened = await file.stat({ bigint: true })
56
+ const size = Number(opened.size)
57
+ if (!opened.isFile() || opened.nlink !== 1n || !sameRevision(before, opened) || !Number.isSafeInteger(size)) {
58
+ throw fail('changed')
59
+ }
60
+ const result = await run(file, size, opened)
61
+ if (!sameRevision(opened, await plainFile(path))) throw fail('changed')
62
+ return result
63
+ } finally {
64
+ await file.close()
65
+ }
66
+ }
67
+
68
+ /** Chunks borrow one buffer. Use each chunk before advancing the iterator. */
69
+ async function* readChunks(file, size) {
70
+ const buffer = Buffer.allocUnsafe(Math.min(chunkBytes, size))
71
+ let offset = 0
72
+ while (offset < size) {
73
+ const { bytesRead } = await file.read(buffer, 0, Math.min(buffer.length, size - offset), offset)
74
+ if (bytesRead === 0) throw fail('changed')
75
+ offset += bytesRead
76
+ yield buffer.subarray(0, bytesRead)
77
+ }
78
+ }
79
+
80
+ async function digestFrom(file, size) {
81
+ const hash = createHash('sha256')
82
+ for await (const chunk of readChunks(file, size)) hash.update(chunk)
83
+ return hash.digest('hex')
84
+ }
85
+
86
+ function digestFile(path) {
87
+ return withPlainInput(path, digestFrom)
38
88
  }
39
89
 
40
90
  async function writeDurably(path, bytes) {
41
91
  const temporary = `${path}.${randomUUID()}.tmp`
42
92
  try {
43
93
  const file = await open(temporary, 'wx', 0o600)
44
- try { await file.writeFile(bytes); await file.sync() } finally { await file.close() }
94
+ let result
95
+ try {
96
+ result = typeof bytes === 'function' ? await bytes(file) : await file.writeFile(bytes)
97
+ await file.sync()
98
+ } finally {
99
+ await file.close()
100
+ }
45
101
  await publishPath(temporary, path, { replace: true })
46
102
  await syncDirectory(dirname(path))
103
+ return result
47
104
  } catch (error) {
48
105
  await unlink(temporary).catch(() => {})
49
106
  throw error
50
107
  }
51
108
  }
52
109
 
110
+ function rewriteFirstFrame(frame, { id, oldCwd, targetCwd, allowTorn }) {
111
+ let text
112
+ let header
113
+ let newline
114
+ try {
115
+ text = zstdDecompressSync(frame, { maxOutputLength: maxHeaderBytes }).toString('utf8')
116
+ newline = text.indexOf('\n')
117
+ header = JSON.parse(newline === -1 ? text : text.slice(0, newline))
118
+ } catch (error) {
119
+ throw fail('unsupported', error)
120
+ }
121
+ if (header?.type !== 'session' || header.id !== id || (oldCwd !== undefined && header.cwd !== oldCwd)) {
122
+ throw fail(allowTorn ? 'changed' : 'unsupported')
123
+ }
124
+ if (header.cwd === targetCwd) return frame
125
+ header.cwd = targetCwd
126
+ return zstdCompressSync(JSON.stringify(header) + (newline === -1 ? '' : text.slice(newline)), checksum)
127
+ }
128
+
129
+ async function writeAll(file, chunk) {
130
+ for (let offset = 0; offset < chunk.length;) {
131
+ const { bytesWritten } = await file.write(chunk, offset, chunk.length - offset)
132
+ if (bytesWritten <= 0) throw fail('EIO')
133
+ offset += bytesWritten
134
+ }
135
+ }
136
+
137
+ async function makeWritable(path) {
138
+ const info = await lookup(path)
139
+ if (!info) return
140
+ if (info.isDirectory()) {
141
+ await chmod(path, 0o700).catch(() => {})
142
+ for (const entry of await readdir(path, { withFileTypes: true }).catch(() => [])) {
143
+ await makeWritable(join(path, entry.name))
144
+ }
145
+ } else if (info.isFile()) {
146
+ await chmod(path, 0o600).catch(() => {})
147
+ }
148
+ }
149
+
150
+ async function removeTree(path) {
151
+ try {
152
+ await rm(path, { recursive: true })
153
+ } catch (error) {
154
+ if (error.code !== 'EACCES' && error.code !== 'EPERM') throw error
155
+ await makeWritable(path)
156
+ await rm(path, { recursive: true })
157
+ }
158
+ }
159
+
160
+ async function copyFileDurably(source, target, { signal, preserveMode = true } = {}) {
161
+ return withPlainInput(source, async (input, size, opened) => {
162
+ assertPreparing(signal)
163
+ const output = await open(target, 'wx', 0o600)
164
+ try {
165
+ for await (const chunk of readChunks(input, size)) {
166
+ assertPreparing(signal)
167
+ await writeAll(output, chunk)
168
+ }
169
+ await output.sync()
170
+ } finally {
171
+ await output.close()
172
+ }
173
+ if (preserveMode) {
174
+ const mode = Number(opened.mode) & 0o777
175
+ const needsMode = windows ? (mode & 0o200) === 0 : mode !== 0o600
176
+ if (needsMode) await chmod(target, mode)
177
+ }
178
+ })
179
+ }
180
+
181
+ async function copyTree(source, target, { skip = () => false, signal, preserveMode = true, top = true } = {}) {
182
+ assertPreparing(signal)
183
+ const sourceInfo = await directory(source)
184
+ await mkdir(target, { mode: 0o700 })
185
+ await directory(target)
186
+ for (const entry of await readdir(source, { withFileTypes: true })) {
187
+ assertPreparing(signal)
188
+ if (skip(entry.name, top)) continue
189
+ const from = join(source, entry.name)
190
+ const to = join(target, entry.name)
191
+ if (entry.isDirectory()) await copyTree(from, to, { skip, signal, preserveMode, top: false })
192
+ else await copyFileDurably(from, to, { signal, preserveMode })
193
+ }
194
+ await syncDirectory(target)
195
+ if (!top && preserveMode) {
196
+ const mode = Number(sourceInfo.mode) & 0o777
197
+ const needsMode = windows ? (mode & 0o200) === 0 : mode !== 0o700
198
+ if (needsMode) await chmod(target, mode)
199
+ }
200
+ }
201
+
202
+ async function repairTornTail(input, truncateTo, size, expectedCount, write, signal) {
203
+ const stream = input.createReadStream({ start: truncateTo, end: size - 1, autoClose: false, highWaterMark: chunkBytes })
204
+ const decoder = createZstdDecompress({
205
+ chunkSize: chunkBytes,
206
+ finishFlush: constants.ZSTD_e_flush,
207
+ params: { [constants.ZSTD_d_windowLogMax]: 27 },
208
+ })
209
+ const transport = pipeline(stream, decoder).then(() => undefined, (error) => error)
210
+ let fragments = []
211
+ let lineBytes = 0
212
+ let batch = []
213
+ let batchBytes = 0
214
+ let recovered = 0
215
+ async function flushBatch() {
216
+ if (!batchBytes) return
217
+ const compressed = zstdCompressSync(Buffer.concat(batch, batchBytes), checksum)
218
+ batch = []
219
+ batchBytes = 0
220
+ await write(compressed)
221
+ }
222
+ try {
223
+ try {
224
+ for await (const chunk of decoder) {
225
+ assertPreparing(signal)
226
+ let cursor = 0
227
+ while (cursor < chunk.length) {
228
+ const newline = chunk.indexOf(0x0a, cursor)
229
+ const part = chunk.subarray(cursor, newline < 0 ? chunk.length : newline + 1)
230
+ lineBytes += part.length
231
+ if (lineBytes > maxHeaderBytes) throw fail('history-resource')
232
+ if (newline < 0) fragments.push(Buffer.from(part))
233
+ else {
234
+ const line = fragments.length ? Buffer.concat([...fragments, part], lineBytes) : Buffer.from(part)
235
+ fragments = []
236
+ lineBytes = 0
237
+ try { JSON.parse(line.toString('utf8')) } catch (error) { throw fail('unsupported', error) }
238
+ recovered++
239
+ batch.push(line)
240
+ batchBytes += line.length
241
+ if (batchBytes >= tornBatchBytes) await flushBatch()
242
+ }
243
+ cursor += part.length
244
+ }
245
+ }
246
+ const transportError = await transport
247
+ if (transportError) {
248
+ assertPreparing(signal)
249
+ if (recovered > 0) throw fail('unsupported', transportError)
250
+ }
251
+ } catch (error) {
252
+ assertPreparing(signal)
253
+ if (error?.code === 'history-resource' || error?.code === 'unsupported') throw error
254
+ if (recovered > 0) throw fail('unsupported', error)
255
+ }
256
+ } finally {
257
+ decoder.destroy()
258
+ stream.destroy()
259
+ await transport
260
+ }
261
+ await flushBatch()
262
+ if (recovered !== expectedCount) throw fail('changed')
263
+ }
264
+
265
+ /** Replace just the independent header frame and copy all original body bytes. */
266
+ function rewriteLog(source, target, options) {
267
+ return writeDurably(target, (output) => withPlainInput(source, async (input, size) => {
268
+ const truncateTo = options.tornTruncateTo
269
+ if (truncateTo !== undefined && (!Number.isSafeInteger(truncateTo) || truncateTo <= 0 || truncateTo >= size)) {
270
+ throw fail('changed')
271
+ }
272
+ const scanner = createFrameScanner()
273
+ const oldHash = createHash('sha256')
274
+ const nextHash = createHash('sha256')
275
+ let nextBytes = 0
276
+ let offset = 0
277
+ let headerLength = 0
278
+ let headerWritten = false
279
+ let headerParts = []
280
+ async function write(chunk) {
281
+ if (!chunk.length) return
282
+ await writeAll(output, chunk)
283
+ nextHash.update(chunk)
284
+ nextBytes += chunk.length
285
+ }
286
+ for await (const chunk of readChunks(input, size)) {
287
+ assertPreparing(options.signal)
288
+ oldHash.update(chunk)
289
+ const active = truncateTo === undefined ? chunk
290
+ : offset >= truncateTo ? chunk.subarray(0, 0) : chunk.subarray(0, Math.min(chunk.length, truncateTo - offset))
291
+ if (active.length) {
292
+ let headerEnd
293
+ scanner.write(active, headerWritten ? undefined : ({ end }) => { headerEnd ??= end })
294
+ if (headerWritten) {
295
+ await write(active)
296
+ } else {
297
+ const headerInChunk = headerEnd === undefined ? active.length : headerEnd - offset
298
+ headerLength += headerInChunk
299
+ if (headerLength > maxHeaderBytes) throw fail('unsupported')
300
+ headerParts.push(Buffer.from(active.subarray(0, headerInChunk)))
301
+ if (headerEnd !== undefined) {
302
+ await write(rewriteFirstFrame(Buffer.concat(headerParts, headerLength), options))
303
+ headerParts = []
304
+ headerWritten = true
305
+ await write(active.subarray(headerInChunk))
306
+ }
307
+ }
308
+ }
309
+ offset += chunk.length
310
+ }
311
+ if (!headerWritten || (!options.allowTorn && scanner.finish() !== undefined)) throw fail('unsupported')
312
+ if (truncateTo !== undefined) {
313
+ await repairTornTail(input, truncateTo, size, options.tornRecoveredCount ?? 0, write, options.signal)
314
+ }
315
+ if (options.append) await write(zstdCompressSync(JSON.stringify(options.append) + '\n', checksum))
316
+ return { oldHash: oldHash.digest('hex'), nextHash: nextHash.digest('hex'), nextBytes }
317
+ }))
318
+ }
319
+
320
+ function restoreOriginal(source, target, expected) {
321
+ return writeDurably(target, (output) => withPlainInput(source, async (input, size) => {
322
+ const hash = createHash('sha256')
323
+ for await (const chunk of readChunks(input, size)) {
324
+ hash.update(chunk)
325
+ await writeAll(output, chunk)
326
+ }
327
+ if (hash.digest('hex') !== expected) throw fail('changed')
328
+ }))
329
+ }
330
+
53
331
  async function renameDurably(from, to) {
54
332
  try { await restorePath(from, to) } catch (error) {
55
333
  if (error.code === 'EXDEV') throw fail('cross-device', error)
@@ -74,47 +352,90 @@ function isShadow(name) {
74
352
 
75
353
  // The native reader selects v4 in a directory with older compressed generations.
76
354
  // 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)
355
+ async function planCopies(plan, backups, signal, summaries, readSpace = statfs) {
356
+ const volume = await directory(backups)
357
+ const space = await readSpace(backups, { bigint: true })
358
+ const block = space.frsize > 0n ? space.frsize : space.bsize
359
+ if (block <= 0n || space.bavail < 0n) throw fail('disk-space')
360
+ // Reserve journal metadata plus per-member headroom for the rewritten header
361
+ // delta and appended directory event, rather than the 16 MiB decode ceiling.
362
+ let required = 1024n * 1024n + 8n * block
363
+ const round = (size) => ((size + block - 1n) / block) * block
364
+ const cwdHeadroom = BigInt(Buffer.byteLength(plan.targetCwd)) * 2n + 64n * 1024n
365
+ const trees = new Map()
366
+ for (const { id, oldCwd, oldDir, nextDir } of plan.members) {
367
+ if (oldCwd === plan.targetCwd) continue
368
+ const shadows = []
369
+ const inPlace = oldDir === nextDir
370
+ const nextParent = dirname(nextDir)
371
+ const targetVolume = await lookup(nextParent) ? await directory(nextParent) : await directory(dirname(nextParent))
372
+ if (targetVolume.dev !== volume.dev) throw fail('cross-device')
373
+ const tornTruncateTo = summaries?.get(id)?.tornTruncateTo
374
+ required += round(cwdHeadroom) + 4n * block
375
+ await inspectTree(oldDir, '', shadows, inPlace, tornTruncateTo)
376
+ trees.set(id, shadows)
87
377
  }
88
- }
378
+ if (required > space.bavail * block) throw fail('disk-space')
379
+ return trees
89
380
 
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
381
+ async function inspectTree(path, relative, shadows, inPlace, tornTruncateTo) {
382
+ assertPreparing(signal)
383
+ if ((await directory(path)).dev !== volume.dev) throw fail('cross-device')
384
+ required += inPlace ? block : 2n * block
385
+ for (const entry of await readdir(path, { withFileTypes: true })) {
386
+ assertPreparing(signal)
387
+ const child = join(path, entry.name)
388
+ const top = relative === ''
389
+ if (top && entry.name === LOCK_FILENAME) continue
390
+ if (top && generation(entry.name)) {
391
+ if (entry.name !== LOG_FILENAME && !isShadow(entry.name)) throw fail('unsupported')
392
+ if (entry.name !== LOG_FILENAME) shadows.push(entry.name)
393
+ } else if (entry.isDirectory()) {
394
+ await inspectTree(child, entry.name, shadows, inPlace, tornTruncateTo)
395
+ continue
396
+ }
397
+ const info = await plainFile(child)
398
+ if (info.dev !== BigInt(volume.dev)) throw fail('cross-device')
399
+ const copies = !inPlace || (top && entry.name === LOG_FILENAME) ? 2n : 1n
400
+ required += copies * (round(info.size) + block)
401
+ if (top && entry.name === LOG_FILENAME && tornTruncateTo !== undefined && info.size > BigInt(tornTruncateTo)) {
402
+ required += round(info.size - BigInt(tornTruncateTo))
403
+ }
404
+ }
101
405
  }
102
- return false
103
406
  }
104
407
 
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() }
408
+ function hasPublishedPrefix(path, { nextBytes, nextHash }, exact) {
409
+ return withPlainInput(path, async (file, size) => {
410
+ if (nextBytes !== undefined) {
411
+ if (size < nextBytes || (exact && size !== nextBytes)) return false
412
+ return await digestFrom(file, nextBytes) === nextHash
112
413
  }
113
- }
114
- await syncDirectory(path)
414
+ if (await digestFrom(file, size) === nextHash) return true
415
+ if (exact) return false
416
+ // Older journals recorded only the digest. Native appends start a new
417
+ // frame, so check the digest at each complete boundary.
418
+ const hash = createHash('sha256')
419
+ const scanner = createFrameScanner()
420
+ let offset = 0
421
+ let matched = false
422
+ for await (const chunk of readChunks(file, size)) {
423
+ let cursor = 0
424
+ scanner.write(chunk, ({ end }) => {
425
+ if (matched) return
426
+ const boundary = end - offset
427
+ hash.update(chunk.subarray(cursor, boundary))
428
+ cursor = boundary
429
+ matched = hash.copy().digest('hex') === nextHash
430
+ })
431
+ if (!matched) hash.update(chunk.subarray(cursor))
432
+ offset += chunk.length
433
+ }
434
+ return matched
435
+ })
115
436
  }
116
437
 
117
- export function moveStorage(root, base, { checkpoint = async () => {} } = {}) {
438
+ export function moveStorage(root, base, { checkpoint = async () => {}, statfs: readSpace = statfs } = {}) {
118
439
  const journal = join(base, journalName)
119
440
  const backups = join(base, 'backups')
120
441
 
@@ -194,11 +515,37 @@ export function moveStorage(root, base, { checkpoint = async () => {} } = {}) {
194
515
  const target = ticketDir(ticket)
195
516
  if (await lookup(target)) {
196
517
  await directory(target)
197
- await rm(target, { recursive: true })
518
+ await removeTree(target)
198
519
  await syncDirectory(backups)
199
520
  }
200
521
  }
201
522
 
523
+ async function discardPrepared(ticket) {
524
+ if (await hasJournal()) return false
525
+ await removeTicket(ticket)
526
+ return true
527
+ }
528
+
529
+ async function hasOrphans() {
530
+ const info = await lookup(backups)
531
+ if (!info?.isDirectory()) return false
532
+ const entries = await readdir(backups, { withFileTypes: true })
533
+ return entries.some((entry) => entry.isDirectory() && isTicket(entry.name))
534
+ }
535
+
536
+ async function sweepOrphans() {
537
+ if (await hasJournal()) return 0
538
+ if (!await lookup(backups)) return 0
539
+ await directory(backups)
540
+ let removed = 0
541
+ for (const entry of await readdir(backups, { withFileTypes: true })) {
542
+ if (!entry.isDirectory() || !isTicket(entry.name)) continue
543
+ await removeTicket(entry.name)
544
+ removed++
545
+ }
546
+ return removed
547
+ }
548
+
202
549
  async function finish(state) {
203
550
  await removeTicket(state.ticket)
204
551
  await unlink(journal)
@@ -237,14 +584,18 @@ export function moveStorage(root, base, { checkpoint = async () => {} } = {}) {
237
584
  }
238
585
  }
239
586
 
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()
587
+ async function prepare(_ctx, plan, ledger, lockStage, { signal, summaries = new Map() } = {}) {
588
+ // The leases pin this exact cut until commit. Keep only the bounded
589
+ // projection values, and use the same cut for the appended event.
244
590
  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)
591
+ assertPreparing(signal)
592
+ summaries.set(member.id, await inspectMoveHistory({ path: member.oldFile, id: member.id,
593
+ cwd: member.oldCwd, checkInbox: true }, { signal }))
247
594
  }
595
+ await directory(root)
596
+ await directory(backups, true)
597
+ const sourceTrees = await planCopies(plan, backups, signal, summaries, readSpace)
598
+ assertPreparing(signal)
248
599
 
249
600
  const ticket = randomUUID()
250
601
  const home = ticketDir(ticket)
@@ -270,29 +621,24 @@ export function moveStorage(root, base, { checkpoint = async () => {} } = {}) {
270
621
  if ((await directory(oldDir)).dev !== (await directory(home)).dev
271
622
  || (await directory(dirname(nextDir))).dev !== (await directory(home)).dev) throw fail('cross-device')
272
623
  if (!inPlace && await lookup(nextDir)) throw fail('collision')
273
- const shadows = []
274
- await validateTree(oldDir, shadows)
624
+ const shadows = sourceTrees.get(id)
275
625
  const name = encodeSegment(id)
276
626
  const original = join(home, 'original', name)
277
627
  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)
628
+ await copyTree(oldDir, original, { skip: (file, top) => top && file === LOCK_FILENAME, signal })
281
629
  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)
630
+ else await copyTree(original, stage, { skip: (file, top) => top && file === LOG_FILENAME, signal })
631
+ assertPreparing(signal)
632
+ const cut = summaries.get(id)
633
+ const cwdChangeSeq = cut.lastSeq + 1
288
634
  // DSH turns this event into native runtime context on the next request.
289
635
  const cwdChange = {
290
636
  type: 'working-directory/change', seq: cwdChangeSeq, time: Date.now(), data: { cwd: plan.targetCwd },
291
637
  }
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)
638
+ const fingerprints = await rewriteLog(join(original, LOG_FILENAME), join(stage, LOG_FILENAME), {
639
+ id, oldCwd, targetCwd: plan.targetCwd, append: cwdChange, signal,
640
+ tornTruncateTo: cut.tornTruncateTo, tornRecoveredCount: cut.tornRecoveredCount,
641
+ })
296
642
  if (!inPlace) {
297
643
  await lockStage(stage)
298
644
  if (shadows.length) {
@@ -301,15 +647,16 @@ export function moveStorage(root, base, { checkpoint = async () => {} } = {}) {
301
647
  await syncDirectory(holding)
302
648
  }
303
649
  }
304
- await syncTree(stage)
650
+ await syncDirectory(stage)
305
651
  state.members.push({
306
- ...entry, oldHash: digest(bytes), nextHash: digest(next), nextBytes: next.length,
652
+ ...entry, ...fingerprints,
307
653
  cwdChangeSeq, ...(!inPlace && shadows.length ? { shadows } : {}),
308
654
  })
309
655
  }
310
656
  for (const path of privateDirectories) await syncDirectory(join(home, path))
311
657
  await syncDirectory(home)
312
658
  await syncDirectory(backups)
659
+ assertPreparing(signal)
313
660
  return state
314
661
  } catch (error) {
315
662
  await removeTicket(ticket).catch(() => {})
@@ -323,7 +670,7 @@ export function moveStorage(root, base, { checkpoint = async () => {} } = {}) {
323
670
  if (p.unchanged) continue
324
671
  await plainFile(p.oldFile)
325
672
  if (p.inPlace) {
326
- if (digest(await readFile(p.oldFile)) !== member.oldHash) throw fail('changed')
673
+ if (await digestFile(p.oldFile) !== member.oldHash) throw fail('changed')
327
674
  // The original remains visible until a single replace publishes the new
328
675
  // log. Both headers derive the same physical path, and the lease stays put.
329
676
  await publishPath(p.stageFile, p.oldFile, { replace: true })
@@ -356,26 +703,24 @@ export function moveStorage(root, base, { checkpoint = async () => {} } = {}) {
356
703
  if (p.inPlace) {
357
704
  await plainFile(p.oldFile)
358
705
  if (await lookup(p.stageFile)) continue
359
- const current = digest(await readFile(p.oldFile))
706
+ const current = await digestFile(p.oldFile)
360
707
  if (current === member.oldHash) continue
361
708
  // Do not overwrite a log that acquired additional entries after publish.
362
709
  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))
710
+ if (await digestFile(p.originalFile) !== member.oldHash) throw fail('changed')
711
+ actions.push(() => restoreOriginal(p.originalFile, p.oldFile, member.oldHash))
367
712
  continue
368
713
  }
369
714
  if (await lookup(p.held)) {
370
715
  if (await lookup(p.oldFile)) throw fail('restore-pending')
371
716
  if (!await lookup(p.stage)) {
372
717
  await directory(p.nextDir)
373
- await plainFile(p.nextFile)
374
- if (digest(await readFile(p.nextFile)) !== member.nextHash) throw fail('changed')
718
+ if (await digestFile(p.nextFile) !== member.nextHash) throw fail('changed')
375
719
  actions.push(() => renameDurably(p.nextDir, p.stage))
376
720
  }
377
- await plainFile(p.held)
378
- if (member.oldHash && digest(await readFile(p.held)) !== member.oldHash) throw fail('changed')
721
+ if (member.oldHash) {
722
+ if (await digestFile(p.held) !== member.oldHash) throw fail('changed')
723
+ } else await plainFile(p.held)
379
724
  actions.push(() => renameDurably(p.held, p.oldFile))
380
725
  } else {
381
726
  // The source was never hidden, or a prior recovery put it back.
@@ -394,14 +739,13 @@ export function moveStorage(root, base, { checkpoint = async () => {} } = {}) {
394
739
  for (const action of actions) await action()
395
740
  }
396
741
 
397
- async function verifyPublished(state) {
742
+ async function verifyPublished(state, { exact = false } = {}) {
398
743
  for (const member of state.members) {
399
744
  const p = paths(state, member)
400
745
  if (p.unchanged) continue
401
746
  if (await lookup(p.inPlace ? p.stageFile : p.stage)) throw fail('changed')
402
747
  await directory(p.nextDir)
403
- await plainFile(p.nextFile)
404
- if (!hasPublishedPrefix(await readFile(p.nextFile), member)) throw fail('changed')
748
+ if (!await hasPublishedPrefix(p.nextFile, member, exact)) throw fail('changed')
405
749
  }
406
750
  }
407
751
 
@@ -413,14 +757,15 @@ export function moveStorage(root, base, { checkpoint = async () => {} } = {}) {
413
757
  if (p.unchanged || p.inPlace || !await lookup(p.oldDir)) continue
414
758
  await directory(p.oldDir)
415
759
  if ((await readdir(p.oldDir)).some(generation)) throw fail('changed')
416
- await rm(p.oldDir, { recursive: true })
760
+ await removeTree(p.oldDir)
417
761
  await syncDirectory(dirname(p.oldDir))
418
762
  }
419
763
  await finish(state)
420
764
  }
421
765
 
422
766
  return {
423
- hasJournal, readState, hasHeld, withLock, save, finish, withSessionLocks, prepare, publish, rollback, verifyPublished, cleanCommitted,
767
+ hasJournal, readState, hasHeld, hasOrphans, sweepOrphans, discardPrepared,
768
+ withLock, save, finish, withSessionLocks, prepare, publish, rollback, verifyPublished, cleanCommitted,
424
769
  }
425
770
  }
426
771
 
@@ -457,10 +802,7 @@ export async function recoverLegacyDisk(root, base) {
457
802
  }
458
803
  const file = join(held, LOG_FILENAME)
459
804
  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))
805
+ await rewriteLog(file, file, { id, targetCwd: oldCwd, allowTorn: true })
464
806
  await renameDurably(held, oldDir)
465
807
  }
466
808
  // Keep the v0.1.0 backup for manual inspection. Its ledger order was not journaled.