rvlib-shipkit 2.22.0 → 2.23.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/package.json +1 -1
  3. package/src/annex/annex.ts +3 -0
  4. package/src/annex/born.ts +464 -0
  5. package/src/annex/flush.ts +46 -0
  6. package/src/annex/offload.ts +171 -38
  7. package/src/annex/snapshots.ts +53 -0
  8. package/src/annex/tidy.ts +368 -0
  9. package/src/checks/SK041-annex-links.check.ts +4 -2
  10. package/src/checks/SK043-scratch-on-the-mac.check.ts +45 -0
  11. package/src/cli/cmd_Annex.ts +60 -9
  12. package/src/cli/cmd_Home.ts +28 -0
  13. package/src/cli/cmd_Rec.ts +17 -7
  14. package/src/cli/cmd_Review.ts +27 -3
  15. package/src/core/machine-db.ts +8 -0
  16. package/src/home/claude-temp.ts +139 -0
  17. package/src/home/daemon-jobs.ts +10 -3
  18. package/src/home/global-units.ts +3 -0
  19. package/src/home/machine-stores.ts +27 -3
  20. package/src/home/pm.ts +4 -1
  21. package/src/home/run-pm.ts +1 -0
  22. package/src/identities/identities.ts +92 -24
  23. package/src/media-store/daemon.ts +2 -2
  24. package/src/media-store/purge.ts +4 -0
  25. package/src/recordings/load.ts +3 -3
  26. package/src/recordings/model.ts +7 -0
  27. package/src/recordings/open.ts +12 -0
  28. package/src/recordings/presets.ts +12 -5
  29. package/src/recordings/recorder-app/Capture.swift +34 -5
  30. package/src/recordings/recorder-app/Clip.swift +218 -54
  31. package/src/recordings/recorder-app/Editor.swift +177 -7
  32. package/src/recordings/recorder-app/Hud.swift +189 -0
  33. package/src/recordings/recorder-app/Tray.swift +179 -36
  34. package/src/recordings/recorder-app/icon.svg +16 -0
  35. package/src/recordings/recorder-app/main.swift +363 -29
  36. package/src/recordings/recorder-app.ts +8 -4
  37. package/src/recordings/recorder.shipkit.ts +2 -1
  38. package/src/recordings/routes.ts +52 -6
  39. package/src/recordings/run-recorder.ts +2 -1
  40. package/src/recordings/share.ts +27 -0
  41. package/src/recordings/take.ts +36 -4
  42. package/src/recordings/view.ts +11 -0
  43. package/src/repo-config.ts +9 -1
  44. package/src/review/model.ts +33 -4
  45. package/src/serve/hub-app/hub.css +4 -0
  46. package/src/serve/hub-app/recordings-st.ts +135 -24
  47. package/src/serve/hub-app/recordings-view.tsx +293 -54
  48. package/src/serve/hub-app/recordings.css +77 -24
  49. package/src/shipkit-files.ts +5 -0
  50. package/src/social/drafts.ts +4 -3
  51. package/src/social/load.ts +7 -2
  52. package/src/social/publish/discord.ts +10 -3
@@ -2,12 +2,13 @@
2
2
  // tools/shipkit/annex.md, Scratch). Each refusal guards what an unplugged drive must never take: a db, a lock, a git
3
3
  // worktree, what the backup holds, what the media store indexes, a file a process holds open. A move is a copy checked
4
4
  // by its count and bytes, then the swap
5
- import { closeSync, existsSync, lstatSync, mkdirSync, openSync, readdirSync, readlinkSync, readSync, renameSync, rmSync, symlinkSync } from 'node:fs'
5
+ import { closeSync, existsSync, lstatSync, mkdirSync, openSync, readdirSync, readlinkSync, readSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
6
6
  import { homedir } from 'node:os'
7
7
  import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'
8
- import { machineGet, machineSet } from '../core/machine-db.ts'
8
+ import { machineGet, machineRead, machineSet } from '../core/machine-db.ts'
9
9
  import { openOf } from '../media-store/purge.ts'
10
10
  import { driveFree, keepFree, presentAnnexes } from './annex.ts'
11
+ import { flushDrive, syncFile } from './flush.ts'
11
12
 
12
13
  const GB = 1e9
13
14
  /** room the Mac keeps beyond a folder brought back */
@@ -23,9 +24,75 @@ export type Offload = {
23
24
  files: number
24
25
  bytes: number
25
26
  at: number
27
+ /** declared in a config (`annex.born`): it lives on the annex from its first byte (born.ts) */
28
+ born?: boolean
29
+ /** since when a local folder stands in for the link while no annex is present: merged back when one returns */
30
+ spill?: number
31
+ /** a Mac folder a swap first move put aside, its copy to the annex not finished: the next pass goes on. Recorded
32
+ * before the rename, so a kill at any step leaves a state the next pass completes */
33
+ aside?: string
34
+ /** the losers a merge kept beside their winner (`<name>.mac-<time>`, `<name>.annex-<time>`): named by drift until
35
+ * someone deletes them, never dropped */
36
+ kept?: string[]
37
+ /** its link has held at least once: only then is a real folder in its place a tool's wipe, never a move that did
38
+ * not finish */
39
+ held?: boolean
26
40
  }
27
41
 
42
+ /** the file that marks a staging folder (`<target>.<pid>.part/`) as shipkit's own: the sweep removes only those */
43
+ export const PART_MARK = '.shipkit-part'
44
+ /** a staging folder beside `to`, marked, for this process */
45
+ export function stageOf(to: string): string {
46
+ const stage = `${to}.${process.pid}.part`
47
+ mkdirSync(stage, { recursive: true })
48
+ writeFileSync(join(stage, PART_MARK), '')
49
+ return stage
50
+ }
51
+
52
+ /** the records, for a reader: a db that does not open reads as none */
28
53
  export const offloads = (): Offload[] => machineGet<Offload[]>(RECORDS) ?? []
54
+ export const saveOffloads = (list: Offload[]): void => save(list)
55
+ /** the records changed by `fn`, read strictly: a busy db throws, never reads as none (which would save the one record
56
+ * being changed over all the others) */
57
+ export function editOffloads(fn: (list: Offload[]) => Offload[]): void {
58
+ save(fn(machineRead<Offload[]>(RECORDS) ?? []))
59
+ }
60
+
61
+ /** the moment a merge or a trash names its leftovers by, `20261111-190500` (UTC) */
62
+ export const stampOf = (now: number): string => new Date(now).toISOString().slice(0, 19).replace(/[-:]/g, '').replace('T', '-')
63
+
64
+ /** a record's annex content moved whole to `<annex>/offload/.trash/<time>-<repo>/<rel>` (one rename on the drive): the
65
+ * annex's scratch cap trims it like any scratch. Its new path, null when there was nothing */
66
+ export function toTrash(rec: Pick<Offload, 'repo' | 'rel' | 'target'>, now: number): string | null {
67
+ if (!existsSync(rec.target)) return null
68
+ const tail = `/${basename(rec.repo)}/${rec.rel}`
69
+ const off = rec.target.endsWith(tail) ? rec.target.slice(0, -tail.length) : dirname(rec.target)
70
+ const to = join(off, '.trash', `${stampOf(now)}-${basename(rec.repo)}`, rec.rel)
71
+ mkdirSync(dirname(to), { recursive: true })
72
+ let used = to
73
+ for (let i = 2; existsSync(used); i++) used = `${to}-${i}`
74
+ renameSync(rec.target, used)
75
+ return used
76
+ }
77
+
78
+ /** what a move set aside beside a folder (`<name>.<pid>.moving`, `<name>.<pid>.offloading`): a Mac copy whose move did
79
+ * not finish, maybe the only copy */
80
+ const ASIDE = /^(.+)\.\d+\.(moving|offloading)$/
81
+ export function asidesOf(root: string, rel: string): string[] {
82
+ const at = join(root, rel)
83
+ let names: string[]
84
+ try {
85
+ names = readdirSync(dirname(at))
86
+ } catch {
87
+ return []
88
+ }
89
+ return names.filter((n) => ASIDE.exec(n)?.[1] === basename(at)).map((n) => join(dirname(at), n))
90
+ }
91
+
92
+ /** the record of another repo whose annex folder `target` would share, or sit in, or hold: two repos of one folder
93
+ * name meet at `offload/<name>/` */
94
+ export const ownerOf = (root: string, target: string): Offload | undefined =>
95
+ offloads().find((x) => resolve(x.repo) !== resolve(root) && (x.target === target || x.target.startsWith(`${target}/`) || target.startsWith(`${x.target}/`)))
29
96
  const save = (list: Offload[]): void => {
30
97
  if (!machineSet(RECORDS, list)) throw new Error('the machine db does not open: the offload is not recorded')
31
98
  }
@@ -60,14 +127,14 @@ export function isDb(dir: string, rel: string, file: boolean): boolean {
60
127
 
61
128
  /** every entry under `dir`, relative to it, by lstat: a link is an entry, never followed (a venv or a tree with a
62
129
  * link loop holds them) */
63
- export function entries(dir: string): { rel: string; dir: boolean; file: boolean; size: number }[] {
64
- const out: { rel: string; dir: boolean; file: boolean; size: number }[] = []
130
+ export function entries(dir: string): { rel: string; dir: boolean; file: boolean; link: boolean; size: number }[] {
131
+ const out: { rel: string; dir: boolean; file: boolean; link: boolean; size: number }[] = []
65
132
  const go = (abs: string, rel: string): void => {
66
133
  for (const name of readdirSync(abs)) {
67
134
  const p = join(abs, name)
68
135
  const r = rel ? `${rel}/${name}` : name
69
136
  const s = lstatSync(p)
70
- out.push({ rel: r, dir: s.isDirectory(), file: s.isFile(), size: s.isFile() ? s.size : 0 })
137
+ out.push({ rel: r, dir: s.isDirectory(), file: s.isFile(), link: s.isSymbolicLink(), size: s.isFile() ? s.size : 0 })
71
138
  if (s.isDirectory()) go(p, r)
72
139
  }
73
140
  }
@@ -83,7 +150,7 @@ export function tally(path: string): { files: number; bytes: number } {
83
150
  return { files: all.length, bytes: all.reduce((n, e) => n + e.size, 0) }
84
151
  }
85
152
 
86
- const git = (root: string, args: string[]): { ok: boolean; out: string } => {
153
+ export const git = (root: string, args: string[]): { ok: boolean; out: string } => {
87
154
  const r = Bun.spawnSync(['git', '-C', root, ...args], { stdout: 'pipe', stderr: 'pipe' })
88
155
  return { ok: r.exitCode === 0, out: r.stdout.toString().trim() }
89
156
  }
@@ -97,33 +164,57 @@ export const inScratch = (rel: string): boolean => SCRATCH.some((d) => rel === d
97
164
  export type Probe = {
98
165
  /** the home folder the backup inventory reads (the real one by default) */
99
166
  home?: string
167
+ /** the drive that holds a folder flushed before a Mac copy goes (`flushDrive` by default) */
168
+ flush?: (dir: string) => void
100
169
  /** the paths some process holds open (`lsof`, about 180 ms a call, by default) */
101
170
  openOf?: (paths: readonly string[]) => Set<string>
171
+ /** git in the repo (`git -C <root> …`, about 20 ms a call, by default) */
172
+ git?: (root: string, args: string[]) => { ok: boolean; out: string }
173
+ /** the first path at or under `path` the backup's own inventory holds (`collect`, about 45 ms, by default) */
174
+ backupHolds?: (root: string, path: string, home: string) => Promise<string | null>
102
175
  }
103
176
 
104
- export async function refusal(root: string, rel: string, o: Probe = {}): Promise<string | null> {
177
+ /** the backup's own inventory of `root`: the first path it holds at or under `path` */
178
+ async function backupHolds(root: string, path: string, home: string): Promise<string | null> {
179
+ const { collect } = await import('../media-store/backup/sources.ts')
180
+ return (await collect({ home, repos: [root] })).find((x) => x.abs === path || x.abs.startsWith(`${path}/`))?.abs ?? null
181
+ }
182
+
183
+ /** a copy first move (born.ts) checks the open files on the aside after its copy: this switches that check off */
184
+ export type Checks = Probe & { open?: boolean }
185
+
186
+ export async function refusal(root: string, rel: string, o: Checks = {}): Promise<string | null> {
105
187
  const path = join(root, rel)
106
188
  if (isAbsolute(rel) || rel.startsWith('..') || rel === '' || rel === '.') return `${rel} is not inside the repo`
107
189
  const s = lstatSync(path, { throwIfNoEntry: false })
108
190
  if (!s) return `${rel} does not exist`
109
191
  if (s.isSymbolicLink()) return `${rel} is a symlink already${offloads().some((o) => o.repo === root && o.rel === rel) ? ' (offloaded)' : ''}`
110
192
  if (!inScratch(rel)) return `${rel} is outside ${SCRATCH.join(' and ')}: only scratch leaves the Mac`
111
- if (git(root, ['ls-files', '--', rel]).out !== '') return `git tracks files under ${rel}`
112
- if (!git(root, ['check-ignore', '-q', '--', rel]).ok) return `git does not ignore ${rel}: work in progress stays on the Mac`
113
- const list = s.isDirectory() ? entries(path) : [{ rel: basename(rel), dir: false, file: s.isFile(), size: s.size }]
193
+ const run = o.git ?? git
194
+ if (run(root, ['ls-files', '--', rel]).out !== '') return `git tracks files under ${rel}`
195
+ if (!run(root, ['check-ignore', '-q', '--', rel]).ok) return `git does not ignore ${rel}: work in progress stays on the Mac`
196
+ const list = s.isDirectory() ? entries(path) : [{ rel: basename(rel), dir: false, file: s.isFile(), link: false, size: s.size }]
114
197
  const base = s.isDirectory() ? path : dirname(path)
115
198
  const names = list.map((e) => e.rel)
116
199
  const gits = names.filter((n) => n.split('/').includes('.git'))
117
200
  if (gits.length > 0) return `${rel} holds a git repo or worktree (${gits[0]}): its uncommitted work stays on the Mac`
118
201
  const dbs = list.filter((e) => isDb(base, e.rel, e.file)).map((e) => e.rel)
119
202
  if (dbs.length > 0) return `${rel} holds a db or a lock (${dbs.slice(0, 3).join(', ')}${dbs.length > 3 ? ', …' : ''}): it stays on the Mac`
120
- const { collect } = await import('../media-store/backup/sources.ts')
121
- const kept = (await collect({ home: o.home ?? homedir(), repos: [root] })).find((x) => x.abs === path || x.abs.startsWith(`${path}/`))
122
- if (kept) return `the backup holds ${relative(root, kept.abs)}: what a backup keeps stays on the Mac`
203
+ const out = list.find((e) => {
204
+ if (!e.link) return false
205
+ const to = readlinkSync(join(base, e.rel))
206
+ if (isAbsolute(to)) return false
207
+ const lands = resolve(dirname(join(base, e.rel)), to)
208
+ return lands !== path && !lands.startsWith(`${path}/`)
209
+ })
210
+ if (out) return `${rel} holds a relative link that points out of it (${out.rel} -> ${readlinkSync(join(base, out.rel))}): moved, it would point elsewhere`
211
+ const kept = await (o.backupHolds ?? backupHolds)(root, path, o.home ?? homedir())
212
+ if (kept) return `the backup holds ${relative(root, kept)}: what a backup keeps stays on the Mac`
123
213
  const { mediaDb } = await import('../media-store/db.ts')
124
214
  const rows = (mediaDb()?.query('select store, item, name from files where local = 1').all() ?? []) as { store: string; item: string; name: string }[]
125
215
  const indexed = rows.map((r) => join(r.store, r.item, r.name)).find((p) => p === path || p.startsWith(`${path}/`))
126
216
  if (indexed) return `the media store indexes ${relative(root, indexed)}: its purge moves media to the annex, never an offload`
217
+ if (o.open === false) return null
127
218
  const probe = o.openOf ?? openOf
128
219
  const open = s.isDirectory() ? [...probe(names.map((n) => join(path, n)))] : [...probe([path])]
129
220
  if (open.length > 0) return `a process holds ${open[0]} open${open.length > 1 ? ` (and ${open.length - 1} more)` : ''}`
@@ -151,49 +242,56 @@ export async function offload(root: string, rel: string, o: Probe & { dry?: bool
151
242
  if (!annex) throw new Error(`no annex present keeps its free space with ${rel} (${(t.bytes / GB).toFixed(1)} GB)`)
152
243
  const target = join(annex.path, 'offload', basename(root), rel)
153
244
  if (existsSync(target)) throw new Error(`${target} exists already: an earlier offload, look before you move`)
245
+ const owner = ownerOf(root, target)
246
+ if (owner) throw new Error(`another repo (${owner.repo}) holds ${owner.target} on the annex: two repos of one folder name, ${basename(root)}`)
154
247
  if (o.dry) return { rel, target, ...t }
155
- const part = `${target}.${process.pid}.part`
156
248
  mkdirSync(dirname(target), { recursive: true })
249
+ const stage = stageOf(target)
250
+ const part = join(stage, 'copy')
157
251
  try {
158
252
  const cp = Bun.spawnSync(['cp', '-Rp', src, part], { stdout: 'pipe', stderr: 'pipe' })
159
253
  if (cp.exitCode !== 0) throw new Error(`cp: ${cp.stderr.toString().trim()}`)
160
254
  const got = tally(part)
161
255
  if (got.files !== t.files || got.bytes !== t.bytes) throw new Error(`the copy holds ${got.files} files and ${got.bytes} bytes, the source ${t.files} and ${t.bytes}`)
256
+ for (const e of entries(part)) if (e.file) syncFile(join(part, e.rel))
162
257
  renameSync(part, target)
258
+ rmSync(stage, { recursive: true, force: true })
163
259
  } catch (e) {
164
- rmSync(part, { recursive: true, force: true })
260
+ rmSync(stage, { recursive: true, force: true })
165
261
  throw new Error(`${rel} not offloaded: ${(e as Error).message}`)
166
262
  }
167
- const others = offloads().filter((x) => !(x.repo === root && x.rel === rel))
168
- const undo = (aside: string | null, why: string): never => {
169
- if (aside) {
263
+ const mine = (x: Offload): boolean => x.repo === root && x.rel === rel
264
+ const aside = `${src}.${process.pid}.offloading`
265
+ const undo = (moved: boolean, why: string): never => {
266
+ if (moved) {
170
267
  if (lstatSync(src, { throwIfNoEntry: false })?.isSymbolicLink()) rmSync(src)
171
268
  renameSync(aside, src)
172
269
  }
173
- save(others)
270
+ editOffloads((list) => list.filter((x) => !mine(x)))
174
271
  rmSync(target, { recursive: true, force: true })
175
272
  throw new Error(`${rel} not offloaded, the folder stays on the Mac: ${why}`)
176
273
  }
177
274
  try {
178
- save([...others, { repo: root, rel, target, ...t, at: Date.now() }])
275
+ editOffloads((list) => [...list.filter((x) => !mine(x)), { repo: root, rel, target, ...t, at: Date.now(), aside }])
179
276
  } catch (e) {
180
277
  rmSync(target, { recursive: true, force: true })
181
278
  throw e
182
279
  }
183
- const aside = `${src}.${process.pid}.offloading`
184
280
  try {
185
281
  renameSync(src, aside)
186
282
  } catch (e) {
187
- return undo(null, (e as Error).message)
283
+ return undo(false, (e as Error).message)
188
284
  }
189
285
  try {
190
286
  symlinkSync(target, src)
191
287
  } catch (e) {
192
- return undo(aside, `the link was not made: ${(e as Error).message}`)
288
+ return undo(true, `the link was not made: ${(e as Error).message}`)
193
289
  }
194
290
  const after = tally(aside)
195
- if (after.files !== t.files || after.bytes !== t.bytes) return undo(aside, `it changed during the copy (${after.files} files, ${after.bytes} bytes now)`)
291
+ if (after.files !== t.files || after.bytes !== t.bytes) return undo(true, `it changed during the copy (${after.files} files, ${after.bytes} bytes now)`)
292
+ ;(o.flush ?? flushDrive)(target)
196
293
  rmSync(aside, { recursive: true, force: true })
294
+ editOffloads((list) => list.map((x) => (mine(x) ? { ...x, aside: undefined, held: true } : x)))
197
295
  return { rel, target, ...t }
198
296
  }
199
297
 
@@ -201,6 +299,8 @@ export async function offload(root: string, rel: string, o: Probe & { dry?: bool
201
299
  export function back(root: string, rel: string): Moved {
202
300
  const rec = offloads().find((x) => x.repo === root && x.rel === rel)
203
301
  if (!rec) throw new Error(`${rel} is not offloaded (sk annex lists what is)`)
302
+ if (rec.born) throw new Error(`${rel} is born on the annex (annex.born of the repo or house config): drop it from that list first, or the next pass links it again`)
303
+ if (rec.aside !== undefined || asidesOf(root, rel).length > 0) throw new Error(`a move of ${rel} is in flight (its Mac copy aside): the next pass finishes it, sk annex tidy does it now`)
204
304
  const src = join(root, rel)
205
305
  if (!lstatSync(src, { throwIfNoEntry: false })?.isSymbolicLink() || readlinkSync(src) !== rec.target) throw new Error(`${src} is no longer the link to ${rec.target}: look before you move`)
206
306
  if (!existsSync(rec.target)) throw new Error(`${rec.target} is missing: plug the drive in`)
@@ -213,21 +313,28 @@ export function back(root: string, rel: string): Moved {
213
313
  rmSync(part, { recursive: true, force: true })
214
314
  throw new Error(`${rel} not brought back: ${cp.exitCode !== 0 ? cp.stderr.toString().trim() : `the copy holds ${got?.files} files, the annex ${t.files}`}`)
215
315
  }
316
+ for (const e of entries(part)) if (e.file) syncFile(join(part, e.rel))
317
+ flushDrive(part)
216
318
  rmSync(src)
217
319
  renameSync(part, src)
218
- save(offloads().filter((x) => x !== rec && !(x.repo === root && x.rel === rel)))
320
+ editOffloads((list) => list.filter((x) => !(x.repo === root && x.rel === rel)))
219
321
  rmSync(rec.target, { recursive: true, force: true })
220
322
  return { rel, target: rec.target, ...t }
221
323
  }
222
324
 
223
325
  /** a record the Mac no longer needs, settled by what is there:
224
- * - a real folder where the link was (a split): the Mac's folder stays, the stale annex copy goes;
326
+ * - a real folder where the link was (a split): the Mac's folder stays, the stale annex copy goes to the annex's trash;
225
327
  * - a dangling link (the drive gone for good): the link and the record go, nothing else is reachable;
226
328
  * - nothing at all where the link was, and no annex copy: the record goes.
227
- * Refused while the link holds (that is `back`), and when the path is gone but the annex copy is there (relink it) */
228
- export function forget(root: string, rel: string): { rec: Offload; did: string } {
329
+ * Refused while the link holds (that is `back`), when the path is gone but the annex copy is there (relink it), and
330
+ * for what it would destroy: a born record (its pass owns it), a spill (written while the drive was away, merged back
331
+ * when it returns), a move in flight (its aside may hold the only copy) */
332
+ export function forget(root: string, rel: string, now = Date.now()): { rec: Offload; did: string } {
229
333
  const rec = offloads().find((x) => x.repo === root && x.rel === rel)
230
334
  if (!rec) throw new Error(`${rel} is not offloaded (sk annex lists what is)`)
335
+ if (rec.born) throw new Error(`${rel} is born on the annex: the daemon's pass keeps it (a wipe stays wiped, a spill goes back); to let it go, drop it from annex.born first`)
336
+ if (rec.spill !== undefined) throw new Error(`${rel} is a spill, written on the Mac while its drive was away: plug the drive in, the next pass merges it back`)
337
+ if (rec.aside !== undefined || asidesOf(root, rel).length > 0) throw new Error(`a move of ${rel} is in flight (its Mac copy aside, maybe the only copy): the next pass finishes it, sk annex tidy does it now`)
231
338
  const at = join(root, rel)
232
339
  const l = lstatSync(at, { throwIfNoEntry: false })
233
340
  let did: string
@@ -236,33 +343,59 @@ export function forget(root: string, rel: string): { rec: Offload; did: string }
236
343
  rmSync(at)
237
344
  did = `the dangling link went; ${rec.target} is unreachable`
238
345
  } else if (l) {
239
- rmSync(rec.target, { recursive: true, force: true })
240
- did = `the Mac folder stays, ${rec.target} was deleted`
346
+ const trash = toTrash(rec, now)
347
+ did = `the Mac folder stays, ${trash ? `the annex copy went to the annex's trash: ${trash}` : 'the annex copy was gone already'}`
241
348
  } else {
242
349
  if (existsSync(rec.target)) throw new Error(`${rel} is gone and ${rec.target} holds the copy: relink it with ln -s '${rec.target}' '${at}'`)
243
350
  did = 'nothing was left on either side'
244
351
  }
245
- save(offloads().filter((x) => !(x.repo === root && x.rel === rel)))
352
+ editOffloads((list) => list.filter((x) => !(x.repo === root && x.rel === rel)))
246
353
  return { rec, did }
247
354
  }
248
355
 
249
- export type Drift = { kind: 'dangling' | 'split' | 'gone' | 'orphan'; path: string; why: string; fix: string }
356
+ export type Drift = { kind: 'dangling' | 'split' | 'reset' | 'gone' | 'orphan' | 'spill' | 'aside' | 'kept'; path: string; why: string; fix: string }
250
357
 
251
- /** what no longer matches the records, for one repo, each with the command that settles it: a link that reaches
252
- * nothing (the drive unplugged), a real folder where the link was (a cache reset), a link gone, a file on a present
253
- * annex under this repo's name that no record of any repo reaches */
358
+ /** what no longer matches the records, for one repo, each with what settles it: a move in flight (an aside, recorded
359
+ * or not), a spill, a link that reaches nothing (the drive unplugged), a real folder where the link was (a split; for
360
+ * a born folder, a wipe its pass settles), a link gone, a loser a merge kept, and a file on a present annex under this
361
+ * repo's name that no record of any repo reaches. A born record's fix never names `forget` */
254
362
  export async function drift(root: string): Promise<Drift[]> {
255
363
  const out: Drift[] = []
256
364
  const mine = offloads().filter((x) => resolve(x.repo) === resolve(root))
365
+ const named = new Set<string>()
257
366
  for (const x of mine) {
258
367
  const at = join(x.repo, x.rel)
259
368
  const l = lstatSync(at, { throwIfNoEntry: false })
260
- if (l?.isSymbolicLink()) {
261
- if (!existsSync(at)) out.push({ kind: 'dangling', path: at, why: `its link reaches nothing: ${x.target} is missing (the drive unplugged?)`, fix: `plug the drive in; if it is gone for good, sk annex forget ${at}` })
262
- } else if (l) out.push({ kind: 'split', path: at, why: `a real folder on the Mac again, while ${x.target} holds the offloaded copy`, fix: `sk annex forget ${at} keeps the Mac folder and deletes the stale annex copy` })
369
+ for (const a of [...new Set([...(x.aside !== undefined && existsSync(x.aside) ? [x.aside] : []), ...asidesOf(x.repo, x.rel)])]) {
370
+ named.add(a)
371
+ out.push({ kind: 'aside', path: a, why: `the Mac's copy of ${x.rel} set aside, its move to ${x.target} not finished`, fix: 'the next pass finishes it (sk annex tidy does it now); never delete it, it can hold the only copy' })
372
+ }
373
+ for (const k of x.kept ?? []) if (existsSync(k)) out.push({ kind: 'kept', path: k, why: `two versions of one file met in a merge, this one lost its name`, fix: `compare it with ${k.replace(/\.(mac|annex)-\d{8}-\d{6}(-\d+)?$/, '')}, then delete the one you do not want` })
374
+ if (x.spill !== undefined && l && !l.isSymbolicLink()) {
375
+ const t = tally(at)
376
+ out.push({ kind: 'spill', path: at, why: `on the Mac since ${new Date(x.spill).toISOString().slice(0, 16)}Z while no annex is present (${t.files} files, ${(t.bytes / GB).toFixed(1)} GB)`, fix: 'plug the drive in: the daemon merges it back within a minute; sk annex tidy does it now' })
377
+ } else if (l?.isSymbolicLink()) {
378
+ if (!existsSync(at)) out.push({ kind: 'dangling', path: at, why: `its link reaches nothing: ${x.target} is missing (the drive unplugged?)`, fix: x.born ? "plug the drive in; while it is away, a pass spills it on the Mac (the daemon's annex job when on, or sk annex tidy)" : `plug the drive in; if it is gone for good, sk annex forget ${at}` })
379
+ } else if (l && x.born) out.push({ kind: 'reset', path: at, why: 'a real folder where its born link was: a tool wiped it', fix: "the next pass keeps this folder and moves the old annex copy to the annex's trash; sk annex tidy does it now" })
380
+ else if (l) out.push({ kind: 'split', path: at, why: `a real folder on the Mac again, while ${x.target} holds the offloaded copy`, fix: `sk annex forget ${at} keeps the Mac folder and moves the stale annex copy to the annex's trash` })
381
+ else if (x.born) out.push({ kind: 'gone', path: at, why: 'its born link is gone', fix: 'the next pass links it again; sk annex tidy does it now' })
263
382
  else if (existsSync(x.target)) out.push({ kind: 'gone', path: at, why: `the link is gone, ${x.target} holds the copy`, fix: `ln -s '${x.target}' '${at}'` })
264
383
  else out.push({ kind: 'gone', path: at, why: `the link and ${x.target} are both gone`, fix: `sk annex forget ${at}` })
265
384
  }
385
+ // an aside of a folder no record of this repo names: no pass adopts it
386
+ for (const dir of new Set([...SCRATCH.map((d) => join(root, d)), ...mine.map((x) => dirname(join(x.repo, x.rel)))])) {
387
+ let names: string[] = []
388
+ try {
389
+ names = readdirSync(dir)
390
+ } catch {
391
+ continue
392
+ }
393
+ for (const n of names) {
394
+ const p = join(dir, n)
395
+ if (!ASIDE.test(n) || named.has(p)) continue
396
+ out.push({ kind: 'aside', path: p, why: 'a Mac folder a move set aside, and no record names its folder', fix: `move its files back into ${join(dir, ASIDE.exec(n)![1]!)} by hand; never delete it, it can hold the only copy` })
397
+ }
398
+ }
266
399
  const targets = offloads().map((x) => x.target)
267
400
  const reached = (p: string): boolean => targets.some((t) => p === t || p.startsWith(`${t}/`) || t.startsWith(`${p}/`))
268
401
  for (const a of await presentAnnexes()) {
@@ -0,0 +1,53 @@
1
+ // what a move off the Mac really freed (wiki tools/shipkit/annex.md, Freed is not free). A local Time Machine snapshot
2
+ // holds the blocks of every file that existed when it was taken, so moving or deleting such a file frees nothing until
3
+ // the snapshot goes (Time Machine replaces it at its next backup, macOS purges it when space runs short). Measured: 15
4
+ // GB moved off one repo, the disk 3 GB freer. So a report says what is still held, never lets `df` speak
5
+ import type { Offload } from './offload.ts'
6
+
7
+ export type Snapshot = { name: string; at: number }
8
+
9
+ /** a snapshot's date from its name, `com.apple.TimeMachine.2030-01-02-030405.local`, in local time */
10
+ export function snapshotAt(name: string): number | null {
11
+ const m = /(\d{4})-(\d{2})-(\d{2})-(\d{2})(\d{2})(\d{2})/.exec(name)
12
+ return m ? new Date(+m[1]!, +m[2]! - 1, +m[3]!, +m[4]!, +m[5]!, +m[6]!).getTime() : null
13
+ }
14
+
15
+ /** the boot disk's local Time Machine snapshots, oldest first (one `tmutil` call, about 50 ms) */
16
+ export function localSnapshots(): Snapshot[] {
17
+ const r = Bun.spawnSync(['tmutil', 'listlocalsnapshots', '/'], { stdout: 'pipe', stderr: 'ignore' })
18
+ return r.stdout
19
+ .toString()
20
+ .split('\n')
21
+ .map((l) => l.trim())
22
+ .filter((l) => l.startsWith('com.apple.TimeMachine'))
23
+ .flatMap((name) => {
24
+ const at = snapshotAt(name)
25
+ return at === null ? [] : [{ name, at }]
26
+ })
27
+ .sort((a, b) => a.at - b.at)
28
+ }
29
+
30
+ /** the bytes the records moved off the Mac, and of them those a snapshot taken before their move may still hold: an
31
+ * upper bound, since a file born after that snapshot is not held. `until` names the newest such snapshot */
32
+ export function held(recs: readonly Offload[], snaps: readonly Snapshot[]): { moved: number; held: number; until: string | null } {
33
+ let moved = 0
34
+ let kept = 0
35
+ let until: Snapshot | null = null
36
+ for (const r of recs) {
37
+ moved += r.bytes
38
+ const before = snaps.filter((s) => s.at < r.at)
39
+ if (before.length === 0) continue
40
+ kept += r.bytes
41
+ const last = before[before.length - 1]!
42
+ if (!until || last.at > until.at) until = last
43
+ }
44
+ return { moved, held: kept, until: until?.name ?? null }
45
+ }
46
+
47
+ /** one line for a report: what moved, and what a snapshot still holds; null when nothing moved */
48
+ export function heldWords(h: ReturnType<typeof held>): string | null {
49
+ if (h.moved === 0) return null
50
+ const gb = (n: number): string => `${(n / 1e9).toFixed(1)} GB`
51
+ if (h.held === 0) return `moved off the Mac: ${gb(h.moved)}, all of it free`
52
+ return `moved off the Mac: ${gb(h.moved)}, of which at most ${gb(h.held)} is still held by the local snapshot ${h.until} until it goes (the next Time Machine backup replaces it): df will not show it before`
53
+ }