rvlib-shipkit 2.25.0 → 2.27.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 (456) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/package.json +2 -2
  3. package/src/agent-time/diet.ts +77 -0
  4. package/src/agent-time/family.ts +72 -0
  5. package/src/agent-time/hooks.ts +331 -0
  6. package/src/agent-time/limits.ts +44 -0
  7. package/src/agent-time/live.ts +1 -3
  8. package/src/agent-time/mask.ts +96 -18
  9. package/src/agent-time/refused.ts +45 -0
  10. package/src/agent-time/render.ts +130 -17
  11. package/src/agent-time/report-cache.ts +57 -0
  12. package/src/agent-time/report.ts +349 -23
  13. package/src/agent-time/shape.ts +50 -3
  14. package/src/agent-time/store.ts +370 -95
  15. package/src/agent-time/timeline.ts +140 -21
  16. package/src/agent-time/turns.ts +18 -8
  17. package/src/annex/offload.ts +17 -6
  18. package/src/annex/tidy.ts +70 -10
  19. package/src/asks/ask-after.ts +40 -0
  20. package/src/asks/asks-queue.ts +205 -47
  21. package/src/assets/kit-config.ts +7 -3
  22. package/src/assets/kits/identity-kit.ts +289 -10
  23. package/src/check.ts +3 -1
  24. package/src/checks/SK004-gitignore-policy.check.ts +12 -5
  25. package/src/checks/SK013-one-way-in-policy.check.ts +8 -3
  26. package/src/checks/SK026-asks-autoclose.check.ts +5 -5
  27. package/src/checks/SK028-readme.check.ts +7 -66
  28. package/src/checks/SK030-cache-audit.check.ts +6 -1
  29. package/src/checks/SK031-trace-audit.check.ts +2 -0
  30. package/src/checks/SK033-global-contribution.check.ts +3 -1
  31. package/src/checks/SK035-public-clean.check.ts +2 -2
  32. package/src/checks/SK043-scratch-on-the-mac.check.ts +59 -4
  33. package/src/checks/SK045-slow-hooks.check.ts +47 -0
  34. package/src/checks/SK046-hook-records.check.ts +76 -0
  35. package/src/checks/SK047-login-in-description.check.ts +36 -0
  36. package/src/checks/SK048-one-local-file.check.ts +36 -0
  37. package/src/cli/cmd_Asks.ts +71 -5
  38. package/src/cli/cmd_Backup.ts +5 -3
  39. package/src/cli/cmd_Capacity.ts +2 -2
  40. package/src/cli/cmd_CrossRepoActivity.ts +5 -4
  41. package/src/cli/cmd_Db.ts +253 -0
  42. package/src/cli/cmd_History.ts +212 -0
  43. package/src/cli/cmd_Home.ts +31 -3
  44. package/src/cli/cmd_Hq.ts +516 -0
  45. package/src/cli/cmd_Machines.ts +36 -0
  46. package/src/cli/cmd_Media.ts +38 -6
  47. package/src/cli/cmd_Mv.ts +1 -1
  48. package/src/cli/cmd_Reflect.ts +23 -2
  49. package/src/cli/cmd_Releases.ts +30 -0
  50. package/src/cli/cmd_Review.ts +569 -118
  51. package/src/cli/cmd_Secret.ts +62 -12
  52. package/src/cli/cmd_Social.ts +83 -1
  53. package/src/cli/cmd_Space.ts +324 -0
  54. package/src/cli/cmd_Time.ts +82 -5
  55. package/src/cli/cmd_Tmp.ts +28 -4
  56. package/src/cli/cmd_Trailer.ts +14 -10
  57. package/src/cli/cmd_Urls.ts +56 -0
  58. package/src/cli/cmd_Vault.ts +583 -0
  59. package/src/cli/family-help.ts +4 -2
  60. package/src/cli/family-pages.ts +1 -1
  61. package/src/cli/registry.ts +26 -4
  62. package/src/collections/actions.ts +63 -13
  63. package/src/collections/collection-types.ts +23 -1
  64. package/src/collections/providers.ts +117 -23
  65. package/src/collections/review.ts +4 -4
  66. package/src/commands/runner.ts +5 -1
  67. package/src/contracts/contract-manifests.ts +6 -5
  68. package/src/contracts/contract-types.ts +6 -4
  69. package/src/contracts/contracts-engine.ts +11 -0
  70. package/src/contracts/manifests/chrome-web-store.contract.ts +31 -0
  71. package/src/core/budget.ts +12 -17
  72. package/src/core/capacity.ts +27 -18
  73. package/src/core/check-runner.ts +7 -4
  74. package/src/core/history-files.ts +9 -5
  75. package/src/core/layout.ts +3 -0
  76. package/src/core/machine-busy.ts +127 -0
  77. package/src/core/machine-commit.ts +6 -1
  78. package/src/core/machine-db.ts +368 -20
  79. package/src/core/machine-layout.ts +137 -0
  80. package/src/core/machine-read.ts +81 -0
  81. package/src/core/migrate-layout.ts +1 -1
  82. package/src/core/one-way-in-policy.ts +64 -7
  83. package/src/core/polling-policy.ts +27 -0
  84. package/src/core/retention.ts +16 -2
  85. package/src/core/scope.ts +107 -14
  86. package/src/core/signal-name.ts +6 -0
  87. package/src/core/slots.ts +5 -4
  88. package/src/core/trace-audit.ts +6 -1
  89. package/src/core/transient.ts +6 -0
  90. package/src/drill/clean.ts +25 -1
  91. package/src/drill/run.ts +2 -2
  92. package/src/drill/seal.ts +27 -4
  93. package/src/home/activity-shape.ts +2 -0
  94. package/src/home/activity.ts +66 -3
  95. package/src/home/app-sign.ts +15 -4
  96. package/src/home/daemon-jobs.ts +149 -7
  97. package/src/home/database-projects.ts +111 -0
  98. package/src/home/database-words.ts +203 -0
  99. package/src/home/databases.ts +460 -0
  100. package/src/home/global-units.ts +6 -0
  101. package/src/home/gui-app/ShipkitGui.swift +122 -1
  102. package/src/home/gui-app.ts +6 -3
  103. package/src/home/home-move.ts +514 -0
  104. package/src/home/home-paths.ts +12 -3
  105. package/src/home/home-routes.ts +68 -0
  106. package/src/home/inbox-shape.ts +24 -14
  107. package/src/home/machine-fold.ts +820 -0
  108. package/src/home/machine-host.ts +20 -5
  109. package/src/home/machine-repair.ts +503 -0
  110. package/src/home/machine-stores.ts +66 -15
  111. package/src/home/machine-temp.ts +547 -86
  112. package/src/home/resume.ts +79 -0
  113. package/src/home/run-daemon.ts +25 -4
  114. package/src/home/run-pm.ts +18 -5
  115. package/src/home/serve-daemon.ts +18 -3
  116. package/src/home/serve-web.ts +175 -7
  117. package/src/home/space-job.ts +115 -0
  118. package/src/home/space-page.ts +257 -0
  119. package/src/home/space-route.ts +167 -0
  120. package/src/home/space-words.ts +103 -0
  121. package/src/home/time-page-shape.ts +202 -0
  122. package/src/home/time-page.ts +64 -0
  123. package/src/home/vault-page.ts +482 -0
  124. package/src/home/vault-words.ts +132 -0
  125. package/src/hooks/leak-guard.ts +40 -13
  126. package/src/hooks/one-way-in-guard.ts +17 -4
  127. package/src/hq/cards.ts +581 -0
  128. package/src/hq/door-route.ts +43 -0
  129. package/src/hq/door.ts +163 -0
  130. package/src/hq/files-send.ts +348 -0
  131. package/src/hq/forgotten-log.ts +35 -0
  132. package/src/hq/history-check.ts +255 -0
  133. package/src/hq/history-place.ts +146 -0
  134. package/src/hq/history-send.ts +487 -0
  135. package/src/hq/hq-db.ts +99 -0
  136. package/src/hq/hq-local.ts +469 -0
  137. package/src/hq/hq-routes.ts +196 -0
  138. package/src/hq/hq-store.ts +599 -0
  139. package/src/hq/kinds/ask.ts +147 -0
  140. package/src/hq/kinds/card-gone.ts +83 -0
  141. package/src/hq/kinds/card-msg.ts +66 -0
  142. package/src/hq/kinds/card.ts +99 -0
  143. package/src/hq/kinds/index.ts +21 -0
  144. package/src/hq/kinds/kind.ts +126 -0
  145. package/src/hq/kinds/media.ts +125 -0
  146. package/src/hq/kinds/prompt.ts +219 -0
  147. package/src/hq/kinds/reflection.ts +128 -0
  148. package/src/hq/kinds/report.ts +55 -0
  149. package/src/hq/kinds/time-day.ts +236 -0
  150. package/src/hq/ledger.ts +473 -0
  151. package/src/hq/machine-key.ts +44 -0
  152. package/src/hq/machine-notes.ts +131 -0
  153. package/src/hq/outbox.ts +372 -0
  154. package/src/hq/replica.ts +168 -0
  155. package/src/hq/repo-id.ts +4 -0
  156. package/src/hq/report-facts.ts +117 -0
  157. package/src/hq/report.ts +274 -0
  158. package/src/hq/switch.ts +151 -0
  159. package/src/hq/vault-grant.ts +92 -0
  160. package/src/identities/identities.ts +15 -3
  161. package/src/identities/steps.ts +31 -0
  162. package/src/ledger/db.ts +73 -26
  163. package/src/ledger/gate-checks.ts +29 -4
  164. package/src/ledger/git-key.ts +3 -3
  165. package/src/ledger/git-scan.ts +49 -7
  166. package/src/ledger/run-log.ts +11 -3
  167. package/src/ledger/store.ts +26 -4
  168. package/src/media-store/backup/daemon.ts +36 -17
  169. package/src/media-store/backup/kept.ts +241 -0
  170. package/src/media-store/backup/restore.ts +14 -4
  171. package/src/media-store/backup/run.ts +11 -11
  172. package/src/media-store/backup/secret.ts +6 -4
  173. package/src/media-store/backup/snapshot.ts +4 -2
  174. package/src/media-store/backup/sources.ts +68 -20
  175. package/src/media-store/copy/config.ts +77 -0
  176. package/src/media-store/copy/copy.ts +194 -0
  177. package/src/media-store/copy/lifecycle.ts +43 -0
  178. package/src/media-store/copy/night.ts +90 -0
  179. package/src/media-store/copy/proof.ts +151 -0
  180. package/src/media-store/copy/snapshot.ts +152 -0
  181. package/src/media-store/copy/store.ts +62 -0
  182. package/src/media-store/copy/stream.ts +176 -0
  183. package/src/media-store/daemon.ts +66 -16
  184. package/src/media-store/db.ts +22 -11
  185. package/src/media-store/forget.ts +23 -3
  186. package/src/media-store/hand.ts +4 -3
  187. package/src/media-store/hq-find.ts +75 -0
  188. package/src/media-store/hq-send.ts +277 -0
  189. package/src/media-store/kind.ts +2 -0
  190. package/src/media-store/purge.ts +18 -15
  191. package/src/media-store/put.ts +24 -8
  192. package/src/media-store/remote.ts +16 -7
  193. package/src/media-store/space-listing.ts +240 -0
  194. package/src/media-store/space.ts +40 -21
  195. package/src/media-store/sync.ts +5 -5
  196. package/src/media-store/tidy.ts +98 -0
  197. package/src/media-store/upload.ts +3 -3
  198. package/src/media-store/webp.ts +66 -0
  199. package/src/messages/model.ts +16 -7
  200. package/src/messages/routes.ts +14 -4
  201. package/src/messages/score.ts +2 -2
  202. package/src/messages/suggest.ts +96 -0
  203. package/src/pages/frame-client.ts +10 -0
  204. package/src/plan/planner.ts +28 -17
  205. package/src/recordings/media-kind.ts +1 -0
  206. package/src/recordings/model.ts +1 -1
  207. package/src/recordings/recorder-app/Capture.swift +9 -7
  208. package/src/reflect/hq-corpus.ts +56 -0
  209. package/src/reflect/prompt-corpus.ts +3 -1
  210. package/src/reflect/transcript.ts +146 -36
  211. package/src/release/machine-words.ts +67 -0
  212. package/src/release/public-clean.ts +8 -3
  213. package/src/releases/from-card.ts +1 -1
  214. package/src/releases/model.ts +18 -0
  215. package/src/releases/routes.ts +10 -5
  216. package/src/releases/store.ts +23 -2
  217. package/src/repo-config.ts +42 -2
  218. package/src/review/anim.ts +2 -2
  219. package/src/review/auto.ts +2 -2
  220. package/src/review/card-db.ts +244 -0
  221. package/src/review/card-rows.ts +266 -0
  222. package/src/review/cells.ts +76 -5
  223. package/src/review/draft-card.ts +41 -0
  224. package/src/review/draft-model.ts +78 -0
  225. package/src/review/format.ts +29 -10
  226. package/src/review/gone.ts +98 -0
  227. package/src/review/inbox-hook.ts +35 -0
  228. package/src/review/marks.ts +1 -1
  229. package/src/review/media-kind.ts +7 -5
  230. package/src/review/media-read.ts +9 -7
  231. package/src/review/media.ts +32 -5
  232. package/src/review/model.ts +214 -45
  233. package/src/review/move.ts +491 -0
  234. package/src/review/notes.ts +12 -20
  235. package/src/review/previews.ts +15 -19
  236. package/src/review/project.ts +1 -1
  237. package/src/review/rev.ts +8 -0
  238. package/src/review/role.ts +1 -1
  239. package/src/review/routes.ts +64 -13
  240. package/src/review/stage-card.ts +8 -4
  241. package/src/review/stage-routes.ts +1 -1
  242. package/src/review/store.ts +529 -83
  243. package/src/review/thread-fold.ts +51 -0
  244. package/src/review/threads.ts +147 -9
  245. package/src/review/trailer-auto-mock.ts +63 -0
  246. package/src/review/trailer-card.ts +4 -4
  247. package/src/review/trailer-desk.ts +41 -7
  248. package/src/review/trailer-media.ts +1 -0
  249. package/src/review/trailer-model.ts +8 -0
  250. package/src/review/trailer-notes.ts +1 -1
  251. package/src/review/trailer-routes.ts +9 -1
  252. package/src/review/unit.ts +6 -6
  253. package/src/review/watchers.ts +1 -1
  254. package/src/rules/untrack-generated.ts +92 -8
  255. package/src/secrets/held.ts +16 -0
  256. package/src/secrets/keychain.ts +113 -0
  257. package/src/secrets/list.ts +16 -6
  258. package/src/secrets/manager.ts +24 -10
  259. package/src/secrets/read.ts +257 -0
  260. package/src/secrets/who-reads.ts +49 -0
  261. package/src/serve/door-forward.ts +268 -0
  262. package/src/serve/door-names.ts +47 -0
  263. package/src/serve/embed.ts +1 -1
  264. package/src/serve/hub-app/activity-view.tsx +56 -32
  265. package/src/serve/hub-app/activity.css +7 -1
  266. package/src/serve/hub-app/asks-page.tsx +48 -0
  267. package/src/serve/hub-app/asks-st.ts +25 -0
  268. package/src/serve/hub-app/clock-svc.ts +1 -2
  269. package/src/serve/hub-app/col-card.tsx +64 -13
  270. package/src/serve/hub-app/col-list-page.tsx +122 -0
  271. package/src/serve/hub-app/col-list-st.ts +103 -0
  272. package/src/serve/hub-app/col-tables-view.tsx +10 -41
  273. package/src/serve/hub-app/col-tables.ts +76 -8
  274. package/src/serve/hub-app/cols-svc.ts +70 -16
  275. package/src/serve/hub-app/database-st.ts +260 -0
  276. package/src/serve/hub-app/database-view.tsx +289 -0
  277. package/src/serve/hub-app/database.css +32 -0
  278. package/src/serve/hub-app/entry-bar.css +14 -0
  279. package/src/serve/hub-app/entry-bar.tsx +33 -0
  280. package/src/serve/hub-app/entry-pick.ts +31 -0
  281. package/src/serve/hub-app/floating.tsx +1 -0
  282. package/src/serve/hub-app/hash-route.ts +11 -1
  283. package/src/serve/hub-app/header-bar.tsx +14 -18
  284. package/src/serve/hub-app/home-st.ts +89 -9
  285. package/src/serve/hub-app/home-strip.css +5 -19
  286. package/src/serve/hub-app/home-strip.tsx +58 -92
  287. package/src/serve/hub-app/home.html +7 -0
  288. package/src/serve/hub-app/hub-app.tsx +31 -142
  289. package/src/serve/hub-app/hub-types.ts +3 -1
  290. package/src/serve/hub-app/hub.css +109 -23
  291. package/src/serve/hub-app/icons.tsx +18 -1
  292. package/src/serve/hub-app/identities-st.ts +56 -6
  293. package/src/serve/hub-app/identities-view.tsx +100 -58
  294. package/src/serve/hub-app/identities.css +17 -15
  295. package/src/serve/hub-app/identity-address.ts +5 -0
  296. package/src/serve/hub-app/inbox-st.ts +41 -24
  297. package/src/serve/hub-app/inbox-view.tsx +37 -41
  298. package/src/serve/hub-app/inbox.css +2 -5
  299. package/src/serve/hub-app/index.html +7 -0
  300. package/src/serve/hub-app/kept-cols.tsx +7 -0
  301. package/src/serve/hub-app/keys.ts +28 -15
  302. package/src/serve/hub-app/later.tsx +26 -0
  303. package/src/serve/hub-app/list-filter.tsx +14 -0
  304. package/src/serve/hub-app/list-walk.ts +72 -3
  305. package/src/serve/hub-app/machines-st.ts +251 -0
  306. package/src/serve/hub-app/machines-view.tsx +224 -0
  307. package/src/serve/hub-app/machines.css +76 -0
  308. package/src/serve/hub-app/md-copy.tsx +79 -0
  309. package/src/serve/hub-app/media-view.tsx +2 -0
  310. package/src/serve/hub-app/messages/messages-page.tsx +79 -7
  311. package/src/serve/hub-app/messages/messages-st.ts +99 -3
  312. package/src/serve/hub-app/messages.css +14 -0
  313. package/src/serve/hub-app/page-keys.ts +175 -0
  314. package/src/serve/hub-app/pages-frames.tsx +11 -3
  315. package/src/serve/hub-app/palette-st.ts +58 -11
  316. package/src/serve/hub-app/palette-view.tsx +3 -1
  317. package/src/serve/hub-app/project-list.css +54 -8
  318. package/src/serve/hub-app/project-list.tsx +128 -59
  319. package/src/serve/hub-app/projects-svc.ts +78 -7
  320. package/src/serve/hub-app/reader-chips.tsx +13 -0
  321. package/src/serve/hub-app/readme-view.tsx +2 -3
  322. package/src/serve/hub-app/readme.css +27 -5
  323. package/src/serve/hub-app/reflections-page.tsx +42 -0
  324. package/src/serve/hub-app/reflections-st.ts +17 -0
  325. package/src/serve/hub-app/releases/releases-page.tsx +25 -2
  326. package/src/serve/hub-app/releases/releases-st.ts +1 -1
  327. package/src/serve/hub-app/repo-sections.ts +9 -5
  328. package/src/serve/hub-app/repo-st.ts +35 -8
  329. package/src/serve/hub-app/review/draft-card.tsx +163 -0
  330. package/src/serve/hub-app/review/kit.tsx +50 -7
  331. package/src/serve/hub-app/review/note-place.ts +1 -1
  332. package/src/serve/hub-app/review/review-board.tsx +2 -2
  333. package/src/serve/hub-app/review/review-cells.tsx +145 -65
  334. package/src/serve/hub-app/review/review-kit.ts +27 -1
  335. package/src/serve/hub-app/review/review-list.tsx +68 -30
  336. package/src/serve/hub-app/review/review-page.tsx +7 -8
  337. package/src/serve/hub-app/review/review-st.ts +111 -24
  338. package/src/serve/hub-app/review/review-thread.tsx +49 -19
  339. package/src/serve/hub-app/review/review-views.tsx +475 -144
  340. package/src/serve/hub-app/review/thread-control-st.ts +115 -0
  341. package/src/serve/hub-app/review/thread-control.tsx +74 -0
  342. package/src/serve/hub-app/review/thread-st.ts +73 -26
  343. package/src/serve/hub-app/review/trailer-card.tsx +1 -1
  344. package/src/serve/hub-app/review/trailer-page.tsx +37 -16
  345. package/src/serve/hub-app/review/trailer-st.ts +41 -7
  346. package/src/serve/hub-app/review.css +267 -61
  347. package/src/serve/hub-app/side-lists.ts +72 -0
  348. package/src/serve/hub-app/sidebar.tsx +6 -3
  349. package/src/serve/hub-app/site/site-part.tsx +2 -8
  350. package/src/serve/hub-app/site/site-st.ts +4 -4
  351. package/src/serve/hub-app/social/comms-page.tsx +20 -5
  352. package/src/serve/hub-app/social/kit.tsx +30 -4
  353. package/src/serve/hub-app/social/post-card.tsx +139 -49
  354. package/src/serve/hub-app/social/serial-writes.ts +13 -0
  355. package/src/serve/hub-app/social/social-model.ts +11 -0
  356. package/src/serve/hub-app/social/social-page.tsx +94 -35
  357. package/src/serve/hub-app/social/social-st.ts +120 -36
  358. package/src/serve/hub-app/social/stage-popup.tsx +1 -1
  359. package/src/serve/hub-app/social/stage-st.ts +1 -1
  360. package/src/serve/hub-app/social/step-layout.ts +1 -1
  361. package/src/serve/hub-app/social.css +3 -0
  362. package/src/serve/hub-app/space-st.ts +209 -0
  363. package/src/serve/hub-app/space-view.tsx +196 -0
  364. package/src/serve/hub-app/space.css +27 -0
  365. package/src/serve/hub-app/stores/stores-page.tsx +91 -23
  366. package/src/serve/hub-app/stores/stores-st.ts +44 -19
  367. package/src/serve/hub-app/stores.css +6 -1
  368. package/src/serve/hub-app/theme-st.ts +22 -9
  369. package/src/serve/hub-app/time-charts.tsx +291 -0
  370. package/src/serve/hub-app/time-pages.tsx +749 -0
  371. package/src/serve/hub-app/time-st.ts +162 -0
  372. package/src/serve/hub-app/time-view.tsx +76 -0
  373. package/src/serve/hub-app/time.css +138 -0
  374. package/src/serve/hub-app/tree-build.ts +52 -42
  375. package/src/serve/hub-app/tree-row.tsx +4 -4
  376. package/src/serve/hub-app/tree-svc.ts +18 -9
  377. package/src/serve/hub-app/urls-svc.ts +154 -0
  378. package/src/serve/hub-app/urls-view.tsx +117 -0
  379. package/src/serve/hub-app/urls.css +30 -0
  380. package/src/serve/hub-app/vault-st.ts +127 -0
  381. package/src/serve/hub-app/vault-view.tsx +154 -0
  382. package/src/serve/hub-app/vault.css +38 -0
  383. package/src/serve/hub-app/veille/veille-st.ts +12 -10
  384. package/src/serve/hub-app/waiting-svc.ts +29 -0
  385. package/src/serve/hub-app/wikis-view.tsx +2 -2
  386. package/src/serve/hub-runtime.ts +15 -2
  387. package/src/serve/project-gutter-route.ts +27 -14
  388. package/src/serve/project-gutter.ts +25 -12
  389. package/src/serve/same-origin.ts +10 -0
  390. package/src/serve/serve-hub.ts +13 -4
  391. package/src/shipkit-files.ts +16 -2
  392. package/src/shipkit.ts +1 -1
  393. package/src/shot/shooter.ts +616 -420
  394. package/src/shot/shot-ask.ts +246 -155
  395. package/src/site/desk.ts +2 -2
  396. package/src/smoke/run-smoke.ts +3 -2
  397. package/src/social/cover.ts +202 -0
  398. package/src/social/discord-layout.ts +37 -13
  399. package/src/social/drafts.ts +3 -0
  400. package/src/social/load.ts +23 -2
  401. package/src/social/media-kind.ts +2 -1
  402. package/src/social/publish/discord.ts +5 -2
  403. package/src/social/publish/secret.ts +2 -2
  404. package/src/social/release-stage.ts +28 -13
  405. package/src/social/routes.ts +26 -1
  406. package/src/social/stage.ts +1 -1
  407. package/src/social/stats.ts +12 -9
  408. package/src/social/strip.ts +4 -1
  409. package/src/social/thumbnail.ts +255 -0
  410. package/src/stores/collection.ts +15 -11
  411. package/src/stores/desk.ts +236 -42
  412. package/src/stores/model.ts +72 -6
  413. package/src/stores/routes.ts +37 -12
  414. package/src/stores/unit.ts +14 -8
  415. package/src/suite/judge-suites.ts +113 -16
  416. package/src/suite/select.ts +45 -3
  417. package/src/suite/suite-cli.ts +81 -34
  418. package/src/trailer/bed.ts +1 -1
  419. package/src/trailer/build.ts +134 -21
  420. package/src/trailer/ffmpeg.ts +7 -0
  421. package/src/trailer/fonts.ts +3 -2
  422. package/src/trailer/grammar.ts +201 -2
  423. package/src/trailer/graph.ts +42 -5
  424. package/src/trailer/look.ts +21 -0
  425. package/src/trailer/mock.ts +154 -0
  426. package/src/trailer/passage.ts +65 -26
  427. package/src/trailer/score/heard.ts +89 -0
  428. package/src/trailer/score/sound.ts +14 -8
  429. package/src/trailer/sound/run.ts +16 -6
  430. package/src/trailer/stitch.ts +26 -5
  431. package/src/trailer/titles.ts +82 -19
  432. package/src/trailer/versions.ts +1 -3
  433. package/src/trailer/vertical.ts +3 -1
  434. package/src/urls/frame.ts +195 -0
  435. package/src/urls/routes.ts +43 -0
  436. package/src/urls/rows.ts +171 -0
  437. package/src/urls/unit.ts +73 -0
  438. package/src/vault/house-keys.ts +42 -0
  439. package/src/vault/layout.ts +50 -0
  440. package/src/vault/policy.ts +165 -0
  441. package/src/vault/vault-audit.ts +276 -0
  442. package/src/vault/vault-client.ts +40 -0
  443. package/src/vault/vault-config.ts +159 -0
  444. package/src/vault/vault-destroy.ts +78 -0
  445. package/src/vault/vault-handover.ts +305 -0
  446. package/src/vault/vault-http.ts +352 -0
  447. package/src/vault/vault-import.ts +208 -0
  448. package/src/vault/vault-init.ts +328 -0
  449. package/src/vault/vault-minter.ts +271 -0
  450. package/src/vault/vault-restore.ts +333 -0
  451. package/src/vault/vault-serve.ts +342 -0
  452. package/src/vault/vault-snapshot.ts +281 -0
  453. package/src/veille/asks.ts +1 -1
  454. package/src/veille/desk.ts +2 -2
  455. package/src/wiki/run-wiki.ts +2 -1
  456. package/src/wiki/scan-md.ts +42 -2
@@ -0,0 +1,77 @@
1
+ // the second place of the Space (wiki tools/shipkit/media-store.md): the house config's `serve.spaceCopy`, a bucket at
2
+ // another provider that holds a copy of every object of the Space and the copy's own snapshots. Both key pairs are
3
+ // read through the house's `credsReadCommand` and held in memory only
4
+ import { houseSpaceConfig, type SpaceConfig } from '../space.ts'
5
+
6
+ /** the house config's `serve.spaceCopy` */
7
+ export interface SpaceCopy {
8
+ /** the origin of the second provider (`https://<account>.r2.cloudflarestorage.com`), or `endpointSecret` */
9
+ endpoint?: string
10
+ /** the secret whose value is that origin, when the origin names an account */
11
+ endpointSecret?: string
12
+ bucket: string
13
+ /** `auto` at R2 */
14
+ region: string
15
+ /** the bucket in the path, not the host: an account wide origin (R2) wants it */
16
+ path?: boolean
17
+ /** the secret whose value is `KEY:SECRET`, read through `credsReadCommand` */
18
+ secret: string
19
+ }
20
+
21
+ /** the copy's own objects, never copied from the Space: a Space key under it is refused */
22
+ export const SNAPSHOTS = '_snapshots/'
23
+
24
+ export type CopyEnds = { from: SpaceConfig; to: SpaceConfig; skip: string[] }
25
+
26
+ /** the Space and its second place, both signed, and the prefixes a copy never mirrors (the hq's Litestream folder,
27
+ * rewritten as the hq writes: its nightly snapshot is copied instead); or why there is none */
28
+ export async function houseCopy(cwd: string = process.cwd()): Promise<CopyEnds | { why: string; configured: boolean }> {
29
+ // the Space's own switch: off, neither end is read, no secret either
30
+ if (process.env.SHIPKIT_SPACES === 'off') return { why: 'SHIPKIT_SPACES=off', configured: false }
31
+ try {
32
+ const { houseRootOf } = await import('../../home/home-start.ts')
33
+ const { loadRepoConfig } = await import('../../repo-config.ts')
34
+ const { readThrough } = await import('../../secrets/read.ts')
35
+ const house = houseRootOf(cwd)
36
+ if (!house) return { why: `no house repo seen from ${cwd}`, configured: false }
37
+ const c = await loadRepoConfig(house)
38
+ const copy = c.serve?.spaceCopy
39
+ if (!copy) return { why: `the house config (${house}) names no serve.spaceCopy: the Space has no second place`, configured: false }
40
+ if (!c.credsReadCommand) return { why: `the house config (${house}) declares no credsReadCommand to read ${copy.secret}`, configured: true }
41
+ const read = async (name: string): Promise<string | { why: string }> => {
42
+ try {
43
+ return await readThrough(c.credsReadCommand!, name)
44
+ } catch (e) {
45
+ return { why: `the secret ${name}: ${(e as Error).message}` }
46
+ }
47
+ }
48
+ const pair = await read(copy.secret)
49
+ if (typeof pair !== 'string') return { ...pair, configured: true }
50
+ const endpoint = copy.endpoint ?? (copy.endpointSecret ? await read(copy.endpointSecret) : { why: 'serve.spaceCopy names neither endpoint nor endpointSecret' })
51
+ if (typeof endpoint !== 'string') return { ...endpoint, configured: true }
52
+ const to = copyConfig(copy, endpoint, pair)
53
+ if ('why' in to) return { ...to, configured: true }
54
+ const from = await houseSpaceConfig()
55
+ if (!from.config) return { why: `the Space itself: ${from.why}`, configured: true }
56
+ const replica = c.serve?.hqReplica
57
+ const skip = replica && replica.bucket === from.config.bucket ? [`${(replica.path ?? 'hq').replace(/\/$/, '')}/`] : []
58
+ if (from.config.bucket === to.bucket && new URL(from.config.endpoint).host === new URL(to.endpoint).host) return { why: 'serve.spaceCopy names the Space itself: a copy in the same place is no second copy', configured: true }
59
+ return { from: from.config, to, skip }
60
+ } catch (e) {
61
+ return { why: `the house config does not load: ${(e as Error).message}`, configured: false }
62
+ }
63
+ }
64
+
65
+ /** the second place as a config the Space's calls sign with */
66
+ export function copyConfig(copy: SpaceCopy, endpoint: string, pair: string): SpaceConfig | { why: string } {
67
+ const at = pair.indexOf(':')
68
+ if (at <= 0) return { why: `the secret ${copy.secret} is no KEY:SECRET pair` }
69
+ let origin: URL
70
+ try {
71
+ origin = new URL(endpoint.trim())
72
+ } catch {
73
+ return { why: `the endpoint of serve.spaceCopy is no URL` }
74
+ }
75
+ if (origin.protocol !== 'https:' && origin.hostname !== '127.0.0.1' && origin.hostname !== 'localhost') return { why: 'the endpoint of serve.spaceCopy is not https' }
76
+ return { endpoint: origin.origin, bucket: copy.bucket, region: copy.region, ...(copy.path === true ? { path: true } : {}), cdn: null, creds: { accessKeyId: pair.slice(0, at), secretAccessKey: pair.slice(at + 1) } }
77
+ }
@@ -0,0 +1,194 @@
1
+ // a run of the copy of the Space (wiki tools/shipkit/media-store.md, The second copy): the Space listed once, page by
2
+ // page, into the copy's table; every key it lists and the copy lacks streamed over, the oldest first, a few at a time,
3
+ // until the run's budget of bytes or time. What the run did is in the table, so a run that stops is taken up by the
4
+ // next. A key the copy holds with other bytes is never overwritten. Nothing here deletes, at either end
5
+ import type { Database } from 'bun:sqlite'
6
+ import { type SpaceConfig, signedFetch } from '../space.ts'
7
+ import { SNAPSHOTS } from './config.ts'
8
+ import { metaGet, metaSet, takeLock } from './store.ts'
9
+ import { copyOne, type One, type Pace } from './stream.ts'
10
+
11
+ export const unxml = (s: string): string => s.replace(/&(?:#(\d+)|#x([0-9a-f]+)|(amp|lt|gt|quot|apos));/gi, (_, d: string, x: string, n: string) => (d ? String.fromCodePoint(Number(d)) : x ? String.fromCodePoint(parseInt(x, 16)) : ({ amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" } as Record<string, string>)[n.toLowerCase()]!))
12
+
13
+ /** one listing call of a bucket (`q` its query: a list, its versions, its uploads), its answer's text. A call that
14
+ * fails is tried again twice, a 4xx never */
15
+ export async function listCall(c: SpaceConfig, q: Record<string, string>, pace?: Pace): Promise<string> {
16
+ for (let i = 0; ; i++) {
17
+ const r = await signedFetch(c, 'GET', null, q).catch((e: Error) => e)
18
+ if (!(r instanceof Error) && r.ok) return r.text()
19
+ const why = r instanceof Error ? r.message : `${r.status} ${/<Code>([^<]+)<\/Code>/.exec(await r.text())?.[1] ?? ''}`.trim()
20
+ if (i >= 2 || (!(r instanceof Error) && r.status < 500)) throw new Error(`the listing of ${c.bucket} failed: ${why}`)
21
+ await Bun.sleep((pace?.backoffMs ?? 300) * 2 ** i)
22
+ }
23
+ }
24
+
25
+ /** the text of an element of an answer, its entities read, null when it holds none */
26
+ export const tagOf = (xml: string, name: string): string | null => {
27
+ const m = new RegExp(`<${name}>([\\s\\S]*?)</${name}>`).exec(xml)
28
+ return m == null ? null : unxml(m[1]!)
29
+ }
30
+
31
+ /** a time the bucket writes (LastModified), in ms; null when it gives none it can read */
32
+ export const timeOf = (text: string | null): number | null => (text == null ? null : Date.parse(text) || null)
33
+
34
+ /** every object of a bucket, a page of at most 1,000 at a time handed to `page` (ListObjectsV2): never the whole
35
+ * listing in memory. `modified` is the bucket's own date of the object */
36
+ export async function listPages(c: SpaceConfig, page: (rows: { key: string; size: number; modified: number | null }[]) => void, o: { prefix?: string; pace?: Pace } = {}): Promise<number> {
37
+ let token: string | null = null
38
+ let n = 0
39
+ do {
40
+ const q: Record<string, string> = { 'list-type': '2', 'max-keys': '1000', ...(o.prefix ? { prefix: o.prefix } : {}), ...(token ? { 'continuation-token': token } : {}) }
41
+ const text = await listCall(c, q, o.pace)
42
+ const rows = [...text.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)].map((m) => ({ key: tagOf(m[1]!, 'Key') ?? '', size: Number(/<Size>(\d+)<\/Size>/.exec(m[1]!)?.[1] ?? -1), modified: timeOf(tagOf(m[1]!, 'LastModified')) }))
43
+ if (rows.some((r) => r.key === '' || r.size < 0)) throw new Error(`the listing of ${c.bucket} holds a row with no key or size`)
44
+ page(rows)
45
+ n += rows.length
46
+ token = /<IsTruncated>true<\/IsTruncated>/.test(text) ? (tagOf(text, 'NextContinuationToken') ?? '') : null
47
+ if (token === '') throw new Error(`the listing of ${c.bucket} says more and names no next page`)
48
+ } while (token)
49
+ return n
50
+ }
51
+
52
+ export type Budget = { bytes: number; ms: number }
53
+ /** a night of the daemon: under its kill at 60 min */
54
+ export const NIGHT: Budget = { bytes: 20e9, ms: 45 * 60_000 }
55
+
56
+ export type Run = {
57
+ at: number
58
+ ms: number
59
+ listed: number
60
+ /** keys of the Space the copy held already, by this table */
61
+ held: number
62
+ copied: number
63
+ bytes: number
64
+ there: number
65
+ conflicts: { key: string; why: string }[]
66
+ failed: { key: string; why: string }[]
67
+ gone: number
68
+ /** keys left for the next run: the budget ran out, or the run was stopped */
69
+ left: number
70
+ leftBytes: number
71
+ skipped: number
72
+ stopped: string | null
73
+ }
74
+
75
+ export const RUN_KEY = 'last-run'
76
+ const FAILS_IN_A_ROW = 10
77
+
78
+ /** the copy listed once into the table, when the table never saw it: a lost file is known again, and nothing the copy
79
+ * holds is sent twice */
80
+ function inventory(db: Database, to: SpaceConfig, now: number): Promise<number> {
81
+ const up = db.query('insert into objects (key, size, first_seen, listed, copied, there) values (?1, ?2, ?3, 0, ?3, ?2) on conflict (key) do update set there = excluded.there, copied = coalesce(objects.copied, excluded.copied)')
82
+ return listPages(to, (rows) => db.transaction(() => { for (const r of rows) if (!r.key.startsWith(SNAPSHOTS)) up.run(r.key, r.size, now) })())
83
+ }
84
+
85
+ /** one run: the lock taken or refused, the Space listed, what lacks copied within the budget */
86
+ export async function copyRun(o: { from: SpaceConfig; to: SpaceConfig; db: Database; skip?: string[]; budget?: Budget; jobs?: number; dry?: boolean; signal?: AbortSignal; pace?: Pace; now?: () => number; clock?: () => number; print?: (l: string) => void; onOne?: (r: One) => void }): Promise<Run | { refused: string }> {
87
+ const now = o.now ?? Date.now
88
+ const clock = o.clock ?? (() => performance.now())
89
+ const t0 = clock()
90
+ const at = now()
91
+ const budget = o.budget ?? NIGHT
92
+ const lock = takeLock(o.db, { now: at })
93
+ if (!lock.ok) return { refused: `a copy runs already (pid ${lock.pid}, since ${new Date(lock.at).toISOString()}): one at a time` }
94
+ const run: Run = { at, ms: 0, listed: 0, held: 0, copied: 0, bytes: 0, there: 0, conflicts: [], failed: [], gone: 0, left: 0, leftBytes: 0, skipped: 0, stopped: null }
95
+ try {
96
+ const db = o.db
97
+ if (metaGet(db, 'inventory') == null) {
98
+ const n = await inventory(db, o.to, at)
99
+ metaSet(db, 'inventory', String(at))
100
+ o.print?.(`the copy listed once: it holds ${n} ${n === 1 ? 'object' : 'objects'}`)
101
+ }
102
+ const skip = [...(o.skip ?? []), SNAPSHOTS]
103
+ // a key whose size moved since the copy took it: the Space's bytes changed under one name
104
+ const seen = db.query('insert into objects (key, size, first_seen, listed) values (?1, ?2, ?3, ?3) on conflict (key) do update set listed = excluded.listed, conflict = case when objects.copied is not null and objects.size != excluded.size then ?4 || excluded.size || \' bytes, the copy holds \' || objects.size else objects.conflict end, size = case when objects.copied is null then excluded.size else objects.size end')
105
+ run.listed = await listPages(o.from, (rows) =>
106
+ db.transaction(() => {
107
+ for (const r of rows) {
108
+ if (skip.some((p) => r.key.startsWith(p))) {
109
+ run.skipped++
110
+ continue
111
+ }
112
+ seen.run(r.key, r.size, at, 'the Space now lists ')
113
+ }
114
+ })(),
115
+ )
116
+ run.listed -= run.skipped
117
+ run.held = (db.query('select count(*) as n from objects where listed = ? and copied is not null and conflict is null').get(at) as { n: number }).n
118
+ const todo = db.query('select key, size from objects where listed = ? and copied is null and conflict is null order by first_seen, key limit 500')
119
+ const mark = {
120
+ copied: db.query('update objects set copied = ?, there = size, error = null where key = ?'),
121
+ conflict: db.query('update objects set conflict = ?, there = ? where key = ?'),
122
+ failed: db.query('update objects set tries = tries + 1, error = ? where key = ?'),
123
+ gone: db.query('update objects set listed = 0 where key = ?'),
124
+ }
125
+ const left = (): { n: number; bytes: number } => db.query('select count(*) as n, coalesce(sum(size), 0) as bytes from objects where listed = ? and copied is null and conflict is null').get(at) as { n: number; bytes: number }
126
+ if (o.dry === true) {
127
+ const l = left()
128
+ return { ...run, left: l.n, leftBytes: l.bytes, stopped: 'dry: nothing sent' }
129
+ }
130
+ const failedNow = new Set<string>()
131
+ let sent = 0
132
+ // the copy refusing object after object is the copy, not the objects: the run stops and says the first answer
133
+ let inARow = 0
134
+ const over = (): string | null => (o.signal?.aborted ? 'stopped' : inARow >= FAILS_IN_A_ROW ? `${inARow} objects failed in a row, the first: ${run.failed.at(-inARow)?.why ?? ''}` : sent >= budget.bytes ? `the budget of ${budget.bytes >= 1e9 ? `${(budget.bytes / 1e9).toFixed(1)} GB` : `${Math.round(budget.bytes / 1e6)} MB`}` : clock() - t0 >= budget.ms ? `the budget of ${Math.round(budget.ms / 60_000)} min` : null)
135
+ const note = (r: One): void => {
136
+ o.onOne?.(r)
137
+ inARow = r.outcome === 'failed' ? inARow + 1 : 0
138
+ if (r.outcome === 'copied') {
139
+ run.copied++
140
+ run.bytes += r.bytes
141
+ mark.copied.run(now(), r.key)
142
+ } else if (r.outcome === 'there') {
143
+ run.there++
144
+ mark.copied.run(now(), r.key)
145
+ } else if (r.outcome === 'conflict') {
146
+ mark.conflict.run(r.why ?? 'other bytes', r.there ?? null, r.key)
147
+ } else if (r.outcome === 'gone') {
148
+ run.gone++
149
+ mark.gone.run(r.key)
150
+ } else {
151
+ failedNow.add(r.key)
152
+ run.failed.push({ key: r.key, why: r.why ?? '' })
153
+ mark.failed.run(r.why ?? '', r.key)
154
+ }
155
+ }
156
+ for (;;) {
157
+ const batch = (todo.all(at) as { key: string; size: number }[]).filter((r) => !failedNow.has(r.key))
158
+ if (batch.length === 0 || over() != null) break
159
+ let i = 0
160
+ const worker = async (): Promise<void> => {
161
+ while (i < batch.length && over() == null) {
162
+ const b = batch[i++]!
163
+ sent += b.size
164
+ note(await copyOne(o.from, o.to, b.key, b.size, { ...(o.signal ? { signal: o.signal } : {}), ...(o.pace ? { pace: o.pace } : {}) }))
165
+ }
166
+ }
167
+ await Promise.all(Array.from({ length: Math.max(1, o.jobs ?? 3) }, worker))
168
+ }
169
+ run.stopped = over()
170
+ // every conflict the Space's keys hold, each run: found by the listing or by the HEAD of this run
171
+ run.conflicts = db.query('select key, conflict as why from objects where listed = ? and conflict is not null order by key').all(at) as { key: string; why: string }[]
172
+ const l = left()
173
+ run.left = l.n
174
+ run.leftBytes = l.bytes
175
+ return run
176
+ } finally {
177
+ run.ms = Math.round(clock() - t0)
178
+ if (o.dry !== true) metaSet(o.db, RUN_KEY, JSON.stringify(run))
179
+ lock.release()
180
+ }
181
+ }
182
+
183
+ /** the keys the copy holds that the Space no longer lists, from the last run's listing: what a purge of versions or
184
+ * an owner's forget took from the Space. A list only: the copy never deletes by itself */
185
+ export function onlyAtCopy(db: Database): { key: string; size: number }[] {
186
+ const last = lastRun(db)
187
+ if (last == null) return []
188
+ return db.query('select key, size from objects where copied is not null and listed != ? order by key').all(last.at) as { key: string; size: number }[]
189
+ }
190
+
191
+ export const lastRun = (db: Database): Run | null => {
192
+ const v = metaGet(db, RUN_KEY)
193
+ return v == null ? null : (JSON.parse(v) as Run)
194
+ }
@@ -0,0 +1,43 @@
1
+ // the copy bucket's lifecycle rule (wiki tools/shipkit/media-store.md, The second copy): the provider, not shipkit,
2
+ // drops a snapshot after SNAPSHOT_DAYS and an upload left unfinished after a day, so no delete call enters shipkit.
3
+ // Its own rules are added beside the ones the bucket holds, never in their place
4
+ import { type SpaceConfig, signedCall } from '../space.ts'
5
+ import { SNAPSHOTS } from './config.ts'
6
+ import { SNAPSHOT_DAYS } from './snapshot.ts'
7
+
8
+ const OURS = ['shipkit-snapshots', 'shipkit-unfinished-uploads']
9
+
10
+ export const ourRules = (): string =>
11
+ `<Rule><ID>${OURS[0]}</ID><Status>Enabled</Status><Filter><Prefix>${SNAPSHOTS}</Prefix></Filter><Expiration><Days>${SNAPSHOT_DAYS}</Days></Expiration></Rule>` +
12
+ `<Rule><ID>${OURS[1]}</ID><Status>Enabled</Status><Filter><Prefix></Prefix></Filter><AbortIncompleteMultipartUpload><DaysAfterInitiation>1</DaysAfterInitiation></AbortIncompleteMultipartUpload></Rule>`
13
+
14
+ const rulesOf = (xml: string): string[] => [...xml.matchAll(/<Rule>[\s\S]*?<\/Rule>/g)].map((m) => m[0])
15
+ const idOf = (rule: string): string => /<ID>([^<]*)<\/ID>/.exec(rule)?.[1] ?? ''
16
+
17
+ /** the rules the copy bucket holds, null when it holds none */
18
+ export async function readLifecycle(to: SpaceConfig): Promise<string[] | null> {
19
+ try {
20
+ return rulesOf(await signedCall(to, 'GET', null, { lifecycle: '' }))
21
+ } catch (e) {
22
+ if (/NoSuchLifecycleConfiguration|: 404/.test((e as Error).message)) return null
23
+ throw e
24
+ }
25
+ }
26
+
27
+ /** ours set beside the bucket's other rules, then read back: ok when both are there */
28
+ export async function setLifecycle(to: SpaceConfig): Promise<{ ok: boolean; kept: string[]; why: string }> {
29
+ const before = (await readLifecycle(to)) ?? []
30
+ const kept = before.filter((r) => !OURS.includes(idOf(r)))
31
+ await signedCall(to, 'PUT', null, { lifecycle: '' }, `<?xml version="1.0" encoding="UTF-8"?><LifecycleConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">${kept.join('')}${ourRules()}</LifecycleConfiguration>`)
32
+ const after = (await readLifecycle(to)) ?? []
33
+ const ids = after.map(idOf)
34
+ const lack = OURS.filter((id) => !ids.includes(id))
35
+ return { ok: lack.length === 0, kept: kept.map(idOf), why: lack.length === 0 ? '' : `the bucket did not keep ${lack.join(', ')}` }
36
+ }
37
+
38
+ /** what the owner does in the provider's page when the copy's key may not set the rule (an object only key) */
39
+ export const LIFECYCLE_BY_HAND = [
40
+ `the copy's key may not set the bucket's rules: set them in the provider's page of the bucket (R2: Settings, Object lifecycle rules)`,
41
+ ` 1. a rule on the prefix ${SNAPSHOTS}: delete objects ${SNAPSHOT_DAYS} days after they are written`,
42
+ ' 2. a rule on the whole bucket: abort unfinished multipart uploads after 1 day',
43
+ ]
@@ -0,0 +1,90 @@
1
+ // a night of the second copy (wiki tools/shipkit/media-store.md, The second copy): the copy run within its budget, the
2
+ // hq's snapshot when this machine carries the hq, then the proof. What the daemon's `space copy` job and `sk space copy`
3
+ // both run. The machine's switch `space-copy` is off until the owner turns it on; the daemon looks only then
4
+ import { machineGet, machineSet } from '../../core/machine-db.ts'
5
+ import { type CopyEnds, houseCopy } from './config.ts'
6
+ import { type Budget, copyRun, NIGHT, type Run } from './copy.ts'
7
+ import { type Proof, proveCopy } from './proof.ts'
8
+ import { type Snapshot, snapshotHq } from './snapshot.ts'
9
+ import { copyDbPath, openCopyDb } from './store.ts'
10
+
11
+ const AUTO_KEY = 'space-copy'
12
+ const TRIED_KEY = 'space-copy-tried'
13
+ const NO_COPY = 'space-copy-none'
14
+ export const copyOn = (): boolean => machineGet<boolean>(AUTO_KEY) === true
15
+ export const setCopyOn = (on: boolean): boolean => machineSet(AUTO_KEY, on)
16
+
17
+ /** the night's window, local time, and the least time between two nights */
18
+ export const NIGHT_FROM_H = 1
19
+ export const NIGHT_TO_H = 6
20
+ export const NIGHT_GAP_MS = 20 * 3_600_000
21
+
22
+ /** the daemon's look: two reads of the machine db, no network */
23
+ export function copyDue(now: number): boolean {
24
+ if (!copyOn()) return false
25
+ const h = new Date(now).getHours()
26
+ if (h < NIGHT_FROM_H || h >= NIGHT_TO_H) return false
27
+ const tried = machineGet<number>(TRIED_KEY) ?? 0
28
+ // a stamp after now: the clock went back, so the night is not held for a day
29
+ return tried > now || now - tried >= NIGHT_GAP_MS
30
+ }
31
+
32
+ const many = (n: number, one: string): string => `${n} ${one}${n === 1 ? '' : 's'}`
33
+ const gb = (n: number): string => `${(n / 1e9).toFixed(n >= 1e10 ? 0 : 2)} GB`
34
+ const mins = (ms: number): string => (ms >= 60_000 ? `${Math.round(ms / 60_000)} min` : `${(ms / 1000).toFixed(1)} s`)
35
+
36
+ export function runLine(r: Run): string {
37
+ const left = r.left > 0 ? `, ${r.left} left (${gb(r.leftBytes)}) for the next run` : ', nothing left'
38
+ const stop = r.stopped && r.left > 0 ? ` (stopped by ${r.stopped})` : ''
39
+ return `${many(r.copied, 'object')} copied (${gb(r.bytes)}) in ${mins(r.ms)} of ${r.listed} the Space lists, ${r.held + r.there} already there${left}${stop}`
40
+ }
41
+
42
+ export function proofLine(p: Proof): string {
43
+ const at = p.kinds.reduce((n, k) => n + k.copy.n, 0)
44
+ const bytes = p.kinds.reduce((n, k) => n + k.copy.bytes, 0)
45
+ const snap = p.snapshot ? `, the hq's snapshot ${p.snapshot.ok ? 'restored' : 'NOT restored'}` : ''
46
+ return `${p.ok ? 'green' : 'RED'}: ${many(at, 'object')} (${gb(bytes)}) at the copy, ${p.waiting} waiting, ${p.sample.filter((s) => s.ok).length} of ${p.sample.length} sampled the same${snap}`
47
+ }
48
+
49
+ export type Night = { run: Run | null; snapshot: Snapshot | null; proof: Proof | null; refused?: string }
50
+
51
+ /** one night: the run, the hq's snapshot when `hq` is true, the proof. Each failure is a line on `printErr` */
52
+ export async function copyNight(o: { ends?: CopyEnds; budget?: Budget; jobs?: number; hq: boolean; hqDb?: string; signal?: AbortSignal; print: (l: string) => void; printErr: (l: string) => void; now?: () => number }): Promise<Night> {
53
+ const out: Night = { run: null, snapshot: null, proof: null }
54
+ const ends = o.ends ?? (await houseCopy())
55
+ if ('why' in ends) {
56
+ // said once per reason: each night is a child of its own
57
+ if (machineGet<string>(NO_COPY) !== ends.why) o.printErr(`WARN space copy: nothing copied: ${ends.why}`)
58
+ machineSet(NO_COPY, ends.why)
59
+ return { ...out, refused: ends.why }
60
+ }
61
+ machineSet(NO_COPY, '')
62
+ machineSet(TRIED_KEY, (o.now ?? Date.now)())
63
+ const db = openCopyDb(copyDbPath())
64
+ try {
65
+ const r = await copyRun({ ...ends, db, budget: o.budget ?? NIGHT, ...(o.jobs != null ? { jobs: o.jobs } : {}), ...(o.signal ? { signal: o.signal } : {}), ...(o.now ? { now: o.now } : {}), print: o.print })
66
+ if ('refused' in r) {
67
+ o.printErr(`WARN space copy: ${r.refused}`)
68
+ return { ...out, refused: r.refused }
69
+ }
70
+ out.run = r
71
+ o.print(`ok: space copy: ${runLine(r)}`)
72
+ for (const c of r.conflicts.slice(0, 3)) o.printErr(`WARN space copy: a conflict, never overwritten: ${c.key}: ${c.why}`)
73
+ if (r.failed.length > 0) o.printErr(`WARN space copy: ${r.failed.length} objects failed, tried again next run; first: ${r.failed[0]!.key}: ${r.failed[0]!.why}`)
74
+ if (o.hq && o.signal?.aborted !== true) {
75
+ try {
76
+ out.snapshot = await snapshotHq({ to: ends.to, ...(o.hqDb ? { db: o.hqDb } : {}), ...(o.now ? { now: o.now } : {}) })
77
+ o.print(`ok: space copy: the hq's snapshot ${out.snapshot.key} (${(out.snapshot.size / 1e6).toFixed(1)} MB gzipped of ${((out.snapshot.raw ?? 0) / 1e6).toFixed(1)} MB)`)
78
+ } catch (e) {
79
+ o.printErr(`WARN space copy: no snapshot of the hq: ${(e as Error).message}`)
80
+ }
81
+ }
82
+ if (o.signal?.aborted === true) return out
83
+ out.proof = await proveCopy({ ...ends, db, hq: o.hq, ...(o.now ? { now: o.now } : {}) })
84
+ if (out.proof.ok) o.print(`ok: space copy proof ${proofLine(out.proof)}`)
85
+ else for (const w of out.proof.why) o.printErr(`WARN space copy proof: ${w}`)
86
+ return out
87
+ } finally {
88
+ db.close()
89
+ }
90
+ }
@@ -0,0 +1,151 @@
1
+ // the proof of the second copy, after each run (wiki tools/shipkit/media-store.md, The second copy): the copy listed
2
+ // beside the Space's last listing, kind by kind; every key copied and now absent, every size that differs, every key
3
+ // left behind two days; a random sample read back and hashed; the hq's last snapshot restored and counted. Red is a
4
+ // reason in `why`. A key found lost is marked to go again at the next run
5
+ import type { Database } from 'bun:sqlite'
6
+ import { machineGet, machineSet } from '../../core/machine-db.ts'
7
+ import { type SpaceConfig, signedFetch } from '../space.ts'
8
+ import { SNAPSHOTS } from './config.ts'
9
+ import { lastRun, listPages } from './copy.ts'
10
+ import { lastSnapshot, restoreHq, type Snapshot } from './snapshot.ts'
11
+ import { type Pace, shaOfKey } from './stream.ts'
12
+
13
+ /** older than this, the copy or the snapshot is red */
14
+ export const STALE_MS = 2 * 86_400_000
15
+ export const SAMPLE_N = 8
16
+ export const SAMPLE_BYTES = 256 * 1024 * 1024
17
+ /** more hq snapshots than this: the lifecycle rule that keeps 30 days is not doing its work */
18
+ const SNAPSHOTS_MAX = 40
19
+
20
+ export type Side = { n: number; bytes: number }
21
+ export type Proof = {
22
+ at: number
23
+ ms: number
24
+ ok: boolean
25
+ /** each reason it is red, worst first */
26
+ why: string[]
27
+ run: { at: number; copied: number; bytes: number; left: number } | null
28
+ kinds: { kind: string; space: Side; copy: Side }[]
29
+ lost: number
30
+ differ: number
31
+ behind: number
32
+ conflicts: number
33
+ onlyAtCopy: number
34
+ /** keys of the Space's last listing the copy does not hold yet: the night's uploads, a budget run out */
35
+ waiting: number
36
+ sample: { key: string; bytes: number; ok: boolean; why?: string }[]
37
+ snapshot: { key: string; at: number; ok: boolean; why: string; ms: number } | null
38
+ snapshots: number
39
+ }
40
+
41
+ export const PROOF_KEY = 'space-copy-proof'
42
+ /** the last proof of this machine, for the database page and `sk machines`: when, the counts, the sample, the verdict */
43
+ export const lastCopyProof = (): Proof | null => machineGet<Proof>(PROOF_KEY)
44
+
45
+ const kindOf = (key: string): string => (key.includes('/') ? key.slice(0, key.indexOf('/')) : '(top)')
46
+
47
+ async function shaAt(c: SpaceConfig, key: string): Promise<{ sha: string; bytes: number } | string> {
48
+ const r = await signedFetch(c, 'GET', key, {}, { signal: AbortSignal.timeout(10 * 60_000) }).catch((e: Error) => e)
49
+ if (r instanceof Error) return r.message
50
+ if (!r.ok || r.body == null) return `${r.status}`
51
+ const h = new Bun.CryptoHasher('sha256')
52
+ let bytes = 0
53
+ for await (const chunk of r.body) {
54
+ h.update(chunk)
55
+ bytes += chunk.length
56
+ }
57
+ return { sha: h.digest('hex'), bytes }
58
+ }
59
+
60
+ export async function proveCopy(o: { from: SpaceConfig; to: SpaceConfig; db: Database; now?: () => number; sample?: number; sampleBytes?: number; snap?: Snapshot | null; hq?: boolean; pace?: Pace; keep?: boolean }): Promise<Proof> {
61
+ const now = (o.now ?? Date.now)()
62
+ const t0 = performance.now()
63
+ const db = o.db
64
+ const why: string[] = []
65
+ const last = lastRun(db)
66
+ const proof: Proof = { at: now, ms: 0, ok: false, why, run: last ? { at: last.at, copied: last.copied, bytes: last.bytes, left: last.left } : null, kinds: [], lost: 0, differ: 0, behind: 0, conflicts: 0, onlyAtCopy: 0, waiting: 0, sample: [], snapshot: null, snapshots: 0 }
67
+ const finish = (): Proof => {
68
+ proof.ms = Math.round(performance.now() - t0)
69
+ proof.ok = why.length === 0
70
+ if (o.keep !== false) machineSet(PROOF_KEY, proof)
71
+ return proof
72
+ }
73
+ if (last == null) {
74
+ why.push('no copy has run yet: sk space copy')
75
+ return finish()
76
+ }
77
+ if (last.at > now + 60_000) why.push(`the last copy is dated ${new Date(last.at).toISOString()}, after now: the clock moved back`)
78
+ else if (now - last.at > STALE_MS) why.push(`the last copy ran ${((now - last.at) / 86_400_000).toFixed(1)} days ago`)
79
+ try {
80
+ db.exec('create temp table if not exists atcopy (key text primary key, size integer not null) without rowid; delete from atcopy')
81
+ const put = db.query('insert or replace into temp.atcopy (key, size) values (?, ?)')
82
+ await listPages(o.to, (rows) => db.transaction(() => { for (const r of rows) put.run(r.key, r.size) })(), o.pace ? { pace: o.pace } : {})
83
+ proof.snapshots = (db.query("select count(*) as n from temp.atcopy where key like ? escape '\\'").get(`${SNAPSHOTS.replace(/_/g, '\\_')}hq/%`) as { n: number }).n
84
+ db.exec(`delete from temp.atcopy where substr(key, 1, ${SNAPSHOTS.length}) = '${SNAPSHOTS}'`)
85
+ const at = last.at
86
+ const sides = new Map<string, { space: Side; copy: Side }>()
87
+ const side = (k: string) => sides.get(k) ?? (sides.set(k, { space: { n: 0, bytes: 0 }, copy: { n: 0, bytes: 0 } }), sides.get(k)!)
88
+ for (const r of db.query('select key, size from objects where listed = ?').iterate(at) as Iterable<{ key: string; size: number }>) {
89
+ const s = side(kindOf(r.key)).space
90
+ s.n++
91
+ s.bytes += r.size
92
+ }
93
+ for (const r of db.query('select key, size from temp.atcopy').iterate() as Iterable<{ key: string; size: number }>) {
94
+ const s = side(kindOf(r.key)).copy
95
+ s.n++
96
+ s.bytes += r.size
97
+ }
98
+ proof.kinds = [...sides.entries()].map(([kind, v]) => ({ kind, ...v })).sort((a, b) => b.space.bytes - a.space.bytes)
99
+ const lost = db.query('select o.key from objects o left join temp.atcopy c on c.key = o.key where o.listed = ? and o.copied is not null and c.key is null').all(at) as { key: string }[]
100
+ proof.lost = lost.length
101
+ if (lost.length > 0) {
102
+ why.push(`${lost.length} ${lost.length === 1 ? 'object copied is' : 'objects copied are'} no longer at the copy (first: ${lost[0]!.key}): sent again at the next run`)
103
+ const again = db.query('update objects set copied = null, there = null where key = ?')
104
+ db.transaction(() => { for (const l of lost) again.run(l.key) })()
105
+ }
106
+ proof.differ = (db.query('select count(*) as n from objects o join temp.atcopy c on c.key = o.key where o.listed = ? and o.conflict is null and c.size != o.size').get(at) as { n: number }).n
107
+ if (proof.differ > 0) why.push(`${proof.differ} objects have another size at the copy than in the Space`)
108
+ proof.conflicts = (db.query('select count(*) as n from objects where listed = ? and conflict is not null').get(at) as { n: number }).n
109
+ if (proof.conflicts > 0) {
110
+ const first = db.query('select key, conflict from objects where listed = ? and conflict is not null order by key limit 1').get(at) as { key: string; conflict: string }
111
+ why.push(`${proof.conflicts} ${proof.conflicts === 1 ? 'conflict' : 'conflicts'}, never overwritten (first: ${first.key}: ${first.conflict}): sk space copy --dry lists them`)
112
+ }
113
+ proof.behind = (db.query('select count(*) as n from objects where listed = ? and copied is null and conflict is null and first_seen < ?').get(at, now - STALE_MS) as { n: number }).n
114
+ if (proof.behind > 0) why.push(`${proof.behind} objects of the Space wait for the copy since more than 2 days`)
115
+ proof.onlyAtCopy = (db.query('select count(*) as n from temp.atcopy c left join objects o on o.key = c.key and o.listed = ? where o.key is null').get(at) as { n: number }).n
116
+ proof.waiting = (db.query('select count(*) as n from objects where listed = ? and copied is null and conflict is null').get(at) as { n: number }).n
117
+ if (proof.snapshots > SNAPSHOTS_MAX) why.push(`${proof.snapshots} hq snapshots at the copy: the lifecycle rule that keeps 30 days is missing (sk space setup)`)
118
+ const picks = db.query('select key, size from objects where listed = ? and copied is not null and conflict is null order by random() limit 64').all(at) as { key: string; size: number }[]
119
+ let budget = o.sampleBytes ?? SAMPLE_BYTES
120
+ for (const p of picks) {
121
+ if (proof.sample.length >= (o.sample ?? SAMPLE_N)) break
122
+ if (p.size > budget) continue
123
+ budget -= p.size
124
+ const want = shaOfKey(p.key)
125
+ const got = await shaAt(o.to, p.key)
126
+ if (typeof got === 'string') {
127
+ proof.sample.push({ key: p.key, bytes: p.size, ok: false, why: `the copy does not read it back: ${got}` })
128
+ continue
129
+ }
130
+ const ref = want ?? (await shaAt(o.from, p.key))
131
+ const refSha = typeof ref === 'string' && want == null ? null : typeof ref === 'string' ? ref : ref.sha
132
+ if (refSha == null) proof.sample.push({ key: p.key, bytes: p.size, ok: true, why: 'the Space did not read back to compare: its size alone' })
133
+ else if (got.sha !== refSha || got.bytes !== p.size) proof.sample.push({ key: p.key, bytes: got.bytes, ok: false, why: `the copy's bytes hash to ${got.sha.slice(0, 12)}, ${want != null ? 'the key names' : "the Space's hash to"} ${refSha.slice(0, 12)}` })
134
+ else proof.sample.push({ key: p.key, bytes: got.bytes, ok: true })
135
+ }
136
+ const bad = proof.sample.filter((s) => !s.ok)
137
+ if (bad.length > 0) why.push(`${bad.length} of ${proof.sample.length} objects sampled differ at the copy (first: ${bad[0]!.key}: ${bad[0]!.why})`)
138
+ } catch (e) {
139
+ why.push(`the copy was not read: ${(e as Error).message}`)
140
+ }
141
+ // a machine that carries no hq has no snapshot to prove
142
+ const snap = o.hq === false ? null : o.snap === undefined ? lastSnapshot() : o.snap
143
+ if (snap == null && o.hq !== false) why.push("the hq has no snapshot at the copy yet")
144
+ else if (snap != null) {
145
+ const r = await restoreHq({ to: o.to, snap, ...(o.pace ? { pace: o.pace } : {}) })
146
+ proof.snapshot = { key: snap.key, at: snap.at, ok: r.ok, why: r.why, ms: r.ms }
147
+ if (!r.ok) why.push(`the hq's snapshot does not restore: ${r.why}`)
148
+ else if (now - snap.at > STALE_MS) why.push(`the hq's last snapshot is ${((now - snap.at) / 86_400_000).toFixed(1)} days old`)
149
+ }
150
+ return finish()
151
+ }