rvlib-shipkit 2.12.0 → 2.14.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 (378) hide show
  1. package/CHANGELOG.md +75 -21
  2. package/README.md +1 -1
  3. package/package.json +4 -2
  4. package/src/agent-time/store.ts +2 -2
  5. package/src/assets/run-assets.ts +2 -2
  6. package/src/assets/server/studio-server.ts +27 -23
  7. package/src/check.ts +4 -4
  8. package/src/checks/SK001-package-json-shape.check.ts +8 -4
  9. package/src/checks/SK002-contracts-fulfillness.check.ts +2 -2
  10. package/src/checks/SK003-claude-md-shape.check.ts +20 -13
  11. package/src/checks/SK004-gitignore-policy.check.ts +45 -6
  12. package/src/checks/SK005-rvlib-versions.check.ts +2 -2
  13. package/src/checks/SK006-npm-publish-safety.check.ts +3 -3
  14. package/src/checks/SK007-github-visibility.check.ts +2 -2
  15. package/src/checks/SK008-reviewer-agent.check.ts +3 -3
  16. package/src/checks/SK010-undeclared-unit.check.ts +2 -2
  17. package/src/checks/SK011-sibling-unit-ranges.check.ts +2 -2
  18. package/src/checks/SK012-config-barrel-import.check.ts +2 -2
  19. package/src/checks/SK013-one-way-in-policy.check.ts +2 -2
  20. package/src/checks/SK015-nested-repo.check.ts +3 -3
  21. package/src/checks/SK016-legacy-check-shapes.check.ts +2 -2
  22. package/src/checks/SK017-vscode-hub-task.check.ts +2 -2
  23. package/src/checks/SK018-test-files-run.check.ts +2 -2
  24. package/src/checks/SK019-tests-run-in-units.check.ts +2 -2
  25. package/src/checks/SK020-self-spawning-check.check.ts +2 -2
  26. package/src/checks/SK022-machine-runs-the-pin.check.ts +2 -2
  27. package/src/checks/SK024-identity-colors.check.ts +1 -1
  28. package/src/checks/SK025-release-drift.check.ts +2 -2
  29. package/src/checks/SK026-asks-autoclose.check.ts +2 -2
  30. package/src/checks/SK027-agent-wiki-links.check.ts +8 -2
  31. package/src/checks/SK028-readme.check.ts +2 -2
  32. package/src/checks/SK029-explicit-check-files.check.ts +3 -3
  33. package/src/checks/SK030-cache-audit.check.ts +7 -5
  34. package/src/checks/SK031-trace-audit.check.ts +7 -7
  35. package/src/checks/SK032-ignored-inputs.check.ts +3 -3
  36. package/src/checks/SK033-global-contribution.check.ts +11 -4
  37. package/src/checks/SK034-commit-gates-armed.check.ts +2 -2
  38. package/src/checks/SK035-public-clean.check.ts +46 -0
  39. package/src/checks/SK036-draft-media-size.check.ts +28 -0
  40. package/src/checks/SK037-keyword-additions.check.ts +43 -0
  41. package/src/cli/cmd_Backup.ts +152 -0
  42. package/src/cli/cmd_Ci.ts +8 -11
  43. package/src/cli/cmd_Commands.ts +4 -4
  44. package/src/cli/cmd_ConfigKeys.ts +2 -2
  45. package/src/cli/cmd_Drill.ts +145 -0
  46. package/src/cli/cmd_Home.ts +50 -3
  47. package/src/cli/cmd_Init.ts +1 -1
  48. package/src/cli/cmd_Media.ts +10 -8
  49. package/src/cli/cmd_Mv.ts +14 -7
  50. package/src/cli/cmd_Review.ts +6 -4
  51. package/src/cli/cmd_Shot.ts +5 -2
  52. package/src/cli/cmd_Smoke.ts +5 -2
  53. package/src/cli/cmd_Social.ts +226 -0
  54. package/src/cli/cmd_Sound.ts +1 -1
  55. package/src/cli/cmd_Start.ts +1 -1
  56. package/src/cli/cmd_Time.ts +1 -1
  57. package/src/cli/cmd_TraceAudit.ts +6 -6
  58. package/src/cli/cmd_Trailer.ts +7 -4
  59. package/src/cli/cmd_Veille.ts +173 -0
  60. package/src/cli/cmd_When.ts +2 -2
  61. package/src/cli/family-pages.ts +19 -16
  62. package/src/cli/registry.ts +13 -2
  63. package/src/cli.ts +5 -2
  64. package/src/collections/actions.ts +1 -49
  65. package/src/collections/checks.ts +2 -1
  66. package/src/collections/collection-types.ts +12 -3
  67. package/src/collections/providers.ts +4 -4
  68. package/src/collections/review.ts +3 -2
  69. package/src/collections/tests.ts +19 -8
  70. package/src/comfy/comfy-panel.ts +2 -2
  71. package/src/contracts/apply-contracts.ts +1 -3
  72. package/src/contracts/contract-manifests.ts +2 -3
  73. package/src/contracts/contract-types.ts +0 -1
  74. package/src/contracts/contracts-engine.ts +0 -3
  75. package/src/contracts/manifests/discord.contract.ts +1 -1
  76. package/src/contracts/manifests/identity.contract.ts +1 -1
  77. package/src/contracts/manifests/itch.contract.ts +1 -1
  78. package/src/contracts/manifests/steam.contract.ts +1 -1
  79. package/src/core/agent-dir-at.ts +12 -0
  80. package/src/core/agent-dir.ts +16 -0
  81. package/src/core/app-icon.ts +9 -3
  82. package/src/core/budget.ts +1 -1
  83. package/src/core/bun-builtins.ts +2 -2
  84. package/src/core/canonical-scripts.ts +2 -2
  85. package/src/core/discover-checks.ts +38 -6
  86. package/src/core/fix-scope.ts +4 -2
  87. package/src/core/floor-resolve.ts +68 -48
  88. package/src/core/floor.ts +9 -0
  89. package/src/core/git-root.ts +24 -0
  90. package/src/core/global-contribution.ts +4 -1
  91. package/src/core/ignored-block.ts +1 -1
  92. package/src/core/ignored-inputs.ts +3 -2
  93. package/src/core/last-good.ts +3 -1
  94. package/src/core/layout.ts +8 -0
  95. package/src/core/log-stamp.ts +36 -0
  96. package/src/core/loop-watch.ts +93 -0
  97. package/src/core/machine-link.ts +134 -0
  98. package/src/core/memory-watch.ts +41 -0
  99. package/src/core/motherhome.ts +2 -2
  100. package/src/core/one-way-in-policy.ts +34 -26
  101. package/src/core/run-ci.ts +9 -11
  102. package/src/core/run-fixers.ts +9 -9
  103. package/src/core/runs-matrix.ts +1 -1
  104. package/src/core/slots.ts +30 -0
  105. package/src/core/trace-audit.ts +50 -9
  106. package/src/core/tree-rev.ts +60 -0
  107. package/src/core/unit-files.ts +42 -0
  108. package/src/drill/render.ts +140 -0
  109. package/src/drill/run.ts +269 -0
  110. package/src/fleet/scan-fleet.ts +6 -5
  111. package/src/home/daemon-jobs.ts +201 -0
  112. package/src/home/global-context.ts +44 -8
  113. package/src/home/gui-app/ShipkitGui.swift +91 -2
  114. package/src/home/home-routes.ts +22 -15
  115. package/src/home/hubs.ts +10 -3
  116. package/src/home/inbox-shape.ts +54 -5
  117. package/src/home/inbox.ts +17 -2
  118. package/src/home/lib-watch.ts +10 -3
  119. package/src/home/machine-stores.ts +15 -29
  120. package/src/home/pm-config.ts +4 -1
  121. package/src/home/pm-inputs.ts +2 -0
  122. package/src/home/resources.ts +7 -2
  123. package/src/home/run-daemon.ts +15 -18
  124. package/src/home/run-pm.ts +3 -1
  125. package/src/home/serve-daemon.ts +4 -3
  126. package/src/home/serve-web.ts +104 -1
  127. package/src/hooks/commit-message.ts +29 -20
  128. package/src/hooks/hook-gates.ts +1 -1
  129. package/src/hooks/leak-guard.ts +69 -9
  130. package/src/hooks/run-hooks.ts +18 -22
  131. package/src/identities/identities.ts +334 -0
  132. package/src/identities/machine-route.ts +126 -0
  133. package/src/identities/machine.ts +62 -0
  134. package/src/init-repo.ts +3 -3
  135. package/src/ledger/check-stats.ts +10 -9
  136. package/src/ledger/gate-checks.ts +32 -1
  137. package/src/ledger/record-kept.ts +112 -0
  138. package/src/ledger/repo-view.ts +10 -0
  139. package/src/ledger/run-log.ts +17 -12
  140. package/src/ledger/run-timeline.ts +8 -4
  141. package/src/ledger/store.ts +7 -0
  142. package/src/ledger/suite-log.ts +17 -13
  143. package/src/media-kinds.ts +3 -2
  144. package/src/media-store/backup/daemon.ts +73 -0
  145. package/src/media-store/backup/keys.ts +25 -0
  146. package/src/media-store/backup/manifest.ts +193 -0
  147. package/src/media-store/backup/restore.ts +192 -0
  148. package/src/media-store/backup/run.ts +278 -0
  149. package/src/media-store/backup/secret.ts +86 -0
  150. package/src/media-store/backup/snapshot.ts +64 -0
  151. package/src/media-store/backup/sources.ts +199 -0
  152. package/src/media-store/content.ts +1 -1
  153. package/src/media-store/daemon.ts +56 -70
  154. package/src/media-store/db.ts +1 -1
  155. package/src/media-store/fact.ts +1 -1
  156. package/src/media-store/hand.ts +1 -1
  157. package/src/media-store/kind.ts +1 -1
  158. package/src/media-store/purge.ts +1 -1
  159. package/src/media-store/put.ts +5 -3
  160. package/src/media-store/remote.ts +1 -1
  161. package/src/media-store/space.ts +24 -5
  162. package/src/mv/mv-md.ts +63 -22
  163. package/src/pages/forward.ts +35 -0
  164. package/src/pages/frame-client.ts +118 -0
  165. package/src/pages/routes.ts +29 -0
  166. package/src/pages/unit.ts +92 -0
  167. package/src/plan/planner.ts +12 -0
  168. package/src/plan/repo-source.ts +19 -5
  169. package/src/reflect/transcript.ts +35 -10
  170. package/src/release/public-clean.ts +319 -0
  171. package/src/release/published-here.ts +22 -0
  172. package/src/release/run-bump.ts +3 -2
  173. package/src/release/run-release.ts +7 -4
  174. package/src/repo-config.ts +71 -13
  175. package/src/review/anim.ts +1 -1
  176. package/src/review/auto.ts +1 -1
  177. package/src/review/cells.ts +15 -1
  178. package/src/review/format.ts +2 -2
  179. package/src/review/http.ts +16 -2
  180. package/src/review/marks.ts +1 -1
  181. package/src/review/media-kind.ts +1 -1
  182. package/src/review/media-read.ts +1 -1
  183. package/src/review/model.ts +27 -6
  184. package/src/review/notes.ts +125 -0
  185. package/src/review/previews.ts +1 -1
  186. package/src/review/project.ts +7 -39
  187. package/src/review/role.ts +1 -1
  188. package/src/review/routes.ts +18 -14
  189. package/src/review/store.ts +42 -2
  190. package/src/review/threads.ts +1 -1
  191. package/src/review/trailer-desk.ts +3 -3
  192. package/src/review/trailer-media.ts +8 -5
  193. package/src/review/trailer-model.ts +1 -1
  194. package/src/review/trailer-routes.ts +1 -1
  195. package/src/review/trailer-shots.ts +22 -5
  196. package/src/review/unit.ts +2 -2
  197. package/src/scaffold/files/agent-handoff.md +3 -0
  198. package/src/scaffold/files/agent-index.md +4 -12
  199. package/src/scaffold/files/tsconfig.json +1 -1
  200. package/src/scaffold/project-scaffold.ts +6 -5
  201. package/src/serve/embed.ts +2 -2
  202. package/src/serve/hub-app/check-words.ts +1 -1
  203. package/src/serve/hub-app/col-card.tsx +3 -17
  204. package/src/serve/hub-app/col-tables-view.tsx +2 -1
  205. package/src/serve/hub-app/cols-svc.ts +0 -13
  206. package/src/serve/hub-app/dock-st.ts +4 -2
  207. package/src/serve/hub-app/dock-view.tsx +2 -0
  208. package/src/serve/hub-app/frames-st.ts +35 -0
  209. package/src/serve/hub-app/hash-route.ts +64 -1
  210. package/src/serve/hub-app/home-st.ts +32 -8
  211. package/src/serve/hub-app/home-strip.css +9 -1
  212. package/src/serve/hub-app/home-strip.tsx +7 -6
  213. package/src/serve/hub-app/home.html +5 -0
  214. package/src/serve/hub-app/hub-app.tsx +51 -7
  215. package/src/serve/hub-app/hub.css +29 -11
  216. package/src/serve/hub-app/icons.tsx +16 -1
  217. package/src/serve/hub-app/identities-st.ts +210 -0
  218. package/src/serve/hub-app/identities-view.tsx +353 -0
  219. package/src/serve/hub-app/identities.css +48 -0
  220. package/src/serve/hub-app/identity-address.ts +52 -0
  221. package/src/serve/hub-app/inbox-st.ts +60 -7
  222. package/src/serve/hub-app/inbox-view.tsx +49 -7
  223. package/src/serve/hub-app/inbox.css +12 -1
  224. package/src/serve/hub-app/index.html +3 -0
  225. package/src/serve/hub-app/kept-cols.tsx +30 -0
  226. package/src/serve/hub-app/keys.ts +10 -2
  227. package/src/serve/hub-app/list-walk.ts +89 -0
  228. package/src/serve/hub-app/machine-st.ts +12 -0
  229. package/src/serve/hub-app/media-svc.ts +1 -1
  230. package/src/serve/hub-app/media-view.tsx +2 -1
  231. package/src/serve/hub-app/pages-frames.tsx +134 -0
  232. package/src/serve/hub-app/pages-svc.ts +111 -0
  233. package/src/serve/hub-app/palette-st.ts +18 -3
  234. package/src/serve/hub-app/palette-view.tsx +9 -2
  235. package/src/serve/hub-app/planned-view.tsx +2 -1
  236. package/src/serve/hub-app/project-list.css +18 -14
  237. package/src/serve/hub-app/project-list.tsx +88 -49
  238. package/src/serve/hub-app/projects-svc.ts +33 -3
  239. package/src/serve/hub-app/repo-sections.ts +19 -2
  240. package/src/serve/hub-app/repo-st.ts +76 -20
  241. package/src/serve/hub-app/review/review-board.tsx +1 -1
  242. package/src/serve/hub-app/review/review-cells.tsx +6 -5
  243. package/src/serve/hub-app/review/review-kit.ts +30 -7
  244. package/src/serve/hub-app/review/review-page.tsx +6 -5
  245. package/src/serve/hub-app/review/review-st.ts +34 -15
  246. package/src/serve/hub-app/review/review-thread.tsx +63 -14
  247. package/src/serve/hub-app/review/review-views.tsx +133 -51
  248. package/src/serve/hub-app/review/thread-st.ts +80 -37
  249. package/src/serve/hub-app/review/trailer-page.tsx +7 -5
  250. package/src/serve/hub-app/review/trailer-st.ts +1 -1
  251. package/src/serve/hub-app/review.css +26 -9
  252. package/src/serve/hub-app/site/site-part.tsx +173 -0
  253. package/src/serve/hub-app/site/site-st.ts +157 -0
  254. package/src/serve/hub-app/site.css +35 -0
  255. package/src/serve/hub-app/social/calendar.tsx +182 -0
  256. package/src/serve/hub-app/social/comms-page.tsx +330 -0
  257. package/src/serve/hub-app/social/kit.tsx +244 -0
  258. package/src/serve/hub-app/social/post-card.tsx +456 -0
  259. package/src/serve/hub-app/social/problems.tsx +60 -0
  260. package/src/serve/hub-app/social/social-model.ts +154 -0
  261. package/src/serve/hub-app/social/social-page.tsx +681 -0
  262. package/src/serve/hub-app/social/social-st.ts +1014 -0
  263. package/src/serve/hub-app/social.css +289 -0
  264. package/src/serve/hub-app/stores/stores-page.tsx +312 -0
  265. package/src/serve/hub-app/stores/stores-st.ts +286 -0
  266. package/src/serve/hub-app/stores.css +54 -0
  267. package/src/serve/hub-app/timeline-geometry.ts +1 -1
  268. package/src/serve/hub-app/timeline-view.tsx +3 -2
  269. package/src/serve/hub-app/tree-build.ts +6 -0
  270. package/src/serve/hub-app/tree-row.tsx +27 -4
  271. package/src/serve/hub-app/tree-svc.ts +18 -49
  272. package/src/serve/hub-app/veille/veille-page.tsx +515 -0
  273. package/src/serve/hub-app/veille/veille-st.ts +443 -0
  274. package/src/serve/hub-app/veille.css +84 -0
  275. package/src/serve/hub-runtime.ts +20 -11
  276. package/src/serve/project-gutter-route.ts +44 -12
  277. package/src/serve/run-lanes.ts +7 -4
  278. package/src/serve/same-origin.ts +1 -1
  279. package/src/serve/serve-hub.ts +20 -12
  280. package/src/serve/tracked-watch.ts +24 -3
  281. package/src/serve/warm-cell.ts +5 -1
  282. package/src/shipkit-files.ts +15 -4
  283. package/src/shipkit.ts +0 -1
  284. package/src/shot/box.ts +160 -0
  285. package/src/shot/browser-slot.ts +74 -0
  286. package/src/shot/client.ts +42 -7
  287. package/src/shot/clip-encoder.ts +108 -24
  288. package/src/shot/film-box.ts +292 -0
  289. package/src/shot/shooter.ts +71 -17
  290. package/src/shot/shot-ask.ts +10 -2
  291. package/src/shot/stepped-clip.ts +5 -4
  292. package/src/site/desk.ts +242 -0
  293. package/src/site/routes.ts +66 -0
  294. package/src/site/unit.ts +62 -0
  295. package/src/social/brands.ts +22 -0
  296. package/src/social/card-drafts.ts +24 -0
  297. package/src/social/compose.ts +97 -0
  298. package/src/social/desk-index.ts +123 -0
  299. package/src/social/desk-wire.ts +64 -0
  300. package/src/social/drafts.ts +183 -0
  301. package/src/social/house.ts +24 -0
  302. package/src/social/load.ts +332 -0
  303. package/src/social/md.ts +70 -0
  304. package/src/social/media-facts.ts +53 -0
  305. package/src/social/media-kind.ts +189 -0
  306. package/src/social/media-limit.ts +42 -0
  307. package/src/social/media-of.ts +30 -0
  308. package/src/social/migrate.ts +123 -0
  309. package/src/social/open.ts +17 -0
  310. package/src/social/post-url.ts +158 -0
  311. package/src/social/presence.ts +332 -0
  312. package/src/social/public-read.ts +53 -0
  313. package/src/social/publish/bluesky.ts +168 -0
  314. package/src/social/publish/discord.ts +76 -0
  315. package/src/social/publish/index.ts +24 -0
  316. package/src/social/publish/secret.ts +13 -0
  317. package/src/social/push.ts +37 -0
  318. package/src/social/richtext.ts +37 -0
  319. package/src/social/routes.ts +186 -0
  320. package/src/social/stats.ts +134 -0
  321. package/src/social/text.ts +267 -0
  322. package/src/social/tracker-route.ts +39 -0
  323. package/src/social/tracker.ts +255 -0
  324. package/src/social/unit.ts +53 -0
  325. package/src/social/writes.ts +130 -0
  326. package/src/start-repo.ts +14 -9
  327. package/src/stores/collection.ts +27 -0
  328. package/src/stores/desk.ts +336 -0
  329. package/src/stores/model.ts +187 -0
  330. package/src/stores/routes.ts +126 -0
  331. package/src/stores/unit.ts +57 -0
  332. package/src/suite/calibrate.ts +127 -0
  333. package/src/suite/core-counters.ts +91 -0
  334. package/src/suite/judge-suites.ts +95 -35
  335. package/src/suite/suite-cli.ts +44 -10
  336. package/src/suite/suite-cpu-preload.ts +34 -9
  337. package/src/trace/tracer.ts +12 -5
  338. package/src/trailer/adapter.ts +5 -1
  339. package/src/trailer/build.ts +45 -12
  340. package/src/trailer/ffmpeg.ts +11 -0
  341. package/src/trailer/footage.ts +30 -13
  342. package/src/trailer/grammar.ts +18 -2
  343. package/src/trailer/graph.ts +28 -6
  344. package/src/trailer/holes.ts +1 -1
  345. package/src/trailer/passage.ts +18 -6
  346. package/src/trailer/plan.ts +74 -3
  347. package/src/trailer/prune.ts +1 -1
  348. package/src/trailer/states.ts +1 -1
  349. package/src/trailer/stitch.ts +67 -26
  350. package/src/trailer/url.ts +1 -1
  351. package/src/trailer/versions.ts +24 -0
  352. package/src/trailer/words.ts +1 -1
  353. package/src/ts/gate-typecheck.ts +32 -0
  354. package/src/ts/typecheck-cli.ts +9 -11
  355. package/src/tui/run-tui.ts +1 -1
  356. package/src/tui/tui-app.tsx +0 -1
  357. package/src/tui/tui-store.ts +1 -1
  358. package/src/veille/asks.ts +155 -0
  359. package/src/veille/auto.ts +31 -0
  360. package/src/veille/batch.ts +27 -0
  361. package/src/veille/chrome.ts +127 -0
  362. package/src/veille/collection.ts +28 -0
  363. package/src/veille/desk.ts +242 -0
  364. package/src/veille/identity.ts +80 -0
  365. package/src/veille/import.ts +68 -0
  366. package/src/veille/log.ts +183 -0
  367. package/src/veille/platforms.ts +118 -0
  368. package/src/veille/reads.ts +66 -0
  369. package/src/veille/replied.ts +110 -0
  370. package/src/veille/routes.ts +185 -0
  371. package/src/veille/service.ts +81 -0
  372. package/src/veille/watch.ts +116 -0
  373. package/src/veille/worth.ts +46 -0
  374. package/src/wiki/scan-md.ts +18 -0
  375. package/src/collections/posts.ts +0 -142
  376. package/src/contracts/manifests/social.contract.ts +0 -20
  377. package/src/scaffold/files/agent-coding.md +0 -35
  378. package/src/ts/typecheck-cache.ts +0 -11
@@ -0,0 +1,192 @@
1
+ // A RESTORE (wiki tools/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
+ }
@@ -0,0 +1,278 @@
1
+ // A BACKUP RUN (wiki tools/shipkit/media-store.md, Backup): every source read once, refused or hashed (a sqlite
2
+ // snapshotted first), each object the Space lacks sent from the bytes that were hashed (never
3
+ // the live file again: it may have moved), then the run's parts the Space lacks, then the run itself, last, so a run
4
+ // never names an object the Space lacks. A run whose state equals the last one writes nothing. The objects are never
5
+ // deleted: every version stays
6
+ import { constants, copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
7
+ import { hostname, tmpdir } from 'node:os'
8
+ import { basename, dirname, join, relative } from 'node:path'
9
+ import { homeDir } from '../../home/home-paths.ts'
10
+ import { gzipSync } from 'node:zlib'
11
+ import { machineGet, machineSet } from '../../core/machine-db.ts'
12
+ import { mediaKey } from '../content.ts'
13
+ import { isUp } from '../remote.ts'
14
+ import type { Space } from '../space.ts'
15
+ import { uploadOne } from '../upload.ts'
16
+ import { BACKUP_LABEL, runKey } from './keys.ts'
17
+ import { digestOf, encodeRun, readManifest, readRunHead, runAt, type Entry, type Refused } from './manifest.ts'
18
+ import { fileRefusal, refusal } from './secret.ts'
19
+ import { snapshotSqlite } from './snapshot.ts'
20
+ import { collect, type Collect, type Source } from './sources.ts'
21
+
22
+ const LAST = 'backup-last'
23
+ /** the files named whole, by path: their size, time, sha and key, so an unchanged archive is never read again */
24
+ const SEEN = 'backup-seen'
25
+
26
+ export interface Last {
27
+ key: string
28
+ digest: string
29
+ at: string
30
+ }
31
+
32
+ type Seen = Record<string, { size: number; mtime: number; sha: string; key: string }>
33
+
34
+ export const lastRun = (): Last | null => machineGet<Last>(LAST)
35
+
36
+ const sha256 = (b: Uint8Array): string => new Bun.CryptoHasher('sha256').update(b).digest('hex')
37
+
38
+ /** one source made ready: its entry and where the object's bytes are (in memory, a frozen copy, or already up) */
39
+ export interface Ready {
40
+ entry: Entry
41
+ bytes?: Uint8Array
42
+ /** a copy in the scratch folder (an APFS clone): the bytes that were hashed, whatever the live file does next */
43
+ file?: string
44
+ /** the object's size: a sqlite's is its gzip */
45
+ size: number
46
+ /** a path the repo names whole: its sha kept by its size and time */
47
+ whole?: true
48
+ }
49
+
50
+ /** every source read: hashed, snapshotted, or refused */
51
+ export async function prepare(sources: readonly Source[], scratch: string, seen: Seen = machineGet<Seen>(SEEN) ?? {}): Promise<{ ready: Ready[]; refused: Refused[] }> {
52
+ const ready: Ready[] = []
53
+ const refused: Refused[] = []
54
+ for (const s of sources) {
55
+ try {
56
+ if (s.broken) {
57
+ refused.push({ path: s.rel, why: s.broken })
58
+ continue
59
+ }
60
+ if (s.sqlite) {
61
+ const to = join(scratch, `${ready.length}-${basename(s.abs)}`)
62
+ const snap = snapshotSqlite(s.abs, to, s.sqlite)
63
+ const raw = new Uint8Array(await Bun.file(to).arrayBuffer())
64
+ rmSync(to, { force: true })
65
+ const why = refusal(basename(s.rel), raw)
66
+ if (why) {
67
+ refused.push({ path: s.rel, why })
68
+ continue
69
+ }
70
+ const gz = new Uint8Array(gzipSync(raw))
71
+ // a snapshot is a new file each run: its live file's time would move the part with no change
72
+ const entry: Entry = { path: s.rel, sha: sha256(raw), size: raw.length, mtime: 0, key: `${BACKUP_LABEL}/${sha256(gz)}.gz`, sqlite: { ...s.sqlite, rows: snap.rows } }
73
+ ready.push({ entry, bytes: gz, size: gz.length })
74
+ continue
75
+ }
76
+ if (s.whole) {
77
+ const was = seen[s.rel]
78
+ if (was && was.size === s.size && was.mtime === s.mtime && isUp(was.key)) {
79
+ ready.push({ entry: { path: s.rel, sha: was.sha, size: was.size, mtime: s.mtime, key: was.key }, size: was.size, whole: true })
80
+ continue
81
+ }
82
+ const copy = join(scratch, `${ready.length}-whole${extname(s.abs)}`)
83
+ copyFileSync(s.abs, copy, constants.COPYFILE_FICLONE)
84
+ const r = await fileRefusal(copy, basename(s.abs))
85
+ if (r.why) {
86
+ rmSync(copy, { force: true })
87
+ refused.push({ path: s.rel, why: r.why })
88
+ continue
89
+ }
90
+ ready.push({ entry: { path: s.rel, sha: r.sha, size: r.size, mtime: s.mtime, key: mediaKey(BACKUP_LABEL, { sha: r.sha }, s.abs) }, file: copy, size: r.size, whole: true })
91
+ continue
92
+ }
93
+ const bytes = new Uint8Array(await Bun.file(s.abs).arrayBuffer())
94
+ const why = refusal(basename(s.abs), bytes)
95
+ if (why) {
96
+ refused.push({ path: s.rel, why })
97
+ continue
98
+ }
99
+ const sha = sha256(bytes)
100
+ ready.push({ entry: { path: s.rel, sha, size: bytes.length, mtime: s.mtime, key: mediaKey(BACKUP_LABEL, { sha }, s.abs) }, bytes, size: bytes.length })
101
+ } catch (e) {
102
+ refused.push({ path: s.rel, why: `not read: ${(e as Error).message}` })
103
+ }
104
+ }
105
+ return { ready, refused }
106
+ }
107
+
108
+ const extname = (p: string): string => /(\.[^./]+)$/.exec(basename(p))?.[1]?.toLowerCase() ?? ''
109
+
110
+ export interface RunResult {
111
+ files: number
112
+ bytes: number
113
+ sent: number
114
+ sentBytes: number
115
+ /** objects the Space already held */
116
+ there: number
117
+ refused: Refused[]
118
+ failed: { key: string; error: string }[]
119
+ /** the run written, null when nothing changed since `last` or an upload failed */
120
+ manifest: string | null
121
+ /** what the record of the run cost: its parts sent (of all), their bytes, and the run's own bytes */
122
+ record: { parts: number; partsSent: number; partsBytes: number; runBytes: number }
123
+ last: Last | null
124
+ digest: string
125
+ }
126
+
127
+ /** one object up from the bytes that were hashed, checked by a HEAD of its size: true when it was sent */
128
+ async function sendOne(space: Space, key: string, size: number, from: { bytes?: Uint8Array; file?: string }, scratch: string, n: number): Promise<boolean> {
129
+ if (from.file) return uploadOne(space, { key, size, path: from.file })
130
+ const path = join(scratch, `${n}.obj`)
131
+ try {
132
+ writeFileSync(path, from.bytes ?? new Uint8Array(0))
133
+ return await uploadOne(space, { key, size, path })
134
+ } finally {
135
+ rmSync(path, { force: true })
136
+ }
137
+ }
138
+
139
+ /** the objects of `ready` up, `jobs` at a time */
140
+ async function sendAll(space: Space, ready: readonly Ready[], scratch: string, jobs: number, out: RunResult): Promise<void> {
141
+ const byKey = new Map<string, Ready>()
142
+ for (const r of ready) byKey.set(r.entry.key, r)
143
+ const list = [...byKey.values()].filter((r) => !isUp(r.entry.key))
144
+ out.there += byKey.size - list.length
145
+ let next = 0
146
+ const work = async (): Promise<void> => {
147
+ for (;;) {
148
+ const i = next++
149
+ const r = list[i]
150
+ if (!r) return
151
+ try {
152
+ if (!r.bytes && !r.file) throw new Error(`${r.entry.path}: no bytes held for ${r.entry.key}, and the index does not see it up`)
153
+ if (await sendOne(space, r.entry.key, r.size, r, scratch, i)) {
154
+ out.sent++
155
+ out.sentBytes += r.size
156
+ } else out.there++
157
+ } catch (e) {
158
+ out.failed.push({ key: r.entry.key, error: (e as Error).message })
159
+ } finally {
160
+ if (r.file) rmSync(r.file, { force: true })
161
+ }
162
+ }
163
+ }
164
+ await Promise.all(Array.from({ length: Math.max(1, jobs) }, work))
165
+ }
166
+
167
+ /** the last run's digest: the machine db's record, else the Space's last run */
168
+ async function lastOf(space: Space, scratch: string): Promise<Last | null> {
169
+ const held = lastRun()
170
+ if (held) return held
171
+ const run = await runAt(space)
172
+ if (!run) return null
173
+ const m = await readRunHead(space, run.key, join(scratch, 'last.json.gz'))
174
+ return { key: run.key, digest: m.digest, at: m.at }
175
+ }
176
+
177
+ /** a lock this old is taken over even when its pid runs: a restart in place keeps the pid of the process that held it
178
+ * (a daemon that ran a backup in process), and a job child is killed at an hour */
179
+ export const LOCK_STALE_MS = 2 * 3600_000
180
+
181
+ /** one run at a time on the machine (the daemon's job and a hand run): a lock file with its pid, taken over once its
182
+ * process is gone or the lock is older than LOCK_STALE_MS */
183
+ function lock(): () => void {
184
+ const path = join(homeDir(), 'backup.lock')
185
+ mkdirSync(dirname(path), { recursive: true })
186
+ for (let i = 0; i < 2; i++) {
187
+ try {
188
+ writeFileSync(path, String(process.pid), { flag: 'wx' })
189
+ return () => rmSync(path, { force: true })
190
+ } catch {
191
+ const pid = Number(readFileSync(path, 'utf8').trim())
192
+ let alive = false
193
+ try {
194
+ alive = pid > 0 && process.kill(pid, 0)
195
+ } catch {
196
+ alive = false
197
+ }
198
+ const age = Date.now() - (statSync(path, { throwIfNoEntry: false })?.mtimeMs ?? 0)
199
+ if (alive && age < LOCK_STALE_MS) throw new Error(`another backup runs (pid ${pid}): it holds ${path}`)
200
+ if (alive) console.error(`WARN backup: ${path} held by pid ${pid} for ${Math.round(age / 60_000)} min, past ${LOCK_STALE_MS / 3600_000} h: taken over`)
201
+ rmSync(path, { force: true })
202
+ }
203
+ }
204
+ throw new Error(`${path}: the lock did not take`)
205
+ }
206
+
207
+ /** one run: every source to the Space, then the run's parts the Space lacks, then the run itself, last */
208
+ export async function backupRun(space: Space, o: Collect & { now?: Date; jobs?: number }): Promise<RunResult> {
209
+ const unlock = lock()
210
+ const scratch = mkdtempSync(join(tmpdir(), 'shipkit-backup-'))
211
+ try {
212
+ const now = o.now ?? new Date()
213
+ const { ready, refused } = await prepare(await collect(o), scratch)
214
+ const files = ready.map((r) => r.entry)
215
+ const digest = digestOf(files, refused)
216
+ const last = await lastOf(space, scratch)
217
+ const out: RunResult = { files: files.length, bytes: ready.reduce((n, r) => n + r.entry.size, 0), sent: 0, sentBytes: 0, there: 0, refused, failed: [], manifest: null, record: { parts: 0, partsSent: 0, partsBytes: 0, runBytes: 0 }, last, digest }
218
+ await sendAll(space, ready, scratch, o.jobs ?? 8, out)
219
+ if (out.failed.length > 0) return out
220
+ const seen: Seen = {}
221
+ for (const r of ready) if (r.whole) seen[r.entry.path] = { size: r.entry.size, mtime: r.entry.mtime, sha: r.entry.sha, key: r.entry.key }
222
+ machineSet(SEEN, seen)
223
+ if (last?.digest === digest) return out
224
+ const enc = encodeRun({ at: now.toISOString(), host: hostname(), home: o.home, digest, files, refused }, o.repos.map((r) => relative(o.home, r)))
225
+ out.record.parts = enc.parts.length
226
+ for (const [i, p] of enc.parts.entries()) {
227
+ if (isUp(p.ref.key)) continue
228
+ try {
229
+ if (await sendOne(space, p.ref.key, p.bytes.length, p, scratch, -1 - i)) {
230
+ out.record.partsSent++
231
+ out.record.partsBytes += p.bytes.length
232
+ }
233
+ } catch (e) {
234
+ out.failed.push({ key: p.ref.key, error: (e as Error).message })
235
+ }
236
+ }
237
+ if (out.failed.length > 0) return out
238
+ const key = runKey(now, digest)
239
+ await sendOne(space, key, enc.run.length, { bytes: enc.run }, scratch, -1 - enc.parts.length)
240
+ out.record.runBytes = enc.run.length
241
+ machineSet(LAST, { key, digest, at: now.toISOString() } satisfies Last)
242
+ out.manifest = key
243
+ return out
244
+ } finally {
245
+ rmSync(scratch, { recursive: true, force: true })
246
+ unlock()
247
+ }
248
+ }
249
+
250
+ export interface CheckResult {
251
+ files: number
252
+ /** sources whose object the Space lacks */
253
+ waiting: { path: string; size: number }[]
254
+ /** sources the last run holds another content of, or none */
255
+ changed: string[]
256
+ refused: Refused[]
257
+ last: Last | null
258
+ }
259
+
260
+ /** what is not backed up yet: each source read and hashed, nothing sent */
261
+ export async function backupCheck(space: Space, o: Collect): Promise<CheckResult> {
262
+ const scratch = mkdtempSync(join(tmpdir(), 'shipkit-backup-'))
263
+ try {
264
+ const { ready, refused } = await prepare(await collect(o), scratch)
265
+ const last = await lastOf(space, scratch)
266
+ const held = last ? new Map((await readManifest(space, last.key, join(scratch, 'last'))).files.map((f) => [f.path, f.sha])) : new Map<string, string>()
267
+ const waiting: CheckResult['waiting'] = []
268
+ for (const r of ready) {
269
+ if (isUp(r.entry.key)) continue
270
+ const h = await space.head(r.entry.key)
271
+ if (h?.size !== r.size) waiting.push({ path: r.entry.path, size: r.size })
272
+ }
273
+ const changed = ready.filter((r) => held.get(r.entry.path) !== r.entry.sha && !r.entry.sqlite).map((r) => r.entry.path)
274
+ return { files: ready.length, waiting, changed, refused, last }
275
+ } finally {
276
+ rmSync(scratch, { recursive: true, force: true })
277
+ }
278
+ }
@@ -0,0 +1,86 @@
1
+ // what the backup never sends (wiki tools/shipkit/media-store.md, Backup): a secret's home is the keychain, never the
2
+ // Space. A file is refused by its name (an env file, a key file, a name that says secret, token, password, api key), by
3
+ // the leak guard's secret shapes in its bytes, by a credential line whose value is no keychain pointer, or by its
4
+ // size (over 50 MB is a question for the owner first, unless his repo names the path whole: `backup.paths`). The
5
+ // reason is printed, the content never
6
+ import { parsePatterns, SECRET_ROWS } from '../../hooks/leak-guard.ts'
7
+
8
+ export const MAX_BYTES = 50e6
9
+
10
+ const SHAPES = parsePatterns(SECRET_ROWS.join('\n')).regexes
11
+
12
+ /** a token word counts only at the end of a name (`github-token`, `token.txt`): `lane-token-budget.md` is prose */
13
+ const SECRET_NAME = /^\.env(?:\..*)?$|\.(?:pem|key|p12|pfx|jks|keystore)$|^id_(?:rsa|dsa|ecdsa|ed25519)$|(?:^|[-_.])(?:secrets?|api-?keys?|passwords?|passwd|credentials?|creds)(?:[-_.]|$)|(?:^|[-_.])tokens?(?:\.[a-z]+)?$/i
14
+
15
+ const KEY = '(?:password|passwd|pwd|mot de passe|api[ _-]?key|secret|token|bearer)'
16
+ /** a line that sets a credential to a value: a bare key at the start of a line, or a quoted key with its closing quote
17
+ * (`"secret:cave"` is a value, « 3. Secret : la grotte » inside a note is prose). A value that points at the keychain
18
+ * (a `secret get` command, the word keychain, an `rv/<name>` secret name) passes */
19
+ const CREDENTIAL_LINE = new RegExp(`(?:^[ \\t>*#-]*${KEY}|"${KEY}"|'${KEY}')[ \\t]*[:=][ \\t]*(?![ \\t]*$)(?!.*(?:\\bsecret get\\b|keychain|\\brv/[\\w/-]+))`, 'im')
20
+
21
+ /** why these bytes never go up, null when they may */
22
+ function textRefusal(bytes: Uint8Array): string | null {
23
+ const text = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('latin1')
24
+ const shape = SHAPES.find((s) => s.re.test(text))
25
+ if (shape) return `it holds a secret shape (${shape.row.slice(3, 24)}…): the keychain keeps those`
26
+ if (CREDENTIAL_LINE.test(text)) return 'a line sets a credential to a value (not a keychain pointer): the keychain keeps those'
27
+ return null
28
+ }
29
+
30
+ const nameRefusal = (name: string): string | null => (SECRET_NAME.test(name) ? 'its name says it holds a secret: the keychain keeps those' : null)
31
+
32
+ /** why the file never goes up, null when it may */
33
+ export function refusal(name: string, bytes: Uint8Array): string | null {
34
+ if (bytes.length > MAX_BYTES) return `over 50 MB (${(bytes.length / 1e6).toFixed(0)} MB): asked before it goes`
35
+ return nameRefusal(name) ?? textRefusal(bytes)
36
+ }
37
+
38
+ /** a window of a stream, its end carried into the next so a shape cut by a window's edge is still seen */
39
+ const WINDOW = 8 << 20
40
+ const CARRY = 4096
41
+
42
+ async function streamRefusal(stream: ReadableStream<Uint8Array>, each?: (chunk: Uint8Array) => void): Promise<string | null> {
43
+ let held = new Uint8Array(0)
44
+ let why: string | null = null
45
+ for await (const chunk of stream) {
46
+ each?.(chunk)
47
+ if (why) continue
48
+ const joined = new Uint8Array(held.length + chunk.length)
49
+ joined.set(held)
50
+ joined.set(chunk, held.length)
51
+ held = joined
52
+ if (held.length < WINDOW) continue
53
+ why = textRefusal(held)
54
+ held = held.slice(held.length - CARRY)
55
+ }
56
+ return why ?? (held.length > 0 ? textRefusal(held) : null)
57
+ }
58
+
59
+ /** the names and the bytes inside a zip (`unzip`), never only its compressed bytes: a secret packed in an archive is
60
+ * still a secret */
61
+ async function zipRefusal(path: string): Promise<string | null> {
62
+ const list = Bun.spawn(['unzip', '-Z1', path], { stdout: 'pipe', stderr: 'pipe' })
63
+ const names = (await new Response(list.stdout).text()).split('\n').filter(Boolean)
64
+ if ((await list.exited) !== 0) return `not read: unzip could not list it: ${(await new Response(list.stderr).text()).trim().slice(0, 200)}`
65
+ for (const n of names) {
66
+ const why = nameRefusal(n.split('/').pop() ?? n)
67
+ if (why) return `${n} inside: ${why}`
68
+ }
69
+ const all = Bun.spawn(['unzip', '-p', path], { stdout: 'pipe', stderr: 'ignore' })
70
+ const why = await streamRefusal(all.stdout)
71
+ if ((await all.exited) > 1) return 'not read: unzip could not read every entry'
72
+ return why ? `inside: ${why}` : null
73
+ }
74
+
75
+ /** a file the owner named whole (an archive, a dump): no size bound, its bytes read as a stream, its sha read on the
76
+ * way. A zip is read inside */
77
+ export async function fileRefusal(path: string, name: string): Promise<{ why: string | null; sha: string; size: number }> {
78
+ const h = new Bun.CryptoHasher('sha256')
79
+ let size = 0
80
+ const scan = await streamRefusal(Bun.file(path).stream(), (c) => {
81
+ h.update(c)
82
+ size += c.length
83
+ })
84
+ const why = nameRefusal(name) ?? scan ?? (/\.zip$/i.test(name) ? await zipRefusal(path) : null)
85
+ return { why, sha: h.digest('hex'), size }
86
+ }
@@ -0,0 +1,64 @@
1
+ // a live sqlite copied consistently (wiki tools/shipkit/media-store.md, Backup): the live file attached read only into
2
+ // a fresh database, the tables kept copied inside ONE transaction (one read snapshot of the WAL), then vacuumed. Never a
3
+ // copy of the file while a process writes it. The same rows give the same bytes, so an unchanged db is one object.
4
+ // A cut leaves out the rows that move by themselves (a pid, the backup's own records): else every run differs
5
+ import { Database } from 'bun:sqlite'
6
+
7
+ export interface SqliteCut {
8
+ /** the tables kept, null: every table */
9
+ tables: string[] | null
10
+ /** per table, a where clause of the rows left out */
11
+ except?: Record<string, string>
12
+ }
13
+
14
+ export interface Snapshot {
15
+ /** the tables copied and their rows */
16
+ rows: Record<string, number>
17
+ }
18
+
19
+ const quote = (name: string): string => `"${name.replace(/"/g, '""')}"`
20
+ const kept = (cut: SqliteCut, table: string): string => (cut.except?.[table] ? ` where not (${cut.except[table]})` : '')
21
+
22
+ /** the live db at `live` copied into the new file `to` */
23
+ export function snapshotSqlite(live: string, to: string, cut: SqliteCut): Snapshot {
24
+ const db = new Database(to, { create: true, readwrite: true })
25
+ try {
26
+ db.exec('pragma journal_mode = delete')
27
+ db.query('attach database ? as live').run(`file:${encodeURI(live)}?mode=ro`)
28
+ db.exec('begin')
29
+ const all = db.query(`select name, sql from live.sqlite_schema where type = 'table' and name not like 'sqlite_%' order by name`).all() as { name: string; sql: string }[]
30
+ const keep = cut.tables === null ? all : all.filter((t) => cut.tables!.includes(t.name))
31
+ const missing = (cut.tables ?? []).filter((t) => !all.some((a) => a.name === t))
32
+ if (missing.length > 0) throw new Error(`${live}: no table ${missing.join(', ')}`)
33
+ const rows: Record<string, number> = {}
34
+ for (const t of keep) {
35
+ db.exec(t.sql)
36
+ db.exec(`insert into main.${quote(t.name)} select * from live.${quote(t.name)}${kept(cut, t.name)}`)
37
+ rows[t.name] = (db.query(`select count(*) as n from main.${quote(t.name)}`).get() as { n: number }).n
38
+ }
39
+ const names = keep.map((t) => t.name)
40
+ const idx = db.query(`select sql from live.sqlite_schema where type = 'index' and sql is not null and tbl_name in (${names.map(() => '?').join(',') || "''"}) order by name`).all(...names) as { sql: string }[]
41
+ for (const i of idx) db.exec(i.sql)
42
+ db.exec('commit')
43
+ db.exec('detach database live')
44
+ db.exec('vacuum')
45
+ return { rows }
46
+ } finally {
47
+ db.close()
48
+ }
49
+ }
50
+
51
+ /** the rows of each table a cut keeps, read through one read transaction */
52
+ export function rowsOf(file: string, cut: SqliteCut): Record<string, number> {
53
+ const db = new Database(file, { readonly: true })
54
+ try {
55
+ db.exec('begin')
56
+ const names = (db.query(`select name from sqlite_schema where type = 'table' and name not like 'sqlite_%' order by name`).all() as { name: string }[]).map((r) => r.name).filter((n) => cut.tables === null || cut.tables.includes(n))
57
+ const out: Record<string, number> = {}
58
+ for (const n of names) out[n] = (db.query(`select count(*) as n from ${quote(n)}${kept(cut, n)}`).get() as { n: number }).n
59
+ db.exec('commit')
60
+ return out
61
+ } finally {
62
+ db.close()
63
+ }
64
+ }