rvlib-shipkit 2.11.0 → 2.13.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 (298) hide show
  1. package/CHANGELOG.md +56 -12
  2. package/README.md +1 -1
  3. package/package.json +4 -2
  4. package/src/agent-time/store.ts +2 -2
  5. package/src/check.ts +1 -1
  6. package/src/checks/SK001-package-json-shape.check.ts +4 -0
  7. package/src/checks/SK003-claude-md-shape.check.ts +1 -1
  8. package/src/checks/SK004-gitignore-policy.check.ts +27 -2
  9. package/src/checks/SK005-rvlib-versions.check.ts +1 -1
  10. package/src/checks/SK008-reviewer-agent.check.ts +2 -2
  11. package/src/checks/SK012-config-barrel-import.check.ts +1 -1
  12. package/src/checks/SK015-nested-repo.check.ts +1 -1
  13. package/src/checks/SK035-public-clean.check.ts +46 -0
  14. package/src/checks/SK036-draft-media-size.check.ts +28 -0
  15. package/src/cli/cmd_Backup.ts +152 -0
  16. package/src/cli/cmd_Ci.ts +8 -11
  17. package/src/cli/cmd_Drill.ts +145 -0
  18. package/src/cli/cmd_Home.ts +50 -3
  19. package/src/cli/cmd_Media.ts +96 -5
  20. package/src/cli/cmd_Review.ts +8 -2
  21. package/src/cli/cmd_Shot.ts +5 -2
  22. package/src/cli/cmd_Smoke.ts +4 -1
  23. package/src/cli/cmd_Social.ts +226 -0
  24. package/src/cli/cmd_Start.ts +1 -1
  25. package/src/cli/cmd_Time.ts +1 -1
  26. package/src/cli/cmd_Trailer.ts +9 -2
  27. package/src/cli/cmd_Veille.ts +173 -0
  28. package/src/cli/family-pages.ts +3 -0
  29. package/src/cli/registry.ts +13 -2
  30. package/src/cli.ts +5 -2
  31. package/src/collections/actions.ts +1 -49
  32. package/src/collections/checks.ts +2 -1
  33. package/src/collections/collection-types.ts +11 -2
  34. package/src/collections/providers.ts +4 -4
  35. package/src/collections/review.ts +2 -1
  36. package/src/collections/tests.ts +19 -8
  37. package/src/contracts/apply-contracts.ts +1 -3
  38. package/src/contracts/contract-manifests.ts +2 -3
  39. package/src/contracts/contract-types.ts +0 -1
  40. package/src/contracts/contracts-engine.ts +0 -3
  41. package/src/core/app-icon.ts +9 -3
  42. package/src/core/bun-builtins.ts +2 -2
  43. package/src/core/discover-checks.ts +37 -5
  44. package/src/core/fix-scope.ts +4 -2
  45. package/src/core/floor-resolve.ts +68 -48
  46. package/src/core/floor.ts +9 -0
  47. package/src/core/git-root.ts +24 -0
  48. package/src/core/last-good.ts +3 -1
  49. package/src/core/layout.ts +8 -0
  50. package/src/core/log-stamp.ts +36 -0
  51. package/src/core/loop-watch.ts +93 -0
  52. package/src/core/machine-link.ts +134 -0
  53. package/src/core/memory-watch.ts +41 -0
  54. package/src/core/one-way-in-policy.ts +27 -19
  55. package/src/core/run-ci.ts +6 -8
  56. package/src/core/run-fixers.ts +9 -9
  57. package/src/core/slots.ts +21 -0
  58. package/src/core/tree-rev.ts +60 -0
  59. package/src/core/unit-files.ts +42 -0
  60. package/src/drill/render.ts +140 -0
  61. package/src/drill/run.ts +269 -0
  62. package/src/fleet/scan-fleet.ts +6 -5
  63. package/src/home/daemon-jobs.ts +201 -0
  64. package/src/home/global-context.ts +34 -1
  65. package/src/home/home-routes.ts +22 -15
  66. package/src/home/hubs.ts +10 -3
  67. package/src/home/inbox-shape.ts +61 -6
  68. package/src/home/inbox.ts +75 -4
  69. package/src/home/lib-watch.ts +10 -3
  70. package/src/home/machine-stores.ts +15 -29
  71. package/src/home/run-daemon.ts +15 -18
  72. package/src/home/run-pm.ts +2 -0
  73. package/src/home/serve-daemon.ts +4 -3
  74. package/src/home/serve-web.ts +110 -1
  75. package/src/hooks/commit-message.ts +28 -19
  76. package/src/hooks/leak-guard.ts +10 -3
  77. package/src/hooks/run-hooks.ts +2 -6
  78. package/src/identities/identities.ts +334 -0
  79. package/src/identities/machine-route.ts +126 -0
  80. package/src/identities/machine.ts +62 -0
  81. package/src/init-repo.ts +1 -1
  82. package/src/ledger/check-stats.ts +10 -9
  83. package/src/ledger/gate-checks.ts +32 -1
  84. package/src/ledger/record-kept.ts +112 -0
  85. package/src/ledger/repo-view.ts +10 -0
  86. package/src/ledger/run-log.ts +17 -12
  87. package/src/ledger/run-timeline.ts +8 -4
  88. package/src/ledger/store.ts +7 -0
  89. package/src/ledger/suite-log.ts +17 -13
  90. package/src/media-kinds.ts +9 -1
  91. package/src/media-store/backup/daemon.ts +73 -0
  92. package/src/media-store/backup/keys.ts +25 -0
  93. package/src/media-store/backup/manifest.ts +193 -0
  94. package/src/media-store/backup/restore.ts +192 -0
  95. package/src/media-store/backup/run.ts +278 -0
  96. package/src/media-store/backup/secret.ts +86 -0
  97. package/src/media-store/backup/snapshot.ts +64 -0
  98. package/src/media-store/backup/sources.ts +199 -0
  99. package/src/media-store/content.ts +11 -1
  100. package/src/media-store/daemon.ts +56 -70
  101. package/src/media-store/hand.ts +58 -0
  102. package/src/media-store/put.ts +122 -0
  103. package/src/media-store/space.ts +73 -11
  104. package/src/pages/forward.ts +35 -0
  105. package/src/pages/frame-client.ts +118 -0
  106. package/src/pages/routes.ts +29 -0
  107. package/src/pages/unit.ts +92 -0
  108. package/src/plan/planner.ts +12 -0
  109. package/src/plan/repo-source.ts +19 -5
  110. package/src/reflect/transcript.ts +35 -10
  111. package/src/release/public-clean.ts +301 -0
  112. package/src/release/published-here.ts +22 -0
  113. package/src/release/run-bump.ts +2 -1
  114. package/src/release/run-release.ts +4 -1
  115. package/src/repo-config.ts +53 -2
  116. package/src/review/http.ts +16 -2
  117. package/src/review/media-kind.ts +3 -3
  118. package/src/review/media-read.ts +3 -3
  119. package/src/review/model.ts +24 -5
  120. package/src/review/notes.ts +77 -0
  121. package/src/review/project.ts +6 -38
  122. package/src/review/routes.ts +8 -13
  123. package/src/review/store.ts +46 -4
  124. package/src/review/trailer-media.ts +24 -3
  125. package/src/review/trailer-shots.ts +106 -0
  126. package/src/review/unit.ts +1 -1
  127. package/src/scaffold/files/agent-handoff.md +3 -0
  128. package/src/scaffold/files/agent-index.md +4 -12
  129. package/src/scaffold/project-scaffold.ts +5 -4
  130. package/src/serve/embed.ts +1 -1
  131. package/src/serve/hub-app/col-card.tsx +3 -17
  132. package/src/serve/hub-app/col-tables-view.tsx +2 -1
  133. package/src/serve/hub-app/cols-svc.ts +12 -14
  134. package/src/serve/hub-app/dock-st.ts +4 -2
  135. package/src/serve/hub-app/dock-view.tsx +2 -0
  136. package/src/serve/hub-app/frames-st.ts +35 -0
  137. package/src/serve/hub-app/hash-route.ts +64 -1
  138. package/src/serve/hub-app/home-st.ts +31 -7
  139. package/src/serve/hub-app/home-strip.css +9 -1
  140. package/src/serve/hub-app/home-strip.tsx +7 -6
  141. package/src/serve/hub-app/home.html +5 -0
  142. package/src/serve/hub-app/hub-app.tsx +49 -5
  143. package/src/serve/hub-app/hub.css +29 -11
  144. package/src/serve/hub-app/icons.tsx +16 -1
  145. package/src/serve/hub-app/identities-st.ts +210 -0
  146. package/src/serve/hub-app/identities-view.tsx +352 -0
  147. package/src/serve/hub-app/identities.css +48 -0
  148. package/src/serve/hub-app/identity-address.ts +52 -0
  149. package/src/serve/hub-app/inbox-st.ts +59 -6
  150. package/src/serve/hub-app/inbox-view.tsx +48 -6
  151. package/src/serve/hub-app/inbox.css +12 -1
  152. package/src/serve/hub-app/index.html +3 -0
  153. package/src/serve/hub-app/keys.ts +10 -2
  154. package/src/serve/hub-app/list-walk.ts +89 -0
  155. package/src/serve/hub-app/machine-st.ts +12 -0
  156. package/src/serve/hub-app/media-view.tsx +2 -1
  157. package/src/serve/hub-app/pages-frames.tsx +134 -0
  158. package/src/serve/hub-app/pages-svc.ts +111 -0
  159. package/src/serve/hub-app/palette-st.ts +18 -3
  160. package/src/serve/hub-app/palette-view.tsx +9 -2
  161. package/src/serve/hub-app/planned-view.tsx +2 -1
  162. package/src/serve/hub-app/project-list.css +18 -14
  163. package/src/serve/hub-app/project-list.tsx +88 -49
  164. package/src/serve/hub-app/projects-svc.ts +33 -3
  165. package/src/serve/hub-app/repo-sections.ts +19 -2
  166. package/src/serve/hub-app/repo-st.ts +75 -19
  167. package/src/serve/hub-app/review/review-cells.tsx +3 -3
  168. package/src/serve/hub-app/review/review-kit.ts +30 -7
  169. package/src/serve/hub-app/review/review-page.tsx +1 -1
  170. package/src/serve/hub-app/review/review-st.ts +33 -11
  171. package/src/serve/hub-app/review/review-thread.tsx +11 -9
  172. package/src/serve/hub-app/review/review-views.tsx +84 -19
  173. package/src/serve/hub-app/review/thread-st.ts +1 -10
  174. package/src/serve/hub-app/review/trailer-page.tsx +2 -1
  175. package/src/serve/hub-app/review.css +17 -8
  176. package/src/serve/hub-app/site/site-part.tsx +173 -0
  177. package/src/serve/hub-app/site/site-st.ts +157 -0
  178. package/src/serve/hub-app/site.css +35 -0
  179. package/src/serve/hub-app/social/calendar.tsx +182 -0
  180. package/src/serve/hub-app/social/comms-page.tsx +306 -0
  181. package/src/serve/hub-app/social/kit.tsx +244 -0
  182. package/src/serve/hub-app/social/post-card.tsx +456 -0
  183. package/src/serve/hub-app/social/problems.tsx +60 -0
  184. package/src/serve/hub-app/social/social-model.ts +154 -0
  185. package/src/serve/hub-app/social/social-page.tsx +674 -0
  186. package/src/serve/hub-app/social/social-st.ts +986 -0
  187. package/src/serve/hub-app/social.css +289 -0
  188. package/src/serve/hub-app/stores/stores-page.tsx +311 -0
  189. package/src/serve/hub-app/stores/stores-st.ts +286 -0
  190. package/src/serve/hub-app/stores.css +54 -0
  191. package/src/serve/hub-app/test-view.tsx +9 -2
  192. package/src/serve/hub-app/tests-svc.ts +16 -1
  193. package/src/serve/hub-app/timeline-geometry.ts +1 -1
  194. package/src/serve/hub-app/timeline-view.tsx +3 -2
  195. package/src/serve/hub-app/tree-build.ts +6 -0
  196. package/src/serve/hub-app/tree-row.tsx +27 -4
  197. package/src/serve/hub-app/tree-svc.ts +18 -49
  198. package/src/serve/hub-app/veille/veille-page.tsx +514 -0
  199. package/src/serve/hub-app/veille/veille-st.ts +443 -0
  200. package/src/serve/hub-app/veille.css +84 -0
  201. package/src/serve/hub-runtime.ts +14 -9
  202. package/src/serve/project-gutter-route.ts +44 -12
  203. package/src/serve/resources-wire.ts +48 -0
  204. package/src/serve/run-lanes.ts +7 -4
  205. package/src/serve/same-origin.ts +1 -1
  206. package/src/serve/serve-hub.ts +27 -18
  207. package/src/serve/tracked-watch.ts +24 -3
  208. package/src/serve/warm-cell.ts +5 -1
  209. package/src/shipkit-files.ts +15 -4
  210. package/src/shipkit.ts +0 -1
  211. package/src/shot/box.ts +162 -0
  212. package/src/shot/browser-slot.ts +62 -0
  213. package/src/shot/client.ts +43 -7
  214. package/src/shot/clip-encoder.ts +93 -12
  215. package/src/shot/film-box.ts +188 -0
  216. package/src/shot/shooter.ts +50 -15
  217. package/src/shot/shot-ask.ts +10 -2
  218. package/src/shot/stepped-clip.ts +5 -4
  219. package/src/site/desk.ts +242 -0
  220. package/src/site/routes.ts +66 -0
  221. package/src/site/unit.ts +62 -0
  222. package/src/social/brands.ts +22 -0
  223. package/src/social/compose.ts +97 -0
  224. package/src/social/desk-index.ts +123 -0
  225. package/src/social/desk-wire.ts +64 -0
  226. package/src/social/drafts.ts +183 -0
  227. package/src/social/house.ts +24 -0
  228. package/src/social/load.ts +319 -0
  229. package/src/social/md.ts +70 -0
  230. package/src/social/media-facts.ts +53 -0
  231. package/src/social/media-kind.ts +189 -0
  232. package/src/social/media-limit.ts +42 -0
  233. package/src/social/media-of.ts +30 -0
  234. package/src/social/migrate.ts +123 -0
  235. package/src/social/open.ts +17 -0
  236. package/src/social/post-url.ts +158 -0
  237. package/src/social/presence.ts +332 -0
  238. package/src/social/public-read.ts +53 -0
  239. package/src/social/publish/bluesky.ts +168 -0
  240. package/src/social/publish/discord.ts +76 -0
  241. package/src/social/publish/index.ts +24 -0
  242. package/src/social/publish/secret.ts +13 -0
  243. package/src/social/push.ts +31 -0
  244. package/src/social/richtext.ts +37 -0
  245. package/src/social/routes.ts +180 -0
  246. package/src/social/stats.ts +134 -0
  247. package/src/social/text.ts +267 -0
  248. package/src/social/tracker-route.ts +39 -0
  249. package/src/social/tracker.ts +255 -0
  250. package/src/social/unit.ts +53 -0
  251. package/src/social/writes.ts +130 -0
  252. package/src/start-repo.ts +14 -9
  253. package/src/stores/collection.ts +27 -0
  254. package/src/stores/desk.ts +336 -0
  255. package/src/stores/model.ts +187 -0
  256. package/src/stores/routes.ts +126 -0
  257. package/src/stores/unit.ts +57 -0
  258. package/src/suite/calibrate.ts +127 -0
  259. package/src/suite/core-counters.ts +91 -0
  260. package/src/suite/judge-suites.ts +94 -34
  261. package/src/suite/suite-cli.ts +44 -10
  262. package/src/suite/suite-cpu-preload.ts +34 -9
  263. package/src/trailer/adapter.ts +4 -0
  264. package/src/trailer/build.ts +42 -11
  265. package/src/trailer/ffmpeg.ts +11 -0
  266. package/src/trailer/footage.ts +30 -13
  267. package/src/trailer/grammar.ts +18 -2
  268. package/src/trailer/graph.ts +28 -6
  269. package/src/trailer/passage.ts +21 -6
  270. package/src/trailer/plan.ts +74 -3
  271. package/src/trailer/shelf.ts +16 -0
  272. package/src/trailer/stitch.ts +67 -26
  273. package/src/trailer/url.ts +1 -1
  274. package/src/trailer/versions.ts +24 -0
  275. package/src/ts/gate-typecheck.ts +32 -0
  276. package/src/ts/typecheck-cli.ts +9 -11
  277. package/src/tui/tui-app.tsx +0 -1
  278. package/src/veille/asks.ts +155 -0
  279. package/src/veille/auto.ts +31 -0
  280. package/src/veille/batch.ts +27 -0
  281. package/src/veille/chrome.ts +127 -0
  282. package/src/veille/collection.ts +28 -0
  283. package/src/veille/desk.ts +242 -0
  284. package/src/veille/identity.ts +80 -0
  285. package/src/veille/import.ts +68 -0
  286. package/src/veille/log.ts +183 -0
  287. package/src/veille/platforms.ts +118 -0
  288. package/src/veille/reads.ts +66 -0
  289. package/src/veille/replied.ts +110 -0
  290. package/src/veille/routes.ts +185 -0
  291. package/src/veille/service.ts +81 -0
  292. package/src/veille/watch.ts +116 -0
  293. package/src/veille/worth.ts +46 -0
  294. package/src/wiki/scan-md.ts +18 -0
  295. package/src/collections/posts.ts +0 -142
  296. package/src/contracts/manifests/social.contract.ts +0 -20
  297. package/src/scaffold/files/agent-coding.md +0 -35
  298. package/src/ts/typecheck-cache.ts +0 -11
@@ -0,0 +1,199 @@
1
+ // WHAT THE BACKUP HOLDS (wiki build/shipkit/media-store.md, Backup, The inventory): every file of the machine that no
2
+ // git and no Space keeps, its authored or irreplaceable state. The home's veille logs, the rail order, the media index
3
+ // and the machine db (consistent sqlite snapshots), the machine's private folder, the agents' memories of each house
4
+ // repo; in each house repo, every untracked file of `.shipkit/` and the hand tuned `.comfy-ts/` files, and its
5
+ // gitignored `*.local.*` files; and what the repo's config adds (`backup`: paths kept whole, sqlite files). Never a cache, a log, a scratch folder, a lock, a dev database it did not name or a media file a kind of
6
+ // the store holds. Walked with async fs: the daemon runs this between requests
7
+ import type { Dirent } from 'node:fs'
8
+ import { lstat, readdir } from 'node:fs/promises'
9
+ import { existsSync, statSync } from 'node:fs'
10
+ import { basename, extname, join, relative, sep } from 'node:path'
11
+ import { homeDir } from '../../home/home-paths.ts'
12
+ import { machineDbPath } from '../../core/machine-db.ts'
13
+ import { MACHINE_PRIVATE } from '../../core/layout.ts'
14
+ import { ORDER_FILE } from '../../serve/project-gutter-route.ts'
15
+ import { mediaDbPath } from '../db.ts'
16
+ import { loadRepoConfig, type RepoBackup } from '../../repo-config.ts'
17
+ import type { SqliteCut } from './snapshot.ts'
18
+
19
+ export interface Source {
20
+ abs: string
21
+ /** the path under the home folder: the form a manifest and a restore use */
22
+ rel: string
23
+ size: number
24
+ mtime: number
25
+ /** a live sqlite: snapshotted, never copied */
26
+ sqlite?: SqliteCut
27
+ /** a path the repo names whole: no size bound, read as a stream, not read again while its size and time hold */
28
+ whole?: true
29
+ /** why it cannot be read: refused with this reason, loud each run */
30
+ broken?: string
31
+ }
32
+
33
+ /** `.shipkit/` folders rebuilt, scratch, logs, runtime, or media the store or another owner keeps */
34
+ const SHIPKIT_DENY = new Set(['cache', 'tmp', 'logs', 'wrapper', 'locks', 'shots', 'backups', 'cloud', 'review-watchers', 'worktrees', 'node_modules', '.git'])
35
+ const FILE_DENY = /^(?:STATUS(?:\.full)?\.md|\.DS_Store|\.review-index\.json|review-dispatcher\.json)$|\.(?:log|pid|lock|sqlite(?:-wal|-shm)?|db(?:-wal|-shm)?)$/
36
+ /** the review store's media go up as the `review` kind: only its records come here */
37
+ const RECORD = /\.(?:json|jsonl|md|txt|csv)$/
38
+ /** the atelier's rolls are generated media: its kit files and records come here, never its images or sounds */
39
+ const MEDIA = /\.(?:png|jpe?g|webp|gif|avif|mp4|webm|mov|wav|mp3|flac|ogg|opus|m4a|glb|exr|safetensors)$/i
40
+ /** the hand tuned files of `.comfy-ts/`: its caches, outputs and fetched templates stay out */
41
+ const COMFY_KEEP = ['drafts', 'llm-configs', 'settings.json', 'lora-keywords.json', 'image-picker.json', 'serve-tabs.json']
42
+ /** gitignored by some repos and authored there */
43
+ const REPO_EXTRA = ['agent/global-contribution.md', 'proposal', '.local']
44
+ const CODE = /\.(?:[cm]?[jt]sx?)$/
45
+
46
+ async function walk(dir: string, keep: (rel: string, isDir: boolean) => boolean, out: string[], base = dir): Promise<void> {
47
+ let names: Dirent[]
48
+ try {
49
+ names = await readdir(dir, { withFileTypes: true })
50
+ } catch {
51
+ return
52
+ }
53
+ for (const d of names.sort((a, b) => (a.name < b.name ? -1 : 1))) {
54
+ const abs = join(dir, d.name)
55
+ const rel = relative(base, abs)
56
+ if (d.isDirectory()) {
57
+ if (keep(rel, true)) await walk(abs, keep, out, base)
58
+ } else if (d.isFile() && keep(rel, false)) out.push(abs)
59
+ }
60
+ }
61
+
62
+ const shipkitKeep = (rel: string, isDir: boolean): boolean => {
63
+ const parts = rel.split(sep)
64
+ const name = parts[parts.length - 1] ?? ''
65
+ if (isDir) return !(parts.length === 1 && SHIPKIT_DENY.has(name)) && name !== 'node_modules' && name !== '.git' && !(parts[0] === 'social' && name === 'media')
66
+ if (FILE_DENY.test(name)) return false
67
+ if (parts[0] === 'review' && !RECORD.test(name)) return false
68
+ if (parts[0] === 'assets' && MEDIA.test(name)) return false
69
+ return true
70
+ }
71
+
72
+ const comfyKeep = (rel: string): boolean => COMFY_KEEP.some((k) => rel === k || rel.startsWith(`${k}${sep}`))
73
+
74
+ async function git(repo: string, args: string[]): Promise<string[]> {
75
+ const p = Bun.spawn(['git', '-C', repo, ...args], { stdout: 'pipe', stderr: 'ignore' })
76
+ const text = await new Response(p.stdout).text()
77
+ if ((await p.exited) !== 0) return []
78
+ return text.split('\0').filter((l) => l !== '')
79
+ }
80
+
81
+ /** the gitignored `*.local.*` files of a repo, never a settings file or code */
82
+ export async function localFiles(repo: string): Promise<string[]> {
83
+ const names = await git(repo, ['ls-files', '-z', '-o', '-i', '--exclude-standard', '--', ':(glob)**/*.local.*'])
84
+ return names.filter((n) => basename(n) !== 'settings.local.json' && !CODE.test(n) && !n.split('/').some((p) => p === 'node_modules')).map((n) => join(repo, n))
85
+ }
86
+
87
+ /** the agents' config roots under the home: `.claude`, `.claude-<account>` */
88
+ async function agentRoots(home: string): Promise<string[]> {
89
+ const names = await readdir(home).catch(() => [] as string[])
90
+ return names.filter((n) => /^\.claude(?:-[\w-]+)?$/.test(n)).map((n) => join(home, n, 'projects')).filter((p) => existsSync(p))
91
+ }
92
+
93
+ /** how a session folder names a repo's path */
94
+ const sessionName = (repo: string): string => repo.replace(/[^A-Za-z0-9]/g, '-')
95
+
96
+ export interface Collect {
97
+ home: string
98
+ repos: readonly string[]
99
+ /** each repo's `*.local.*` files; the daemon caches the git walk */
100
+ locals?: (repo: string) => Promise<string[]>
101
+ /** each repo's `backup` key; by default its repo.config.ts, read again when the file moves */
102
+ backupOf?: (repo: string) => Promise<RepoBackup | null>
103
+ }
104
+
105
+ const configs = new Map<string, { mtime: number; backup: RepoBackup | null }>()
106
+
107
+ /** a repo's `backup` key from its config, loaded again only when the file moved; a config that does not load throws */
108
+ export async function backupOfRepo(repo: string): Promise<RepoBackup | null> {
109
+ const path = join(repo, 'repo.config.ts')
110
+ const mtime = statSync(path, { throwIfNoEntry: false })?.mtimeMs
111
+ if (mtime === undefined) return null
112
+ const held = configs.get(repo)
113
+ if (held?.mtime === mtime) return held.backup
114
+ const backup = (await loadRepoConfig(repo, { fresh: held !== undefined })).backup ?? null
115
+ configs.set(repo, { mtime, backup })
116
+ return backup
117
+ }
118
+
119
+ /** a live db's own side files and the locks of a folder named whole: never part of it */
120
+ const WHOLE_DENY = /^(?:\.DS_Store)$|\.(?:pid|lock)$|-(?:wal|shm|journal)$/
121
+
122
+ /** every source the backup holds now, under the home folder, sorted by path */
123
+ export async function collect(o: Collect): Promise<Source[]> {
124
+ const files: string[] = []
125
+ const add = (abs: string): void => void files.push(abs)
126
+ // the backup's own objects and records, and the pids, move by themselves: left out, else every run differs
127
+ const sqlite = new Map<string, SqliteCut>([
128
+ [mediaDbPath(), { tables: ['files', 'objects'], except: { objects: "key like 'backup/%'" } }],
129
+ [machineDbPath(), { tables: null, except: { state: "name like 'pid:%' or name like 'backup-%'" } }],
130
+ ])
131
+ await walk(join(homeDir(), 'veille'), () => true, files)
132
+ add(join(o.home, ORDER_FILE))
133
+ await walk(join(o.home, MACHINE_PRIVATE), () => true, files)
134
+ for (const root of await agentRoots(o.home)) for (const repo of o.repos) await walk(join(root, sessionName(repo), 'memory'), () => true, files)
135
+ // the git walks of ignored trees take seconds each: all at once
136
+ const locals = new Map(await Promise.all(o.repos.map(async (r) => [r, await (o.locals ?? localFiles)(r)] as const)))
137
+ const whole = new Set<string>()
138
+ const extra: Source[] = []
139
+ for (const repo of o.repos) {
140
+ let cfg: RepoBackup | null = null
141
+ try {
142
+ cfg = await (o.backupOf ?? backupOfRepo)(repo)
143
+ } catch (e) {
144
+ extra.push({ abs: join(repo, 'repo.config.ts'), rel: relative(o.home, join(repo, 'repo.config.ts')), size: 0, mtime: 0, broken: `its backup key is unread, the config does not load: ${(e as Error).message.split('\n')[0]}` })
145
+ }
146
+ const named = cfg?.paths ?? []
147
+ const tracked = new Set((await git(repo, ['ls-files', '-z', '--', '.shipkit', '.comfy-ts', ...REPO_EXTRA, ...named])).map((n) => join(repo, n)))
148
+ for (const p of named) {
149
+ const abs = join(repo, p)
150
+ const st = await lstat(abs).catch(() => null)
151
+ const got: string[] = []
152
+ if (st?.isFile()) got.push(abs)
153
+ else if (st?.isDirectory()) await walk(abs, (rel, isDir) => (isDir ? !['.git', 'node_modules'].includes(basename(rel)) : !WHOLE_DENY.test(basename(rel))), got)
154
+ else extra.push({ abs, rel: relative(o.home, abs), size: 0, mtime: 0, broken: `the repo's backup.paths names it and it is not on the disk` })
155
+ for (const f of got) if (!tracked.has(f)) {
156
+ files.push(f)
157
+ whole.add(f)
158
+ }
159
+ }
160
+ for (const s of cfg?.sqlite ?? []) {
161
+ const { path, except } = typeof s === 'string' ? { path: s, except: undefined } : s
162
+ const hits = [...new Bun.Glob(path).scanSync({ cwd: repo, dot: true, onlyFiles: true })].filter((n) => !WHOLE_DENY.test(basename(n))).sort()
163
+ if (hits.length === 0) extra.push({ abs: join(repo, path), rel: relative(o.home, join(repo, path)), size: 0, mtime: 0, broken: `the repo's backup.sqlite names it and no file matches` })
164
+ for (const n of hits) sqlite.set(join(repo, n), { tables: null, ...(except ? { except } : {}) })
165
+ }
166
+ const mine: string[] = []
167
+ await walk(join(repo, '.shipkit'), shipkitKeep, mine)
168
+ await walk(join(repo, '.comfy-ts'), (rel, isDir) => (isDir ? COMFY_KEEP.some((k) => k === rel.split(sep)[0]) : comfyKeep(rel)), mine)
169
+ for (const x of REPO_EXTRA) {
170
+ const abs = join(repo, x)
171
+ const st = await lstat(abs).catch(() => null)
172
+ if (st?.isFile()) mine.push(abs)
173
+ else if (st?.isDirectory()) await walk(abs, (rel, isDir) => isDir || !FILE_DENY.test(basename(rel)), mine)
174
+ }
175
+ mine.push(...(locals.get(repo) ?? []))
176
+ for (const f of mine) if (!tracked.has(f)) files.push(f)
177
+ }
178
+ const out = new Map<string, Source>()
179
+ for (const abs of [...files, ...sqlite.keys()]) {
180
+ if (out.has(abs)) continue
181
+ const st = await lstat(abs).catch(() => null)
182
+ if (!st?.isFile()) continue
183
+ const rel = relative(o.home, abs)
184
+ if (rel.startsWith('..') || rel === '') continue
185
+ const cut = sqlite.get(abs)
186
+ out.set(abs, { abs, rel, size: st.size, mtime: Math.floor(st.mtimeMs), ...(cut !== undefined ? { sqlite: cut } : whole.has(abs) ? { whole: true as const } : {}) })
187
+ }
188
+ for (const x of extra) out.set(`extra\0${x.rel}`, x)
189
+ return [...out.values()].sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0))
190
+ }
191
+
192
+ /** a cheap stamp of the sources that are files (a sqlite moves every few seconds; its snapshot runs on the clock) */
193
+ export const stampOfSources = (list: readonly Source[]): string => {
194
+ const h = new Bun.CryptoHasher('sha256')
195
+ for (const s of list) if (!s.sqlite) h.update(`${s.rel}\0${s.size}\0${s.mtime}\0${s.broken ?? ''}\n`)
196
+ return h.digest('hex')
197
+ }
198
+
199
+ export const extOf = (rel: string): string => extname(rel).toLowerCase()
@@ -17,6 +17,16 @@ const TYPES: Record<string, string> = {
17
17
  '.ogg': 'audio/ogg',
18
18
  '.opus': 'audio/opus',
19
19
  '.m4a': 'audio/mp4',
20
+ '.gif': 'image/gif',
21
+ '.pdf': 'application/pdf',
22
+ '.zip': 'application/zip',
23
+ '.gz': 'application/gzip',
24
+ '.tar': 'application/x-tar',
25
+ '.dmg': 'application/x-apple-diskimage',
26
+ '.json': 'application/json',
27
+ '.txt': 'text/plain; charset=utf-8',
28
+ '.md': 'text/markdown; charset=utf-8',
29
+ '.csv': 'text/csv; charset=utf-8',
20
30
  }
21
31
 
22
32
  export const typeOf = (name: string): string => TYPES[extname(name).toLowerCase()] ?? 'application/octet-stream'
@@ -48,4 +58,4 @@ export async function factsOf(folder: string, names: readonly string[], keep: Re
48
58
  export const mediaKey = (kind: string, f: Pick<MediaFact, 'sha'>, name: string): string => `${kind}/${f.sha}${extname(name).toLowerCase()}`
49
59
 
50
60
  /** the sha a key names, null when it is no content key */
51
- export const shaOfKey = (key: string): string | null => /^[a-z][a-z0-9-]*\/([0-9a-f]{64})\./.exec(key)?.[1] ?? null
61
+ export const shaOfKey = (key: string): string | null => /^[a-z0-9-]+\/([0-9a-f]{64})(?:\.|$)/.exec(key)?.[1] ?? null
@@ -1,6 +1,7 @@
1
- // the daemon's media loop (wiki build/shipkit/media-store.md, The daemon): every kind of every house repo scanned into
2
- // the machine index once its store moved, what waits sent up, and (when the owner turned it on) the disk purged under
3
- // 40 GB free. Each failure is one line in the daemon's log
1
+ // the daemon's media job (wiki build/shipkit/media-store.md, The daemon): one pass, in a child process the daemon
2
+ // starts every 30 s (home/daemon-jobs.ts), never on its loop. Every kind of every house repo scanned into the machine
3
+ // index once its store moved, what waits sent up, and (when the owner turned it on) the disk purged under 40 GB free.
4
+ // Each failure is one line in the daemon's log
4
5
  import { existsSync } from 'node:fs'
5
6
  import { machineGet, machineSet } from '../core/machine-db.ts'
6
7
  import type { MediaKind } from './kind.ts'
@@ -9,7 +10,7 @@ import { machineSpace } from './space.ts'
9
10
  import { syncKind } from './sync.ts'
10
11
  import { mb, uploadWaiting } from './upload.ts'
11
12
 
12
- const TICK_MS = 30_000
13
+ export const MEDIA_EVERY_MS = 30_000
13
14
  const PURGE_EVERY_MS = 10 * 60_000
14
15
  const AUTO_KEY = 'media-purge-auto'
15
16
 
@@ -17,75 +18,60 @@ const AUTO_KEY = 'media-purge-auto'
17
18
  export const autoPurgeOn = (): boolean => machineGet<boolean>(AUTO_KEY) === true
18
19
  export const setAutoPurge = (on: boolean): boolean => machineSet(AUTO_KEY, on)
19
20
 
20
- export interface MediaLoop {
21
- stop(): void
22
- /** one pass now, for a test */
23
- once(): Promise<void>
24
- }
21
+ /** each store's stamp at its last full scan, and the last purge: kept between two child runs */
22
+ const SYNCED = 'media-synced'
23
+ const PURGED_AT = 'media-purged-at'
24
+ const NO_SPACE = 'media-no-space'
25
25
 
26
- export function startMediaStore(o: { roots: () => string[]; kinds: readonly MediaKind[]; print: (l: string) => void; printErr: (l: string) => void; tickMs?: number }): MediaLoop {
27
- const synced = new Map<string, string>()
28
- let busy = false
29
- let lastPurge = 0
30
- let toldNoSpace = false
31
- const stores = (): { kind: MediaKind; root: string; dir: string }[] =>
32
- o.roots().flatMap((root) =>
33
- o.kinds.flatMap((kind) => {
34
- const dir = kind.storeOf(root)
35
- return dir && existsSync(dir) ? [{ kind, root, dir }] : []
36
- }),
37
- )
38
- const once = async (): Promise<void> => {
39
- if (busy) return
40
- busy = true
41
- try {
42
- for (const { kind, root, dir } of stores()) {
43
- const id = `${kind.kind}\0${dir}`
44
- try {
45
- const stamp = kind.stamp(dir)
46
- if (synced.get(id) === stamp) continue
47
- const r = await syncKind(kind, dir, { fill: 50 })
48
- // files left to hash: the next tick goes on with them
49
- synced.set(id, r.left > 0 ? '' : stamp)
50
- if (r.filled > 0) o.print(`ok: media store: ${r.filled} ${kind.kind} files of ${root} hashed${r.left > 0 ? `, ${r.left} to go` : ''}`)
51
- } catch (e) {
52
- o.printErr(`WARN media store: the ${kind.kind} files of ${root} did not sync: ${(e as Error).message}`)
53
- }
54
- }
55
- const { space, why } = await machineSpace()
56
- if (!space) {
57
- if (!toldNoSpace) o.printErr(`WARN media store: nothing goes up: ${why}`)
58
- toldNoSpace = true
59
- return
26
+ /** one pass of the daemon's media job, in its child process: what `startMediaStore` does each tick, with what it
27
+ * remembers in the machine db */
28
+ export async function mediaTick(o: { roots: string[]; kinds: () => readonly MediaKind[]; print: (l: string) => void; printErr: (l: string) => void }): Promise<void> {
29
+ const synced = machineGet<Record<string, string>>(SYNCED) ?? {}
30
+ const stores = o.roots.flatMap((root) =>
31
+ o.kinds().flatMap((kind) => {
32
+ const dir = kind.storeOf(root)
33
+ return dir && existsSync(dir) ? [{ kind, root, dir }] : []
34
+ }),
35
+ )
36
+ try {
37
+ let moved = false
38
+ for (const { kind, root, dir } of stores) {
39
+ const id = `${kind.kind}\0${dir}`
40
+ try {
41
+ const stamp = kind.stamp(dir)
42
+ if (synced[id] === stamp) continue
43
+ const r = await syncKind(kind, dir, { fill: 50 })
44
+ // files left to hash: the next pass goes on with them
45
+ synced[id] = r.left > 0 ? '' : stamp
46
+ moved = true
47
+ if (r.filled > 0) o.print(`ok: media store: ${r.filled} ${kind.kind} files of ${root} hashed${r.left > 0 ? `, ${r.left} to go` : ''}`)
48
+ } catch (e) {
49
+ o.printErr(`WARN media store: the ${kind.kind} files of ${root} did not sync: ${(e as Error).message}`)
60
50
  }
61
- const up = await uploadWaiting(space, { limit: 200, jobs: 3 })
62
- if (up.up + up.there > 0) o.print(`ok: media store: ${up.up} up (${mb(up.bytes)})${up.there > 0 ? `, ${up.there} already there` : ''}`)
63
- if (up.failed.length > 0) o.printErr(`WARN media store: ${up.failed.length} uploads failed, tried again later; first: ${up.failed[0]?.key}: ${up.failed[0]?.error}`)
64
- if (autoPurgeOn() && Date.now() - lastPurge > PURGE_EVERY_MS) {
65
- lastPurge = Date.now()
66
- for (const { kind, root, dir } of stores()) {
67
- if (freeBytes(dir) >= FREE_MIN_BYTES) continue
68
- const { candidates } = await purgeCandidates(kind, dir)
69
- const r = await purge(kind, dir, space, candidates, { enough: () => freeBytes(dir) >= FREE_MIN_BYTES })
70
- if (r.files > 0) o.print(`ok: media store: the disk under ${mb(FREE_MIN_BYTES)} free, ${r.files} ${kind.kind} files of ${root} purged (${mb(r.freed)})`)
71
- if (r.refused.length > 0) o.printErr(`WARN media store: ${r.refused.length} ${kind.kind} files of ${root} kept: ${r.refused[0]?.key}: ${r.refused[0]?.why}`)
72
- }
51
+ }
52
+ if (moved) machineSet(SYNCED, synced)
53
+ const { space, why } = await machineSpace()
54
+ // said once per reason, not once per pass: a pass is a child of its own
55
+ if (!space) {
56
+ if (machineGet<string>(NO_SPACE) !== why) o.printErr(`WARN media store: nothing goes up: ${why}`)
57
+ machineSet(NO_SPACE, why)
58
+ return
59
+ }
60
+ machineSet(NO_SPACE, '')
61
+ const up = await uploadWaiting(space, { limit: 200, jobs: 3 })
62
+ if (up.up + up.there > 0) o.print(`ok: media store: ${up.up} up (${mb(up.bytes)})${up.there > 0 ? `, ${up.there} already there` : ''}`)
63
+ if (up.failed.length > 0) o.printErr(`WARN media store: ${up.failed.length} uploads failed, tried again later; first: ${up.failed[0]?.key}: ${up.failed[0]?.error}`)
64
+ if (autoPurgeOn() && Date.now() - (machineGet<number>(PURGED_AT) ?? 0) > PURGE_EVERY_MS) {
65
+ machineSet(PURGED_AT, Date.now())
66
+ for (const { kind, root, dir } of stores) {
67
+ if (freeBytes(dir) >= FREE_MIN_BYTES) continue
68
+ const { candidates } = await purgeCandidates(kind, dir)
69
+ const r = await purge(kind, dir, space, candidates, { enough: () => freeBytes(dir) >= FREE_MIN_BYTES })
70
+ if (r.files > 0) o.print(`ok: media store: the disk under ${mb(FREE_MIN_BYTES)} free, ${r.files} ${kind.kind} files of ${root} purged (${mb(r.freed)})`)
71
+ if (r.refused.length > 0) o.printErr(`WARN media store: ${r.refused.length} ${kind.kind} files of ${root} kept: ${r.refused[0]?.key}: ${r.refused[0]?.why}`)
73
72
  }
74
- } catch (e) {
75
- o.printErr(`WARN media store: the pass broke: ${(e as Error).message}`)
76
- } finally {
77
- busy = false
78
73
  }
79
- }
80
- const every = setInterval(() => void once(), o.tickMs ?? TICK_MS)
81
- every.unref()
82
- const boot = setTimeout(() => void once(), 15_000)
83
- boot.unref()
84
- return {
85
- stop: () => {
86
- clearInterval(every)
87
- clearTimeout(boot)
88
- },
89
- once,
74
+ } catch (e) {
75
+ o.printErr(`WARN media store: the pass broke: ${(e as Error).message}`)
90
76
  }
91
77
  }
@@ -0,0 +1,58 @@
1
+ // the generic kind (wiki build/shipkit/media-store.md, Put a file from any repo): a label no `MediaKind` of the code
2
+ // owns, its files named by hand through `sk media put`. The index is its only record, so its scan reads the index's
3
+ // own rows back and asks the disk whether each file still holds the bytes of its key; nothing else names them
4
+ import { statSync } from 'node:fs'
5
+ import { join, resolve } from 'node:path'
6
+ import { shaOf, shaOfKey, typeOf } from './content.ts'
7
+ import { mediaDb } from './db.ts'
8
+ import type { MediaKind, MediaRow } from './kind.ts'
9
+
10
+ /** a label `sk media put` takes: the key prefix in the Space */
11
+ export const LABEL = /^[a-z0-9-]+$/
12
+ export const DEFAULT_LABEL = 'files'
13
+
14
+ /** the stores the index holds rows of under this label */
15
+ function storesOf(label: string): string[] {
16
+ const db = mediaDb()
17
+ if (!db) return []
18
+ const p = `${label}/`
19
+ return (db.query('select distinct store from files where substr(key, 1, ?) = ?').all(p.length, p) as { store: string }[]).map((r) => r.store)
20
+ }
21
+
22
+ /** every label the index holds rows of */
23
+ export function labelsInIndex(): string[] {
24
+ const db = mediaDb()
25
+ if (!db) return []
26
+ return (db.query(`select distinct substr(key, 1, instr(key, '/') - 1) as label from files`).all() as { label: string }[]).map((r) => r.label).filter((l) => LABEL.test(l))
27
+ }
28
+
29
+ const rowsOf = (label: string, store: string): { item: string; name: string; key: string; size: number }[] => {
30
+ const p = `${label}/`
31
+ return (mediaDb()?.query('select item, name, key, size from files where store = ? and substr(key, 1, ?) = ?').all(store, p.length, p) ?? []) as { item: string; name: string; key: string; size: number }[]
32
+ }
33
+
34
+ export function handKind(label: string): MediaKind {
35
+ return {
36
+ kind: label,
37
+ storeOf: (root) => (storesOf(label).includes(resolve(root)) ? resolve(root) : null),
38
+ // the index is the record: read it again every 10 min, to see a file the disk let go
39
+ stamp: () => String(Math.floor(Date.now() / 600_000)),
40
+ async scan(store) {
41
+ const rows: MediaRow[] = []
42
+ for (const r of rowsOf(label, store)) {
43
+ const sha = shaOfKey(r.key)
44
+ if (!sha) continue
45
+ const size = statSync(join(store, r.item, r.name), { throwIfNoEntry: false })?.size
46
+ rows.push({ item: r.item, name: r.name, fact: { sha, size: r.size, type: typeOf(r.name) }, local: size === r.size })
47
+ }
48
+ return { rows, filled: 0, left: 0 }
49
+ },
50
+ async holds(store) {
51
+ return (row) => ({ pinned: false, used: statSync(join(store, row.item, row.name), { throwIfNoEntry: false })?.mtimeMs })
52
+ },
53
+ async beforePurge(store, _space, row) {
54
+ const sha = await shaOf(join(store, row.item, row.name))
55
+ if (sha !== shaOfKey(row.key)) throw new Error(`${join(row.item, row.name)} changed since it was put: its bytes hash to ${sha.slice(0, 12)}, the key says ${row.key}`)
56
+ },
57
+ }
58
+ }
@@ -0,0 +1,122 @@
1
+ // a file put in the store by hand, and a fresh link to anything it holds (wiki build/shipkit/media-store.md, Put a file
2
+ // from any repo): the one way a repo's agent keeps a file in the private Space. The index row is written before the
3
+ // upload, so a failed upload waits for the daemon like any other; a link lasts at most 7 days, the object for good
4
+ import { realpathSync, statSync } from 'node:fs'
5
+ import { basename, dirname, join, relative } from 'node:path'
6
+ import { findRepoRoot } from '../ts/config.ts'
7
+ import { factOf, mediaKey, shaOf, shaOfKey, typeOf } from './content.ts'
8
+ import { mediaDb } from './db.ts'
9
+ import { DEFAULT_LABEL, LABEL } from './hand.ts'
10
+ import { confirmedUp } from './remote.ts'
11
+ import { machineSpace, SIGNED_MAX_S } from './space.ts'
12
+ import { uploadOne } from './upload.ts'
13
+
14
+ /** a duration as seconds: `90s`, `30m`, `2h`, `7d`, or a bare number of seconds; never over 7 days */
15
+ export function durationS(text: string): number {
16
+ const m = /^(\d+(?:\.\d+)?)([smhd]?)$/.exec(text.trim())
17
+ if (!m) throw new Error(`${text}: a duration is a number and a unit, like 30m, 2h or 7d`)
18
+ const s = Math.round(Number(m[1]) * { '': 1, s: 1, m: 60, h: 3600, d: 86_400 }[m[2] as '' | 's' | 'm' | 'h' | 'd'])
19
+ if (s < 1) throw new Error(`${text}: a link lasts at least 1 s`)
20
+ if (s > SIGNED_MAX_S) throw new Error(`${text}: a signed link lasts at most 7d (the SigV4 limit); the object never expires, sk media link makes a new one`)
21
+ return s
22
+ }
23
+
24
+ export interface Put {
25
+ key: string
26
+ sha: string
27
+ size: number
28
+ /** the file's own name, the one a link downloads under */
29
+ name: string
30
+ /** false: the Space already held this content */
31
+ sent: boolean
32
+ }
33
+
34
+ export interface Link {
35
+ key: string
36
+ sha: string
37
+ size: number
38
+ name: string
39
+ url: string
40
+ /** ISO time */
41
+ expires: string
42
+ }
43
+
44
+ /** the labels a kind of the code owns: their rows come from their own scan, never a hand put. `backup` too: a hand
45
+ * row under it would make its file a purge candidate, and a backup never frees the live file */
46
+ async function codeLabels(): Promise<Set<string>> {
47
+ const { MEDIA_KINDS } = await import('../media-kinds.ts')
48
+ const { BACKUP_LABEL } = await import('./backup/keys.ts')
49
+ return new Set([...MEDIA_KINDS.map((k) => k.kind), BACKUP_LABEL])
50
+ }
51
+
52
+ /** where the index keeps a file: its repo (else its folder) as the store, the folder in it, its name */
53
+ function placeOf(file: string): { store: string; item: string; name: string } {
54
+ const real = realpathSync(file)
55
+ const store = findRepoRoot(dirname(real))
56
+ return { store, item: relative(store, dirname(real)), name: basename(real) }
57
+ }
58
+
59
+ /** the file kept by its content under the label: its index row first, then up at once, checked by a HEAD */
60
+ export async function putMedia(file: string, o: { kind?: string } = {}): Promise<Put> {
61
+ const label = o.kind ?? DEFAULT_LABEL
62
+ if (!LABEL.test(label)) throw new Error(`--kind ${label}: a label is lowercase letters, digits and dashes`)
63
+ if ((await codeLabels()).has(label)) throw new Error(`--kind ${label}: that kind's files come from its own scan, never a hand put; pick another label`)
64
+ const st = statSync(file, { throwIfNoEntry: false })
65
+ if (!st?.isFile()) throw new Error(`${file}: no such file`)
66
+ const at = placeOf(file)
67
+ const path = join(at.store, at.item, at.name)
68
+ const fact = await factOf(path)
69
+ const key = mediaKey(label, fact, at.name)
70
+ const db = mediaDb()
71
+ if (!db) throw new Error('the media index does not open: nothing is put without its record')
72
+ db.transaction(() => {
73
+ db.query('insert or replace into files (store, item, name, key, size, local, purged) values (?, ?, ?, ?, ?, 1, null)').run(at.store, at.item, at.name, key, fact.size)
74
+ db.query('insert or ignore into objects (key, size) values (?, ?)').run(key, fact.size)
75
+ })()
76
+ const { space, why } = await machineSpace()
77
+ if (!space) throw new Error(`${key} recorded, not up: ${why}; the daemon sends it once the Space answers`)
78
+ const sent = await uploadOne(space, { key, size: fact.size, path })
79
+ return { key, sha: fact.sha, size: fact.size, name: at.name, sent }
80
+ }
81
+
82
+ /** the key a reference names: a key, a sha (or 12 hex of one), or a file the store holds */
83
+ async function keyOf(ref: string): Promise<{ key: string; size: number; name: string | null }> {
84
+ const db = mediaDb()
85
+ if (!db) throw new Error('the media index does not open')
86
+ const sizeOf = (key: string): number | null => (db.query('select size from objects where key = ?').get(key) as { size: number } | null)?.size ?? null
87
+ const nameOf = (key: string): string | null => (db.query('select name from files where key = ? order by name limit 1').get(key) as { name: string } | null)?.name ?? null
88
+ if (shaOfKey(ref)) {
89
+ const size = sizeOf(ref)
90
+ if (size === null) throw new Error(`${ref}: the index holds no such key`)
91
+ return { key: ref, size, name: nameOf(ref) }
92
+ }
93
+ const asFile = statSync(ref, { throwIfNoEntry: false })?.isFile()
94
+ if (!asFile && /^[0-9a-f]{12,64}$/.test(ref)) {
95
+ const keys = (db.query(`select key, size from objects where substr(key, instr(key, '/') + 1, ?) = ?`).all(ref.length, ref) as { key: string; size: number }[]).filter((r) => shaOfKey(r.key)?.startsWith(ref))
96
+ if (keys.length === 0) throw new Error(`${ref}: no object of the index has that sha`)
97
+ if (keys.length > 1) throw new Error(`${ref}: ${keys.length} objects match (${keys.map((k) => k.key).join(', ')}); name the key`)
98
+ const k = keys[0]!
99
+ return { key: k.key, size: k.size, name: nameOf(k.key) }
100
+ }
101
+ if (!asFile) throw new Error(`${ref}: neither a key, a sha, nor a file`)
102
+ const at = placeOf(ref)
103
+ const row = db.query('select key, size from files where store = ? and item = ? and name = ?').get(at.store, at.item, at.name) as { key: string; size: number } | null
104
+ const sha = await shaOf(join(at.store, at.item, at.name))
105
+ if (row && shaOfKey(row.key) === sha) return { key: row.key, size: row.size, name: at.name }
106
+ const same = db.query(`select key, size from objects where instr(key, ?) > 0`).all(`/${sha}`) as { key: string; size: number }[]
107
+ if (same.length === 0) throw new Error(`${ref}: not in the store; sk media put ${ref} first`)
108
+ if (same.length > 1) throw new Error(`${ref}: its content is kept under ${same.map((k) => k.key).join(', ')}; name the key`)
109
+ return { key: same[0]!.key, size: same[0]!.size, name: at.name }
110
+ }
111
+
112
+ /** a fresh signed link to what the Space holds, downloading under the index's name (or `name`) */
113
+ export async function linkMedia(ref: string, o: { seconds: number; name?: string; now?: number }): Promise<Link> {
114
+ if (o.seconds > SIGNED_MAX_S) throw new Error(`a signed link lasts at most 7d (the SigV4 limit); the object never expires, sk media link makes a new one`)
115
+ const k = await keyOf(ref)
116
+ const { space, why } = await machineSpace()
117
+ if (!space) throw new Error(why)
118
+ if (!(await confirmedUp(k.key, k.size))) throw new Error(`${k.key}: not in the Space yet (sk media upload sends what waits)`)
119
+ const name = o.name ?? k.name ?? basename(k.key)
120
+ const url = space.signed(k.key, o.seconds, { name, type: typeOf(name) })
121
+ return { key: k.key, sha: shaOfKey(k.key) ?? '', size: k.size, name, url, expires: new Date((o.now ?? Date.now()) + o.seconds * 1000).toISOString() }
122
+ }