rvlib-shipkit 2.12.0 → 2.13.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 (290) hide show
  1. package/CHANGELOG.md +48 -13
  2. package/README.md +1 -1
  3. package/package.json +4 -2
  4. package/src/agent-time/store.ts +2 -2
  5. package/src/check.ts +1 -1
  6. package/src/checks/SK001-package-json-shape.check.ts +4 -0
  7. package/src/checks/SK003-claude-md-shape.check.ts +1 -1
  8. package/src/checks/SK004-gitignore-policy.check.ts +27 -2
  9. package/src/checks/SK005-rvlib-versions.check.ts +1 -1
  10. package/src/checks/SK008-reviewer-agent.check.ts +2 -2
  11. package/src/checks/SK012-config-barrel-import.check.ts +1 -1
  12. package/src/checks/SK015-nested-repo.check.ts +1 -1
  13. package/src/checks/SK035-public-clean.check.ts +46 -0
  14. package/src/checks/SK036-draft-media-size.check.ts +28 -0
  15. package/src/cli/cmd_Backup.ts +152 -0
  16. package/src/cli/cmd_Ci.ts +8 -11
  17. package/src/cli/cmd_Drill.ts +145 -0
  18. package/src/cli/cmd_Home.ts +50 -3
  19. package/src/cli/cmd_Media.ts +7 -5
  20. package/src/cli/cmd_Review.ts +4 -2
  21. package/src/cli/cmd_Shot.ts +5 -2
  22. package/src/cli/cmd_Smoke.ts +4 -1
  23. package/src/cli/cmd_Social.ts +226 -0
  24. package/src/cli/cmd_Start.ts +1 -1
  25. package/src/cli/cmd_Time.ts +1 -1
  26. package/src/cli/cmd_Trailer.ts +5 -2
  27. package/src/cli/cmd_Veille.ts +173 -0
  28. package/src/cli/family-pages.ts +3 -0
  29. package/src/cli/registry.ts +13 -2
  30. package/src/cli.ts +5 -2
  31. package/src/collections/actions.ts +1 -49
  32. package/src/collections/checks.ts +2 -1
  33. package/src/collections/collection-types.ts +11 -2
  34. package/src/collections/providers.ts +4 -4
  35. package/src/collections/review.ts +2 -1
  36. package/src/collections/tests.ts +19 -8
  37. package/src/contracts/apply-contracts.ts +1 -3
  38. package/src/contracts/contract-manifests.ts +2 -3
  39. package/src/contracts/contract-types.ts +0 -1
  40. package/src/contracts/contracts-engine.ts +0 -3
  41. package/src/core/app-icon.ts +9 -3
  42. package/src/core/bun-builtins.ts +2 -2
  43. package/src/core/discover-checks.ts +37 -5
  44. package/src/core/fix-scope.ts +4 -2
  45. package/src/core/floor-resolve.ts +68 -48
  46. package/src/core/floor.ts +9 -0
  47. package/src/core/git-root.ts +24 -0
  48. package/src/core/last-good.ts +3 -1
  49. package/src/core/layout.ts +8 -0
  50. package/src/core/log-stamp.ts +36 -0
  51. package/src/core/loop-watch.ts +93 -0
  52. package/src/core/machine-link.ts +134 -0
  53. package/src/core/memory-watch.ts +41 -0
  54. package/src/core/one-way-in-policy.ts +27 -19
  55. package/src/core/run-ci.ts +6 -8
  56. package/src/core/run-fixers.ts +9 -9
  57. package/src/core/slots.ts +21 -0
  58. package/src/core/tree-rev.ts +60 -0
  59. package/src/core/unit-files.ts +42 -0
  60. package/src/drill/render.ts +140 -0
  61. package/src/drill/run.ts +269 -0
  62. package/src/fleet/scan-fleet.ts +6 -5
  63. package/src/home/daemon-jobs.ts +201 -0
  64. package/src/home/global-context.ts +34 -1
  65. package/src/home/home-routes.ts +22 -15
  66. package/src/home/hubs.ts +10 -3
  67. package/src/home/inbox-shape.ts +53 -4
  68. package/src/home/inbox.ts +16 -1
  69. package/src/home/lib-watch.ts +10 -3
  70. package/src/home/machine-stores.ts +15 -29
  71. package/src/home/run-daemon.ts +15 -18
  72. package/src/home/run-pm.ts +2 -0
  73. package/src/home/serve-daemon.ts +4 -3
  74. package/src/home/serve-web.ts +104 -1
  75. package/src/hooks/commit-message.ts +28 -19
  76. package/src/hooks/leak-guard.ts +10 -3
  77. package/src/hooks/run-hooks.ts +2 -6
  78. package/src/identities/identities.ts +334 -0
  79. package/src/identities/machine-route.ts +126 -0
  80. package/src/identities/machine.ts +62 -0
  81. package/src/init-repo.ts +1 -1
  82. package/src/ledger/check-stats.ts +10 -9
  83. package/src/ledger/gate-checks.ts +32 -1
  84. package/src/ledger/record-kept.ts +112 -0
  85. package/src/ledger/repo-view.ts +10 -0
  86. package/src/ledger/run-log.ts +17 -12
  87. package/src/ledger/run-timeline.ts +8 -4
  88. package/src/ledger/store.ts +7 -0
  89. package/src/ledger/suite-log.ts +17 -13
  90. package/src/media-kinds.ts +2 -1
  91. package/src/media-store/backup/daemon.ts +73 -0
  92. package/src/media-store/backup/keys.ts +25 -0
  93. package/src/media-store/backup/manifest.ts +193 -0
  94. package/src/media-store/backup/restore.ts +192 -0
  95. package/src/media-store/backup/run.ts +278 -0
  96. package/src/media-store/backup/secret.ts +86 -0
  97. package/src/media-store/backup/snapshot.ts +64 -0
  98. package/src/media-store/backup/sources.ts +199 -0
  99. package/src/media-store/daemon.ts +56 -70
  100. package/src/media-store/put.ts +4 -2
  101. package/src/media-store/space.ts +23 -4
  102. package/src/pages/forward.ts +35 -0
  103. package/src/pages/frame-client.ts +118 -0
  104. package/src/pages/routes.ts +29 -0
  105. package/src/pages/unit.ts +92 -0
  106. package/src/plan/planner.ts +12 -0
  107. package/src/plan/repo-source.ts +19 -5
  108. package/src/reflect/transcript.ts +35 -10
  109. package/src/release/public-clean.ts +301 -0
  110. package/src/release/published-here.ts +22 -0
  111. package/src/release/run-bump.ts +2 -1
  112. package/src/release/run-release.ts +4 -1
  113. package/src/repo-config.ts +53 -2
  114. package/src/review/http.ts +16 -2
  115. package/src/review/model.ts +15 -4
  116. package/src/review/notes.ts +77 -0
  117. package/src/review/project.ts +6 -38
  118. package/src/review/routes.ts +4 -12
  119. package/src/review/store.ts +41 -1
  120. package/src/review/trailer-media.ts +7 -4
  121. package/src/review/trailer-shots.ts +21 -4
  122. package/src/review/unit.ts +1 -1
  123. package/src/scaffold/files/agent-handoff.md +3 -0
  124. package/src/scaffold/files/agent-index.md +4 -12
  125. package/src/scaffold/project-scaffold.ts +5 -4
  126. package/src/serve/embed.ts +1 -1
  127. package/src/serve/hub-app/col-card.tsx +3 -17
  128. package/src/serve/hub-app/col-tables-view.tsx +2 -1
  129. package/src/serve/hub-app/cols-svc.ts +0 -13
  130. package/src/serve/hub-app/dock-st.ts +4 -2
  131. package/src/serve/hub-app/dock-view.tsx +2 -0
  132. package/src/serve/hub-app/frames-st.ts +35 -0
  133. package/src/serve/hub-app/hash-route.ts +64 -1
  134. package/src/serve/hub-app/home-st.ts +31 -7
  135. package/src/serve/hub-app/home-strip.css +9 -1
  136. package/src/serve/hub-app/home-strip.tsx +7 -6
  137. package/src/serve/hub-app/home.html +5 -0
  138. package/src/serve/hub-app/hub-app.tsx +49 -5
  139. package/src/serve/hub-app/hub.css +29 -11
  140. package/src/serve/hub-app/icons.tsx +16 -1
  141. package/src/serve/hub-app/identities-st.ts +210 -0
  142. package/src/serve/hub-app/identities-view.tsx +352 -0
  143. package/src/serve/hub-app/identities.css +48 -0
  144. package/src/serve/hub-app/identity-address.ts +52 -0
  145. package/src/serve/hub-app/inbox-st.ts +59 -6
  146. package/src/serve/hub-app/inbox-view.tsx +48 -6
  147. package/src/serve/hub-app/inbox.css +12 -1
  148. package/src/serve/hub-app/index.html +3 -0
  149. package/src/serve/hub-app/keys.ts +10 -2
  150. package/src/serve/hub-app/list-walk.ts +89 -0
  151. package/src/serve/hub-app/machine-st.ts +12 -0
  152. package/src/serve/hub-app/media-view.tsx +2 -1
  153. package/src/serve/hub-app/pages-frames.tsx +134 -0
  154. package/src/serve/hub-app/pages-svc.ts +111 -0
  155. package/src/serve/hub-app/palette-st.ts +18 -3
  156. package/src/serve/hub-app/palette-view.tsx +9 -2
  157. package/src/serve/hub-app/planned-view.tsx +2 -1
  158. package/src/serve/hub-app/project-list.css +18 -14
  159. package/src/serve/hub-app/project-list.tsx +88 -49
  160. package/src/serve/hub-app/projects-svc.ts +33 -3
  161. package/src/serve/hub-app/repo-sections.ts +19 -2
  162. package/src/serve/hub-app/repo-st.ts +75 -19
  163. package/src/serve/hub-app/review/review-cells.tsx +3 -3
  164. package/src/serve/hub-app/review/review-kit.ts +30 -7
  165. package/src/serve/hub-app/review/review-page.tsx +1 -1
  166. package/src/serve/hub-app/review/review-st.ts +19 -8
  167. package/src/serve/hub-app/review/review-thread.tsx +11 -9
  168. package/src/serve/hub-app/review/review-views.tsx +84 -19
  169. package/src/serve/hub-app/review/thread-st.ts +1 -10
  170. package/src/serve/hub-app/review/trailer-page.tsx +2 -1
  171. package/src/serve/hub-app/review.css +17 -8
  172. package/src/serve/hub-app/site/site-part.tsx +173 -0
  173. package/src/serve/hub-app/site/site-st.ts +157 -0
  174. package/src/serve/hub-app/site.css +35 -0
  175. package/src/serve/hub-app/social/calendar.tsx +182 -0
  176. package/src/serve/hub-app/social/comms-page.tsx +306 -0
  177. package/src/serve/hub-app/social/kit.tsx +244 -0
  178. package/src/serve/hub-app/social/post-card.tsx +456 -0
  179. package/src/serve/hub-app/social/problems.tsx +60 -0
  180. package/src/serve/hub-app/social/social-model.ts +154 -0
  181. package/src/serve/hub-app/social/social-page.tsx +674 -0
  182. package/src/serve/hub-app/social/social-st.ts +986 -0
  183. package/src/serve/hub-app/social.css +289 -0
  184. package/src/serve/hub-app/stores/stores-page.tsx +311 -0
  185. package/src/serve/hub-app/stores/stores-st.ts +286 -0
  186. package/src/serve/hub-app/stores.css +54 -0
  187. package/src/serve/hub-app/timeline-geometry.ts +1 -1
  188. package/src/serve/hub-app/timeline-view.tsx +3 -2
  189. package/src/serve/hub-app/tree-build.ts +6 -0
  190. package/src/serve/hub-app/tree-row.tsx +27 -4
  191. package/src/serve/hub-app/tree-svc.ts +18 -49
  192. package/src/serve/hub-app/veille/veille-page.tsx +514 -0
  193. package/src/serve/hub-app/veille/veille-st.ts +443 -0
  194. package/src/serve/hub-app/veille.css +84 -0
  195. package/src/serve/hub-runtime.ts +14 -9
  196. package/src/serve/project-gutter-route.ts +44 -12
  197. package/src/serve/run-lanes.ts +7 -4
  198. package/src/serve/same-origin.ts +1 -1
  199. package/src/serve/serve-hub.ts +20 -12
  200. package/src/serve/tracked-watch.ts +24 -3
  201. package/src/serve/warm-cell.ts +5 -1
  202. package/src/shipkit-files.ts +15 -4
  203. package/src/shipkit.ts +0 -1
  204. package/src/shot/box.ts +162 -0
  205. package/src/shot/browser-slot.ts +62 -0
  206. package/src/shot/client.ts +43 -7
  207. package/src/shot/clip-encoder.ts +93 -12
  208. package/src/shot/film-box.ts +188 -0
  209. package/src/shot/shooter.ts +50 -15
  210. package/src/shot/shot-ask.ts +10 -2
  211. package/src/shot/stepped-clip.ts +5 -4
  212. package/src/site/desk.ts +242 -0
  213. package/src/site/routes.ts +66 -0
  214. package/src/site/unit.ts +62 -0
  215. package/src/social/brands.ts +22 -0
  216. package/src/social/compose.ts +97 -0
  217. package/src/social/desk-index.ts +123 -0
  218. package/src/social/desk-wire.ts +64 -0
  219. package/src/social/drafts.ts +183 -0
  220. package/src/social/house.ts +24 -0
  221. package/src/social/load.ts +319 -0
  222. package/src/social/md.ts +70 -0
  223. package/src/social/media-facts.ts +53 -0
  224. package/src/social/media-kind.ts +189 -0
  225. package/src/social/media-limit.ts +42 -0
  226. package/src/social/media-of.ts +30 -0
  227. package/src/social/migrate.ts +123 -0
  228. package/src/social/open.ts +17 -0
  229. package/src/social/post-url.ts +158 -0
  230. package/src/social/presence.ts +332 -0
  231. package/src/social/public-read.ts +53 -0
  232. package/src/social/publish/bluesky.ts +168 -0
  233. package/src/social/publish/discord.ts +76 -0
  234. package/src/social/publish/index.ts +24 -0
  235. package/src/social/publish/secret.ts +13 -0
  236. package/src/social/push.ts +31 -0
  237. package/src/social/richtext.ts +37 -0
  238. package/src/social/routes.ts +180 -0
  239. package/src/social/stats.ts +134 -0
  240. package/src/social/text.ts +267 -0
  241. package/src/social/tracker-route.ts +39 -0
  242. package/src/social/tracker.ts +255 -0
  243. package/src/social/unit.ts +53 -0
  244. package/src/social/writes.ts +130 -0
  245. package/src/start-repo.ts +14 -9
  246. package/src/stores/collection.ts +27 -0
  247. package/src/stores/desk.ts +336 -0
  248. package/src/stores/model.ts +187 -0
  249. package/src/stores/routes.ts +126 -0
  250. package/src/stores/unit.ts +57 -0
  251. package/src/suite/calibrate.ts +127 -0
  252. package/src/suite/core-counters.ts +91 -0
  253. package/src/suite/judge-suites.ts +94 -34
  254. package/src/suite/suite-cli.ts +44 -10
  255. package/src/suite/suite-cpu-preload.ts +34 -9
  256. package/src/trailer/adapter.ts +4 -0
  257. package/src/trailer/build.ts +42 -11
  258. package/src/trailer/ffmpeg.ts +11 -0
  259. package/src/trailer/footage.ts +30 -13
  260. package/src/trailer/grammar.ts +18 -2
  261. package/src/trailer/graph.ts +28 -6
  262. package/src/trailer/passage.ts +17 -5
  263. package/src/trailer/plan.ts +74 -3
  264. package/src/trailer/stitch.ts +67 -26
  265. package/src/trailer/url.ts +1 -1
  266. package/src/trailer/versions.ts +24 -0
  267. package/src/ts/gate-typecheck.ts +32 -0
  268. package/src/ts/typecheck-cli.ts +9 -11
  269. package/src/tui/tui-app.tsx +0 -1
  270. package/src/veille/asks.ts +155 -0
  271. package/src/veille/auto.ts +31 -0
  272. package/src/veille/batch.ts +27 -0
  273. package/src/veille/chrome.ts +127 -0
  274. package/src/veille/collection.ts +28 -0
  275. package/src/veille/desk.ts +242 -0
  276. package/src/veille/identity.ts +80 -0
  277. package/src/veille/import.ts +68 -0
  278. package/src/veille/log.ts +183 -0
  279. package/src/veille/platforms.ts +118 -0
  280. package/src/veille/reads.ts +66 -0
  281. package/src/veille/replied.ts +110 -0
  282. package/src/veille/routes.ts +185 -0
  283. package/src/veille/service.ts +81 -0
  284. package/src/veille/watch.ts +116 -0
  285. package/src/veille/worth.ts +46 -0
  286. package/src/wiki/scan-md.ts +18 -0
  287. package/src/collections/posts.ts +0 -142
  288. package/src/contracts/manifests/social.contract.ts +0 -20
  289. package/src/scaffold/files/agent-coding.md +0 -35
  290. package/src/ts/typecheck-cache.ts +0 -11
@@ -0,0 +1,73 @@
1
+ // the daemon's backup job (wiki build/shipkit/media-store.md, Backup, The daemon): one look, in a child process the
2
+ // daemon starts every 2 min (home/daemon-jobs.ts), never on its loop. A cheap stamp of the sources (paths, sizes,
3
+ // times, no hashing); once it moved and then held still for one look, a run, at most one each 10 min; a run every 6 h
4
+ // whatever moved, which takes the sqlite snapshots. Each failure is one line in the log
5
+ import { machineGet, machineSet } from '../../core/machine-db.ts'
6
+ import type { Space } from '../space.ts'
7
+ import { backupRun, lastRun } from './run.ts'
8
+ import { collect, localFiles, stampOfSources } from './sources.ts'
9
+
10
+ export const BACKUP_EVERY_MS = 120_000
11
+ const FLOOR_MS = 10 * 60_000
12
+ const EVERY_MS = 6 * 3600_000
13
+ /** the git walk for `*.local.*` files, kept this long per repo */
14
+ const LOCALS_MS = 30 * 60_000
15
+
16
+ /** the stamp the last look saw and the one the last good run sent; `backup-` rows are left out of the snapshot */
17
+ const STAMPS = 'backup-stamps'
18
+ const LOCALS = 'backup-locals'
19
+ const NO_SPACE = 'backup-no-space'
20
+
21
+ type Stamps = { seen: string; ran: string }
22
+ type Locals = Record<string, { at: number; files: string[] }>
23
+
24
+ export interface BackupTick {
25
+ home: string
26
+ repos: string[]
27
+ space: () => Promise<{ space: Space | null; why: string }>
28
+ print: (l: string) => void
29
+ printErr: (l: string) => void
30
+ now?: () => number
31
+ }
32
+
33
+ /** one look of the daemon's backup job, in its child process: a run when it is due, else nothing. What a look
34
+ * remembers lives in the machine db, so a daemon restart never makes a run of its own */
35
+ export async function backupTick(o: BackupTick): Promise<void> {
36
+ const now = o.now ?? Date.now
37
+ const locals: Locals = machineGet<Locals>(LOCALS) ?? {}
38
+ let walked = false
39
+ const cachedLocals = async (repo: string): Promise<string[]> => {
40
+ const held = locals[repo]
41
+ if (held && now() - held.at < LOCALS_MS) return held.files
42
+ const files = await localFiles(repo)
43
+ locals[repo] = { at: now(), files }
44
+ walked = true
45
+ return files
46
+ }
47
+ try {
48
+ const stamp = stampOfSources(await collect({ home: o.home, repos: o.repos, locals: cachedLocals }))
49
+ if (walked) machineSet(LOCALS, locals)
50
+ const held: Stamps = machineGet<Stamps>(STAMPS) ?? { seen: '', ran: '' }
51
+ const last = lastRun()
52
+ const since = last ? now() - Date.parse(last.at) : Infinity
53
+ const due = since >= EVERY_MS || (stamp !== held.ran && stamp === held.seen && since >= FLOOR_MS)
54
+ machineSet(STAMPS, { ...held, seen: stamp } satisfies Stamps)
55
+ if (!due) return
56
+ const { space, why } = await o.space()
57
+ // said once per reason: a look is a child of its own
58
+ if (!space) {
59
+ if (machineGet<string>(NO_SPACE) !== why) o.printErr(`WARN backup: nothing goes up: ${why}`)
60
+ machineSet(NO_SPACE, why)
61
+ return
62
+ }
63
+ machineSet(NO_SPACE, '')
64
+ const r = await backupRun(space, { home: o.home, repos: o.repos, locals: cachedLocals })
65
+ if (r.failed.length === 0) machineSet(STAMPS, { seen: stamp, ran: stamp } satisfies Stamps)
66
+ if (r.failed.length > 0) o.printErr(`WARN backup: ${r.failed.length} objects did not go up, no manifest written; first: ${r.failed[0]?.key}: ${r.failed[0]?.error}`)
67
+ else if (r.manifest) o.print(`ok: backup: ${r.files} files, ${r.sent} objects up (${(r.sentBytes / 1e6).toFixed(1)} MB), ${r.refused.length} refused, manifest ${r.manifest}`)
68
+ } catch (e) {
69
+ // a hand run holds the lock: the next look tries again, and says so (a lock that never goes stops every backup)
70
+ const msg = (e as Error).message
71
+ o.printErr(/^another backup runs/.test(msg) ? `note: backup: not now, ${msg}` : `WARN backup: the run broke: ${msg}`)
72
+ }
73
+ }
@@ -0,0 +1,25 @@
1
+ // where the backup keeps its objects in the private Space (wiki build/shipkit/media-store.md, Backup): a file's bytes
2
+ // under `backup/<sha256>.<ext>`, a sqlite snapshot gzipped under `backup/<sha256 of the gz>.gz`, one manifest a run
3
+ // under `backup/runs/<time>-<digest>.json.gz`. Nothing under the prefix is ever deleted
4
+ export const BACKUP_LABEL = 'backup'
5
+ export const RUNS_PREFIX = `${BACKUP_LABEL}/runs/`
6
+
7
+ /** a time as the run keys write it: `20261104T135000Z`, sorted as text */
8
+ export const stampOf = (d: Date): string => d.toISOString().replace(/\.\d{3}Z$/, 'Z').replace(/[-:]/g, '')
9
+
10
+ export const runKey = (at: Date, digest: string): string => `${RUNS_PREFIX}${stampOf(at)}-${digest.slice(0, 12)}.json.gz`
11
+
12
+ /** the time a run key names, null for a key that is no run */
13
+ export function timeOfRun(key: string): Date | null {
14
+ const m = /^backup\/runs\/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z-[0-9a-f]{12}\.json\.gz$/.exec(key)
15
+ return m ? new Date(`${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}Z`) : null
16
+ }
17
+
18
+ /** a time a person types: ISO (`2026-11-04T13:50`, `2026-11-04`) or a run stamp (`20261104T135000Z`) */
19
+ export function parseAt(text: string): Date {
20
+ const t = text.trim()
21
+ const s = /^(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})Z?)?$/.exec(t)
22
+ const d = s ? new Date(`${s[1]}-${s[2]}-${s[3]}T${s[4] ?? '23'}:${s[5] ?? '59'}:${s[6] ?? '59'}Z`) : new Date(/^\d{4}-\d{2}-\d{2}$/.test(t) ? `${t}T23:59:59Z` : t)
23
+ if (Number.isNaN(d.getTime())) throw new Error(`--at ${text}: a time like 2026-11-04T13:50Z, 2026-11-04 or 20261104T135000Z`)
24
+ return d
25
+ }
@@ -0,0 +1,193 @@
1
+ // one backup run as a record (wiki build/shipkit/media-store.md, Backup, In the Space): every file the machine held,
2
+ // its sha, size, time and the key its bytes are under, and every file refused with the reason. A run of version 2 keeps
3
+ // its files in PARTS, one a group (the home, the memories, a house repo; a big group cut in buckets by folder), each
4
+ // part content addressed: a run that changes one file writes that file's part and the run's list of parts. A run of
5
+ // version 1 holds every file in one object, still read. A restore reads only this and the keys
6
+ import { rmSync } from 'node:fs'
7
+ import { gunzipSync, gzipSync } from 'node:zlib'
8
+ import { dirname, join } from 'node:path'
9
+ import { BACKUP_LABEL, RUNS_PREFIX, timeOfRun } from './keys.ts'
10
+ import type { Space } from '../space.ts'
11
+ import type { SqliteCut } from './snapshot.ts'
12
+
13
+ export interface Entry {
14
+ /** under the home folder */
15
+ path: string
16
+ /** the bytes a restore writes back (a sqlite: its snapshot's) */
17
+ sha: string
18
+ size: number
19
+ /** the live file's time; 0 for a snapshot, a new file each run */
20
+ mtime: number
21
+ key: string
22
+ /** a sqlite: the tables kept and their rows; its object is the snapshot gzipped */
23
+ sqlite?: SqliteCut & { rows: Record<string, number> }
24
+ }
25
+
26
+ export interface Refused {
27
+ path: string
28
+ why: string
29
+ }
30
+
31
+ /** a run as a restore reads it, whatever version wrote it */
32
+ export interface Manifest {
33
+ v: 1 | 2
34
+ at: string
35
+ host: string
36
+ home: string
37
+ /** the sha of every path and sha, and every refused path: two runs of one state have one digest */
38
+ digest: string
39
+ files: Entry[]
40
+ refused: Refused[]
41
+ }
42
+
43
+ /** one part of a run of version 2: its key is the sha of its json, so an unchanged part is the same object */
44
+ export interface PartRef {
45
+ name: string
46
+ key: string
47
+ files: number
48
+ bytes: number
49
+ }
50
+
51
+ interface RunV2 {
52
+ v: 2
53
+ at: string
54
+ host: string
55
+ home: string
56
+ digest: string
57
+ parts: PartRef[]
58
+ refused: Refused[]
59
+ }
60
+
61
+ interface PartV2 {
62
+ v: 2
63
+ name: string
64
+ files: Entry[]
65
+ }
66
+
67
+ export const PARTS_PREFIX = `${BACKUP_LABEL}/parts/`
68
+
69
+ export function digestOf(files: readonly Pick<Entry, 'path' | 'sha'>[], refused: readonly Refused[]): string {
70
+ const h = new Bun.CryptoHasher('sha256')
71
+ for (const f of [...files].sort((a, b) => (a.path < b.path ? -1 : 1))) h.update(`${f.path}\0${f.sha}\n`)
72
+ for (const r of [...refused].sort((a, b) => (a.path < b.path ? -1 : 1))) h.update(`refused\0${r.path}\n`)
73
+ return h.digest('hex')
74
+ }
75
+
76
+ const sha256 = (b: Uint8Array | string): string => new Bun.CryptoHasher('sha256').update(b).digest('hex')
77
+ const gz = (text: string): Uint8Array => new Uint8Array(gzipSync(Buffer.from(text)))
78
+
79
+ /** a group with more files than this is cut in buckets, so one change rewrites a part of about BUCKET files */
80
+ const SPLIT_OVER = 256
81
+ const BUCKET = 128
82
+
83
+ /** the group a file's part belongs to: the memories, the house repo it sits in, else the home */
84
+ export function groupOf(path: string, repos: readonly string[]): string {
85
+ if (/^\.claude[^/]*\/projects\//.test(path)) return 'memories'
86
+ return repos.find((r) => path.startsWith(`${r}/`)) ?? 'home'
87
+ }
88
+
89
+ /** the parts of a run: each group whole, or cut in a power of two of buckets by the hash of a file's folder (the files
90
+ * of one card or one folder change together, and stay in one part) */
91
+ export function partsOf(files: readonly Entry[], repos: readonly string[]): { name: string; files: Entry[] }[] {
92
+ const groups = new Map<string, Entry[]>()
93
+ for (const f of files) {
94
+ const g = groupOf(f.path, repos)
95
+ const list = groups.get(g)
96
+ if (list) list.push(f)
97
+ else groups.set(g, [f])
98
+ }
99
+ const out: { name: string; files: Entry[] }[] = []
100
+ for (const [g, list] of [...groups.entries()].sort((a, b) => (a[0] < b[0] ? -1 : 1))) {
101
+ if (list.length <= SPLIT_OVER) {
102
+ out.push({ name: g, files: list })
103
+ continue
104
+ }
105
+ const n = 2 ** Math.ceil(Math.log2(list.length / BUCKET))
106
+ const buckets = new Map<number, Entry[]>()
107
+ for (const f of list) {
108
+ const b = Number.parseInt(sha256(dirname(f.path)).slice(0, 8), 16) % n
109
+ const l = buckets.get(b)
110
+ if (l) l.push(f)
111
+ else buckets.set(b, [f])
112
+ }
113
+ for (const [b, l] of [...buckets.entries()].sort((x, y) => x[0] - y[0])) out.push({ name: `${g}#${b}/${n}`, files: l })
114
+ }
115
+ return out
116
+ }
117
+
118
+ /** a run of version 2: its parts, each with its key and bytes, and the run's own bytes */
119
+ export function encodeRun(m: Omit<Manifest, 'v'>, repos: readonly string[]): { run: Uint8Array; parts: { ref: PartRef; bytes: Uint8Array }[] } {
120
+ const parts = partsOf(m.files, repos).map((p) => {
121
+ const json = JSON.stringify({ v: 2, name: p.name, files: p.files } satisfies PartV2)
122
+ return { ref: { name: p.name, key: `${PARTS_PREFIX}${sha256(json)}.json.gz`, files: p.files.length, bytes: p.files.reduce((n, f) => n + f.size, 0) }, bytes: gz(json) }
123
+ })
124
+ const run: RunV2 = { v: 2, at: m.at, host: m.host, home: m.home, digest: m.digest, parts: parts.map((p) => p.ref), refused: m.refused }
125
+ return { run: gz(JSON.stringify(run)), parts }
126
+ }
127
+
128
+ /** a run of version 1, every file in one object: the form the first runs wrote */
129
+ export const encodeManifestV1 = (m: Omit<Manifest, 'v'>): Uint8Array => gz(JSON.stringify({ ...m, v: 1 }))
130
+
131
+ /** every run the Space holds, oldest first */
132
+ export async function runsOf(space: Space): Promise<{ key: string; at: Date; size: number }[]> {
133
+ return (await space.list(RUNS_PREFIX))
134
+ .flatMap((o) => {
135
+ const at = timeOfRun(o.key)
136
+ return at ? [{ key: o.key, at, size: o.size }] : []
137
+ })
138
+ .sort((a, b) => a.at.getTime() - b.at.getTime() || (a.key < b.key ? -1 : 1))
139
+ }
140
+
141
+ /** the last run at or before `at` (the last run when none is given), null when the Space holds none */
142
+ export async function runAt(space: Space, at?: Date): Promise<{ key: string; at: Date } | null> {
143
+ const runs = (await runsOf(space)).filter((r) => !at || r.at.getTime() <= at.getTime())
144
+ return runs[runs.length - 1] ?? null
145
+ }
146
+
147
+ async function getJson<T>(space: Space, key: string, tmp: string): Promise<{ json: string; value: T }> {
148
+ await space.get(key, tmp)
149
+ const bytes = new Uint8Array(await Bun.file(tmp).arrayBuffer())
150
+ rmSync(tmp, { force: true })
151
+ const json = gunzipSync(bytes).toString('utf8')
152
+ return { json, value: JSON.parse(json) as T }
153
+ }
154
+
155
+ /** a part read once a process: it is content addressed, so its bytes never change */
156
+ const partCache = new Map<string, Entry[]>()
157
+
158
+ async function readPart(space: Space, ref: PartRef, tmp: string): Promise<Entry[]> {
159
+ const held = partCache.get(ref.key)
160
+ if (held) return held
161
+ const { json, value: p } = await getJson<PartV2>(space, ref.key, tmp)
162
+ const want = /([0-9a-f]{64})\.json\.gz$/.exec(ref.key)?.[1]
163
+ if (sha256(json) !== want) throw new Error(`${ref.key}: the part hashes to ${sha256(json).slice(0, 12)}, its key says ${want?.slice(0, 12)}`)
164
+ if (p.v !== 2 || !Array.isArray(p.files) || p.files.length !== ref.files) throw new Error(`${ref.key}: no backup part of ${ref.files} files`)
165
+ partCache.set(ref.key, p.files)
166
+ return p.files
167
+ }
168
+
169
+ /** the top of a run, without its parts: its digest and time */
170
+ export async function readRunHead(space: Space, key: string, tmp: string): Promise<{ v: number; digest: string; at: string; parts?: PartRef[] }> {
171
+ const { value: m } = await getJson<{ v: number; digest: string; at: string; parts?: PartRef[] }>(space, key, tmp)
172
+ if (m.v !== 1 && m.v !== 2) throw new Error(`${key}: no backup run of version 1 or 2`)
173
+ return m
174
+ }
175
+
176
+ /** a run read from the Space through files in `dir`, its parts 8 at a time, each checked by its sha */
177
+ export async function readManifest(space: Space, key: string, dir: string): Promise<Manifest> {
178
+ const { value: m } = await getJson<(Omit<Manifest, 'v'> & { v: 1 }) | RunV2>(space, key, join(dir, 'run.json.gz'))
179
+ if (m.v === 1) {
180
+ if (!Array.isArray(m.files)) throw new Error(`${key}: no backup manifest of version 1`)
181
+ return m
182
+ }
183
+ if (m.v !== 2 || !Array.isArray(m.parts)) throw new Error(`${key}: no backup run of version 1 or 2`)
184
+ const parts = m.parts
185
+ const lists: Entry[][] = []
186
+ let next = 0
187
+ const work = async (): Promise<void> => {
188
+ for (let i = next++; i < parts.length; i = next++) lists[i] = await readPart(space, parts[i]!, join(dir, `part-${i}.json.gz`))
189
+ }
190
+ await Promise.all(Array.from({ length: 8 }, work))
191
+ const files = lists.flat().sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
192
+ return { v: 2, at: m.at, host: m.host, home: m.home, digest: m.digest, files, refused: m.refused }
193
+ }
@@ -0,0 +1,192 @@
1
+ // A RESTORE (wiki build/shipkit/media-store.md, Backup, Restore): a run's files written back from the Space, each one
2
+ // checked by its sha before it lands. Into a folder that is empty or new, by default. In place only when asked, and
3
+ // then a live file that differs is copied aside first, and a sqlite lands beside its live file (`.restored`): a live
4
+ // db is never swapped under the process that writes it. The DRILL restores into a scratch folder and compares every
5
+ // sha against the live files
6
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
7
+ import { tmpdir } from 'node:os'
8
+ import { dirname, join, resolve } from 'node:path'
9
+ import { gunzipSync } from 'node:zlib'
10
+ import { shaOf } from '../content.ts'
11
+ import type { Space } from '../space.ts'
12
+ import { stampOf } from './keys.ts'
13
+ import { readManifest, runAt, type Entry, type Manifest } from './manifest.ts'
14
+ import { rowsOf } from './snapshot.ts'
15
+
16
+ export interface RestoreResult {
17
+ run: string
18
+ at: string
19
+ files: number
20
+ bytes: number
21
+ written: number
22
+ /** in place: the live file already held these bytes */
23
+ same: number
24
+ /** in place: live files copied aside before they were replaced, and where */
25
+ aside: { n: number; dir: string | null }
26
+ /** in place: sqlite files written beside the live one */
27
+ beside: string[]
28
+ failed: { path: string; error: string }[]
29
+ }
30
+
31
+ const RESTORE_JOBS = 8
32
+ let fetched = 0
33
+
34
+ /** an entry's bytes from the Space into a file of the scratch folder, checked by its sha (an archive of hundreds of MB
35
+ * is hashed as a stream, never held in memory) */
36
+ async function fetchEntry(space: Space, e: Entry, scratch: string): Promise<string> {
37
+ const tmp = join(scratch, `${++fetched}-${e.key.replace(/\//g, '_')}`)
38
+ await space.get(e.key, tmp)
39
+ if (e.sqlite) {
40
+ const bytes = new Uint8Array(gunzipSync(new Uint8Array(await Bun.file(tmp).arrayBuffer())))
41
+ writeFileSync(tmp, bytes)
42
+ }
43
+ const sha = await shaOf(tmp)
44
+ const size = statSync(tmp).size
45
+ if (sha !== e.sha || size !== e.size) {
46
+ rmSync(tmp, { force: true })
47
+ throw new Error(`${e.key}: the bytes hash to ${sha.slice(0, 12)} (${size} B), the manifest says ${e.sha.slice(0, 12)} (${e.size} B)`)
48
+ }
49
+ return tmp
50
+ }
51
+
52
+ /** a checked file moved into its place through a file beside it renamed: no reader sees half of it */
53
+ function land(path: string, from: string): void {
54
+ mkdirSync(dirname(path), { recursive: true })
55
+ const tmp = `${path}.${process.pid}.restore`
56
+ try {
57
+ renameSync(from, tmp)
58
+ } catch {
59
+ copyFileSync(from, tmp)
60
+ rmSync(from, { force: true })
61
+ }
62
+ renameSync(tmp, path)
63
+ }
64
+
65
+ export interface RestoreOptions {
66
+ /** the live home folder: where `--in-place` writes, and what a manifest's paths are under */
67
+ home: string
68
+ /** a folder that is empty or new; the paths land under it */
69
+ to?: string
70
+ inPlace?: boolean
71
+ at?: Date
72
+ /** only the paths under this prefix */
73
+ only?: string
74
+ }
75
+
76
+ /** the run a restore or a drill reads: the last at or before `at` */
77
+ async function runFor(space: Space, at?: Date): Promise<{ key: string; at: Date }> {
78
+ const run = await runAt(space, at)
79
+ if (!run) throw new Error(at ? `no backup run at or before ${at.toISOString()}` : 'the Space holds no backup run yet: sk backup')
80
+ return run
81
+ }
82
+
83
+ export async function restore(space: Space, o: RestoreOptions): Promise<RestoreResult & { manifest: Manifest }> {
84
+ if ((o.inPlace === true) === (o.to !== undefined)) throw new Error('a restore goes --to <dir> (a folder that is empty or new) or --in-place, one of the two')
85
+ const to = o.to === undefined ? null : resolve(o.to)
86
+ if (to && existsSync(to) && readdirSync(to).length > 0) throw new Error(`${to} is not empty: a restore writes into an empty or new folder, never over files`)
87
+ const run = await runFor(space, o.at)
88
+ const scratch = mkdtempSync(join(tmpdir(), 'shipkit-restore-'))
89
+ const stamp = stampOf(new Date())
90
+ const aside = join(o.home, '.shipkit', 'backup-replaced', stamp)
91
+ try {
92
+ const m = await readManifest(space, run.key, join(scratch, 'run'))
93
+ const files = m.files.filter((f) => !o.only || f.path === o.only || f.path.startsWith(o.only.endsWith('/') ? o.only : `${o.only}/`))
94
+ const out: RestoreResult & { manifest: Manifest } = { run: run.key, at: m.at, files: files.length, bytes: 0, written: 0, same: 0, aside: { n: 0, dir: null }, beside: [], failed: [], manifest: m }
95
+ let next = 0
96
+ const one = async (e: Entry): Promise<void> => {
97
+ try {
98
+ if (to) {
99
+ land(join(to, e.path), await fetchEntry(space, e, scratch))
100
+ out.written++
101
+ out.bytes += e.size
102
+ return
103
+ }
104
+ const live = join(o.home, e.path)
105
+ if (e.sqlite) {
106
+ land(`${live}.restored`, await fetchEntry(space, e, scratch))
107
+ out.beside.push(`${live}.restored`)
108
+ out.written++
109
+ out.bytes += e.size
110
+ return
111
+ }
112
+ if (existsSync(live) && statSync(live).size === e.size && (await shaOf(live)) === e.sha) {
113
+ out.same++
114
+ return
115
+ }
116
+ const file = await fetchEntry(space, e, scratch)
117
+ if (existsSync(live)) {
118
+ mkdirSync(dirname(join(aside, e.path)), { recursive: true })
119
+ copyFileSync(live, join(aside, e.path))
120
+ out.aside.n++
121
+ out.aside.dir = aside
122
+ }
123
+ land(live, file)
124
+ out.written++
125
+ out.bytes += e.size
126
+ } catch (err) {
127
+ out.failed.push({ path: e.path, error: (err as Error).message })
128
+ }
129
+ }
130
+ // a GET waits on the network: eight at a time
131
+ const work = async (): Promise<void> => {
132
+ for (let e = files[next++]; e; e = files[next++]) await one(e)
133
+ }
134
+ await Promise.all(Array.from({ length: RESTORE_JOBS }, work))
135
+ return out
136
+ } finally {
137
+ rmSync(scratch, { recursive: true, force: true })
138
+ }
139
+ }
140
+
141
+ export interface DrillResult {
142
+ run: string
143
+ at: string
144
+ files: number
145
+ bytes: number
146
+ /** restored, and its sha read again from the disk matches the manifest */
147
+ restored: number
148
+ /** the live file holds the same bytes now */
149
+ sameAsLive: number
150
+ /** the live file moved since the run: newer bytes, the next run takes them */
151
+ liveMoved: string[]
152
+ liveGone: string[]
153
+ /** sqlite: the restored snapshot's rows against the live db's rows now */
154
+ sqlite: { path: string; restored: Record<string, number>; live: Record<string, number> }[]
155
+ failed: { path: string; error: string }[]
156
+ dir: string
157
+ }
158
+
159
+ /** a run (the last, or the last at or before `at`) restored into a scratch folder (or `to`), every sha read again and
160
+ * compared to the live files */
161
+ export async function drill(space: Space, o: { home: string; to?: string; keep?: boolean; at?: Date }): Promise<DrillResult & { v: number }> {
162
+ const dir = o.to ? resolve(o.to) : mkdtempSync(join(tmpdir(), 'shipkit-drill-'))
163
+ try {
164
+ const r = await restore(space, { home: o.home, to: dir, ...(o.at ? { at: o.at } : {}) })
165
+ const out: DrillResult & { v: number } = { v: r.manifest.v, run: r.run, at: r.at, files: r.files, bytes: r.bytes, restored: 0, sameAsLive: 0, liveMoved: [], liveGone: [], sqlite: [], failed: [...r.failed], dir }
166
+ const bad = new Set(r.failed.map((f) => f.path))
167
+ for (const e of r.manifest.files) {
168
+ if (bad.has(e.path)) continue
169
+ const back = join(dir, e.path)
170
+ const sha = await shaOf(back)
171
+ if (sha !== e.sha) {
172
+ out.failed.push({ path: e.path, error: `restored bytes hash to ${sha.slice(0, 12)}, the manifest says ${e.sha.slice(0, 12)}` })
173
+ continue
174
+ }
175
+ out.restored++
176
+ const live = join(o.home, e.path)
177
+ if (!existsSync(live)) {
178
+ out.liveGone.push(e.path)
179
+ continue
180
+ }
181
+ if (e.sqlite) {
182
+ out.sqlite.push({ path: e.path, restored: rowsOf(back, e.sqlite), live: rowsOf(live, e.sqlite) })
183
+ continue
184
+ }
185
+ if ((await shaOf(live)) === e.sha) out.sameAsLive++
186
+ else out.liveMoved.push(e.path)
187
+ }
188
+ return out
189
+ } finally {
190
+ if (!o.to && !o.keep) rmSync(dir, { recursive: true, force: true })
191
+ }
192
+ }