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,152 @@
1
+ // the snapshots the second place keeps beside its copy of the Space (wiki tools/shipkit/media-store.md, The second
2
+ // copy): the hq's database once a night, consistent (`vacuum into`), gzipped by stream; and any sealed file a caller
3
+ // hands by path (the vault's), its bytes sent as they are and never read for what they hold. Each under `_snapshots/`,
4
+ // kept 30 days by the copy bucket's lifecycle rule: nothing here deletes
5
+ import { Database } from 'bun:sqlite'
6
+ import { mkdtempSync, rmSync, statSync } from 'node:fs'
7
+ import { tmpdir } from 'node:os'
8
+ import { basename, join } from 'node:path'
9
+ import { machineGet, machineSet } from '../../core/machine-db.ts'
10
+ import { hqDbPath } from '../../hq/hq-db.ts'
11
+ import { HQ_MAX_BYTES } from '../../hq/hq-store.ts'
12
+ import { heldRows, missingIn } from '../../hq/replica.ts'
13
+ import { type SpaceConfig, signedFetch } from '../space.ts'
14
+ import { SNAPSHOTS } from './config.ts'
15
+ import { headSize, IDLE_MS, type Pace, putStream } from './stream.ts'
16
+
17
+ /** how long the lifecycle rule keeps a snapshot */
18
+ export const SNAPSHOT_DAYS = 30
19
+
20
+ export type Snapshot = {
21
+ key: string
22
+ at: number
23
+ /** the bytes at the copy (gzipped for the hq) and their sha256 */
24
+ size: number
25
+ sha: string
26
+ /** the hq's: the file's own size, its rows a table, and the rows of the live file it lacks (none: it holds all) */
27
+ raw?: number
28
+ tables?: Record<string, number>
29
+ missing?: { table: string; n: number }[]
30
+ }
31
+
32
+ export const SNAPSHOT_KEY = 'space-copy-snapshot'
33
+ export const lastSnapshot = (): Snapshot | null => machineGet<Snapshot>(SNAPSHOT_KEY)
34
+
35
+ const stampOf = (at: number): string => new Date(at).toISOString().replace(/[-:]|\.\d{3}/g, '')
36
+
37
+ const counts = (db: Database, tables: Iterable<string>): Record<string, number> => {
38
+ const out: Record<string, number> = {}
39
+ for (const t of tables) {
40
+ const there = db.query("select 1 from sqlite_master where type = 'table' and name = ?").get(t) != null
41
+ out[t] = there ? (db.query(`select count(*) as n from "${t}"`).get() as { n: number }).n : 0
42
+ }
43
+ return out
44
+ }
45
+
46
+ /** the hq's file to the copy: every row of the live file noted, the file copied consistent into a scratch folder (the
47
+ * one disk this spends: the file's size, under its cap), that copy checked to hold every noted row, then gzipped by
48
+ * stream under `_snapshots/hq/<stamp>.sqlite.gz`. The live file is only read */
49
+ export async function snapshotHq(o: { to: SpaceConfig; db?: string; now?: () => number; pace?: Pace; keep?: boolean }): Promise<Snapshot> {
50
+ const file = o.db ?? hqDbPath()
51
+ const at = (o.now ?? Date.now)()
52
+ const size = statSync(file, { throwIfNoEntry: false })?.size
53
+ if (size == null) throw new Error(`the hq's file is not there (${file})`)
54
+ if (size > HQ_MAX_BYTES) throw new Error(`the hq's file is ${(size / 1e6).toFixed(0)} MB, past its cap of ${HQ_MAX_BYTES / 1e6} MB: no snapshot until it is swept`)
55
+ const dir = mkdtempSync(join(tmpdir(), 'sk-hq-snapshot-'))
56
+ try {
57
+ const copy = join(dir, 'hq.sqlite')
58
+ const live = new Database(file, { readonly: true })
59
+ let held: Map<string, Set<string>>
60
+ try {
61
+ held = heldRows(live)
62
+ live.exec(`vacuum into '${copy.replace(/'/g, "''")}'`)
63
+ } finally {
64
+ live.close()
65
+ }
66
+ const snap = new Database(copy, { readonly: true })
67
+ let tables: Record<string, number>
68
+ let missing: { table: string; n: number }[]
69
+ try {
70
+ const sound = (snap.query('pragma integrity_check').get() as Record<string, string>)['integrity_check']
71
+ if (sound !== 'ok') throw new Error(`the hq's snapshot is not sound: ${sound}`)
72
+ missing = missingIn(held, snap)
73
+ tables = counts(snap, held.keys())
74
+ } finally {
75
+ snap.close()
76
+ }
77
+ if (missing.length > 0) throw new Error(`the hq's snapshot lacks rows of the live file: ${missing.map((m) => `${m.n} of ${m.table}`).join(', ')}`)
78
+ const key = `${SNAPSHOTS}hq/${stampOf(at)}.sqlite.gz`
79
+ const sent = await putStream(o.to, key, Bun.file(copy).stream().pipeThrough(new CompressionStream('gzip')), { type: 'application/gzip', ...(o.pace ? { pace: o.pace } : {}) })
80
+ const out: Snapshot = { key, at, size: sent.size, sha: sent.sha, raw: statSync(copy).size, tables, missing }
81
+ if (o.keep !== false) machineSet(SNAPSHOT_KEY, out)
82
+ return out
83
+ } finally {
84
+ rmSync(dir, { recursive: true, force: true })
85
+ }
86
+ }
87
+
88
+ /** a label the copy keeps a file under: letters, digits and dashes; `hq` is the hq's own */
89
+ const LABEL = /^[a-z0-9][a-z0-9-]{0,31}$/
90
+
91
+ /** a sealed file to the copy, its bytes as they are, under `_snapshots/<label>/<stamp>-<its name>`: what the vault's
92
+ * nightly snapshot calls. Its content is never read for what it holds, only streamed and hashed */
93
+ export async function snapshotFile(o: { to: SpaceConfig; file: string; label: string; now?: () => number; pace?: Pace }): Promise<Snapshot> {
94
+ if (!LABEL.test(o.label) || o.label === 'hq') throw new Error(`--label ${JSON.stringify(o.label)}: letters, digits and dashes, and not hq (the hq's own)`)
95
+ const st = statSync(o.file, { throwIfNoEntry: false })
96
+ if (st == null || !st.isFile()) throw new Error(`no file ${o.file}`)
97
+ const at = (o.now ?? Date.now)()
98
+ const name = basename(o.file).replace(/[^A-Za-z0-9._-]/g, '_')
99
+ const key = `${SNAPSHOTS}${o.label}/${stampOf(at)}-${name}`
100
+ const sent = await putStream(o.to, key, Bun.file(o.file).stream(), { max: st.size, check: (got) => (got.size !== st.size ? `${o.file} changed while it went up: ${got.size} bytes of ${st.size}` : null), ...(o.pace ? { pace: o.pace } : {}) })
101
+ return { key, at, size: sent.size, sha: sent.sha }
102
+ }
103
+
104
+ export type Restored = { ok: boolean; ms: number; tables: Record<string, number>; why: string }
105
+
106
+ /** the hq's snapshot read back from the copy into a scratch folder: its bytes hashed against the sha it went up with,
107
+ * gunzipped by stream, the file checked sound, and its rows a table counted against the ones it held when it went */
108
+ export async function restoreHq(o: { to: SpaceConfig; snap: Snapshot; pace?: Pace }): Promise<Restored> {
109
+ const t0 = performance.now()
110
+ const done = (ok: boolean, tables: Record<string, number>, why: string): Restored => ({ ok, ms: Math.round(performance.now() - t0), tables, why })
111
+ const dir = mkdtempSync(join(tmpdir(), 'sk-hq-restore-'))
112
+ try {
113
+ const there = await headSize(o.to, o.snap.key, o.pace)
114
+ if (there == null) return done(false, {}, `the snapshot ${o.snap.key} is not at the copy`)
115
+ if (there !== o.snap.size) return done(false, {}, `the snapshot at the copy is ${there} bytes, it went up as ${o.snap.size}`)
116
+ const r = await signedFetch(o.to, 'GET', o.snap.key, {})
117
+ if (!r.ok || r.body == null) return done(false, {}, `the snapshot ${o.snap.key} does not read back: ${r.status}`)
118
+ const h = new Bun.CryptoHasher('sha256')
119
+ let n = 0
120
+ const idle = o.pace?.idleMs ?? IDLE_MS
121
+ const hashed = r.body.pipeThrough(
122
+ new TransformStream<Uint8Array<ArrayBuffer>, BufferSource>({
123
+ transform(chunk, c) {
124
+ h.update(chunk)
125
+ n += chunk.length
126
+ c.enqueue(chunk)
127
+ },
128
+ }),
129
+ )
130
+ const out = join(dir, 'hq.sqlite')
131
+ const write = Bun.write(out, new Response(hashed.pipeThrough(new DecompressionStream('gzip'))))
132
+ let quiet: ReturnType<typeof setTimeout> | undefined
133
+ await Promise.race([write, new Promise<never>((_, no) => (quiet = setTimeout(() => no(new Error(`the snapshot did not read back in ${idle} ms`)), idle * 10)))]).finally(() => clearTimeout(quiet))
134
+ const sha = h.digest('hex')
135
+ if (n !== o.snap.size || sha !== o.snap.sha) return done(false, {}, `the snapshot at the copy is ${n} bytes hashing to ${sha.slice(0, 12)}, it went up as ${o.snap.size} hashing to ${o.snap.sha.slice(0, 12)}`)
136
+ const db = new Database(out, { readonly: true })
137
+ try {
138
+ const sound = (db.query('pragma integrity_check').get() as Record<string, string>)['integrity_check']
139
+ if (sound !== 'ok') return done(false, {}, `the restored snapshot is not sound: ${sound}`)
140
+ const want = o.snap.tables ?? {}
141
+ const got = counts(db, Object.keys(want))
142
+ const off = Object.keys(want).filter((t) => got[t] !== want[t])
143
+ return done(off.length === 0, got, off.length === 0 ? '' : `the restored snapshot holds ${off.map((t) => `${got[t]} of ${t} (it went with ${want[t]})`).join(', ')}`)
144
+ } finally {
145
+ db.close()
146
+ }
147
+ } catch (e) {
148
+ return done(false, {}, `the restore broke: ${(e as Error).message}`)
149
+ } finally {
150
+ rmSync(dir, { recursive: true, force: true })
151
+ }
152
+ }
@@ -0,0 +1,62 @@
1
+ // what the copy of the Space knows between two runs (wiki tools/shipkit/media-store.md, The second copy): one sqlite
2
+ // file of its own in the home's state folder. It is DERIVED: lost, the next run lists the copy once and knows again
3
+ // what it holds. One row a key of the Space, about 120 bytes, and the lock that keeps a second run out
4
+ import { Database } from 'bun:sqlite'
5
+ import { mkdirSync } from 'node:fs'
6
+ import { dirname, join } from 'node:path'
7
+ import { homeDir } from '../../home/home-paths.ts'
8
+ import { ensureWal, migrateTo } from '../../ledger/db.ts'
9
+
10
+ export const COPY_DB_ENV = 'SHIPKIT_SPACE_COPY_DB'
11
+ export const copyDbPath = (): string => process.env[COPY_DB_ENV] || join(homeDir(), 'space-copy.sqlite')
12
+
13
+ /** its cap as a store of the machine: 64 MB holds about 500,000 keys */
14
+ export const COPY_DB_MAX_BYTES = 64 * 1024 * 1024
15
+
16
+ export const COPY_DB_VERSION = 1
17
+
18
+ /** `listed`: the run that last saw the key in the Space; `copied`: when the copy was seen to hold it; `there`: its size
19
+ * at the copy as last seen; `conflict`: the copy holds the key with other bytes, never overwritten */
20
+ const V1 = `
21
+ create table if not exists objects (key text primary key, size integer not null, first_seen integer not null, listed integer not null, copied integer, there integer, conflict text, tries integer not null default 0, error text) without rowid;
22
+ create index if not exists objects_todo on objects (listed, first_seen) where copied is null;
23
+ create table if not exists lock (id integer primary key check (id = 1), pid integer not null, at integer not null);
24
+ create table if not exists meta (name text primary key, value text not null) without rowid;
25
+ `
26
+
27
+ export function openCopyDb(path: string = copyDbPath()): Database {
28
+ mkdirSync(dirname(path), { recursive: true })
29
+ const db = new Database(path, { create: true, readwrite: true })
30
+ db.exec('pragma busy_timeout = 3000')
31
+ ensureWal(db, 3000)
32
+ db.exec('pragma synchronous = NORMAL')
33
+ migrateTo(db, COPY_DB_VERSION, () => db.exec(V1))
34
+ return db
35
+ }
36
+
37
+ export const metaGet = (db: Database, name: string): string | null => (db.query('select value from meta where name = ?').get(name) as { value: string } | null)?.value ?? null
38
+ export const metaSet = (db: Database, name: string, value: string): void => void db.query('insert into meta (name, value) values (?, ?) on conflict (name) do update set value = excluded.value').run(name, value)
39
+
40
+ const aliveReal = (pid: number): boolean => {
41
+ try {
42
+ process.kill(pid, 0)
43
+ return true
44
+ } catch (e) {
45
+ return (e as { code?: string }).code === 'EPERM'
46
+ }
47
+ }
48
+
49
+ /** the run's lock: taken when no live process holds it (a run killed leaves a dead pid, taken over), else the holder.
50
+ * A pid, never a time: a clock that jumps neither frees a live lock nor holds a dead one */
51
+ export function takeLock(db: Database, o: { pid?: number; now?: number; alive?: (pid: number) => boolean } = {}): { ok: true; release: () => void } | { ok: false; pid: number; at: number } {
52
+ const pid = o.pid ?? process.pid
53
+ const alive = o.alive ?? aliveReal
54
+ const held = db.transaction(() => {
55
+ const row = db.query('select pid, at from lock where id = 1').get() as { pid: number; at: number } | null
56
+ if (row && row.pid !== pid && alive(row.pid)) return row
57
+ db.query('insert into lock (id, pid, at) values (1, ?, ?) on conflict (id) do update set pid = excluded.pid, at = excluded.at').run(pid, o.now ?? Date.now())
58
+ return null
59
+ }).immediate()
60
+ if (held) return { ok: false, pid: held.pid, at: held.at }
61
+ return { ok: true, release: () => void db.query('delete from lock where id = 1 and pid = ?').run(pid) }
62
+ }
@@ -0,0 +1,176 @@
1
+ // one object from the Space to its second place, by stream (wiki tools/shipkit/media-store.md, The second copy): never
2
+ // whole in memory, never on the disk. The constraint a reader breaks first: an upload is COMPLETED only once every byte
3
+ // passed and its count and sha256 are the ones expected; a failure leaves an unfinished upload nobody sees, which the
4
+ // copy bucket's lifecycle rule aborts. Nothing here deletes, at either end
5
+ import { type SpaceConfig, signedFetch } from '../space.ts'
6
+
7
+ /** the bytes held at once by one object in flight: one part. Every part but the last has this size (R2 wants it) */
8
+ export const PART = 16 * 1024 * 1024
9
+ const PART_TRIES = 3
10
+ /** how long a call may take before it is given up: a HEAD or a listing, and a part going up (16 MB at 30 kB/s) */
11
+ export const CALL_MS = 60_000
12
+ export const PART_MS = 10 * 60_000
13
+ /** the Space sending nothing this long, in the middle of an object: the read is given up */
14
+ export const IDLE_MS = 60_000
15
+
16
+ /** the sha256 a content addressed key names (`<kind>/<sha256>.<ext>`), null for a key that names none */
17
+ export function shaOfKey(key: string): string | null {
18
+ return /(?:^|\/)([0-9a-f]{64})(?:\.[^/]*)?$/.exec(key)?.[1] ?? null
19
+ }
20
+
21
+ const codeOf = async (r: Response): Promise<string> => {
22
+ const text = r.status === 404 || r.headers.get('content-length') === '0' ? '' : await r.text().catch(() => '')
23
+ return `${r.status}${/<Code>([^<]+)<\/Code>/.exec(text)?.[1] ? ` ${/<Code>([^<]+)<\/Code>/.exec(text)![1]}` : ''}`
24
+ }
25
+
26
+ const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))
27
+
28
+ /** a call retried on a 5xx or a broken connection, never on a 4xx: the answer, or the last failure as an Error */
29
+ async function tried(what: string, call: (signal: AbortSignal) => Promise<Response>, o: { tries?: number; ms?: number; backoffMs?: number } = {}): Promise<Response> {
30
+ const tries = o.tries ?? PART_TRIES
31
+ let last = ''
32
+ for (let i = 0; i < tries; i++) {
33
+ if (i > 0) await sleep((o.backoffMs ?? 200) * 2 ** i)
34
+ let r: Response
35
+ try {
36
+ r = await call(AbortSignal.timeout(o.ms ?? CALL_MS))
37
+ } catch (e) {
38
+ last = (e as Error).message
39
+ continue
40
+ }
41
+ if (r.ok) return r
42
+ last = await codeOf(r)
43
+ if (r.status < 500) break
44
+ }
45
+ throw new Error(`${what}: ${last}`)
46
+ }
47
+
48
+ /** the sizes and waits of a copy: the defaults for a provider, small ones for a suite */
49
+ export type Pace = { part?: number; idleMs?: number; backoffMs?: number }
50
+
51
+ export type Sent = { size: number; sha: string; parts: number }
52
+
53
+ /** the bytes of `body` to `key` at `to`: in one PUT when they fit one part, else in parts of PART bytes, each hashed
54
+ * as it passes. `check` sees the count and the sha of all of them and names what is wrong; the upload completes only
55
+ * when it names nothing. A body larger than `max` is refused at the first byte past it */
56
+ export async function putStream(to: SpaceConfig, key: string, body: ReadableStream<Uint8Array>, o: { check?: (got: { size: number; sha: string }) => string | null; max?: number; signal?: AbortSignal; pace?: Pace; onIdle?: () => void; type?: string } = {}): Promise<Sent> {
57
+ const part = o.pace?.part ?? PART
58
+ const idleMs = o.pace?.idleMs ?? IDLE_MS
59
+ const back = o.pace?.backoffMs != null ? { backoffMs: o.pace.backoffMs } : {}
60
+ const buf = new Uint8Array(new ArrayBuffer(part))
61
+ const h = new Bun.CryptoHasher('sha256')
62
+ const reader = body.getReader()
63
+ let fill = 0
64
+ let size = 0
65
+ let upload: string | null = null
66
+ const etags: string[] = []
67
+ const sendPart = async (n: number): Promise<void> => {
68
+ if (upload == null) {
69
+ const r = await tried(`the upload of ${key} did not start`, (s) => signedFetch(to, 'POST', key, { uploads: '' }, { signal: s, ...(o.type ? { type: o.type } : {}) }), back)
70
+ upload = /<UploadId>([^<]+)<\/UploadId>/.exec(await r.text())?.[1] ?? null
71
+ if (upload == null) throw new Error(`the upload of ${key} did not start: no UploadId`)
72
+ }
73
+ const id = upload
74
+ const no = etags.length + 1
75
+ const r = await tried(`part ${no} of ${key}`, (s) => signedFetch(to, 'PUT', key, { partNumber: String(no), uploadId: id }, { body: buf.subarray(0, n), signal: s }), { ms: PART_MS, ...back })
76
+ const etag = r.headers.get('etag')
77
+ await r.body?.cancel()
78
+ if (!etag) throw new Error(`part ${no} of ${key}: the copy answered no ETag`)
79
+ etags.push(etag)
80
+ }
81
+ try {
82
+ for (;;) {
83
+ if (o.signal?.aborted) throw new Error(`stopped in the middle of ${key}`)
84
+ const { done, value } = await idle(reader.read(), idleMs, `the Space sent nothing for ${idleMs >= 1000 ? `${Math.round(idleMs / 1000)} s` : `${idleMs} ms`} in the middle of ${key}`, o.onIdle)
85
+ if (done) break
86
+ size += value.length
87
+ if (o.max != null && size > o.max) throw new Error(`${key}: the Space sends more than its ${o.max} bytes`)
88
+ h.update(value)
89
+ let at = 0
90
+ while (at < value.length) {
91
+ if (fill === part) {
92
+ await sendPart(fill)
93
+ fill = 0
94
+ }
95
+ const n = Math.min(part - fill, value.length - at)
96
+ buf.set(value.subarray(at, at + n), fill)
97
+ fill += n
98
+ at += n
99
+ }
100
+ }
101
+ const sha = h.digest('hex')
102
+ const wrong = o.check?.({ size, sha }) ?? null
103
+ if (wrong != null) throw new Error(wrong)
104
+ if (upload == null) {
105
+ const r = await tried(`the PUT of ${key}`, (s) => signedFetch(to, 'PUT', key, {}, { body: buf.subarray(0, fill), signal: s, ...(o.type ? { type: o.type } : {}) }), { ms: PART_MS, ...back })
106
+ await r.body?.cancel()
107
+ return { size, sha, parts: 1 }
108
+ }
109
+ if (fill > 0) await sendPart(fill)
110
+ const xml = `<CompleteMultipartUpload>${etags.map((e, i) => `<Part><PartNumber>${i + 1}</PartNumber><ETag>${e}</ETag></Part>`).join('')}</CompleteMultipartUpload>`
111
+ const done = await tried(`the end of the upload of ${key}`, (s) => signedFetch(to, 'POST', key, { uploadId: upload! }, { body: xml, signal: s }), { ms: PART_MS, ...back })
112
+ // a 200 that carries an error: S3's own way of failing a completion
113
+ const text = await done.text()
114
+ if (/<Error>/.test(text)) throw new Error(`the end of the upload of ${key}: ${/<Code>([^<]+)<\/Code>/.exec(text)?.[1] ?? 'an error'}`)
115
+ return { size, sha, parts: etags.length }
116
+ } finally {
117
+ // never awaited: a read that hangs would hold the run with it
118
+ void reader.cancel().catch(() => {})
119
+ }
120
+ }
121
+
122
+ /** a read raced against a timer: the timer wins with `why` as the error, then `after` closes what the read waits on */
123
+ function idle<T>(p: Promise<T>, ms: number, why: string, after?: () => void): Promise<T> {
124
+ let t: ReturnType<typeof setTimeout> | undefined
125
+ return Promise.race([p, new Promise<never>((_, no) => (t = setTimeout(() => (no(new Error(why)), after?.()), ms)))]).finally(() => clearTimeout(t))
126
+ }
127
+
128
+ export type Outcome = 'copied' | 'there' | 'conflict' | 'gone' | 'failed'
129
+ export type One = { key: string; outcome: Outcome; bytes: number; there?: number; why?: string }
130
+
131
+ /** the size of `key` at a place, null when it is not there; throws on any other answer */
132
+ export async function headSize(c: SpaceConfig, key: string, pace: Pace = {}): Promise<number | null> {
133
+ const r = await tried(`HEAD ${key}`, (s) => signedFetch(c, 'HEAD', key, {}, { signal: s }), pace.backoffMs != null ? { backoffMs: pace.backoffMs } : {})
134
+ .catch((e: Error) => (/: 404\b/.test(e.message) ? null : Promise.reject(e)))
135
+ if (r == null) return null
136
+ return Number(r.headers.get('content-length') ?? -1)
137
+ }
138
+
139
+ /** one object of the Space at its second place: done when the copy holds it at its size, a CONFLICT when the copy
140
+ * holds other bytes under its key (never overwritten), else streamed over and checked on the way */
141
+ export async function copyOne(from: SpaceConfig, to: SpaceConfig, key: string, size: number, o: { signal?: AbortSignal; pace?: Pace } = {}): Promise<One> {
142
+ // the GET's own, one an attempt: aborted when no answer comes in CALL_MS, or the Space goes quiet in the middle of
143
+ // the body, so its connection is closed and not left to hang. Never a timeout over the whole body: 1 GB takes long
144
+ let get = new AbortController()
145
+ try {
146
+ const there = await headSize(to, key, o.pace)
147
+ if (there === size) return { key, outcome: 'there', bytes: 0, there }
148
+ if (there != null) return { key, outcome: 'conflict', bytes: 0, there, why: `the copy holds ${there} bytes under this key, the Space ${size}: never overwritten` }
149
+ const r = await tried(`GET ${key} from the Space`, () => {
150
+ get = new AbortController()
151
+ const quiet = setTimeout(() => get.abort(), CALL_MS)
152
+ return signedFetch(from, 'GET', key, {}, { signal: get.signal }).finally(() => clearTimeout(quiet))
153
+ }, o.pace?.backoffMs != null ? { backoffMs: o.pace.backoffMs } : {}).catch((e: Error) => (/: 404\b/.test(e.message) ? null : Promise.reject(e)))
154
+ if (r == null) return { key, outcome: 'gone', bytes: 0, why: 'no longer in the Space' }
155
+ const said = r.headers.get('content-length')
156
+ if (said != null && Number(said) !== size) {
157
+ await r.body?.cancel()
158
+ return { key, outcome: 'failed', bytes: 0, why: `the Space answers ${said} bytes, its listing said ${size}` }
159
+ }
160
+ if (r.body == null) throw new Error(`the Space answered no body for ${key}`)
161
+ const want = shaOfKey(key)
162
+ const type = r.headers.get('content-type')
163
+ const sent = await putStream(to, key, r.body, {
164
+ ...(type ? { type } : {}),
165
+ max: size,
166
+ ...(o.signal ? { signal: o.signal } : {}),
167
+ ...(o.pace ? { pace: o.pace } : {}),
168
+ onIdle: () => get.abort(),
169
+ check: (got) => (got.size !== size ? `${key}: ${got.size} bytes came, the Space lists ${size}` : want != null && got.sha !== want ? `${key}: the Space's bytes hash to ${got.sha.slice(0, 12)}, not to the sha the key names` : null),
170
+ })
171
+ return { key, outcome: 'copied', bytes: sent.size }
172
+ } catch (e) {
173
+ const why = (e as Error).message
174
+ return { key, outcome: /not to the sha the key names/.test(why) ? 'conflict' : 'failed', bytes: 0, why }
175
+ }
176
+ }
@@ -1,13 +1,14 @@
1
1
  // the daemon's media job (wiki tools/shipkit/media-store.md, The daemon): one pass, in a child process the daemon
2
2
  // starts when `mediaDue` says so (home/daemon-jobs.ts), never on its loop. Every kind of every house repo scanned into
3
- // the machine index once its store moved, what waits sent up, and (when the owner turned it on) the disk purged under
4
- // 40 GB free. Each failure is one line in the daemon's log
3
+ // the machine index once its store moved, what waits sent up, and (when the owner turned it on) every row unused for a
4
+ // day purged, whatever the free space. Each failure is one line in the daemon's log
5
5
  import { existsSync, statSync } from 'node:fs'
6
6
  import { resolve } from 'node:path'
7
7
  import { machineGet, machineSet } from '../core/machine-db.ts'
8
8
  import type { MediaKind } from './kind.ts'
9
- import { FREE_MIN_BYTES, freeBytes, purge, purgeCandidates, windowDays } from './purge.ts'
9
+ import { KEEP_DAYS, purge, purgeCandidates } from './purge.ts'
10
10
  import { machineSpace } from './space.ts'
11
+ import { mediaDb } from './db.ts'
11
12
  import { syncKind } from './sync.ts'
12
13
  import { mb, uploadWaiting } from './upload.ts'
13
14
 
@@ -21,10 +22,34 @@ const AUTO_KEY = 'media-purge-auto'
21
22
  export const autoPurgeOn = (): boolean => machineGet<boolean>(AUTO_KEY) === true
22
23
  export const setAutoPurge = (on: boolean): boolean => machineSet(AUTO_KEY, on)
23
24
 
25
+ /** what the last pass saw, for the machine's report and its notes: no Space (why, since when), what waits to go up and
26
+ * what failed. A pass that reads the key clears `noSpace`. Nothing reads it to decide a pass: a hand run from a session
27
+ * that cannot read the keychain never stops the daemon's own */
28
+ export const MEDIA_STATE = 'media-state'
29
+ export type MediaState = { at: number; noSpace: string | null; since: number | null; waiting: number; bytes: number; failing: number }
30
+
31
+ /** the last pass's state as the machine's report carries it: names and counts, a path in the reason said as <path> */
32
+ export function mediaReport(): MediaState | null {
33
+ const s = machineGet<MediaState>(MEDIA_STATE)
34
+ if (s == null) return null
35
+ return { ...s, noSpace: s.noSpace == null ? null : s.noSpace.replace(/(?:~|\/)[^\s,;:()]*/g, '<path>').slice(0, 300) }
36
+ }
37
+
38
+ /** what waits to go up (on the disk, not up) and how many of them failed their last try, from the index */
39
+ export function waitingCounts(): { waiting: number; bytes: number; failing: number } {
40
+ const db = mediaDb()
41
+ if (db == null) return { waiting: 0, bytes: 0, failing: 0 }
42
+ const r = db.query('select count(*) as n, coalesce(sum(o.size), 0) as bytes, coalesce(sum(o.error is not null), 0) as failing from media_objects o where o.up is null and exists (select 1 from media_files f where f.key = o.key and f.local = 1)').get() as { n: number; bytes: number; failing: number }
43
+ return { waiting: r.n, bytes: r.bytes, failing: r.failing }
44
+ }
45
+
24
46
  /** each store's stamp at its last full scan, and the last purge: kept between two child runs */
25
47
  const SYNCED = 'media-synced'
26
48
  const PURGED_AT = 'media-purged-at'
27
49
  const NO_SPACE = 'media-no-space'
50
+ /** the passes in a row that found files waiting and no key: their back off */
51
+ const NO_SPACE_TRIES = 'media-no-space-tries'
52
+ const NO_SPACE_MAX_MS = 30 * 60_000
28
53
  /** when the next pass is due, and the folders whose move brings it sooner */
29
54
  const NEXT = 'media-next'
30
55
 
@@ -40,9 +65,17 @@ export function mediaDue(now: number): boolean {
40
65
 
41
66
  /** one pass of the daemon's media job, in its child process: what `startMediaStore` does each tick, with what it
42
67
  * remembers in the machine db */
43
- export async function mediaTick(o: { roots: string[]; kinds: () => readonly MediaKind[]; print: (l: string) => void; printErr: (l: string) => void; now?: () => number }): Promise<void> {
68
+ export async function mediaTick(o: { roots: string[]; kinds: () => readonly MediaKind[]; print: (l: string) => void; printErr: (l: string) => void; now?: () => number; toHq?: () => Promise<void> }): Promise<void> {
44
69
  const now = o.now ?? Date.now
45
70
  const since = now()
71
+ // the objects up told to the hq, behind its switch (hq-send.ts): a failure there is a line, never the pass's
72
+ const toHq = async (): Promise<void> => {
73
+ try {
74
+ await (o.toHq ?? (async () => (await import('./hq-send.ts')).mediaToHqTick({ roots: o.roots, print: o.print, printErr: o.printErr })))()
75
+ } catch (e) {
76
+ o.printErr(`WARN hq media: ${(e as Error).message}`)
77
+ }
78
+ }
46
79
  const synced = machineGet<Record<string, string>>(SYNCED) ?? {}
47
80
  const kinds = o.kinds()
48
81
  const stores = o.roots.flatMap((root) =>
@@ -53,6 +86,8 @@ export async function mediaTick(o: { roots: string[]; kinds: () => readonly Medi
53
86
  )
54
87
  // work done or left: the next pass at the usual period, else after the quiet one
55
88
  let busy = false
89
+ // a pass with no key and files waiting names its own next one (its back off)
90
+ let nextMs: number | null = null
56
91
  try {
57
92
  let moved = false
58
93
  for (const { kind, root, dir } of stores) {
@@ -74,32 +109,47 @@ export async function mediaTick(o: { roots: string[]; kinds: () => readonly Medi
74
109
  if (moved) machineSet(SYNCED, synced)
75
110
  const { space, why } = await machineSpace()
76
111
  // said once per reason, not once per pass: a pass is a child of its own
112
+ const was = machineGet<MediaState>(MEDIA_STATE)
77
113
  if (!space) {
78
114
  if (machineGet<string>(NO_SPACE) !== why) o.printErr(`WARN media store: nothing goes up: ${why}`)
79
115
  machineSet(NO_SPACE, why)
80
- return
116
+ const w = waitingCounts()
117
+ machineSet(MEDIA_STATE, { at: now(), noSpace: why, since: was?.noSpace != null ? (was.since ?? now()) : now(), ...w } satisfies MediaState)
118
+ // what waits is tried again soon, the daemon's own pass may read the key this one could not, then less and
119
+ // less often: 30 s, 1, 2, 4, 8, 16, then every 30 min
120
+ if (w.waiting > 0) {
121
+ const tries = (machineGet<number>(NO_SPACE_TRIES) ?? 0) + 1
122
+ machineSet(NO_SPACE_TRIES, tries)
123
+ nextMs = Math.min(MEDIA_EVERY_MS * 2 ** (tries - 1), NO_SPACE_MAX_MS)
124
+ }
125
+ } else {
126
+ machineSet(NO_SPACE, '')
127
+ machineSet(NO_SPACE_TRIES, 0)
128
+ const up = await uploadWaiting(space, { limit: 200, jobs: 3 })
129
+ if (up.up + up.there + up.failed.length > 0) busy = true
130
+ if (up.up + up.there > 0) o.print(`ok: media store: ${up.up} up (${mb(up.bytes)})${up.there > 0 ? `, ${up.there} already there` : ''}`)
131
+ if (up.failed.length > 0) o.printErr(`WARN media store: ${up.failed.length} uploads failed, tried again later; first: ${up.failed[0]?.key}: ${up.failed[0]?.error}`)
132
+ machineSet(MEDIA_STATE, { at: now(), noSpace: null, since: null, ...waitingCounts() } satisfies MediaState)
81
133
  }
82
- machineSet(NO_SPACE, '')
83
- const up = await uploadWaiting(space, { limit: 200, jobs: 3 })
84
- if (up.up + up.there + up.failed.length > 0) busy = true
85
- if (up.up + up.there > 0) o.print(`ok: media store: ${up.up} up (${mb(up.bytes)})${up.there > 0 ? `, ${up.there} already there` : ''}`)
86
- if (up.failed.length > 0) o.printErr(`WARN media store: ${up.failed.length} uploads failed, tried again later; first: ${up.failed[0]?.key}: ${up.failed[0]?.error}`)
87
- if (autoPurgeOn() && now() - (machineGet<number>(PURGED_AT) ?? 0) > PURGE_EVERY_MS) {
134
+ await toHq()
135
+ if (space && autoPurgeOn() && now() - (machineGet<number>(PURGED_AT) ?? 0) > PURGE_EVERY_MS) {
88
136
  machineSet(PURGED_AT, now())
89
137
  for (const { kind, root, dir } of stores) {
90
- if (freeBytes(dir) >= FREE_MIN_BYTES) continue
91
- const { candidates } = await purgeCandidates(kind, dir, { olderDays: windowDays(freeBytes(dir)) })
92
- const r = await purge(kind, dir, space, candidates, { enough: () => freeBytes(dir) >= FREE_MIN_BYTES })
93
- if (r.files > 0) o.print(`ok: media store: the disk under ${mb(FREE_MIN_BYTES)} free, ${r.files} ${kind.kind} files of ${root} purged (${mb(r.freed)})`)
138
+ const { candidates } = await purgeCandidates(kind, dir, { olderDays: KEEP_DAYS, now: now() })
139
+ if (candidates.length === 0) continue
140
+ const r = await purge(kind, dir, space, candidates)
141
+ if (r.files > 0) o.print(`ok: media store: ${r.files} ${kind.kind} files of ${root} unused for ${KEEP_DAYS} day purged (${mb(r.freed)})`)
94
142
  if (r.refused.length > 0) o.printErr(`WARN media store: ${r.refused.length} ${kind.kind} files of ${root} kept: ${r.refused[0]?.key}: ${r.refused[0]?.why}`)
95
143
  }
96
144
  }
145
+ // the index kept small on a pass with nothing else to do (tidy.ts)
146
+ if (!busy) await (await import('./tidy.ts')).tidyTick({ print: o.print, printErr: o.printErr, now: now() })
97
147
  } catch (e) {
98
148
  busy = true
99
149
  o.printErr(`WARN media store: the pass broke: ${(e as Error).message}`)
100
150
  } finally {
101
151
  // a store that is the repo itself (a hand label) moves with every save there: the index is its record
102
152
  const dirs = [...new Set(stores.filter((s) => resolve(s.dir) !== resolve(s.root)).map((s) => s.dir))]
103
- machineSet(NEXT, { at: since + (busy ? MEDIA_EVERY_MS : MEDIA_QUIET_MS), since, dirs } satisfies Next)
153
+ machineSet(NEXT, { at: since + (nextMs ?? (busy ? MEDIA_EVERY_MS : MEDIA_QUIET_MS)), since, dirs } satisfies Next)
104
154
  }
105
155
  }
@@ -1,27 +1,34 @@
1
- // THE MACHINE'S MEDIA INDEX (wiki tools/shipkit/media-store.md, The index): one sqlite file in the home's state folder,
1
+ // THE MACHINE'S MEDIA INDEX (wiki tools/shipkit/media-store.md, The index): the `media_*` tables of the machine db,
2
2
  // never in a repo, for every media file of this machine, whatever kind holds it. It is DERIVED: each kind's files stay
3
3
  // the truth, and a deleted index builds again from them (a file's place in the Space is found again by a HEAD). It holds
4
- // each file a kind names (local or not), each Space object (up or waiting, its retries), and the review store's item
5
- // reads by the code that read them
4
+ // each file a kind names (local or not), each Space object (up or waiting, its retries), when a purged file was fetched
5
+ // back (a use the purge counts), and the review store's item reads by the code that read them
6
6
  import { Database } from 'bun:sqlite'
7
7
  import { mkdirSync } from 'node:fs'
8
- import { dirname, join } from 'node:path'
9
- import { homeDir } from '../home/home-paths.ts'
8
+ import { dirname } from 'node:path'
9
+ import { foldRefusal, machineFileCreate, ownerOnlyFile, StoreRefused, storeHome } from '../core/machine-db.ts'
10
+ import { createRefusal } from '../core/machine-layout.ts'
10
11
  import { ensureWal } from '../ledger/db.ts'
11
12
 
13
+ /** the file that holds the index's tables for one process (a suite, a scratch); else the machine db */
12
14
  export const MEDIA_DB_ENV = 'SHIPKIT_MEDIA_DB'
13
- export const mediaDbPath = (): string => process.env[MEDIA_DB_ENV] || join(homeDir(), 'media.sqlite')
15
+ export const mediaDbPath = (): string => process.env[MEDIA_DB_ENV] || storeHome('media index')
14
16
 
15
17
  const BUSY_MS = 3_000
16
18
 
17
19
  const SCHEMA = `
18
- create table if not exists codes (store text not null, code text not null, used integer not null, primary key (store, code)) without rowid;
19
- create table if not exists items (store text not null, code text not null, id text not null, stamp text not null, read text not null, primary key (store, code, id)) without rowid;
20
- create table if not exists files (store text not null, item text not null, name text not null, key text not null, size integer not null, local integer not null, purged integer, primary key (store, item, name)) without rowid;
21
- create index if not exists files_key on files (key);
22
- create table if not exists objects (key text primary key, size integer not null, up integer, tries integer not null default 0, next integer not null default 0, error text) without rowid;
20
+ create table if not exists media_codes (store text not null, code text not null, used integer not null, primary key (store, code)) without rowid;
21
+ create table if not exists media_items (store text not null, code text not null, id text not null, stamp text not null, read text not null, primary key (store, code, id)) without rowid;
22
+ create table if not exists media_files (store text not null, item text not null, name text not null, key text not null, size integer not null, local integer not null, purged integer, primary key (store, item, name)) without rowid;
23
+ create index if not exists media_files_key on media_files (key);
24
+ create table if not exists media_objects (key text primary key, size integer not null, up integer, tries integer not null default 0, next integer not null default 0, error text) without rowid;
25
+ create index if not exists media_objects_up on media_objects (up, key);
26
+ create table if not exists media_fetched (store text not null, item text not null, name text not null, at integer not null, primary key (store, item, name)) without rowid;
23
27
  `
24
28
 
29
+ /** the index's tables, made where they are not: the fold makes them before it copies the old file's rows in */
30
+ export const createMediaTables = (db: Database): void => void db.exec(SCHEMA)
31
+
25
32
  let open: { path: string; db: Database } | null = null
26
33
  let warned = false
27
34
 
@@ -37,9 +44,13 @@ export function mediaDb(): Database | null {
37
44
  }
38
45
  open = null
39
46
  try {
47
+ const refused = createRefusal(path) ?? foldRefusal('media index', path)
48
+ if (refused != null) throw new StoreRefused(refused)
40
49
  mkdirSync(dirname(path), { recursive: true })
50
+ ownerOnlyFile(path)
41
51
  const db = new Database(path, { create: true, readwrite: true })
42
52
  db.exec(`pragma busy_timeout = ${BUSY_MS}`)
53
+ machineFileCreate(path, db)
43
54
  ensureWal(db, BUSY_MS)
44
55
  db.exec('pragma synchronous = NORMAL')
45
56
  db.exec(SCHEMA)
@@ -35,7 +35,7 @@ export async function forgetForGood(keys: readonly string[], o: { owner: string
35
35
  for (const key of keys) {
36
36
  // a row is the owner's when its file sits in the owner's folder (a hand put of it lands under any store)
37
37
  const inside = (store: string, item: string): boolean => owners.some((ow) => (join(store, item) + sep).startsWith(ow + sep))
38
- const others = (db.query('select store, item from files where key = ?').all(key) as { store: string; item: string }[]).filter((r) => !inside(r.store, r.item))
38
+ const others = (db.query('select store, item from media_files where key = ?').all(key) as { store: string; item: string }[]).filter((r) => !inside(r.store, r.item))
39
39
  if (others.length > 0) {
40
40
  kept.push({ key, why: `${others[0]!.store}/${others[0]!.item} holds the same content` })
41
41
  continue
@@ -45,10 +45,30 @@ export async function forgetForGood(keys: readonly string[], o: { owner: string
45
45
  for (const v of await versionsOf(key)) await signedDelete(config, key, { versionId: v })
46
46
  if ((await versionsOf(key)).length > 0) throw new Error(`${key}: versions remain after the delete`)
47
47
  db.transaction(() => {
48
- db.query('delete from files where key = ?').run(key)
49
- db.query('delete from objects where key = ?').run(key)
48
+ db.query('delete from media_files where key = ?').run(key)
49
+ db.query('delete from media_objects where key = ?').run(key)
50
50
  })()
51
51
  gone.push(key)
52
52
  }
53
53
  return { gone, kept }
54
54
  }
55
+
56
+ /** the vault's own sealed snapshots: the one folder the retention may empty */
57
+ export const VAULT_SNAPSHOTS_PREFIX = '_snapshots/vault/'
58
+ const isVaultSnapshot = (key: string): boolean => /^_snapshots\/vault\/(?!\.{1,2}\/)[a-z0-9._-]+\/\d{8}T\d{6}Z\.snap$/.test(key)
59
+
60
+ /** the other way out of the Space: vault snapshots past their retention, every version of each. Its one caller is the
61
+ * snapshot tick (vault/vault-snapshot.ts), which keeps the newest two and every snapshot younger than 30 days, and
62
+ * prunes only after a newer one passed the proof from the Space; any other key is refused before a call */
63
+ export async function forgetVaultSnapshots(keys: readonly string[]): Promise<string[]> {
64
+ for (const key of keys) if (!isVaultSnapshot(key)) throw new Error(`${key} is no vault snapshot: nothing is deleted`)
65
+ const { config, why } = await houseSpaceConfig()
66
+ if (!config) throw new Error(`nothing is deleted: ${why}`)
67
+ const gone: string[] = []
68
+ for (const key of keys) {
69
+ for (const v of await versionsOf(key)) await signedDelete(config, key, { versionId: v })
70
+ if ((await versionsOf(key)).length > 0) throw new Error(`${key}: versions remain after the delete`)
71
+ gone.push(key)
72
+ }
73
+ return gone
74
+ }