dsh-remote 1.4.1 → 1.6.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.
package/lib/sync.js CHANGED
@@ -18,21 +18,33 @@
18
18
  // After a successful pull the local mtime is aligned to the remote mtime, and
19
19
  // after a successful push the local mtime is aligned to the remote mtime the
20
20
  // server assigned — so the invariant L==R==S holds and the next run is cheap.
21
- import { readdirSync, statSync, mkdirSync, existsSync, readFileSync, writeFileSync, utimesSync, renameSync } from 'node:fs'
21
+ import { readdirSync, statSync, lstatSync, existsSync, mkdirSync, readFileSync, writeFileSync, utimesSync, renameSync } from 'node:fs'
22
22
  import path from 'node:path'
23
+ import { assertDownloadHasNoSymlinks, mirrorDownloadTarget } from './mirror-paths.js'
23
24
  import { joinRemotePath, relPathUnder } from './paths.js'
24
25
 
25
- function mapLimit(items, limit, fn) {
26
- const limitN = Math.max(1, Math.min(Math.floor(limit) || 1, items.length))
26
+ function transferFiles(items, maxFiles, stats, transfer, isCancelled = () => false) {
27
+ const workerCount = Math.min(4, items.length)
27
28
  let next = 0
29
+ let inFlight = 0
28
30
  const worker = async () => {
29
- while (next < items.length) {
30
- const i = next++
31
- try { await fn(items[i], i) } catch { /* per-item errors are the fn's concern */ }
31
+ // Reserve a slot before processing the candidate. If it doesn't transfer,
32
+ // this worker can reuse the slot for the next candidate. A cancelled run
33
+ // (#258) stops reserving new work; already in-flight items finish.
34
+ while (next < items.length && stats.files + inFlight < maxFiles && !isCancelled()) {
35
+ const item = items[next++]
36
+ inFlight++
37
+ try {
38
+ if (await transfer(item)) stats.files++
39
+ } catch {
40
+ // Per-item errors are the transfer's concern.
41
+ } finally {
42
+ inFlight--
43
+ }
32
44
  }
33
45
  }
34
46
  const workers = []
35
- for (let w = 0; w < limitN; w++) workers.push(worker())
47
+ for (let w = 0; w < workerCount; w++) workers.push(worker())
36
48
  return Promise.all(workers)
37
49
  }
38
50
 
@@ -41,6 +53,13 @@ const localKey = (st) => (st ? keyOf(st.size, st.mtimeMs / 1000) : null)
41
53
  const remoteKey = (st) => (st ? keyOf(st.size, st.mtime) : null)
42
54
  const isChannelError = (err) => /sftp (?:channel closed|operation timed out)/i.test(String((err && err.message) || err))
43
55
 
56
+ function downloadFileStat(root, file) {
57
+ assertDownloadHasNoSymlinks(root, file)
58
+ const info = lstatSync(file, { throwIfNoEntry: false })
59
+ if (info && !info.isFile()) throw new Error('The sync destination must be a regular file')
60
+ return info
61
+ }
62
+
44
63
  /** Recursively pull remote → local mirror (three-way, ignore-aware). */
45
64
  export async function syncTree(sftp, remoteDir, localDir, opts = {}) {
46
65
  const {
@@ -53,6 +72,7 @@ export async function syncTree(sftp, remoteDir, localDir, opts = {}) {
53
72
  state = {},
54
73
  getSftp = null,
55
74
  maxReconnects = 2,
75
+ isCancelled = () => false,
56
76
  } = opts
57
77
  const stats = {
58
78
  files: 0,
@@ -65,6 +85,7 @@ export async function syncTree(sftp, remoteDir, localDir, opts = {}) {
65
85
  staleRemote: 0,
66
86
  touched: [],
67
87
  truncated: false,
88
+ cancelled: false,
68
89
  }
69
90
  const nextState = { ...state }
70
91
  let curSftp = sftp
@@ -92,30 +113,54 @@ export async function syncTree(sftp, remoteDir, localDir, opts = {}) {
92
113
  try {
93
114
  return await fn(surface)
94
115
  } catch (err) {
95
- if (isChannelError(err)) {
116
+ if (!isCancelled() && isChannelError(err)) {
96
117
  try {
97
118
  const next = await reconnectSftp(surface)
98
- if (next) return await fn(next)
119
+ if (next && !isCancelled()) return await fn(next)
99
120
  } catch (retryErr) {
100
121
  if (isChannelError(retryErr)) err = retryErr
101
122
  else throw retryErr
102
123
  }
103
- channelDead = true
104
- if (!stats.abortedError) stats.abortedError = String((err && err.message) || err)
124
+ if (!isCancelled()) {
125
+ channelDead = true
126
+ if (!stats.abortedError) stats.abortedError = String((err && err.message) || err)
127
+ }
105
128
  }
106
129
  throw err
107
130
  }
108
131
  }
109
132
 
133
+ const remotePath = /^(?:[a-z]:[\\/]|\\\\)/i.test(remoteDir) ? path.win32 : path.posix
134
+ const localRoot = path.resolve(localDir)
135
+ const downloadEntry = (parent, name, isDir) => {
136
+ try {
137
+ if (!name || remotePath.basename(name) !== name || name.includes('\0')) throw new Error('Invalid remote entry name')
138
+ const rp = remotePath.join(parent, name)
139
+ const rel = relPathUnder(remoteDir, rp) || name
140
+ if (isIgnored(rel, isDir)) return null
141
+ const lp = mirrorDownloadTarget(localRoot, remoteDir, rp)
142
+ assertDownloadHasNoSymlinks(localRoot, lp)
143
+ return { rp, lp, rel }
144
+ } catch {
145
+ stats.failed++
146
+ return null
147
+ }
148
+ }
149
+
110
150
  const walk = async (rDir, lDir, depth) => {
111
- if (channelDead) return
151
+ if (channelDead || isCancelled()) return
112
152
  let entries
113
153
  try {
114
154
  entries = (await callSftp((s) => s.readdir(rDir))) || []
155
+ assertDownloadHasNoSymlinks(localRoot, lDir)
156
+ const existing = lstatSync(lDir, { throwIfNoEntry: false })
157
+ if (existing && !existing.isDirectory()) throw new Error('The sync destination must be a directory')
158
+ if (!dryRun && !existing) mkdirSync(lDir, { recursive: true })
115
159
  } catch {
116
160
  stats.failed++
117
161
  return
118
162
  }
163
+ if (isCancelled()) return
119
164
  if (!dryRun && !existsSync(lDir)) mkdirSync(lDir, { recursive: true })
120
165
 
121
166
  // Sync files in the current directory BEFORE recursing into subdirectories,
@@ -125,28 +170,26 @@ export async function syncTree(sftp, remoteDir, localDir, opts = {}) {
125
170
  (e) => !(e.attrs && e.attrs.isDirectory && e.attrs.isDirectory()) &&
126
171
  String(e.filename) !== '.' && String(e.filename) !== '..',
127
172
  )
128
- await mapLimit(files, 4, async (e) => {
173
+ await transferFiles(files, maxFiles, stats, async (e) => {
129
174
  if (channelDead) return
130
175
  if (stats.files >= maxFiles) { stats.truncated = true; return }
131
- const name = String(e.filename)
132
- const rp = joinRemotePath(rDir, name)
133
- const lp = path.join(lDir, name)
134
- const rel = relPathUnder(remoteDir, rp) || name
135
- if (isIgnored(rel, false)) return
136
- let r
176
+ // #258: a cancelled run must not preflight a NOT-yet-started entry.
177
+ if (isCancelled()) return
178
+ const target = downloadEntry(rDir, String(e.filename ?? ''), false)
179
+ if (!target) return
180
+ const { rp, lp, rel } = target
181
+ let r, lk
137
182
  try {
138
183
  r = await callSftp((s) => s.stat(rp))
184
+ lk = localKey(downloadFileStat(localRoot, lp))
139
185
  } catch {
140
186
  stats.failed++
141
187
  return
142
188
  }
189
+ if (isCancelled()) return
143
190
  if (maxFileBytes > 0 && r.size > maxFileBytes) { stats.skippedLarge++; return }
144
191
  const rk = remoteKey(r)
145
192
  const sk = state[rel] ? keyOf(state[rel].size, state[rel].mtime) : null
146
- let lk = null
147
- if (existsSync(lp)) {
148
- try { lk = localKey(statSync(lp)) } catch { lk = null }
149
- }
150
193
  if (sk && rk === sk && lk && lk === sk) { stats.skippedUnchanged++; return }
151
194
  if (!force && sk && rk !== sk && lk && lk !== sk && rk !== lk) {
152
195
  stats.conflicts.push({ path: rp, reason: 'both-modified(远端与本地都改过,跳过不覆盖)' })
@@ -158,29 +201,29 @@ export async function syncTree(sftp, remoteDir, localDir, opts = {}) {
158
201
  return
159
202
  }
160
203
  if (dryRun) {
161
- stats.files++
162
204
  stats.touched.push(rp)
163
205
  nextState[rel] = { size: r.size, mtime: r.mtime }
164
- return
206
+ return true
165
207
  }
166
208
  try {
167
209
  const buf = await callSftp((s) => s.readFile(rp))
210
+ downloadFileStat(localRoot, lp)
168
211
  writeFileSync(lp, buf)
169
212
  try { utimesSync(lp, new Date(r.mtime * 1000), new Date(r.mtime * 1000)) } catch {}
170
- stats.files++
171
213
  stats.touched.push(rp)
172
214
  nextState[rel] = { size: r.size, mtime: r.mtime }
215
+ return true
173
216
  } catch {
174
217
  stats.failed++
175
218
  }
176
219
  })
177
- if (channelDead) return
220
+ if (channelDead || isCancelled()) return
178
221
  if (stats.files >= maxFiles) { stats.truncated = true; return }
179
222
 
180
223
  // Subdirectories next (sequential, depth-bounded). Local directories are
181
224
  // only created after their remote readdir succeeds, never when SFTP is dead.
182
225
  for (const e of entries) {
183
- if (channelDead) break
226
+ if (channelDead || isCancelled()) break
184
227
  const name = String(e.filename)
185
228
  if (name === '.' || name === '..') continue
186
229
  const isDir = !!(e.attrs && e.attrs.isDirectory && e.attrs.isDirectory())
@@ -189,17 +232,16 @@ export async function syncTree(sftp, remoteDir, localDir, opts = {}) {
189
232
  stats.truncated = true
190
233
  continue
191
234
  }
192
- const rp = joinRemotePath(rDir, name)
193
- const lp = path.join(lDir, name)
194
- const rel = relPathUnder(remoteDir, rp) || name
195
- if (isIgnored(rel, true)) continue
196
- await walk(rp, lp, depth - 1)
197
- if (!channelDead) stats.dirs++
235
+ const target = downloadEntry(rDir, name, true)
236
+ if (!target) continue
237
+ await walk(target.rp, target.lp, depth - 1)
238
+ if (!channelDead && !isCancelled()) stats.dirs++
198
239
  if (stats.files >= maxFiles) { stats.truncated = true; break }
199
240
  }
200
241
  }
201
242
 
202
- await walk(remoteDir, localDir, maxDepth)
243
+ await walk(remoteDir, localRoot, maxDepth)
244
+ stats.cancelled = isCancelled()
203
245
  if (stats.files >= maxFiles) stats.truncated = true
204
246
  // Informational: remote entries in the snapshot that no longer exist remotely.
205
247
  for (const rel of Object.keys(state)) {
@@ -217,11 +259,13 @@ export async function pushTree(sftp, localDir, remoteDir, opts = {}) {
217
259
  dryRun = false,
218
260
  force = false,
219
261
  state = {},
262
+ isCancelled = () => false,
220
263
  } = opts
221
- const stats = { files: 0, dirs: 0, skippedUnchanged: 0, skippedLarge: 0, conflicts: [], staleLocal: 0, pushed: [], truncated: false }
264
+ const stats = { files: 0, dirs: 0, skippedUnchanged: 0, skippedLarge: 0, failed: 0, conflicts: [], staleLocal: 0, pushed: [], truncated: false, cancelled: false }
222
265
  const nextState = { ...state }
223
266
 
224
267
  const walk = async (lDir, rDir) => {
268
+ if (isCancelled()) return
225
269
  const entries = readdirSync(lDir, { withFileTypes: true }).filter(
226
270
  (e) => e.name !== '.dsh-remote-meta.json' && e.name !== '.dsh-remote-sync-state.json',
227
271
  )
@@ -231,26 +275,36 @@ export async function pushTree(sftp, localDir, remoteDir, opts = {}) {
231
275
  const rp = joinRemotePath(rDir, e.name)
232
276
  const rel = relPathUnder(remoteDir, rp) || e.name
233
277
  if (isIgnored(rel, true)) continue
234
- try { await sftp.mkdir(rp) } catch { /* already exists */ }
278
+ if (!dryRun) {
279
+ try { await sftp.mkdir(rp) } catch { /* already exists */ }
280
+ }
235
281
  stats.dirs++
236
282
  await walk(path.join(lDir, e.name), rp)
283
+ if (isCancelled()) return
237
284
  if (stats.files >= maxFiles) break
238
285
  }
239
286
  if (stats.files >= maxFiles) { stats.truncated = true; return }
240
287
 
241
288
  const files = entries.filter((e) => !e.isDirectory())
242
- await mapLimit(files, 4, async (e) => {
289
+ await transferFiles(files, maxFiles, stats, async (e) => {
243
290
  if (stats.files >= maxFiles) { stats.truncated = true; return }
291
+ // #258: a cancelled run must not even preflight a NOT-yet-started entry
292
+ // (the cancel test asserts no new sftp.stat after cancellation).
293
+ if (isCancelled()) return
244
294
  const lp = path.join(lDir, e.name)
245
295
  const rp = joinRemotePath(rDir, e.name)
246
296
  const rel = relPathUnder(remoteDir, rp) || e.name
247
297
  if (isIgnored(rel, false)) return
248
298
  let l
249
- try { l = statSync(lp) } catch { return }
299
+ try { l = statSync(lp) } catch {
300
+ stats.failed++
301
+ return
302
+ }
250
303
  if (maxFileBytes > 0 && l.size > maxFileBytes) { stats.skippedLarge++; return }
251
304
  const lk = localKey(l)
252
305
  let r = null
253
306
  try { r = await sftp.stat(rp) } catch { /* absent → upload */ }
307
+ if (isCancelled()) return
254
308
  const rk = remoteKey(r)
255
309
  const sk = state[rel] ? keyOf(state[rel].size, state[rel].mtime) : null
256
310
  if (r && sk && lk === sk && rk === sk) { stats.skippedUnchanged++; return }
@@ -266,27 +320,29 @@ export async function pushTree(sftp, localDir, remoteDir, opts = {}) {
266
320
  // Normal case: local edited since sync, remote untouched → push.
267
321
  }
268
322
  if (dryRun) {
269
- stats.files++
270
323
  stats.pushed.push(rp)
271
- return
324
+ return true
272
325
  }
273
326
  try {
274
327
  const buf = readFileSync(lp)
275
328
  await sftp.writeFile(rp, buf)
276
- // Align local mtime to whatever the remote server assigned, so the
277
- // L==R==S invariant holds for the next run.
329
+ // Finalize a started upload even if cancelled. The server mtime keeps
330
+ // the local file and its snapshot aligned with the completed upload.
278
331
  let r2 = null
279
332
  try { r2 = await sftp.stat(rp) } catch {}
280
333
  const rmt = r2 ? r2.mtime : Math.floor(Date.now() / 1000)
281
334
  try { utimesSync(lp, new Date(rmt * 1000), new Date(rmt * 1000)) } catch {}
282
- stats.files++
283
335
  stats.pushed.push(rp)
284
336
  nextState[rel] = { size: l.size, mtime: rmt }
285
- } catch { /* skip unwritable */ }
337
+ return true
338
+ } catch {
339
+ stats.failed++
340
+ }
286
341
  })
287
342
  }
288
343
 
289
344
  await walk(localDir, remoteDir)
345
+ stats.cancelled = isCancelled()
290
346
  if (stats.files >= maxFiles) stats.truncated = true
291
347
  for (const rel of Object.keys(state)) {
292
348
  if (state[rel] && !nextState[rel]) stats.staleLocal++
@@ -297,7 +353,9 @@ export async function pushTree(sftp, localDir, remoteDir, opts = {}) {
297
353
  /** Load the sync-state snapshot from a mirror dir (or {}). */
298
354
  export function loadSyncState(localDir) {
299
355
  try {
300
- const j = JSON.parse(readFileSync(path.join(localDir, '.dsh-remote-sync-state.json'), 'utf8'))
356
+ const target = path.resolve(localDir, '.dsh-remote-sync-state.json')
357
+ if (!downloadFileStat(localDir, target)) return {}
358
+ const j = JSON.parse(readFileSync(target, 'utf8'))
301
359
  if (j && typeof j === 'object' && !Array.isArray(j)) return j
302
360
  } catch {}
303
361
  return {}
@@ -306,10 +364,13 @@ export function loadSyncState(localDir) {
306
364
  /** Persist the snapshot (atomic-ish: tmp + rename). */
307
365
  export function saveSyncState(localDir, state) {
308
366
  try {
367
+ const target = path.resolve(localDir, '.dsh-remote-sync-state.json')
368
+ const tmp = `${target}.tmp`
369
+ downloadFileStat(localDir, target)
370
+ downloadFileStat(localDir, tmp)
309
371
  mkdirSync(localDir, { recursive: true })
310
- const tmp = path.join(localDir, '.dsh-remote-sync-state.json.tmp')
311
372
  writeFileSync(tmp, JSON.stringify(state, null, 1))
312
- renameSync(tmp, path.join(localDir, '.dsh-remote-sync-state.json'))
373
+ renameSync(tmp, target)
313
374
  } catch { /* best effort */ }
314
375
  }
315
376
 
package/lib/terminal.js CHANGED
@@ -60,15 +60,19 @@ class TerminalSession {
60
60
 
61
61
  _push(text) {
62
62
  if (!text) return
63
+ const bytes = Buffer.byteLength(text, 'utf8')
63
64
  this.chunks.push({ at: this.total, text })
64
- this.total += Buffer.byteLength(text, 'utf8')
65
- this.retained += text.length
65
+ this.total += bytes
66
+ // `retained` shares the byte accounting `total` has used since 953a5f1:
67
+ // text.length is UTF-16 code units, so counting those let CJK output (3
68
+ // bytes/char) hold up to 3x TERMINAL_RING_BYTES before the head dropped.
69
+ this.retained += bytes
66
70
  // Drop from the head until back inside the budget. A single huge chunk is
67
71
  // kept whole (truncating a UTF-8 string mid-chunk would corrupt it); the
68
72
  // lossy flag already tells the reader bytes are missing.
69
73
  while (this.retained > TERMINAL_RING_BYTES && this.chunks.length > 1) {
70
74
  const dropped = this.chunks.shift()
71
- this.retained -= dropped.text.length
75
+ this.retained -= Buffer.byteLength(dropped.text, 'utf8')
72
76
  }
73
77
  }
74
78
 
package/lib/update.js CHANGED
@@ -9,10 +9,14 @@
9
9
  // • applyUpdate() — download the tarball, extract package/{lib,package.json,
10
10
  // cordis.patch.yml} with a minimal tar reader, verify the version, then
11
11
  // replace the installed files atomically (temp file + rename, never a
12
- // half-written lib/*.js). A `.dsh-remote-updated` marker records the version
13
- // that landed; the host half removes it once that version is the code it is
14
- // actually running (see LOADED_VERSION), so the marker means "restart still
15
- // required" rather than "an update once happened".
12
+ // half-written lib/*.js) and remove managed files the new tarball dropped,
13
+ // so the tree ends up exactly what shipped. A failure rolls back EVERY
14
+ // file it touched — the tree is always fully old or fully new, never
15
+ // half-applied (the #164 promise, completed). A `.dsh-remote-updated`
16
+ // marker records the version that landed; the host half removes it once
17
+ // that version is the code it is actually running (see LOADED_VERSION), so
18
+ // the marker means "restart still required" rather than "an update once
19
+ // happened".
16
20
  // • reloadSelf() — swap the RUNNING host half to the code now on disk: drop
17
21
  // Node's module caches for this package's own files, then dispose + re-init
18
22
  // the loader entry so apply() runs again from the fresh module. Without it
@@ -335,9 +339,11 @@ function parseTar(buf) {
335
339
 
336
340
  /**
337
341
  * Download the given version's tarball and atomically replace the installed
338
- * package files (lib/*.js, cordis.patch.yml, package.json). On success writes
339
- * `.dsh-remote-updated` in the install dir; throws on any failure (leaves the
340
- * installed files untouched).
342
+ * package files (lib/**, cordis.patch.yml, package.json), removing managed
343
+ * files the new tarball no longer ships so the tree is exactly what shipped.
344
+ * On success writes `.dsh-remote-updated` in the install dir and returns
345
+ * `{ok, to, changed, removed}`; throws on any failure after attempting to
346
+ * roll back every touched file (the tree ends up old, never half-applied).
341
347
  * @param targetVersion - exact npm version to install (e.g. "0.8.0").
342
348
  */
343
349
  export async function applyUpdate(targetVersion, options = {}) {
@@ -451,6 +457,19 @@ export async function applyUpdate(targetVersion, options = {}) {
451
457
  writeAtomic(dest, bytes)
452
458
  changed.push(path.relative(dir, dest).split(path.sep).join('/'))
453
459
  }
460
+ // Completing #164 (commit 25e0e95): its promise is that a failed update
461
+ // can never leave a half-applied tree, so the rollback must attempt EVERY
462
+ // file — stopping at the first restore failure strands the files behind
463
+ // it and produces exactly the mixed tree this function exists to prevent.
464
+ // Verified shape: an old tree shipping the extension-less file `lib/tui`
465
+ // met a tarball adding `lib/tui/helper.js`; the install died ENOTDIR
466
+ // after lib/index.js landed, the reverse-order restore hit the
467
+ // never-existed helper.js first (rmSync ENOTDIR, its parent still being
468
+ // the old file), and the old `break` left index.js NEW while
469
+ // package.json stayed OLD — auto-update then retried the doomed swap
470
+ // forever. Keep the FIRST failure in the message (the backup is retained
471
+ // either way) but keep restoring, so the tree ends fully old even when
472
+ // some restores keep failing.
454
473
  const rollback = () => {
455
474
  if (!mutationStarted) return
456
475
  for (const [dest, saved] of [...backups].reverse()) {
@@ -459,14 +478,50 @@ export async function applyUpdate(targetVersion, options = {}) {
459
478
  if (saved.existed) restoreFile(saved.path, dest)
460
479
  else rmSync(dest, { force: true })
461
480
  } catch (error) {
462
- rollbackError = `rollback failed at ${path.relative(dir, dest)}: ${(error && error.message) || error}; backup retained at ${backupRoot}`
463
- break
481
+ if (!rollbackError) {
482
+ rollbackError = `rollback failed at ${path.relative(dir, dest)}: ${(error && error.message) || error}; backup retained at ${backupRoot}`
483
+ }
464
484
  }
465
485
  }
466
486
  }
487
+ // Files the new tarball no longer ships must not outlive the swap: the
488
+ // marker names the version whose tree is on disk, so a leftover
489
+ // lib/legacy-helper.js makes the install claim a version whose tree is
490
+ // not what shipped (verified: a dropped file survived every update, and
491
+ // the repairInstall path drives this same code, so a repaired tree must
492
+ // drop the leftovers too). The walk stays bounded to the surface this
493
+ // updater manages — everything under lib/ plus cordis.patch.yml — so
494
+ // package-local state it must not own (update-mode, the marker, README…)
495
+ // is never touched. Each removal joins the SAME transaction: the file is
496
+ // backed up first, so a later failure resurrects it through the ordinary
497
+ // rollback and the tree returns fully old. Best-effort per file; removals
498
+ // that landed are reported in the `removed` list.
499
+ const removeStale = () => {
500
+ const wanted = new Set(manifest.map((entry) => entry.dest))
501
+ const stale = []
502
+ for (const rel of listFilesRecursive(installLib)) {
503
+ const dest = path.join(installLib, rel)
504
+ if (!wanted.has(dest)) stale.push(dest)
505
+ }
506
+ const patchYml = path.join(dir, 'cordis.patch.yml')
507
+ if (existsSync(patchYml) && !wanted.has(patchYml)) stale.push(patchYml)
508
+ const removed = []
509
+ for (const dest of stale) {
510
+ try {
511
+ backup(dest)
512
+ rmSync(dest, { force: true })
513
+ mutationStarted = true
514
+ removed.push(path.relative(dir, dest).split(path.sep).join('/'))
515
+ } catch { /* best-effort: one undeletable leftover must not fail the swap */ }
516
+ }
517
+ return removed
518
+ }
467
519
 
468
520
  try {
469
521
  for (const { src, dest } of manifest) install(src, dest)
522
+ // Completing the transaction also means clearing what the new tarball
523
+ // dropped; the removals share the backup table the rollback restores.
524
+ const removed = removeStale()
470
525
  // Do not trust the writes alone: verify every selected tarball file after
471
526
  // the install, including nested .cjs/.js files and package metadata.
472
527
  for (const { src, dest } of manifest) {
@@ -481,7 +536,7 @@ export async function applyUpdate(targetVersion, options = {}) {
481
536
  backup(marker)
482
537
  mutationStarted = true
483
538
  writeAtomic(marker, Buffer.from(String(targetVersion)))
484
- return { ok: true, to: targetVersion, changed }
539
+ return { ok: true, to: targetVersion, changed, removed }
485
540
  } catch (error) {
486
541
  rollback()
487
542
  if (rollbackError) {