rvlib-shipkit 2.18.0 → 2.20.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 (186) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/package.json +1 -1
  3. package/src/annex/annex.ts +227 -0
  4. package/src/annex/offload.ts +279 -0
  5. package/src/asks/asks-queue.ts +63 -10
  6. package/src/checks/SK040-release-words.check.ts +43 -0
  7. package/src/checks/SK041-annex-links.check.ts +28 -0
  8. package/src/checks/SK042-post-kinds.check.ts +73 -0
  9. package/src/cli/cmd_Annex.ts +179 -0
  10. package/src/cli/cmd_Asks.ts +3 -1
  11. package/src/cli/cmd_Commands.ts +4 -1
  12. package/src/cli/cmd_GlobalProcesses.ts +34 -11
  13. package/src/cli/cmd_Home.ts +41 -4
  14. package/src/cli/cmd_Messages.ts +155 -0
  15. package/src/cli/cmd_Releases.ts +48 -0
  16. package/src/cli/cmd_Review.ts +161 -6
  17. package/src/cli/cmd_Secret.ts +4 -30
  18. package/src/cli/cmd_Shot.ts +4 -4
  19. package/src/cli/cmd_Social.ts +179 -3
  20. package/src/cli/cmd_Trailer.ts +15 -3
  21. package/src/cli/family-pages.ts +2 -0
  22. package/src/cli/kit/index.ts +1 -1
  23. package/src/cli/kit/verb.ts +11 -3
  24. package/src/cli/registry.ts +8 -2
  25. package/src/collections/actions.ts +29 -1
  26. package/src/collections/collection-types.ts +10 -1
  27. package/src/collections/providers.ts +5 -2
  28. package/src/commands/model.ts +36 -0
  29. package/src/commands/registry.ts +49 -0
  30. package/src/commands/routes.ts +59 -0
  31. package/src/commands/runner.ts +35 -0
  32. package/src/commands/runs.ts +112 -0
  33. package/src/core/app-icon.ts +4 -3
  34. package/src/core/icon-type.ts +8 -0
  35. package/src/core/jobs.ts +4 -3
  36. package/src/core/layout.ts +5 -2
  37. package/src/core/squircle.ts +95 -0
  38. package/src/home/daemon-jobs.ts +26 -2
  39. package/src/home/global-units.ts +3 -0
  40. package/src/home/gui-app/ShipkitGui.swift +302 -5
  41. package/src/home/gui-app.ts +63 -33
  42. package/src/home/hmr-keep.ts +134 -0
  43. package/src/home/home-paths.ts +5 -1
  44. package/src/home/home-start.ts +14 -14
  45. package/src/home/lib-watch.ts +21 -11
  46. package/src/home/pm.ts +1 -1
  47. package/src/home/process-apps.ts +181 -0
  48. package/src/home/resources.ts +3 -3
  49. package/src/home/run-daemon.ts +11 -2
  50. package/src/home/run-pm.ts +9 -1
  51. package/src/home/run-web.ts +7 -4
  52. package/src/home/serve-web.ts +64 -14
  53. package/src/home/supervise.ts +3 -1
  54. package/src/identities/collection.ts +49 -0
  55. package/src/identities/identities.ts +130 -11
  56. package/src/identities/machine.ts +4 -3
  57. package/src/identities/rating.ts +33 -0
  58. package/src/identities/shown.ts +170 -0
  59. package/src/identities/steps.ts +5 -0
  60. package/src/media-store/purge.ts +15 -1
  61. package/src/media-store/remote.ts +22 -6
  62. package/src/messages/brief.ts +117 -0
  63. package/src/messages/collection.ts +40 -0
  64. package/src/messages/model.ts +171 -0
  65. package/src/messages/routes.ts +15 -0
  66. package/src/messages/score.ts +180 -0
  67. package/src/messages/tabs.ts +13 -0
  68. package/src/release/notes.ts +130 -0
  69. package/src/release/run-bump.ts +41 -18
  70. package/src/release/run-release.ts +22 -4
  71. package/src/release/run-releases.ts +17 -15
  72. package/src/release/unit-resolve.ts +9 -0
  73. package/src/releases/add.ts +66 -0
  74. package/src/releases/collection.ts +36 -0
  75. package/src/releases/from-card.ts +66 -0
  76. package/src/releases/model.ts +267 -0
  77. package/src/releases/pictures.ts +89 -0
  78. package/src/releases/routes.ts +36 -0
  79. package/src/releases/store.ts +71 -0
  80. package/src/repo-config.ts +5 -0
  81. package/src/review/cells.ts +0 -11
  82. package/src/review/format.ts +10 -6
  83. package/src/review/http.ts +7 -2
  84. package/src/review/model.ts +92 -3
  85. package/src/review/notes.ts +2 -48
  86. package/src/review/routes.ts +28 -10
  87. package/src/review/stage-card.ts +197 -0
  88. package/src/review/stage-routes.ts +123 -0
  89. package/src/review/store.ts +117 -19
  90. package/src/review/trailer-card.ts +99 -0
  91. package/src/review/trailer-desk.ts +57 -4
  92. package/src/review/trailer-model.ts +41 -7
  93. package/src/review/trailer-notes.ts +45 -0
  94. package/src/review/trailer-routes.ts +22 -13
  95. package/src/secrets/manager.ts +59 -0
  96. package/src/secrets/name.ts +2 -0
  97. package/src/serve/hub-app/app-bridge.ts +71 -0
  98. package/src/serve/hub-app/col-card.tsx +10 -0
  99. package/src/serve/hub-app/cols-svc.ts +37 -6
  100. package/src/serve/hub-app/commands/commands-page.tsx +122 -0
  101. package/src/serve/hub-app/commands/commands-st.ts +177 -0
  102. package/src/serve/hub-app/commands.css +24 -0
  103. package/src/serve/hub-app/hash-route.ts +40 -1
  104. package/src/serve/hub-app/home-st.ts +11 -2
  105. package/src/serve/hub-app/home.html +3 -0
  106. package/src/serve/hub-app/hub-app.tsx +6 -0
  107. package/src/serve/hub-app/hub.css +1 -0
  108. package/src/serve/hub-app/icons.tsx +5 -0
  109. package/src/serve/hub-app/identities-view.tsx +4 -1
  110. package/src/serve/hub-app/identities.css +1 -0
  111. package/src/serve/hub-app/index.html +3 -0
  112. package/src/serve/hub-app/keys.ts +2 -2
  113. package/src/serve/hub-app/machine-st.ts +41 -10
  114. package/src/serve/hub-app/messages/messages-page.tsx +354 -0
  115. package/src/serve/hub-app/messages/messages-st.ts +74 -0
  116. package/src/serve/hub-app/messages.css +35 -0
  117. package/src/serve/hub-app/releases/releases-page.tsx +94 -0
  118. package/src/serve/hub-app/releases/releases-st.ts +69 -0
  119. package/src/serve/hub-app/releases.css +25 -0
  120. package/src/serve/hub-app/repo-sections.ts +15 -1
  121. package/src/serve/hub-app/repo-st.ts +56 -5
  122. package/src/serve/hub-app/review/clip-st.ts +31 -3
  123. package/src/serve/hub-app/review/note-place.ts +31 -0
  124. package/src/serve/hub-app/review/review-cells.tsx +27 -3
  125. package/src/serve/hub-app/review/review-st.ts +77 -2
  126. package/src/serve/hub-app/review/review-thread.tsx +9 -31
  127. package/src/serve/hub-app/review/review-views.tsx +164 -58
  128. package/src/serve/hub-app/review/thread-st.ts +108 -41
  129. package/src/serve/hub-app/review/trailer-card.tsx +187 -0
  130. package/src/serve/hub-app/review/trailer-page.tsx +62 -31
  131. package/src/serve/hub-app/review/trailer-st.ts +138 -26
  132. package/src/serve/hub-app/review/trailer-timeline.tsx +39 -26
  133. package/src/serve/hub-app/review.css +49 -6
  134. package/src/serve/hub-app/social/comms-page.tsx +55 -23
  135. package/src/serve/hub-app/social/identity-pictures.ts +112 -0
  136. package/src/serve/hub-app/social/kit.tsx +9 -6
  137. package/src/serve/hub-app/social/post-card.tsx +10 -2
  138. package/src/serve/hub-app/social/social-model.ts +37 -3
  139. package/src/serve/hub-app/social/social-page.tsx +236 -82
  140. package/src/serve/hub-app/social/social-st.ts +79 -26
  141. package/src/serve/hub-app/social/stage-popup.tsx +268 -0
  142. package/src/serve/hub-app/social/stage-st.ts +310 -0
  143. package/src/serve/hub-app/social/step-layout.ts +42 -0
  144. package/src/serve/hub-app/social.css +68 -4
  145. package/src/serve/hub-app/tree-build.ts +38 -1
  146. package/src/serve/hub-app/tree-svc.ts +10 -3
  147. package/src/serve/project-gutter-route.ts +4 -2
  148. package/src/serve/same-origin.ts +24 -1
  149. package/src/serve/serve-hub.ts +27 -3
  150. package/src/shipkit-files.ts +9 -7
  151. package/src/shot/shooter.ts +3 -3
  152. package/src/shot/shot-ask.ts +14 -3
  153. package/src/shot/shot.shipkit.ts +1 -1
  154. package/src/social/discord-layout.ts +282 -0
  155. package/src/social/fit.ts +84 -0
  156. package/src/social/identity-words.ts +74 -0
  157. package/src/social/kind-pages.ts +41 -0
  158. package/src/social/kinds.ts +92 -0
  159. package/src/social/load.ts +105 -9
  160. package/src/social/md.ts +14 -6
  161. package/src/social/media-limit.ts +63 -2
  162. package/src/social/presence.ts +1 -1
  163. package/src/social/publish/bluesky.ts +58 -19
  164. package/src/social/publish/discord.ts +3 -2
  165. package/src/social/publish/index.ts +31 -5
  166. package/src/social/reach.ts +49 -0
  167. package/src/social/release-stage.ts +173 -0
  168. package/src/social/routes.ts +44 -9
  169. package/src/social/stage.ts +227 -0
  170. package/src/social/strip.ts +85 -0
  171. package/src/social/text.ts +6 -2
  172. package/src/social/unit.ts +57 -1
  173. package/src/social/writes.ts +11 -0
  174. package/src/stores/routes.ts +2 -2
  175. package/src/suite/judge-suites.ts +1 -1
  176. package/src/suite/suite-cli.ts +5 -5
  177. package/src/trailer/build.ts +90 -52
  178. package/src/trailer/draft.ts +28 -0
  179. package/src/trailer/footage.ts +4 -2
  180. package/src/trailer/grammar.ts +25 -13
  181. package/src/trailer/graph.ts +32 -9
  182. package/src/trailer/profile.ts +35 -0
  183. package/src/trailer/prune.ts +15 -10
  184. package/src/trailer/public-words.ts +41 -0
  185. package/src/trailer/stitch.ts +22 -10
  186. package/src/trailer/titles.ts +47 -2
package/CHANGELOG.md CHANGED
@@ -1,3 +1,34 @@
1
+ ## 2.20.0
2
+
3
+ - **Post kinds: a closed set, checked.** A draft's `kind` is one of `announcement`, `feature`, `iteration`, `showcase`, `release`, `trailer`, `throwback` or `custom`, or a kind its social unit declares (`kinds: [{ id, for, page }]`). SK042 fails a draft with no kind, a word outside the set, or a `custom` with no `kindWhy:` line; an older word only warns and names its kind. A kind problem never blocks Publish. The Communications desk filters by kind and links each kind's rules page.
4
+ - **The stage popup picks the post's kind.** A card stages as `feature` and a release as `release`; `custom` asks why no kind fits. `sk review stage` takes `--kind` and `--kind-why`.
5
+ - **One guard on every public word.** The repo's `guard` now reads heading titles and tags, a cut's titles and voice transcripts, the identity's profile rows and pictures, and its Discord layout. `sk identities push` and `sk social discord apply` send nothing the guard refuses.
6
+ - **Card to post.** A card's media stages as a draft, rated against each place it can reach and guarded; a staged clip can be cut to a passage and fitted to each venue's limits.
7
+ - **Releases as illustrated files.** One md per version in `.shipkit/releases/`, filled from approved cards (`sk review add --changelog`) or by hand (`sk releases add`), each change with its picture kept private until the release; the hub's Releases row. A change written again keeps its card.
8
+ - **The messages store as a unit.** `sk messages` checks every phrasing through the repo's guard and runs the blind reader packets, briefs, matrix and surface ranking; the hub's Messages row has its four pages.
9
+ - **The shipkit app's Dock badge and notifications.** The badge counts the review cards waiting across every repo; a new card posts one notification, removed once the card is answered. The app keeps running with no window open; `--background` starts it with none.
10
+ - **The hub reloads only when what it shows changed.** A page edit hot swaps with no server restart; a server restart the page did not need keeps the page; pm no longer restarts on unit edits; an outage card shows only past 15 s.
11
+ - **A commands page per repo**: the project CLI's commands as a tree, run from the page with the log live.
12
+ - **Review cards**: a choice card shows the agent's pick; a trailer card takes notes by time with rectangles, and every version plays its own render; the « changes » compare mode stays on its card.
13
+ - **The annex: an external drive for heavy files.** A purge copies to the drive before it deletes, `fetchBack` reads it first, and a database never goes there.
14
+ - **`sk shot` writes a webp at quality 90 by default**; the extension of `--out` picks the encoding.
15
+ - **The hub's tab has an icon**, and `/favicon.ico` no longer answers 404.
16
+
17
+ ## 2.19.0
18
+
19
+ - **`sk trailer --draft`: a quick cut to judge the beats.** Half the size, `out/<name>-draft.mp4`, the cut's own mix, no strip (`--strip` draws one), no shelf. It reads every take the cut has filmed; a take the cut lacks films as a draft take under its own key, its row told by `SK_TRAILER_DRAFT=1` and the draft's size, so no full build or `keep` ever reads it. The prune keeps a cut's draft renders beside its own.
20
+ - **The trailer's sound is mixed while the takes film.** It reads no take, so it no longer waits for the filming nor runs beside the sections.
21
+ - **The mix lands on its `master` in two or three passes.** A pass counts what its trim takes off the loudness and what a dB of gain moved it last time, and a gap measured on the 0.3 LU tolerance holds (a float difference of 0.30000000000000071 used to run four more passes). A mix that never holds keeps its pass under the ceiling nearest its master, not its last one. Measured on a 74 s cut: 5, 6, 2 and 6 passes at four masters became 2, 2, 3 and 3. A cut whose mix is cached mixes again once, and lands within the same 0.3 LU, at a slightly different level.
22
+ - **`sk trailer --profile`** prints every phase of a build, with its start, its seconds and its share of the run.
23
+ - **A big title can stand in the middle.** `place middle` joins top and bottom and centres the title's block on the frame. `sub` draws the lines after the first break smaller, at that share of the size. `shade` lays a soft dark scrim round the words, so they read over a busy picture. A title without these words draws as before.
24
+ - **`sk social discord apply [identity]`: an identity's Discord server is data.** `layout.md` beside the identity's discord `account.md` holds a `## Roles` table, one `##` heading per category with its channels (emoji, topic, read only, voice, age restricted, the roles it is only for), and a `## Members` table that gives roles to members by username. The parser names every bad row at once. The apply writes only what differs, compares each channel by name, category, topic, nsfw flag and permission overwrites, and only gives roles, never takes them. With no guild yet, it names the servers the bot is in.
25
+ - **A credential ask takes the token on its hub page.** An ask that names `secret: <name> [<name>…]` in its front matter shows a password field and a store button per secret. The hub stores the value through the repo's `credsCommand` (the same argv as `sk secret set`, value on stdin), runs that ask's check, and archives the ask when it passes.
26
+ - **`sk pm restart [daemon|web]`** restarts the daemon, the web or both through pm and waits until each probe answers.
27
+ - **pm runs from the house wherever it starts.** `sk pm install` typed in a subfolder of a repo wrote that folder as the LaunchAgent's working directory, and the daemon died at boot with no `repo.config.ts` there. Install now writes the house root of the folder, and pm and the daemon each resolve the house from the wiki index they read, so a hand run inside any folder runs from the house too.
28
+ - **The full test tier runs in parallel workers**, as the quick tier does: the slow suites included, the serial ones alone after, with the full tier's own timeout. Measured on this package: 339 files in 20.2 s on 8 workers, against 44.1 s one suite at a time.
29
+ - **An identity's hub page shows every picture.** The hub serves `.svg` as `image/svg+xml`, so an svg avatar draws. A profile row with a note in parentheses shows its files as tiles and the note under them. The identity's own `pictures/` folder is always listed, one tile per picture with its other formats as downloads, avatars and banners grouped by venue.
30
+ - **The review list can no longer go stale.** It refreshed from file watch events alone, so a watch that went silent under load froze it until the daemon restarted. The watch is now a fast path, and every request also checks the store folder on disk.
31
+
1
32
  ## 2.18.0
2
33
 
3
34
  - **SK039: VS Code watches none of shipkit's generated folders.** `.vscode/settings.json` excludes `**/.shipkit/cache/**`, `**/.shipkit/tmp/**`, `**/.shipkit/review/**` and `**/trailer/**/out/**` from `files.watcherExclude`, so the files a build, a film or a test writes never wake the extension host. It warns, and the fix pass of every `sk ci` inserts the missing globs into the hand written jsonc, every other byte kept, or writes a settings file holding the exclusion alone. A glob set to `false` stays; a root published to npm or a linked `.vscode/` is left alone. The scaffold's template carries the block.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rvlib-shipkit",
3
- "version": "2.18.0",
3
+ "version": "2.20.0",
4
4
  "funding": "https://github.com/sponsors/rvion",
5
5
  "description": "All-in-one repo companion: ci gate (task DAG), auto-discovered health checks, release-contract fulfillness, asks queue, md-wiki tools, asset atelier, live tui",
6
6
  "license": "MIT",
@@ -0,0 +1,227 @@
1
+ // the annex: folders on external drives the house config lists, for the machine's heavy files and never a db (wiki
2
+ // tools/shipkit/annex.md). An annex is present only while its root holds the marker `sk annex init` wrote, so an
3
+ // unplugged drive, or a phantom folder where it used to mount, is never written. Its media are the Space's keys under
4
+ // `media/`: every one is also in the Space, so the cap may drop any of them
5
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, statfsSync, utimesSync, writeFileSync } from 'node:fs'
6
+ import { homedir } from 'node:os'
7
+ import { dirname, join, resolve } from 'node:path'
8
+ import { shaOf, shaOfKey } from '../media-store/content.ts'
9
+
10
+ export const ANNEX_MARK = '.shipkit-annex'
11
+ /** a JSON list of annexes, or `off`, in place of the house config's for one process (a test's temp folder) */
12
+ export const ANNEX_ENV = 'SHIPKIT_ANNEXES'
13
+ const GB = 1e9
14
+ /** under this much free space on its drive an annex takes no new media, and its sweep trims, unless the annex says
15
+ * `keepFreeGb`: the drive is shared (the T7 holds Time Machine beside it) */
16
+ export const ANNEX_FREE_MIN = 50 * GB
17
+ /** a `.part` left by a killed copy, swept after this long */
18
+ const PART_STALE_MS = 86_400_000
19
+
20
+ export type AnnexSpec = {
21
+ /** the annex root on the external drive: `sk annex init` writes its marker there */
22
+ path: string
23
+ /** the most its media may hold, in GB; offloaded folders never count against it */
24
+ maxGb?: number
25
+ /** the free space its drive keeps, in GB (ANNEX_FREE_MIN when none is given) */
26
+ keepFreeGb?: number
27
+ }
28
+
29
+ export const keepFree = (spec: AnnexSpec): number => (spec.keepFreeGb === undefined ? ANNEX_FREE_MIN : spec.keepFreeGb * GB)
30
+
31
+ let held: Promise<AnnexSpec[]> | null = null
32
+
33
+ /** the annexes the house config lists, in order, read once per process */
34
+ export function annexSpecs(): Promise<AnnexSpec[]> {
35
+ held ??= (async (): Promise<AnnexSpec[]> => {
36
+ const env = process.env[ANNEX_ENV]
37
+ if (env !== undefined) return env === 'off' ? [] : (JSON.parse(env) as AnnexSpec[])
38
+ const { houseRoot } = await import('../home/home-start.ts')
39
+ const { loadRepoConfig } = await import('../repo-config.ts')
40
+ const house = houseRoot(process.cwd())
41
+ return house ? ((await loadRepoConfig(house)).serve?.annexes ?? []) : []
42
+ })().catch((e: unknown) => {
43
+ console.error(`WARN annex: the annex list does not load: ${(e as Error).message}`)
44
+ return []
45
+ })
46
+ return held
47
+ }
48
+
49
+ /** a test's own annex list in place of the machine's; undefined reads the machine's again */
50
+ export function useAnnexes(specs: AnnexSpec[] | undefined): void {
51
+ held = specs === undefined ? null : Promise.resolve(specs)
52
+ }
53
+
54
+ /** the annex is mounted and marked: never only that its path exists */
55
+ export const isPresent = (spec: AnnexSpec): boolean => statSync(join(spec.path, ANNEX_MARK), { throwIfNoEntry: false })?.isFile() === true
56
+
57
+ export const presentAnnexes = async (): Promise<AnnexSpec[]> => (await annexSpecs()).filter(isPresent)
58
+
59
+ /** free bytes on the drive that holds `path` */
60
+ export function driveFree(path: string): number {
61
+ const s = statfsSync(path)
62
+ return Number(s.bavail) * Number(s.bsize)
63
+ }
64
+
65
+ /** mark `path` as an annex. Refused when its parent is missing (the drive is not mounted) or it sits on the same disk
66
+ * as the home folder (it would free nothing) */
67
+ export function initAnnex(path: string): string {
68
+ const root = resolve(path)
69
+ const parent = dirname(root)
70
+ if (!existsSync(parent)) throw new Error(`${parent} does not exist: mount the drive first, an annex root is never made with its parents`)
71
+ if (statSync(parent).dev === statSync(homedir()).dev) throw new Error(`${root} is on the same disk as ${homedir()}: an annex there frees nothing`)
72
+ const tm = timeMachineOf(parent)
73
+ if (tm) throw new Error(`${parent} is a Time Machine volume (${tm}): an annex goes on the data volume beside it`)
74
+ if (!existsSync(root)) mkdirSync(root, { mode: 0o700 })
75
+ writeFileSync(join(root, ANNEX_MARK), `shipkit annex, made ${new Date().toISOString()}: wiki tools/shipkit/annex.md\n`)
76
+ return root
77
+ }
78
+
79
+ /** the mount point of the volume holding `path`: its highest folder on the same device */
80
+ export function mountOf(path: string): string {
81
+ let p = resolve(path)
82
+ const dev = statSync(p).dev
83
+ while (p !== '/' && statSync(dirname(p)).dev === dev) p = dirname(p)
84
+ return p
85
+ }
86
+
87
+ /** why the volume holding `path` is a Time Machine one, null when it is not: a destination tmutil names, the Backup
88
+ * role, a backup folder at its root, or its name */
89
+ export function timeMachineOf(path: string): string | null {
90
+ const mount = mountOf(path)
91
+ if (!mount || mount === '/') return null
92
+ const dest = Bun.spawnSync(['tmutil', 'destinationinfo'], { stdout: 'pipe', stderr: 'ignore' }).stdout.toString()
93
+ if (dest.split('\n').some((l) => /^Mount Point\s*:/.test(l) && l.split(':').slice(1).join(':').trim() === mount)) return 'a tmutil destination'
94
+ if (/Role:.*Backup|\(Backup\)/i.test(Bun.spawnSync(['diskutil', 'info', mount], { stdout: 'pipe', stderr: 'ignore' }).stdout.toString())) return 'the APFS Backup role'
95
+ if (['Backups.backupdb', '.timemachine'].some((n) => existsSync(join(mount, n)))) return 'a backup folder at its root'
96
+ if (/time ?machine/i.test(mount)) return 'its name'
97
+ return null
98
+ }
99
+
100
+ export const mediaAt = (spec: AnnexSpec, key: string): string => join(spec.path, 'media', key)
101
+
102
+ /** bytes of media an annex holds, walked once per process, then kept by the keep and the sweep */
103
+ const used = new Map<string, number>()
104
+ function mediaBytes(spec: AnnexSpec): number {
105
+ const had = used.get(spec.path)
106
+ if (had !== undefined) return had
107
+ const n = mediaFiles(spec).reduce((s, f) => s + f.size, 0)
108
+ used.set(spec.path, n)
109
+ return n
110
+ }
111
+
112
+ /** every media file of an annex, `.part` copies left out */
113
+ export function mediaFiles(spec: AnnexSpec): { path: string; size: number; used: number }[] {
114
+ const dir = join(spec.path, 'media')
115
+ if (!existsSync(dir)) return []
116
+ const out: { path: string; size: number; used: number }[] = []
117
+ for (const d of readdirSync(dir, { withFileTypes: true, recursive: true })) {
118
+ if (!d.isFile() || d.name.endsWith('.part')) continue
119
+ const path = join(d.parentPath, d.name)
120
+ const s = statSync(path, { throwIfNoEntry: false })
121
+ if (s) out.push({ path, size: s.size, used: s.mtimeMs })
122
+ }
123
+ return out
124
+ }
125
+
126
+ const roomFor = (spec: AnnexSpec, size: number): boolean =>
127
+ driveFree(spec.path) - size > keepFree(spec) && (spec.maxGb === undefined || mediaBytes(spec) + size <= spec.maxGb * GB)
128
+
129
+ /** each copy's own `.part`: the purge's jobs can hold one key twice */
130
+ let parts = 0
131
+
132
+ const touch = (path: string): void => {
133
+ const now = new Date()
134
+ utimesSync(path, now, now)
135
+ }
136
+
137
+ /** keep `file` (the content `key` names) on the first annex present with room: a `.part` copy of its own, its sha
138
+ * checked against the key, then renamed. The annex it is on and whether this call copied it (an annex holding the key
139
+ * already is only touched), null when none is present or has room, or the key names no sha. A copy that fails throws,
140
+ * its `.part` removed */
141
+ export async function annexKeep(file: string, key: string, size: number): Promise<{ annex: AnnexSpec; copied: boolean } | null> {
142
+ const sha = shaOfKey(key)
143
+ if (!sha) return null
144
+ const annexes = await presentAnnexes()
145
+ for (const a of annexes) {
146
+ const at = mediaAt(a, key)
147
+ if (statSync(at, { throwIfNoEntry: false })?.size === size) {
148
+ touch(at)
149
+ return { annex: a, copied: false }
150
+ }
151
+ }
152
+ const a = annexes.find((x) => roomFor(x, size))
153
+ if (!a) return null
154
+ const at = mediaAt(a, key)
155
+ const part = `${at}.${process.pid}-${(++parts).toString(36)}.part`
156
+ mkdirSync(dirname(at), { recursive: true })
157
+ try {
158
+ copyFileSync(file, part)
159
+ const got = await shaOf(part)
160
+ if (got !== sha || statSync(part).size !== size) throw new Error(`the copy hashes to ${got.slice(0, 12)}, the key says ${sha.slice(0, 12)}`)
161
+ if (statSync(at, { throwIfNoEntry: false })?.size === size) {
162
+ rmSync(part, { force: true })
163
+ return { annex: a, copied: false }
164
+ }
165
+ renameSync(part, at)
166
+ } catch (e) {
167
+ rmSync(part, { force: true })
168
+ throw new Error(`${key} not kept on the annex ${a.path}: ${(e as Error).message}`)
169
+ }
170
+ used.set(a.path, mediaBytes(a) + size)
171
+ return { annex: a, copied: true }
172
+ }
173
+
174
+ /** the annex's copy of `key` at `size` copied to `dest`: the annex file it came from, null when no present annex holds
175
+ * it. The caller checks the sha, and calls `annexDrop` on a copy that fails */
176
+ export async function annexCopy(key: string, size: number, dest: string): Promise<string | null> {
177
+ for (const a of await presentAnnexes()) {
178
+ const at = mediaAt(a, key)
179
+ if (statSync(at, { throwIfNoEntry: false })?.size !== size) continue
180
+ copyFileSync(at, dest)
181
+ touch(at)
182
+ return at
183
+ }
184
+ return null
185
+ }
186
+
187
+ /** a wrong annex copy removed, loud: the Space still holds the content */
188
+ export function annexDrop(at: string, why: string): void {
189
+ console.error(`WARN annex: ${at} dropped: ${why}`)
190
+ rmSync(at, { force: true })
191
+ used.clear()
192
+ }
193
+
194
+ export interface Sweep {
195
+ annex: string
196
+ files: number
197
+ bytes: number
198
+ freed: { files: number; bytes: number }
199
+ }
200
+
201
+ /** trim an annex's media, used longest ago first, until it is under its cap and its drive keeps its free space.
202
+ * Safe for any file: the Space holds every media of an annex. A stale `.part` goes too */
203
+ export function annexSweep(spec: AnnexSpec, o: { dry?: boolean; now?: number } = {}): Sweep {
204
+ const files = mediaFiles(spec).sort((a, b) => a.used - b.used)
205
+ let bytes = files.reduce((s, f) => s + f.size, 0)
206
+ const out: Sweep = { annex: spec.path, files: files.length, bytes, freed: { files: 0, bytes: 0 } }
207
+ if (!isPresent(spec)) return out
208
+ const cap = spec.maxGb === undefined ? Infinity : spec.maxGb * GB
209
+ let free = driveFree(spec.path)
210
+ for (const f of files) {
211
+ if (bytes <= cap && free >= keepFree(spec)) break
212
+ if (!o.dry) rmSync(f.path, { force: true })
213
+ bytes -= f.size
214
+ free += f.size
215
+ out.freed.files++
216
+ out.freed.bytes += f.size
217
+ }
218
+ if (!o.dry) {
219
+ const now = o.now ?? Date.now()
220
+ const dir = join(spec.path, 'media')
221
+ if (existsSync(dir))
222
+ for (const d of readdirSync(dir, { withFileTypes: true, recursive: true }))
223
+ if (d.isFile() && d.name.endsWith('.part') && now - (statSync(join(d.parentPath, d.name), { throwIfNoEntry: false })?.mtimeMs ?? now) > PART_STALE_MS) rmSync(join(d.parentPath, d.name), { force: true })
224
+ used.set(spec.path, bytes)
225
+ }
226
+ return out
227
+ }
@@ -0,0 +1,279 @@
1
+ // a repo's scratch (`.shipkit/cache`, `.shipkit/tmp`) moved to the annex behind a symlink, and back (wiki
2
+ // tools/shipkit/annex.md, Scratch). Each refusal guards what an unplugged drive must never take: a db, a lock, a git
3
+ // worktree, what the backup holds, what the media store indexes, a file a process holds open. A move is a copy checked
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'
6
+ import { homedir } from 'node:os'
7
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'
8
+ import { machineGet, machineSet } from '../core/machine-db.ts'
9
+ import { openOf } from '../media-store/purge.ts'
10
+ import { driveFree, keepFree, presentAnnexes } from './annex.ts'
11
+
12
+ const GB = 1e9
13
+ /** room the Mac keeps beyond a folder brought back */
14
+ export const BACK_FREE_MIN = 10 * GB
15
+ const RECORDS = 'annex-offloads'
16
+
17
+ export type Offload = {
18
+ /** the repo root and the path in it, as the symlink sits */
19
+ repo: string
20
+ rel: string
21
+ /** where the content lives on the annex */
22
+ target: string
23
+ files: number
24
+ bytes: number
25
+ at: number
26
+ }
27
+
28
+ export const offloads = (): Offload[] => machineGet<Offload[]>(RECORDS) ?? []
29
+ const save = (list: Offload[]): void => {
30
+ if (!machineSet(RECORDS, list)) throw new Error('the machine db does not open: the offload is not recorded')
31
+ }
32
+
33
+ /** a name that marks a db or a lock: never on a drive that can be unplugged. LevelDB keeps `LOCK` and `MANIFEST-<n>`,
34
+ * LMDB `data.mdb` and `lock.mdb` */
35
+ export const DB_NAME = /(\.(sqlite3?|db)(-wal|-shm|-journal)?|\.lock|\.mdb)$|^(LOCK|MANIFEST-\d+|pb_data)$/i
36
+ /** a package manager's lockfile is a text file, never a lock: it moves */
37
+ const PACKAGE_LOCKS = new Set(['bun.lock', 'yarn.lock', 'Cargo.lock', 'poetry.lock', 'uv.lock', 'Gemfile.lock', 'composer.lock', 'flake.lock', 'Pipfile.lock', 'pdm.lock'])
38
+ /** a vendored package's own marker files (setuptools' `_vendor/.lock`) are files of the package, never a live lock */
39
+ const PACKAGE_DIRS = new Set(['site-packages', 'node_modules'])
40
+ const SQLITE_HEAD = 'SQLite format 3\0'
41
+
42
+ /** the db or lock `rel` names, by its name or, for a file, the SQLite header: an extension-less db (Chrome's `Cookies`) */
43
+ export function isDb(dir: string, rel: string, file: boolean): boolean {
44
+ const parts = rel.split('/')
45
+ const name = parts[parts.length - 1] ?? ''
46
+ if (parts.some((p) => p === 'pb_data')) return true
47
+ if (DB_NAME.test(name) && !PACKAGE_LOCKS.has(name) && !(name.endsWith('.lock') && parts.some((p) => PACKAGE_DIRS.has(p)))) return true
48
+ if (!file) return false
49
+ let fd = -1
50
+ try {
51
+ fd = openSync(join(dir, rel), 'r')
52
+ const head = Buffer.alloc(16)
53
+ return readSync(fd, head, 0, 16, 0) === 16 && head.toString('latin1') === SQLITE_HEAD
54
+ } catch {
55
+ return false
56
+ } finally {
57
+ if (fd >= 0) closeSync(fd)
58
+ }
59
+ }
60
+
61
+ /** every entry under `dir`, relative to it, by lstat: a link is an entry, never followed (a venv or a tree with a
62
+ * 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 }[] = []
65
+ const go = (abs: string, rel: string): void => {
66
+ for (const name of readdirSync(abs)) {
67
+ const p = join(abs, name)
68
+ const r = rel ? `${rel}/${name}` : name
69
+ const s = lstatSync(p)
70
+ out.push({ rel: r, dir: s.isDirectory(), file: s.isFile(), size: s.isFile() ? s.size : 0 })
71
+ if (s.isDirectory()) go(p, r)
72
+ }
73
+ }
74
+ go(dir, '')
75
+ return out
76
+ }
77
+
78
+ /** the files and bytes under `path`, links counted, never followed */
79
+ export function tally(path: string): { files: number; bytes: number } {
80
+ const s = lstatSync(path)
81
+ if (!s.isDirectory()) return { files: 1, bytes: s.isFile() ? s.size : 0 }
82
+ const all = entries(path).filter((e) => !e.dir)
83
+ return { files: all.length, bytes: all.reduce((n, e) => n + e.size, 0) }
84
+ }
85
+
86
+ const git = (root: string, args: string[]): { ok: boolean; out: string } => {
87
+ const r = Bun.spawnSync(['git', '-C', root, ...args], { stdout: 'pipe', stderr: 'pipe' })
88
+ return { ok: r.exitCode === 0, out: r.stdout.toString().trim() }
89
+ }
90
+
91
+ /** the folders whose content is scratch by the house's own rule: the backup denies them, a gate rebuilds them */
92
+ export const SCRATCH = ['.shipkit/cache', '.shipkit/tmp'] as const
93
+ export const inScratch = (rel: string): boolean => SCRATCH.some((d) => rel === d || rel.startsWith(`${d}/`))
94
+
95
+ /** the reason `rel` may not leave `root`, null when it may. Checked in this order: the place, git, the names inside,
96
+ * what the backup holds, what the media store indexes, what a process holds open */
97
+ export type Probe = {
98
+ /** the home folder the backup inventory reads (the real one by default) */
99
+ home?: string
100
+ /** the paths some process holds open (`lsof`, about 180 ms a call, by default) */
101
+ openOf?: (paths: readonly string[]) => Set<string>
102
+ }
103
+
104
+ export async function refusal(root: string, rel: string, o: Probe = {}): Promise<string | null> {
105
+ const path = join(root, rel)
106
+ if (isAbsolute(rel) || rel.startsWith('..') || rel === '' || rel === '.') return `${rel} is not inside the repo`
107
+ const s = lstatSync(path, { throwIfNoEntry: false })
108
+ if (!s) return `${rel} does not exist`
109
+ if (s.isSymbolicLink()) return `${rel} is a symlink already${offloads().some((o) => o.repo === root && o.rel === rel) ? ' (offloaded)' : ''}`
110
+ 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 }]
114
+ const base = s.isDirectory() ? path : dirname(path)
115
+ const names = list.map((e) => e.rel)
116
+ const gits = names.filter((n) => n.split('/').includes('.git'))
117
+ if (gits.length > 0) return `${rel} holds a git repo or worktree (${gits[0]}): its uncommitted work stays on the Mac`
118
+ const dbs = list.filter((e) => isDb(base, e.rel, e.file)).map((e) => e.rel)
119
+ 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`
123
+ const { mediaDb } = await import('../media-store/db.ts')
124
+ const rows = (mediaDb()?.query('select store, item, name from files where local = 1').all() ?? []) as { store: string; item: string; name: string }[]
125
+ const indexed = rows.map((r) => join(r.store, r.item, r.name)).find((p) => p === path || p.startsWith(`${path}/`))
126
+ if (indexed) return `the media store indexes ${relative(root, indexed)}: its purge moves media to the annex, never an offload`
127
+ const probe = o.openOf ?? openOf
128
+ const open = s.isDirectory() ? [...probe(names.map((n) => join(path, n)))] : [...probe([path])]
129
+ if (open.length > 0) return `a process holds ${open[0]} open${open.length > 1 ? ` (and ${open.length - 1} more)` : ''}`
130
+ return null
131
+ }
132
+
133
+ export interface Moved {
134
+ rel: string
135
+ target: string
136
+ files: number
137
+ bytes: number
138
+ }
139
+
140
+ /** `rel` of the repo `root` to the first annex present with room, a symlink in its place. The order: copy to a
141
+ * `.part`, count it, rename it to the target, record, move the Mac's folder aside, link, count the aside again (a
142
+ * write during the copy), delete the aside. Any check that fails puts the Mac's folder back and drops the record */
143
+ export async function offload(root: string, rel: string, o: Probe & { dry?: boolean } = {}): Promise<Moved> {
144
+ const why = await refusal(root, rel, o)
145
+ if (why) throw new Error(why)
146
+ const src = join(root, rel)
147
+ const t = tally(src)
148
+ const present = await presentAnnexes()
149
+ if (present.length === 0) throw new Error('no annex is present: plug the drive in, or sk annex init <path>')
150
+ const annex = present.find((a) => driveFree(a.path) - t.bytes >= keepFree(a))
151
+ if (!annex) throw new Error(`no annex present keeps its free space with ${rel} (${(t.bytes / GB).toFixed(1)} GB)`)
152
+ const target = join(annex.path, 'offload', basename(root), rel)
153
+ if (existsSync(target)) throw new Error(`${target} exists already: an earlier offload, look before you move`)
154
+ if (o.dry) return { rel, target, ...t }
155
+ const part = `${target}.${process.pid}.part`
156
+ mkdirSync(dirname(target), { recursive: true })
157
+ try {
158
+ const cp = Bun.spawnSync(['cp', '-Rp', src, part], { stdout: 'pipe', stderr: 'pipe' })
159
+ if (cp.exitCode !== 0) throw new Error(`cp: ${cp.stderr.toString().trim()}`)
160
+ const got = tally(part)
161
+ 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}`)
162
+ renameSync(part, target)
163
+ } catch (e) {
164
+ rmSync(part, { recursive: true, force: true })
165
+ throw new Error(`${rel} not offloaded: ${(e as Error).message}`)
166
+ }
167
+ const others = offloads().filter((x) => !(x.repo === root && x.rel === rel))
168
+ const undo = (aside: string | null, why: string): never => {
169
+ if (aside) {
170
+ if (lstatSync(src, { throwIfNoEntry: false })?.isSymbolicLink()) rmSync(src)
171
+ renameSync(aside, src)
172
+ }
173
+ save(others)
174
+ rmSync(target, { recursive: true, force: true })
175
+ throw new Error(`${rel} not offloaded, the folder stays on the Mac: ${why}`)
176
+ }
177
+ try {
178
+ save([...others, { repo: root, rel, target, ...t, at: Date.now() }])
179
+ } catch (e) {
180
+ rmSync(target, { recursive: true, force: true })
181
+ throw e
182
+ }
183
+ const aside = `${src}.${process.pid}.offloading`
184
+ try {
185
+ renameSync(src, aside)
186
+ } catch (e) {
187
+ return undo(null, (e as Error).message)
188
+ }
189
+ try {
190
+ symlinkSync(target, src)
191
+ } catch (e) {
192
+ return undo(aside, `the link was not made: ${(e as Error).message}`)
193
+ }
194
+ 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)`)
196
+ rmSync(aside, { recursive: true, force: true })
197
+ return { rel, target, ...t }
198
+ }
199
+
200
+ /** an offloaded `rel` of `root` back on the Mac's disk, its link replaced by the folder */
201
+ export function back(root: string, rel: string): Moved {
202
+ const rec = offloads().find((x) => x.repo === root && x.rel === rel)
203
+ if (!rec) throw new Error(`${rel} is not offloaded (sk annex lists what is)`)
204
+ const src = join(root, rel)
205
+ 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
+ if (!existsSync(rec.target)) throw new Error(`${rec.target} is missing: plug the drive in`)
207
+ const t = tally(rec.target)
208
+ if (driveFree(root) - t.bytes < BACK_FREE_MIN) throw new Error(`the Mac's disk would keep under ${BACK_FREE_MIN / GB} GB free with ${rel} (${(t.bytes / GB).toFixed(1)} GB)`)
209
+ const part = `${src}.${process.pid}.back`
210
+ const cp = Bun.spawnSync(['cp', '-Rp', rec.target, part], { stdout: 'pipe', stderr: 'pipe' })
211
+ const got = cp.exitCode === 0 ? tally(part) : null
212
+ if (!got || got.files !== t.files || got.bytes !== t.bytes) {
213
+ rmSync(part, { recursive: true, force: true })
214
+ 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
+ }
216
+ rmSync(src)
217
+ renameSync(part, src)
218
+ save(offloads().filter((x) => x !== rec && !(x.repo === root && x.rel === rel)))
219
+ rmSync(rec.target, { recursive: true, force: true })
220
+ return { rel, target: rec.target, ...t }
221
+ }
222
+
223
+ /** 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;
225
+ * - a dangling link (the drive gone for good): the link and the record go, nothing else is reachable;
226
+ * - 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 } {
229
+ const rec = offloads().find((x) => x.repo === root && x.rel === rel)
230
+ if (!rec) throw new Error(`${rel} is not offloaded (sk annex lists what is)`)
231
+ const at = join(root, rel)
232
+ const l = lstatSync(at, { throwIfNoEntry: false })
233
+ let did: string
234
+ if (l?.isSymbolicLink()) {
235
+ if (existsSync(at)) throw new Error(`${rel} is still the link to ${rec.target}: sk annex back brings it home`)
236
+ rmSync(at)
237
+ did = `the dangling link went; ${rec.target} is unreachable`
238
+ } else if (l) {
239
+ rmSync(rec.target, { recursive: true, force: true })
240
+ did = `the Mac folder stays, ${rec.target} was deleted`
241
+ } else {
242
+ 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
+ did = 'nothing was left on either side'
244
+ }
245
+ save(offloads().filter((x) => !(x.repo === root && x.rel === rel)))
246
+ return { rec, did }
247
+ }
248
+
249
+ export type Drift = { kind: 'dangling' | 'split' | 'gone' | 'orphan'; path: string; why: string; fix: string }
250
+
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 */
254
+ export async function drift(root: string): Promise<Drift[]> {
255
+ const out: Drift[] = []
256
+ const mine = offloads().filter((x) => resolve(x.repo) === resolve(root))
257
+ for (const x of mine) {
258
+ const at = join(x.repo, x.rel)
259
+ 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` })
263
+ 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
+ else out.push({ kind: 'gone', path: at, why: `the link and ${x.target} are both gone`, fix: `sk annex forget ${at}` })
265
+ }
266
+ const targets = offloads().map((x) => x.target)
267
+ const reached = (p: string): boolean => targets.some((t) => p === t || p.startsWith(`${t}/`) || t.startsWith(`${p}/`))
268
+ for (const a of await presentAnnexes()) {
269
+ const dir = join(a.path, 'offload', basename(root))
270
+ if (!existsSync(dir)) continue
271
+ for (const e of entries(dir)) {
272
+ const p = join(dir, e.rel)
273
+ if (e.dir || reached(p) || /\.\d+\.part(\/|$)/.test(p)) continue
274
+ out.push({ kind: 'orphan', path: p, why: 'on the annex, and no recorded offload of any repo reaches it', fix: `nothing on the Mac reaches it: delete ${p}` })
275
+ break
276
+ }
277
+ }
278
+ return out
279
+ }