dsh-timeback 0.0.0-stage → 0.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.
@@ -0,0 +1,577 @@
1
+ /**
2
+ * Persistent, content-addressed workspace snapshots over a private git object
3
+ * store.
4
+ *
5
+ * Every workspace gets one private bare repository under the plugin data
6
+ * directory. A snapshot records the complete work-tree as a git tree object and
7
+ * points a ref at it, so the repository's own `.git` (if any), index, refs and
8
+ * commits are never read or written. Restoring a snapshot rewrites exactly the
9
+ * paths that differ, removes the paths that did not exist yet, and leaves the
10
+ * work tree's file modes and symlinks as the snapshot recorded them.
11
+ */
12
+
13
+ import { createHash, randomUUID } from 'node:crypto'
14
+ import { promises as fs } from 'node:fs'
15
+ import path from 'node:path'
16
+
17
+ /** Ignore patterns written into each private repository beyond the work tree's own `.gitignore`. */
18
+ const DEFAULT_EXCLUDE = ['node_modules/', '.venv/', 'venv/', '__pycache__/', '.pytest_cache/', '.cache/']
19
+
20
+ /** Bytes one snapshot diff may return before the summary is marked truncated. */
21
+ const DIFF_MAX_BYTES = 32 * 1024 * 1024
22
+ /** Paths listed in one capture/restore result. */
23
+ const PATH_LIST_LIMIT = 100
24
+
25
+ /** A response that cannot be served as ordinary data. */
26
+ export class SnapshotError extends Error {
27
+ constructor(message, code = 'snapshot/failed', details = {}) {
28
+ super(message)
29
+ this.name = 'SnapshotError'
30
+ this.code = code
31
+ this.details = details
32
+ }
33
+ }
34
+
35
+ /** Whether an fs error names a missing path. */
36
+ function isMissing(error) {
37
+ return error?.code === 'ENOENT'
38
+ }
39
+
40
+ /** Whether one repo-relative path stays inside the work tree. */
41
+ function isSafeRelative(relative) {
42
+ if (typeof relative !== 'string' || relative === '') return false
43
+ if (relative.startsWith('/') || relative.startsWith('\\')) return false
44
+ if (/^[A-Za-z]:[\\/]/.test(relative)) return false
45
+ return !relative.split(/[\\/]/).some((segment) => segment === '..' || segment === '')
46
+ }
47
+
48
+ /** Hard cap a list of paths. */
49
+ function capPaths(paths) {
50
+ return paths.length <= PATH_LIST_LIMIT ? paths : paths.slice(0, PATH_LIST_LIMIT)
51
+ }
52
+
53
+ /** Produce a git ref component that cannot collide with ref syntax. */
54
+ function refComponent(value) {
55
+ return String(value || 'unknown').replace(/[^A-Za-z0-9._-]/g, '-').slice(0, 120)
56
+ }
57
+
58
+ /** Map one `diff-tree --name-status -z` status letter to a summary bucket. */
59
+ function bucketOf(status) {
60
+ if (status === 'A') return 'added'
61
+ if (status === 'D') return 'deleted'
62
+ return 'modified'
63
+ }
64
+
65
+ /**
66
+ * Snapshot and restore one or more workspaces.
67
+ */
68
+ export class SnapshotStore {
69
+ /**
70
+ * @param options - data directory, git runner, ignore patterns, logger.
71
+ */
72
+ constructor(options) {
73
+ this.dataDir = options.dataDir
74
+ this.runner = options.runner
75
+ this.exclude = Array.isArray(options.exclude) && options.exclude.length > 0 ? options.exclude : DEFAULT_EXCLUDE
76
+ this.protectedPaths = Array.isArray(options.protectedPaths) ? options.protectedPaths.filter(Boolean) : []
77
+ this.maxFiles = Number.isSafeInteger(options.maxFiles) && options.maxFiles > 0 ? options.maxFiles : 20_000
78
+ this.probeTimeoutMs = Number.isSafeInteger(options.probeTimeoutMs) && options.probeTimeoutMs > 0 ? options.probeTimeoutMs : 8_000
79
+ this.logger = options.logger
80
+ this.probes = new Map()
81
+ this.blocked = new Map()
82
+ this.repoDir = path.join(this.dataDir, 'repos')
83
+ this.repos = new Map()
84
+ this.tail = Promise.resolve()
85
+ }
86
+
87
+ /**
88
+ * Serialize every mutating snapshot operation. Snapshots are small enough
89
+ * that one queue keeps the private index and repositories race-free.
90
+ * @param operation - queued operation.
91
+ * @returns the operation's result.
92
+ */
93
+ exclusive(operation) {
94
+ const run = this.tail.then(operation, operation)
95
+ this.tail = run.then(
96
+ () => undefined,
97
+ () => undefined,
98
+ )
99
+ return run
100
+ }
101
+
102
+ /** @returns {Promise<boolean>} whether git is usable. */
103
+ async available() {
104
+ return this.runner.available || (await this.runner.ready()) !== null
105
+ }
106
+
107
+ /**
108
+ * Resolve (and lazily initialize) the private repository for one work tree.
109
+ * @param cwd - absolute work-tree directory.
110
+ * @param signal - cancellation.
111
+ * @returns {Promise<{id: string, cwd: string, gitDir: string}>}
112
+ */
113
+ async ensureRepo(cwd, signal) {
114
+ const canonical = await fs.realpath(path.resolve(cwd)).catch((error) => {
115
+ if (isMissing(error)) throw new SnapshotError(`工作目录不存在:${cwd}`, 'snapshot/cwd-missing')
116
+ throw error
117
+ })
118
+ const stat = await fs.stat(canonical)
119
+ if (!stat.isDirectory()) throw new SnapshotError(`工作目录不是目录:${canonical}`, 'snapshot/cwd-invalid')
120
+ const id = createHash('sha1').update(canonical).digest('hex').slice(0, 16)
121
+ const cached = this.repos.get(id)
122
+ if (cached) return cached
123
+ const gitDir = path.join(this.repoDir, id)
124
+ const created = await fs.mkdir(gitDir, { recursive: true }).then(() => exists(path.join(gitDir, 'HEAD')))
125
+ if (!created) {
126
+ const init = await this.runner.run(['init', '-q', '--bare', gitDir], { signal })
127
+ if (init.exitCode !== 0) throw new SnapshotError(`初始化快照仓库失败:${init.stderr.trim()}`, 'snapshot/init-failed')
128
+ for (const [key, value] of [
129
+ ['core.bare', 'false'],
130
+ ['core.autocrlf', 'false'],
131
+ ['core.safecrlf', 'false'],
132
+ ['core.logAllRefUpdates', 'false'],
133
+ ]) {
134
+ const configured = await this.runner.run(['--git-dir', gitDir, 'config', key, value], { signal })
135
+ if (configured.exitCode !== 0) throw new SnapshotError(`配置快照仓库失败:${configured.stderr.trim()}`, 'snapshot/init-failed')
136
+ }
137
+ }
138
+ const repo = { id, cwd: canonical, gitDir, exclude: this.excludesFor(canonical) }
139
+ await this.writeExcludes(repo)
140
+ this.repos.set(id, repo)
141
+ return repo
142
+ }
143
+
144
+ /** Ignore patterns for one work tree, including plugin/DSH data directories inside it. */
145
+ excludesFor(cwd) {
146
+ const patterns = [...this.exclude]
147
+ for (const protectedPath of this.protectedPaths) {
148
+ const relative = path.relative(cwd, path.resolve(protectedPath))
149
+ if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) continue
150
+ const posix = relative.split(path.sep).join('/')
151
+ if (posix !== '') patterns.push(`${posix}/`)
152
+ }
153
+ return patterns
154
+ }
155
+
156
+ /** Write the private ignore list so dependency directories never enter snapshots. */
157
+ async writeExcludes(repo) {
158
+ const file = path.join(repo.gitDir, 'info', 'exclude')
159
+ const body = [
160
+ '# timeback: private snapshot ignore list (never written into the work tree)',
161
+ ...repo.exclude,
162
+ '',
163
+ ].join('\n')
164
+ try {
165
+ await fs.mkdir(path.dirname(file), { recursive: true })
166
+ const current = await fs.readFile(file, 'utf8').catch(() => undefined)
167
+ if (current === body) return
168
+ await fs.writeFile(file, body, 'utf8')
169
+ } catch (error) {
170
+ if (this.logger) this.logger.warn?.(`timeback: cannot write snapshot exclude file: ${error?.message ?? error}`)
171
+ }
172
+ }
173
+
174
+ /** @returns {object|undefined} a cached "too large" verdict for one work tree. */
175
+ blockedWorkspace(cwd) {
176
+ let canonical
177
+ try {
178
+ canonical = path.resolve(cwd)
179
+ } catch {
180
+ return undefined
181
+ }
182
+ return this.blocked.get(canonical)
183
+ }
184
+
185
+ /**
186
+ * Cheaply bound one work tree before a real snapshot. `git add --dry-run`
187
+ * lists what would be staged without writing any object, so an accidentally
188
+ * huge workspace (a home directory, a dataset root) is refused before it can
189
+ * consume time and disk.
190
+ * @returns {Promise<{ok: boolean, files?: number, reason?: string}>}
191
+ */
192
+ async probeWorkspace(repo, signal) {
193
+ const cached = this.probes.get(repo.id)
194
+ if (cached) return cached
195
+ const env = { GIT_INDEX_FILE: path.join(repo.gitDir, 'probe.index') }
196
+ let verdict
197
+ try {
198
+ const dryRun = await this.git(repo, ['--work-tree', repo.cwd, 'add', '-A', '--ignore-errors', '--dry-run'], {
199
+ env,
200
+ signal,
201
+ timeoutMs: this.probeTimeoutMs,
202
+ maxBytes: 2 * 1024 * 1024,
203
+ })
204
+ const lines = dryRun.stdout === '' ? 0 : dryRun.stdout.split('\n').filter((line) => line !== '').length
205
+ if (dryRun.truncated || lines > this.maxFiles) {
206
+ verdict = { ok: false, files: dryRun.truncated ? -1 : lines, reason: 'workspace-too-large' }
207
+ } else if (dryRun.exitCode !== 0 && dryRun.exitCode !== 1) {
208
+ verdict = { ok: false, reason: `dry-run-failed: ${dryRun.stderr.trim().slice(0, 200)}` }
209
+ } else {
210
+ verdict = { ok: true }
211
+ }
212
+ } catch (error) {
213
+ verdict = { ok: false, reason: `dry-run-failed: ${error?.message ?? error}` }
214
+ } finally {
215
+ await fs.rm(path.join(repo.gitDir, 'probe.index'), { force: true }).catch(() => {})
216
+ }
217
+ this.probes.set(repo.id, verdict)
218
+ if (!verdict.ok) {
219
+ this.blocked.set(repo.cwd, verdict)
220
+ this.logger?.warn?.(
221
+ `timeback: refusing to snapshot ${repo.cwd}: ${verdict.reason}` +
222
+ (verdict.files > 0 ? ` (${verdict.files} files > maxFiles ${this.maxFiles})` : '') +
223
+ '; raise maxFiles or add exclude patterns to enable snapshots for this workspace',
224
+ )
225
+ }
226
+ return verdict
227
+ }
228
+
229
+ /** Run git against one private snapshot repository. */
230
+ git(repo, args, options = {}) {
231
+ return this.runner.run(['--git-dir', repo.gitDir, ...args], options)
232
+ }
233
+
234
+ /** Remove an index lock left behind by a killed git process. */
235
+ async clearStaleLock(gitDir) {
236
+ const lock = path.join(gitDir, 'index.lock')
237
+ try {
238
+ const stat = await fs.stat(lock)
239
+ if (Date.now() - stat.mtimeMs > 5 * 60_000) await fs.rm(lock, { force: true })
240
+ } catch {
241
+ // No lock present.
242
+ }
243
+ }
244
+
245
+ /**
246
+ * Stage the work tree into the private index and return its tree id.
247
+ * @param repo - private repository.
248
+ * @param signal - cancellation.
249
+ * @returns {Promise<string>} tree object id.
250
+ */
251
+ async treeOfHead(repo, signal) {
252
+ await this.clearStaleLock(repo.gitDir)
253
+ const env = { GIT_INDEX_FILE: path.join(repo.gitDir, 'index') }
254
+ const add = await this.git(repo, ['--work-tree', repo.cwd, 'add', '-A', '--ignore-errors'], { env, signal })
255
+ // Exit code 1 means individual unreadable entries were skipped; the tree
256
+ // built from everything else is still usable.
257
+ if (add.exitCode !== 0 && add.exitCode !== 1) {
258
+ throw new SnapshotError(`快照失败(git add):${add.stderr.trim()}`, 'snapshot/add-failed')
259
+ }
260
+ const write = await this.git(repo, ['write-tree'], { env, signal })
261
+ if (write.exitCode !== 0) throw new SnapshotError(`快照失败(write-tree):${write.stderr.trim()}`, 'snapshot/tree-failed')
262
+ const tree = write.stdout.trim()
263
+ if (!/^[0-9a-f]{40,64}$/.test(tree)) throw new SnapshotError('快照失败:git 返回了无效的 tree id', 'snapshot/tree-invalid')
264
+ return tree
265
+ }
266
+
267
+ /**
268
+ * Capture the work tree as a snapshot tree and preserve it with a ref.
269
+ * @param options - workspace, session, checkpoint identity, previous tree.
270
+ * @returns {Promise<{tree: string, repoId: string, cwd: string, files: object|null}>}
271
+ */
272
+ async capture(options) {
273
+ return this.exclusive(async () => {
274
+ await this.available()
275
+ const repo = await this.ensureRepo(options.cwd, options.signal)
276
+ const blocked = this.blocked.get(repo.cwd)
277
+ if (blocked) {
278
+ throw new SnapshotError(
279
+ `工作区过大,未创建文件快照(${blocked.reason})。可在插件配置里提高 maxFiles 或添加 exclude 规则。`,
280
+ 'snapshot/workspace-too-large',
281
+ { files: blocked.files ?? null, maxFiles: this.maxFiles },
282
+ )
283
+ }
284
+ const probe = await this.probeWorkspace(repo, options.signal)
285
+ if (!probe.ok) {
286
+ throw new SnapshotError(
287
+ `工作区过大,未创建文件快照(${probe.reason})。可在插件配置里提高 maxFiles 或添加 exclude 规则。`,
288
+ 'snapshot/workspace-too-large',
289
+ { files: probe.files ?? null, maxFiles: this.maxFiles },
290
+ )
291
+ }
292
+ const tree = await this.treeOfHead(repo, options.signal)
293
+ const ref = `refs/timeback/${refComponent(options.sessionId)}/${refComponent(options.checkpointId)}`
294
+ const updated = await this.git(repo, ['update-ref', ref, tree], { signal: options.signal })
295
+ if (updated.exitCode !== 0) {
296
+ throw new SnapshotError(`保存快照引用失败:${updated.stderr.trim()}`, 'snapshot/ref-failed')
297
+ }
298
+ let files = null
299
+ if (options.previousTree && /^[0-9a-f]{40,64}$/.test(options.previousTree) && options.previousTree !== tree) {
300
+ files = await this._diffSummary(repo, options.previousTree, tree, options.signal)
301
+ }
302
+ return { tree, repoId: repo.id, cwd: repo.cwd, files }
303
+ })
304
+ }
305
+
306
+ /**
307
+ * Summarize the paths that differ between two snapshot trees.
308
+ * @returns {Promise<{total: number, added: string[], modified: string[], deleted: string[], files: object[], truncated: boolean}>}
309
+ */
310
+ async diffTrees(options) {
311
+ return this.exclusive(async () => {
312
+ await this.available()
313
+ const repo = await this.ensureRepo(options.cwd, options.signal)
314
+ return this._diffSummary(repo, options.fromTree, options.toTree, options.signal)
315
+ })
316
+ }
317
+
318
+ async _diffSummary(repo, fromTree, toTree, signal) {
319
+ const entries = await this._diffEntries(repo, fromTree, toTree, signal, DIFF_MAX_BYTES, true)
320
+ const added = []
321
+ const modified = []
322
+ const deleted = []
323
+ const byBucket = { added, modified, deleted }
324
+ for (const entry of entries.entries) {
325
+ const bucket = bucketOf(entry.status)
326
+ if (byBucket[bucket].length < PATH_LIST_LIMIT) byBucket[bucket].push(entry.path)
327
+ }
328
+ return {
329
+ total: entries.entries.length,
330
+ added,
331
+ modified,
332
+ deleted,
333
+ files: entries.entries.slice(0, PATH_LIST_LIMIT).map((entry) => ({ path: entry.path, status: bucketOf(entry.status) })),
334
+ truncated: entries.truncated || entries.entries.length > PATH_LIST_LIMIT,
335
+ }
336
+ }
337
+
338
+ /**
339
+ * Read `diff-tree --raw -z` records: `:<oldmode> <newmode> <oldsha> <newsha>
340
+ * <status>\0<path>\0`. Modes identify symlinks and gitlinks (nested
341
+ * repositories), which restore must never treat as ordinary files.
342
+ * @returns {Promise<{entries: {status: string, path: string, oldMode: string, newMode: string}[], truncated: boolean}>}
343
+ */
344
+ async _diffEntries(repo, fromTree, toTree, signal, maxBytes, allowTruncated) {
345
+ const diff = await this.git(
346
+ repo,
347
+ ['diff-tree', '-r', '--raw', '--no-renames', '-z', fromTree, toTree],
348
+ { signal, maxBytes: maxBytes ?? DIFF_MAX_BYTES },
349
+ )
350
+ if (diff.exitCode !== 0) throw new SnapshotError(`比较快照失败:${diff.stderr.trim()}`, 'snapshot/diff-failed')
351
+ const parts = diff.stdout.split('\0')
352
+ const entries = []
353
+ for (let index = 0; index + 1 < parts.length; index += 2) {
354
+ const metadata = parts[index]
355
+ const file = parts[index + 1]
356
+ if (metadata === '' || file === '' || metadata[0] !== ':') continue
357
+ const fields = metadata.slice(1).split(' ')
358
+ if (fields.length < 5) continue
359
+ const status = fields[4][0]
360
+ if (!isSafeRelative(file)) continue
361
+ entries.push({ status, path: file, oldMode: fields[0], newMode: fields[1] })
362
+ }
363
+ if (diff.truncated && !allowTruncated) {
364
+ throw new SnapshotError('快照差异过大,无法安全恢复', 'snapshot/diff-too-large')
365
+ }
366
+ return { entries, truncated: diff.truncated }
367
+ }
368
+
369
+ /**
370
+ * Restore the work tree to one snapshot tree.
371
+ *
372
+ * Deletions run before checkouts so a file that became a directory (or the
373
+ * reverse) cannot block the restore; paths whose entry is a nested repository
374
+ * (gitlink) in either tree are never written or recursively deleted, because
375
+ * their contents are not part of the snapshot.
376
+ * @returns {Promise<{noop: boolean, restored: number, deleted: number, skipped: number, gitlinks: number, failed: string[], restoredPaths: string[], deletedPaths: string[]}>}
377
+ */
378
+ async restore(options) {
379
+ return this.exclusive(async () => {
380
+ await this.available()
381
+ const repo = await this.ensureRepo(options.cwd, options.signal)
382
+ const type = await this.git(repo, ['cat-file', '-t', options.targetTree], { signal: options.signal })
383
+ if (type.exitCode !== 0 || type.stdout.trim() !== 'tree') {
384
+ throw new SnapshotError('目标文件快照不存在或已损坏', 'snapshot/target-missing')
385
+ }
386
+ const currentTree = options.currentTree ?? (await this.treeOfHead(repo, options.signal))
387
+ if (currentTree === options.targetTree) {
388
+ return { noop: true, restored: 0, deleted: 0, skipped: 0, gitlinks: 0, failed: [], restoredPaths: [], deletedPaths: [] }
389
+ }
390
+ const entries = await this._diffEntries(repo, currentTree, options.targetTree, options.signal, DIFF_MAX_BYTES, false)
391
+ const restorePaths = []
392
+ const deletePaths = []
393
+ let gitlinks = 0
394
+ for (const entry of entries.entries) {
395
+ const gitlink = entry.oldMode === '160000' || entry.newMode === '160000'
396
+ if (gitlink) {
397
+ gitlinks += 1
398
+ continue
399
+ }
400
+ if (entry.status === 'D') deletePaths.push(entry.path)
401
+ else restorePaths.push(entry.path)
402
+ }
403
+ const failed = []
404
+ let deleted = 0
405
+ let skipped = 0
406
+ if (options.deleteExtra === false) {
407
+ skipped = deletePaths.length
408
+ } else if (deletePaths.length > 0) {
409
+ for (const relative of deletePaths) {
410
+ try {
411
+ await fs.rm(path.join(repo.cwd, relative), { force: true, recursive: true })
412
+ deleted += 1
413
+ } catch (error) {
414
+ failed.push(`${relative}: ${error?.message ?? error}`)
415
+ }
416
+ }
417
+ }
418
+ if (deletePaths.length > 0) await this.pruneEmptyDirs(repo.cwd, deletePaths)
419
+ if (restorePaths.length > 0) await this._checkoutPaths(repo, options.targetTree, restorePaths, failed, options.signal)
420
+ return {
421
+ noop: false,
422
+ restored: restorePaths.length,
423
+ deleted,
424
+ skipped,
425
+ gitlinks,
426
+ failed,
427
+ restoredPaths: capPaths(restorePaths),
428
+ deletedPaths: capPaths(deletePaths),
429
+ }
430
+ })
431
+ }
432
+
433
+ /**
434
+ * Forget the refs of dropped checkpoints so their objects become reachable
435
+ * only when some other ref still points at them, then let git collect.
436
+ * @param sessionId - owning session.
437
+ * @param checkpointIds - dropped checkpoint ids.
438
+ */
439
+ async dropCheckpointRefs(sessionId, checkpointIds) {
440
+ if (!Array.isArray(checkpointIds) || checkpointIds.length === 0) return
441
+ await this.exclusive(async () => {
442
+ for (const [repoId, repo] of this.repos) {
443
+ for (const checkpointId of checkpointIds) {
444
+ const ref = `refs/timeback/${refComponent(sessionId)}/${refComponent(checkpointId)}`
445
+ await this.git(repo, ['update-ref', '-d', ref], {}).catch(() => {})
446
+ }
447
+ // A quick opportunistic collection; failures are harmless.
448
+ await this.git(repo, ['gc', '--auto', '--quiet'], {}).catch(() => {})
449
+ this.probes.delete(repoId)
450
+ }
451
+ })
452
+ }
453
+
454
+ /**
455
+ * Refuse restore paths occupied by a non-empty directory that git never
456
+ * snapshotted, so `checkout-index -f` can never silently drop ignored or
457
+ * untracked content. Empty directories are already safe to replace.
458
+ * @returns {Promise<string[]>} paths that are still safe to check out.
459
+ */
460
+ async preflightPaths(repo, paths, failed) {
461
+ const safe = []
462
+ for (const relative of paths) {
463
+ const target = path.join(repo.cwd, relative)
464
+ try {
465
+ const stat = await fs.lstat(target)
466
+ if (!stat.isDirectory()) {
467
+ safe.push(relative)
468
+ continue
469
+ }
470
+ try {
471
+ await fs.rmdir(target)
472
+ safe.push(relative)
473
+ } catch (error) {
474
+ if (isMissing(error)) {
475
+ safe.push(relative)
476
+ continue
477
+ }
478
+ failed.push(`${relative}: ${error?.code === 'ENOTEMPTY' ? '非空目录挡住了恢复,且其中内容未被快照(已跳过,防止删除未跟踪文件)' : error?.message ?? error}`)
479
+ }
480
+ } catch (error) {
481
+ if (isMissing(error)) safe.push(relative)
482
+ else failed.push(`${relative}: ${error?.message ?? error}`)
483
+ }
484
+ }
485
+ return safe
486
+ }
487
+
488
+ /** Write selected snapshot paths into the work tree from one target tree index. */
489
+ async _checkoutPaths(repo, targetTree, paths, failed, signal) {
490
+ const indexFile = path.join(repo.gitDir, `restore-${randomUUID()}.index`)
491
+ const env = { GIT_INDEX_FILE: indexFile }
492
+ try {
493
+ const read = await this.git(repo, ['read-tree', targetTree], { env, signal })
494
+ if (read.exitCode !== 0) throw new SnapshotError(`准备恢复索引失败:${read.stderr.trim()}`, 'snapshot/restore-index-failed')
495
+ const safe = await this.preflightPaths(repo, paths, failed)
496
+ if (safe.length === 0) return
497
+ const checkout = await this.runner.run(
498
+ ['--git-dir', repo.gitDir, 'checkout-index', '-f', '-z', '--stdin'],
499
+ { cwd: repo.cwd, env, stdin: `${safe.join('\0')}\0`, signal },
500
+ )
501
+ if (checkout.exitCode === 0) return
502
+ // One bad path (permission, a directory in the way) must not abandon the rest.
503
+ for (const relative of safe) {
504
+ const single = await this.runner.run(
505
+ ['--git-dir', repo.gitDir, 'checkout-index', '-f', '-z', '--stdin'],
506
+ { cwd: repo.cwd, env, stdin: `${relative}\0`, signal },
507
+ )
508
+ if (single.exitCode === 0) continue
509
+ const recovered = await this.clearConflict(repo.cwd, relative)
510
+ if (recovered.ok) {
511
+ const retry = await this.runner.run(
512
+ ['--git-dir', repo.gitDir, 'checkout-index', '-f', '-z', '--stdin'],
513
+ { cwd: repo.cwd, env, stdin: `${relative}\0`, signal },
514
+ )
515
+ if (retry.exitCode === 0) continue
516
+ }
517
+ failed.push(`${relative}: ${recovered.reason ?? (single.stderr.trim().split('\n').pop() || 'checkout failed')}`)
518
+ }
519
+ } finally {
520
+ await fs.rm(indexFile, { force: true }).catch(() => {})
521
+ }
522
+ }
523
+
524
+ /**
525
+ * Remove an empty directory that blocks restoring a file at the same path.
526
+ * A non-empty directory may hold ignored/untracked content that git never
527
+ * snapshotted, so it is refused rather than deleted.
528
+ * @returns {Promise<{ok: boolean, reason?: string}>}
529
+ */
530
+ async clearConflict(cwd, relative) {
531
+ try {
532
+ const target = path.join(cwd, relative)
533
+ const stat = await fs.lstat(target)
534
+ if (!stat.isDirectory()) return { ok: false, reason: 'a file occupies this path' }
535
+ await fs.rmdir(target)
536
+ return { ok: true }
537
+ } catch (error) {
538
+ if (error?.code === 'ENOTEMPTY' || error?.code === 'EEXIST') {
539
+ return { ok: false, reason: 'a non-empty directory occupies this path (untracked content is never deleted)' }
540
+ }
541
+ if (isMissing(error)) return { ok: true }
542
+ return { ok: false, reason: error?.message ?? String(error) }
543
+ }
544
+ }
545
+
546
+ /** Remove directories left empty by deleted files, never above the work tree. */
547
+ async pruneEmptyDirs(cwd, relativePaths) {
548
+ const directories = new Set()
549
+ for (const relative of relativePaths) {
550
+ let directory = path.dirname(relative)
551
+ while (directory && directory !== '.' && directory !== '/') {
552
+ directories.add(directory)
553
+ directory = path.dirname(directory)
554
+ }
555
+ }
556
+ const ordered = [...directories].sort((left, right) => right.split('/').length - left.split('/').length)
557
+ for (const relative of ordered) {
558
+ try {
559
+ await fs.rmdir(path.join(cwd, relative))
560
+ } catch {
561
+ // Not empty, missing, or not a directory: nothing to clean.
562
+ }
563
+ }
564
+ }
565
+ }
566
+
567
+ /** Whether a path exists. */
568
+ async function exists(target) {
569
+ try {
570
+ await fs.access(target)
571
+ return true
572
+ } catch {
573
+ return false
574
+ }
575
+ }
576
+
577
+ export default SnapshotStore