rvlib-shipkit 2.26.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 (442) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/package.json +1 -1
  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 +6 -4
  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 +122 -21
  11. package/src/agent-time/report-cache.ts +57 -0
  12. package/src/agent-time/report.ts +314 -40
  13. package/src/agent-time/shape.ts +50 -3
  14. package/src/agent-time/store.ts +320 -99
  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/SK047-login-in-description.check.ts +36 -0
  34. package/src/checks/SK048-one-local-file.check.ts +36 -0
  35. package/src/cli/cmd_Asks.ts +71 -5
  36. package/src/cli/cmd_Backup.ts +2 -2
  37. package/src/cli/cmd_Capacity.ts +2 -2
  38. package/src/cli/cmd_CrossRepoActivity.ts +5 -4
  39. package/src/cli/cmd_Db.ts +253 -0
  40. package/src/cli/cmd_History.ts +212 -0
  41. package/src/cli/cmd_Home.ts +31 -3
  42. package/src/cli/cmd_Hq.ts +516 -0
  43. package/src/cli/cmd_Machines.ts +36 -0
  44. package/src/cli/cmd_Media.ts +38 -6
  45. package/src/cli/cmd_Reflect.ts +23 -2
  46. package/src/cli/cmd_Review.ts +548 -116
  47. package/src/cli/cmd_Secret.ts +62 -12
  48. package/src/cli/cmd_Social.ts +83 -1
  49. package/src/cli/cmd_Space.ts +324 -0
  50. package/src/cli/cmd_Time.ts +76 -5
  51. package/src/cli/cmd_Tmp.ts +28 -4
  52. package/src/cli/cmd_Trailer.ts +14 -10
  53. package/src/cli/cmd_Urls.ts +56 -0
  54. package/src/cli/cmd_Vault.ts +583 -0
  55. package/src/cli/family-help.ts +4 -2
  56. package/src/cli/family-pages.ts +1 -1
  57. package/src/cli/registry.ts +24 -3
  58. package/src/collections/actions.ts +63 -13
  59. package/src/collections/collection-types.ts +23 -1
  60. package/src/collections/providers.ts +117 -23
  61. package/src/collections/review.ts +4 -4
  62. package/src/contracts/contract-manifests.ts +6 -5
  63. package/src/contracts/contract-types.ts +6 -4
  64. package/src/contracts/contracts-engine.ts +11 -0
  65. package/src/contracts/manifests/chrome-web-store.contract.ts +31 -0
  66. package/src/core/budget.ts +12 -17
  67. package/src/core/capacity.ts +27 -18
  68. package/src/core/check-runner.ts +7 -4
  69. package/src/core/layout.ts +3 -0
  70. package/src/core/machine-busy.ts +127 -0
  71. package/src/core/machine-commit.ts +6 -1
  72. package/src/core/machine-db.ts +368 -20
  73. package/src/core/machine-layout.ts +137 -0
  74. package/src/core/machine-read.ts +81 -0
  75. package/src/core/migrate-layout.ts +1 -1
  76. package/src/core/one-way-in-policy.ts +64 -7
  77. package/src/core/polling-policy.ts +27 -0
  78. package/src/core/retention.ts +16 -2
  79. package/src/core/scope.ts +107 -14
  80. package/src/core/slots.ts +5 -4
  81. package/src/drill/clean.ts +25 -1
  82. package/src/drill/run.ts +1 -1
  83. package/src/drill/seal.ts +27 -4
  84. package/src/home/activity-shape.ts +2 -0
  85. package/src/home/activity.ts +66 -3
  86. package/src/home/app-sign.ts +15 -4
  87. package/src/home/daemon-jobs.ts +149 -7
  88. package/src/home/database-projects.ts +111 -0
  89. package/src/home/database-words.ts +203 -0
  90. package/src/home/databases.ts +460 -0
  91. package/src/home/global-units.ts +6 -0
  92. package/src/home/gui-app/ShipkitGui.swift +122 -1
  93. package/src/home/gui-app.ts +6 -3
  94. package/src/home/home-move.ts +514 -0
  95. package/src/home/home-paths.ts +12 -3
  96. package/src/home/home-routes.ts +68 -0
  97. package/src/home/inbox-shape.ts +24 -14
  98. package/src/home/machine-fold.ts +820 -0
  99. package/src/home/machine-host.ts +20 -5
  100. package/src/home/machine-repair.ts +503 -0
  101. package/src/home/machine-stores.ts +66 -15
  102. package/src/home/machine-temp.ts +547 -86
  103. package/src/home/resume.ts +79 -0
  104. package/src/home/run-daemon.ts +25 -4
  105. package/src/home/run-pm.ts +18 -5
  106. package/src/home/serve-daemon.ts +18 -3
  107. package/src/home/serve-web.ts +175 -7
  108. package/src/home/space-job.ts +115 -0
  109. package/src/home/space-page.ts +257 -0
  110. package/src/home/space-route.ts +167 -0
  111. package/src/home/space-words.ts +103 -0
  112. package/src/home/time-page-shape.ts +202 -0
  113. package/src/home/time-page.ts +64 -0
  114. package/src/home/vault-page.ts +482 -0
  115. package/src/home/vault-words.ts +132 -0
  116. package/src/hooks/leak-guard.ts +40 -13
  117. package/src/hooks/one-way-in-guard.ts +17 -4
  118. package/src/hq/cards.ts +581 -0
  119. package/src/hq/door-route.ts +43 -0
  120. package/src/hq/door.ts +163 -0
  121. package/src/hq/files-send.ts +348 -0
  122. package/src/hq/forgotten-log.ts +35 -0
  123. package/src/hq/history-check.ts +255 -0
  124. package/src/hq/history-place.ts +146 -0
  125. package/src/hq/history-send.ts +487 -0
  126. package/src/hq/hq-db.ts +99 -0
  127. package/src/hq/hq-local.ts +469 -0
  128. package/src/hq/hq-routes.ts +196 -0
  129. package/src/hq/hq-store.ts +599 -0
  130. package/src/hq/kinds/ask.ts +147 -0
  131. package/src/hq/kinds/card-gone.ts +83 -0
  132. package/src/hq/kinds/card-msg.ts +66 -0
  133. package/src/hq/kinds/card.ts +99 -0
  134. package/src/hq/kinds/index.ts +21 -0
  135. package/src/hq/kinds/kind.ts +126 -0
  136. package/src/hq/kinds/media.ts +125 -0
  137. package/src/hq/kinds/prompt.ts +219 -0
  138. package/src/hq/kinds/reflection.ts +128 -0
  139. package/src/hq/kinds/report.ts +55 -0
  140. package/src/hq/kinds/time-day.ts +236 -0
  141. package/src/hq/ledger.ts +473 -0
  142. package/src/hq/machine-key.ts +44 -0
  143. package/src/hq/machine-notes.ts +131 -0
  144. package/src/hq/outbox.ts +372 -0
  145. package/src/hq/replica.ts +168 -0
  146. package/src/hq/repo-id.ts +4 -0
  147. package/src/hq/report-facts.ts +117 -0
  148. package/src/hq/report.ts +274 -0
  149. package/src/hq/switch.ts +151 -0
  150. package/src/hq/vault-grant.ts +92 -0
  151. package/src/identities/identities.ts +15 -3
  152. package/src/identities/steps.ts +31 -0
  153. package/src/ledger/db.ts +73 -26
  154. package/src/ledger/gate-checks.ts +6 -2
  155. package/src/ledger/run-log.ts +11 -3
  156. package/src/ledger/store.ts +26 -4
  157. package/src/media-store/backup/daemon.ts +25 -17
  158. package/src/media-store/backup/kept.ts +241 -0
  159. package/src/media-store/backup/restore.ts +14 -4
  160. package/src/media-store/backup/run.ts +11 -11
  161. package/src/media-store/backup/secret.ts +6 -4
  162. package/src/media-store/backup/snapshot.ts +4 -2
  163. package/src/media-store/backup/sources.ts +67 -16
  164. package/src/media-store/copy/config.ts +77 -0
  165. package/src/media-store/copy/copy.ts +194 -0
  166. package/src/media-store/copy/lifecycle.ts +43 -0
  167. package/src/media-store/copy/night.ts +90 -0
  168. package/src/media-store/copy/proof.ts +151 -0
  169. package/src/media-store/copy/snapshot.ts +152 -0
  170. package/src/media-store/copy/store.ts +62 -0
  171. package/src/media-store/copy/stream.ts +176 -0
  172. package/src/media-store/daemon.ts +66 -16
  173. package/src/media-store/db.ts +22 -11
  174. package/src/media-store/forget.ts +23 -3
  175. package/src/media-store/hand.ts +4 -3
  176. package/src/media-store/hq-find.ts +75 -0
  177. package/src/media-store/hq-send.ts +277 -0
  178. package/src/media-store/kind.ts +2 -0
  179. package/src/media-store/purge.ts +18 -15
  180. package/src/media-store/put.ts +24 -8
  181. package/src/media-store/remote.ts +16 -7
  182. package/src/media-store/space-listing.ts +240 -0
  183. package/src/media-store/space.ts +40 -21
  184. package/src/media-store/sync.ts +5 -5
  185. package/src/media-store/tidy.ts +98 -0
  186. package/src/media-store/upload.ts +3 -3
  187. package/src/media-store/webp.ts +66 -0
  188. package/src/messages/model.ts +16 -7
  189. package/src/messages/routes.ts +14 -4
  190. package/src/messages/score.ts +2 -2
  191. package/src/messages/suggest.ts +96 -0
  192. package/src/pages/frame-client.ts +10 -0
  193. package/src/plan/planner.ts +28 -17
  194. package/src/recordings/media-kind.ts +1 -0
  195. package/src/recordings/model.ts +1 -1
  196. package/src/recordings/recorder-app/Capture.swift +9 -7
  197. package/src/reflect/hq-corpus.ts +56 -0
  198. package/src/reflect/prompt-corpus.ts +3 -1
  199. package/src/reflect/transcript.ts +129 -37
  200. package/src/release/machine-words.ts +67 -0
  201. package/src/release/public-clean.ts +8 -3
  202. package/src/releases/from-card.ts +1 -1
  203. package/src/releases/routes.ts +10 -5
  204. package/src/releases/store.ts +10 -1
  205. package/src/repo-config.ts +32 -2
  206. package/src/review/anim.ts +2 -2
  207. package/src/review/auto.ts +2 -2
  208. package/src/review/card-db.ts +244 -0
  209. package/src/review/card-rows.ts +266 -0
  210. package/src/review/cells.ts +76 -5
  211. package/src/review/draft-card.ts +41 -0
  212. package/src/review/draft-model.ts +78 -0
  213. package/src/review/format.ts +29 -10
  214. package/src/review/gone.ts +98 -0
  215. package/src/review/inbox-hook.ts +4 -4
  216. package/src/review/marks.ts +1 -1
  217. package/src/review/media-kind.ts +7 -5
  218. package/src/review/media-read.ts +9 -7
  219. package/src/review/media.ts +32 -5
  220. package/src/review/model.ts +202 -39
  221. package/src/review/move.ts +491 -0
  222. package/src/review/notes.ts +12 -20
  223. package/src/review/previews.ts +15 -19
  224. package/src/review/project.ts +1 -1
  225. package/src/review/rev.ts +8 -0
  226. package/src/review/role.ts +1 -1
  227. package/src/review/routes.ts +64 -13
  228. package/src/review/stage-card.ts +8 -4
  229. package/src/review/stage-routes.ts +1 -1
  230. package/src/review/store.ts +529 -83
  231. package/src/review/thread-fold.ts +51 -0
  232. package/src/review/threads.ts +147 -9
  233. package/src/review/trailer-auto-mock.ts +63 -0
  234. package/src/review/trailer-card.ts +4 -4
  235. package/src/review/trailer-desk.ts +41 -7
  236. package/src/review/trailer-media.ts +1 -0
  237. package/src/review/trailer-model.ts +8 -0
  238. package/src/review/trailer-notes.ts +1 -1
  239. package/src/review/trailer-routes.ts +9 -1
  240. package/src/review/unit.ts +6 -6
  241. package/src/review/watchers.ts +1 -1
  242. package/src/rules/untrack-generated.ts +92 -8
  243. package/src/secrets/held.ts +16 -0
  244. package/src/secrets/keychain.ts +113 -0
  245. package/src/secrets/list.ts +16 -6
  246. package/src/secrets/manager.ts +24 -10
  247. package/src/secrets/read.ts +257 -0
  248. package/src/secrets/who-reads.ts +49 -0
  249. package/src/serve/door-forward.ts +268 -0
  250. package/src/serve/door-names.ts +47 -0
  251. package/src/serve/embed.ts +1 -1
  252. package/src/serve/hub-app/activity-view.tsx +56 -32
  253. package/src/serve/hub-app/activity.css +7 -1
  254. package/src/serve/hub-app/asks-page.tsx +48 -0
  255. package/src/serve/hub-app/asks-st.ts +25 -0
  256. package/src/serve/hub-app/clock-svc.ts +1 -2
  257. package/src/serve/hub-app/col-card.tsx +64 -13
  258. package/src/serve/hub-app/col-list-page.tsx +122 -0
  259. package/src/serve/hub-app/col-list-st.ts +103 -0
  260. package/src/serve/hub-app/col-tables-view.tsx +10 -41
  261. package/src/serve/hub-app/col-tables.ts +76 -8
  262. package/src/serve/hub-app/cols-svc.ts +70 -16
  263. package/src/serve/hub-app/database-st.ts +260 -0
  264. package/src/serve/hub-app/database-view.tsx +289 -0
  265. package/src/serve/hub-app/database.css +32 -0
  266. package/src/serve/hub-app/entry-bar.css +14 -0
  267. package/src/serve/hub-app/entry-bar.tsx +33 -0
  268. package/src/serve/hub-app/entry-pick.ts +31 -0
  269. package/src/serve/hub-app/floating.tsx +1 -0
  270. package/src/serve/hub-app/hash-route.ts +11 -1
  271. package/src/serve/hub-app/header-bar.tsx +14 -18
  272. package/src/serve/hub-app/home-st.ts +89 -9
  273. package/src/serve/hub-app/home-strip.css +5 -19
  274. package/src/serve/hub-app/home-strip.tsx +58 -92
  275. package/src/serve/hub-app/home.html +7 -0
  276. package/src/serve/hub-app/hub-app.tsx +31 -142
  277. package/src/serve/hub-app/hub-types.ts +3 -1
  278. package/src/serve/hub-app/hub.css +109 -23
  279. package/src/serve/hub-app/icons.tsx +18 -1
  280. package/src/serve/hub-app/identities-st.ts +56 -6
  281. package/src/serve/hub-app/identities-view.tsx +100 -58
  282. package/src/serve/hub-app/identities.css +17 -15
  283. package/src/serve/hub-app/identity-address.ts +5 -0
  284. package/src/serve/hub-app/inbox-st.ts +41 -24
  285. package/src/serve/hub-app/inbox-view.tsx +37 -41
  286. package/src/serve/hub-app/inbox.css +2 -5
  287. package/src/serve/hub-app/index.html +7 -0
  288. package/src/serve/hub-app/kept-cols.tsx +7 -0
  289. package/src/serve/hub-app/keys.ts +28 -15
  290. package/src/serve/hub-app/later.tsx +26 -0
  291. package/src/serve/hub-app/list-filter.tsx +14 -0
  292. package/src/serve/hub-app/list-walk.ts +72 -3
  293. package/src/serve/hub-app/machines-st.ts +251 -0
  294. package/src/serve/hub-app/machines-view.tsx +224 -0
  295. package/src/serve/hub-app/machines.css +76 -0
  296. package/src/serve/hub-app/md-copy.tsx +79 -0
  297. package/src/serve/hub-app/media-view.tsx +2 -0
  298. package/src/serve/hub-app/messages/messages-page.tsx +79 -7
  299. package/src/serve/hub-app/messages/messages-st.ts +99 -3
  300. package/src/serve/hub-app/messages.css +14 -0
  301. package/src/serve/hub-app/page-keys.ts +175 -0
  302. package/src/serve/hub-app/pages-frames.tsx +11 -3
  303. package/src/serve/hub-app/palette-st.ts +58 -11
  304. package/src/serve/hub-app/palette-view.tsx +3 -1
  305. package/src/serve/hub-app/project-list.css +54 -8
  306. package/src/serve/hub-app/project-list.tsx +128 -59
  307. package/src/serve/hub-app/projects-svc.ts +78 -7
  308. package/src/serve/hub-app/reader-chips.tsx +13 -0
  309. package/src/serve/hub-app/readme-view.tsx +2 -3
  310. package/src/serve/hub-app/readme.css +27 -5
  311. package/src/serve/hub-app/reflections-page.tsx +42 -0
  312. package/src/serve/hub-app/reflections-st.ts +17 -0
  313. package/src/serve/hub-app/releases/releases-page.tsx +25 -2
  314. package/src/serve/hub-app/releases/releases-st.ts +1 -1
  315. package/src/serve/hub-app/repo-sections.ts +9 -5
  316. package/src/serve/hub-app/repo-st.ts +35 -8
  317. package/src/serve/hub-app/review/draft-card.tsx +163 -0
  318. package/src/serve/hub-app/review/kit.tsx +50 -7
  319. package/src/serve/hub-app/review/note-place.ts +1 -1
  320. package/src/serve/hub-app/review/review-board.tsx +2 -2
  321. package/src/serve/hub-app/review/review-cells.tsx +145 -65
  322. package/src/serve/hub-app/review/review-kit.ts +27 -1
  323. package/src/serve/hub-app/review/review-list.tsx +68 -30
  324. package/src/serve/hub-app/review/review-page.tsx +7 -8
  325. package/src/serve/hub-app/review/review-st.ts +111 -24
  326. package/src/serve/hub-app/review/review-thread.tsx +49 -19
  327. package/src/serve/hub-app/review/review-views.tsx +475 -144
  328. package/src/serve/hub-app/review/thread-control-st.ts +115 -0
  329. package/src/serve/hub-app/review/thread-control.tsx +74 -0
  330. package/src/serve/hub-app/review/thread-st.ts +73 -26
  331. package/src/serve/hub-app/review/trailer-card.tsx +1 -1
  332. package/src/serve/hub-app/review/trailer-page.tsx +37 -16
  333. package/src/serve/hub-app/review/trailer-st.ts +41 -7
  334. package/src/serve/hub-app/review.css +267 -61
  335. package/src/serve/hub-app/side-lists.ts +72 -0
  336. package/src/serve/hub-app/sidebar.tsx +6 -3
  337. package/src/serve/hub-app/site/site-part.tsx +2 -8
  338. package/src/serve/hub-app/site/site-st.ts +4 -4
  339. package/src/serve/hub-app/social/comms-page.tsx +20 -5
  340. package/src/serve/hub-app/social/kit.tsx +30 -4
  341. package/src/serve/hub-app/social/post-card.tsx +139 -49
  342. package/src/serve/hub-app/social/serial-writes.ts +13 -0
  343. package/src/serve/hub-app/social/social-model.ts +11 -0
  344. package/src/serve/hub-app/social/social-page.tsx +94 -35
  345. package/src/serve/hub-app/social/social-st.ts +120 -36
  346. package/src/serve/hub-app/social/stage-popup.tsx +1 -1
  347. package/src/serve/hub-app/social/stage-st.ts +1 -1
  348. package/src/serve/hub-app/social/step-layout.ts +1 -1
  349. package/src/serve/hub-app/social.css +3 -0
  350. package/src/serve/hub-app/space-st.ts +209 -0
  351. package/src/serve/hub-app/space-view.tsx +196 -0
  352. package/src/serve/hub-app/space.css +27 -0
  353. package/src/serve/hub-app/stores/stores-page.tsx +91 -23
  354. package/src/serve/hub-app/stores/stores-st.ts +44 -19
  355. package/src/serve/hub-app/stores.css +6 -1
  356. package/src/serve/hub-app/theme-st.ts +22 -9
  357. package/src/serve/hub-app/time-charts.tsx +291 -0
  358. package/src/serve/hub-app/time-pages.tsx +749 -0
  359. package/src/serve/hub-app/time-st.ts +162 -0
  360. package/src/serve/hub-app/time-view.tsx +76 -0
  361. package/src/serve/hub-app/time.css +138 -0
  362. package/src/serve/hub-app/tree-build.ts +52 -42
  363. package/src/serve/hub-app/tree-row.tsx +4 -4
  364. package/src/serve/hub-app/tree-svc.ts +18 -9
  365. package/src/serve/hub-app/urls-svc.ts +154 -0
  366. package/src/serve/hub-app/urls-view.tsx +117 -0
  367. package/src/serve/hub-app/urls.css +30 -0
  368. package/src/serve/hub-app/vault-st.ts +127 -0
  369. package/src/serve/hub-app/vault-view.tsx +154 -0
  370. package/src/serve/hub-app/vault.css +38 -0
  371. package/src/serve/hub-app/veille/veille-st.ts +12 -10
  372. package/src/serve/hub-app/waiting-svc.ts +29 -0
  373. package/src/serve/hub-app/wikis-view.tsx +2 -2
  374. package/src/serve/hub-runtime.ts +15 -2
  375. package/src/serve/project-gutter-route.ts +27 -14
  376. package/src/serve/project-gutter.ts +25 -12
  377. package/src/serve/same-origin.ts +10 -0
  378. package/src/serve/serve-hub.ts +13 -4
  379. package/src/shipkit-files.ts +16 -2
  380. package/src/shipkit.ts +1 -1
  381. package/src/shot/shooter.ts +616 -420
  382. package/src/shot/shot-ask.ts +246 -155
  383. package/src/site/desk.ts +2 -2
  384. package/src/smoke/run-smoke.ts +3 -2
  385. package/src/social/cover.ts +202 -0
  386. package/src/social/discord-layout.ts +37 -13
  387. package/src/social/drafts.ts +3 -0
  388. package/src/social/load.ts +23 -2
  389. package/src/social/media-kind.ts +2 -1
  390. package/src/social/publish/discord.ts +5 -2
  391. package/src/social/publish/secret.ts +2 -2
  392. package/src/social/release-stage.ts +28 -13
  393. package/src/social/routes.ts +26 -1
  394. package/src/social/stage.ts +1 -1
  395. package/src/social/stats.ts +12 -9
  396. package/src/social/strip.ts +4 -1
  397. package/src/social/thumbnail.ts +255 -0
  398. package/src/stores/collection.ts +15 -11
  399. package/src/stores/desk.ts +236 -42
  400. package/src/stores/model.ts +72 -6
  401. package/src/stores/routes.ts +37 -12
  402. package/src/stores/unit.ts +14 -8
  403. package/src/suite/judge-suites.ts +41 -11
  404. package/src/suite/select.ts +45 -3
  405. package/src/suite/suite-cli.ts +16 -10
  406. package/src/trailer/bed.ts +1 -1
  407. package/src/trailer/build.ts +134 -21
  408. package/src/trailer/ffmpeg.ts +7 -0
  409. package/src/trailer/fonts.ts +3 -2
  410. package/src/trailer/grammar.ts +201 -2
  411. package/src/trailer/graph.ts +42 -5
  412. package/src/trailer/look.ts +21 -0
  413. package/src/trailer/mock.ts +154 -0
  414. package/src/trailer/passage.ts +65 -26
  415. package/src/trailer/score/heard.ts +89 -0
  416. package/src/trailer/score/sound.ts +14 -8
  417. package/src/trailer/sound/run.ts +16 -6
  418. package/src/trailer/stitch.ts +26 -5
  419. package/src/trailer/titles.ts +82 -19
  420. package/src/trailer/versions.ts +1 -3
  421. package/src/trailer/vertical.ts +3 -1
  422. package/src/urls/frame.ts +195 -0
  423. package/src/urls/routes.ts +43 -0
  424. package/src/urls/rows.ts +171 -0
  425. package/src/urls/unit.ts +73 -0
  426. package/src/vault/house-keys.ts +42 -0
  427. package/src/vault/layout.ts +50 -0
  428. package/src/vault/policy.ts +165 -0
  429. package/src/vault/vault-audit.ts +276 -0
  430. package/src/vault/vault-client.ts +40 -0
  431. package/src/vault/vault-config.ts +159 -0
  432. package/src/vault/vault-destroy.ts +78 -0
  433. package/src/vault/vault-handover.ts +305 -0
  434. package/src/vault/vault-http.ts +352 -0
  435. package/src/vault/vault-import.ts +208 -0
  436. package/src/vault/vault-init.ts +328 -0
  437. package/src/vault/vault-minter.ts +271 -0
  438. package/src/vault/vault-restore.ts +333 -0
  439. package/src/vault/vault-serve.ts +342 -0
  440. package/src/vault/vault-snapshot.ts +281 -0
  441. package/src/veille/asks.ts +1 -1
  442. package/src/veille/desk.ts +2 -2
@@ -24,14 +24,20 @@ export function machineName(): string {
24
24
  /** the tailscale cli: on PATH when its wrapper is installed, else inside the app */
25
25
  export const TAILSCALE = ['tailscale', '/Applications/Tailscale.app/Contents/MacOS/Tailscale']
26
26
 
27
- /** `Self.DNSName` of `tailscale status --json`, without its final dot; null when no tailscale answers */
28
- export function readTailnetName(bins: string[] = TAILSCALE): string | null {
27
+ export type TailnetNode = { HostName?: string; DNSName?: string; TailscaleIPs?: string[] }
28
+ /** what `tailscale status --json` says of this machine and its peers */
29
+ export type TailnetStatus = { Self?: TailnetNode; Peer?: Record<string, TailnetNode>; MagicDNSSuffix?: string; BackendState?: string }
30
+
31
+ /** how long one tailscale cli may take to answer */
32
+ export const TAILSCALE_MS = 3000
33
+
34
+ /** `tailscale status --json`, null when no tailscale answers within `timeout` */
35
+ export function readTailscaleStatus(bins: string[] = TAILSCALE, timeout = TAILSCALE_MS): TailnetStatus | null {
29
36
  for (const bin of bins) {
30
37
  try {
31
- const p = Bun.spawnSync([bin, 'status', '--json'], { stdout: 'pipe', stderr: 'ignore', timeout: 3000 })
38
+ const p = Bun.spawnSync([bin, 'status', '--json'], { stdout: 'pipe', stderr: 'ignore', timeout })
32
39
  if (p.exitCode !== 0) continue
33
- const name = (JSON.parse(p.stdout.toString()) as { Self?: { DNSName?: string } }).Self?.DNSName?.replace(/\.$/, '')
34
- if (name) return name
40
+ return JSON.parse(p.stdout.toString()) as TailnetStatus
35
41
  } catch {
36
42
  // a missing binary throws: the next one is tried
37
43
  }
@@ -39,6 +45,15 @@ export function readTailnetName(bins: string[] = TAILSCALE): string | null {
39
45
  return null
40
46
  }
41
47
 
48
+ /** `Self.DNSName` of `tailscale status --json`, without its final dot; null when no tailscale answers */
49
+ export function readTailnetName(bins: string[] = TAILSCALE, timeout = TAILSCALE_MS): string | null {
50
+ for (const bin of bins) {
51
+ const name = readTailscaleStatus([bin], timeout)?.Self?.DNSName?.replace(/\.$/, '')
52
+ if (name) return name
53
+ }
54
+ return null
55
+ }
56
+
42
57
  const TAILNET = 'tailnet-name'
43
58
  /** how long a process keeps "tailscale did not answer" before it asks again */
44
59
  export const TAILNET_RETRY_MS = 60_000
@@ -0,0 +1,503 @@
1
+ // the repair of a part of the machine db (`sk db drop`, `sk db repair`): a cache part dropped and made again empty, or
2
+ // the tables sqlite finds damaged repaired. A damaged table, or a table with a damaged index, has every row that still
3
+ // reads saved aside in steps (by rowid ranges, read around a damaged page), then it is cut out of the schema (a DROP
4
+ // walks every page and stops at the damaged one), made again from its store's schema, and filled again in steps: its
5
+ // indexes come back from its rows, and only the rows of a damaged page are lost, counted before anything is cut.
6
+ // The one constraint a reader breaks first: the agent time index alone holds what Claude Code pruned, so nothing here
7
+ // empties one of its tables to clear a damage
8
+ import type { Database } from 'bun:sqlite'
9
+ import { existsSync } from 'fs'
10
+ import { type FoldedStore, machineDb, machineDbPath, REPAIR_MARK, REPAIR_UNUSED, type RepairMark, repairMarkOf } from '../core/machine-db.ts'
11
+ import { COPY_STEP, count, dropTables, foldState, openHost, type Print, q, shapeOf, STORES, takeLock } from './machine-fold.ts'
12
+ import { vacuumSteps } from '../core/machine-db.ts'
13
+
14
+ /** the part of the machine db a name says: `media` or `time`, or the store's own name */
15
+ export const partNamed = (name: string): FoldedStore | null => (/^media( index)?$/i.test(name) ? 'media index' : /^(agent )?time( index)?$/i.test(name) ? 'agent time index' : /^daemon( file)?$/i.test(name) ? 'daemon file' : null)
16
+ export const partWord = (store: FoldedStore): string => (store === 'media index' ? 'media' : store === 'daemon file' ? 'daemon' : 'time')
17
+
18
+ /** the system's sqlite shell: the one sqlite here that may edit a schema (bun's refuses: « table sqlite_master may not
19
+ * be modified »), the only way to cut out a table a damaged page makes undroppable */
20
+ const SQLITE_SHELL = '/usr/bin/sqlite3'
21
+ /** where a repair keeps a table's rows while the table is made again */
22
+ const saved = (table: string): string => `${table}__saved`
23
+
24
+ export type Dropped = { store: FoldedStore; tables: { table: string; rows: number | null }[]; done: boolean; why: string }
25
+
26
+ /** a cache part's tables dropped in steps and made again empty: the media index builds again from the files and the
27
+ * Space; the agent time index is never dropped whole. `go` false: says what it would do */
28
+ export async function dropPart(store: FoldedStore, o: { go: boolean; print: Print }): Promise<Dropped> {
29
+ const { prefix, tables, create } = STORES[store]
30
+ const state = foldState().find((s) => s.store === store)!
31
+ if (state.state !== 'folded') return { store, tables: [], done: false, why: `the ${store} is not tables of the machine db (${state.state}): nothing to drop` }
32
+ const lock = takeLock()
33
+ if (!lock.ok) throw new Error(`a fold runs (pid ${lock.pid}): one at a time`)
34
+ const db = openHost()
35
+ try {
36
+ const list = tables.map((t) => `${prefix}${t}`).filter((t) => shapeOf(db, 'main', t) != null).map((t) => ({ table: t, rows: rowsOf(db, t) }))
37
+ if (store === 'agent time index') return { store, tables: list, done: false, why: 'the agent time index is no cache: it alone holds what Claude Code pruned, so it is never dropped whole; sk db repair time repairs a damaged table' }
38
+ if (!o.go) return { store, tables: list, done: false, why: `dry run: --go drops ${list.map((x) => x.table).join(', ')} and makes each again empty` }
39
+ try {
40
+ await dropTables(db, store)
41
+ } catch (e) {
42
+ if (/malformed|corrupt/i.test((e as Error).message)) throw new Error(`a table of the ${store} is damaged and sqlite does not drop it: sk db repair ${partWord(store)} --go repairs it`)
43
+ throw e
44
+ }
45
+ create(db)
46
+ o.print(`ok: the ${store}: ${list.map((x) => x.table).join(', ')} dropped and made again empty`)
47
+ return { store, tables: list, done: true, why: 'dropped' }
48
+ } finally {
49
+ db.close()
50
+ lock.release()
51
+ }
52
+ }
53
+
54
+ const rowsOf = (db: Database, t: string): number | null => {
55
+ try {
56
+ return count(db, 'main', t)
57
+ } catch {
58
+ return null
59
+ }
60
+ }
61
+
62
+ /** a damaged table's rows that read, and the rows it held by a sound index: the look and the repair say the same */
63
+ /** `cut`: read by key order with no index that lists its keys, so the read stopped at the damaged page and every row
64
+ * after it is lost too */
65
+ export type Repaired = { table: string; damaged: string[]; saved: number; held: number | null; lost: number | null; cut?: boolean }
66
+ export type Repair = { store: FoldedStore; tables: Repaired[]; done: boolean; why: string }
67
+
68
+ /** every rowid range of `table` that reads, in steps of `step` rowids; a range that does not read is halved until one
69
+ * rowid, which is lost. `each` takes the rows of a range that reads */
70
+ function readAround(db: Database, table: string, step: number, each: (lo: number, hi: number) => number): { saved: number; bad: number } {
71
+ const max = maxRowid(db, table)
72
+ let savedRows = 0
73
+ let bad = 0
74
+ const range = (lo: number, hi: number): void => {
75
+ try {
76
+ savedRows += each(lo, hi)
77
+ } catch (e) {
78
+ if (!/malformed|corrupt/i.test((e as Error).message)) throw e
79
+ if (hi - lo <= 1) return void bad++
80
+ const mid = Math.floor((lo + hi) / 2)
81
+ range(lo, mid)
82
+ range(mid, hi)
83
+ }
84
+ }
85
+ for (let lo = 0; lo < max; lo += step) {
86
+ range(lo, Math.min(max, lo + step))
87
+ }
88
+ return { saved: savedRows, bad }
89
+ }
90
+
91
+ /** a table of no rowid read by its key: the keys listed through one of its indexes that reads (an index holds the
92
+ * key of every row), then the rows fetched by their keys in steps of `step`, a step that does not read halved until one
93
+ * key, which is lost; so a damaged page costs its own rows. With no index that reads, by key order from the first key
94
+ * until a step does not read. `each` takes a step's clause (after the table's name) and its values, and gives the rows
95
+ * it read */
96
+ function readByKey(db: Database, table: string, pk: readonly string[], step: number, each: (where: string, args: unknown[]) => number, skip: readonly string[] = []): { saved: number; bad: number; cut?: boolean } {
97
+ const keys = pk.map(q).join(', ')
98
+ const tuple = `(${keys})`
99
+ const marks = `(${pk.map(() => '?').join(', ')})`
100
+ const indexes = (db.query("select name from sqlite_master where type = 'index' and tbl_name = ? and sql is not null").all(table) as { name: string }[]).map((r) => r.name).filter((n) => !skip.includes(n))
101
+ let listed: unknown[][] | null = null
102
+ for (const i of indexes) {
103
+ try {
104
+ listed = db.query(`select ${keys} from ${q(table)} indexed by ${q(i)}`).values() as unknown[][]
105
+ break
106
+ } catch {
107
+ // that index is damaged too
108
+ }
109
+ }
110
+ if (listed != null) {
111
+ let savedRows = 0
112
+ let bad = 0
113
+ const some = (rows: unknown[][]): void => {
114
+ if (rows.length === 0) return
115
+ try {
116
+ savedRows += each(`not indexed where ${tuple} in (values ${rows.map(() => marks).join(', ')})`, rows.flat())
117
+ } catch (e) {
118
+ if (!/malformed|corrupt/i.test((e as Error).message)) throw e
119
+ if (rows.length === 1) return void bad++
120
+ const mid = Math.floor(rows.length / 2)
121
+ some(rows.slice(0, mid))
122
+ some(rows.slice(mid))
123
+ }
124
+ }
125
+ for (let at = 0; at < listed.length; at += step) some(listed.slice(at, at + step))
126
+ return { saved: savedRows, bad }
127
+ }
128
+ let lo: unknown[] | null = null
129
+ let savedRows = 0
130
+ for (;;) {
131
+ try {
132
+ const after = lo == null ? '' : `where ${tuple} > ${marks}`
133
+ const hi = db.query(`select ${keys} from ${q(table)} ${after} order by ${keys} limit 1 offset ${step - 1}`).values(...((lo ?? []) as never[]))[0] as unknown[] | undefined
134
+ const upto = hi == null ? '' : `${lo == null ? 'where' : 'and'} ${tuple} <= ${marks}`
135
+ savedRows += each(`${after} ${upto}`, [...(lo ?? []), ...(hi ?? [])])
136
+ if (hi == null) return { saved: savedRows, bad: 0 }
137
+ lo = hi
138
+ } catch (e) {
139
+ if (!/malformed|corrupt/i.test((e as Error).message)) throw e
140
+ return { saved: savedRows, bad: 1, cut: true }
141
+ }
142
+ }
143
+ }
144
+
145
+ /** the highest rowid of a table: through the table, else through one of its indexes that reads */
146
+ function maxRowid(db: Database, table: string): number {
147
+ const tries = [`select max(rowid) as m from ${q(table)}`, ...(db.query("select name from sqlite_master where type = 'index' and tbl_name = ? and sql is not null").all(table) as { name: string }[]).map((i) => `select max(rowid) as m from ${q(table)} indexed by ${q(i.name)}`)]
148
+ for (const sql of tries) {
149
+ try {
150
+ return Number((db.query(sql).get() as { m: number | null }).m ?? 0)
151
+ } catch {
152
+ // that tree does not read either
153
+ }
154
+ }
155
+ throw new Error(`no page of ${table} says its last row: the file is to be rebuilt by hand (sqlite3 .recover)`)
156
+ }
157
+
158
+ /** the rows a table held, through one of its indexes that reads: null when none does */
159
+ function heldBy(db: Database, table: string, damaged: readonly string[]): number | null {
160
+ const idx = (db.query("select name from sqlite_master where type = 'index' and tbl_name = ? and sql is not null").all(table) as { name: string }[]).map((r) => r.name).filter((n) => !damaged.includes(n))
161
+ for (const i of idx) {
162
+ try {
163
+ return (db.query(`select count(*) as n from ${q(table)} indexed by ${q(i)}`).get() as { n: number }).n
164
+ } catch {
165
+ // that index is damaged too
166
+ }
167
+ }
168
+ return null
169
+ }
170
+
171
+ /** the tables of a part sqlite finds damaged, a table or one of its indexes, with what each still holds; `go` saves
172
+ * every row that reads, cuts the table out, makes it again from the store's schema and fills it again, in steps */
173
+ export async function repairPart(store: FoldedStore, o: { go: boolean; print: Print; step?: number; pmUp?: boolean }): Promise<Repair> {
174
+ const r = await repairTables(store, o)
175
+ if (!r.done || machineDb((db) => db.query('select 1 from state where name = ?').get(REPAIR_UNUSED)) == null) return r
176
+ // the cut tables' pages are unused and unknown to the page map: the file is written again whole as the last step,
177
+ // or, while another process holds it, it says so and no vacuum moves a page until a rebuild
178
+ try {
179
+ const b = await rebuild({ go: true, print: o.print, pmUp: o.pmUp ?? false })
180
+ if (!b.done) o.print(`WARN the machine db keeps the pages of the cut tables unused, and gives no free page back, until it is written again: ${b.why}; with the home down: sk pm uninstall, sk db rebuild --go, sk pm install`)
181
+ } catch (e) {
182
+ o.print(`WARN the machine db keeps the pages of the cut tables unused, and gives no free page back, until it is written again (${(e as Error).message}); with the home down: sk pm uninstall, sk db rebuild --go, sk pm install`)
183
+ }
184
+ return r
185
+ }
186
+
187
+ async function repairTables(store: FoldedStore, o: { go: boolean; print: Print; step?: number }): Promise<Repair> {
188
+ const { prefix, tables } = STORES[store]
189
+ const state = foldState().find((s) => s.store === store)!
190
+ if (state.state === 'own file') return recoverOwn(store, state.old, o)
191
+ if (state.state !== 'folded') return { store, tables: [], done: false, why: `the ${store} is neither tables of the machine db nor a file of its own (${state.state}): nothing to repair` }
192
+ const lock = takeLock()
193
+ if (!lock.ok) throw new Error(`a fold runs (pid ${lock.pid}): one at a time`)
194
+ const db = openHost()
195
+ const step = o.step ?? COPY_STEP
196
+ try {
197
+ const was = repairMarkOf(store)
198
+ if (was != null) {
199
+ // a repair stopped once its rows were saved: the table is made again and filled from them
200
+ if (was.phase === 'saved' && o.go) return await finish(db, store, was, step, o.print)
201
+ if (was.phase === 'saved') return { store, tables: was.tables.map((t) => ({ table: t, damaged: [], saved: savedCount(db, t), held: null, lost: null })), done: false, why: `a repair stopped after it saved the rows of ${was.tables.join(', ')}: --go makes the tables again and fills them from those rows` }
202
+ // stopped while it saved: its saved rows go, the table is still the one it read
203
+ for (const t of was.tables) await dropSaved(db, t)
204
+ clearRepair(store)
205
+ }
206
+ const names = new Set(tables.map((t) => `${prefix}${t}`))
207
+ // --go: the mark first, before the first read, so no reader nor the indexer uses a table it is about to cut
208
+ if (o.go) {
209
+ setRepair(store, { tables: [...names], phase: 'saving' })
210
+ o.print(`the ${store} is marked for its repair: every open of it waits until it ends`)
211
+ }
212
+ const { damageOf } = await import('./databases.ts')
213
+ const hurt = new Map<string, string[]>()
214
+ for (const d of damageOf(db, { deep: true })) if (d.table != null && names.has(d.table)) hurt.set(d.table, [...(hurt.get(d.table) ?? []), ...(d.index == null ? [d.table] : [d.index])])
215
+ if (hurt.size === 0) {
216
+ if (o.go) clearRepair(store)
217
+ return { store, tables: [], done: false, why: `sqlite's check finds no damaged table or index of the ${store}` }
218
+ }
219
+ const list: Repaired[] = []
220
+ for (const [table, damaged] of hurt) {
221
+ const s = shapeOf(db, 'main', table)
222
+ if (s == null) continue
223
+ // the look reads every row as --go copies it, all its values: a count reads only the pages' heads, and
224
+ // promised rows a damaged cell then loses
225
+ const cols = s.cols.map(q).join(', ')
226
+ const seen = s.rowid ? readAround(db, table, step, (lo, hi) => db.query(`select rowid, ${cols} from ${q(table)} not indexed where rowid > ? and rowid <= ?`).values(lo, hi).length) : readByKey(db, table, s.pk, step, (where, args) => db.query(`select ${cols} from ${q(table)} ${where}`).values(...(args as never[])).length, [...new Set(damaged)])
227
+ const held = heldBy(db, table, [...new Set(damaged)])
228
+ list.push({ table, damaged: [...new Set(damaged)], saved: seen.saved, held, lost: held == null ? (damaged.includes(table) ? null : 0) : Math.max(0, held - seen.saved), ...('cut' in seen && seen.cut === true ? { cut: true } : {}) })
229
+ }
230
+ const words = list.map((r) => `${r.table} (damaged: ${r.damaged.join(', ')}): ${r.saved.toLocaleString('en-US')} rows read and kept, ${r.lost == null ? (r.cut === true ? 'every row from its damaged page to the end of the table is lost, how many is unknown (no sound index lists its keys)' : 'the rows of its damaged page are lost, how many is unknown (no sound index counts them)') : `${r.lost.toLocaleString('en-US')} lost`}`)
231
+ if (!o.go) return { store, tables: list, done: false, why: `dry run: ${words.join('; ')}. --go saves those rows, makes the table again with its indexes and fills it again, in steps` }
232
+ // the mark names what is repaired now: its tables, nothing else is cut
233
+ // the rows that read, aside, in steps: the table stays as it is until all are there
234
+ setRepair(store, { tables: list.map((r) => r.table), phase: 'saving' })
235
+ for (const r of list) {
236
+ await dropSaved(db, r.table)
237
+ const sh = shapeOf(db, 'main', r.table)!
238
+ const cols = sh.cols.map(q).join(', ')
239
+ if (sh.rowid) {
240
+ db.exec(`create table ${q(saved(r.table))} as select rowid as _r, * from ${q(r.table)} where 0`)
241
+ readAround(db, r.table, step, (lo, hi) => db.transaction(() => db.query(`insert into ${q(saved(r.table))} (_r, ${cols}) select rowid, ${cols} from ${q(r.table)} not indexed where rowid > ? and rowid <= ?`).run(lo, hi).changes)())
242
+ } else {
243
+ db.exec(`create table ${q(saved(r.table))} as select * from ${q(r.table)} where 0`)
244
+ readByKey(db, r.table, sh.pk, step, (where, args) => db.transaction(() => db.query(`insert into ${q(saved(r.table))} (${cols}) select ${cols} from ${q(r.table)} ${where}`).run(...(args as never[])).changes)(), r.damaged)
245
+ }
246
+ }
247
+ setRepair(store, { tables: list.map((r) => r.table), phase: 'saved' })
248
+ const done = await finish(db, store, repairMarkOf(store)!, step, o.print)
249
+ return { ...done, tables: list }
250
+ } finally {
251
+ db.close()
252
+ lock.release()
253
+ }
254
+ }
255
+
256
+ const savedCount = (db: Database, t: string): number => (shapeOf(db, 'main', saved(t)) == null ? 0 : count(db, 'main', saved(t)))
257
+
258
+ /** the saved rows' table dropped in steps: its pages are sound */
259
+ async function dropSaved(db: Database, t: string): Promise<void> {
260
+ if (shapeOf(db, 'main', saved(t)) == null) return
261
+ for (;;) if (db.transaction(() => db.query(`delete from ${q(saved(t))} where rowid in (select rowid from ${q(saved(t))} limit ${COPY_STEP})`).run().changes).immediate() === 0) break
262
+ db.exec(`drop table ${q(saved(t))}`)
263
+ }
264
+
265
+ /** the tables of a repair cut out of the schema, made again empty from the store's schema, filled from their saved
266
+ * rows in steps (each row under its rowid, so a rerun takes up where it stopped), the saved rows dropped */
267
+ async function finish(db: Database, store: FoldedStore, mark: RepairMark, step: number, print: Print): Promise<Repair> {
268
+ const { create } = STORES[store]
269
+ // a table there is the damaged one, or one a stopped rerun made again: cut either, its rows are all saved
270
+ const live = mark.tables.filter((t) => shapeOf(db, 'main', t) != null)
271
+ if (live.length > 0) {
272
+ if (!existsSync(SQLITE_SHELL)) throw new Error(`no ${SQLITE_SHELL} here: the saved rows are in ${mark.tables.map(saved).join(', ')}; cut the tables out by hand with a sqlite shell (pragma writable_schema = on; delete from sqlite_schema where tbl_name in (${live.map((t) => `'${t}'`).join(', ')}); pragma writable_schema = off), then sk db repair ${partWord(store)} --go`)
273
+ const sv = Number((db.query('pragma schema_version').get() as { schema_version: number }).schema_version)
274
+ // the schema's version raised in the same run, so every other connection reads the schema again
275
+ const sql = `pragma writable_schema = on; delete from sqlite_schema where tbl_name in (${live.map((t) => `'${t.replace(/'/g, "''")}'`).join(', ')}); pragma schema_version = ${sv + 1}; pragma writable_schema = off;`
276
+ const r = Bun.spawnSync([SQLITE_SHELL, '-batch', '-init', '/dev/null', machineDbPath(), sql], { stdout: 'pipe', stderr: 'pipe' })
277
+ if (r.exitCode !== 0) throw new Error(`${SQLITE_SHELL} did not cut the tables out: ${r.stderr.toString().trim()}; the saved rows stay, sk db repair ${partWord(store)} --go goes on`)
278
+ db.query('select count(*) from sqlite_master').get()
279
+ db.query('insert or replace into state (name, value, at) values (?, ?, ?)').run(REPAIR_UNUSED, JSON.stringify({ tables: live }), Date.now())
280
+ }
281
+ create(db)
282
+ const out: Repaired[] = []
283
+ for (const t of mark.tables) {
284
+ const own = shapeOf(db, 'main', t)!
285
+ const cols = own.cols.filter((c) => shapeOf(db, 'main', saved(t))!.cols.includes(c)).map(q).join(', ')
286
+ // a table of no rowid (the media index's) takes its rows by its key; one of rowids keeps each row's
287
+ const head = own.rowid ? `(rowid, ${cols}) select _r, ${cols}` : `(${cols}) select ${cols}`
288
+ let lo = 0
289
+ for (;;) {
290
+ const hi = (db.query(`select rowid as r from ${q(saved(t))} where rowid > ? order by rowid limit 1 offset ${step - 1}`).get(lo) as { r: number } | null)?.r ?? null
291
+ db.transaction(() => db.query(`insert or ignore into ${q(t)} ${head} from ${q(saved(t))} where rowid > ?${hi == null ? '' : ' and rowid <= ?'}`).run(...(hi == null ? [lo] : [lo, hi]))).immediate()
292
+ if (hi == null) break
293
+ lo = hi
294
+ }
295
+ out.push({ table: t, damaged: [], saved: count(db, 'main', t), held: null, lost: null })
296
+ await dropSaved(db, t)
297
+ }
298
+ clearRepair(store)
299
+ await vacuumSteps(db)
300
+ print(`ok: the ${store}: ${out.map((r) => `${r.table} made again, ${r.saved.toLocaleString('en-US')} rows`).join(', ')}; the pages of the cut tables stay unused until sk db rebuild --go`)
301
+ return { store, tables: out, done: true, why: 'repaired' }
302
+ }
303
+
304
+ const setRepair = (store: FoldedStore, m: Omit<RepairMark, 'pid' | 'at'>): void => void machineDb((db) => db.query('insert or replace into state (name, value, at) values (?, ?, ?)').run(`${REPAIR_MARK}${store}`, JSON.stringify({ ...m, pid: process.pid, at: Date.now() } satisfies RepairMark), Date.now()))
305
+ const clearRepair = (store: FoldedStore): void => void machineDb((db) => db.query('delete from state where name = ?').run(`${REPAIR_MARK}${store}`))
306
+
307
+ /** where the machine db is kept as it was before a rebuild */
308
+ export const rebuildCopy = (path: string): string => `${path}.before-rebuild`
309
+
310
+ export type Rebuilt = { done: boolean; why: string; tables: { table: string; rows: number; same: boolean }[]; before: number; after: number; ms: number }
311
+
312
+ /** each table's rows and a hash of them in rowid (or key) order: the old file and the new one must say the same */
313
+ function tableSums(db: Database): Map<string, { rows: number; sum: string }> {
314
+ const out = new Map<string, { rows: number; sum: string }>()
315
+ for (const { name } of db.query("select name from sqlite_master where type = 'table' and name not like 'sqlite_%' order by name").all() as { name: string }[]) {
316
+ const s = shapeOf(db, 'main', name)!
317
+ const order = s.rowid ? 'rowid' : s.pk.map(q).join(', ')
318
+ const h = new Bun.CryptoHasher('sha256')
319
+ let rows = 0
320
+ for (const r of db.query(`select ${s.rowid ? 'rowid, ' : ''}* from ${q(name)} order by ${order}`).values() as unknown[][]) {
321
+ h.update(JSON.stringify(r, (_k, v) => (typeof v === 'bigint' ? v.toString() : v instanceof Uint8Array ? Buffer.from(v).toString('base64') : v)))
322
+ rows++
323
+ }
324
+ out.set(name, { rows, sum: h.digest('hex') })
325
+ }
326
+ return out
327
+ }
328
+
329
+ /** the machine db written again whole into a new file (VACUUM INTO: its unused pages gone, every page checked), every
330
+ * table counted and hashed against the old one, then one rename under the write lock; the old file kept as
331
+ * `<file>.before-rebuild`. A write by another process between the copy and the rename makes it stop and say so.
332
+ * `go` false: says what it would do. `pmUp`: the home answers, its processes hold the file open */
333
+ export type RebuildStep = 'copied' | 'checked' | 'logged' | 'moved' | 'swapped'
334
+
335
+ export async function rebuild(o: { go: boolean; print: Print; pmUp: boolean; stopAfter?: (step: RebuildStep) => boolean }): Promise<Rebuilt> {
336
+ const stop = (step: RebuildStep): void => {
337
+ if (o.stopAfter?.(step) === true) throw new Error(`stopped after ${step} of the rebuild`)
338
+ }
339
+ const t0 = performance.now()
340
+ const path = machineDbPath()
341
+ const size = (p: string): number => (existsSync(p) ? Bun.file(p).size : 0)
342
+ const before = size(path) + size(`${path}-wal`)
343
+ const done = (x: Partial<Rebuilt> & { why: string }): Rebuilt => ({ done: false, tables: [], before, after: 0, ms: Math.round(performance.now() - t0), ...x })
344
+ const { statfsSync, renameSync, rmSync, chmodSync, linkSync } = await import('fs')
345
+ let free = Number.MAX_SAFE_INTEGER
346
+ try {
347
+ const f = statfsSync(path.replace(/\/[^/]+$/, ''))
348
+ free = Number(f.bavail) * Number(f.bsize)
349
+ } catch {
350
+ // a disk that does not say: the copy says it when it fails
351
+ }
352
+ if (!o.go) return done({ why: `dry run: --go writes ${path} again into a new file (it needs ${Math.round(before / 1e6)} MB, the disk has ${Math.round(free / 1e6)} MB free), checks every table's rows and hash against it, and keeps the old one as ${rebuildCopy(path)}; with the home down (sk pm uninstall): its processes hold the file open` })
353
+ if (o.pmUp) throw new Error(`the rebuild needs the home down (pm answers on port ${process.env.SHIPKIT_PM_PORT ?? 'its default'}): its processes hold ${path} open and would go on writing the old file; sk pm uninstall, then sk db rebuild --go, then sk pm install`)
354
+ if (before > free) throw new Error(`the rebuild needs ${Math.round(before / 1e6)} MB and the disk has ${Math.round(free / 1e6)} MB free`)
355
+ const lock = takeLock()
356
+ if (!lock.ok) throw new Error(`a fold runs (pid ${lock.pid}): one at a time`)
357
+ const db = openHost()
358
+ const tmp = `${path}.rebuild-tmp`
359
+ try {
360
+ for (const f of [tmp, `${tmp}-journal`, `${tmp}-wal`, `${tmp}-shm`]) rmSync(f, { force: true })
361
+ const version = (): number => Number((db.query('pragma data_version').get() as { data_version: number }).data_version)
362
+ const v0 = version()
363
+ // a damaged page first: VACUUM INTO meets it as « database or disk is full » with the disk free
364
+ const { damageOf } = await import('./databases.ts')
365
+ const hurt = damageOf(db, { deep: true }).filter((d) => d.table != null)
366
+ if (hurt.length > 0) throw new Error(`${[...new Set(hurt.map((d) => d.index ?? d.table))].join(', ')} of ${path} ${hurt.length === 1 ? 'is' : 'are'} damaged: sk db repair time and sk db repair media first`)
367
+ try {
368
+ db.exec(`vacuum into '${tmp.replace(/'/g, "''")}'`)
369
+ } catch (e) {
370
+ for (const f of [tmp, `${tmp}-journal`]) rmSync(f, { force: true })
371
+ if (/malformed|corrupt|disk is full/i.test((e as Error).message)) throw new Error(`a page of ${path} does not read (${(e as Error).message}): sk db repair time and sk db repair media first`)
372
+ throw e
373
+ }
374
+ chmodSync(tmp, 0o600)
375
+ stop('copied')
376
+ const { Database } = await import('bun:sqlite')
377
+ const nu = new Database(tmp, { readwrite: true })
378
+ const [a, b] = [tableSums(db), tableSums(nu)]
379
+ nu.close()
380
+ const tables = [...a].map(([table, x]) => ({ table, rows: x.rows, same: b.get(table)?.sum === x.sum && b.get(table)?.rows === x.rows }))
381
+ const off = tables.filter((t) => !t.same).map((t) => t.table)
382
+ if (off.length > 0 || b.size !== a.size) {
383
+ rmSync(tmp, { force: true })
384
+ return done({ tables, why: `the new file does not hold the same rows (${off.join(', ') || 'its tables differ'}): nothing renamed, run it again` })
385
+ }
386
+ if (version() !== v0) {
387
+ rmSync(tmp, { force: true })
388
+ return done({ tables, why: `another process wrote ${path} while it was copied: nothing renamed, run it again` })
389
+ }
390
+ stop('checked')
391
+ // the old file's log into it and out of WAL: sqlite refuses that while another connection holds the file, and
392
+ // this connection's close then touches no log by the file's name; the rename under the write lock
393
+ db.query('pragma wal_checkpoint(truncate)').all()
394
+ try {
395
+ db.exec('pragma journal_mode = delete')
396
+ } catch (e) {
397
+ rmSync(tmp, { force: true })
398
+ return done({ tables, why: `another process holds ${path} open (${(e as Error).message}): nothing renamed; stop it, then run it again` })
399
+ }
400
+ if (String(Object.values(db.query('pragma journal_mode').get() as Record<string, string>)[0]) !== 'delete') {
401
+ rmSync(tmp, { force: true })
402
+ return done({ tables, why: `another process holds ${path} open: nothing renamed; stop it, then run it again` })
403
+ }
404
+ stop('logged')
405
+ db.exec('begin immediate')
406
+ try {
407
+ if (version() !== v0) throw new Error(`another process wrote ${path} while it was copied: nothing renamed, run it again`)
408
+ // the old file under a second name first, then the new one renamed over the first: the machine db's path
409
+ // names a whole file at every moment, the old one or the new one
410
+ rmSync(rebuildCopy(path), { force: true })
411
+ linkSync(path, rebuildCopy(path))
412
+ stop('moved')
413
+ for (const f of [`${path}-wal`, `${path}-shm`]) rmSync(f, { force: true })
414
+ renameSync(tmp, path)
415
+ stop('swapped')
416
+ } finally {
417
+ db.exec('rollback')
418
+ }
419
+ // the new file holds no page a repair left unused: its vacuums run again
420
+ machineDb((m) => m.query('delete from state where name = ?').run(REPAIR_UNUSED), path)
421
+ const after = size(path)
422
+ o.print(`ok: ${path} written again: ${Math.round(before / 1e6)} MB to ${Math.round(after / 1e6)} MB, ${tables.length} tables, every one the same rows and hash; the old file is ${rebuildCopy(path)}`)
423
+ return done({ done: true, tables, after, why: 'rebuilt' })
424
+ } finally {
425
+ db.close()
426
+ lock.release()
427
+ }
428
+ }
429
+
430
+ /** a store's own file (not folded) that sqlite finds damaged, written again by sqlite's own recovery (`.recover` of the
431
+ * system's shell: every row that reads, page by page) into a new file that replaces it; the damaged one kept as
432
+ * `<file>.damaged`. Then the fold or this code reads it as before */
433
+ async function recoverOwn(store: FoldedStore, old: string, o: { go: boolean; print: Print }): Promise<Repair> {
434
+ const { oldDamage, forgetDamage } = await import('./machine-fold.ts')
435
+ const hurt = oldDamage(old)
436
+ if (hurt == null) return { store, tables: [], done: false, why: `its own file ${old} reads whole: nothing to repair` }
437
+ if (!existsSync(SQLITE_SHELL)) throw new Error(`no ${SQLITE_SHELL} here: sqlite3 ${old} .recover | sqlite3 ${old}.recovered, then mv ${old} ${old}.damaged and mv ${old}.recovered ${old}`)
438
+ const lock = takeLock()
439
+ if (!lock.ok) throw new Error(`a fold runs (pid ${lock.pid}): one at a time`)
440
+ const { rmSync, renameSync, chmodSync } = await import('fs')
441
+ const tmp = `${old}.recovered`
442
+ const clear = (): void => {
443
+ for (const f of [tmp, `${tmp}-journal`, `${tmp}-wal`, `${tmp}-shm`]) rmSync(f, { force: true })
444
+ }
445
+ try {
446
+ // the look runs the same recovery into a file beside, counts it and deletes it: the counts it promises are
447
+ // what --go puts in place, and the store is not written
448
+ clear()
449
+ const dump = Bun.spawn([SQLITE_SHELL, '-batch', '-init', '/dev/null', old, '.recover'], { stdout: 'pipe', stderr: 'pipe' })
450
+ const load = Bun.spawn([SQLITE_SHELL, '-batch', '-init', '/dev/null', tmp], { stdin: dump.stdout, stdout: 'pipe', stderr: 'pipe' })
451
+ const [a, b] = [await dump.exited, await load.exited]
452
+ if (a !== 0 || b !== 0 || oldDamage(tmp) != null) {
453
+ const why = (await new Response(dump.stderr).text()).trim().slice(0, 200)
454
+ clear()
455
+ throw new Error(`sqlite's recovery of ${old} did not give a whole file (${why}): the file stays as it is`)
456
+ }
457
+ const list = recoveredCounts(old, tmp)
458
+ const words = list.map((r) => `${r.table}: ${r.saved.toLocaleString('en-US')} rows kept, ${r.lost == null ? 'how many lost is unknown (nothing of the damaged file counts them)' : `${r.lost.toLocaleString('en-US')} lost`}`)
459
+ if (!o.go) {
460
+ clear()
461
+ return { store, tables: list, done: false, why: `dry run: its own file ${old} is damaged (${hurt}); sqlite's recovery (${SQLITE_SHELL} .recover) keeps ${words.join('; ')}. --go puts that file in its place and keeps the damaged one as ${old}.damaged` }
462
+ }
463
+ chmodSync(tmp, 0o600)
464
+ renameSync(old, `${old}.damaged`)
465
+ for (const f of [`${old}-wal`, `${old}-shm`]) {
466
+ try {
467
+ renameSync(f, `${old}.damaged${f.slice(old.length)}`)
468
+ } catch { /* none */ }
469
+ }
470
+ renameSync(tmp, old)
471
+ forgetDamage(store)
472
+ o.print(`ok: the ${store}: ${old} written again from every row that read (${words.join('; ')}), the damaged file kept as ${old}.damaged`)
473
+ return { store, tables: list, done: true, why: 'recovered' }
474
+ } finally {
475
+ lock.release()
476
+ }
477
+ }
478
+
479
+ /** per table, the rows sqlite's recovery kept, and those it lost against what the damaged file still counts (through
480
+ * an index that reads, else its count) */
481
+ function recoveredCounts(old: string, recovered: string): Repaired[] {
482
+ const { Database } = require('bun:sqlite') as typeof import('bun:sqlite')
483
+ const was = new Database(old, { readwrite: true, create: false })
484
+ const now = new Database(recovered, { readwrite: true, create: false })
485
+ try {
486
+ const names = (now.query("select name from sqlite_master where type = 'table' and name not like 'sqlite_%' and name != 'lost_and_found'").all() as { name: string }[]).map((r) => r.name)
487
+ return names.map((t) => {
488
+ const saved = (now.query(`select count(*) as n from ${q(t)}`).get() as { n: number }).n
489
+ let held = heldBy(was, t, [])
490
+ if (held == null) {
491
+ try {
492
+ held = (was.query(`select count(*) as n from ${q(t)}`).get() as { n: number }).n
493
+ } catch {
494
+ held = null
495
+ }
496
+ }
497
+ return { table: t, damaged: [], saved, held, lost: held == null ? null : Math.max(0, held - saved) }
498
+ })
499
+ } finally {
500
+ was.close()
501
+ now.close()
502
+ }
503
+ }