rvlib-shipkit 2.12.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 (290) hide show
  1. package/CHANGELOG.md +48 -13
  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 +7 -5
  20. package/src/cli/cmd_Review.ts +4 -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 +5 -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 +53 -4
  68. package/src/home/inbox.ts +16 -1
  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 +104 -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 +2 -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/daemon.ts +56 -70
  100. package/src/media-store/put.ts +4 -2
  101. package/src/media-store/space.ts +23 -4
  102. package/src/pages/forward.ts +35 -0
  103. package/src/pages/frame-client.ts +118 -0
  104. package/src/pages/routes.ts +29 -0
  105. package/src/pages/unit.ts +92 -0
  106. package/src/plan/planner.ts +12 -0
  107. package/src/plan/repo-source.ts +19 -5
  108. package/src/reflect/transcript.ts +35 -10
  109. package/src/release/public-clean.ts +301 -0
  110. package/src/release/published-here.ts +22 -0
  111. package/src/release/run-bump.ts +2 -1
  112. package/src/release/run-release.ts +4 -1
  113. package/src/repo-config.ts +53 -2
  114. package/src/review/http.ts +16 -2
  115. package/src/review/model.ts +15 -4
  116. package/src/review/notes.ts +77 -0
  117. package/src/review/project.ts +6 -38
  118. package/src/review/routes.ts +4 -12
  119. package/src/review/store.ts +41 -1
  120. package/src/review/trailer-media.ts +7 -4
  121. package/src/review/trailer-shots.ts +21 -4
  122. package/src/review/unit.ts +1 -1
  123. package/src/scaffold/files/agent-handoff.md +3 -0
  124. package/src/scaffold/files/agent-index.md +4 -12
  125. package/src/scaffold/project-scaffold.ts +5 -4
  126. package/src/serve/embed.ts +1 -1
  127. package/src/serve/hub-app/col-card.tsx +3 -17
  128. package/src/serve/hub-app/col-tables-view.tsx +2 -1
  129. package/src/serve/hub-app/cols-svc.ts +0 -13
  130. package/src/serve/hub-app/dock-st.ts +4 -2
  131. package/src/serve/hub-app/dock-view.tsx +2 -0
  132. package/src/serve/hub-app/frames-st.ts +35 -0
  133. package/src/serve/hub-app/hash-route.ts +64 -1
  134. package/src/serve/hub-app/home-st.ts +31 -7
  135. package/src/serve/hub-app/home-strip.css +9 -1
  136. package/src/serve/hub-app/home-strip.tsx +7 -6
  137. package/src/serve/hub-app/home.html +5 -0
  138. package/src/serve/hub-app/hub-app.tsx +49 -5
  139. package/src/serve/hub-app/hub.css +29 -11
  140. package/src/serve/hub-app/icons.tsx +16 -1
  141. package/src/serve/hub-app/identities-st.ts +210 -0
  142. package/src/serve/hub-app/identities-view.tsx +352 -0
  143. package/src/serve/hub-app/identities.css +48 -0
  144. package/src/serve/hub-app/identity-address.ts +52 -0
  145. package/src/serve/hub-app/inbox-st.ts +59 -6
  146. package/src/serve/hub-app/inbox-view.tsx +48 -6
  147. package/src/serve/hub-app/inbox.css +12 -1
  148. package/src/serve/hub-app/index.html +3 -0
  149. package/src/serve/hub-app/keys.ts +10 -2
  150. package/src/serve/hub-app/list-walk.ts +89 -0
  151. package/src/serve/hub-app/machine-st.ts +12 -0
  152. package/src/serve/hub-app/media-view.tsx +2 -1
  153. package/src/serve/hub-app/pages-frames.tsx +134 -0
  154. package/src/serve/hub-app/pages-svc.ts +111 -0
  155. package/src/serve/hub-app/palette-st.ts +18 -3
  156. package/src/serve/hub-app/palette-view.tsx +9 -2
  157. package/src/serve/hub-app/planned-view.tsx +2 -1
  158. package/src/serve/hub-app/project-list.css +18 -14
  159. package/src/serve/hub-app/project-list.tsx +88 -49
  160. package/src/serve/hub-app/projects-svc.ts +33 -3
  161. package/src/serve/hub-app/repo-sections.ts +19 -2
  162. package/src/serve/hub-app/repo-st.ts +75 -19
  163. package/src/serve/hub-app/review/review-cells.tsx +3 -3
  164. package/src/serve/hub-app/review/review-kit.ts +30 -7
  165. package/src/serve/hub-app/review/review-page.tsx +1 -1
  166. package/src/serve/hub-app/review/review-st.ts +19 -8
  167. package/src/serve/hub-app/review/review-thread.tsx +11 -9
  168. package/src/serve/hub-app/review/review-views.tsx +84 -19
  169. package/src/serve/hub-app/review/thread-st.ts +1 -10
  170. package/src/serve/hub-app/review/trailer-page.tsx +2 -1
  171. package/src/serve/hub-app/review.css +17 -8
  172. package/src/serve/hub-app/site/site-part.tsx +173 -0
  173. package/src/serve/hub-app/site/site-st.ts +157 -0
  174. package/src/serve/hub-app/site.css +35 -0
  175. package/src/serve/hub-app/social/calendar.tsx +182 -0
  176. package/src/serve/hub-app/social/comms-page.tsx +306 -0
  177. package/src/serve/hub-app/social/kit.tsx +244 -0
  178. package/src/serve/hub-app/social/post-card.tsx +456 -0
  179. package/src/serve/hub-app/social/problems.tsx +60 -0
  180. package/src/serve/hub-app/social/social-model.ts +154 -0
  181. package/src/serve/hub-app/social/social-page.tsx +674 -0
  182. package/src/serve/hub-app/social/social-st.ts +986 -0
  183. package/src/serve/hub-app/social.css +289 -0
  184. package/src/serve/hub-app/stores/stores-page.tsx +311 -0
  185. package/src/serve/hub-app/stores/stores-st.ts +286 -0
  186. package/src/serve/hub-app/stores.css +54 -0
  187. package/src/serve/hub-app/timeline-geometry.ts +1 -1
  188. package/src/serve/hub-app/timeline-view.tsx +3 -2
  189. package/src/serve/hub-app/tree-build.ts +6 -0
  190. package/src/serve/hub-app/tree-row.tsx +27 -4
  191. package/src/serve/hub-app/tree-svc.ts +18 -49
  192. package/src/serve/hub-app/veille/veille-page.tsx +514 -0
  193. package/src/serve/hub-app/veille/veille-st.ts +443 -0
  194. package/src/serve/hub-app/veille.css +84 -0
  195. package/src/serve/hub-runtime.ts +14 -9
  196. package/src/serve/project-gutter-route.ts +44 -12
  197. package/src/serve/run-lanes.ts +7 -4
  198. package/src/serve/same-origin.ts +1 -1
  199. package/src/serve/serve-hub.ts +20 -12
  200. package/src/serve/tracked-watch.ts +24 -3
  201. package/src/serve/warm-cell.ts +5 -1
  202. package/src/shipkit-files.ts +15 -4
  203. package/src/shipkit.ts +0 -1
  204. package/src/shot/box.ts +162 -0
  205. package/src/shot/browser-slot.ts +62 -0
  206. package/src/shot/client.ts +43 -7
  207. package/src/shot/clip-encoder.ts +93 -12
  208. package/src/shot/film-box.ts +188 -0
  209. package/src/shot/shooter.ts +50 -15
  210. package/src/shot/shot-ask.ts +10 -2
  211. package/src/shot/stepped-clip.ts +5 -4
  212. package/src/site/desk.ts +242 -0
  213. package/src/site/routes.ts +66 -0
  214. package/src/site/unit.ts +62 -0
  215. package/src/social/brands.ts +22 -0
  216. package/src/social/compose.ts +97 -0
  217. package/src/social/desk-index.ts +123 -0
  218. package/src/social/desk-wire.ts +64 -0
  219. package/src/social/drafts.ts +183 -0
  220. package/src/social/house.ts +24 -0
  221. package/src/social/load.ts +319 -0
  222. package/src/social/md.ts +70 -0
  223. package/src/social/media-facts.ts +53 -0
  224. package/src/social/media-kind.ts +189 -0
  225. package/src/social/media-limit.ts +42 -0
  226. package/src/social/media-of.ts +30 -0
  227. package/src/social/migrate.ts +123 -0
  228. package/src/social/open.ts +17 -0
  229. package/src/social/post-url.ts +158 -0
  230. package/src/social/presence.ts +332 -0
  231. package/src/social/public-read.ts +53 -0
  232. package/src/social/publish/bluesky.ts +168 -0
  233. package/src/social/publish/discord.ts +76 -0
  234. package/src/social/publish/index.ts +24 -0
  235. package/src/social/publish/secret.ts +13 -0
  236. package/src/social/push.ts +31 -0
  237. package/src/social/richtext.ts +37 -0
  238. package/src/social/routes.ts +180 -0
  239. package/src/social/stats.ts +134 -0
  240. package/src/social/text.ts +267 -0
  241. package/src/social/tracker-route.ts +39 -0
  242. package/src/social/tracker.ts +255 -0
  243. package/src/social/unit.ts +53 -0
  244. package/src/social/writes.ts +130 -0
  245. package/src/start-repo.ts +14 -9
  246. package/src/stores/collection.ts +27 -0
  247. package/src/stores/desk.ts +336 -0
  248. package/src/stores/model.ts +187 -0
  249. package/src/stores/routes.ts +126 -0
  250. package/src/stores/unit.ts +57 -0
  251. package/src/suite/calibrate.ts +127 -0
  252. package/src/suite/core-counters.ts +91 -0
  253. package/src/suite/judge-suites.ts +94 -34
  254. package/src/suite/suite-cli.ts +44 -10
  255. package/src/suite/suite-cpu-preload.ts +34 -9
  256. package/src/trailer/adapter.ts +4 -0
  257. package/src/trailer/build.ts +42 -11
  258. package/src/trailer/ffmpeg.ts +11 -0
  259. package/src/trailer/footage.ts +30 -13
  260. package/src/trailer/grammar.ts +18 -2
  261. package/src/trailer/graph.ts +28 -6
  262. package/src/trailer/passage.ts +17 -5
  263. package/src/trailer/plan.ts +74 -3
  264. package/src/trailer/stitch.ts +67 -26
  265. package/src/trailer/url.ts +1 -1
  266. package/src/trailer/versions.ts +24 -0
  267. package/src/ts/gate-typecheck.ts +32 -0
  268. package/src/ts/typecheck-cli.ts +9 -11
  269. package/src/tui/tui-app.tsx +0 -1
  270. package/src/veille/asks.ts +155 -0
  271. package/src/veille/auto.ts +31 -0
  272. package/src/veille/batch.ts +27 -0
  273. package/src/veille/chrome.ts +127 -0
  274. package/src/veille/collection.ts +28 -0
  275. package/src/veille/desk.ts +242 -0
  276. package/src/veille/identity.ts +80 -0
  277. package/src/veille/import.ts +68 -0
  278. package/src/veille/log.ts +183 -0
  279. package/src/veille/platforms.ts +118 -0
  280. package/src/veille/reads.ts +66 -0
  281. package/src/veille/replied.ts +110 -0
  282. package/src/veille/routes.ts +185 -0
  283. package/src/veille/service.ts +81 -0
  284. package/src/veille/watch.ts +116 -0
  285. package/src/veille/worth.ts +46 -0
  286. package/src/wiki/scan-md.ts +18 -0
  287. package/src/collections/posts.ts +0 -142
  288. package/src/contracts/manifests/social.contract.ts +0 -20
  289. package/src/scaffold/files/agent-coding.md +0 -35
  290. package/src/ts/typecheck-cache.ts +0 -11
@@ -8,7 +8,7 @@ import type { TrailerFilmLine, TrailerUnit } from './adapter.ts'
8
8
  import { scratchObjects } from '../core/scratch-objects.ts'
9
9
  import { duration } from './ffmpeg.ts'
10
10
  import type { Shot, Trailer } from './grammar.ts'
11
- import { cliArgv, isTake, recipeText, recipeWords, runCommand, type Stamp, specOf, type Take, type TakeFilm, type TakeSpec, takeIsStill, takeName, takeSeconds } from './plan.ts'
11
+ import { cliArgv, isTake, recipeText, recipeWords, runCommand, type Stamp, specOf, type Take, type TakeFilm, type TakeSpec, takeIsStill, takeName, takeSeconds, entryPath, treeEntry, worldOfEntries, type WorldState } from './plan.ts'
12
12
  import { statesOf } from './states.ts'
13
13
 
14
14
  export const trailerCache = (root: string, part: 'footage' | 'pieces' | 'titles' | 'sound' | 'score'): string => join(root, '.shipkit', 'cache', 'trailer', part)
@@ -68,18 +68,35 @@ const git = (root: string, args: string[], env?: Record<string, string>): string
68
68
  return r.exitCode === 0 ? r.stdout.toString() : null
69
69
  }
70
70
 
71
+ /** git's entries as lines, the last newline dropped */
72
+ const linesOf = (out: string): string[] => (out === '' ? [] : out.replace(/\n$/, '').split('\n'))
73
+
74
+ /** the folders a world of the whole repo leaves out: the cuts themselves and the house's caches */
75
+ const OUTSIDE = ['trailer', '.shipkit']
76
+
71
77
  /**
72
- * the world the takes show: every file of the repo as it stands, by its content (`trailer/` and `.shipkit/` left out),
73
- * or only the `paths` the trailer unit's `stamp` names; a repo with no git: `no-git`. Content addressed: the working
74
- * tree is staged into a throwaway copy of the index and the staged entries hashed, so the same content dirty or
75
- * committed is one world, and an edit of the cut alone moves nothing. The blobs the add hashes go to a throwaway
76
- * object dir too (core/scratch-objects.ts), never into the repo's store
78
+ * the world the takes show: every file of the repo by its content (`trailer/` and `.shipkit/` left out), or only the
79
+ * `paths` the trailer unit's `stamp` names; a repo with no git: `no-git`. Content addressed, one hash per part
80
+ * (plan.ts worldOfEntries). With no `ref`: the working tree as it stands, staged into a throwaway copy of the index, so
81
+ * the same content dirty or committed is one world and an edit of the cut alone moves nothing; the blobs the add
82
+ * hashes go to a throwaway object dir (core/scratch-objects.ts), never into the repo's store. With a `ref`: that
83
+ * commit's tree, for a page served from a commit, so an uncommitted edit moves nothing
77
84
  */
78
- export function worldStamp(root: string, paths?: readonly string[]): string {
85
+ export function worldStamp(root: string, paths?: readonly string[], ref?: string): WorldState {
79
86
  const real = git(root, ['rev-parse', '--git-path', 'index'])
80
- if (real === null) return 'no-git'
81
- const spec = paths ? ['--', ...paths] : ['--', '.', ':(exclude)trailer', ':(exclude).shipkit']
87
+ if (real === null) return { id: 'no-git', parts: {} }
82
88
  if (paths) for (const p of paths) if (!existsSync(join(root, p))) throw new Error(`the trailer unit's stamp names a path the repo does not hold: ${p}`)
89
+ if (ref !== undefined) {
90
+ // relative to the root, as ls-files is: a root below the git top level reads the same tree in both modes
91
+ const tree = git(root, ['ls-tree', '-r', ref, ...(paths ? ['--', ...paths] : [])])
92
+ if (tree === null) throw new Error(`the trailer unit's ref names no commit: ${ref}`)
93
+ const lines = linesOf(tree).map(treeEntry)
94
+ const w = worldOfEntries(paths ? lines : lines.filter((l) => !OUTSIDE.includes(entryPath(l).split('/')[0]!)), paths ?? null)
95
+ const empty = (paths ?? []).filter((p) => w.parts[p] === undefined)
96
+ if (empty.length > 0 || lines.length === 0) throw new Error(`the trailer unit's ref ${ref} holds nothing at ${empty.length > 0 ? empty.join(', ') : 'the repo root'}: a take's world would never move`)
97
+ return w
98
+ }
99
+ const spec = paths ? ['--', ...paths] : ['--', '.', ...OUTSIDE.map((p) => `:(exclude)${p}`)]
83
100
  const index = join(tmpdir(), `sk-world-${process.pid}-${Math.random().toString(36).slice(2)}`)
84
101
  const objects = scratchObjects(root, tmpdir())
85
102
  try {
@@ -90,7 +107,7 @@ export function worldStamp(root: string, paths?: readonly string[]): string {
90
107
  if (git(root, ['add', '-A', ...spec], env) === null) throw new Error('git add into the world\'s throwaway index failed')
91
108
  const staged = git(root, ['ls-files', '-s', ...spec], env)
92
109
  if (staged === null) throw new Error('git ls-files of the world\'s throwaway index failed')
93
- return new Bun.CryptoHasher('sha1').update(staged).digest('hex').slice(0, 12)
110
+ return worldOfEntries(linesOf(staged), paths ?? null)
94
111
  } finally {
95
112
  rmSync(index, { force: true })
96
113
  objects.drop()
@@ -100,7 +117,7 @@ export function worldStamp(root: string, paths?: readonly string[]): string {
100
117
  export interface FilmContext {
101
118
  root: string
102
119
  t: Pick<Trailer, 'size' | 'fps' | 'base'>
103
- world: string
120
+ world: WorldState
104
121
  /** the project CLI's argv, null when the repo has none */
105
122
  cli: readonly string[] | null
106
123
  /** a clip take that drops its picture is filmed again once, then refused (the unit's `holes`) */
@@ -134,12 +151,12 @@ export async function filmTake(tk: Take, c: FilmContext): Promise<Take> {
134
151
  const states = statesOf(said)
135
152
  const first = (said.split('\n')[0] ?? '').replace(/\s·\sstates \S+/, '').replace(part, '').trim()
136
153
  const stamp: Stamp = {
137
- world: tk.spec.world ?? c.world,
154
+ world: tk.spec.world ?? c.world.id,
138
155
  filmedAt: new Date().toISOString(),
139
156
  seconds: still ? 0 : duration(tk.file),
140
157
  note: first.slice(0, 200),
141
158
  ...(states ? { states } : {}),
142
- ...(tk.spec.world ? { fixed: true as const } : {}),
159
+ ...(tk.spec.world ? { fixed: true as const } : { parts: c.world.parts }),
143
160
  }
144
161
  writeFileSync(`${tk.file}.json`, JSON.stringify(stamp, null, 2))
145
162
  c.say(` filmed ${tk.shot.name}: ${still ? 'a still' : `${stamp.seconds.toFixed(2)} s`} in ${((performance.now() - t0) / 1000).toFixed(1)} s`)
@@ -378,6 +378,9 @@ export const SCORE_LEAD = 0.05
378
378
  /** the score in the cut's music cues */
379
379
  export const SCORE = '@score'
380
380
 
381
+ /** the loudness a `master` line may ask, LUFS: a whisper's floor to a club's ceiling, the -1 dBTP limiter between */
382
+ export const MASTER_RANGE = [-30, -8] as const
383
+
381
384
  export interface Trailer {
382
385
  name: string
383
386
  /** `footage` blocks: filmed like shots, never cut in; a grid or a split reads them */
@@ -389,6 +392,8 @@ export interface Trailer {
389
392
  duck: number
390
393
  /** dB the music drops under each sfx, negative; null: none */
391
394
  duckSfx: number | null
395
+ /** the integrated loudness the mix is brought to, LUFS (`master -14 LUFS`); null: each sound at its own volume */
396
+ master: number | null
392
397
  fadeIn: number
393
398
  shots: Shot[]
394
399
  sections: Section[]
@@ -1053,7 +1058,7 @@ export function parseTrailer(text: string, o: ParseOptions = {}): { trailer: Tra
1053
1058
  const verbs = o.verbs ?? null
1054
1059
  const variants = variantsOf(text)
1055
1060
  const variant = o.variant ?? variants[0] ?? null
1056
- const t: Trailer = { name: '', footage: [], size: [1920, 1080], fps: 30, music: null, duck: -10, duckSfx: null, fadeIn: 0, shots: [], sections: [], score: null, timelineAt: null, vertical: null, base: null, variants, variant }
1061
+ const t: Trailer = { name: '', footage: [], size: [1920, 1080], fps: 30, music: null, duck: -10, duckSfx: null, master: null, fadeIn: 0, shots: [], sections: [], score: null, timelineAt: null, vertical: null, base: null, variants, variant }
1057
1062
  /** a music line of another variant plays elsewhere; one of this variant takes the place of the line with none */
1058
1063
  const mine = (m: Music, had: Music | null, what: string): boolean => {
1059
1064
  if (m.variant !== undefined && m.variant !== variant) return false
@@ -1242,6 +1247,17 @@ export function parseTrailer(text: string, o: ParseOptions = {}): { trailer: Tra
1242
1247
  }
1243
1248
  break
1244
1249
  }
1250
+ case 'master': {
1251
+ once('master')
1252
+ const [v, unit, ...more] = rest
1253
+ const m = v && !v.quoted ? /^(-?\d+(?:\.\d+)?)(LUFS)?$/.exec(v.text) : null
1254
+ const lufs = Number(m?.[1])
1255
+ const said = m?.[2] ? unit === undefined : unit?.text === 'LUFS' && !unit.quoted && more.length === 0
1256
+ if (!m || !said || lufs < MASTER_RANGE[0] || lufs > MASTER_RANGE[1])
1257
+ bad(`master wants the cut's loudness from ${MASTER_RANGE[0]} to ${MASTER_RANGE[1]} LUFS (master -14 LUFS)${rest.length ? `, got ${rest.map((w) => w.text).join(' ')}` : ''}`)
1258
+ t.master = lufs
1259
+ break
1260
+ }
1245
1261
  case 'fade-in':
1246
1262
  once('fade-in')
1247
1263
  t.fadeIn = time('fade-in', rest[0])
@@ -1313,7 +1329,7 @@ export function parseTrailer(text: string, o: ParseOptions = {}): { trailer: Tra
1313
1329
  break
1314
1330
  }
1315
1331
  default:
1316
- bad(`unknown word ${head.text} before the first shot (trailer, size, fps, music, duck, fade-in, vertical, base, preset, score, track, drums, section, defaults, shot)`)
1332
+ bad(`unknown word ${head.text} before the first shot (trailer, size, fps, music, duck, master, fade-in, vertical, base, preset, score, track, drums, section, defaults, shot)`)
1317
1333
  }
1318
1334
  continue
1319
1335
  }
@@ -290,7 +290,6 @@ export function pieceArgs(a: Pick<StitchInput, 't' | 'sources' | 'titles' | 'loo
290
290
  const [W, H] = t.size
291
291
  const fps = t.fps
292
292
  const T = total(t)
293
- const st = starts(t)
294
293
  const spans = frameSpans(t)
295
294
  // the graph starts at the piece's first frame: the shot before a section draws only what its cut overlaps
296
295
  const base = p.from
@@ -514,10 +513,32 @@ const LIMIT_MARGIN_DB = 0.5
514
513
  /** the limiter runs 4 times oversampled, so it sees the peaks between samples a player's converter makes */
515
514
  const OVERSAMPLE = 4
516
515
 
516
+ /** a mix's two gains, dB: `gain` on the sum before the limiter (toward the cut's `master`), `trim` after it, never
517
+ * above 0 (for an aac encode that still overshoots) */
518
+ export interface MixLevel {
519
+ gain: number
520
+ trim: number
521
+ }
522
+
523
+ /** how close a mix lands to its `master`, LU */
524
+ export const MASTER_TOLERANCE = 0.3
525
+
526
+ /** the level of the mix's next pass, from what the last one measured; null: it holds. Over the ceiling, the trim drops
527
+ * by the overshoot; off its master, the gain moves by the gap, the limiter taking the peaks it raises */
528
+ export function nextMixLevel(master: number | null, m: { lufs: number; truePeak: number }, level: MixLevel): MixLevel | null {
529
+ const over = m.truePeak - MIX_TRUE_PEAK
530
+ const gap = master === null ? 0 : master - m.lufs
531
+ if (over <= 0 && Math.abs(gap) <= MASTER_TOLERANCE) return null
532
+ return {
533
+ gain: Math.abs(gap) > MASTER_TOLERANCE ? +(level.gain + gap).toFixed(2) : level.gain,
534
+ trim: over > 0 ? +(level.trim - over - 0.1).toFixed(2) : level.trim,
535
+ }
536
+ }
537
+
517
538
  /** the ffmpeg arguments that mix the cut's sound: the music trimmed, faded and ducked under each voice line, the sfx
518
- * and the voices on their times, the sum through a true peak limiter held under MIX_TRUE_PEAK. `trimDb` lowers the
519
- * limited sum before the encode, for a mix whose aac encode still overshoots (stitch.ts) */
520
- export function mixArgs(a: Pick<StitchInput, 't' | 'music' | 'sfx' | 'voices'>, out: string, trimDb = 0): string[] {
539
+ * and the voices on their times, the sum raised or lowered by `level.gain`, then through a true peak limiter held
540
+ * under MIX_TRUE_PEAK, then lowered by `level.trim` before the encode (stitch.ts renderMix finds both) */
541
+ export function mixArgs(a: Pick<StitchInput, 't' | 'music' | 'sfx' | 'voices'>, out: string, level: MixLevel = { gain: 0, trim: 0 }): string[] {
521
542
  const { t } = a
522
543
  const T = total(t)
523
544
  const st = starts(t)
@@ -576,7 +597,8 @@ export function mixArgs(a: Pick<StitchInput, 't' | 'music' | 'sfx' | 'voices'>,
576
597
  mix.push(`[${silence}:a]`)
577
598
  // level=disabled: alimiter's default auto level lifts the output back to 0 dBFS, past the limit
578
599
  const limit = n3(10 ** ((MIX_TRUE_PEAK - LIMIT_MARGIN_DB) / 20))
579
- const limiter = `aresample=${48000 * OVERSAMPLE},alimiter=limit=${limit}:attack=1:release=60:level=disabled,aresample=48000${trimDb < 0 ? `,volume=${n3(trimDb)}dB` : ''}`
580
- graph.push(`${mix.join('')}amix=inputs=${mix.length}:normalize=0:duration=longest,atrim=duration=${n3(T)},${limiter}[aout]`)
600
+ const gain = level.gain !== 0 ? `volume=${n3(level.gain)}dB,` : ''
601
+ const limiter = `aresample=${48000 * OVERSAMPLE},alimiter=limit=${limit}:attack=1:release=60:level=disabled,aresample=48000${level.trim < 0 ? `,volume=${n3(level.trim)}dB` : ''}`
602
+ graph.push(`${mix.join('')}amix=inputs=${mix.length}:normalize=0:duration=longest,atrim=duration=${n3(T)},${gain}${limiter}[aout]`)
581
603
  return ['-hide_banner', '-loglevel', 'error', '-y', ...inputs, '-filter_complex', graph.join(';\n'), '-map', '[aout]', '-c:a', 'aac', '-b:a', '192k', '-t', n3(T), out]
582
604
  }
@@ -6,6 +6,7 @@ import { type Loaded, load, Refused, type Say, takesOfLoaded } from './build.ts'
6
6
  import { ffmpeg } from './ffmpeg.ts'
7
7
  import { starts, type Trailer } from './grammar.ts'
8
8
  import { shotFacts } from './shelf.ts'
9
+ import { cutStem, versionName } from './versions.ts'
9
10
 
10
11
  const outOf = (l: Pick<Loaded, 'dir'>): string => join(l.dir, 'out')
11
12
 
@@ -61,8 +62,18 @@ export function versionVideo(dir: string, v: string): string | null {
61
62
  return f ? join(d, f) : null
62
63
  }
63
64
 
65
+ /** the version a cut names for what was typed (versions.ts): its own `v<n>` or `<stem>-v<n>`, a refusal otherwise */
66
+ const ownVersion = (l: Pick<Loaded, 'file'>, typed: string): string => {
67
+ try {
68
+ return versionName(cutStem(l.file), typed)
69
+ } catch (e) {
70
+ throw new Refused((e as Error).message)
71
+ }
72
+ }
73
+
64
74
  /** a version's cut text read as today's tool reads it, with the cut's own recipes, and its video */
65
- async function versionCut(l: Loaded, v: string, cwd: string): Promise<{ t: Trailer; video: string }> {
75
+ async function versionCut(l: Loaded, typed: string, cwd: string): Promise<{ t: Trailer; video: string }> {
76
+ const v = ownVersion(l, typed)
66
77
  const text = join(l.dir, 'versions', `${v}.trailer`)
67
78
  if (!existsSync(text)) throw new Refused(`no ${relative(cwd, text)}`)
68
79
  const kept = await load(text, l.root, { dir: l.dir, check: false })
@@ -87,13 +98,14 @@ export async function clip(l: Loaded, from: string, to: string, pad: number, ver
87
98
  await cut(l.t, builtOf(l, cwd), join(outOf(l), `clip-${tag}.mp4`))
88
99
  if (version) {
89
100
  const v = await versionCut(l, version, cwd)
90
- await cut(v.t, v.video, join(outOf(l), `clip-${tag}-${version}.mp4`))
101
+ await cut(v.t, v.video, join(outOf(l), `clip-${tag}-${ownVersion(l, version)}.mp4`))
91
102
  }
92
103
  }
93
104
 
94
- /** keep the built cut as a version: its text, its video, its strip and each shot's take, cloned so they cost nothing */
95
- export function keep(l: Loaded, v: string, say: Say, cwd: string): void {
96
- if (!/^v\d+$/.test(v)) throw new Refused(`keep: a version is v<n>, not ${v}`)
105
+ /** keep the built cut as a version: its text, its video, its strip and each shot's take, cloned so they cost nothing.
106
+ * main.trailer keeps `v<n>`, another cut `<stem>-v<n>` (versions.ts) */
107
+ export function keep(l: Loaded, typed: string, say: Say, cwd: string): void {
108
+ const v = ownVersion(l, typed)
97
109
  const text = join(l.dir, 'versions', `${v}.trailer`)
98
110
  const dir = join(l.dir, 'versions', v)
99
111
  if (existsSync(text) || existsSync(dir)) throw new Refused(`${v} is kept already: versions are never overwritten`)
@@ -97,9 +97,72 @@ export interface Stamp {
97
97
  states?: string
98
98
  /** its world was fixed by its spec (a film of a past commit): never stale */
99
99
  fixed?: true
100
+ /** each part of its world by its hash (worldOfEntries), so a stale take says which part moved */
101
+ parts?: Record<string, string>
100
102
  }
101
103
 
102
- export const fresh = (stamp: Stamp, world: string): boolean => stamp.fixed === true || stamp.world === world
104
+ /** the world the takes show: its id, and one hash per part (each stamp path, else each top level entry) */
105
+ export interface WorldState {
106
+ id: string
107
+ parts: Record<string, string>
108
+ }
109
+
110
+ const sha12 = (s: string): string => new Bun.CryptoHasher('sha1').update(s).digest('hex').slice(0, 12)
111
+
112
+ const ESCAPES: Record<string, number> = { a: 7, b: 8, t: 9, n: 10, v: 11, f: 12, r: 13, '"': 34, '\\': 92 }
113
+
114
+ /** an entry's path as the repo names it: git prints an odd name (non ASCII, a quote, a backslash) C quoted, its bytes
115
+ * in octal (`"src/\303\251.ts"`) */
116
+ export function entryPath(l: string): string {
117
+ const q = l.slice(l.indexOf('\t') + 1)
118
+ if (!q.startsWith('"') || !q.endsWith('"')) return q
119
+ const bytes: number[] = []
120
+ const s = q.slice(1, -1)
121
+ for (let i = 0; i < s.length; i++) {
122
+ if (s[i] !== '\\') {
123
+ bytes.push(...new TextEncoder().encode(s[i]!))
124
+ continue
125
+ }
126
+ const oct = /^[0-7]{3}/.exec(s.slice(i + 1))
127
+ if (oct) {
128
+ bytes.push(parseInt(oct[0], 8))
129
+ i += 3
130
+ } else bytes.push(ESCAPES[s[++i]!] ?? s.charCodeAt(i))
131
+ }
132
+ return new TextDecoder().decode(new Uint8Array(bytes))
133
+ }
134
+
135
+ /** a world from git's entries of the files it holds, `<mode> <sha> <stage>\t<path>` as `ls-files -s` prints them, in
136
+ * git's order: the id hashes them all as printed, each part its own. The working tree's staged entries and a
137
+ * commit's tree (ls-tree, made the same shape) give one world for one content */
138
+ export function worldOfEntries(lines: readonly string[], paths: readonly string[] | null): WorldState {
139
+ const by = new Map<string, string[]>()
140
+ for (const l of lines) {
141
+ const path = entryPath(l)
142
+ const part = paths ? paths.find((p) => path === p || path.startsWith(`${p}/`)) : path.split('/')[0]
143
+ if (part === undefined) continue
144
+ const g = by.get(part)
145
+ if (g) g.push(l)
146
+ else by.set(part, [l])
147
+ }
148
+ return { id: sha12(lines.map((l) => `${l}\n`).join('')), parts: Object.fromEntries([...by].sort(([a], [b]) => (a < b ? -1 : 1)).map(([p, ls]) => [p, sha12(ls.join('\n'))])) }
149
+ }
150
+
151
+ /** a commit's `ls-tree -r` line (`<mode> <type> <sha>\t<path>`) in the shape of a staged entry */
152
+ export const treeEntry = (l: string): string => {
153
+ const tab = l.indexOf('\t')
154
+ const [mode, , sha] = l.slice(0, tab).split(' ')
155
+ return `${mode} ${sha} 0\t${l.slice(tab + 1)}`
156
+ }
157
+
158
+ export const fresh = (stamp: Stamp, world: WorldState): boolean => stamp.fixed === true || stamp.world === world.id
159
+
160
+ /** the parts of the world that moved since the take was filmed, null when its stamp kept none */
161
+ export function movedParts(stamp: Stamp, world: WorldState): string[] | null {
162
+ const was = stamp.parts
163
+ if (was === undefined) return null
164
+ return [...new Set([...Object.keys(was), ...Object.keys(world.parts)])].filter((p) => was[p] !== world.parts[p]).sort()
165
+ }
103
166
 
104
167
  /** a take as a build sees it: its shot, its file, its stamp when it was filmed */
105
168
  export interface Take {
@@ -118,8 +181,8 @@ export type Refilm = 'stale' | ReadonlySet<string> | null
118
181
  /** the takes to film, each group sharing one file and filmed once by its first shot: a missing take, a stale one under
119
182
  * `--refilm`, or one whose shot `--refilm` names */
120
183
  /** the world a take is measured against: one for the cut, or one a take (a row that names its own paths) */
121
- export type World = string | ((tk: Take) => string)
122
- export const worldFor = (w: World, tk: Take): string => (typeof w === 'string' ? w : w(tk))
184
+ export type World = WorldState | ((tk: Take) => WorldState)
185
+ export const worldFor = (w: World, tk: Take): WorldState => (typeof w === 'function' ? w(tk) : w)
123
186
 
124
187
  export function takesToFilm(takes: readonly Take[], world: World, refilm: Refilm, only?: ReadonlySet<string>): Take[][] {
125
188
  const groups = new Map<string, Take[]>()
@@ -154,6 +217,14 @@ export function runCommand(f: Extract<Film, { kind: 'run' }>, o: { out: string;
154
217
  .replaceAll('{fps}', String(o.fps))
155
218
  }
156
219
 
220
+ /** another stem holding `key` among a folder's names (`<stem>-<key>.<ext>`): the key is what the render is, the stem
221
+ * only who uses it, so another cut's section or a renamed section is the same render */
222
+ export function twinStem(names: readonly string[], stem: string, key: string, ext: string): string | null {
223
+ const end = `-${key}.${ext}`
224
+ const hit = names.find((n) => n.endsWith(end) && n !== `${stem}${end}`)
225
+ return hit === undefined ? null : hit.slice(0, -end.length)
226
+ }
227
+
157
228
  /** the first frame at or after a time: a shot, a cut or a title starts on it */
158
229
  export const frameAt = (seconds: number, fps: number): number => Math.ceil(seconds * fps - 1e-6) || 0
159
230
 
@@ -1,14 +1,14 @@
1
1
  // the stitch: the cut rendered piece by piece (a piece = a section), each cached on its ffmpeg arguments and the size
2
2
  // and time of every file it reads, so an edit renders only the pieces it touches. The pieces join with no second
3
3
  // encode, the sound is mixed once (cached the same way) and muxed beside them, and the strip lays out each piece's row
4
- import { existsSync, mkdirSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'
4
+ import { constants, copyFileSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'
5
5
  import { availableParallelism } from 'node:os'
6
6
  import { dirname, join } from 'node:path'
7
7
  import sharp from 'sharp'
8
8
  import { ffmpeg, loudnessKept } from './ffmpeg.ts'
9
- import { type Encoder, GRID_RADIUS, gridLayout, MIX_TRUE_PEAK, mixArgs, pieceArgs, type SplitMasks, splitPane, type StitchInput, THUMB_W } from './graph.ts'
9
+ import { type Encoder, GRID_RADIUS, gridLayout, type MixLevel, mixArgs, nextMixLevel, pieceArgs, type SplitMasks, splitPane, type StitchInput, THUMB_W } from './graph.ts'
10
10
  import type { TrailerLook } from './look.ts'
11
- import { type Piece, pieces } from './plan.ts'
11
+ import { type Piece, pieces, twinStem } from './plan.ts'
12
12
 
13
13
  /** bump when the stitch changes what the same arguments make */
14
14
  const STITCH_VERSION = 1
@@ -26,21 +26,52 @@ function keyOf(args: string[]): string {
26
26
  return new Bun.CryptoHasher('sha1').update(JSON.stringify([STITCH_VERSION, args, reads])).digest('hex').slice(0, 16)
27
27
  }
28
28
 
29
+ /** a render as the cache answers it: its files, its key, made by this run, or cloned from the stem that held its key */
30
+ export interface Render {
31
+ files: string[]
32
+ key: string
33
+ made: boolean
34
+ twin?: string
35
+ }
36
+
29
37
  /** a render kept under its key, one file per extension (the first always made, the others when the render has them):
30
38
  * made only when missing, written aside then moved in place, the first last */
31
- async function cached(dir: string, stem: string, exts: string[], make: (outs: string[]) => string[]): Promise<{ files: string[]; made: boolean }> {
39
+ async function cached(dir: string, stem: string, exts: string[], make: (outs: string[]) => string[]): Promise<Render> {
32
40
  return cachedAs(dir, stem, keyOf(make(exts.map((e) => `out.${e}`))), exts, make)
33
41
  }
34
42
 
43
+ /** a twin's files cloned under `stem`: each aside then moved in place, its first extension last, so a file there means
44
+ * the whole render is; false when a prune took the twin meanwhile (a sidecar cloned before it is the same key's) */
45
+ function cloneTwin(dir: string, names: readonly string[], twin: string, stem: string, key: string, first: string, now: Date): boolean {
46
+ const head = `${twin}-${key}.${first}`
47
+ const own = names.filter((n) => n.startsWith(`${twin}-${key}.`) && !/\.part(\.|$)/.test(n) && n !== head)
48
+ for (const n of [...own, head]) {
49
+ const to = join(dir, `${stem}${n.slice(twin.length)}`)
50
+ const part = `${to}.${process.pid}-${Math.random().toString(36).slice(2, 8)}.part`
51
+ try {
52
+ copyFileSync(join(dir, n), part, constants.COPYFILE_FICLONE)
53
+ } catch (e) {
54
+ if ((e as NodeJS.ErrnoException).code === 'ENOENT') return false
55
+ throw e
56
+ }
57
+ utimesSync(part, now, now)
58
+ renameSync(part, to)
59
+ }
60
+ return true
61
+ }
62
+
35
63
  /** a render kept under a key its caller computed: for one whose inputs are rewritten by every build */
36
- export async function cachedAs(dir: string, stem: string, key: string, exts: string[], make: (outs: string[]) => string[]): Promise<{ files: string[]; made: boolean }> {
64
+ export async function cachedAs(dir: string, stem: string, key: string, exts: string[], make: (outs: string[]) => string[]): Promise<Render> {
37
65
  const files = exts.map((e) => join(dir, `${stem}-${key}.${e}`))
66
+ const now = new Date()
38
67
  if (existsSync(files[0]!)) {
39
- const now = new Date()
40
68
  for (const f of files) if (existsSync(f)) utimesSync(f, now, now)
41
- return { files, made: false }
69
+ return { files, key, made: false }
42
70
  }
43
71
  mkdirSync(dir, { recursive: true })
72
+ const names = readdirSync(dir)
73
+ const twin = twinStem(names, stem, key, exts[0]!)
74
+ if (twin !== null && cloneTwin(dir, names, twin, stem, key, exts[0]!, now)) return { files, key, made: false, twin }
44
75
  const parts = exts.map((e) => join(dir, `${stem}-${key}.part.${e}`))
45
76
  try {
46
77
  await ffmpeg(make(parts), { nice: 10 })
@@ -48,7 +79,7 @@ export async function cachedAs(dir: string, stem: string, key: string, exts: str
48
79
  } finally {
49
80
  for (const f of parts) rmSync(f, { force: true })
50
81
  }
51
- return { files, made: true }
82
+ return { files, key, made: true }
52
83
  }
53
84
 
54
85
  const n3 = (x: number): string => (+x.toFixed(4)).toString()
@@ -130,14 +161,20 @@ export async function pool<T>(jobs: (() => Promise<T>)[], n: number): Promise<T[
130
161
  const LANES = Math.max(1, Math.min(4, Math.floor(availableParallelism() / 2)))
131
162
 
132
163
  export interface Stitched {
133
- /** the pieces, each with whether this run rendered it, its video and its row of the contact strip */
134
- pieces: (Piece & { made: boolean; file: string; thumbs: string })[]
164
+ /** the pieces, each with whether this run rendered it, the render it was cloned from, its key, its video and its row of
165
+ * the contact strip */
166
+ pieces: (Piece & Pick<Render, 'made' | 'twin' | 'key'> & { file: string; thumbs: string })[]
135
167
  /** the sound was mixed again */
136
168
  mixed: boolean
137
- /** the mix file, null for a silent stitch */
169
+ /** the mix file and its key, null for a silent stitch */
138
170
  mix: string | null
171
+ mixKey: string | null
172
+ /** the cut the mix was cloned from */
173
+ mixFrom?: string
139
174
  }
140
175
 
176
+ const mixOf = (m: Awaited<ReturnType<typeof renderMix>> | null): Omit<Stitched, 'pieces'> => ({ mixed: m?.made ?? false, mix: m?.file ?? null, mixKey: m?.key ?? null, ...(m?.twin !== undefined ? { mixFrom: m.twin } : {}) })
177
+
141
178
  export interface StitchRun extends StitchInput {
142
179
  out: string
143
180
  /** where the rendered pieces and the mix are kept */
@@ -150,24 +187,26 @@ export interface StitchRun extends StitchInput {
150
187
  async function renderPieces(a: StitchRun, ps: Piece[]): Promise<Stitched['pieces']> {
151
188
  return pool(
152
189
  ps.map((p) => async () => {
153
- const { files, made } = await cached(a.cache, `${a.t.name}-${p.name}`, ['mp4', 'png'], ([video, row]) => pieceArgs(a, p, video!, a.encoder, row))
154
- return { ...p, made, file: files[0]!, thumbs: files[1]! }
190
+ const { files, made, twin, key } = await cached(a.cache, `${a.t.name}-${p.name}`, ['mp4', 'png'], ([video, row]) => pieceArgs(a, p, video!, a.encoder, row))
191
+ return { ...p, made, key, ...(twin !== undefined ? { twin } : {}), file: files[0]!, thumbs: files[1]! }
155
192
  }),
156
193
  LANES,
157
194
  )
158
195
  }
159
196
 
160
- /** the mix, its true peak held under MIX_TRUE_PEAK after the aac encode: the encoder's band limit rings over a limited
161
- * harsh sound (a square wave measured +2.1 dB), so a mix that overshoots is made again that much lower */
162
- export async function renderMix(a: Pick<StitchRun, 't' | 'music' | 'sfx' | 'voices' | 'cache'>): Promise<{ file: string; made: boolean }> {
163
- let trim = 0
197
+ /** the mix, its true peak held under MIX_TRUE_PEAK after the aac encode (the encoder's band limit rings over a limited
198
+ * harsh sound: a square wave measured +2.1 dB), and with a `master` its integrated loudness on it: each pass measured
199
+ * as ebur128 hears it, then made again at the level nextMixLevel says, every pass kept in the cache */
200
+ export async function renderMix(a: Pick<StitchRun, 't' | 'music' | 'sfx' | 'voices' | 'cache'>): Promise<{ file: string; key: string; made: boolean; twin?: string }> {
201
+ const passes = a.t.master === null ? 3 : 6
202
+ let level: MixLevel = { gain: 0, trim: 0 }
164
203
  let made = false
165
- for (let pass = 0; ; pass++) {
166
- const r = await cached(join(a.cache, 'mix'), `mix-${a.t.name}`, ['m4a'], ([out]) => mixArgs(a, out!, trim))
204
+ for (let pass = 1; ; pass++) {
205
+ const r = await cached(join(a.cache, 'mix'), `mix-${a.t.name}`, ['m4a'], ([out]) => mixArgs(a, out!, level))
167
206
  made ||= r.made
168
- const { truePeak } = await loudnessKept(r.files[0]!)
169
- if (truePeak <= MIX_TRUE_PEAK || pass === 2) return { file: r.files[0]!, made }
170
- trim = +(trim - (truePeak - MIX_TRUE_PEAK) - 0.1).toFixed(2)
207
+ const next = nextMixLevel(a.t.master, await loudnessKept(r.files[0]!), level)
208
+ if (next === null || pass === passes) return { file: r.files[0]!, key: r.key, made, ...(r.twin !== undefined && !made ? { twin: r.twin } : {}) }
209
+ level = next
171
210
  }
172
211
  }
173
212
 
@@ -193,7 +232,7 @@ async function joinPieces(files: string[], sound: { file: string; start?: number
193
232
  export async function stitch(a: StitchRun): Promise<Stitched> {
194
233
  const [ps, mix] = await Promise.all([renderPieces(a, pieces(a.t)), a.silent ? null : renderMix(a)])
195
234
  await joinPieces(ps.map((p) => p.file), mix ? { file: mix.file } : null, a.out)
196
- return { pieces: ps, mixed: mix?.made ?? false, mix: mix?.file ?? null }
235
+ return { pieces: ps, ...mixOf(mix) }
197
236
  }
198
237
 
199
238
  /** one piece alone (a section, `start` the shots before the first), with its window of the sound */
@@ -202,7 +241,7 @@ export async function stitchPiece(a: StitchRun, name: string): Promise<Stitched>
202
241
  if (!p) throw new Error(`no section ${name}: ${pieces(a.t).map((x) => x.name).join(', ')}`)
203
242
  const [ps, mix] = await Promise.all([renderPieces(a, [p]), a.silent ? null : renderMix(a)])
204
243
  await joinPieces(ps.map((x) => x.file), mix && { file: mix.file, start: p.from / a.t.fps, seconds: (p.to - p.from) / a.t.fps }, a.out)
205
- return { pieces: ps, mixed: mix?.made ?? false, mix: mix?.file ?? null }
244
+ return { pieces: ps, ...mixOf(mix) }
206
245
  }
207
246
 
208
247
  /** one frame from the middle of each shot, side by side, rows of six: the cut at a glance. Each piece drew its own
@@ -228,6 +267,8 @@ export async function strip(ps: Pick<Stitched['pieces'][number], 'thumbs'>[], ou
228
267
  export function rendered(d: Stitched): string {
229
268
  const made = d.pieces.filter((p) => p.made).map((p) => p.name)
230
269
  const all = d.pieces.length
231
- const sound = d.mixed ? ', the sound mixed' : ''
232
- return made.length === 0 ? `every section cached${sound}` : made.length === all ? `${all} section(s) rendered${sound}` : `rendered ${made.join(', ')}, ${all - made.length} of ${all} sections cached${sound}`
270
+ const sound = d.mixed ? ', the sound mixed' : d.mixFrom !== undefined ? `, the sound cloned from ${d.mixFrom}` : ''
271
+ const shared = d.pieces.filter((p) => p.twin !== undefined).length
272
+ const cloned = shared > 0 ? ` (${shared} cloned from another cut or section)` : ''
273
+ return made.length === 0 ? `every section cached${cloned}${sound}` : made.length === all ? `${all} section(s) rendered${sound}` : `rendered ${made.join(', ')}, ${all - made.length} of ${all} sections cached${cloned}${sound}`
233
274
  }
@@ -118,6 +118,6 @@ export async function filmUrl(f: UrlFilm, o: UrlTake): Promise<string> {
118
118
  const log = (l: string): void => o.say(` ${l}`)
119
119
  const step = f.kind === 'page' ? { step: f.step } : {}
120
120
  const still = f.kind === 'page' ? { step: f.step, at: f.at ?? 0 } : {}
121
- const r = o.seconds === null ? await shotUrl({ url, out: o.out, viewport, dpr, ...wait, ...still }, log) : await clipUrl({ url, out: o.out, viewport, dpr, seconds: o.seconds, fps: o.fps, ...wait, ...step }, log)
121
+ const r = o.seconds === null ? await shotUrl({ url, out: o.out, viewport, dpr, root: o.root, ...wait, ...still }, log) : await clipUrl({ url, out: o.out, viewport, dpr, root: o.root, seconds: o.seconds, fps: o.fps, ...wait, ...step }, log)
122
122
  return `${url} at ${viewport.width}x${viewport.height}@${dpr}, ${r.via}, ${r.ms} ms${r.note ? `: ${r.note}` : ''}`
123
123
  }
@@ -0,0 +1,24 @@
1
+ // the names of a cut's kept versions (wiki build/trailer.md, Versions): main.trailer keeps `v<n>`, any other cut of the
2
+ // folder `<stem>-v<n>`, so two cuts of one picture keep in one versions/ and never take each other's numbers
3
+ import { basename } from 'node:path'
4
+
5
+ const MAIN = 'main'
6
+ const STEM_RE = /^[a-z0-9][a-z0-9-]*$/
7
+
8
+ /** the stem of a cut's file: `main` for main.trailer */
9
+ export const cutStem = (file: string): string => basename(file, '.trailer')
10
+
11
+ /** the version a cut keeps or reads for what was typed: `v<n>`, or a non main cut's own `<stem>-v<n>`; never a bare
12
+ * `v<n>` for a non main cut, never another cut's name */
13
+ export function versionName(stem: string, typed: string): string {
14
+ if (!STEM_RE.test(stem)) throw new Error(`a cut keeps versions when its file is named in lowercase letters, digits and dashes, not ${stem}.trailer`)
15
+ if (/^v\d+$/.test(typed)) return stem === MAIN ? typed : `${stem}-${typed}`
16
+ if (stem !== MAIN && typed.startsWith(`${stem}-`) && /^v\d+$/.test(typed.slice(stem.length + 1))) return typed
17
+ throw new Error(`a version of ${stem}.trailer is v<n>${stem === MAIN ? '' : `, kept as ${stem}-v<n>`}, not ${typed}`)
18
+ }
19
+
20
+ /** a kept version's name read back: the stem of its cut and its number; null for a name no keep writes */
21
+ export function versionOf(name: string): { cut: string; n: number } | null {
22
+ const m = /^(?:([a-z0-9][a-z0-9-]*)-)?v(\d+)$/.exec(name)
23
+ return m ? { cut: m[1] ?? MAIN, n: Number(m[2]) } : null
24
+ }
@@ -0,0 +1,32 @@
1
+ // the one command the gate types a project with: `bun check`, bun's built-in
2
+ // checker (tsc's diagnostics, one `file(l,c): error TSnnnn: msg` line each,
3
+ // every core). What each flag buys:
4
+ // -b follows `references` like tsc -b, so a solution style config
5
+ // checks its leaves; a config that compiles nothing (TS18002,
6
+ // TS18003) or a reference that is gone (TS6053) exits 1, never
7
+ // a vacuous green
8
+ // --no-script else a package.json `check` script runs in its place
9
+ // --all every error printed, none grouped
10
+ // --no-pretty one line per error, whatever the terminal
11
+ // it keeps no build info, so no answer comes from an earlier run's state
12
+ // (TypeScript 7.0.2's own build info answered green over a red tree), and the
13
+ // ledger keeps a green by content key.
14
+ //
15
+ // a bun with no `bun check` (core/bun-builtins.ts says which) makes the gate
16
+ // run tsc cold, project by project (ts/typecheck-cli.ts), and say so on every
17
+ // run. That fallback dies once every machine and CI runner that gates a house
18
+ // repo has bun 1.4.4.
19
+ import { BUN_TOOLS_SINCE } from '../core/bun-builtins.ts'
20
+
21
+ /** the gate's typecheck over one tsconfig and every project it references */
22
+ export const gateCheckCmd = (tsconfig: string, bun: string = process.execPath): string[] => [bun, 'check', '--no-pretty', '--no-script', '--all', '-b', '-p', tsconfig]
23
+
24
+ /** the note the gate prints while the tsc fallback runs */
25
+ export const tscFallbackNote = (version: string = Bun.version): string =>
26
+ `skip: bun check (bun ${version} has none, it ships in ${BUN_TOOLS_SINCE}): typecheck runs tsc cold, project by project; \`bun upgrade --canary\` brings it`
27
+
28
+ // the fallback's command. `--composite false`: a composite config refuses `--incremental false`
29
+ export const GATE_TSC_FLAGS: readonly string[] = ['--incremental', 'false', '--composite', 'false']
30
+
31
+ /** the cold tsc the fallback runner spawns per project */
32
+ export const gateTscCmd = (tsc: string, tsconfig: string): string[] => [tsc, '--noEmit', '-p', tsconfig, ...GATE_TSC_FLAGS]
@@ -1,16 +1,14 @@
1
1
  #!/usr/bin/env bun
2
- // the typecheck floor for a repo that has no typecheck script, as one small
3
- // binary the gate spawns, for the same reason source-graph-cli.ts exists: a
4
- // tool the gate REQUIRES must not be a published version behind the repo it
5
- // gates.
2
+ // the typecheck fallback of a bun with no `bun check` (ts/gate-typecheck.ts
3
+ // owns when it runs and when it dies): tsc cold over each project a tsconfig
4
+ // reaches, because `tsc --noEmit` over a solution style config compiles zero
5
+ // files and exits 0. A spawned binary, so the tool the gate requires is never
6
+ // a published version behind the repo it gates.
6
7
  //
7
- // One tsc run per project, sequential, output streamed straight through so the
8
- // task log and its last-line summary behave like any other subprocess task. It
9
- // runs EVERY project rather than stopping at the first red, because a caller
10
- // who fixes the one error tsc showed and re-runs into a second one has been
11
- // told the truth twice and believed it once.
8
+ // Sequential, output streamed straight through. It runs EVERY project rather
9
+ // than stopping at the first red, and a pass names what it checked.
12
10
  import { resolveTypecheckProjects } from 'rvlib-shipkit/src/ts/tsconfig-projects.ts'
13
- import { gateBuildInfoArgs } from 'rvlib-shipkit/src/ts/typecheck-cache.ts'
11
+ import { gateTscCmd } from 'rvlib-shipkit/src/ts/gate-typecheck.ts'
14
12
 
15
13
  export function typecheckCli(argv: string[]): number {
16
14
  const [tsc, tsconfig] = argv
@@ -31,7 +29,7 @@ export function typecheckCli(argv: string[]): number {
31
29
 
32
30
  let worst = 0
33
31
  for (const p of resolved.projects) {
34
- const r = Bun.spawnSync([tsc, '--noEmit', '-p', p, ...gateBuildInfoArgs(p)], { stdout: 'inherit', stderr: 'inherit' })
32
+ const r = Bun.spawnSync(gateTscCmd(tsc, p), { stdout: 'inherit', stderr: 'inherit' })
35
33
  if (r.exitCode !== 0) {
36
34
  console.log(`FAIL: ${p}`)
37
35
  worst = r.exitCode ?? 1