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
@@ -1,7 +1,9 @@
1
- // the one feedback store on disk (wiki tools/shipkit/review.md): `.shipkit/review/<id>/`, gitignored: `item.json`, the
1
+ // the one feedback store (wiki tools/shipkit/threads.md): `.shipkit/review/<id>/`, gitignored: `item.json`, the
2
2
  // media, and `thread/`, one file per message, never rewritten. An item is built in a dot folder and renamed, every file
3
3
  // written beside its place and renamed, so no reader sees half of one. The format is a project's own store's, verbatim. A folder of
4
- // the old shape (request.json, feedback.json, a message with `seen`) fails loud
4
+ // the old shape (request.json, feedback.json, a message with `seen`) fails loud. With the switch cards-in-db on, the
5
+ // heads and the messages are rows of the daemon's file instead (card-rows.ts), through the same functions: `io` picks
6
+ // the backend, every function above it is one code path
5
7
  import * as fs from 'node:fs'
6
8
  import { existsSync, readdirSync, readFileSync, statSync, watch } from 'node:fs'
7
9
  import { basename, dirname, extname, join, resolve } from 'node:path'
@@ -10,8 +12,17 @@ import { yieldLoop } from '../core/loop-watch.ts'
10
12
  import { ffmpeg } from '../trailer/ffmpeg.ts'
11
13
  import { probe, sizeOf, stillAt } from './media.ts'
12
14
  import { factsOf } from '../media-store/content.ts'
15
+ import { anyWebp, exactWebp, webpable } from '../media-store/webp.ts'
13
16
  import { mediaDb, tryWrite } from '../media-store/db.ts'
17
+ import { cardsInDb, cardsMoving, cardsOn } from '../hq/switch.ts'
18
+ import { rowsAll, rowsIO, rowsStamp, type CardBackend } from './card-rows.ts'
19
+ import { moveFolder, spoolOf } from './card-db.ts'
20
+ import { jsonText, revOf } from './rev.ts'
21
+ import { GONE, goneEntryFor } from './gone.ts'
14
22
  import {
23
+ ADDRESS_RE,
24
+ ownAddressOf,
25
+ partyOf,
15
26
  AGENT_RE,
16
27
  allowed,
17
28
  FILE_RE,
@@ -55,6 +66,7 @@ import {
55
66
  type ReviewMark,
56
67
  type ReviewView,
57
68
  type TrailerCard,
69
+ type DraftCard,
58
70
  type Spec,
59
71
  type Subject,
60
72
  type Verdict,
@@ -64,7 +76,7 @@ import {
64
76
  isGallery,
65
77
  } from './model.ts'
66
78
  import { beatRole, roleOf } from './role.ts'
67
- import { chainOf, coveringHead, followedIds, isFollowed } from './threads.ts'
79
+ import { chainOf, coveringHead, followedIds, isFollowed, threadOfAddress } from './threads.ts'
68
80
  import { liveWatchers } from './watchers.ts'
69
81
 
70
82
  /** the store of a repo */
@@ -88,12 +100,73 @@ const copyFileSync = (a: string, b: string): void => (fs.copyFileSync(a, b), tou
88
100
  const writeFileSync = (p: string, d: string): void => (fs.writeFileSync(p, d), touched(p))
89
101
  const mkdirSync = (p: string, o?: fs.MakeDirectoryOptions): void => (fs.mkdirSync(p, o), touched(p))
90
102
 
103
+ export { jsonText, revOf }
104
+
91
105
  function writeJson(file: string, v: unknown): void {
92
106
  const tmp = `${file}.tmp`
93
- writeFileSync(tmp, `${JSON.stringify(v, null, 4)}\n`)
107
+ writeFileSync(tmp, jsonText(v))
94
108
  renameSync(tmp, file)
95
109
  }
96
110
 
111
+ /** where the store's operations read and write: the rows of the local copy while the switch cards-in-db is on, else
112
+ * the files. Picked once an operation, so one operation never reads one backend and writes the other */
113
+ const io = (dir: string): CardBackend => (cardsInDb() ? rowsIO(dir) : filesIO(dir))
114
+
115
+ /** the store holds this card's head, or this message of its thread: what the machine has, never what it sent */
116
+ export const holdsCard = (dir: string, id: string): boolean => io(dir).has(id)
117
+ export const holdsMessage = (dir: string, id: string, mid: string): boolean => io(dir).hasMessage(id, mid)
118
+
119
+ /** the store's files, as they always were: one folder a card */
120
+ export function filesIO(dir: string): CardBackend {
121
+ const folder = (id: string): string => join(dir, id)
122
+ return {
123
+ rows: false,
124
+ names: () => (existsSync(dir) ? readdirSync(dir).filter((n) => !n.startsWith('.')).sort() : []),
125
+ has: (id) => ID_RE.test(id) && existsSync(join(dir, id, 'item.json')),
126
+ taken: (id) => existsSync(folder(id)),
127
+ head: (id) => {
128
+ if (!ID_RE.test(id)) return null
129
+ const f = join(dir, id, 'item.json')
130
+ const s = statSync(f, { throwIfNoEntry: false })
131
+ return s ? { head: JSON.parse(readFileSync(f, 'utf8')) as unknown, at: Math.floor(s.mtimeMs) } : null
132
+ },
133
+ threadIds: (id) => {
134
+ const t = join(dir, id, 'thread')
135
+ if (!ID_RE.test(id) || !existsSync(t)) return []
136
+ return readdirSync(t)
137
+ .filter((n) => n.endsWith('.json') && MESSAGE_RE.test(n.slice(0, -5)))
138
+ .map((n) => n.slice(0, -5))
139
+ .sort()
140
+ },
141
+ message: (id, mid) => JSON.parse(readFileSync(join(dir, id, 'thread', `${mid}.json`), 'utf8')) as unknown,
142
+ hasMessage: (id, mid) => existsSync(join(dir, id, 'thread', `${mid}.json`)),
143
+ raw: (id) => readRawFile(dir, id),
144
+ create: (id, tmp, head) => {
145
+ writeJson(join(tmp, 'item.json'), head)
146
+ // a card begun while the rows were the store: its folder comes from the spool
147
+ moveFolder(tmp, folder(id))
148
+ touched(tmp)
149
+ touched(folder(id))
150
+ },
151
+ write: (id, head, at) => {
152
+ const f = join(dir, id, 'item.json')
153
+ writeJson(f, head)
154
+ if (at !== undefined) fs.utimesSync(f, new Date(at), new Date(at))
155
+ },
156
+ append: (id, m) => {
157
+ const t = join(dir, id, 'thread')
158
+ if (!existsSync(t)) mkdirSync(t)
159
+ writeJson(join(t, `${m.id}.json`), m)
160
+ },
161
+ lock: (id, fn, waitMs) => locked(dir, id, fn, waitMs),
162
+ setAside: (id, o) => setAsideFile(dir, id, o),
163
+ keepReplaced: (id, head) => writeJson(join(folder(id), REPLACED), head),
164
+ hasReplaced: (id) => ID_RE.test(id) && existsSync(join(dir, id, REPLACED)),
165
+ stamp: (id) => stampOf(folder(id)),
166
+ folder,
167
+ }
168
+ }
169
+
97
170
  /** one view as given: a label, and an image, a clip, a sound or a pair (a clip or a sound goes anywhere an image goes,
98
171
  * by its extension), or a gallery of images */
99
172
  export interface ViewInput {
@@ -130,6 +203,10 @@ export interface AddInput {
130
203
  supersedes?: string
131
204
  /** the raised items (a report, his note) this card answers, by id */
132
205
  answers?: string[]
206
+ /** its subject's address when the agent names it (`--on`): one thread per address */
207
+ on?: string
208
+ /** other objects it is about: links that find it */
209
+ about?: string[]
133
210
  /** what a new version of an approved look keeps of it: required then */
134
211
  keeps?: string
135
212
  /** another subject on purpose, next to an active card: needs `why` */
@@ -150,6 +227,10 @@ export interface AddInput {
150
227
  agentPick?: string
151
228
  /** a trailer card: the cut the hub plays in its body; its one view is the cut's strip */
152
229
  trailer?: TrailerCard
230
+ /** a draft card: the post draft the hub shows in its body, read live; it holds no view */
231
+ draft?: DraftCard
232
+ /** every picture as given, never a webp: the file itself kept, where the card holds only its webp otherwise */
233
+ keep?: boolean
153
234
  now?: Date
154
235
  }
155
236
 
@@ -163,10 +244,45 @@ interface Loaded {
163
244
  /** a sound: its length, and the files its waveforms are drawn from (the after's or the one's, then the before's) */
164
245
  audio?: { duration: number; from: string; before?: string }
165
246
  tiles?: { path: string; label: string; size: { w: number; h: number }; before?: string; group?: string }[]
247
+ /** the webps made of its pictures, by the name of each in place of its source (`<source>.webp`, no such file) */
248
+ webps?: Map<string, Uint8Array>
249
+ }
250
+
251
+ /** the view's pictures as the card keeps them: each png a lossless webp found exact (media-store/webp.ts), made in
252
+ * memory and written where the card is by copyFiles; never with `keep`. The sides of a pair, and a tile and its
253
+ * before, are webps together or stay as given together, so two sides never differ in kind. `always`: a webp whatever
254
+ * the picture holds (a draft's live frame, whose name its card made a webp) */
255
+ async function asWebp(v: Loaded, keep: boolean, always: boolean): Promise<Loaded> {
256
+ if (keep || v.clip || v.audio) return v
257
+ const pics = [...v.sources.map(([, p]) => p), ...(v.tiles ?? []).flatMap((t) => [t.path, ...(t.before ? [t.before] : [])])]
258
+ if (!pics.some(webpable) && !always) return v
259
+ const webps = new Map<string, Uint8Array>()
260
+ /** the paths of a group as the card keeps them: every one a webp, or every one as given */
261
+ const group = async (paths: readonly string[]): Promise<string[]> => {
262
+ const made = await Promise.all(paths.map(async (p) => (always ? { bytes: await anyWebp(p) } : await exactWebp(p))))
263
+ if (made.some((m) => 'keep' in m)) return [...paths]
264
+ return paths.map((p, i) => {
265
+ webps.set(`${p}.webp`, (made[i] as { bytes: Uint8Array }).bytes)
266
+ return `${p}.webp`
267
+ })
268
+ }
269
+ const kept = await group(v.sources.map(([, p]) => p))
270
+ const sources = v.sources.map(([name], i): Loaded['sources'][number] => [name, kept[i]!])
271
+ const tiles = v.tiles && (await Promise.all(v.tiles.map(async (t) => {
272
+ const [path, before] = await group([t.path, ...(t.before ? [t.before] : [])])
273
+ return { ...t, path: path!, ...(before ? { before } : {}) }
274
+ })))
275
+ return { ...v, sources, ...(tiles ? { tiles } : {}), ...(webps.size > 0 ? { webps } : {}) }
166
276
  }
167
277
 
168
278
  /** a view's files checked and sized, a pair of one size (and one length, two clips); throws with the reason, naming the view */
169
- async function loadView(v: ViewInput, which: string): Promise<Loaded> {
279
+ async function loadView(v: ViewInput, which: string, o: { keep?: boolean; always?: boolean } = {}): Promise<Loaded> {
280
+ const l = await checkView(v, which)
281
+ return asWebp(l, o.keep === true, o.always === true)
282
+ }
283
+
284
+ /** a view's files checked and sized, as given */
285
+ async function checkView(v: ViewInput, which: string): Promise<Loaded> {
170
286
  if (v.gallery !== undefined) {
171
287
  if (v.image !== undefined || v.video !== undefined || v.audio !== undefined || v.before !== undefined || v.after !== undefined)
172
288
  throw new Error(`${which}: a gallery is a list of images, no --image, --video or pair beside it`)
@@ -309,11 +425,32 @@ function coveredText(c: { head: ReviewItem; by: 'subject' | 'near' | 'title' }):
309
425
  return [
310
426
  `one subject is one card: the active card ${r.id} "${r.title}" (${r.topic ?? 'no topic'}) already covers it, ${by}.`,
311
427
  ` a new version of it: --supersedes ${r.id}`,
312
- ` another angle of it: sk review add-view ${r.id} "<label>" <image> [<after>]`,
428
+ ` another angle of it: sk thread add-view ${r.id} "<label>" <image> [<after>]`,
313
429
  ` truly another subject: --new --why "<reason>"`,
314
430
  ].join('\n')
315
431
  }
316
432
 
433
+ /** the thread a new version goes into (wiki tools/shipkit/threads-store.md, The one thread guard): the one that owns its
434
+ * address. No link given: it supersedes that thread's newest version, or answers the note at its head, and answers his
435
+ * notes the thread took in that are not closed. A link given must be that one, else it is refused with the thread
436
+ * named. `thread` null: its address has no thread yet, or it names none (the older guard decides) */
437
+ export function threadLink(
438
+ dir: string,
439
+ card: Pick<Item, 'subject' | 'on' | 'trailer'>,
440
+ given: { supersedes?: string; answers: readonly string[] },
441
+ spec: Spec = specOf(dir),
442
+ ): { thread: string | null; supersedes?: string; answers: string[] } {
443
+ const own = ownAddressOf({ ...card, origin: { by: 'agent' } } as Item, spec)
444
+ const t = own === null ? null : threadOfAddress(own, readAll(dir).items, spec)
445
+ if (!t) return { thread: null, ...given, answers: [...given.answers] }
446
+ const head = t.head.item
447
+ const openNotes = t.answers.filter((x) => t.joined.has(x.item.id) && stateOf(x, false).state !== 'closed').map((x) => x.item.id)
448
+ const want = head.origin.by === 'agent' ? { supersedes: head.id, answers: openNotes } : { answers: [head.id, ...openNotes] }
449
+ if (given.supersedes !== undefined && given.supersedes !== want.supersedes)
450
+ throw new Error(`${own} already has its thread ${head.id} "${head.title}": a new version of it supersedes its newest version${want.supersedes ? ` ${want.supersedes}` : `, here the note it answers: --answers ${head.id}`}, never ${given.supersedes}; or leave --supersedes out and the tool links it`)
451
+ return { thread: head.id, ...(want.supersedes !== undefined ? { supersedes: want.supersedes } : {}), answers: [...new Set([...given.answers, ...want.answers])] }
452
+ }
453
+
317
454
  /** the Claude Code session that runs this process, null outside one */
318
455
  export const sessionId = (): string | null => process.env.CLAUDE_CODE_SESSION_ID?.trim() || null
319
456
 
@@ -329,14 +466,16 @@ export async function addItem(dir: string, input: AddInput): Promise<Item> {
329
466
  const given: ViewInput[] = [...(first ? [{ label: input.label ?? '', image: input.image, video: input.video, audio: input.audio, before: input.before, after: input.after }] : []), ...(input.views ?? [])].map(
330
467
  (v) => Object.fromEntries(Object.entries(v).filter(([, x]) => x !== undefined)) as unknown as ViewInput,
331
468
  )
332
- if (given.length === 0) throw new Error('give --image, --video or --audio, or --before and --after, or --view "<label>" <image>')
469
+ if (input.draft && given.length > 0) throw new Error('--draft: the card shows the draft itself, no image, clip, sound or view beside it')
470
+ if (given.length === 0 && !input.draft) throw new Error('give --image, --video or --audio, or --before and --after, or --view "<label>" <image>')
333
471
  for (const [i, v] of given.entries()) if (i > 0 && !v.label.trim()) throw new Error('--view: every view after the first needs its label')
334
472
  if (input.choice && given.length < 2) throw new Error('--choice: a choice has two options or more, one --view each')
335
473
  if (input.agentPick !== undefined && !input.choice) throw new Error('--pick: only on a --choice card')
336
474
  const agentPick = input.agentPick === undefined ? undefined : pickIndex(given, input.agentPick)
337
475
  for (const v of given) if (v.note !== undefined && v.gallery) throw new Error(`--view "${v.label}": a note goes on an image, a clip or a sound, never a gallery`)
338
- const loaded = await Promise.all(given.map((v, i) => loadView(v, i === 0 ? 'the first view' : `--view "${v.label}"`)))
339
- if (input.supersedes !== undefined && !existsSync(join(dir, input.supersedes, 'item.json'))) throw new Error(`--supersedes ${input.supersedes}: no such card in ${dir}`)
476
+ const loaded = await Promise.all(given.map((v, i) => loadView(v, i === 0 ? 'the first view' : `--view "${v.label}"`, { keep: input.keep === true })))
477
+ const c = io(dir)
478
+ if (input.supersedes !== undefined && !c.has(input.supersedes)) throw new Error(`--supersedes ${input.supersedes}: no such card in ${dir}`)
340
479
  if (input.supersedes !== undefined && readItem(dir, input.supersedes)?.item.origin.by !== 'agent')
341
480
  throw new Error(`--supersedes ${input.supersedes}: a report or a note is answered, never superseded: --answers ${input.supersedes}`)
342
481
  const answers = [...new Set(input.answers ?? [])]
@@ -351,6 +490,12 @@ export async function addItem(dir: string, input: AddInput): Promise<Item> {
351
490
  if (wrong.length > 0) throw new Error(wrong.join('; '))
352
491
  if (input.wip && (given.length > 2 || given.slice(1).some((v) => !v.gallery))) throw new Error('--wip: the card shows the live frame, and its history as a gallery, nothing else')
353
492
  if (input.marks && input.marks.length > given.length) throw new Error(`marks: ${input.marks.length} lists for ${given.length} views`)
493
+ const about = [...new Set((input.about ?? []).map((a) => a.trim()))]
494
+ const on = input.on?.trim() || undefined
495
+ for (const a of [...(on ? [on] : []), ...about]) if (!ADDRESS_RE.test(a)) throw new Error(`${a}: an address is <kind>:<key>, like page:review or trailer:<name>/<cut>`)
496
+ const link = threadLink(dir, { subject, ...(on ? { on } : {}), ...(input.trailer ? { trailer: input.trailer } : {}) }, { ...(input.supersedes !== undefined ? { supersedes: input.supersedes } : {}), answers }, spec)
497
+ input = { ...input, ...(link.supersedes !== undefined ? { supersedes: link.supersedes } : {}) }
498
+ answers.splice(0, answers.length, ...link.answers)
354
499
  if (input.supersedes !== undefined && !input.keeps?.trim()) {
355
500
  const all = readAll(dir).items
356
501
  const old = all.find((x) => x.item.id === input.supersedes)
@@ -361,7 +506,7 @@ export async function addItem(dir: string, input: AddInput): Promise<Item> {
361
506
  `${answered.item.id} "${answered.item.title}" was approved: an approval locks the look. Keep what he approved, say what stays with --keeps "<what of the approved version stays>", and say the change in --what`,
362
507
  )
363
508
  }
364
- if (input.supersedes === undefined) {
509
+ if (input.supersedes === undefined && link.thread === null) {
365
510
  if (input.fresh === true) {
366
511
  if (!input.why?.trim()) throw new Error('--new needs --why "<reason>": why this is another subject than the active card next to it')
367
512
  } else {
@@ -376,7 +521,7 @@ export async function addItem(dir: string, input: AddInput): Promise<Item> {
376
521
  const now = input.now ?? new Date()
377
522
  const base = idOf(now, input.title)
378
523
  let id = base
379
- for (let n = 2; existsSync(join(dir, id)); n++) id = `${base}-${n}`
524
+ for (let n = 2; c.taken(id); n++) id = `${base}-${n}`
380
525
  const session = sessionId()
381
526
  const item: Item = {
382
527
  id,
@@ -392,6 +537,8 @@ export async function addItem(dir: string, input: AddInput): Promise<Item> {
392
537
  views: loaded.map((v, n) => viewOf(v, n, input.marks?.[n], given[n]?.note)),
393
538
  ...(input.supersedes ? { supersedes: input.supersedes } : {}),
394
539
  ...(answers.length > 0 ? { answers } : {}),
540
+ ...(on ? { on } : {}),
541
+ ...(about.length > 0 ? { about } : {}),
395
542
  ...(input.fresh && input.why ? { why: input.why.trim() } : {}),
396
543
  ...(input.supersedes && input.keeps?.trim() ? { keeps: input.keeps.trim() } : {}),
397
544
  ...(input.light ? { light: input.light } : {}),
@@ -399,45 +546,72 @@ export async function addItem(dir: string, input: AddInput): Promise<Item> {
399
546
  ...(input.choice ? { choice: true as const } : {}),
400
547
  ...(agentPick !== undefined ? { agentPick } : {}),
401
548
  ...(input.trailer ? { trailer: input.trailer } : {}),
549
+ ...(input.draft ? { draft: input.draft } : {}),
402
550
  }
403
551
  const problems = itemProblems(item)
404
552
  if (problems.length > 0) throw new Error(problems.join('; '))
405
- const tmp = join(dir, `.${id}.tmp`)
406
- rmSync(tmp, { recursive: true, force: true })
407
- mkdirSync(tmp)
553
+ const tmp = tmpOf(c, id)
408
554
  loaded.forEach((v, n) => copyFiles(v, n, tmp))
409
555
  await Promise.all(loaded.map((v, n) => Promise.all([writePoster(v, n, tmp), writeWaves(v, n, tmp)])))
410
556
  const head: Item = { ...item, media: await factsOf(tmp, viewFilesOf(item)) }
411
- writeJson(join(tmp, 'item.json'), head)
412
- renameSync(tmp, join(dir, id))
557
+ createAtCommit(dir, c, id, tmp, head)
413
558
  return head
414
559
  }
415
560
 
561
+ /** the empty folder a new card's files are written in, beside the folder they become: the repo's store, or the spool */
562
+ function tmpOf(c: CardBackend, id: string): string {
563
+ const tmp = join(dirname(c.folder(id)), `.${id}.tmp`)
564
+ rmSync(tmp, { recursive: true, force: true })
565
+ mkdirSync(tmp, { recursive: true })
566
+ return tmp
567
+ }
568
+
569
+ /** where a store's card media are: the folder of each card in the repo, or, with the cards as rows, the spool beside the
570
+ * daemon's file (card-db.ts spoolOf). A card's file is `join(mediaDir(dir), id, name)` either way */
571
+ export const mediaDir = (dir: string): string => (cardsInDb() ? spoolOf(dir) : dir)
572
+
573
+ /** a new card committed to the store the switch names NOW: its files took their time (a clip, a big picture), and a
574
+ * move may have turned the switch meanwhile, past its lag. Its id was free in the store it was chosen in */
575
+ function createAtCommit(dir: string, picked: CardBackend, id: string, tmp: string, head: Item): void {
576
+ const now = io(dir)
577
+ if (now.rows !== picked.rows && now.taken(id)) throw new Error(`${id}: the store moved while this card was written, and the id is taken there: add it again`)
578
+ now.create(id, tmp, head)
579
+ }
580
+
416
581
  /** every file of view `n` into the folder, each as `<name>.tmp` renamed, so no reader sees half of one */
417
582
  function copyFiles(v: Loaded, n: number, into: string): void {
418
583
  const files = filesOf(v, n) as Record<string, string>
419
584
  const copies: [string, string][] = [...v.sources.map(([name, p]): [string, string] => [p, files[name] ?? name]), ...(v.tiles ?? []).flatMap((t, k): [string, string][] => [[t.path, tileName(n, k, t.path)], ...(t.before ? [[t.before, tileName(n, k, t.before, '-before')] as [string, string]] : [])])]
420
585
  for (const [from, name] of copies) {
421
586
  const to = join(into, name)
422
- copyFileSync(from, `${to}.tmp`)
587
+ putFile(v, from, `${to}.tmp`)
423
588
  renameSync(`${to}.tmp`, to)
424
589
  }
425
590
  }
426
591
 
592
+ /** one file of a view where it lands: its webp, else a copy of it */
593
+ function putFile(v: Loaded, from: string, to: string): void {
594
+ const webp = v.webps?.get(from)
595
+ if (webp == null) return copyFileSync(from, to)
596
+ fs.writeFileSync(to, webp)
597
+ touched(to)
598
+ }
599
+
427
600
  /** the command that posts an update, as a refusal names it */
428
- const updateLine = (id: string): string => `sk review update ${id} <${UPDATE_STATES.join('|')}> "<one line>" <file> | <before> <after>`
601
+ const updateLine = (id: string): string => `sk thread update ${id} <${UPDATE_STATES.join('|')}> "<one line>" <file> | <before> <after>`
429
602
 
430
603
  /** another angle of an open card's subject, appended as its next view; refused once he answered, except the view of an
431
604
  * update (`update`), which goes on at any time */
432
- export async function addView(dir: string, id: string, v: ViewInput, o: { marks?: ReviewMark[]; light?: 'review'; update?: true } = {}): Promise<Item> {
605
+ export async function addView(dir: string, id: string, v: ViewInput, o: { marks?: ReviewMark[]; light?: 'review'; update?: true; keep?: boolean } = {}): Promise<Item> {
433
606
  const x = readItem(dir, id)
434
607
  if (!x) throw new Error(`no card ${id}`)
435
608
  if (verdictOf(x) && !o.update) throw new Error(`${id} has his answer already: a picture of the work since goes on as an update, ${updateLine(id)}; a new version passes --supersedes ${id}`)
436
609
  if (v.note !== undefined && v.gallery) throw new Error(`"${v.label}": a note goes on an image, a clip or a sound, never a gallery`)
437
610
  if (!v.label.trim()) throw new Error('add-view: the view needs its label')
438
- const loaded = await loadView(v, `the view "${v.label}"`)
611
+ const loaded = await loadView(v, `the view "${v.label}"`, { keep: o.keep === true })
439
612
  const n = x.item.views.length
440
- const folder = join(dir, id)
613
+ const folder = io(dir).folder(id)
614
+ if (!existsSync(folder)) mkdirSync(folder, { recursive: true })
441
615
  // the files land before the head names them, so no reader sees a view without its images
442
616
  copyFiles(loaded, n, folder)
443
617
  await writePoster(loaded, n, folder)
@@ -471,23 +645,145 @@ export function setAgentPick(dir: string, id: string, ref: string): Item {
471
645
 
472
646
  /** the head rewritten under the item's lock, from what the file says now: a write that raced this one is never lost */
473
647
  export function updateHead(dir: string, id: string, fn: (cur: Item) => Item): Item {
474
- return locked(dir, id, () => {
475
- const f = join(dir, id, 'item.json')
476
- const cur = JSON.parse(readFileSync(f, 'utf8')) as Item
477
- const next = fn(cur)
648
+ const c = io(dir)
649
+ return c.lock(id, () => {
650
+ const held = c.head(id)
651
+ if (held == null) throw Object.assign(new Error(`no card ${id}`), { code: 'ENOENT' })
652
+ const next = fn(held.head as Item)
478
653
  const problems = itemProblems(next)
479
654
  if (problems.length > 0) throw new Error(problems.join('; '))
480
- writeJson(f, next)
655
+ c.write(id, next)
481
656
  return next
482
657
  })
483
658
  }
484
659
 
660
+ /** the ids of a store's cards, as their folders name them */
661
+ export const cardIds = (dir: string): string[] => io(dir).names().filter((n) => ID_RE.test(n))
662
+
663
+ /** a card's stamp: any write of its head or its thread moves it */
664
+ export const cardStamp = (dir: string, id: string): string => io(dir).stamp(id)
665
+
666
+ /** a card's head as it is stored, and the time it was written; null with no head */
667
+ export const rawHead = (dir: string, id: string): { head: unknown; at: number } | null => io(dir).head(id)
668
+
669
+ /** the ids of a card's messages, oldest first */
670
+ export const threadIds = (dir: string, id: string): string[] => (ID_RE.test(id) ? io(dir).threadIds(id) : [])
671
+
672
+ /** one message as it is stored */
673
+ export const rawMessage = (dir: string, id: string, mid: string): unknown => io(dir).message(id, mid)
674
+
675
+ export type LandedFile = { did: 'landed' | 'same' | 'kept'; why?: string }
676
+
677
+ /** the longest card or message id a card carried between machines may have: a folder or file name of about 120
678
+ * characters fits every file system, with its `.tmp` and `.land-<pid>` beside it */
679
+ export const MAX_ID_LENGTH = 120
680
+
681
+ /** a head made on another machine written as this card's item.json: a new card built in a dot folder and renamed,
682
+ * an existing one rewritten under its lock once `keep` (given the head as the file says now) has no reason to keep
683
+ * it. A head that is no item of that id is kept out. `dry` says what it would do */
684
+ export function landHead(dir: string, id: string, head: unknown, o: { keep: (cur: Item) => string | null; aside?: (cur: Item) => boolean; dry?: boolean; waitMs?: number }): LandedFile {
685
+ if (id.length > MAX_ID_LENGTH) return { did: 'kept', why: `card ${id.slice(0, 40)}…: its id is over ${MAX_ID_LENGTH} characters` }
686
+ const problems = itemProblems(head)
687
+ if (problems.length > 0 || (head as Item).id !== id) return { did: 'kept', why: `card ${id}: its head is no item of that id (${problems.join('; ') || 'another id'})` }
688
+ const c = io(dir)
689
+ const folder = c.folder(id)
690
+ const decide = (cur: Item): LandedFile | null => {
691
+ if (revOf(cur) === revOf(head)) return { did: 'same' }
692
+ const why = o.keep(cur)
693
+ return why == null ? null : { did: 'kept', why }
694
+ }
695
+ if (!c.has(id)) {
696
+ if (o.dry) return { did: 'landed' }
697
+ // the rows land a new card under the lock below, in one transaction
698
+ if (!c.rows && !c.taken(id)) {
699
+ mkdirSync(dir, { recursive: true })
700
+ const tmp = join(dir, `.${id}.land-${process.pid}`)
701
+ rmSync(tmp, { recursive: true, force: true })
702
+ mkdirSync(tmp)
703
+ writeJson(join(tmp, 'item.json'), head)
704
+ try {
705
+ renameSync(tmp, folder)
706
+ return { did: 'landed' }
707
+ } catch {
708
+ // a card of that id came meanwhile: its lock decides below
709
+ rmSync(tmp, { recursive: true, force: true })
710
+ }
711
+ }
712
+ }
713
+ if (o.dry) return decide(c.head(id)?.head as Item) ?? { did: 'landed' }
714
+ return c.lock(id, () => {
715
+ let aside = false
716
+ const now = c.head(id)
717
+ if (now != null) {
718
+ const cur = now.head as Item
719
+ const held = decide(cur)
720
+ if (held != null) return held
721
+ // the head it replaces stays beside it, the last one: a loss is never silent and never final
722
+ if (o.aside?.(cur) === true) {
723
+ c.keepReplaced(id, cur)
724
+ aside = true
725
+ }
726
+ }
727
+ const moved = setAsideClashes(folder, head as Item)
728
+ c.write(id, head)
729
+ const said = [
730
+ ...(aside ? [`a head made apart replaced this machine's, which is kept beside it as ${REPLACED}`] : []),
731
+ ...(moved.length > 0 ? [`this machine's files of the names the landing head gives to other bytes are kept as ${moved.join(', ')}`] : []),
732
+ ]
733
+ return said.length > 0 ? { did: 'landed', why: `card ${id}: ${said.join('; ')}` } : { did: 'landed' }
734
+ }, o.waitMs)
735
+ }
736
+
737
+ /** the head a landing replaced while this machine's change of it was not in it */
738
+ export const REPLACED = 'item.replaced.json'
739
+ /** the files of this machine a landing head names with other bytes (a view added apart under the same file name) */
740
+ export const REPLACED_FILES = 'replaced'
741
+
742
+ /** each file the head names by its facts whose bytes here are other bytes moves to `replaced/`: the media store would
743
+ * take it for the head's (purge it as up in the Space, or write its facts into the head), and it is this machine's */
744
+ function setAsideClashes(folder: string, head: Item): string[] {
745
+ const moved: string[] = []
746
+ for (const [name, fact] of Object.entries(head.media ?? {})) {
747
+ const f = join(folder, name)
748
+ const s = statSync(f, { throwIfNoEntry: false })
749
+ if (!s?.isFile()) continue
750
+ if (s.size === fact.size && new Bun.CryptoHasher('sha256').update(readFileSync(f)).digest('hex') === fact.sha) continue
751
+ mkdirSync(join(folder, REPLACED_FILES, dirname(name)), { recursive: true })
752
+ // an earlier clash of that name stays: the next one takes `<name>.2.<ext>`, `.3`
753
+ const ext = extname(name)
754
+ let to = name
755
+ for (let n = 2; existsSync(join(folder, REPLACED_FILES, to)); n++) to = `${name.slice(0, name.length - ext.length)}.${n}${ext}`
756
+ renameSync(f, join(folder, REPLACED_FILES, to))
757
+ moved.push(`${REPLACED_FILES}/${to}`)
758
+ }
759
+ return moved
760
+ }
761
+
762
+ /** does that card keep a head a landing replaced */
763
+ export const hasReplaced = (dir: string, id: string): boolean => ID_RE.test(id) && io(dir).hasReplaced(id)
764
+
765
+ /** a message made on another machine written into its card's thread, once: never over a file of its id. `no-card`
766
+ * while the card has no head here: the caller holds it. A message that is not one is kept out */
767
+ export function landMessage(dir: string, id: string, m: unknown, o: { dry?: boolean } = {}): LandedFile | { did: 'no-card' } {
768
+ const mid = m != null && typeof m === 'object' ? (m as { id?: unknown }).id : undefined
769
+ const problems = typeof mid === 'string' && MESSAGE_RE.test(mid) ? messageProblems(m, mid) : ['no message id']
770
+ if (id.length > MAX_ID_LENGTH || (typeof mid === 'string' && mid.length > MAX_ID_LENGTH)) return { did: 'kept', why: `a message of card ${id.slice(0, 40)}: an id over ${MAX_ID_LENGTH} characters` }
771
+ if (!ID_RE.test(id) || problems.length > 0) return { did: 'kept', why: `a message of card ${id}: ${problems.join('; ') || 'no card id'}` }
772
+ const c = io(dir)
773
+ if (!c.has(id)) return { did: 'no-card' }
774
+ // one id is made on two machines only by one party in one millisecond: the one here stays, and it is said
775
+ if (c.hasMessage(id, mid as string)) return revOf(c.message(id, mid as string)) === revOf(m) ? { did: 'same' } : { did: 'kept', why: `message ${mid as string} of card ${id}: another message of that id is on this machine, each machine keeps its own` }
776
+ if (o.dry) return { did: 'landed' }
777
+ c.append(id, m as Message)
778
+ return { did: 'landed' }
779
+ }
780
+
485
781
  /** the media facts an item lacks (one written before facts were kept, a file whose size moved): each file still in the
486
782
  * folder hashed, written under its lock; the item as it is when nothing was missing */
487
783
  export async function fillMedia(dir: string, id: string): Promise<Item | null> {
488
784
  const x = readRaw(dir, id)
489
785
  if (!x) return null
490
- const folder = join(dir, id)
786
+ const folder = io(dir).folder(id)
491
787
  const held = x.item.media ?? {}
492
788
  const names = mediaFilesOf(x)
493
789
  const size = (n: string): number | undefined => statSync(join(folder, n), { throwIfNoEntry: false })?.size
@@ -514,8 +810,23 @@ export function readItem(dir: string, id: string): ReviewItem | null {
514
810
  return x
515
811
  }
516
812
 
517
- /** one item as the file says, whatever the unit: what the index keeps */
518
- function readRaw(dir: string, id: string): ReviewItem | null {
813
+ /** one item as it is stored, whatever the unit: what the index keeps */
814
+ const readRaw = (dir: string, id: string): ReviewItem | null => (ID_RE.test(id) ? (io(dir).raw(id) ?? (healed(dir, id) ? io(dir).raw(id) : null)) : null)
815
+
816
+ /** a card this process misses while a move runs: a process that read the switch before it turned made it on the side
817
+ * the move left, so it is carried over now, as the move's own pass after its lag would. Whether it is here now */
818
+ function healed(dir: string, id: string): boolean {
819
+ if (!cardsMoving()) return false
820
+ const c = io(dir)
821
+ const other = c.rows ? filesIO(dir) : rowsIO(dir)
822
+ if (!other.has(id)) return false
823
+ const { carryCard } = require('./move.ts') as typeof import('./move.ts')
824
+ carryCard(dir, id, other, c)
825
+ return c.has(id)
826
+ }
827
+
828
+ /** one item as its files say */
829
+ function readRawFile(dir: string, id: string): ReviewItem | null {
519
830
  if (!ID_RE.test(id)) return null
520
831
  const folder = join(dir, id)
521
832
  if (!existsSync(folder)) return null
@@ -554,16 +865,31 @@ export function appendMessage(dir: string, id: string, m: Omit<Message, 'id' | '
554
865
  if (!existsSync(o.image)) throw new Error(`${o.image}: no such file`)
555
866
  if (!IMAGE_EXT.test(extname(o.image).toLowerCase())) throw new Error(`${o.image}: a png, jpg or webp`)
556
867
  }
557
- const folder = join(dir, id, 'thread')
558
- mkdirSync(folder, { recursive: true })
868
+ // a card with no head here (set aside, deleted) gets no thread: a folder with no head would read as a broken card
869
+ const c = io(dir)
870
+ if (!c.has(id) && !healed(dir, id)) throw new Error(`no card ${id}`)
871
+ const folder = join(c.folder(id), 'thread')
559
872
  const base = messageIdOf(now, m.who)
560
- let mid = base
561
- for (let n = 2; existsSync(join(folder, `${mid}.json`)); n++) mid = `${base}-${n}`
562
- const file = o.image === undefined ? undefined : `${mid}${extname(o.image).toLowerCase()}`
563
- if (o.image !== undefined && file) copyFileSync(o.image, join(folder, file))
564
- const out: Message = { id: mid, at: now.toISOString(), ...m, ...(file ? { image: file } : {}) }
565
- writeJson(join(folder, `${mid}.json`), out)
566
- return out
873
+ let n = 1
874
+ for (;;) {
875
+ let mid = n === 1 ? base : `${base}-${n}`
876
+ for (; c.hasMessage(id, mid); n++) mid = `${base}-${n + 1}`
877
+ const file = o.image === undefined ? undefined : `${mid}${extname(o.image).toLowerCase()}`
878
+ if (o.image !== undefined && file) {
879
+ mkdirSync(folder, { recursive: true })
880
+ copyFileSync(o.image, join(folder, file))
881
+ }
882
+ const session = partyOf(m.who) === 'agent' && m.session === undefined ? sessionId() : null
883
+ const out: Message = { id: mid, at: now.toISOString(), ...m, ...(session ? { session } : {}), ...(file ? { image: file } : {}) }
884
+ try {
885
+ c.append(id, out)
886
+ return out
887
+ } catch (e) {
888
+ // another process took that id between the look and the write: the next one
889
+ if ((e as { code?: unknown }).code !== 'EEXIST' || n > 50) throw e
890
+ n++
891
+ }
892
+ }
567
893
  }
568
894
 
569
895
  /** a reply on an item from `who` (the owner, or an agent by its name), with an optional image; `re` the message of the
@@ -577,6 +903,53 @@ export function addMessage(dir: string, id: string, who: string, text: unknown,
577
903
  return appendMessage(dir, id, { who, text: t.text, ...(typeof re === 'string' ? { re } : {}) }, { ...(image !== undefined ? { image } : {}), now })
578
904
  }
579
905
 
906
+ /** an agent's question to the owner on a thread's item: its words, two options or more, the option it picks; the
907
+ * owner answers it in one click (answerAsk) */
908
+ export function postAsk(dir: string, id: string, q: { who: string; text: unknown; options: readonly string[]; pick?: number; now?: Date }): Message {
909
+ if (!readItem(dir, id)) throw new Error(`no item ${id}`)
910
+ const t = textOf(q.text)
911
+ if ('error' in t) throw new Error(`the question: ${t.error.replace(/^text: /, '')}`)
912
+ const options = q.options.map((o) => o.trim()).filter((o) => o !== '')
913
+ if (options.length < 2) throw new Error('a question offers two options or more: --option "<a>" --option "<b>"')
914
+ if (q.pick !== undefined && !(Number.isInteger(q.pick) && q.pick >= 0 && q.pick < options.length)) throw new Error(`--pick: an option's number, 1 to ${options.length}`)
915
+ return appendMessage(dir, id, { who: q.who, text: t.text, ask: { options, ...(q.pick !== undefined ? { pick: q.pick } : {}) } }, q.now ? { now: q.now } : {})
916
+ }
917
+
918
+ /** an agent's proposed change of an object's text: the owner applies it, or applies his edit of it (answerAsk), and the
919
+ * agent lands what he applied */
920
+ export function postPropose(dir: string, id: string, p: { who: string; text: unknown; on: string; before?: string; after: string; now?: Date }): Message {
921
+ if (!readItem(dir, id)) throw new Error(`no item ${id}`)
922
+ if (!ADDRESS_RE.test(p.on)) throw new Error(`${p.on}: an address is <kind>:<key>`)
923
+ if (p.after.trim() === '') throw new Error('--after: the text it proposes')
924
+ const t = textOf(p.text ?? `a change of ${p.on}`)
925
+ if ('error' in t) throw new Error(t.error)
926
+ return appendMessage(dir, id, { who: p.who, text: t.text, propose: { on: p.on, ...(p.before !== undefined ? { before: p.before } : {}), after: p.after } }, p.now ? { now: p.now } : {})
927
+ }
928
+
929
+ /** the owner's answer to a question (an option) or to a proposed change (apply, the owner's edit in `text`), with words */
930
+ export function answerAsk(dir: string, id: string, a: { re: string; option?: number; apply?: boolean; text?: string; now?: Date }): Message {
931
+ const x = readItem(dir, id)
932
+ if (!x) throw new Error(`no item ${id}`)
933
+ const m = x.thread.find((y) => y.id === a.re)
934
+ if (!m || (m.ask === undefined && m.propose === undefined)) throw new Error(`re: ${a.re} is no question nor proposed change of ${id}`)
935
+ const words = a.text?.trim() ?? ''
936
+ if (m.ask) {
937
+ const o = a.option
938
+ if (o === undefined || !Number.isInteger(o) || o < 0 || o >= m.ask.options.length) throw new Error(`option: one of 0 to ${m.ask.options.length - 1}`)
939
+ const label = m.ask.options[o]!
940
+ return appendMessage(dir, id, { who: 'owner', re: a.re, answer: { option: o }, text: words === '' ? label : `${label}: ${words}` }, a.now ? { now: a.now } : {})
941
+ }
942
+ if (a.apply !== true) throw new Error('a proposed change is answered by apply, or by a reply')
943
+ return appendMessage(dir, id, { who: 'owner', re: a.re, answer: { apply: true }, text: words === '' ? m.propose!.after : words }, a.now ? { now: a.now } : {})
944
+ }
945
+
946
+ /** a link from a thread to another object: the thread names it, the object's thread control finds the thread */
947
+ export function attachTo(dir: string, id: string, who: string, address: string, now = new Date()): Message {
948
+ if (!readItem(dir, id)) throw new Error(`no item ${id}`)
949
+ if (!ADDRESS_RE.test(address)) throw new Error(`${address}: an address is <kind>:<key>`)
950
+ return appendMessage(dir, id, { who, text: `attached ${address}`, about: [address] }, { now })
951
+ }
952
+
580
953
  /** a view of files as typed: one file an image, a clip or a sound (by its extension), two a before and an after; loadView
581
954
  * checks them */
582
955
  export function filesView(label: string, files: readonly string[], usage: string): ViewInput {
@@ -593,6 +966,8 @@ export interface UpdateInput {
593
966
  state: string
594
967
  text: unknown
595
968
  files?: readonly string[]
969
+ /** its pictures as given, never a webp */
970
+ keep?: boolean
596
971
  now?: Date
597
972
  }
598
973
 
@@ -603,7 +978,7 @@ export async function postUpdate(dir: string, id: string, u: UpdateInput): Promi
603
978
  const x = readItem(dir, id)
604
979
  if (!x) throw new Error(`no card ${id}`)
605
980
  if (x.item.origin.by !== 'agent') throw new Error(`${id} was raised, not sent by an agent: an update goes on the card that answers it`)
606
- if (x.item.wip) throw new Error(`${id} is a draft on a live shot: its frame refreshes itself, sk review ready ${id} when it is done`)
981
+ if (x.item.wip) throw new Error(`${id} is a draft on a live shot: its frame refreshes itself, sk thread ready ${id} when it is done`)
607
982
  if (!UPDATE_STATES.includes(u.state as UpdateState)) throw new Error(`the state: one of ${UPDATE_STATES.join(', ')}, not « ${u.state} »`)
608
983
  const state = u.state as UpdateState
609
984
  const t = textOf(u.text)
@@ -612,7 +987,7 @@ export async function postUpdate(dir: string, id: string, u: UpdateInput): Promi
612
987
  for (const f of files) if (!existsSync(f)) throw new Error(`${f}: no such file`)
613
988
  const k = updatesOf(x).length + 1
614
989
  const label = `update ${k}: ${UPDATE_WORDS[state]}`
615
- const item = files.length === 0 ? x.item : await addView(dir, id, { ...filesView(label, files, `an update holds one file, or a before and an after: ${updateLine(id)}`), note: t.text }, { update: true })
990
+ const item = files.length === 0 ? x.item : await addView(dir, id, { ...filesView(label, files, `an update holds one file, or a before and an after: ${updateLine(id)}`), note: t.text }, { update: true, ...(u.keep ? { keep: true } : {}) })
616
991
  const view = files.length === 0 ? null : item.views.length - 1
617
992
  const message = appendMessage(dir, id, { who: u.who, text: t.text, update: { state, ...(view !== null ? { view } : {}) } }, u.now ? { now: u.now } : {})
618
993
  return { item, message, tag: `update ${k} (${UPDATE_WORDS[state]})`, view }
@@ -631,7 +1006,7 @@ export function markRead(dir: string, id: string, party: Party, who: string = pa
631
1006
  /** the path of a message's image, null for any other name */
632
1007
  export function threadImage(dir: string, id: string, name: string): string | null {
633
1008
  if (!ID_RE.test(id) || !MESSAGE_FILE_RE.test(name)) return null
634
- const f = join(dir, id, 'thread', name)
1009
+ const f = join(io(dir).folder(id), 'thread', name)
635
1010
  return existsSync(f) ? f : null
636
1011
  }
637
1012
 
@@ -664,7 +1039,7 @@ function readOne(dir: string, id: string): Read {
664
1039
 
665
1040
  /** every item of the store as its unit reads it: an item its unit refuses (a subject kind or a topic it does not
666
1041
  * declare, a subject's problems) is broken; the index keeps the raw reads, so a unit's change never invalidates it */
667
- export const readAll = (dir: string): ReadAll => checked(readRaws(dir), specOf(dir))
1042
+ export const readAll = (dir: string): ReadAll => checked(cardsInDb() ? rowsAll(dir) : readRaws(dir), specOf(dir))
668
1043
 
669
1044
  const checks = new WeakMap<ReadAll, { spec: Spec; all: ReadAll }>()
670
1045
 
@@ -686,10 +1061,10 @@ function checked(raw: ReadAll, spec: Spec): ReadAll {
686
1061
  /** the json index each store kept beside it before the machine index, removed once per process */
687
1062
  const OLD_INDEX = (dir: string): string => join(dirname(resolve(dir)), `.${basename(dir)}-index.shipkit.json`)
688
1063
  const swept = new Set<string>()
689
- /** the stores this process marked its code as using, once each */
690
- const used = new Set<string>()
691
- /** a code that read no store for this long: its reads go */
692
- const CODE_KEEP_MS = 7 * 24 * 3600_000
1064
+ /** when this process last marked its code as using each store: again each USED_EVERY_MS, so the media job's tidy
1065
+ * (media-store/tidy.ts) never takes the reads of a code that runs */
1066
+ const used = new Map<string, number>()
1067
+ const USED_EVERY_MS = 3600_000
693
1068
 
694
1069
  /** items a step of a read covers before it gives the loop back (readRawsAsync) */
695
1070
  const READ_STEP = 250
@@ -724,7 +1099,7 @@ function* readRawsSteps(dir: string, stamps?: Map<string, string>): Generator<vo
724
1099
  const was = new Map<string, { stamp: string; read: string }>()
725
1100
  if (db)
726
1101
  try {
727
- for (const r of db.query('select id, stamp, read from items where store = ? and code = ?').all(store, code) as { id: string; stamp: string; read: string }[]) was.set(r.id, r)
1102
+ for (const r of db.query('select id, stamp, read from media_items where store = ? and code = ?').all(store, code) as { id: string; stamp: string; read: string }[]) was.set(r.id, r)
728
1103
  } catch (e) {
729
1104
  console.error(`WARN review index: ${store} read from its files: ${(e as Error).message}`)
730
1105
  }
@@ -757,20 +1132,17 @@ function* readRawsSteps(dir: string, stamps?: Map<string, string>): Generator<vo
757
1132
  else out.broken.push({ id, error: read.error })
758
1133
  }
759
1134
  const gone = [...was.keys()].filter((id) => !seen.has(id))
760
- const first = !used.has(store)
761
- if (moved.length === 0 && gone.length === 0 && !first) return out
762
- used.add(store)
1135
+ const now = Date.now()
1136
+ const due = now - (used.get(store) ?? 0) >= USED_EVERY_MS
1137
+ if (moved.length === 0 && gone.length === 0 && !due) return out
1138
+ used.set(store, now)
1139
+ // the reads of a code no process runs leave in the media job's tidy, in small steps, never here
763
1140
  tryWrite(`the reads of ${store}`, (d) => {
764
- const now = Date.now()
765
- d.query('insert or replace into codes (store, code, used) values (?, ?, ?)').run(store, code, now)
766
- const put = d.query('insert or replace into items (store, code, id, stamp, read) values (?, ?, ?, ?, ?)')
1141
+ d.query('insert or replace into media_codes (store, code, used) values (?, ?, ?)').run(store, code, now)
1142
+ const put = d.query('insert or replace into media_items (store, code, id, stamp, read) values (?, ?, ?, ?, ?)')
767
1143
  for (const m of moved) put.run(store, code, m.id, m.stamp, JSON.stringify(m.read))
768
- const drop = d.query('delete from items where store = ? and code = ? and id = ?')
1144
+ const drop = d.query('delete from media_items where store = ? and code = ? and id = ?')
769
1145
  for (const id of gone) drop.run(store, code, id)
770
- for (const r of d.query('select code from codes where store = ? and used < ?').all(store, now - CODE_KEEP_MS) as { code: string }[]) {
771
- d.query('delete from items where store = ? and code = ?').run(store, r.code)
772
- d.query('delete from codes where store = ? and code = ?').run(store, r.code)
773
- }
774
1146
  })
775
1147
  return out
776
1148
  }
@@ -802,8 +1174,8 @@ export function withdraw(dir: string, id: string, why: string, now = new Date())
802
1174
  if (before) return { already: `by ${before.who}, ${before.at.slice(0, 16).replace('T', ' ')} UTC` }
803
1175
  const v = verdictOf(x)
804
1176
  if (v) {
805
- const owes = v.status === 'approved-with-fix' ? `sk review done ${id} "<what changed>", ` : ''
806
- const close = v.status === 'approved-with-fix' || v.status === 'rejected' ? `; what it owes: ${owes}--supersedes ${id} on its new card, or sk review wontfix ${id} --note "<why>"` : ''
1177
+ const owes = v.status === 'approved-with-fix' ? `sk thread done ${id} "<what changed>", ` : ''
1178
+ const close = v.status === 'approved-with-fix' || v.status === 'rejected' ? `; what it owes: ${owes}--supersedes ${id} on its new card, or sk thread wontfix ${id} --note "<why>"` : ''
807
1179
  return { refused: `${id}: he answered it (${v.status}), so it waits on him no more${close}` }
808
1180
  }
809
1181
  appendMessage(dir, id, { who: agentName(), op: 'withdraw', note: why }, { now })
@@ -823,7 +1195,7 @@ export function reopen(dir: string, id: string, o: { who?: string; now?: Date }
823
1195
  /** the path of one image, clip or poster of an item, null for any other name */
824
1196
  export function imageFile(dir: string, id: string, name: string): string | null {
825
1197
  if (!ID_RE.test(id) || !FILE_RE.test(name)) return null
826
- const f = join(dir, id, name)
1198
+ const f = join(io(dir).folder(id), name)
827
1199
  return existsSync(f) ? f : null
828
1200
  }
829
1201
 
@@ -857,10 +1229,11 @@ export async function raiseItem(dir: string, input: RaiseInput): Promise<ReviewI
857
1229
  if (input.image !== undefined && (!existsSync(input.image) || !IMAGE_EXT.test(extname(input.image).toLowerCase()))) throw new Error(`${input.image}: a png, jpg or webp`)
858
1230
  const now = input.now ?? new Date()
859
1231
  mkdirSync(dir, { recursive: true })
860
- if (input.id !== undefined && (!ID_RE.test(input.id) || existsSync(join(dir, input.id)))) throw new Error(`${input.id}: no item id, or taken`)
1232
+ const c = io(dir)
1233
+ if (input.id !== undefined && (!ID_RE.test(input.id) || c.taken(input.id))) throw new Error(`${input.id}: no item id, or taken`)
861
1234
  const base = input.id ?? idOf(now, input.title)
862
1235
  let id = base
863
- for (let n = 2; existsSync(join(dir, id)); n++) id = `${base}-${n}`
1236
+ for (let n = 2; c.taken(id); n++) id = `${base}-${n}`
864
1237
  const image = input.image === undefined ? undefined : `image${extname(input.image).toLowerCase()}`
865
1238
  const item: Item = {
866
1239
  id,
@@ -875,12 +1248,10 @@ export async function raiseItem(dir: string, input: RaiseInput): Promise<ReviewI
875
1248
  }
876
1249
  const problems = [...itemProblems(item), ...specProblems(item, specOf(dir))]
877
1250
  if (problems.length > 0) throw new Error(problems.join('; '))
878
- const tmp = join(dir, `.${id}.tmp`)
879
- rmSync(tmp, { recursive: true, force: true })
880
- mkdirSync(tmp)
1251
+ const tmp = tmpOf(c, id)
881
1252
  if (input.image !== undefined && image) copyFileSync(input.image, join(tmp, image))
882
- writeJson(join(tmp, 'item.json'), { ...item, ...(image ? { media: await factsOf(tmp, [image]) } : {}) })
883
- renameSync(tmp, join(dir, id))
1253
+ const head = { ...item, ...(image ? { media: await factsOf(tmp, [image]) } : {}) }
1254
+ createAtCommit(dir, c, id, tmp, head)
884
1255
  const who = input.origin.by === 'player' ? 'player' : 'owner'
885
1256
  if (text) appendMessage(dir, id, { who, text, ...(input.rects && input.rects.length > 0 ? { rects: input.rects } : {}) }, { now })
886
1257
  return readItem(dir, id) as ReviewItem
@@ -922,15 +1293,17 @@ export async function ownerVerdict(dir: string, o: { subject: Subject; from: str
922
1293
  }
923
1294
 
924
1295
  /** the lock of one item while an act is checked and written: a folder made atomically, waited on for at most 2 s */
925
- function locked<T>(dir: string, id: string, fn: () => T): T {
1296
+ function locked<T>(dir: string, id: string, fn: () => T, waitMs = 2000): T {
926
1297
  const lock = join(dir, id, '.lock')
927
- const until = Date.now() + 2000
1298
+ const until = Date.now() + waitMs
928
1299
  for (;;) {
929
1300
  try {
930
1301
  mkdirSync(lock)
931
1302
  break
932
- } catch {
933
- if (Date.now() > until) {
1303
+ } catch (e) {
1304
+ // only a lock another holds is waited for: a folder that is missing or a file in the way is said at once
1305
+ if ((e as { code?: unknown }).code !== 'EEXIST') throw e
1306
+ if (Date.now() >= until) {
934
1307
  // a lock left by a dead process: older than the wait itself
935
1308
  if (Date.now() - statSync(lock).mtimeMs > 2000) {
936
1309
  rmSync(lock, { recursive: true, force: true })
@@ -961,7 +1334,9 @@ export function act(dir: string, id: string, op: Exclude<Op, 'seen'>, who: strin
961
1334
  if (o.topic !== undefined && Object.keys(spec.topics).length > 0 && !spec.topics[o.topic]) throw new Error(`no topic « ${o.topic} »: ${Object.keys(spec.topics).join(', ')}`)
962
1335
  if (o.commit !== undefined && !/^[0-9a-f]{7,40}$/.test(o.commit)) throw new Error(`« ${o.commit} » is no commit`)
963
1336
  const now = o.now ?? new Date()
964
- return locked(dir, id, () => {
1337
+ // the first read of a process reads every card: done before the lock, the read under it only takes what moved
1338
+ readAll(dir)
1339
+ return io(dir).lock(id, () => {
965
1340
  const x = readItem(dir, id) as ReviewItem
966
1341
  const superseded = isFollowed(id, readAll(dir).items)
967
1342
  const role = spec.dispatcher ? (roleOf(dir)?.name ?? null) : null
@@ -1015,7 +1390,7 @@ export function deleteRaised(dir: string, id: string): void {
1015
1390
  const x = ID_RE.test(id) ? readItem(dir, id) : null
1016
1391
  if (!x) throw new Error(`no item ${id}`)
1017
1392
  if (x.item.origin.by !== 'owner') throw new Error(`${id} was not raised by the owner: never deleted from the hub`)
1018
- rmSync(join(dir, id), { recursive: true, force: true })
1393
+ removeItem(dir, id)
1019
1394
  }
1020
1395
 
1021
1396
  /** a player's report removed from the store, once its source deleted it there */
@@ -1023,7 +1398,43 @@ export function deleteReport(dir: string, id: string): void {
1023
1398
  const x = ID_RE.test(id) ? readItem(dir, id) : null
1024
1399
  if (!x) throw new Error(`no item ${id}`)
1025
1400
  if (x.item.origin.by !== 'player') throw new Error(`${id} is no player's report`)
1026
- rmSync(join(dir, id), { recursive: true, force: true })
1401
+ removeItem(dir, id)
1402
+ }
1403
+
1404
+ export { GONE, GONE_KEEP_MS, goneCreated, goneEntries, sweepGone } from './gone.ts'
1405
+
1406
+ /** a card out of the store: set aside while this machine carries its cards to the hq (the switch hq-cards), so the
1407
+ * job sends its deletion, and always as rows (kept GONE_KEEP_MS, the way back), else removed as it always was */
1408
+ function removeItem(dir: string, id: string): void {
1409
+ const c = io(dir)
1410
+ // while a move runs, a deletion stays as a card set aside, so neither pass carries the card back
1411
+ if (c.rows || cardsOn() || cardsMoving()) c.setAside(id, {})
1412
+ else rmSync(join(dir, id), { recursive: true, force: true })
1413
+ }
1414
+
1415
+ /** a card's folder moved to `.gone/<id>` (or `<id>.<n>` beside an earlier one), whole and under its lock: the one way
1416
+ * a card leaves the store when another machine deleted it. `created`: only the card made at that moment, so another
1417
+ * card under that id stays. What it did */
1418
+ export const setAside = (dir: string, id: string, o: { created?: string; before?: number } = {}): 'moved' | 'none' | 'other' => (ID_RE.test(id) ? io(dir).setAside(id, o) : 'none')
1419
+
1420
+ /** the files' set aside: the folder moved, whole */
1421
+ function setAsideFile(dir: string, id: string, o: { created?: string; before?: number }): 'moved' | 'none' | 'other' {
1422
+ if (!ID_RE.test(id) || !existsSync(join(dir, id))) return 'none'
1423
+ return locked(dir, id, () => {
1424
+ if (o.created !== undefined || o.before !== undefined) {
1425
+ const f = join(dir, id, 'item.json')
1426
+ const cur = existsSync(f) ? (JSON.parse(readFileSync(f, 'utf8')) as { created?: unknown }) : null
1427
+ if (o.created !== undefined && cur?.created !== o.created) return 'other'
1428
+ // `before`: only a card made before that moment
1429
+ if (o.before !== undefined && !(Date.parse(String(cur?.created)) < o.before)) return 'other'
1430
+ }
1431
+ mkdirSync(join(dir, GONE), { recursive: true })
1432
+ const to = join(dir, GONE, goneEntryFor(dir, id))
1433
+ renameSync(join(dir, id), to)
1434
+ // the lock moved with the folder: the card is no longer here to lock
1435
+ rmSync(join(to, '.lock'), { recursive: true, force: true })
1436
+ return 'moved'
1437
+ })
1027
1438
  }
1028
1439
 
1029
1440
  /** a player's report by its ref (`live#3`: its server and number), or an item by its id. A pulled report's item is named
@@ -1033,7 +1444,7 @@ export function itemOfRef(dir: string, ref: string): ReviewItem | null {
1033
1444
  if (!m) return ID_RE.test(ref) ? readItem(dir, ref) : itemOfPrefix(dir, ref)
1034
1445
  const holds = (x: ReviewItem | null): x is ReviewItem => x !== null && x.item.origin.by === 'player' && x.item.origin.server === m[1] && x.item.origin.serverId === Number(m[2])
1035
1446
  const tail = `-${m[1]}-${m[2]}`
1036
- for (const n of existsSync(dir) ? readdirSync(dir).filter((n) => n.endsWith(tail)).sort() : []) {
1447
+ for (const n of io(dir).names().filter((n) => n.endsWith(tail))) {
1037
1448
  try {
1038
1449
  const x = readItem(dir, n)
1039
1450
  if (holds(x)) return x
@@ -1048,8 +1459,8 @@ export function itemOfRef(dir: string, ref: string): ReviewItem | null {
1048
1459
  * a short id never picks one by chance. A longer ref is an exact id: a gone item's id never lands on one it starts */
1049
1460
  function itemOfPrefix(dir: string, ref: string): ReviewItem | null {
1050
1461
  const p = ref.trim()
1051
- if (!/^\d{8}-\d{6}$/.test(p) || !existsSync(dir)) return null
1052
- const hits = readdirSync(dir).filter((n) => n.startsWith(`${p}-`))
1462
+ if (!/^\d{8}-\d{6}$/.test(p)) return null
1463
+ const hits = io(dir).names().filter((n) => n.startsWith(`${p}-`))
1053
1464
  if (hits.length > 1) throw new Error(`${p} starts ${hits.length} items: ${hits.sort().join(', ')}; give more of the id`)
1054
1465
  return hits.length === 1 ? readItem(dir, hits[0]!) : null
1055
1466
  }
@@ -1066,10 +1477,13 @@ export async function refreshDraft(dir: string, id: string, o: { image: string;
1066
1477
  if (!r.wip || verdictOf(x)) throw new Error(`${id} is not a draft card waiting`)
1067
1478
  const f0 = r.views[0]
1068
1479
  if (!f0 || isGallery(f0) || !('image' in f0.files)) throw new Error(`${id}: its first view is no image`)
1069
- const folder = join(dir, id)
1070
- const main = await loadView({ label: f0.label, image: o.image }, 'the live frame')
1480
+ const folder = io(dir).folder(id)
1481
+ mkdirSync(folder, { recursive: true })
1071
1482
  const image = f0.files.image
1072
- copyFileSync(main.sources[0]?.[1] ?? '', join(folder, `${image}.tmp`))
1483
+ // the frame keeps the name the card gave its first one: a webp, or a picture as given before cards kept webps
1484
+ const webp = extname(image) === '.webp'
1485
+ const main = await loadView({ label: f0.label, image: o.image }, 'the live frame', webp ? { always: true } : { keep: true })
1486
+ putFile(main, main.sources[0]?.[1] ?? '', join(folder, `${image}.tmp`))
1073
1487
  renameSync(join(folder, `${image}.tmp`), join(folder, image))
1074
1488
  // a draft's one gallery is its history
1075
1489
  const label = r.views.find((v) => 'gallery' in v)?.label ?? HISTORY
@@ -1107,7 +1521,8 @@ export async function readyItem(dir: string, id: string, o: { image?: string; no
1107
1521
  const f0 = rest.views[0]
1108
1522
  if (!f0 || isGallery(f0)) throw new Error(`${id} has no image to replace`)
1109
1523
  const loaded = await loadView({ label: f0.label, image: o.image }, '--image')
1110
- const folder = join(dir, id)
1524
+ const folder = io(dir).folder(id)
1525
+ mkdirSync(folder, { recursive: true })
1111
1526
  const old = 'image' in f0.files ? f0.files.image : undefined
1112
1527
  copyFiles(loaded, 0, folder)
1113
1528
  const files = filesOf(loaded, 0)
@@ -1184,6 +1599,21 @@ function touched(path: string): void {
1184
1599
  wrote++
1185
1600
  const p = resolve(path)
1186
1601
  for (const [key, w] of watched) if (w && p.startsWith(`${key}/`)) w.dirty.add(p.slice(key.length + 1).split('/')[0] ?? '')
1602
+ stampStore(p)
1603
+ }
1604
+
1605
+ const STORE_SEGMENT = `/${LAYOUT.review}/`
1606
+ /** a write in a card moves the store folder's own times: a process with no watch of it (the daemon's due, a watch that
1607
+ * died) sees any process's write with one stat of the folder. A lock is no change of the store */
1608
+ function stampStore(p: string): void {
1609
+ const i = p.lastIndexOf(STORE_SEGMENT)
1610
+ if (i < 0 || p.endsWith('/.lock')) return
1611
+ const now = new Date()
1612
+ try {
1613
+ fs.utimesSync(p.slice(0, i + STORE_SEGMENT.length - 1), now, now)
1614
+ } catch {
1615
+ // the store went with the write that named it
1616
+ }
1187
1617
  }
1188
1618
 
1189
1619
  function watchOf(dir: string): Watched | null {
@@ -1211,6 +1641,7 @@ function watchOf(dir: string): Watched | null {
1211
1641
  /** a watched store read whole before a page asks, the loop given back between two steps: the first read after a boot
1212
1642
  * is the only whole one, every later one reads the items that moved */
1213
1643
  export async function warmStore(dir: string): Promise<void> {
1644
+ if (cardsInDb()) return void rowsAll(dir)
1214
1645
  if (!existsSync(dir)) return
1215
1646
  const w = watchOf(dir)
1216
1647
  if (!w || (w.held && w.all)) return
@@ -1226,6 +1657,7 @@ export async function warmStore(dir: string): Promise<void> {
1226
1657
  /** changes when anything the list is built from changes: watched, a count of writes and what the disk check found;
1227
1658
  * else a scan. The list's ETag */
1228
1659
  export function storeStamp(dir: string, now = Date.now()): string {
1660
+ if (cardsInDb()) return rowsStamp(dir)
1229
1661
  if (!existsSync(dir)) return 'none'
1230
1662
  const w = watchOf(dir)
1231
1663
  if (!w) return scanStamp(dir)
@@ -1233,11 +1665,25 @@ export function storeStamp(dir: string, now = Date.now()): string {
1233
1665
  return `${BOOT}.${w.moved}.${w.rev}.${wrote}`
1234
1666
  }
1235
1667
 
1668
+ /** what moved the store, from what this process heard: its watch's events, its own writes, the store folder (one
1669
+ * stat). Never a stat of its items: an event the watch missed waits for the next walk of the caller's own */
1670
+ export function storeMoved(dir: string): string {
1671
+ if (cardsInDb()) return rowsStamp(dir)
1672
+ if (!existsSync(dir)) return 'none'
1673
+ const key = resolve(dir)
1674
+ const w = watchOf(dir)
1675
+ return w ? `${BOOT}.${w.moved}.${wrote}.${folderStamp(key)}` : `${BOOT}.-.${wrote}.${folderStamp(key)}`
1676
+ }
1677
+
1678
+ /** does the store hold anything: its folder, or with the switch cards-in-db its rows (a repo's cards may have no folder) */
1679
+ export const hasStore = (dir: string): boolean => (cardsInDb() ? rowsStamp(dir) !== 'none' : existsSync(dir))
1680
+
1236
1681
  /** the store's stamp and who listens (the live watchers' pids), so a watch that starts or dies moves it too */
1237
1682
  export const listingStamp = (dir: string): string => `${storeStamp(dir)}~${liveWatchers(dir).map((w) => w.pid).join(',')}`
1238
1683
 
1239
1684
  /** the stamp from a scan of every item's files: the safety net of a watcher that may miss an event */
1240
1685
  export function scanStamp(dir: string): string {
1686
+ if (cardsInDb()) return rowsStamp(dir)
1241
1687
  const h = new Bun.CryptoHasher('sha1')
1242
1688
  if (!existsSync(dir)) return 'none'
1243
1689
  const mark = (f: string): void => {
@@ -1256,7 +1702,7 @@ export function scanStamp(dir: string): string {
1256
1702
  let cached: { dir: string; tag: string; all: ReadAll } | null = null
1257
1703
 
1258
1704
  /** readAll kept while nothing it reads changed: watched, only the items written since are read again */
1259
- export const readAllCached = (dir: string): ReadAll => checked(readRawsCached(dir), specOf(dir))
1705
+ export const readAllCached = (dir: string): ReadAll => checked(cardsInDb() ? rowsAll(dir) : readRawsCached(dir), specOf(dir))
1260
1706
 
1261
1707
  function readRawsCached(dir: string): ReadAll {
1262
1708
  const w = existsSync(dir) ? watchOf(dir) : null