rvlib-shipkit 2.26.0 → 2.28.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 (605) hide show
  1. package/CHANGELOG.md +36 -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 +16 -7
  6. package/src/agent-time/limits.ts +44 -0
  7. package/src/agent-time/live.ts +12 -8
  8. package/src/agent-time/mask.ts +96 -18
  9. package/src/agent-time/refused.ts +45 -0
  10. package/src/agent-time/registry.ts +289 -0
  11. package/src/agent-time/render.ts +122 -21
  12. package/src/agent-time/report-cache.ts +57 -0
  13. package/src/agent-time/report.ts +314 -40
  14. package/src/agent-time/shape.ts +50 -3
  15. package/src/agent-time/store.ts +322 -101
  16. package/src/agent-time/timeline.ts +140 -21
  17. package/src/agent-time/turns.ts +18 -8
  18. package/src/annex/born.ts +2 -2
  19. package/src/annex/offload.ts +29 -17
  20. package/src/annex/tidy.ts +70 -10
  21. package/src/asks/ask-after.ts +44 -0
  22. package/src/asks/ask-bar-fold.ts +57 -0
  23. package/src/asks/ask-migrate.ts +280 -0
  24. package/src/asks/ask-steps-fold.ts +166 -0
  25. package/src/asks/ask-store.ts +586 -0
  26. package/src/assets/kit-config.ts +7 -3
  27. package/src/assets/kits/identity-kit.ts +361 -14
  28. package/src/assets/kits/poster-thumbnail.ts +282 -0
  29. package/src/check.ts +3 -1
  30. package/src/checks/SK003-claude-md-shape.check.ts +92 -25
  31. package/src/checks/SK004-gitignore-policy.check.ts +20 -9
  32. package/src/checks/SK013-one-way-in-policy.check.ts +18 -3
  33. package/src/checks/SK026-asks-autoclose.check.ts +9 -23
  34. package/src/checks/SK028-readme.check.ts +7 -66
  35. package/src/checks/SK030-cache-audit.check.ts +6 -1
  36. package/src/checks/SK031-trace-audit.check.ts +2 -0
  37. package/src/checks/SK033-global-contribution.check.ts +3 -1
  38. package/src/checks/SK035-public-clean.check.ts +2 -2
  39. package/src/checks/SK038-speaks-as.check.ts +3 -3
  40. package/src/checks/SK042-post-kinds.check.ts +26 -24
  41. package/src/checks/SK043-scratch-on-the-mac.check.ts +59 -4
  42. package/src/checks/SK047-login-in-description.check.ts +36 -0
  43. package/src/checks/SK048-one-local-file.check.ts +36 -0
  44. package/src/checks/SK049-thread-answers-hook.check.ts +81 -0
  45. package/src/checks/SK050-retired-commands.check.ts +127 -0
  46. package/src/cli/cmd_Asks.ts +244 -27
  47. package/src/cli/cmd_Backup.ts +153 -10
  48. package/src/cli/cmd_Calls.ts +1 -0
  49. package/src/cli/cmd_Capacity.ts +2 -2
  50. package/src/cli/cmd_Commands.ts +140 -34
  51. package/src/cli/cmd_Contracts.ts +1 -0
  52. package/src/cli/cmd_CrossRepoActivity.ts +5 -4
  53. package/src/cli/cmd_Db.ts +253 -0
  54. package/src/cli/cmd_History.ts +212 -0
  55. package/src/cli/cmd_Home.ts +31 -3
  56. package/src/cli/cmd_Hq.ts +516 -0
  57. package/src/cli/cmd_Keys.ts +1 -0
  58. package/src/cli/cmd_Lanes.ts +15 -4
  59. package/src/cli/cmd_Machines.ts +36 -0
  60. package/src/cli/cmd_Media.ts +38 -6
  61. package/src/cli/cmd_Messages.ts +152 -1
  62. package/src/cli/cmd_Needs.ts +1 -0
  63. package/src/cli/cmd_Reflect.ts +23 -2
  64. package/src/cli/cmd_Review.ts +1357 -223
  65. package/src/cli/cmd_Secret.ts +295 -24
  66. package/src/cli/cmd_Social.ts +113 -28
  67. package/src/cli/cmd_SocialDrafts.ts +235 -0
  68. package/src/cli/cmd_Sound.ts +22 -1
  69. package/src/cli/cmd_Space.ts +324 -0
  70. package/src/cli/cmd_Start.ts +3 -2
  71. package/src/cli/cmd_ThreadHolds.ts +34 -0
  72. package/src/cli/cmd_ThreadKinds.ts +146 -0
  73. package/src/cli/cmd_ThreadReflect.ts +83 -0
  74. package/src/cli/cmd_ThreadSyncNeeds.ts +62 -0
  75. package/src/cli/cmd_Time.ts +76 -5
  76. package/src/cli/cmd_Tmp.ts +28 -4
  77. package/src/cli/cmd_Trailer.ts +14 -10
  78. package/src/cli/cmd_Urls.ts +56 -0
  79. package/src/cli/cmd_Vault.ts +583 -0
  80. package/src/cli/cmd_When.ts +1 -0
  81. package/src/cli/family-help.ts +5 -3
  82. package/src/cli/family-pages.ts +1 -1
  83. package/src/cli/kit/builtins.ts +1 -0
  84. package/src/cli/kit/verb.ts +6 -2
  85. package/src/cli/registry.ts +44 -4
  86. package/src/cli.ts +5 -2
  87. package/src/collections/actions.ts +42 -41
  88. package/src/collections/collection-types.ts +30 -4
  89. package/src/collections/md-body.ts +5 -3
  90. package/src/collections/pings.ts +13 -6
  91. package/src/collections/providers.ts +147 -61
  92. package/src/collections/reflections.ts +9 -4
  93. package/src/collections/review.ts +4 -4
  94. package/src/contracts/contract-manifests.ts +6 -5
  95. package/src/contracts/contract-types.ts +6 -4
  96. package/src/contracts/contracts-engine.ts +11 -0
  97. package/src/contracts/manifests/chrome-web-store.contract.ts +31 -0
  98. package/src/core/budget.ts +12 -17
  99. package/src/core/capacity.ts +27 -18
  100. package/src/core/check-runner.ts +7 -4
  101. package/src/core/discover-checks.ts +18 -3
  102. package/src/core/git.ts +31 -0
  103. package/src/core/house-layout.ts +17 -0
  104. package/src/core/layout.ts +13 -5
  105. package/src/core/locked-write.ts +4 -1
  106. package/src/core/machine-busy.ts +127 -0
  107. package/src/core/machine-commit.ts +6 -1
  108. package/src/core/machine-db.ts +370 -20
  109. package/src/core/machine-layout.ts +137 -0
  110. package/src/core/machine-read.ts +81 -0
  111. package/src/core/migrate-layout.ts +9 -11
  112. package/src/core/one-way-in-policy.ts +64 -7
  113. package/src/core/polling-policy.ts +27 -0
  114. package/src/core/retention.ts +16 -2
  115. package/src/core/scope.ts +107 -14
  116. package/src/core/slots.ts +5 -4
  117. package/src/drill/clean.ts +25 -1
  118. package/src/drill/run.ts +1 -1
  119. package/src/drill/seal.ts +27 -4
  120. package/src/home/activity-shape.ts +2 -0
  121. package/src/home/activity.ts +59 -3
  122. package/src/home/app-sign.ts +15 -4
  123. package/src/home/daemon-jobs.ts +161 -7
  124. package/src/home/database-projects.ts +111 -0
  125. package/src/home/database-words.ts +203 -0
  126. package/src/home/databases.ts +460 -0
  127. package/src/home/global-units.ts +6 -0
  128. package/src/home/gui-app/ShipkitGui.swift +122 -1
  129. package/src/home/gui-app.ts +6 -3
  130. package/src/home/home-move.ts +514 -0
  131. package/src/home/home-paths.ts +18 -6
  132. package/src/home/home-routes.ts +76 -0
  133. package/src/home/inbox-shape.ts +234 -91
  134. package/src/home/inbox.ts +26 -71
  135. package/src/home/machine-fold.ts +815 -0
  136. package/src/home/machine-host.ts +38 -5
  137. package/src/home/machine-repair.ts +503 -0
  138. package/src/home/machine-stores.ts +66 -15
  139. package/src/home/machine-temp.ts +547 -86
  140. package/src/home/other-macs.ts +2 -2
  141. package/src/home/resume.ts +79 -0
  142. package/src/home/run-daemon.ts +25 -4
  143. package/src/home/run-pm.ts +18 -5
  144. package/src/home/serve-daemon.ts +18 -3
  145. package/src/home/serve-web.ts +179 -10
  146. package/src/home/space-job.ts +115 -0
  147. package/src/home/space-page.ts +257 -0
  148. package/src/home/space-route.ts +167 -0
  149. package/src/home/space-words.ts +103 -0
  150. package/src/home/time-page-shape.ts +202 -0
  151. package/src/home/time-page.ts +64 -0
  152. package/src/home/vault-page.ts +516 -0
  153. package/src/home/vault-words.ts +132 -0
  154. package/src/hooks/leak-guard.ts +40 -13
  155. package/src/hooks/one-way-in-guard.ts +41 -6
  156. package/src/hq/cards.ts +581 -0
  157. package/src/hq/door-route.ts +43 -0
  158. package/src/hq/door.ts +163 -0
  159. package/src/hq/files-send.ts +347 -0
  160. package/src/hq/forgotten-log.ts +35 -0
  161. package/src/hq/history-check.ts +255 -0
  162. package/src/hq/history-place.ts +146 -0
  163. package/src/hq/history-send.ts +487 -0
  164. package/src/hq/hq-db.ts +102 -0
  165. package/src/hq/hq-local.ts +502 -0
  166. package/src/hq/hq-routes.ts +204 -0
  167. package/src/hq/hq-store.ts +603 -0
  168. package/src/hq/kinds/ask.ts +147 -0
  169. package/src/hq/kinds/card-gone.ts +83 -0
  170. package/src/hq/kinds/card-msg.ts +66 -0
  171. package/src/hq/kinds/card.ts +99 -0
  172. package/src/hq/kinds/index.ts +21 -0
  173. package/src/hq/kinds/kind.ts +126 -0
  174. package/src/hq/kinds/media.ts +125 -0
  175. package/src/hq/kinds/prompt.ts +219 -0
  176. package/src/hq/kinds/reflection.ts +128 -0
  177. package/src/hq/kinds/report.ts +55 -0
  178. package/src/hq/kinds/time-day.ts +236 -0
  179. package/src/hq/ledger.ts +473 -0
  180. package/src/hq/machine-key.ts +44 -0
  181. package/src/hq/machine-notes.ts +131 -0
  182. package/src/hq/outbox.ts +374 -0
  183. package/src/hq/replica.ts +167 -0
  184. package/src/hq/repo-id.ts +4 -0
  185. package/src/hq/report-facts.ts +117 -0
  186. package/src/hq/report.ts +274 -0
  187. package/src/hq/switch.ts +151 -0
  188. package/src/hq/vault-grant.ts +92 -0
  189. package/src/hq/vault-route.ts +112 -0
  190. package/src/identities/collection.ts +2 -2
  191. package/src/identities/identities.ts +24 -11
  192. package/src/identities/machine-route.ts +8 -3
  193. package/src/identities/steps.ts +31 -0
  194. package/src/ledger/db.ts +81 -27
  195. package/src/ledger/gate-checks.ts +6 -2
  196. package/src/ledger/run-log.ts +11 -3
  197. package/src/ledger/store.ts +26 -4
  198. package/src/media-store/backup/daemon.ts +73 -25
  199. package/src/media-store/backup/kept.ts +241 -0
  200. package/src/media-store/backup/keys.ts +1 -1
  201. package/src/media-store/backup/manifest.ts +20 -2
  202. package/src/media-store/backup/prune.ts +365 -0
  203. package/src/media-store/backup/restore.ts +14 -4
  204. package/src/media-store/backup/retention.ts +122 -0
  205. package/src/media-store/backup/run.ts +25 -19
  206. package/src/media-store/backup/secret.ts +6 -4
  207. package/src/media-store/backup/snapshot.ts +4 -2
  208. package/src/media-store/backup/sources.ts +83 -31
  209. package/src/media-store/backup/thread-copy.ts +340 -0
  210. package/src/media-store/copy/config.ts +76 -0
  211. package/src/media-store/copy/copy.ts +194 -0
  212. package/src/media-store/copy/lifecycle.ts +43 -0
  213. package/src/media-store/copy/night.ts +90 -0
  214. package/src/media-store/copy/proof.ts +151 -0
  215. package/src/media-store/copy/snapshot.ts +152 -0
  216. package/src/media-store/copy/store.ts +62 -0
  217. package/src/media-store/copy/stream.ts +176 -0
  218. package/src/media-store/daemon.ts +66 -16
  219. package/src/media-store/db.ts +24 -13
  220. package/src/media-store/forget.ts +141 -3
  221. package/src/media-store/hand.ts +4 -3
  222. package/src/media-store/hq-find.ts +75 -0
  223. package/src/media-store/hq-send.ts +277 -0
  224. package/src/media-store/kind.ts +2 -0
  225. package/src/media-store/purge.ts +21 -17
  226. package/src/media-store/put.ts +24 -8
  227. package/src/media-store/remote.ts +16 -7
  228. package/src/media-store/space-listing.ts +256 -0
  229. package/src/media-store/space.ts +46 -26
  230. package/src/media-store/sync.ts +5 -5
  231. package/src/media-store/tidy.ts +98 -0
  232. package/src/media-store/upload.ts +3 -3
  233. package/src/media-store/webp.ts +66 -0
  234. package/src/messages/guard.ts +49 -0
  235. package/src/messages/model.ts +16 -7
  236. package/src/messages/objects.ts +201 -0
  237. package/src/messages/routes.ts +14 -4
  238. package/src/messages/score.ts +3 -3
  239. package/src/messages/write.ts +285 -0
  240. package/src/pages/frame-client.ts +191 -4
  241. package/src/plan/planner.ts +28 -17
  242. package/src/recordings/media-kind.ts +1 -0
  243. package/src/recordings/model.ts +1 -1
  244. package/src/recordings/recorder-app/Capture.swift +9 -7
  245. package/src/reflect/hq-corpus.ts +56 -0
  246. package/src/reflect/prompt-corpus.ts +3 -1
  247. package/src/reflect/transcript.ts +129 -37
  248. package/src/reflections/reflections-queue.ts +1 -1
  249. package/src/release/gate-checkout.ts +2 -1
  250. package/src/release/git-facts.ts +3 -2
  251. package/src/release/machine-words.ts +67 -0
  252. package/src/release/public-clean.ts +11 -5
  253. package/src/releases/from-card.ts +1 -1
  254. package/src/releases/routes.ts +10 -5
  255. package/src/releases/store.ts +10 -1
  256. package/src/repo-config.ts +71 -19
  257. package/src/review/anim.ts +3 -3
  258. package/src/review/answer-kinds.ts +131 -0
  259. package/src/review/auto.ts +2 -2
  260. package/src/review/band.ts +53 -0
  261. package/src/review/branch-hold.ts +84 -0
  262. package/src/review/card-db.ts +254 -0
  263. package/src/review/card-rows.ts +267 -0
  264. package/src/review/cells.ts +360 -57
  265. package/src/review/close.ts +92 -0
  266. package/src/review/draft-card.ts +33 -0
  267. package/src/review/draft-model.ts +78 -0
  268. package/src/review/events.ts +171 -0
  269. package/src/review/format.ts +152 -19
  270. package/src/review/glyphs.ts +63 -0
  271. package/src/review/gone.ts +98 -0
  272. package/src/review/holds-sync.ts +62 -0
  273. package/src/review/holds.ts +85 -0
  274. package/src/review/house-kind-defs.ts +41 -0
  275. package/src/review/inbox-hook.ts +23 -10
  276. package/src/review/inbox-read.ts +201 -0
  277. package/src/review/instructions.ts +199 -0
  278. package/src/review/kind-apply.ts +61 -0
  279. package/src/review/kind-catalog.ts +96 -0
  280. package/src/review/kinds.ts +278 -0
  281. package/src/review/lane-ask.ts +109 -0
  282. package/src/review/marks.ts +1 -1
  283. package/src/review/media-kind.ts +7 -5
  284. package/src/review/media-read.ts +9 -7
  285. package/src/review/media.ts +32 -5
  286. package/src/review/model.ts +582 -109
  287. package/src/review/move.ts +491 -0
  288. package/src/review/need-address.ts +15 -0
  289. package/src/review/need-threads.ts +93 -0
  290. package/src/review/notes.ts +12 -20
  291. package/src/review/object-card.ts +48 -0
  292. package/src/review/object-read.ts +31 -0
  293. package/src/review/owner-verdict.ts +36 -0
  294. package/src/review/parties.ts +182 -0
  295. package/src/review/previews.ts +18 -20
  296. package/src/review/project.ts +1 -1
  297. package/src/review/projections.ts +235 -0
  298. package/src/review/referring.ts +54 -0
  299. package/src/review/reflection-object.ts +195 -0
  300. package/src/review/rev.ts +8 -0
  301. package/src/review/role.ts +1 -1
  302. package/src/review/routes.ts +194 -38
  303. package/src/review/secret-route.ts +80 -0
  304. package/src/review/snooze.ts +38 -0
  305. package/src/review/stage-card.ts +12 -8
  306. package/src/review/stage-routes.ts +1 -1
  307. package/src/review/store.ts +851 -124
  308. package/src/review/supersede.ts +116 -0
  309. package/src/review/take-back.ts +52 -0
  310. package/src/review/thread-fold.ts +64 -0
  311. package/src/review/threads.ts +349 -14
  312. package/src/review/traces.ts +218 -0
  313. package/src/review/trailer-auto-mock.ts +63 -0
  314. package/src/review/trailer-card.ts +6 -6
  315. package/src/review/trailer-desk.ts +41 -7
  316. package/src/review/trailer-media.ts +1 -0
  317. package/src/review/trailer-model.ts +8 -0
  318. package/src/review/trailer-notes.ts +1 -1
  319. package/src/review/trailer-routes.ts +9 -1
  320. package/src/review/unit.ts +77 -11
  321. package/src/review/verdict-items.ts +73 -0
  322. package/src/review/verdict-write.ts +15 -0
  323. package/src/review/wait.ts +85 -0
  324. package/src/review/watchers.ts +23 -10
  325. package/src/rules/untrack-generated.ts +92 -8
  326. package/src/scaffold/files/claude-settings-local.json +2 -0
  327. package/src/secrets/archive-mark.ts +52 -0
  328. package/src/secrets/archive.ts +83 -0
  329. package/src/secrets/copy.ts +14 -14
  330. package/src/secrets/held.ts +16 -0
  331. package/src/secrets/keychain-write.ts +48 -0
  332. package/src/secrets/keychain.ts +116 -0
  333. package/src/secrets/lapse-mark.ts +33 -0
  334. package/src/secrets/lapse.ts +60 -0
  335. package/src/secrets/list.ts +21 -17
  336. package/src/secrets/manager.ts +55 -26
  337. package/src/secrets/read.ts +385 -0
  338. package/src/secrets/tail.ts +31 -0
  339. package/src/secrets/who-reads.ts +49 -0
  340. package/src/serve/door-forward.ts +268 -0
  341. package/src/serve/door-names.ts +47 -0
  342. package/src/serve/embed.ts +1 -1
  343. package/src/serve/hub-app/activity-view.tsx +56 -32
  344. package/src/serve/hub-app/activity.css +7 -1
  345. package/src/serve/hub-app/asks-page.tsx +49 -0
  346. package/src/serve/hub-app/asks-st.ts +25 -0
  347. package/src/serve/hub-app/auto-text.tsx +14 -6
  348. package/src/serve/hub-app/benign-errors.ts +15 -1
  349. package/src/serve/hub-app/card-head.tsx +49 -0
  350. package/src/serve/hub-app/check-view.tsx +3 -2
  351. package/src/serve/hub-app/clock-svc.ts +1 -2
  352. package/src/serve/hub-app/code-copy.ts +35 -0
  353. package/src/serve/hub-app/col-card.tsx +72 -30
  354. package/src/serve/hub-app/col-list-page.tsx +125 -0
  355. package/src/serve/hub-app/col-list-st.ts +103 -0
  356. package/src/serve/hub-app/col-tables-view.tsx +17 -45
  357. package/src/serve/hub-app/col-tables.ts +76 -8
  358. package/src/serve/hub-app/cols-svc.ts +18 -39
  359. package/src/serve/hub-app/commands/commands-page.tsx +2 -1
  360. package/src/serve/hub-app/controls.css +83 -0
  361. package/src/serve/hub-app/database-st.ts +260 -0
  362. package/src/serve/hub-app/database-view.tsx +289 -0
  363. package/src/serve/hub-app/database.css +32 -0
  364. package/src/serve/hub-app/entry-bar.css +14 -0
  365. package/src/serve/hub-app/entry-bar.tsx +33 -0
  366. package/src/serve/hub-app/entry-pick.ts +31 -0
  367. package/src/serve/hub-app/floating.tsx +1 -0
  368. package/src/serve/hub-app/frames-st.ts +17 -1
  369. package/src/serve/hub-app/git-view.tsx +3 -2
  370. package/src/serve/hub-app/hash-route.ts +11 -1
  371. package/src/serve/hub-app/header-bar.tsx +14 -18
  372. package/src/serve/hub-app/home-st.ts +142 -11
  373. package/src/serve/hub-app/home-strip.css +6 -25
  374. package/src/serve/hub-app/home-strip.tsx +60 -93
  375. package/src/serve/hub-app/home.html +10 -0
  376. package/src/serve/hub-app/house-wiki-view.tsx +20 -0
  377. package/src/serve/hub-app/hub-app.tsx +71 -166
  378. package/src/serve/hub-app/hub-types.ts +5 -1
  379. package/src/serve/hub-app/hub.css +146 -71
  380. package/src/serve/hub-app/icons.tsx +32 -5
  381. package/src/serve/hub-app/identities-st.ts +56 -6
  382. package/src/serve/hub-app/identities-view.tsx +104 -61
  383. package/src/serve/hub-app/identities.css +17 -15
  384. package/src/serve/hub-app/identity-address.ts +5 -0
  385. package/src/serve/hub-app/inbox-st.ts +227 -49
  386. package/src/serve/hub-app/inbox-view.tsx +204 -120
  387. package/src/serve/hub-app/inbox.css +47 -47
  388. package/src/serve/hub-app/index.html +10 -0
  389. package/src/serve/hub-app/instructions.css +30 -0
  390. package/src/serve/hub-app/kept-cols.tsx +7 -0
  391. package/src/serve/hub-app/keys.ts +32 -17
  392. package/src/serve/hub-app/later.tsx +26 -0
  393. package/src/serve/hub-app/list-filter.tsx +14 -0
  394. package/src/serve/hub-app/list-walk.ts +72 -3
  395. package/src/serve/hub-app/machine-st.ts +2 -2
  396. package/src/serve/hub-app/machines-st.ts +251 -0
  397. package/src/serve/hub-app/machines-view.tsx +217 -0
  398. package/src/serve/hub-app/machines.css +67 -0
  399. package/src/serve/hub-app/markdown.css +51 -0
  400. package/src/serve/hub-app/md-copy.tsx +57 -0
  401. package/src/serve/hub-app/md.ts +25 -9
  402. package/src/serve/hub-app/media-view.tsx +4 -2
  403. package/src/serve/hub-app/messages/messages-page.tsx +81 -8
  404. package/src/serve/hub-app/messages/messages-st.ts +99 -3
  405. package/src/serve/hub-app/messages.css +14 -1
  406. package/src/serve/hub-app/objects.css +51 -0
  407. package/src/serve/hub-app/page-keys.ts +175 -0
  408. package/src/serve/hub-app/pages-frames.tsx +21 -3
  409. package/src/serve/hub-app/palette-st.ts +58 -11
  410. package/src/serve/hub-app/palette-view.tsx +3 -1
  411. package/src/serve/hub-app/pane-boundary.tsx +72 -0
  412. package/src/serve/hub-app/pane-errors.ts +54 -0
  413. package/src/serve/hub-app/plan-view.tsx +3 -2
  414. package/src/serve/hub-app/planned-view.tsx +3 -3
  415. package/src/serve/hub-app/planned.css +0 -4
  416. package/src/serve/hub-app/processes-view.tsx +3 -2
  417. package/src/serve/hub-app/project-list.css +46 -8
  418. package/src/serve/hub-app/project-list.tsx +125 -59
  419. package/src/serve/hub-app/projects-svc.ts +83 -8
  420. package/src/serve/hub-app/reader-chips.tsx +13 -0
  421. package/src/serve/hub-app/readme-view.tsx +2 -3
  422. package/src/serve/hub-app/readme.css +22 -6
  423. package/src/serve/hub-app/reflections-page.tsx +95 -0
  424. package/src/serve/hub-app/reflections-st.ts +17 -0
  425. package/src/serve/hub-app/releases/releases-page.tsx +28 -4
  426. package/src/serve/hub-app/releases/releases-st.ts +1 -1
  427. package/src/serve/hub-app/releases.css +0 -1
  428. package/src/serve/hub-app/repo-sections.ts +9 -5
  429. package/src/serve/hub-app/repo-st.ts +35 -8
  430. package/src/serve/hub-app/review/code-colors.ts +30 -0
  431. package/src/serve/hub-app/review/diff-view.tsx +75 -0
  432. package/src/serve/hub-app/review/dock.tsx +104 -0
  433. package/src/serve/hub-app/review/draft-card.tsx +163 -0
  434. package/src/serve/hub-app/review/group-block.tsx +209 -0
  435. package/src/serve/hub-app/review/instructions-view.tsx +116 -0
  436. package/src/serve/hub-app/review/item-verdict.tsx +38 -0
  437. package/src/serve/hub-app/review/kind-states.tsx +193 -0
  438. package/src/serve/hub-app/review/kind-view.tsx +1 -37
  439. package/src/serve/hub-app/review/kit.tsx +75 -29
  440. package/src/serve/hub-app/review/lane-bar.tsx +64 -0
  441. package/src/serve/hub-app/review/note-place.ts +1 -1
  442. package/src/serve/hub-app/review/object-card.tsx +62 -0
  443. package/src/serve/hub-app/review/object-panel.tsx +179 -0
  444. package/src/serve/hub-app/review/question-views.tsx +385 -0
  445. package/src/serve/hub-app/review/review-board.tsx +2 -2
  446. package/src/serve/hub-app/review/review-cells.tsx +148 -87
  447. package/src/serve/hub-app/review/review-kit.ts +27 -1
  448. package/src/serve/hub-app/review/review-list.tsx +160 -65
  449. package/src/serve/hub-app/review/review-page.tsx +12 -12
  450. package/src/serve/hub-app/review/review-st.ts +174 -47
  451. package/src/serve/hub-app/review/review-thread.tsx +214 -53
  452. package/src/serve/hub-app/review/review-views.tsx +494 -159
  453. package/src/serve/hub-app/review/thread-close.tsx +124 -0
  454. package/src/serve/hub-app/review/thread-control-st.ts +115 -0
  455. package/src/serve/hub-app/review/thread-control.tsx +74 -0
  456. package/src/serve/hub-app/review/thread-st.ts +288 -41
  457. package/src/serve/hub-app/review/trailer-card.tsx +2 -2
  458. package/src/serve/hub-app/review/trailer-page.tsx +37 -16
  459. package/src/serve/hub-app/review/trailer-st.ts +41 -7
  460. package/src/serve/hub-app/review/trailer-timeline.tsx +2 -2
  461. package/src/serve/hub-app/review.css +462 -97
  462. package/src/serve/hub-app/section-head.tsx +51 -0
  463. package/src/serve/hub-app/side-lists.ts +72 -0
  464. package/src/serve/hub-app/sidebar.tsx +6 -3
  465. package/src/serve/hub-app/site/site-part.tsx +2 -8
  466. package/src/serve/hub-app/site/site-st.ts +4 -4
  467. package/src/serve/hub-app/social/calendar.tsx +5 -11
  468. package/src/serve/hub-app/social/comms-page.tsx +43 -15
  469. package/src/serve/hub-app/social/kit.tsx +32 -13
  470. package/src/serve/hub-app/social/next-release.tsx +3 -5
  471. package/src/serve/hub-app/social/post-card.tsx +142 -49
  472. package/src/serve/hub-app/social/post-page.tsx +80 -0
  473. package/src/serve/hub-app/social/problems.tsx +5 -9
  474. package/src/serve/hub-app/social/serial-writes.ts +13 -0
  475. package/src/serve/hub-app/social/social-model.ts +24 -5
  476. package/src/serve/hub-app/social/social-page.tsx +95 -36
  477. package/src/serve/hub-app/social/social-st.ts +162 -41
  478. package/src/serve/hub-app/social/stage-popup.tsx +1 -1
  479. package/src/serve/hub-app/social/stage-st.ts +1 -1
  480. package/src/serve/hub-app/social/step-layout.ts +1 -1
  481. package/src/serve/hub-app/social.css +10 -17
  482. package/src/serve/hub-app/space-st.ts +209 -0
  483. package/src/serve/hub-app/space-view.tsx +196 -0
  484. package/src/serve/hub-app/space.css +27 -0
  485. package/src/serve/hub-app/stores/stores-page.tsx +97 -25
  486. package/src/serve/hub-app/stores/stores-st.ts +44 -19
  487. package/src/serve/hub-app/stores.css +6 -1
  488. package/src/serve/hub-app/theme-st.ts +22 -9
  489. package/src/serve/hub-app/thread-row.tsx +101 -0
  490. package/src/serve/hub-app/time-ago.tsx +3 -2
  491. package/src/serve/hub-app/time-charts.tsx +291 -0
  492. package/src/serve/hub-app/time-pages.tsx +749 -0
  493. package/src/serve/hub-app/time-st.ts +162 -0
  494. package/src/serve/hub-app/time-view.tsx +77 -0
  495. package/src/serve/hub-app/time.css +135 -0
  496. package/src/serve/hub-app/tree-build.ts +52 -42
  497. package/src/serve/hub-app/tree-row.tsx +3 -11
  498. package/src/serve/hub-app/tree-svc.ts +18 -9
  499. package/src/serve/hub-app/urls-svc.ts +154 -0
  500. package/src/serve/hub-app/urls-view.tsx +117 -0
  501. package/src/serve/hub-app/urls.css +30 -0
  502. package/src/serve/hub-app/vault-st.ts +127 -0
  503. package/src/serve/hub-app/vault-view.tsx +154 -0
  504. package/src/serve/hub-app/vault.css +38 -0
  505. package/src/serve/hub-app/veille/veille-page.tsx +2 -11
  506. package/src/serve/hub-app/veille/veille-st.ts +12 -10
  507. package/src/serve/hub-app/veille.css +0 -1
  508. package/src/serve/hub-app/waiting-svc.ts +29 -0
  509. package/src/serve/hub-app/when-view.tsx +6 -3
  510. package/src/serve/hub-app/wiki-st.ts +30 -4
  511. package/src/serve/hub-app/wikis-view.tsx +6 -5
  512. package/src/serve/hub-runtime.ts +35 -8
  513. package/src/serve/project-gutter-route.ts +42 -19
  514. package/src/serve/project-gutter.ts +16 -50
  515. package/src/serve/same-origin.ts +13 -0
  516. package/src/serve/secret-gate.ts +21 -0
  517. package/src/serve/serve-hub.ts +38 -20
  518. package/src/serve/tailnet-caller.ts +117 -0
  519. package/src/shipkit-files.ts +16 -2
  520. package/src/shipkit.ts +3 -3
  521. package/src/shot/shooter.ts +616 -420
  522. package/src/shot/shot-ask.ts +246 -155
  523. package/src/site/desk.ts +4 -4
  524. package/src/smoke/run-smoke.ts +6 -6
  525. package/src/social/brands.ts +4 -0
  526. package/src/social/card-drafts.ts +11 -19
  527. package/src/social/cover.ts +202 -0
  528. package/src/social/desk-index.ts +34 -13
  529. package/src/social/discord-layout.ts +37 -13
  530. package/src/social/drafts.ts +7 -4
  531. package/src/social/import-drafts.ts +244 -0
  532. package/src/social/kind-pages.ts +3 -3
  533. package/src/social/kinds.ts +1 -1
  534. package/src/social/load.ts +111 -65
  535. package/src/social/media-kind.ts +68 -160
  536. package/src/social/media-of.ts +5 -4
  537. package/src/social/open.ts +3 -2
  538. package/src/social/post-object.ts +120 -0
  539. package/src/social/post-sources.ts +136 -0
  540. package/src/social/post-text.ts +103 -0
  541. package/src/social/posts.ts +378 -0
  542. package/src/social/presence.ts +7 -5
  543. package/src/social/publish/discord.ts +5 -2
  544. package/src/social/publish/index.ts +17 -5
  545. package/src/social/publish/secret.ts +4 -4
  546. package/src/social/release-stage.ts +79 -63
  547. package/src/social/routes.ts +89 -24
  548. package/src/social/stage.ts +43 -58
  549. package/src/social/stats.ts +12 -9
  550. package/src/social/strip.ts +4 -1
  551. package/src/social/text.ts +4 -3
  552. package/src/social/thumbnail.ts +347 -0
  553. package/src/social/tracker.ts +1 -1
  554. package/src/social/writes.ts +12 -29
  555. package/src/stores/collection.ts +15 -11
  556. package/src/stores/desk.ts +246 -47
  557. package/src/stores/model.ts +72 -6
  558. package/src/stores/routes.ts +37 -12
  559. package/src/stores/unit.ts +16 -10
  560. package/src/suite/judge-suites.ts +41 -11
  561. package/src/suite/select.ts +45 -3
  562. package/src/suite/suite-cli.ts +16 -10
  563. package/src/trailer/bed.ts +1 -1
  564. package/src/trailer/build.ts +134 -21
  565. package/src/trailer/ffmpeg.ts +7 -0
  566. package/src/trailer/fonts.ts +3 -2
  567. package/src/trailer/grammar.ts +201 -2
  568. package/src/trailer/graph.ts +42 -5
  569. package/src/trailer/look.ts +21 -0
  570. package/src/trailer/mock.ts +154 -0
  571. package/src/trailer/passage.ts +65 -26
  572. package/src/trailer/score/heard.ts +89 -0
  573. package/src/trailer/score/sound.ts +14 -8
  574. package/src/trailer/sound/eleven.ts +33 -3
  575. package/src/trailer/sound/run.ts +16 -6
  576. package/src/trailer/stitch.ts +26 -5
  577. package/src/trailer/titles.ts +82 -19
  578. package/src/trailer/versions.ts +1 -3
  579. package/src/trailer/vertical.ts +3 -1
  580. package/src/urls/frame.ts +195 -0
  581. package/src/urls/routes.ts +43 -0
  582. package/src/urls/rows.ts +171 -0
  583. package/src/urls/unit.ts +73 -0
  584. package/src/vault/house-keys.ts +42 -0
  585. package/src/vault/layout.ts +50 -0
  586. package/src/vault/policy.ts +165 -0
  587. package/src/vault/vault-audit.ts +276 -0
  588. package/src/vault/vault-client.ts +40 -0
  589. package/src/vault/vault-config.ts +159 -0
  590. package/src/vault/vault-destroy.ts +78 -0
  591. package/src/vault/vault-handover.ts +305 -0
  592. package/src/vault/vault-http.ts +360 -0
  593. package/src/vault/vault-import.ts +213 -0
  594. package/src/vault/vault-init.ts +328 -0
  595. package/src/vault/vault-minter.ts +271 -0
  596. package/src/vault/vault-restore.ts +333 -0
  597. package/src/vault/vault-serve.ts +342 -0
  598. package/src/vault/vault-snapshot.ts +281 -0
  599. package/src/veille/asks.ts +1 -1
  600. package/src/veille/desk.ts +2 -2
  601. package/src/veille/identity.ts +2 -2
  602. package/src/wiki/graph-pages.ts +13 -1
  603. package/src/wiki/scan-md.ts +1 -1
  604. package/src/asks/asks-queue.ts +0 -266
  605. package/src/social/migrate.ts +0 -123
@@ -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,22 @@ 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, repoIdOf, spoolOf } from './card-db.ts'
20
+ import { machineDbPath } from '../core/machine-db.ts'
21
+ import { jsonText, revOf } from './rev.ts'
22
+ import { GONE, goneEntryFor } from './gone.ts'
14
23
  import {
24
+ addressOrThrow,
25
+ ANSWER_KINDS,
26
+ type AnswerKind,
27
+ type MessageAsk,
28
+ ownAddressOf,
29
+ partyOf,
30
+ proposeOpen,
15
31
  AGENT_RE,
16
32
  allowed,
17
33
  FILE_RE,
@@ -55,6 +71,7 @@ import {
55
71
  type ReviewMark,
56
72
  type ReviewView,
57
73
  type TrailerCard,
74
+ type DraftCard,
58
75
  type Spec,
59
76
  type Subject,
60
77
  type Verdict,
@@ -62,10 +79,23 @@ import {
62
79
  mediaFilesOf,
63
80
  threadMediaOf,
64
81
  isGallery,
82
+ diffTypeOf,
83
+ DIFF_TYPES,
84
+ proposeFields,
85
+ type DiffType,
86
+ type MessagePropose,
87
+ type ProposeField,
88
+ type StoredState,
89
+ type AskHead,
65
90
  } from './model.ts'
91
+ import { kindOfValue, valueKindOf } from './kinds.ts'
92
+ import { askOpen, linesOf } from './answer-kinds.ts'
93
+ import { choiceName } from './instructions.ts'
94
+ import { SECRET_NAME } from '../secrets/name.ts'
66
95
  import { beatRole, roleOf } from './role.ts'
67
- import { chainOf, coveringHead, followedIds, isFollowed } from './threads.ts'
96
+ import { chainOf, coveringHead, followedIds, isFollowed, threadOfAddress } from './threads.ts'
68
97
  import { liveWatchers } from './watchers.ts'
98
+ import { noteSession } from '../agent-time/registry.ts'
69
99
 
70
100
  /** the store of a repo */
71
101
  export const storeDir = (root: string): string => join(root, LAYOUT.review)
@@ -88,12 +118,73 @@ const copyFileSync = (a: string, b: string): void => (fs.copyFileSync(a, b), tou
88
118
  const writeFileSync = (p: string, d: string): void => (fs.writeFileSync(p, d), touched(p))
89
119
  const mkdirSync = (p: string, o?: fs.MakeDirectoryOptions): void => (fs.mkdirSync(p, o), touched(p))
90
120
 
121
+ export { jsonText, revOf }
122
+
91
123
  function writeJson(file: string, v: unknown): void {
92
124
  const tmp = `${file}.tmp`
93
- writeFileSync(tmp, `${JSON.stringify(v, null, 4)}\n`)
125
+ writeFileSync(tmp, jsonText(v))
94
126
  renameSync(tmp, file)
95
127
  }
96
128
 
129
+ /** where the store's operations read and write: the rows of the local copy while the switch cards-in-db is on, else
130
+ * the files. Picked once an operation, so one operation never reads one backend and writes the other */
131
+ const io = (dir: string): CardBackend => (cardsInDb() ? rowsIO(dir) : filesIO(dir))
132
+
133
+ /** the store holds this card's head, or this message of its thread: what the machine has, never what it sent */
134
+ export const holdsCard = (dir: string, id: string): boolean => io(dir).has(id)
135
+ export const holdsMessage = (dir: string, id: string, mid: string): boolean => io(dir).hasMessage(id, mid)
136
+
137
+ /** the store's files, as they always were: one folder a card */
138
+ export function filesIO(dir: string): CardBackend {
139
+ const folder = (id: string): string => join(dir, id)
140
+ return {
141
+ rows: false,
142
+ names: () => (existsSync(dir) ? readdirSync(dir).filter((n) => !n.startsWith('.')).sort() : []),
143
+ has: (id) => ID_RE.test(id) && existsSync(join(dir, id, 'item.json')),
144
+ taken: (id) => existsSync(folder(id)),
145
+ head: (id) => {
146
+ if (!ID_RE.test(id)) return null
147
+ const f = join(dir, id, 'item.json')
148
+ const s = statSync(f, { throwIfNoEntry: false })
149
+ return s ? { head: JSON.parse(readFileSync(f, 'utf8')) as unknown, at: Math.floor(s.mtimeMs) } : null
150
+ },
151
+ threadIds: (id) => {
152
+ const t = join(dir, id, 'thread')
153
+ if (!ID_RE.test(id) || !existsSync(t)) return []
154
+ return readdirSync(t)
155
+ .filter((n) => n.endsWith('.json') && MESSAGE_RE.test(n.slice(0, -5)))
156
+ .map((n) => n.slice(0, -5))
157
+ .sort()
158
+ },
159
+ message: (id, mid) => JSON.parse(readFileSync(join(dir, id, 'thread', `${mid}.json`), 'utf8')) as unknown,
160
+ hasMessage: (id, mid) => existsSync(join(dir, id, 'thread', `${mid}.json`)),
161
+ raw: (id) => readRawFile(dir, id),
162
+ create: (id, tmp, head) => {
163
+ writeJson(join(tmp, 'item.json'), head)
164
+ // a card begun while the rows were the store: its folder comes from the spool
165
+ moveFolder(tmp, folder(id))
166
+ touched(tmp)
167
+ touched(folder(id))
168
+ },
169
+ write: (id, head, at) => {
170
+ const f = join(dir, id, 'item.json')
171
+ writeJson(f, head)
172
+ if (at !== undefined) fs.utimesSync(f, new Date(at), new Date(at))
173
+ },
174
+ append: (id, m) => {
175
+ const t = join(dir, id, 'thread')
176
+ if (!existsSync(t)) mkdirSync(t)
177
+ writeJson(join(t, `${m.id}.json`), m)
178
+ },
179
+ lock: (id, fn, waitMs) => locked(dir, id, fn, waitMs),
180
+ setAside: (id, o) => setAsideFile(dir, id, o),
181
+ keepReplaced: (id, head) => writeJson(join(folder(id), REPLACED), head),
182
+ hasReplaced: (id) => ID_RE.test(id) && existsSync(join(dir, id, REPLACED)),
183
+ stamp: (id) => stampOf(folder(id)),
184
+ folder,
185
+ }
186
+ }
187
+
97
188
  /** 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
189
  * by its extension), or a gallery of images */
99
190
  export interface ViewInput {
@@ -109,6 +200,9 @@ export interface ViewInput {
109
200
  note?: string
110
201
  }
111
202
 
203
+ /** the most one side of a version of an object weighs, as json */
204
+ const STATE_MAX = 256 * 1024
205
+
112
206
  export interface AddInput {
113
207
  title: string
114
208
  what: string
@@ -127,9 +221,15 @@ export interface AddInput {
127
221
  commit?: string
128
222
  /** the lane that made it; else SK_AGENT */
129
223
  lane?: string
224
+ /** written by the machine (a check run, the reflections queue): no lane and no session, so nobody holds it */
225
+ machine?: true
130
226
  supersedes?: string
131
227
  /** the raised items (a report, his note) this card answers, by id */
132
228
  answers?: string[]
229
+ /** its subject's address when the agent names it (`--on`): one thread per address */
230
+ on?: string
231
+ /** other objects it is about: links that find it */
232
+ about?: string[]
133
233
  /** what a new version of an approved look keeps of it: required then */
134
234
  keeps?: string
135
235
  /** another subject on purpose, next to an active card: needs `why` */
@@ -146,10 +246,22 @@ export interface AddInput {
146
246
  wip?: { live: string }
147
247
  /** every view is an option he picks one of */
148
248
  choice?: boolean
249
+ /** it waits for the owner's verdict (`--verdict`): an opening of words asks it only so, a version always */
250
+ asksVerdict?: true
149
251
  /** on a choice: the option the agent suggests, by its label or its letter */
150
252
  agentPick?: string
151
253
  /** a trailer card: the cut the hub plays in its body; its one view is the cut's strip */
152
254
  trailer?: TrailerCard
255
+ /** a draft card: the post draft the hub shows in its body, read live; it holds no view */
256
+ draft?: DraftCard
257
+ /** every picture as given, never a webp: the file itself kept, where the card holds only its webp otherwise */
258
+ keep?: boolean
259
+ /** a thread opened with words on its address (`on`): no media, nothing he judges (openThread) */
260
+ opening?: boolean
261
+ /** a version of an object of a kind (`on`): its two states as the kind read them; it holds no view */
262
+ states?: { before?: StoredState; after: StoredState }
263
+ /** an ask's facts, on the head of its thread `ask:<id>` (asks/ask-store.ts) */
264
+ ask?: AskHead
153
265
  now?: Date
154
266
  }
155
267
 
@@ -163,10 +275,45 @@ interface Loaded {
163
275
  /** a sound: its length, and the files its waveforms are drawn from (the after's or the one's, then the before's) */
164
276
  audio?: { duration: number; from: string; before?: string }
165
277
  tiles?: { path: string; label: string; size: { w: number; h: number }; before?: string; group?: string }[]
278
+ /** the webps made of its pictures, by the name of each in place of its source (`<source>.webp`, no such file) */
279
+ webps?: Map<string, Uint8Array>
280
+ }
281
+
282
+ /** the view's pictures as the card keeps them: each png a lossless webp found exact (media-store/webp.ts), made in
283
+ * memory and written where the card is by copyFiles; never with `keep`. The sides of a pair, and a tile and its
284
+ * before, are webps together or stay as given together, so two sides never differ in kind. `always`: a webp whatever
285
+ * the picture holds (a draft's live frame, whose name its card made a webp) */
286
+ async function asWebp(v: Loaded, keep: boolean, always: boolean): Promise<Loaded> {
287
+ if (keep || v.clip || v.audio) return v
288
+ const pics = [...v.sources.map(([, p]) => p), ...(v.tiles ?? []).flatMap((t) => [t.path, ...(t.before ? [t.before] : [])])]
289
+ if (!pics.some(webpable) && !always) return v
290
+ const webps = new Map<string, Uint8Array>()
291
+ /** the paths of a group as the card keeps them: every one a webp, or every one as given */
292
+ const group = async (paths: readonly string[]): Promise<string[]> => {
293
+ const made = await Promise.all(paths.map(async (p) => (always ? { bytes: await anyWebp(p) } : await exactWebp(p))))
294
+ if (made.some((m) => 'keep' in m)) return [...paths]
295
+ return paths.map((p, i) => {
296
+ webps.set(`${p}.webp`, (made[i] as { bytes: Uint8Array }).bytes)
297
+ return `${p}.webp`
298
+ })
299
+ }
300
+ const kept = await group(v.sources.map(([, p]) => p))
301
+ const sources = v.sources.map(([name], i): Loaded['sources'][number] => [name, kept[i]!])
302
+ const tiles = v.tiles && (await Promise.all(v.tiles.map(async (t) => {
303
+ const [path, before] = await group([t.path, ...(t.before ? [t.before] : [])])
304
+ return { ...t, path: path!, ...(before ? { before } : {}) }
305
+ })))
306
+ return { ...v, sources, ...(tiles ? { tiles } : {}), ...(webps.size > 0 ? { webps } : {}) }
166
307
  }
167
308
 
168
309
  /** 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> {
310
+ async function loadView(v: ViewInput, which: string, o: { keep?: boolean; always?: boolean } = {}): Promise<Loaded> {
311
+ const l = await checkView(v, which)
312
+ return asWebp(l, o.keep === true, o.always === true)
313
+ }
314
+
315
+ /** a view's files checked and sized, as given */
316
+ async function checkView(v: ViewInput, which: string): Promise<Loaded> {
170
317
  if (v.gallery !== undefined) {
171
318
  if (v.image !== undefined || v.video !== undefined || v.audio !== undefined || v.before !== undefined || v.after !== undefined)
172
319
  throw new Error(`${which}: a gallery is a list of images, no --image, --video or pair beside it`)
@@ -278,14 +425,14 @@ const prefix = (n: number): string => (n > 0 ? `v${n}-` : '')
278
425
  /** the file name of tile `k` of gallery view `n` */
279
426
  const tileName = (n: number, k: number, path: string, side = ''): string => `v${n}-g${k}${side}${extname(path).toLowerCase()}`
280
427
 
281
- function viewOf(v: Loaded, n: number, marks: readonly ReviewMark[] = [], note?: string): ReviewView {
428
+ function viewOf(v: Loaded, n: number, marks: readonly ReviewMark[] = [], note?: string, message?: true): ReviewView {
282
429
  if (v.tiles)
283
430
  return {
284
431
  label: v.label,
285
432
  gallery: v.tiles.map((t, k): GalleryTile => ({ file: tileName(n, k, t.path), label: t.label, size: t.size, ...(t.before ? { before: tileName(n, k, t.before, '-before') } : {}), ...(t.group ? { group: t.group } : {}) })),
286
433
  }
287
434
  const audio = v.audio ? { audio: { duration: v.audio.duration, wave: `${prefix(n)}wave.png`, ...(v.audio.before ? { waveBefore: `${prefix(n)}before-wave.png` } : {}) } } : {}
288
- return { label: v.label, files: filesOf(v, n), size: v.size, ...clipOf(v, n), ...audio, ...(marks.length > 0 ? { marks: [...marks] } : {}), ...(note?.trim() ? { note: note.trim() } : {}) }
435
+ return { label: v.label, files: filesOf(v, n), size: v.size, ...clipOf(v, n), ...audio, ...(marks.length > 0 ? { marks: [...marks] } : {}), ...(note?.trim() ? { note: note.trim() } : {}), ...(message ? { message } : {}) }
289
436
  }
290
437
 
291
438
  /** the file names of view `n` in the folder: `image.png` on the first, `v2-before.png` on a later one */
@@ -302,18 +449,51 @@ async function writePoster(v: Loaded, n: number, folder: string): Promise<void>
302
449
  renameSync(`${to}.tmp`, to)
303
450
  }
304
451
 
305
- /** why an active card refuses a new one, and every way out */
452
+ /** why an active thread refuses a version that names no address, and every way out */
306
453
  function coveredText(c: { head: ReviewItem; by: 'subject' | 'near' | 'title' }): string {
307
454
  const r = c.head.item
308
455
  const by = c.by === 'subject' ? 'the same subject' : c.by === 'near' ? 'the same topic and a subject near it' : 'a title this close'
309
456
  return [
310
- `one subject is one card: the active card ${r.id} "${r.title}" (${r.topic ?? 'no topic'}) already covers it, ${by}.`,
311
- ` a new version of it: --supersedes ${r.id}`,
312
- ` another angle of it: sk review add-view ${r.id} "<label>" <image> [<after>]`,
313
- ` truly another subject: --new --why "<reason>"`,
457
+ `one subject is one thread: the active thread ${r.id} "${r.title}" (${r.topic ?? 'no topic'}) already covers it, ${by}.`,
458
+ ` its next version: sk thread post ${r.id} …`,
459
+ ` another angle of it: sk thread add-view ${r.id} "<label>" <image> [<after>]`,
460
+ ` truly another subject: sk thread post <kind>:<key> … with its own address`,
314
461
  ].join('\n')
315
462
  }
316
463
 
464
+ /** the thread a new version goes into (wiki tools/shipkit/threads-store.md, The one thread guard): the one that owns its
465
+ * address. No link given: it supersedes that thread's newest version; a thread his note heads takes it in at read time,
466
+ * with no link. It never answers his notes: a version closes one only when its agent names it (`answers`). A link given
467
+ * must be the newest version, else it is refused with the thread named. `thread` null: its address has no thread yet,
468
+ * or it names none (the older guard decides) */
469
+ export function threadLink(
470
+ dir: string,
471
+ card: Pick<Item, 'subject' | 'on' | 'trailer'>,
472
+ given: { supersedes?: string; answers: readonly string[] },
473
+ spec: Spec = specOf(dir),
474
+ ): { own: string | null; thread: string | null; supersedes?: string; answers: string[] } {
475
+ const own = ownAddressOf({ ...card, origin: { by: 'agent' } } as Item, spec)
476
+ const t = own === null ? null : threadOfAddress(own, readAll(dir).items, spec)
477
+ if (!t) return { own, thread: null, ...given, answers: [...given.answers] }
478
+ const head = t.head.item
479
+ const want = head.origin.by === 'agent' ? head.id : undefined
480
+ if (given.supersedes !== undefined && given.supersedes !== want)
481
+ throw new Error(`${own} already has its thread ${head.id} "${head.title}": a new version of it supersedes its newest version${want ? ` ${want}` : ', here none: its head is his note'}, never ${given.supersedes}; or leave --supersedes out and the tool links it`)
482
+ return { own, thread: head.id, ...(want !== undefined ? { supersedes: want } : {}), answers: [...given.answers] }
483
+ }
484
+
485
+ /** a thread opened with words on an address no thread owns: its head holds the address and a title, no media, and
486
+ * waits on no verdict; the question, the proposed change or the line goes in it next. Refused when a thread owns it */
487
+ export async function openThread(dir: string, address: string, o: { title: string; what?: string; lane?: string; machine?: true; now?: Date; ask?: AskHead; asksVerdict?: true }): Promise<Item> {
488
+ // an ask is made with its facts (asks/ask-store.ts createAsk): a bare ask: thread would wait on him and no count would hold it
489
+ if (address.startsWith('ask:') && o.ask === undefined) throw new Error(`${address}: an ask is made with sk ask, its thread opened with its facts`)
490
+ const own = threadOfAddress(address, readAll(dir).items, specOf(dir))
491
+ if (own) throw new Error(`${address} already has its thread ${own.head.item.id} "${own.head.item.title}": write in it`)
492
+ const first = o.title.trim().split('\n')[0] ?? ''
493
+ const title = first.length > 80 ? `${first.slice(0, 79).trimEnd()}…` : first
494
+ return addItem(dir, { title, what: o.what?.trim() || (o.ask ? '' : `the thread of ${address}`), subject: { kind: 'object', address }, on: address, opening: true, ...(o.lane ? { lane: o.lane } : {}), ...(o.machine ? { machine: true } : {}), ...(o.now ? { now: o.now } : {}), ...(o.ask ? { ask: o.ask } : {}), ...(o.asksVerdict ? { asksVerdict: o.asksVerdict } : {}) })
495
+ }
496
+
317
497
  /** the Claude Code session that runs this process, null outside one */
318
498
  export const sessionId = (): string | null => process.env.CLAUDE_CODE_SESSION_ID?.trim() || null
319
499
 
@@ -324,19 +504,26 @@ export const agentName = (): string => process.env.SK_AGENT?.trim() || 'agent'
324
504
  export async function addItem(dir: string, input: AddInput): Promise<Item> {
325
505
  const spec = specOf(dir)
326
506
  if (!input.title.trim()) throw new Error('--title: required')
327
- if (!input.what.trim()) throw new Error('--what: required, what changed and why')
507
+ // an ask's head holds its facts alone: its words are its instructions, a message (asks/ask-store.ts createAsk)
508
+ if (!input.what.trim() && input.ask === undefined) throw new Error('--what: required, what changed and why')
328
509
  const first = input.image !== undefined || input.video !== undefined || input.audio !== undefined || input.before !== undefined || input.after !== undefined
329
510
  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
511
  (v) => Object.fromEntries(Object.entries(v).filter(([, x]) => x !== undefined)) as unknown as ViewInput,
331
512
  )
332
- if (given.length === 0) throw new Error('give --image, --video or --audio, or --before and --after, or --view "<label>" <image>')
513
+ if (input.draft && given.length > 0) throw new Error('--draft: the version shows the draft itself, no image, clip, sound or view beside it')
514
+ if (input.opening && (given.length > 0 || input.draft || input.trailer)) throw new Error('a thread opened with words holds no media: a version with media goes into it after')
515
+ if (input.opening && !input.on) throw new Error('a thread opened with words names its address')
516
+ if (input.states && (given.length > 0 || input.draft || input.trailer || !input.on)) throw new Error('a version of an object shows its two states alone: its address (on), no image, clip, sound or view beside it')
517
+ for (const [side, st] of Object.entries(input.states ?? {})) if (st && JSON.stringify(st).length > STATE_MAX) throw new Error(`--${side}: the state is ${Math.round(JSON.stringify(st).length / 1024)} KB, over ${STATE_MAX / 1024} KB: a kind reads what the owner judges, not the whole repo`)
518
+ if (given.length === 0 && !input.draft && !input.opening && !input.states) throw new Error('give --image, --video or --audio, or --before and --after, or --view "<label>" <image>')
333
519
  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
520
  if (input.choice && given.length < 2) throw new Error('--choice: a choice has two options or more, one --view each')
335
521
  if (input.agentPick !== undefined && !input.choice) throw new Error('--pick: only on a --choice card')
336
522
  const agentPick = input.agentPick === undefined ? undefined : pickIndex(given, input.agentPick)
337
523
  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}`)
524
+ const loaded = await Promise.all(given.map((v, i) => loadView(v, i === 0 ? 'the first view' : `--view "${v.label}"`, { keep: input.keep === true })))
525
+ const c = io(dir)
526
+ if (input.supersedes !== undefined && !c.has(input.supersedes)) throw new Error(`--supersedes ${input.supersedes}: no such card in ${dir}`)
340
527
  if (input.supersedes !== undefined && readItem(dir, input.supersedes)?.item.origin.by !== 'agent')
341
528
  throw new Error(`--supersedes ${input.supersedes}: a report or a note is answered, never superseded: --answers ${input.supersedes}`)
342
529
  const answers = [...new Set(input.answers ?? [])]
@@ -351,66 +538,132 @@ export async function addItem(dir: string, input: AddInput): Promise<Item> {
351
538
  if (wrong.length > 0) throw new Error(wrong.join('; '))
352
539
  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
540
  if (input.marks && input.marks.length > given.length) throw new Error(`marks: ${input.marks.length} lists for ${given.length} views`)
354
- if (input.supersedes !== undefined && !input.keeps?.trim()) {
355
- const all = readAll(dir).items
356
- const old = all.find((x) => x.item.id === input.supersedes)
357
- const answered = old ? chainOf(old, all).find((x) => verdictOf(x)) : undefined
358
- const v = answered ? verdictOf(answered) : null
359
- if (answered && v && isApproved(v.status))
360
- throw new Error(
361
- `${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
- )
363
- }
364
- if (input.supersedes === undefined) {
365
- if (input.fresh === true) {
366
- if (!input.why?.trim()) throw new Error('--new needs --why "<reason>": why this is another subject than the active card next to it')
367
- } else {
368
- const others = readAll(dir).items.filter((x) => !answers.includes(x.item.id))
369
- const c = coveringHead({ title: input.title, ...(topic ? { topic } : {}), subject }, others, spec)
370
- if (c) throw new Error(coveredText(c))
541
+ const about = [...new Set((input.about ?? []).map(addressOrThrow))]
542
+ const on = input.on?.trim() ? addressOrThrow(input.on) : undefined
543
+ if (on?.startsWith('ask:') && input.ask === undefined && !threadOfAddress(on, readAll(dir).items, spec)) throw new Error(`${on}: no ask has this address: an ask is made with sk ask, its thread opened with its facts`)
544
+ const given0 = { ...(input.supersedes !== undefined ? { supersedes: input.supersedes } : {}), answers: [...answers] }
545
+ /** the thread it goes into and the refusals that read the store: asked once before the media are written, so a
546
+ * refusal costs no write, and again under the address's lock, where the version is written */
547
+ const settle = (): { own: string | null; supersedes?: string; answers: string[] } => {
548
+ const link = threadLink(dir, { subject, ...(on ? { on } : {}), ...(input.trailer ? { trailer: input.trailer } : {}) }, given0, spec)
549
+ if (link.supersedes !== undefined && !input.keeps?.trim()) {
550
+ const all = readAll(dir).items
551
+ const old = all.find((x) => x.item.id === link.supersedes)
552
+ const answered = old ? chainOf(old, all).find((x) => verdictOf(x)) : undefined
553
+ const v = answered ? verdictOf(answered) : null
554
+ if (answered && v && isApproved(v.status))
555
+ throw new Error(
556
+ `${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`,
557
+ )
371
558
  }
559
+ // an address decides alone: the older guard reads titles only for a version that names none
560
+ if (link.supersedes === undefined && link.thread === null && link.own === null) {
561
+ if (input.fresh === true) {
562
+ if (!input.why?.trim()) throw new Error('--new needs --why "<reason>": why this is another subject than the active card next to it')
563
+ } else {
564
+ const others = readAll(dir).items.filter((x) => !link.answers.includes(x.item.id))
565
+ const c = coveringHead({ title: input.title, ...(topic ? { topic } : {}), subject }, others, spec)
566
+ if (c) throw new Error(coveredText(c))
567
+ }
568
+ }
569
+ return link
372
570
  }
373
- const lane = input.lane?.trim() || process.env.SK_AGENT?.trim() || undefined
571
+ const early = settle()
572
+ const lane = input.machine ? undefined : input.lane?.trim() || process.env.SK_AGENT?.trim() || undefined
374
573
  if (lane !== undefined && !AGENT_RE.test(lane)) throw new Error(`--lane: « ${lane} » is no lane id (${AGENT_RE.source})`)
375
574
  mkdirSync(dir, { recursive: true })
376
575
  const now = input.now ?? new Date()
377
576
  const base = idOf(now, input.title)
378
577
  let id = base
379
- for (let n = 2; existsSync(join(dir, id)); n++) id = `${base}-${n}`
380
- const session = sessionId()
381
- const item: Item = {
578
+ for (let n = 2; c.taken(id); n++) id = `${base}-${n}`
579
+ const session = input.machine ? null : sessionId()
580
+ if (session) noteSession(dir)
581
+ const itemOf =(link: { supersedes?: string; answers: string[] }): Item => ({
382
582
  id,
383
583
  created: now.toISOString(),
384
584
  subject,
385
585
  origin: { by: 'agent', ...(lane ? { lane } : {}), ...(session ? { session } : {}) },
386
586
  title: input.title.trim(),
387
- what: input.what.trim(),
587
+ ...(input.what.trim() !== '' ? { what: input.what.trim() } : {}),
388
588
  ...(input.post?.trim() ? { post: input.post.trim() } : {}),
389
589
  ...(input.changelog ? { changelog: { category: input.changelog.category.trim(), line: input.changelog.line.trim(), ...(input.changelog.rating ? { rating: input.changelog.rating } : {}) } } : {}),
390
590
  ...(topic ? { topic } : {}),
391
591
  ...(input.commit ? { commit: input.commit } : {}),
392
592
  views: loaded.map((v, n) => viewOf(v, n, input.marks?.[n], given[n]?.note)),
393
- ...(input.supersedes ? { supersedes: input.supersedes } : {}),
394
- ...(answers.length > 0 ? { answers } : {}),
593
+ ...(link.supersedes ? { supersedes: link.supersedes } : {}),
594
+ ...(link.answers.length > 0 ? { answers: link.answers } : {}),
595
+ ...(on ? { on } : {}),
596
+ ...(about.length > 0 ? { about } : {}),
395
597
  ...(input.fresh && input.why ? { why: input.why.trim() } : {}),
396
- ...(input.supersedes && input.keeps?.trim() ? { keeps: input.keeps.trim() } : {}),
598
+ ...(link.supersedes && input.keeps?.trim() ? { keeps: input.keeps.trim() } : {}),
397
599
  ...(input.light ? { light: input.light } : {}),
398
600
  ...(input.wip ? { wip: { live: input.wip.live, frame: 1 } } : {}),
399
601
  ...(input.choice ? { choice: true as const } : {}),
602
+ ...(input.asksVerdict ? { asksVerdict: true as const } : {}),
400
603
  ...(agentPick !== undefined ? { agentPick } : {}),
401
604
  ...(input.trailer ? { trailer: input.trailer } : {}),
402
- }
403
- const problems = itemProblems(item)
605
+ ...(input.draft ? { draft: input.draft } : {}),
606
+ ...(input.states ? { states: input.states } : {}),
607
+ ...(input.ask ? { ask: input.ask } : {}),
608
+ })
609
+ const problems = itemProblems(itemOf(early))
404
610
  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)
611
+ const tmp = tmpOf(c, id)
408
612
  loaded.forEach((v, n) => copyFiles(v, n, tmp))
409
613
  await Promise.all(loaded.map((v, n) => Promise.all([writePoster(v, n, tmp), writeWaves(v, n, tmp)])))
410
- const head: Item = { ...item, media: await factsOf(tmp, viewFilesOf(item)) }
411
- writeJson(join(tmp, 'item.json'), head)
412
- renameSync(tmp, join(dir, id))
413
- return head
614
+ const media = await factsOf(tmp, viewFilesOf(itemOf(early)))
615
+ try {
616
+ // the link read and the version written under one lock: two posts at once on one address make one thread
617
+ return addressLocked(dir, early.own, () => {
618
+ const head: Item = { ...itemOf(settle()), media }
619
+ createAtCommit(dir, c, id, tmp, head)
620
+ return head
621
+ })
622
+ } catch (e) {
623
+ rmSync(tmp, { recursive: true, force: true })
624
+ throw e
625
+ }
626
+ }
627
+
628
+ /** where the lock of one own address lives: the store's `.locks/` while the cards are files (a store per checkout),
629
+ * else beside the machine db, keyed by the repo the rows belong to, so every worktree of a repo takes one lock */
630
+ export function addressLockPath(dir: string, address: string): string {
631
+ const rows = cardsInDb()
632
+ const key = new Bun.CryptoHasher('sha1').update(rows ? `${repoIdOf(dir)}\n${address}` : address).digest('hex').slice(0, 16)
633
+ return join(rows ? join(dirname(machineDbPath()), 'thread-locks') : join(dir, '.locks'), key)
634
+ }
635
+
636
+ /** the lock of one own address while its thread is read and a version written into it (the item lock's atomic folder);
637
+ * no address, no lock */
638
+ function addressLocked<T>(dir: string, address: string | null, fn: () => T): T {
639
+ if (address === null) return fn()
640
+ const at = addressLockPath(dir, address)
641
+ mkdirSync(at, { recursive: true })
642
+ try {
643
+ return locked(dirname(at), basename(at), fn, 2000)
644
+ } catch (e) {
645
+ throw (e as Error).message.endsWith('locked by another process') ? new Error(`${address}: another post on it holds its lock past 2 s; post again`) : e
646
+ }
647
+ }
648
+
649
+ /** the empty folder a new card's files are written in, beside the folder they become: the repo's store, or the spool */
650
+ function tmpOf(c: CardBackend, id: string): string {
651
+ const tmp = join(dirname(c.folder(id)), `.${id}.tmp`)
652
+ rmSync(tmp, { recursive: true, force: true })
653
+ mkdirSync(tmp, { recursive: true })
654
+ return tmp
655
+ }
656
+
657
+ /** 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
658
+ * daemon's file (card-db.ts spoolOf). A card's file is `join(mediaDir(dir), id, name)` either way */
659
+ export const mediaDir = (dir: string): string => (cardsInDb() ? spoolOf(dir) : dir)
660
+
661
+ /** a new card committed to the store the switch names NOW: its files took their time (a clip, a big picture), and a
662
+ * move may have turned the switch meanwhile, past its lag. Its id was free in the store it was chosen in */
663
+ function createAtCommit(dir: string, picked: CardBackend, id: string, tmp: string, head: Item): void {
664
+ const now = io(dir)
665
+ 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`)
666
+ now.create(id, tmp, head)
414
667
  }
415
668
 
416
669
  /** every file of view `n` into the folder, each as `<name>.tmp` renamed, so no reader sees half of one */
@@ -419,30 +672,39 @@ function copyFiles(v: Loaded, n: number, into: string): void {
419
672
  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
673
  for (const [from, name] of copies) {
421
674
  const to = join(into, name)
422
- copyFileSync(from, `${to}.tmp`)
675
+ putFile(v, from, `${to}.tmp`)
423
676
  renameSync(`${to}.tmp`, to)
424
677
  }
425
678
  }
426
679
 
680
+ /** one file of a view where it lands: its webp, else a copy of it */
681
+ function putFile(v: Loaded, from: string, to: string): void {
682
+ const webp = v.webps?.get(from)
683
+ if (webp == null) return copyFileSync(from, to)
684
+ fs.writeFileSync(to, webp)
685
+ touched(to)
686
+ }
687
+
427
688
  /** 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>`
689
+ const updateLine = (id: string): string => `sk thread update ${id} <${UPDATE_STATES.join('|')}> "<one line>" <file> | <before> <after>`
429
690
 
430
691
  /** another angle of an open card's subject, appended as its next view; refused once he answered, except the view of an
431
692
  * 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> {
693
+ export async function addView(dir: string, id: string, v: ViewInput, o: { marks?: ReviewMark[]; light?: 'review'; message?: true; keep?: boolean } = {}): Promise<Item> {
433
694
  const x = readItem(dir, id)
434
695
  if (!x) throw new Error(`no card ${id}`)
435
- 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}`)
696
+ if (verdictOf(x) && !o.message) throw new Error(`${id} has the owner's answer already: a picture of the work since goes on as an update, ${updateLine(id)}; a new version passes --supersedes ${id}`)
436
697
  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
698
  if (!v.label.trim()) throw new Error('add-view: the view needs its label')
438
- const loaded = await loadView(v, `the view "${v.label}"`)
699
+ const loaded = await loadView(v, `the view "${v.label}"`, { keep: o.keep === true })
439
700
  const n = x.item.views.length
440
- const folder = join(dir, id)
701
+ const folder = io(dir).folder(id)
702
+ if (!existsSync(folder)) mkdirSync(folder, { recursive: true })
441
703
  // the files land before the head names them, so no reader sees a view without its images
442
704
  copyFiles(loaded, n, folder)
443
705
  await writePoster(loaded, n, folder)
444
706
  await writeWaves(loaded, n, folder)
445
- const view = viewOf(loaded, n, o.marks, v.note)
707
+ const view = viewOf(loaded, n, o.marks, v.note, o.message)
446
708
  const facts = await factsOf(folder, viewFilesOf({ ...x.item, views: [view] }))
447
709
  return updateHead(dir, id, (cur) => {
448
710
  if (cur.views.length !== n) throw new Error(`${id}: another view landed while this one was written: add it again`)
@@ -471,23 +733,145 @@ export function setAgentPick(dir: string, id: string, ref: string): Item {
471
733
 
472
734
  /** the head rewritten under the item's lock, from what the file says now: a write that raced this one is never lost */
473
735
  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)
736
+ const c = io(dir)
737
+ return c.lock(id, () => {
738
+ const held = c.head(id)
739
+ if (held == null) throw Object.assign(new Error(`no card ${id}`), { code: 'ENOENT' })
740
+ const next = fn(held.head as Item)
478
741
  const problems = itemProblems(next)
479
742
  if (problems.length > 0) throw new Error(problems.join('; '))
480
- writeJson(f, next)
743
+ c.write(id, next)
481
744
  return next
482
745
  })
483
746
  }
484
747
 
748
+ /** the ids of a store's cards, as their folders name them */
749
+ export const cardIds = (dir: string): string[] => io(dir).names().filter((n) => ID_RE.test(n))
750
+
751
+ /** a card's stamp: any write of its head or its thread moves it */
752
+ export const cardStamp = (dir: string, id: string): string => io(dir).stamp(id)
753
+
754
+ /** a card's head as it is stored, and the time it was written; null with no head */
755
+ export const rawHead = (dir: string, id: string): { head: unknown; at: number } | null => io(dir).head(id)
756
+
757
+ /** the ids of a card's messages, oldest first */
758
+ export const threadIds = (dir: string, id: string): string[] => (ID_RE.test(id) ? io(dir).threadIds(id) : [])
759
+
760
+ /** one message as it is stored */
761
+ export const rawMessage = (dir: string, id: string, mid: string): unknown => io(dir).message(id, mid)
762
+
763
+ export type LandedFile = { did: 'landed' | 'same' | 'kept'; why?: string }
764
+
765
+ /** the longest card or message id a card carried between machines may have: a folder or file name of about 120
766
+ * characters fits every file system, with its `.tmp` and `.land-<pid>` beside it */
767
+ export const MAX_ID_LENGTH = 120
768
+
769
+ /** a head made on another machine written as this card's item.json: a new card built in a dot folder and renamed,
770
+ * an existing one rewritten under its lock once `keep` (given the head as the file says now) has no reason to keep
771
+ * it. A head that is no item of that id is kept out. `dry` says what it would do */
772
+ export function landHead(dir: string, id: string, head: unknown, o: { keep: (cur: Item) => string | null; aside?: (cur: Item) => boolean; dry?: boolean; waitMs?: number }): LandedFile {
773
+ if (id.length > MAX_ID_LENGTH) return { did: 'kept', why: `card ${id.slice(0, 40)}…: its id is over ${MAX_ID_LENGTH} characters` }
774
+ const problems = itemProblems(head)
775
+ 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'})` }
776
+ const c = io(dir)
777
+ const folder = c.folder(id)
778
+ const decide = (cur: Item): LandedFile | null => {
779
+ if (revOf(cur) === revOf(head)) return { did: 'same' }
780
+ const why = o.keep(cur)
781
+ return why == null ? null : { did: 'kept', why }
782
+ }
783
+ if (!c.has(id)) {
784
+ if (o.dry) return { did: 'landed' }
785
+ // the rows land a new card under the lock below, in one transaction
786
+ if (!c.rows && !c.taken(id)) {
787
+ mkdirSync(dir, { recursive: true })
788
+ const tmp = join(dir, `.${id}.land-${process.pid}`)
789
+ rmSync(tmp, { recursive: true, force: true })
790
+ mkdirSync(tmp)
791
+ writeJson(join(tmp, 'item.json'), head)
792
+ try {
793
+ renameSync(tmp, folder)
794
+ return { did: 'landed' }
795
+ } catch {
796
+ // a card of that id came meanwhile: its lock decides below
797
+ rmSync(tmp, { recursive: true, force: true })
798
+ }
799
+ }
800
+ }
801
+ if (o.dry) return decide(c.head(id)?.head as Item) ?? { did: 'landed' }
802
+ return c.lock(id, () => {
803
+ let aside = false
804
+ const now = c.head(id)
805
+ if (now != null) {
806
+ const cur = now.head as Item
807
+ const held = decide(cur)
808
+ if (held != null) return held
809
+ // the head it replaces stays beside it, the last one: a loss is never silent and never final
810
+ if (o.aside?.(cur) === true) {
811
+ c.keepReplaced(id, cur)
812
+ aside = true
813
+ }
814
+ }
815
+ const moved = setAsideClashes(folder, head as Item)
816
+ c.write(id, head)
817
+ const said = [
818
+ ...(aside ? [`a head made apart replaced this machine's, which is kept beside it as ${REPLACED}`] : []),
819
+ ...(moved.length > 0 ? [`this machine's files of the names the landing head gives to other bytes are kept as ${moved.join(', ')}`] : []),
820
+ ]
821
+ return said.length > 0 ? { did: 'landed', why: `card ${id}: ${said.join('; ')}` } : { did: 'landed' }
822
+ }, o.waitMs)
823
+ }
824
+
825
+ /** the head a landing replaced while this machine's change of it was not in it */
826
+ export const REPLACED = 'item.replaced.json'
827
+ /** the files of this machine a landing head names with other bytes (a view added apart under the same file name) */
828
+ export const REPLACED_FILES = 'replaced'
829
+
830
+ /** each file the head names by its facts whose bytes here are other bytes moves to `replaced/`: the media store would
831
+ * 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 */
832
+ function setAsideClashes(folder: string, head: Item): string[] {
833
+ const moved: string[] = []
834
+ for (const [name, fact] of Object.entries(head.media ?? {})) {
835
+ const f = join(folder, name)
836
+ const s = statSync(f, { throwIfNoEntry: false })
837
+ if (!s?.isFile()) continue
838
+ if (s.size === fact.size && new Bun.CryptoHasher('sha256').update(readFileSync(f)).digest('hex') === fact.sha) continue
839
+ mkdirSync(join(folder, REPLACED_FILES, dirname(name)), { recursive: true })
840
+ // an earlier clash of that name stays: the next one takes `<name>.2.<ext>`, `.3`
841
+ const ext = extname(name)
842
+ let to = name
843
+ for (let n = 2; existsSync(join(folder, REPLACED_FILES, to)); n++) to = `${name.slice(0, name.length - ext.length)}.${n}${ext}`
844
+ renameSync(f, join(folder, REPLACED_FILES, to))
845
+ moved.push(`${REPLACED_FILES}/${to}`)
846
+ }
847
+ return moved
848
+ }
849
+
850
+ /** does that card keep a head a landing replaced */
851
+ export const hasReplaced = (dir: string, id: string): boolean => ID_RE.test(id) && io(dir).hasReplaced(id)
852
+
853
+ /** a message made on another machine written into its card's thread, once: never over a file of its id. `no-card`
854
+ * while the card has no head here: the caller holds it. A message that is not one is kept out */
855
+ export function landMessage(dir: string, id: string, m: unknown, o: { dry?: boolean } = {}): LandedFile | { did: 'no-card' } {
856
+ const mid = m != null && typeof m === 'object' ? (m as { id?: unknown }).id : undefined
857
+ const problems = typeof mid === 'string' && MESSAGE_RE.test(mid) ? messageProblems(m, mid) : ['no message id']
858
+ 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` }
859
+ if (!ID_RE.test(id) || problems.length > 0) return { did: 'kept', why: `a message of card ${id}: ${problems.join('; ') || 'no card id'}` }
860
+ const c = io(dir)
861
+ if (!c.has(id)) return { did: 'no-card' }
862
+ // one id is made on two machines only by one party in one millisecond: the one here stays, and it is said
863
+ 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` }
864
+ if (o.dry) return { did: 'landed' }
865
+ c.append(id, m as Message)
866
+ return { did: 'landed' }
867
+ }
868
+
485
869
  /** the media facts an item lacks (one written before facts were kept, a file whose size moved): each file still in the
486
870
  * folder hashed, written under its lock; the item as it is when nothing was missing */
487
871
  export async function fillMedia(dir: string, id: string): Promise<Item | null> {
488
872
  const x = readRaw(dir, id)
489
873
  if (!x) return null
490
- const folder = join(dir, id)
874
+ const folder = io(dir).folder(id)
491
875
  const held = x.item.media ?? {}
492
876
  const names = mediaFilesOf(x)
493
877
  const size = (n: string): number | undefined => statSync(join(folder, n), { throwIfNoEntry: false })?.size
@@ -514,8 +898,23 @@ export function readItem(dir: string, id: string): ReviewItem | null {
514
898
  return x
515
899
  }
516
900
 
517
- /** one item as the file says, whatever the unit: what the index keeps */
518
- function readRaw(dir: string, id: string): ReviewItem | null {
901
+ /** one item as it is stored, whatever the unit: what the index keeps */
902
+ 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)
903
+
904
+ /** a card this process misses while a move runs: a process that read the switch before it turned made it on the side
905
+ * the move left, so it is carried over now, as the move's own pass after its lag would. Whether it is here now */
906
+ function healed(dir: string, id: string): boolean {
907
+ if (!cardsMoving()) return false
908
+ const c = io(dir)
909
+ const other = c.rows ? filesIO(dir) : rowsIO(dir)
910
+ if (!other.has(id)) return false
911
+ const { carryCard } = require('./move.ts') as typeof import('./move.ts')
912
+ carryCard(dir, id, other, c)
913
+ return c.has(id)
914
+ }
915
+
916
+ /** one item as its files say */
917
+ function readRawFile(dir: string, id: string): ReviewItem | null {
519
918
  if (!ID_RE.test(id)) return null
520
919
  const folder = join(dir, id)
521
920
  if (!existsSync(folder)) return null
@@ -548,22 +947,38 @@ function readThread(dir: string, id: string): Message[] {
548
947
  }
549
948
 
550
949
  /** appends one message to an item's thread, its image copied in beside it; the id never collides */
551
- export function appendMessage(dir: string, id: string, m: Omit<Message, 'id' | 'at'>, o: { image?: string; now?: Date } = {}): Message {
950
+ export function appendMessage(dir: string, id: string, m: Omit<Message, 'id' | 'at'>, o: { image?: string; now?: Date; machine?: true } = {}): Message {
552
951
  const now = o.now ?? new Date()
553
952
  if (o.image !== undefined) {
554
953
  if (!existsSync(o.image)) throw new Error(`${o.image}: no such file`)
555
954
  if (!IMAGE_EXT.test(extname(o.image).toLowerCase())) throw new Error(`${o.image}: a png, jpg or webp`)
556
955
  }
557
- const folder = join(dir, id, 'thread')
558
- mkdirSync(folder, { recursive: true })
956
+ // a card with no head here (set aside, deleted) gets no thread: a folder with no head would read as a broken card
957
+ const c = io(dir)
958
+ if (!c.has(id) && !healed(dir, id)) throw new Error(`no card ${id}`)
959
+ const folder = join(c.folder(id), 'thread')
559
960
  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
961
+ let n = 1
962
+ for (;;) {
963
+ let mid = n === 1 ? base : `${base}-${n}`
964
+ for (; c.hasMessage(id, mid); n++) mid = `${base}-${n + 1}`
965
+ const file = o.image === undefined ? undefined : `${mid}${extname(o.image).toLowerCase()}`
966
+ if (o.image !== undefined && file) {
967
+ mkdirSync(folder, { recursive: true })
968
+ copyFileSync(o.image, join(folder, file))
969
+ }
970
+ const session = !o.machine && partyOf(m.who) === 'agent' && m.session === undefined ? sessionId() : null
971
+ if (session) noteSession(dir)
972
+ const out: Message = { id: mid, at: now.toISOString(), ...m, ...(session ? { session } : {}), ...(file ? { image: file } : {}) }
973
+ try {
974
+ c.append(id, out)
975
+ return out
976
+ } catch (e) {
977
+ // another process took that id between the look and the write: the next one
978
+ if ((e as { code?: unknown }).code !== 'EEXIST' || n > 50) throw e
979
+ n++
980
+ }
981
+ }
567
982
  }
568
983
 
569
984
  /** 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 +992,208 @@ export function addMessage(dir: string, id: string, who: string, text: unknown,
577
992
  return appendMessage(dir, id, { who, text: t.text, ...(typeof re === 'string' ? { re } : {}) }, { ...(image !== undefined ? { image } : {}), now })
578
993
  }
579
994
 
995
+ /** one option of a question: its words, and its media, one file (a picture, a clip, a sound) or a before and an after */
996
+ export interface AskOption {
997
+ label: string
998
+ files?: readonly string[]
999
+ }
1000
+
1001
+ /** an agent's question to the owner on a thread's item: its words, two options or more, each words or a media, the
1002
+ * option it picks; each option's media becomes a view the message holds (addView `message`), and the owner answers in
1003
+ * one click (answerAsk) */
1004
+ export async function postAsk(dir: string, id: string, q: { who: string; text: unknown; options?: readonly (string | AskOption)[]; pick?: number; kind?: AnswerKind; secret?: { name: string; login?: boolean }; done?: readonly number[]; now?: Date; replaces?: string; step?: { of: string; i: number } }): Promise<Message> {
1005
+ const x = readItem(dir, id)
1006
+ if (!x) throw new Error(`no item ${id}`)
1007
+ const t = textOf(q.text)
1008
+ if ('error' in t) throw new Error(`the question: ${t.error.replace(/^text: /, '')}`)
1009
+ const kind = q.kind ?? 'choice'
1010
+ if (!ANSWER_KINDS.includes(kind)) throw new Error(`a question's kind: one of ${ANSWER_KINDS.join(', ')}`)
1011
+ const replaces = { ...(q.replaces !== undefined ? { replaces: q.replaces } : {}), ...(q.step !== undefined ? { step: q.step } : {}) }
1012
+ if (kind !== 'choice') return appendMessage(dir, id, { who: q.who, text: t.text, ask: kindAsk(dir, x, kind, q), ...replaces }, q.now ? { now: q.now } : {})
1013
+ if (q.options === undefined) throw new Error('a question offers two options or more: --option "<a>" --option "<b>"')
1014
+ const options = q.options.map((o) => (typeof o === 'string' ? { label: o } : o)).map((o) => ({ ...o, label: o.label.trim() })).filter((o) => o.label !== '' || (o.files?.length ?? 0) > 0)
1015
+ if (options.length < 2) throw new Error('a question offers two options or more: --option "<a>" --option "<b>"')
1016
+ 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}`)
1017
+ for (const f of options.flatMap((o) => o.files ?? [])) if (!existsSync(f)) throw new Error(`${f}: no such file`)
1018
+ const labels = options.map((o, i) => o.label || basename(o.files![o.files!.length - 1]!).replace(/\.[^.]+$/, '') || `option ${i + 1}`)
1019
+ const views: (number | null)[] = []
1020
+ for (const [i, o] of options.entries()) {
1021
+ if (!o.files?.length) {
1022
+ views.push(null)
1023
+ continue
1024
+ }
1025
+ const item = await addView(dir, id, filesView(labels[i]!, o.files, `option ${i + 1}: one file, or a before and an after`), { message: true })
1026
+ views.push(item.views.length - 1)
1027
+ }
1028
+ const media = views.some((v) => v !== null) ? { views } : {}
1029
+ return appendMessage(dir, id, { who: q.who, text: t.text, ask: { options: labels, ...(q.pick !== undefined ? { pick: q.pick } : {}), ...media }, ...replaces }, q.now ? { now: q.now } : {})
1030
+ }
1031
+
1032
+ /** the longest text or url he answers with */
1033
+ export const ANSWER_VALUE_MAX = 20_000
1034
+
1035
+ export const isWebUrl = (s: string): boolean => {
1036
+ try {
1037
+ const u = new URL(s)
1038
+ return (u.protocol === 'https:' || u.protocol === 'http:') && u.hostname !== ''
1039
+ } catch {
1040
+ return false
1041
+ }
1042
+ }
1043
+
1044
+ /** a question of another kind than a choice, as the store keeps it: a checklist's lines (words alone, no media), a
1045
+ * secret's name; a secret is refused on an object whose kind frames a page, which shares the hub's origin
1046
+ * (wiki tools/shipkit/threads-asks.md, The secret field) */
1047
+ function kindAsk(dir: string, x: ReviewItem, kind: AnswerKind, q: { options?: readonly (string | AskOption)[]; secret?: { name: string; login?: boolean }; done?: readonly number[] }): MessageAsk {
1048
+ if (kind === 'checklist') {
1049
+ const lines = (q.options ?? []).map((o) => (typeof o === 'string' ? o : o.label).replace(/\s+/g, ' ').trim())
1050
+ if (lines.length === 0 || lines.some((l) => l === '')) throw new Error('a checklist holds one line or more, each words: --checklist "<step>" …')
1051
+ if ((q.options ?? []).some((o) => typeof o !== 'string' && (o.files?.length ?? 0) > 0)) throw new Error('a checklist line is words: a picture goes as its own message before it')
1052
+ const done = [...new Set(q.done ?? [])].sort((a, b) => a - b)
1053
+ if (done.some((i) => !Number.isInteger(i) || i < 0 || i >= lines.length)) throw new Error(`a line done: one of 0 to ${lines.length - 1}`)
1054
+ return { kind, options: lines, ...(done.length > 0 ? { done } : {}) }
1055
+ }
1056
+ if ((q.options ?? []).length > 0) throw new Error(`a ${kind} question holds no options: --option goes with a choice`)
1057
+ if (kind !== 'secret') return { kind, options: [] }
1058
+ const name = q.secret?.name.trim() ?? ''
1059
+ if (!SECRET_NAME.test(name)) throw new Error(`--secret: ${name === '' ? 'the secret\'s name' : `${name} is no secret name`} (letters, digits, . _ @ / -, no leading dash), as the registry names it: rv/<service>/<what>`)
1060
+ const spec = specOf(dir)
1061
+ const own = ownAddressOf(x.item, spec)
1062
+ const def = own == null ? undefined : spec.kinds[own.slice(0, own.indexOf(':'))]
1063
+ if (def?.view !== undefined || def?.diff?.page !== undefined)
1064
+ throw new Error(`--secret on ${own}: its kind frames a page of the repo in the hub, and a secret field never sits beside one; ask it on the ask's own thread, ask:<id> (wiki tools/shipkit/threads-asks.md, The secret field)`)
1065
+ return { kind, options: [], secret: { name, ...(q.secret?.login ? { login: true as const } : {}) } }
1066
+ }
1067
+
1068
+ /** one field of a proposed change as an agent sends it: its key (empty for a change of one), its values, how it draws */
1069
+ export interface ProposeInput {
1070
+ key?: string
1071
+ before?: string
1072
+ after: string
1073
+ type?: DiffType
1074
+ lang?: string
1075
+ }
1076
+
1077
+ /** an agent's proposed change of an object, one field or several: the owner applies each field alone, as it is or
1078
+ * after the owner's edit (answerAsk), and the agent lands what he applied. A field draws as the agent names it, else as the
1079
+ * object's kind declares (`diff`), else as its values read; a sound field's two files become a view the message holds */
1080
+ export async function postPropose(dir: string, id: string, p: { who: string; text: unknown; on: string; fields: readonly ProposeInput[]; now?: Date; replaces?: string }): Promise<Message> {
1081
+ if (!readItem(dir, id)) throw new Error(`no item ${id}`)
1082
+ const on = addressOrThrow(p.on)
1083
+ if (p.fields.length === 0) throw new Error('--after: the value it proposes')
1084
+ const many = p.fields.length > 1
1085
+ const keys = p.fields.map((f) => f.key?.trim() ?? '')
1086
+ if (many && keys.some((k) => k === '')) throw new Error('a change of several fields names each: --field <key> before its --before and --after')
1087
+ if (new Set(keys).size !== keys.length) throw new Error(`each field once: ${keys.filter((k, i) => keys.indexOf(k) !== i).join(', ')} twice`)
1088
+ const kind = specOf(dir).kinds[on.slice(0, on.indexOf(':'))]?.diff
1089
+ const fields: ProposeField[] = []
1090
+ for (const [i, f] of p.fields.entries()) {
1091
+ const key = keys[i]!
1092
+ if (f.after.trim() === '') throw new Error(`${key ? `--field ${key}: ` : ''}--after: the value it proposes`)
1093
+ if (f.type !== undefined && !DIFF_TYPES.includes(f.type)) throw new Error(`${key ? `--field ${key}: ` : ''}--type: one of ${DIFF_TYPES.join(', ')}`)
1094
+ const declared = kind?.fields?.[key] !== undefined ? valueKindOf(kind.fields[key]!) : null
1095
+ const type: DiffType = f.type ?? declared?.type ?? (f.lang ? 'code' : diffTypeOf(f))
1096
+ const lang = f.lang ?? (type === 'code' ? declared?.lang : undefined)
1097
+ let view: number | undefined
1098
+ if (kindOfValue(type).file) {
1099
+ const files = [...(f.before !== undefined ? [f.before] : []), f.after]
1100
+ for (const x of files) if (!existsSync(x)) throw new Error(`${key ? `--field ${key}: ` : ''}${x}: no such file (a ${kindOfValue(type).label} field takes its files)`)
1101
+ const item = await addView(dir, id, filesView(key || kindOfValue(type).label, files, `a ${kindOfValue(type).label} field: one file, or a before and an after`), { message: true })
1102
+ view = item.views.length - 1
1103
+ }
1104
+ fields.push({ key, after: f.after, ...(f.before !== undefined ? { before: f.before } : {}), ...(type !== 'text' ? { type } : {}), ...(type === 'code' && lang ? { lang } : {}), ...(view !== undefined ? { view } : {}) })
1105
+ }
1106
+ const t = textOf(p.text ?? `a change of ${on}`)
1107
+ if ('error' in t) throw new Error(t.error)
1108
+ const { key: _key, ...flat } = fields[0]!
1109
+ // one field keeps its key when it names one: an object's kind applies it by that name (review/kind-apply.ts)
1110
+ const propose: MessagePropose = many ? { on, after: fields.map((f) => `${f.key}: ${f.after}`).join('\n'), fields } : keys[0] ? { on, ...flat, fields } : { on, ...flat }
1111
+ if (kind?.page) propose.page = kind.page
1112
+ return appendMessage(dir, id, { who: p.who, text: t.text, propose, ...(p.replaces !== undefined ? { replaces: p.replaces } : {}) }, p.now ? { now: p.now } : {})
1113
+ }
1114
+
1115
+ /** the owner's answer to a question (an option) or to a proposed change (apply one field, the value as proposed or the owner's
1116
+ * edit of it in `value`), with the owner's words */
1117
+ export function answerAsk(dir: string, id: string, a: { re: string; option?: number; apply?: boolean; field?: string; value?: string; text?: string; tick?: boolean; pick?: number; opens?: number; now?: Date }): Message {
1118
+ const x = readItem(dir, id)
1119
+ if (!x) throw new Error(`no item ${id}`)
1120
+ const m = x.thread.find((y) => y.id === a.re)
1121
+ if (!m || (m.ask === undefined && m.propose === undefined)) throw new Error(`re: ${a.re} is no question nor proposed change of ${id}`)
1122
+ const words = a.text?.trim() ?? ''
1123
+ const at = a.now ? { now: a.now } : {}
1124
+ const kind = m.ask?.kind ?? 'choice'
1125
+ if (m.ask && kind === 'secret') throw new Error('a secret is typed into its own field of the hub, and its value never goes into a thread')
1126
+ if (m.ask && kind === 'file') throw new Error('a file question is answered by the file he drops')
1127
+ if (m.ask && (kind === 'checklist' || kind === 'confirm')) {
1128
+ const lines = linesOf(m)
1129
+ const o = kind === 'confirm' ? 0 : a.option
1130
+ if (o === undefined || !Number.isInteger(o) || o < 0 || o >= lines.length) throw new Error(`option: the line, one of 0 to ${lines.length - 1}`)
1131
+ const tick = a.tick ?? true
1132
+ const choice = m.ask.choices?.[o] ?? null
1133
+ if (a.pick !== undefined && choice === null) throw new Error(`pick: the step « ${lines[o]} » holds no choice`)
1134
+ if (a.pick !== undefined && !(Number.isInteger(a.pick) && a.pick >= 0 && a.pick < choice!.options.length && tick)) throw new Error(`pick: one of 0 to ${choice!.options.length - 1}, with a tick`)
1135
+ const picked = a.pick !== undefined ? `: ${choiceName(choice!.options[a.pick]!)}` : ''
1136
+ return appendMessage(dir, id, { who: 'owner', re: a.re, answer: { option: o, tick, ...(a.pick !== undefined ? { pick: a.pick } : {}) }, text: words === '' ? `${tick ? '✓' : '✗'} ${lines[o]}${picked}` : words }, at)
1137
+ }
1138
+ if (m.ask && (kind === 'text' || kind === 'url')) {
1139
+ const value = a.value?.trim() ?? ''
1140
+ if (value === '') throw new Error(`value: the ${kind} he gives`)
1141
+ if (value.length > ANSWER_VALUE_MAX) throw new Error(`value: at most ${ANSWER_VALUE_MAX} characters`)
1142
+ if (kind === 'url' && !isWebUrl(value)) throw new Error('value: a link that starts with http:// or https://')
1143
+ const opens = kind === 'url' && a.opens !== undefined && Number.isInteger(a.opens) && a.opens >= 0 ? { opens: a.opens } : {}
1144
+ return appendMessage(dir, id, { who: 'owner', re: a.re, answer: { value, ...opens }, text: words === '' ? value : words }, at)
1145
+ }
1146
+ if (m.ask) {
1147
+ const o = a.option
1148
+ 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}`)
1149
+ const label = m.ask.options[o]!
1150
+ return appendMessage(dir, id, { who: 'owner', re: a.re, answer: { option: o }, text: words === '' ? label : `${label}: ${words}` }, a.now ? { now: a.now } : {})
1151
+ }
1152
+ if (a.apply !== true) throw new Error('a proposed change is answered by apply, or by a reply')
1153
+ const fields = proposeFields(m.propose!)
1154
+ const named = a.field === undefined || a.field === '' ? undefined : a.field
1155
+ if (named === undefined && fields.length > 1) throw new Error(`field: one of ${fields.map((y) => y.key).join(', ')}; « apply all » is one answer a field`)
1156
+ const f = named === undefined ? fields[0]! : fields.find((y) => y.key === named)
1157
+ if (!f) throw new Error(`field: one of ${fields.map((y) => y.key).join(', ')}`)
1158
+ const value = a.value !== undefined && a.value.trim() !== '' ? a.value : f.after
1159
+ return appendMessage(dir, id, { who: 'owner', re: a.re, answer: { apply: true, ...(named !== undefined ? { field: named } : {}), value }, text: words === '' ? value : words }, a.now ? { now: a.now } : {})
1160
+ }
1161
+
1162
+ /** the open secret question `re` of item `id`, or why there is none; its name and whether an account goes with it */
1163
+ export function secretQuestion(dir: string, id: string, re: string): { name: string; login: boolean } | { error: string } {
1164
+ const x = readItem(dir, id)
1165
+ const m = x?.thread.find((y) => y.id === re)
1166
+ if (!x || !m || m.ask?.kind !== 'secret' || !m.ask.secret) return { error: `${re} is no secret question of ${id}` }
1167
+ if (!askOpen(x.thread, m)) return { error: `${m.ask.secret.name} is no longer asked here` }
1168
+ return { name: m.ask.secret.name, login: m.ask.secret.login === true }
1169
+ }
1170
+
1171
+ /** the owner's answer to a secret question once its value is in the house secret manager: the name and the time, never
1172
+ * the value, which this function never sees */
1173
+ export function answerSecret(dir: string, id: string, a: { re: string; now?: Date }): Message {
1174
+ const q = secretQuestion(dir, id, a.re)
1175
+ if ('error' in q) throw new Error(q.error)
1176
+ return appendMessage(dir, id, { who: 'owner', re: a.re, answer: { stored: q.name }, text: `stored as ${q.name}` }, a.now ? { now: a.now } : {})
1177
+ }
1178
+
1179
+ /** the owner's click on one of the kind's actions on the thread's object: a message the holder's watch prints */
1180
+ export function postAction(dir: string, id: string, a: { name: string; text?: string; re?: string; now?: Date }): Message {
1181
+ const x = readItem(dir, id)
1182
+ if (!x) throw new Error(`no item ${id}`)
1183
+ if (!/^[a-z][a-z0-9-]*$/.test(a.name)) throw new Error(`action: ${a.name} is no action name`)
1184
+ // `re`: the link of an object in the thread the action is on (a reflection's box), so the box reads its own answer
1185
+ if (a.re !== undefined && !x.thread.some((m) => m.id === a.re && m.about !== undefined)) throw new Error(`re: ${a.re} is no link of ${id}`)
1186
+ const words = a.text?.trim() ?? ''
1187
+ return appendMessage(dir, id, { who: 'owner', action: { name: a.name }, text: words === '' ? a.name : words, ...(a.re !== undefined ? { re: a.re } : {}) }, a.now ? { now: a.now } : {})
1188
+ }
1189
+
1190
+ /** a link from a thread to another object: the thread names it, the object's thread control finds the thread */
1191
+ export function attachTo(dir: string, id: string, who: string, address: string, now = new Date(), o: { asksVerdict?: true } = {}): Message {
1192
+ if (!readItem(dir, id)) throw new Error(`no item ${id}`)
1193
+ const a = addressOrThrow(address)
1194
+ return appendMessage(dir, id, { who, text: `attached ${a}`, about: [a], ...o }, { now })
1195
+ }
1196
+
580
1197
  /** 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
1198
  * checks them */
582
1199
  export function filesView(label: string, files: readonly string[], usage: string): ViewInput {
@@ -593,7 +1210,11 @@ export interface UpdateInput {
593
1210
  state: string
594
1211
  text: unknown
595
1212
  files?: readonly string[]
1213
+ /** its pictures as given, never a webp */
1214
+ keep?: boolean
596
1215
  now?: Date
1216
+ /** written by the machine: no session stamped, so it holds nothing */
1217
+ machine?: true
597
1218
  }
598
1219
 
599
1220
  /** an agent's update on its card, at any time, before or after his answer: its file, or its pair, becomes the card's next view
@@ -602,8 +1223,8 @@ export interface UpdateInput {
602
1223
  export async function postUpdate(dir: string, id: string, u: UpdateInput): Promise<{ item: Item; message: Message; tag: string; view: number | null }> {
603
1224
  const x = readItem(dir, id)
604
1225
  if (!x) throw new Error(`no card ${id}`)
605
- 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`)
1226
+ if (x.item.origin.by !== 'agent') return lineOnNote(dir, x, u)
1227
+ 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
1228
  if (!UPDATE_STATES.includes(u.state as UpdateState)) throw new Error(`the state: one of ${UPDATE_STATES.join(', ')}, not « ${u.state} »`)
608
1229
  const state = u.state as UpdateState
609
1230
  const t = textOf(u.text)
@@ -612,12 +1233,28 @@ export async function postUpdate(dir: string, id: string, u: UpdateInput): Promi
612
1233
  for (const f of files) if (!existsSync(f)) throw new Error(`${f}: no such file`)
613
1234
  const k = updatesOf(x).length + 1
614
1235
  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 })
1236
+ 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 }, { message: true, ...(u.keep ? { keep: true } : {}) })
616
1237
  const view = files.length === 0 ? null : item.views.length - 1
617
- const message = appendMessage(dir, id, { who: u.who, text: t.text, update: { state, ...(view !== null ? { view } : {}) } }, u.now ? { now: u.now } : {})
1238
+ const message = appendMessage(dir, id, { who: u.who, text: t.text, update: { state, ...(view !== null ? { view } : {}) } }, { ...(u.now ? { now: u.now } : {}), ...(u.machine ? { machine: true } : {}) })
618
1239
  return { item, message, tag: `update ${k} (${UPDATE_WORDS[state]})`, view }
619
1240
  }
620
1241
 
1242
+ /** an update on an item he raised (a thread his note heads): a line on it, its one picture the line's image; the note
1243
+ * keeps its own state. A clip or a pair is a version of the address: sk thread post */
1244
+ async function lineOnNote(dir: string, x: ReviewItem, u: UpdateInput): Promise<{ item: Item; message: Message; tag: string; view: number | null }> {
1245
+ if (!UPDATE_STATES.includes(u.state as UpdateState)) throw new Error(`the state: one of ${UPDATE_STATES.join(', ')}, not « ${u.state} »`)
1246
+ const state = u.state as UpdateState
1247
+ const t = textOf(u.text)
1248
+ if ('error' in t) throw new Error(`the line: ${t.error.replace(/^text: /, '')}`)
1249
+ const files = u.files ?? []
1250
+ const own = ownAddressOf(x.item, specOf(dir))
1251
+ if (files.length > 1 || files.some((f) => !/\.(png|jpe?g|webp)$/i.test(f))) throw new Error(`a line on his note takes one picture; a clip or a before and an after is a version: sk thread post ${own ?? '<kind>:<key>'} …`)
1252
+ for (const f of files) if (!existsSync(f)) throw new Error(`${f}: no such file`)
1253
+ const k = updatesOf(x).length + 1
1254
+ const message = appendMessage(dir, x.item.id, { who: u.who, text: t.text, update: { state } }, { ...(files[0] ? { image: files[0] } : {}), ...(u.now ? { now: u.now } : {}) })
1255
+ return { item: x.item, message, tag: `update ${k} (${UPDATE_WORDS[state]})`, view: null }
1256
+ }
1257
+
621
1258
  /** `party` read what the other party wrote on an item: one `seen` message naming them; how many it read. `only`: the
622
1259
  * messages a page drew, so a word that came after it is never marked read */
623
1260
  export function markRead(dir: string, id: string, party: Party, who: string = party === 'owner' ? 'owner' : agentName(), now = new Date(), only?: readonly string[]): number {
@@ -631,7 +1268,7 @@ export function markRead(dir: string, id: string, party: Party, who: string = pa
631
1268
  /** the path of a message's image, null for any other name */
632
1269
  export function threadImage(dir: string, id: string, name: string): string | null {
633
1270
  if (!ID_RE.test(id) || !MESSAGE_FILE_RE.test(name)) return null
634
- const f = join(dir, id, 'thread', name)
1271
+ const f = join(io(dir).folder(id), 'thread', name)
635
1272
  return existsSync(f) ? f : null
636
1273
  }
637
1274
 
@@ -664,7 +1301,7 @@ function readOne(dir: string, id: string): Read {
664
1301
 
665
1302
  /** 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
1303
  * 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))
1304
+ export const readAll = (dir: string): ReadAll => checked(cardsInDb() ? rowsAll(dir) : readRaws(dir), specOf(dir))
668
1305
 
669
1306
  const checks = new WeakMap<ReadAll, { spec: Spec; all: ReadAll }>()
670
1307
 
@@ -686,10 +1323,10 @@ function checked(raw: ReadAll, spec: Spec): ReadAll {
686
1323
  /** the json index each store kept beside it before the machine index, removed once per process */
687
1324
  const OLD_INDEX = (dir: string): string => join(dirname(resolve(dir)), `.${basename(dir)}-index.shipkit.json`)
688
1325
  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
1326
+ /** when this process last marked its code as using each store: again each USED_EVERY_MS, so the media job's tidy
1327
+ * (media-store/tidy.ts) never takes the reads of a code that runs */
1328
+ const used = new Map<string, number>()
1329
+ const USED_EVERY_MS = 3600_000
693
1330
 
694
1331
  /** items a step of a read covers before it gives the loop back (readRawsAsync) */
695
1332
  const READ_STEP = 250
@@ -724,7 +1361,7 @@ function* readRawsSteps(dir: string, stamps?: Map<string, string>): Generator<vo
724
1361
  const was = new Map<string, { stamp: string; read: string }>()
725
1362
  if (db)
726
1363
  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)
1364
+ 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
1365
  } catch (e) {
729
1366
  console.error(`WARN review index: ${store} read from its files: ${(e as Error).message}`)
730
1367
  }
@@ -757,20 +1394,17 @@ function* readRawsSteps(dir: string, stamps?: Map<string, string>): Generator<vo
757
1394
  else out.broken.push({ id, error: read.error })
758
1395
  }
759
1396
  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)
1397
+ const now = Date.now()
1398
+ const due = now - (used.get(store) ?? 0) >= USED_EVERY_MS
1399
+ if (moved.length === 0 && gone.length === 0 && !due) return out
1400
+ used.set(store, now)
1401
+ // the reads of a code no process runs leave in the media job's tidy, in small steps, never here
763
1402
  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 (?, ?, ?, ?, ?)')
1403
+ d.query('insert or replace into media_codes (store, code, used) values (?, ?, ?)').run(store, code, now)
1404
+ const put = d.query('insert or replace into media_items (store, code, id, stamp, read) values (?, ?, ?, ?, ?)')
767
1405
  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 = ?')
1406
+ const drop = d.query('delete from media_items where store = ? and code = ? and id = ?')
769
1407
  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
1408
  })
775
1409
  return out
776
1410
  }
@@ -802,14 +1436,33 @@ export function withdraw(dir: string, id: string, why: string, now = new Date())
802
1436
  if (before) return { already: `by ${before.who}, ${before.at.slice(0, 16).replace('T', ' ')} UTC` }
803
1437
  const v = verdictOf(x)
804
1438
  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>"` : ''
1439
+ const owes = v.status === 'approved-with-fix' ? `sk thread done ${id} "<what changed>", ` : ''
1440
+ 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
1441
  return { refused: `${id}: he answered it (${v.status}), so it waits on him no more${close}` }
808
1442
  }
809
1443
  appendMessage(dir, id, { who: agentName(), op: 'withdraw', note: why }, { now })
810
1444
  return {}
811
1445
  }
812
1446
 
1447
+ /** takes back one open question or proposed change of an agent (`re`, its message id), with the reason: it waits on
1448
+ * nobody from then, read only, its line « withdrawn: <why> » (review/supersede.ts). The words he said elsewhere (in
1449
+ * chat) go in the reason, quoted, so a question answered outside the hub never stays open */
1450
+ export function withdrawObject(dir: string, re: string, why: string, now = new Date()): { item: string } | { refused: string } {
1451
+ const x = readAll(dir).items.find((y) => y.thread.some((m) => m.id === re))
1452
+ const m = x?.thread.find((y) => y.id === re)
1453
+ if (!x || !m) return { refused: `no message ${re} (sk thread show <address> lists them)` }
1454
+ if (partyOf(m.who) !== 'agent' || (m.ask === undefined && m.propose === undefined) || m.instructions !== undefined)
1455
+ return { refused: `${re} is no question or proposed change of an agent: withdraw takes those back (an ask's instructions: sk ask … --replaces, or its bar)` }
1456
+ if (m.ask !== undefined ? !askOpen(x.thread, m) : !proposeOpen(x.thread, m)) return { refused: `${re}: he answered it already, so it waits on him no more` }
1457
+ const before = x.thread.find((y) => y.op === 'withdraw' && y.re === re)
1458
+ if (before) return { refused: `${re}: withdrawn already by ${before.who} (${before.note ?? ''})` }
1459
+ appendMessage(dir, x.item.id, { who: agentName(), op: 'withdraw', re, note: why }, { now })
1460
+ return { item: x.item.id }
1461
+ }
1462
+
1463
+ /** the reason a question answered in chat is withdrawn with: the owner's words, quoted */
1464
+ export const answeredInChat = (words: string): string => `answered in chat by the owner: « ${words.replace(/\s+/g, ' ').trim()} »`
1465
+
813
1466
  /** an answered card waits for his answer again: its verdict stays in the thread, before the reopen. `who`: an agent
814
1467
  * (the CLI), or the owner taking the verdict back (the hub). The verdict reopened, null when it has none */
815
1468
  export function reopen(dir: string, id: string, o: { who?: string; now?: Date } = {}): Verdict | null {
@@ -823,7 +1476,7 @@ export function reopen(dir: string, id: string, o: { who?: string; now?: Date }
823
1476
  /** the path of one image, clip or poster of an item, null for any other name */
824
1477
  export function imageFile(dir: string, id: string, name: string): string | null {
825
1478
  if (!ID_RE.test(id) || !FILE_RE.test(name)) return null
826
- const f = join(dir, id, name)
1479
+ const f = join(io(dir).folder(id), name)
827
1480
  return existsSync(f) ? f : null
828
1481
  }
829
1482
 
@@ -857,10 +1510,11 @@ export async function raiseItem(dir: string, input: RaiseInput): Promise<ReviewI
857
1510
  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
1511
  const now = input.now ?? new Date()
859
1512
  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`)
1513
+ const c = io(dir)
1514
+ if (input.id !== undefined && (!ID_RE.test(input.id) || c.taken(input.id))) throw new Error(`${input.id}: no item id, or taken`)
861
1515
  const base = input.id ?? idOf(now, input.title)
862
1516
  let id = base
863
- for (let n = 2; existsSync(join(dir, id)); n++) id = `${base}-${n}`
1517
+ for (let n = 2; c.taken(id); n++) id = `${base}-${n}`
864
1518
  const image = input.image === undefined ? undefined : `image${extname(input.image).toLowerCase()}`
865
1519
  const item: Item = {
866
1520
  id,
@@ -875,12 +1529,10 @@ export async function raiseItem(dir: string, input: RaiseInput): Promise<ReviewI
875
1529
  }
876
1530
  const problems = [...itemProblems(item), ...specProblems(item, specOf(dir))]
877
1531
  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)
1532
+ const tmp = tmpOf(c, id)
881
1533
  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))
1534
+ const head = { ...item, ...(image ? { media: await factsOf(tmp, [image]) } : {}) }
1535
+ createAtCommit(dir, c, id, tmp, head)
884
1536
  const who = input.origin.by === 'player' ? 'player' : 'owner'
885
1537
  if (text) appendMessage(dir, id, { who, text, ...(input.rects && input.rects.length > 0 ? { rects: input.rects } : {}) }, { now })
886
1538
  return readItem(dir, id) as ReviewItem
@@ -922,15 +1574,17 @@ export async function ownerVerdict(dir: string, o: { subject: Subject; from: str
922
1574
  }
923
1575
 
924
1576
  /** 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 {
1577
+ function locked<T>(dir: string, id: string, fn: () => T, waitMs = 2000): T {
926
1578
  const lock = join(dir, id, '.lock')
927
- const until = Date.now() + 2000
1579
+ const until = Date.now() + waitMs
928
1580
  for (;;) {
929
1581
  try {
930
1582
  mkdirSync(lock)
931
1583
  break
932
- } catch {
933
- if (Date.now() > until) {
1584
+ } catch (e) {
1585
+ // only a lock another holds is waited for: a folder that is missing or a file in the way is said at once
1586
+ if ((e as { code?: unknown }).code !== 'EEXIST') throw e
1587
+ if (Date.now() >= until) {
934
1588
  // a lock left by a dead process: older than the wait itself
935
1589
  if (Date.now() - statSync(lock).mtimeMs > 2000) {
936
1590
  rmSync(lock, { recursive: true, force: true })
@@ -951,7 +1605,7 @@ function locked<T>(dir: string, id: string, fn: () => T): T {
951
1605
  /** a state change on an item by `who`, checked by `allowed` under the item's lock, so two workers claiming at once
952
1606
  * never both win; throws with the reason it is refused. The dispatcher's ops need the repo's unit to declare one, and
953
1607
  * its holder; a topic is one the unit declares */
954
- export function act(dir: string, id: string, op: Exclude<Op, 'seen'>, who: string, o: { note?: string; text?: string; commit?: string; topic?: string; now?: Date } = {}): Message {
1608
+ export function act(dir: string, id: string, op: Exclude<Op, 'seen'>, who: string, o: { note?: string; text?: string; commit?: string; topic?: string; now?: Date; holds?: boolean } = {}): Message {
955
1609
  const spec = specOf(dir)
956
1610
  if (who !== 'owner' && who !== 'agent' && !AGENT_RE.test(who)) throw new Error(`« ${who} » is no agent name (${AGENT_RE.source})`)
957
1611
  if (!ID_RE.test(id) || !readItem(dir, id)) throw new Error(`no item ${id}`)
@@ -961,11 +1615,13 @@ export function act(dir: string, id: string, op: Exclude<Op, 'seen'>, who: strin
961
1615
  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
1616
  if (o.commit !== undefined && !/^[0-9a-f]{7,40}$/.test(o.commit)) throw new Error(`« ${o.commit} » is no commit`)
963
1617
  const now = o.now ?? new Date()
964
- return locked(dir, id, () => {
1618
+ // the first read of a process reads every card: done before the lock, the read under it only takes what moved
1619
+ readAll(dir)
1620
+ return io(dir).lock(id, () => {
965
1621
  const x = readItem(dir, id) as ReviewItem
966
1622
  const superseded = isFollowed(id, readAll(dir).items)
967
1623
  const role = spec.dispatcher ? (roleOf(dir)?.name ?? null) : null
968
- const why = op === 'claim' && superseded && x.item.origin.by === 'agent' ? 'a newer card redoes it: claim that one' : allowed(stateOf(x, superseded), op, who, role, spec.dispatcher)
1624
+ const why = op === 'claim' && superseded && x.item.origin.by === 'agent' ? 'a newer card redoes it: claim that one' : allowed(stateOf(x, superseded), op, who, role, spec.dispatcher, o.holds === true)
969
1625
  if (why) throw new Error(`${id}: ${why}`)
970
1626
  const m = appendMessage(
971
1627
  dir,
@@ -1015,7 +1671,7 @@ export function deleteRaised(dir: string, id: string): void {
1015
1671
  const x = ID_RE.test(id) ? readItem(dir, id) : null
1016
1672
  if (!x) throw new Error(`no item ${id}`)
1017
1673
  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 })
1674
+ removeItem(dir, id)
1019
1675
  }
1020
1676
 
1021
1677
  /** a player's report removed from the store, once its source deleted it there */
@@ -1023,7 +1679,43 @@ export function deleteReport(dir: string, id: string): void {
1023
1679
  const x = ID_RE.test(id) ? readItem(dir, id) : null
1024
1680
  if (!x) throw new Error(`no item ${id}`)
1025
1681
  if (x.item.origin.by !== 'player') throw new Error(`${id} is no player's report`)
1026
- rmSync(join(dir, id), { recursive: true, force: true })
1682
+ removeItem(dir, id)
1683
+ }
1684
+
1685
+ export { GONE, GONE_KEEP_MS, goneCreated, goneEntries, sweepGone } from './gone.ts'
1686
+
1687
+ /** a card out of the store: set aside while this machine carries its cards to the hq (the switch hq-cards), so the
1688
+ * job sends its deletion, and always as rows (kept GONE_KEEP_MS, the way back), else removed as it always was */
1689
+ function removeItem(dir: string, id: string): void {
1690
+ const c = io(dir)
1691
+ // while a move runs, a deletion stays as a card set aside, so neither pass carries the card back
1692
+ if (c.rows || cardsOn() || cardsMoving()) c.setAside(id, {})
1693
+ else rmSync(join(dir, id), { recursive: true, force: true })
1694
+ }
1695
+
1696
+ /** a card's folder moved to `.gone/<id>` (or `<id>.<n>` beside an earlier one), whole and under its lock: the one way
1697
+ * a card leaves the store when another machine deleted it. `created`: only the card made at that moment, so another
1698
+ * card under that id stays. What it did */
1699
+ 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')
1700
+
1701
+ /** the files' set aside: the folder moved, whole */
1702
+ function setAsideFile(dir: string, id: string, o: { created?: string; before?: number }): 'moved' | 'none' | 'other' {
1703
+ if (!ID_RE.test(id) || !existsSync(join(dir, id))) return 'none'
1704
+ return locked(dir, id, () => {
1705
+ if (o.created !== undefined || o.before !== undefined) {
1706
+ const f = join(dir, id, 'item.json')
1707
+ const cur = existsSync(f) ? (JSON.parse(readFileSync(f, 'utf8')) as { created?: unknown }) : null
1708
+ if (o.created !== undefined && cur?.created !== o.created) return 'other'
1709
+ // `before`: only a card made before that moment
1710
+ if (o.before !== undefined && !(Date.parse(String(cur?.created)) < o.before)) return 'other'
1711
+ }
1712
+ mkdirSync(join(dir, GONE), { recursive: true })
1713
+ const to = join(dir, GONE, goneEntryFor(dir, id))
1714
+ renameSync(join(dir, id), to)
1715
+ // the lock moved with the folder: the card is no longer here to lock
1716
+ rmSync(join(to, '.lock'), { recursive: true, force: true })
1717
+ return 'moved'
1718
+ })
1027
1719
  }
1028
1720
 
1029
1721
  /** 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 +1725,7 @@ export function itemOfRef(dir: string, ref: string): ReviewItem | null {
1033
1725
  if (!m) return ID_RE.test(ref) ? readItem(dir, ref) : itemOfPrefix(dir, ref)
1034
1726
  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
1727
  const tail = `-${m[1]}-${m[2]}`
1036
- for (const n of existsSync(dir) ? readdirSync(dir).filter((n) => n.endsWith(tail)).sort() : []) {
1728
+ for (const n of io(dir).names().filter((n) => n.endsWith(tail))) {
1037
1729
  try {
1038
1730
  const x = readItem(dir, n)
1039
1731
  if (holds(x)) return x
@@ -1048,8 +1740,8 @@ export function itemOfRef(dir: string, ref: string): ReviewItem | null {
1048
1740
  * 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
1741
  function itemOfPrefix(dir: string, ref: string): ReviewItem | null {
1050
1742
  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}-`))
1743
+ if (!/^\d{8}-\d{6}$/.test(p)) return null
1744
+ const hits = io(dir).names().filter((n) => n.startsWith(`${p}-`))
1053
1745
  if (hits.length > 1) throw new Error(`${p} starts ${hits.length} items: ${hits.sort().join(', ')}; give more of the id`)
1054
1746
  return hits.length === 1 ? readItem(dir, hits[0]!) : null
1055
1747
  }
@@ -1066,10 +1758,13 @@ export async function refreshDraft(dir: string, id: string, o: { image: string;
1066
1758
  if (!r.wip || verdictOf(x)) throw new Error(`${id} is not a draft card waiting`)
1067
1759
  const f0 = r.views[0]
1068
1760
  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')
1761
+ const folder = io(dir).folder(id)
1762
+ mkdirSync(folder, { recursive: true })
1071
1763
  const image = f0.files.image
1072
- copyFileSync(main.sources[0]?.[1] ?? '', join(folder, `${image}.tmp`))
1764
+ // the frame keeps the name the card gave its first one: a webp, or a picture as given before cards kept webps
1765
+ const webp = extname(image) === '.webp'
1766
+ const main = await loadView({ label: f0.label, image: o.image }, 'the live frame', webp ? { always: true } : { keep: true })
1767
+ putFile(main, main.sources[0]?.[1] ?? '', join(folder, `${image}.tmp`))
1073
1768
  renameSync(join(folder, `${image}.tmp`), join(folder, image))
1074
1769
  // a draft's one gallery is its history
1075
1770
  const label = r.views.find((v) => 'gallery' in v)?.label ?? HISTORY
@@ -1107,7 +1802,8 @@ export async function readyItem(dir: string, id: string, o: { image?: string; no
1107
1802
  const f0 = rest.views[0]
1108
1803
  if (!f0 || isGallery(f0)) throw new Error(`${id} has no image to replace`)
1109
1804
  const loaded = await loadView({ label: f0.label, image: o.image }, '--image')
1110
- const folder = join(dir, id)
1805
+ const folder = io(dir).folder(id)
1806
+ mkdirSync(folder, { recursive: true })
1111
1807
  const old = 'image' in f0.files ? f0.files.image : undefined
1112
1808
  copyFiles(loaded, 0, folder)
1113
1809
  const files = filesOf(loaded, 0)
@@ -1184,6 +1880,21 @@ function touched(path: string): void {
1184
1880
  wrote++
1185
1881
  const p = resolve(path)
1186
1882
  for (const [key, w] of watched) if (w && p.startsWith(`${key}/`)) w.dirty.add(p.slice(key.length + 1).split('/')[0] ?? '')
1883
+ stampStore(p)
1884
+ }
1885
+
1886
+ const STORE_SEGMENT = `/${LAYOUT.review}/`
1887
+ /** 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
1888
+ * died) sees any process's write with one stat of the folder. A lock is no change of the store */
1889
+ function stampStore(p: string): void {
1890
+ const i = p.lastIndexOf(STORE_SEGMENT)
1891
+ if (i < 0 || p.endsWith('/.lock')) return
1892
+ const now = new Date()
1893
+ try {
1894
+ fs.utimesSync(p.slice(0, i + STORE_SEGMENT.length - 1), now, now)
1895
+ } catch {
1896
+ // the store went with the write that named it
1897
+ }
1187
1898
  }
1188
1899
 
1189
1900
  function watchOf(dir: string): Watched | null {
@@ -1211,6 +1922,7 @@ function watchOf(dir: string): Watched | null {
1211
1922
  /** a watched store read whole before a page asks, the loop given back between two steps: the first read after a boot
1212
1923
  * is the only whole one, every later one reads the items that moved */
1213
1924
  export async function warmStore(dir: string): Promise<void> {
1925
+ if (cardsInDb()) return void rowsAll(dir)
1214
1926
  if (!existsSync(dir)) return
1215
1927
  const w = watchOf(dir)
1216
1928
  if (!w || (w.held && w.all)) return
@@ -1226,6 +1938,7 @@ export async function warmStore(dir: string): Promise<void> {
1226
1938
  /** changes when anything the list is built from changes: watched, a count of writes and what the disk check found;
1227
1939
  * else a scan. The list's ETag */
1228
1940
  export function storeStamp(dir: string, now = Date.now()): string {
1941
+ if (cardsInDb()) return rowsStamp(dir)
1229
1942
  if (!existsSync(dir)) return 'none'
1230
1943
  const w = watchOf(dir)
1231
1944
  if (!w) return scanStamp(dir)
@@ -1233,11 +1946,25 @@ export function storeStamp(dir: string, now = Date.now()): string {
1233
1946
  return `${BOOT}.${w.moved}.${w.rev}.${wrote}`
1234
1947
  }
1235
1948
 
1949
+ /** what moved the store, from what this process heard: its watch's events, its own writes, the store folder (one
1950
+ * stat). Never a stat of its items: an event the watch missed waits for the next walk of the caller's own */
1951
+ export function storeMoved(dir: string): string {
1952
+ if (cardsInDb()) return rowsStamp(dir)
1953
+ if (!existsSync(dir)) return 'none'
1954
+ const key = resolve(dir)
1955
+ const w = watchOf(dir)
1956
+ return w ? `${BOOT}.${w.moved}.${wrote}.${folderStamp(key)}` : `${BOOT}.-.${wrote}.${folderStamp(key)}`
1957
+ }
1958
+
1959
+ /** does the store hold anything: its folder, or with the switch cards-in-db its rows (a repo's cards may have no folder) */
1960
+ export const hasStore = (dir: string): boolean => (cardsInDb() ? rowsStamp(dir) !== 'none' : existsSync(dir))
1961
+
1236
1962
  /** the store's stamp and who listens (the live watchers' pids), so a watch that starts or dies moves it too */
1237
1963
  export const listingStamp = (dir: string): string => `${storeStamp(dir)}~${liveWatchers(dir).map((w) => w.pid).join(',')}`
1238
1964
 
1239
1965
  /** the stamp from a scan of every item's files: the safety net of a watcher that may miss an event */
1240
1966
  export function scanStamp(dir: string): string {
1967
+ if (cardsInDb()) return rowsStamp(dir)
1241
1968
  const h = new Bun.CryptoHasher('sha1')
1242
1969
  if (!existsSync(dir)) return 'none'
1243
1970
  const mark = (f: string): void => {
@@ -1256,7 +1983,7 @@ export function scanStamp(dir: string): string {
1256
1983
  let cached: { dir: string; tag: string; all: ReadAll } | null = null
1257
1984
 
1258
1985
  /** 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))
1986
+ export const readAllCached = (dir: string): ReadAll => checked(cardsInDb() ? rowsAll(dir) : readRawsCached(dir), specOf(dir))
1260
1987
 
1261
1988
  function readRawsCached(dir: string): ReadAll {
1262
1989
  const w = existsSync(dir) ? watchOf(dir) : null