rvlib-shipkit 2.20.0 → 2.21.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 (91) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/package.json +1 -1
  3. package/src/checks/SK004-gitignore-policy.check.ts +6 -3
  4. package/src/cli/cmd_GlobalProcesses.ts +2 -107
  5. package/src/cli/cmd_Home.ts +1 -1
  6. package/src/cli/cmd_Overview.ts +2 -1
  7. package/src/cli/cmd_Releases.ts +39 -3
  8. package/src/cli/cmd_Review.ts +22 -13
  9. package/src/cli/cmd_Social.ts +13 -7
  10. package/src/cli/cmd_Sound.ts +17 -4
  11. package/src/cli/cmd_Trailer.ts +67 -1
  12. package/src/cli/registry.ts +2 -1
  13. package/src/collections/collection-types.ts +1 -1
  14. package/src/collections/review.ts +23 -4
  15. package/src/core/layout.ts +6 -0
  16. package/src/home/gui-app/ShipkitGui.swift +35 -0
  17. package/src/home/gui-app.ts +1 -0
  18. package/src/home/pm-switch.ts +112 -0
  19. package/src/identities/identities.ts +11 -6
  20. package/src/messages/brief.ts +3 -3
  21. package/src/messages/score.ts +2 -0
  22. package/src/releases/add.ts +33 -5
  23. package/src/releases/before.ts +31 -0
  24. package/src/releases/from-card.ts +104 -19
  25. package/src/releases/model.ts +73 -13
  26. package/src/releases/pictures.ts +29 -8
  27. package/src/review/http.ts +1 -1
  28. package/src/review/model.ts +12 -2
  29. package/src/review/stage-card.ts +1 -1
  30. package/src/review/store.ts +12 -2
  31. package/src/review/trailer-desk.ts +19 -0
  32. package/src/review/trailer-model.ts +65 -0
  33. package/src/review/trailer-routes.ts +98 -1
  34. package/src/review/trailer-voices.ts +144 -0
  35. package/src/review/watchers.ts +58 -1
  36. package/src/serve/hub-app/benign-errors.ts +22 -0
  37. package/src/serve/hub-app/hash-route.ts +27 -15
  38. package/src/serve/hub-app/home-st.ts +8 -0
  39. package/src/serve/hub-app/hub-app.tsx +2 -0
  40. package/src/serve/hub-app/project-list.css +7 -2
  41. package/src/serve/hub-app/project-list.tsx +9 -0
  42. package/src/serve/hub-app/projects-svc.ts +16 -6
  43. package/src/serve/hub-app/releases/releases-page.tsx +121 -28
  44. package/src/serve/hub-app/releases/releases-st.ts +46 -4
  45. package/src/serve/hub-app/releases.css +30 -3
  46. package/src/serve/hub-app/repo-sections.ts +1 -1
  47. package/src/serve/hub-app/repo-st.ts +15 -10
  48. package/src/serve/hub-app/review/clip-st.ts +3 -1
  49. package/src/serve/hub-app/review/kit.tsx +3 -3
  50. package/src/serve/hub-app/review/trailer-page.tsx +31 -6
  51. package/src/serve/hub-app/review/trailer-st.ts +168 -8
  52. package/src/serve/hub-app/review/trailer-timeline.tsx +36 -4
  53. package/src/serve/hub-app/review/trailer-voices-st.ts +370 -0
  54. package/src/serve/hub-app/review/trailer-voices.tsx +574 -0
  55. package/src/serve/hub-app/review.css +88 -0
  56. package/src/serve/hub-app/social/comms-page.tsx +10 -5
  57. package/src/serve/hub-app/social/next-release.tsx +118 -0
  58. package/src/serve/hub-app/social/social-model.ts +2 -0
  59. package/src/serve/hub-app/social/social-st.ts +38 -1
  60. package/src/serve/hub-app/social.css +8 -0
  61. package/src/serve/hub-app/tree-build.ts +2 -0
  62. package/src/serve/project-gutter-route.ts +8 -0
  63. package/src/serve/project-gutter.ts +4 -2
  64. package/src/shot/box.ts +33 -12
  65. package/src/shot/client.ts +1 -1
  66. package/src/shot/shooter.ts +19 -9
  67. package/src/social/desk-index.ts +49 -8
  68. package/src/social/discord-layout.ts +6 -2
  69. package/src/social/drafts.ts +1 -1
  70. package/src/social/kinds.ts +3 -2
  71. package/src/social/load.ts +26 -7
  72. package/src/social/publish/index.ts +24 -9
  73. package/src/social/release-stage.ts +133 -29
  74. package/src/social/routes.ts +2 -1
  75. package/src/social/stage.ts +39 -20
  76. package/src/trailer/bed.ts +111 -0
  77. package/src/trailer/build.ts +57 -38
  78. package/src/trailer/ffmpeg.ts +6 -0
  79. package/src/trailer/grammar.ts +23 -2
  80. package/src/trailer/graph.ts +12 -1
  81. package/src/trailer/shot-plan.ts +75 -0
  82. package/src/trailer/shot-state.ts +191 -0
  83. package/src/trailer/sound/audio.ts +28 -0
  84. package/src/trailer/sound/brand.ts +53 -3
  85. package/src/trailer/sound/gen.ts +61 -2
  86. package/src/trailer/sound/index.ts +25 -11
  87. package/src/trailer/sound/presets.ts +86 -5
  88. package/src/trailer/sound/run.ts +1 -1
  89. package/src/trailer/sound/takes.ts +94 -0
  90. package/src/trailer/titles.ts +36 -0
  91. package/src/trailer/url.ts +1 -1
@@ -50,16 +50,28 @@ export type StageInput = {
50
50
  tags?: string
51
51
  angle: string
52
52
  /** the headings the text goes under; unset, `short` */
53
- headings?: readonly ReleaseHeading[]
53
+ headings?: readonly StageHeading[]
54
54
  now?: Date
55
55
  }
56
56
 
57
- export type Staged = { slug: string; files: string[]; draft: Draft | null; errors: string[] }
57
+ /** a heading a stage writes: a venue of the unit, and what only this message carries, its own media and rating (a
58
+ * release's nsfw picture on the venue that takes it), its `name` beside another message on the same account */
59
+ export type StageHeading = ReleaseHeading & { name?: string; rating?: PostRating; media?: StageMedia }
60
+
61
+ /** every media a stage copies: the draft's, then each heading's own, once a name */
62
+ export function stageMedia(input: Pick<StageInput, 'media' | 'headings'>): { name: string; file: string }[] {
63
+ const all = [input.media, ...(input.headings ?? []).map((h) => h.media)].filter((m): m is StageMedia => m != null)
64
+ const out = new Map<string, string>()
65
+ for (const m of all) out.set(mediaFile(m), m.file)
66
+ return [...out].map(([name, file]) => ({ name, file }))
67
+ }
68
+
69
+ export type Staged = { slug: string; files: string[]; draft: Draft | null; errors: string[]; /** a dry run's draft.md, as it would be written */ text?: string }
58
70
 
59
71
  const sourceLine = (s: StageSource): string => ('review' in s ? `review: ${s.review}` : `release: ${s.release}`)
60
72
 
61
73
  /** the kind a stage writes: the one asked, else its source's */
62
- const kindOf = (input: Pick<StageInput, 'kind' | 'source'>): string => input.kind?.trim() || sourceKind(input.source)
74
+ export const stagedKind = (input: Pick<StageInput, 'kind' | 'source'>): string => input.kind?.trim() || sourceKind(input.source)
63
75
 
64
76
  /** the name a staged media's copy takes in its draft, `media/<name>[-vertical].<ext>` */
65
77
  export const mediaFile = (m: StageMedia): string => {
@@ -72,7 +84,7 @@ export function draftText(input: StageInput, media: string | null): string {
72
84
  const one = (v: string | undefined): string => (v ?? '').replace(/\s*\n\s*/g, ' ').trim()
73
85
  const head = [
74
86
  `title: ${one(input.title)}`,
75
- `kind: ${kindOf(input)}`,
87
+ `kind: ${stagedKind(input)}`,
76
88
  ...(one(input.kindWhy) ? [`kindWhy: ${one(input.kindWhy)}`] : []),
77
89
  `status: ${input.status ?? 'picked'}`,
78
90
  `rating: ${input.rating}`,
@@ -84,8 +96,14 @@ export function draftText(input: StageInput, media: string | null): string {
84
96
  const text = input.text.trim()
85
97
  if (/^## /m.test(text)) throw new Error('the text holds a "## " line: it would start a heading')
86
98
  const tags = one(input.tags)
87
- const opts = (h: ReleaseHeading, tagged: boolean): string => {
88
- const o = [...(h.place ? [`place: ${h.place}`] : []), ...(tagged && tags ? [`tags: ${tags}`] : [])]
99
+ const opts = (h: StageHeading, tagged: boolean): string => {
100
+ const o = [
101
+ ...(h.name ? [`name: ${h.name}`] : []),
102
+ ...(h.place ? [`place: ${h.place}`] : []),
103
+ ...(h.rating ? [`rating: ${h.rating}`] : []),
104
+ ...(h.media ? [`media: ${mediaFile(h.media)}`] : []),
105
+ ...(tagged && tags ? [`tags: ${tags}`] : []),
106
+ ]
89
107
  return o.length ? ` (${o.join(', ')})` : ''
90
108
  }
91
109
  const headings = input.headings ?? [{ id: 'short' }]
@@ -100,16 +118,16 @@ export const stageSlug = (title: string, now: Date): string => idOf(now, title)
100
118
  /** the guard's problems with what the stage would write, and its kind's: run before any file is. A stage never writes
101
119
  * an old word or a custom with no reason, so every kind problem refuses it */
102
120
  export function guardStage(unit: SocialUnit | null, input: StageInput): string[] {
103
- const kind = kindProblem(kindOf(input), input.kindWhy ?? '', unit?.kinds ?? [])
121
+ const kind = kindProblem(stagedKind(input), input.kindWhy ?? '', unit?.kinds ?? [])
104
122
  return [
105
- ...guardWith(unit, { title: input.title, alt: input.alt ?? '', texts: [input.text, ...(input.tags?.trim() ? [input.tags] : [])], files: input.media ? [input.media.file] : [] }),
123
+ ...guardWith(unit, { title: input.title, alt: input.alt ?? '', texts: [input.text, ...(input.tags?.trim() ? [input.tags] : [])], files: stageMedia(input).map((m) => m.file) }),
106
124
  ...(kind ? [kind.text] : []),
107
125
  ]
108
126
  }
109
127
 
110
128
  type Ctx = { unit: SocialUnit | null; speaksAs: string | undefined; identitiesDir?: string | null }
111
129
 
112
- async function contextOf(root: string, o: Partial<Ctx>): Promise<Ctx> {
130
+ export async function contextOf(root: string, o: Partial<Ctx>): Promise<Ctx> {
113
131
  const speaksAs = 'speaksAs' in o ? o.speaksAs : (await loadRepoConfig(root, { fresh: true }).catch(() => null))?.speaksAs
114
132
  const unit = 'unit' in o ? (o.unit ?? null) : await loadSocialUnit(root)
115
133
  // the folder is the real repo's house, resolved here: a dry run loads from a scratch folder that has none
@@ -130,13 +148,14 @@ export async function stageDry(root: string, input: StageInput, o: Partial<Ctx>
130
148
  const slug = stageSlug(input.title, input.now ?? new Date())
131
149
  // a vertical's name, so the load reads it as one, on a link to the very file
132
150
  const media = input.media ? mediaFile(input.media) : null
133
- const r = await dryLoad(root, slug, draftText(input, media), input.media && media ? { name: media, file: input.media.file } : null, c)
134
- return { ...r, errors: [...new Set([...guardStage(c.unit, input), ...r.errors])] }
151
+ const text = draftText(input, media)
152
+ const r = await dryLoad(root, slug, text, stageMedia(input), c)
153
+ return { ...r, text, errors: [...new Set([...guardStage(c.unit, input), ...r.errors])] }
135
154
  }
136
155
 
137
156
  /** one draft's text loaded from a scratch copy of the social folder (its rhythm, a link to its media): the desk's own
138
157
  * lines about it, its path left out of each */
139
- export async function dryLoad(root: string, slug: string, raw: string, media: { name: string; file: string } | null, o: Partial<Ctx> = {}): Promise<Staged> {
158
+ export async function dryLoad(root: string, slug: string, raw: string, media: readonly { name: string; file: string }[], o: Partial<Ctx> = {}): Promise<Staged> {
140
159
  const c = await contextOf(root, o)
141
160
  const scratch = mkdtempSync(join(tmpdir(), 'stage-dry-'))
142
161
  try {
@@ -144,9 +163,9 @@ export async function dryLoad(root: string, slug: string, raw: string, media: {
144
163
  mkdirSync(dir, { recursive: true })
145
164
  const rhythm = join(root, LAYOUT.social, 'rhythm.md')
146
165
  if (existsSync(rhythm)) copyFileSync(rhythm, join(scratch, LAYOUT.social, 'rhythm.md'))
147
- if (media) {
148
- mkdirSync(dirname(join(dir, media.name)), { recursive: true })
149
- symlinkSync(media.file, join(dir, media.name))
166
+ for (const m of media) {
167
+ mkdirSync(dirname(join(dir, m.name)), { recursive: true })
168
+ symlinkSync(m.file, join(dir, m.name))
150
169
  }
151
170
  writeFileSync(join(dir, 'draft.md'), raw)
152
171
  const { draft, errors } = await loadOne(scratch, slug, c)
@@ -201,7 +220,7 @@ export async function stageDraft(root: string, input: StageInput, o: Partial<Ctx
201
220
  const c = await contextOf(root, o)
202
221
  const problems = guardStage(c.unit, input)
203
222
  if (problems.length > 0) throw new Error(`the repo's guard refuses it: ${problems.join('; ')}`)
204
- if (input.media && !existsSync(input.media.file)) throw new Error(`no media ${input.media.file}`)
223
+ for (const m of stageMedia(input)) if (!existsSync(m.file)) throw new Error(`no media ${m.file}`)
205
224
  const slug = stageSlug(input.title, input.now ?? new Date())
206
225
  if (!DRAFT_NAME.test(slug)) throw new Error(`draft ${slug}?`)
207
226
  const dir = join(draftsDir(root), slug)
@@ -210,10 +229,10 @@ export async function stageDraft(root: string, input: StageInput, o: Partial<Ctx
210
229
  const files: string[] = []
211
230
  mkdirSync(dir, { recursive: true })
212
231
  try {
213
- if (input.media && media) {
214
- mkdirSync(join(dir, 'media'), { recursive: true })
215
- stripCopy(input.media.file, join(dir, media))
216
- files.push(join(dir, media))
232
+ for (const m of stageMedia(input)) {
233
+ mkdirSync(dirname(join(dir, m.name)), { recursive: true })
234
+ stripCopy(m.file, join(dir, m.name))
235
+ files.push(join(dir, m.name))
217
236
  }
218
237
  writeFileSync(join(dir, 'draft.md'), draftText(input, media))
219
238
  files.unshift(join(dir, 'draft.md'))
@@ -0,0 +1,111 @@
1
+ // a cut's sound without its voice lines (wiki tools/trailer/trailer-sound.md, Your own voice): the music, ducked under
2
+ // each line as the cut ducks it, and the sfx, so a take is heard over what it will sit in. The mix of the build with
3
+ // every voice at volume 0, at the cut's own level; `.shipkit/cache/trailer/bed/<key>.m4a`, the key its ffmpeg words.
4
+ // Beside it, the whole cut in his voice or its standin's, and one line's passage
5
+ import { existsSync, mkdirSync, renameSync, statSync } from 'node:fs'
6
+ import { join } from 'node:path'
7
+ import { houseRequests, load, soundsOf } from './build.ts'
8
+ import { ffmpeg } from './ffmpeg.ts'
9
+ import { trailerCache } from './footage.ts'
10
+ import { mixArgs } from './graph.ts'
11
+ import { soundStates } from './sound/index.ts'
12
+ import { PASSAGE_PAD, type Timeline } from '../review/trailer-model.ts'
13
+
14
+ /** the bed of the cut in `file`, made when the cache misses; refused while a paid line of the cut is not made yet, so
15
+ * a click on the hub never bills */
16
+ export async function voiceBed(root: string, file: string): Promise<string> {
17
+ const l = await load(file, root)
18
+ const unpaid = (await soundStates(root, houseRequests(l))).filter((s) => 'cost' in s && s.cost !== null)
19
+ if (unpaid.length > 0) throw new Error(`${unpaid.length} paid line${unpaid.length > 1 ? 's' : ''} of this cut ${unpaid.length > 1 ? 'are' : 'is'} not made yet: sk trailer makes ${unpaid.length > 1 ? 'them' : 'it'}, then the bed plays`)
20
+ const sounds = await soundsOf(l, l.t.shots, () => undefined)
21
+ const silent = { ...l.t, shots: l.t.shots.map((s) => ({ ...s, voices: s.voices.map((v) => ({ ...v, volume: 0 })) })) }
22
+ const dir = join(trailerCache(root, 'pieces'), '..', 'bed')
23
+ const probe = mixArgs({ t: silent, ...sounds }, '{out}')
24
+ const key = new Bun.CryptoHasher('sha1').update(probe.join('\0')).digest('hex').slice(0, 16)
25
+ const out = join(dir, `${key}.m4a`)
26
+ if (existsSync(out)) return out
27
+ mkdirSync(dir, { recursive: true })
28
+ const tmp = join(dir, `${key}.part-${process.pid}.m4a`)
29
+ await ffmpeg(mixArgs({ t: silent, ...sounds }, tmp))
30
+ renameSync(tmp, out)
31
+ return out
32
+ }
33
+
34
+
35
+ const voicing = new Map<string, Promise<VoicedCut>>()
36
+
37
+ export interface VoicedCut {
38
+ file: string
39
+ /** the file's name in the cache: what the hub's url names */
40
+ key: string
41
+ }
42
+
43
+ /** the render `video` of the cut in `file` with the cut's whole sound mixed again, his takes on (`takes`, the standin
44
+ * where he made none) or off (the standin on every line): the build's own sounds and mix, its picture copied beside
45
+ * it. `.shipkit/cache/trailer/voiced/<key>.mp4`, the key the render's time and the mix's own; one make at a time per
46
+ * side, so the player's range requests never start a second. Refused while a paid line of that side is not made, so a
47
+ * click on the hub never bills, and when the cut's length is no longer its render's */
48
+ export function voicedCut(root: string, file: string, video: string, takes: boolean, rendered: Timeline | null = null): Promise<VoicedCut> {
49
+ const id = `${file}\0${video}\0${statSync(video).mtimeMs}\0${takes}`
50
+ const going = voicing.get(id)
51
+ if (going) return going
52
+ const p = makeVoiced(root, file, video, takes, rendered).finally(() => voicing.delete(id))
53
+ voicing.set(id, p)
54
+ return p
55
+ }
56
+
57
+ /** `rendered`: the timeline the render was made from, so a cut edited since is refused rather than mixed off its
58
+ * picture */
59
+ async function makeVoiced(root: string, file: string, video: string, takes: boolean, rendered: Timeline | null): Promise<VoicedCut> {
60
+ const [{ durationOf }, { renderMix }, { total }, { timelineOf }] = await Promise.all([import('./ffmpeg.ts'), import('./stitch.ts'), import('./grammar.ts'), import('../review/trailer-desk.ts')])
61
+ const l = await load(file, root, { check: false })
62
+ if (l.errors.length > 0) throw new Error(`${l.errors.length} error${l.errors.length > 1 ? 's' : ''} in the cut: ${l.errors[0]!.message} (line ${l.errors[0]!.line})`)
63
+ if (l.t.vertical) throw new Error("a vertical cut lays its outro's sound after the mix: its voice toggle is not made")
64
+ const unpaid = (await soundStates(root, houseRequests(l), takes)).filter((s) => 'cost' in s && s.cost !== null)
65
+ if (unpaid.length > 0) throw new Error(`${unpaid.length} paid line${unpaid.length > 1 ? 's' : ''} of this side ${unpaid.length > 1 ? 'are' : 'is'} not made yet: sk trailer makes ${unpaid.length > 1 ? 'them' : 'it'}, then it plays`)
66
+ const [seconds, T] = [await durationOf(video), total(l.t)]
67
+ const now = timelineOf(l.t).shots
68
+ const moved = rendered?.shots.find((s, i) => s.name !== now[i]?.name || Math.abs(s.start - (now[i]?.start ?? -1)) > 1e-3)
69
+ if (Math.abs(seconds - T) > 0.1 || (rendered && rendered.shots.length !== now.length) || moved)
70
+ throw new Error(`the cut changed since its render${moved ? ` (shot ${moved.name})` : `: ${T.toFixed(2)} s now, ${seconds.toFixed(2)} s rendered`}: sk trailer renders it again, then both voices play`)
71
+ const mix = await renderMix({ t: l.t, ...(await soundsOf(l, l.t.shots, () => undefined, takes)), cache: trailerCache(root, 'pieces') })
72
+ const dir = join(trailerCache(root, 'pieces'), '..', 'voiced')
73
+ const key = new Bun.CryptoHasher('sha1').update(`${video}\0${statSync(video).mtimeMs}\0${mix.key}`).digest('hex').slice(0, 16)
74
+ const out = join(dir, `${key}.mp4`)
75
+ if (existsSync(out)) return { file: out, key }
76
+ mkdirSync(dir, { recursive: true })
77
+ const tmp = join(dir, `${key}.part-${process.pid}.mp4`)
78
+ await ffmpeg(['-i', video, '-i', mix.file, '-map', '0:v', '-map', '1:a', '-c', 'copy', '-movflags', '+faststart', tmp])
79
+ renameSync(tmp, out)
80
+ return { file: out, key }
81
+ }
82
+
83
+ /** a made voiced cut by its key; null when absent */
84
+ export function voicedFile(root: string, key: string): string | null {
85
+ if (!/^[0-9a-f]{16}$/.test(key)) return null
86
+ const f = join(trailerCache(root, 'pieces'), '..', 'voiced', `${key}.mp4`)
87
+ return existsSync(f) ? f : null
88
+ }
89
+
90
+ /** a voice line's passage as one file: the cut's picture from PASSAGE_PAD before the line to PASSAGE_PAD after its
91
+ * longer version, its bed under it, and one version of the line (`voice`, else none) at its place and volume. One
92
+ * element plays it all on one clock. `.shipkit/cache/trailer/passage/<key>.mp4`, the key its ffmpeg words and the
93
+ * render's time */
94
+ export async function voicePassage(root: string, o: { video: string; videoMtime: number; bed: string; at: number; seconds: number; total: number; voice: string | null; volume: number }): Promise<{ file: string; lead: number }> {
95
+ const lead = Math.min(PASSAGE_PAD, o.at)
96
+ const from = o.at - lead
97
+ const len = Math.min(o.total - from, lead + o.seconds + PASSAGE_PAD)
98
+ const n = (x: number): string => x.toFixed(3)
99
+ const voice = o.voice ? ['-i', o.voice] : []
100
+ const mix = o.voice ? `[2:a]aresample=48000,aformat=channel_layouts=stereo,volume=${n(o.volume)},adelay=${Math.round(lead * 1000)}:all=1[v];[1:a][v]amix=inputs=2:normalize=0:duration=first[a]` : '[1:a]anull[a]'
101
+ const args = (out: string): string[] => ['-ss', n(from), '-t', n(len), '-i', o.video, '-ss', n(from), '-t', n(len), '-i', o.bed, ...voice, '-filter_complex', mix, '-map', '0:v', '-map', '[a]', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart', '-t', n(len), out]
102
+ const dir = join(trailerCache(root, 'pieces'), '..', 'passage')
103
+ const key = new Bun.CryptoHasher('sha1').update(`${o.videoMtime}\0${args('{out}').join('\0')}`).digest('hex').slice(0, 16)
104
+ const file = join(dir, `${key}.mp4`)
105
+ if (existsSync(file)) return { file, lead }
106
+ mkdirSync(dir, { recursive: true })
107
+ const tmp = join(dir, `${key}.part-${process.pid}.mp4`)
108
+ await ffmpeg(args(tmp))
109
+ renameSync(tmp, file)
110
+ return { file, lead }
111
+ }
@@ -8,6 +8,7 @@ import { filmLineOf, type Recipe, takesOf, trailerCache } from './footage.ts'
8
8
  import type { BrandLike, TrailerLook } from './look.ts'
9
9
  import { fresh, isTake, movedParts, type Refilm, recipeWords, type Take, takeIsStill, takesToFilm, type World, type WorldState, worldFor } from './plan.ts'
10
10
  import { decodeStates, edgeChanges } from './states.ts'
11
+ import { type CardAnswer, type CutPlan, shotStatus, type ShotStatus, statusText, summaryOf, summaryText, type TakeFact, type TakeFacts } from './shot-state.ts'
11
12
  import { type CompiledScore, compileScore } from './score/score.ts'
12
13
  import { GROW_RES, type Source, titleMotions } from './graph.ts'
13
14
  import type { TitleMotion } from './motion.ts'
@@ -299,15 +300,15 @@ export function soundIds(t: Trailer): { line: number; kind: 'music' | 'sfx' | 'v
299
300
  }
300
301
 
301
302
  /** a sound that is no plain file: the repo's unit first (an id it knows), else the house's maker (a prompt, a run, a
302
- * `.mid`, an id the unit answers null) */
303
- export async function soundFile(l: Pick<Loaded, 'root' | 'file' | 'unit'>, req: SoundRequest, say: Say): Promise<string> {
303
+ * `.mid`, an id the unit answers null); `takes` forces his takes on or off (sound/index.ts brandSound) */
304
+ export async function soundFile(l: Pick<Loaded, 'root' | 'file' | 'unit'>, req: SoundRequest, say: Say, takes?: boolean): Promise<string> {
304
305
  const unit = l.unit
305
306
  const own = houseOnly(req) ? null : req.kind === 'music' ? unit?.sound?.music && ((x: string) => unit.sound!.music!(x, { ...(req.take ? { take: req.take } : {}), seconds: req.seconds ?? 0 })) : req.kind === 'sfx' ? unit?.sound?.sfx : unit?.sound?.voice
306
307
  const got = own ? await own(req.text) : null
307
308
  if (got) return got
308
309
  const house = await houseSound()
309
310
  if (!house) throw new Refused(`${relative(l.root, l.file)}:${req.line}: ${req.kind} ${req.run ? 'run' : req.prompt ? `"${req.text}"` : req.text} is no file, and neither a trailer unit (a <name>.shipkit.ts default-exporting trailer({ sound })) nor the house's sound maker makes it`)
310
- return house.resolveSound(l.root, req, say)
311
+ return house.resolveSound(l.root, req, say, takes)
311
312
  }
312
313
 
313
314
  /** a request the repo's unit never sees: a prompt, a run, a `.mid` */
@@ -362,9 +363,9 @@ export async function soundLines(l: Loaded): Promise<string[]> {
362
363
  }
363
364
 
364
365
  /** the house's sound maker (design call 9, src/trailer/sound/index.ts), null until it exists */
365
- async function houseSound(): Promise<{ resolveSound(root: string, req: SoundRequest, say: Say): Promise<string> } | null> {
366
+ async function houseSound(): Promise<{ resolveSound(root: string, req: SoundRequest, say: Say, takes?: boolean): Promise<string> } | null> {
366
367
  const p = join(import.meta.dir, 'sound', 'index.ts')
367
- return existsSync(p) ? ((await import(p)) as { resolveSound(root: string, req: SoundRequest, say: Say): Promise<string> }) : null
368
+ return existsSync(p) ? ((await import(p)) as { resolveSound(root: string, req: SoundRequest, say: Say, takes?: boolean): Promise<string> }) : null
368
369
  }
369
370
 
370
371
  /** the errors, which stop the build, then the warnings, which do not */
@@ -374,11 +375,6 @@ export function sayErrors(l: Loaded, say: Say, cwd: string): boolean {
374
375
  return l.errors.length === 0
375
376
  }
376
377
 
377
- const ago = (iso: string): string => {
378
- const m = Math.round((Date.now() - Date.parse(iso)) / 60_000)
379
- return m < 60 ? `${m} min ago` : m < 48 * 60 ? `${Math.round(m / 60)} h ago` : `${Math.round(m / 1440)} days ago`
380
- }
381
-
382
378
  const filmText = (f: Film | null): string => {
383
379
  if (!f) return 'nothing'
384
380
  if (f.kind === 'clip' || f.kind === 'image') return `${f.kind} ${f.path}`
@@ -400,46 +396,68 @@ function edgesOf(s: Shot, tk: Take, fps: number, rule: TrailerUnit['states']): s
400
396
  return found.length > 0 ? `, AT ITS EDGES: ${found.join('; ')}` : ''
401
397
  }
402
398
 
403
- /** the timeline, one line a shot then one a footage block, each take's state against the world: a take's last frame
404
- * held, a change at its edges */
405
- export function timeline(l: Loaded, takes: readonly Take[], world: World | null, cwd: string): string[] {
399
+ /** each shot's and footage block's take against the world: filmed or not, when, the parts that moved since; what the
400
+ * timeline says and what the hub's trailer page reads (shot-plan.ts writeFacts) */
401
+ export function takeFactsOf(l: Pick<Loaded, 't'>, takes: readonly Take[], world: World | null, now = new Date()): TakeFacts {
402
+ const takeOf = (s: Shot): Take | undefined => takes.find((x) => x.shot === s)
403
+ const filmed = (s: Shot | undefined): boolean => s !== undefined && (!isTake(s.film) || takeOf(s)?.stamp != null)
404
+ const factOf = (s: Shot): TakeFact => {
405
+ const f = s.film
406
+ if (f?.kind === 'grid' || f?.kind === 'split') {
407
+ const cells = gridCells(l.t, f.cells)
408
+ const n = cells.filter(filmed).length
409
+ return { kind: 'grid', filmed: n === cells.length, cells: { of: cells.length, filmed: n } }
410
+ }
411
+ if (!isTake(f)) return { kind: f?.kind === 'card' ? 'drawn' : 'file', filmed: true }
412
+ const tk = takeOf(s)
413
+ if (!tk?.stamp) return { kind: 'take', filmed: false }
414
+ const w = world === null ? null : worldFor(world, tk)
415
+ return { kind: 'take', filmed: true, filmedAt: tk.stamp.filmedAt, ...(w && !fresh(tk.stamp, w) ? { moved: movedParts(tk.stamp, w) ?? [] } : {}) }
416
+ }
417
+ return { at: now.toISOString(), shots: Object.fromEntries([...l.t.shots, ...l.t.footage].map((s) => [s.name, factOf(s)])) }
418
+ }
419
+
420
+ /** the timeline with the cut's plan and its cards' answers; the takes' facts written for the hub's trailer page unless
421
+ * `record` is false (a draft's takes are not the cut's) */
422
+ export async function planTimeline(l: Loaded, takes: readonly Take[], world: World | null, cwd: string, record = true): Promise<string[]> {
423
+ const { cutIdOf, readPlan, cardAnswers, writeFacts } = await import('./shot-plan.ts')
424
+ const { trailer, cut } = cutIdOf(l.file)
425
+ if (record) writeFacts(l.root, trailer, cut, takeFactsOf(l, takes, world))
426
+ const plan = readPlan(l.root, trailer, cut)
427
+ return timeline(l, takes, world, cwd, { plan, cards: await cardAnswers(l.root, plan) })
428
+ }
429
+
430
+ /** the timeline, one line a shot then one a footage block, each shot's state in plain words (shot-state.ts: the
431
+ * lanes' plan over its take), its take's details: when and on which world it was filmed, its last frame held, a
432
+ * change at its edges; then the cut at a glance */
433
+ export function timeline(l: Loaded, takes: readonly Take[], world: World | null, cwd: string, o: { plan?: CutPlan; cards?: (id: string) => CardAnswer | null } = {}): string[] {
406
434
  const st = starts(l.t)
407
435
  const out = [`${relative(cwd, l.file)}: ${l.t.shots.length} shots, ${total(l.t).toFixed(2)} s, ${l.t.size.join('x')} at ${l.t.fps} fps`]
408
436
  const takeOf = (s: Shot): Take | undefined => takes.find((x) => x.shot === s)
437
+ const facts = takeFactsOf(l, takes, world)
438
+ const statusOf = (s: Shot): ShotStatus => {
439
+ const e = o.plan?.shots[s.name]
440
+ return shotStatus(e, facts.shots[s.name], e?.card ? (o.cards?.(e.card) ?? null) : null)
441
+ }
409
442
  const line = (s: Shot, head: string): void => {
410
443
  const tk = takeOf(s)
411
- const f = s.film
412
- const cells = f?.kind === 'grid' || f?.kind === 'split' ? gridCells(l.t, f.cells).map((c) => (c ? takeOf(c) : undefined)) : []
413
- const state =
414
- f?.kind === 'grid' || f?.kind === 'split'
415
- ? `a ${f.kind} of ${cells.length}, ${cells.filter((c) => c?.stamp).length} filmed`
416
- : !isTake(f)
417
- ? f?.kind === 'card' ? 'drawn' : 'a file'
418
- : !tk?.stamp
419
- ? 'NOT FILMED'
420
- : world === null || fresh(tk.stamp, worldFor(world, tk))
421
- ? 'filmed'
422
- : `filmed on an older world, ${ago(tk.stamp.filmedAt)}${movedText(movedParts(tk.stamp, worldFor(world, tk)))} (--refilm ${s.name})`
444
+ const status = statusOf(s)
445
+ const refilm = facts.shots[s.name]?.moved !== undefined ? ` (--refilm ${s.name})` : ''
446
+ const detail = status.detail.length > 0 ? ` · ${status.detail.join('; ')}${refilm}` : ''
423
447
  const held = tk?.stamp && !takeIsStill(tk.film) && tk.stamp.seconds - s.from < s.length - 0.05 ? `, its last frame held ${(s.length - (tk.stamp.seconds - s.from)).toFixed(2)} s` : ''
424
448
  const edges = tk ? edgesOf(s, tk, l.t.fps, l.unit?.states) : ''
425
449
  const sec = s.section ? ` [section ${s.section.name} at ${+s.section.at.toFixed(3)} s]` : ''
426
450
  const fit = s.written !== undefined ? ` (fitted, written ${s.written} s)` : ''
427
- out.push(` ${head} ${s.name.padEnd(20)} ${s.length.toFixed(2).padStart(5)} s${fit} ${state}${held}${edges}${sec}`)
451
+ out.push(` ${head} ${s.name.padEnd(20)} ${s.length.toFixed(2).padStart(5)} s${fit} ${statusText(status)}${detail}${held}${edges}${sec}`)
428
452
  }
429
453
  l.t.shots.forEach((s, i) => line(s, `${String(i + 1).padStart(2)} ${st[i]!.toFixed(2).padStart(6)} s `))
430
454
  for (const s of l.t.footage) line(s, ' footage ')
431
455
  const sc = l.score
432
456
  if (sc) out.push(` score: ${sc.sections.length} sections, ${sc.notes.length} notes, ${(sc.seconds - SCORE_LEAD).toFixed(2)} s from the cut's ${(l.t.timelineAt ?? 0).toFixed(2)} s${sc.stop !== null ? `, cut dead at its ${(sc.stop - SCORE_LEAD).toFixed(2)} s` : ''}`)
457
+ out.push(` ${summaryText(summaryOf(l.t.shots.map((s) => ({ name: s.name, status: statusOf(s) }))))}`)
433
458
  return out
434
459
  }
435
460
 
436
- /** the parts of the world that moved, as the timeline says them; nothing when the stamp kept no parts */
437
- function movedText(parts: string[] | null): string {
438
- if (parts === null || parts.length === 0) return ''
439
- const shown = parts.slice(0, 4).join(', ')
440
- return `: ${shown}${parts.length > 4 ? ` and ${parts.length - 4} more` : ''} moved`
441
- }
442
-
443
461
  function secs(x: number): string {
444
462
  return `${+x.toFixed(2)} s`
445
463
  }
@@ -548,9 +566,9 @@ export async function scoreFile(l: Loaded, seconds: number, say: Say): Promise<s
548
566
  }
549
567
 
550
568
  /** every sound the shots play, made where the house or the unit has to: the music cues, each shot's sfx and voices */
551
- async function soundsOf(l: Loaded, shots: readonly Shot[], say: Say) {
569
+ export async function soundsOf(l: Loaded, shots: readonly Shot[], say: Say, takes?: boolean) {
552
570
  const { durationOf } = await import('./ffmpeg.ts')
553
- const resolve = (req: SoundRequest): Promise<string> => soundFile(l, req, say)
571
+ const resolve = (req: SoundRequest): Promise<string> => soundFile(l, req, say, takes)
554
572
  const ask = (kind: SoundRequest['kind'], text: string, x: { prompt?: true; gen?: SoundGen; run?: SoundRun; line: number }, seconds?: number, take?: string): SoundRequest => soundRequest(kind, text, x, l.dir, seconds, take)
555
573
  const music = await timed('sounds', () => Promise.all(
556
574
  musicCues(l.t).map(({ cue, at, end }) => {
@@ -574,7 +592,7 @@ async function soundsOf(l: Loaded, shots: readonly Shot[], say: Say) {
574
592
  /** everything the stitch reads but its output: sources, titles, sounds (`sounds` when the caller started them), the look */
575
593
  async function stitchInput(l: Loaded, takes: readonly Take[], shots: readonly Shot[], silent: boolean, say: Say = () => undefined, sounds?: ReturnType<typeof soundsOf>) {
576
594
  const { gridMask, splitMasks } = await import('./stitch.ts')
577
- const [{ cardPng, titlePng }, { lookOf }, { durationOf }, { trailerCache }, { loadBrand, identityLogo }] = await Promise.all([
595
+ const [{ bandHeight, bandPng, cardPng, titlePng }, { lookOf }, { durationOf }, { trailerCache }, { loadBrand, identityLogo }] = await Promise.all([
578
596
  import('./titles.ts'),
579
597
  import('./look.ts'),
580
598
  import('./ffmpeg.ts'),
@@ -584,8 +602,9 @@ async function stitchInput(l: Loaded, takes: readonly Take[], shots: readonly Sh
584
602
  const brand = await loadBrand(l.root)
585
603
  if (typeof brand === 'string') throw new Refused(brand)
586
604
  const look = lookOf(brand, await identityLogo(l.root))
587
- const base = { look, brand }
588
605
  const titles = trailerCache(l.root, 'titles')
606
+ const b = l.t.band
607
+ const base = { look, brand, ...(b ? { band: { file: bandPng(titles, b.text, l.t.size, look, l.root), h: bandHeight(l.t.size[1]), over: b.over } } : {}) }
589
608
  const pieces = trailerCache(l.root, 'pieces')
590
609
  const takeOf = (s: Shot): Take | undefined => takes.find((x) => x.shot === s) ?? takes.find((x) => x.shot.name === s.name)
591
610
  const sources = await Promise.all(shots.map(async (s): Promise<Source> => {
@@ -732,7 +751,7 @@ export async function build(l: Loaded, o: BuildOptions): Promise<string> {
732
751
  }
733
752
  }
734
753
  if (!small) writeFileSync(join(outDir(l), `${l.t.name}.montage.md`), montage(l.t, basename(l.file)))
735
- for (const line of timeline(l, takes, world, o.cwd)) o.say(line)
754
+ for (const line of await planTimeline(l, takes, world, o.cwd, !small)) o.say(line)
736
755
  const what = small ? `a draft at ${small.size.join('x')}, ` : ''
737
756
  o.say(`ok: ${out} (${what}${(finished?.seconds ?? total(lv.t)).toFixed(2)} s) in ${((performance.now() - t0) / 1000).toFixed(1)} s: filming ${((tFilm - t0) / 1000).toFixed(1)} s, ${rendered(done)}${finished ? `, ${finished.note}` : ''}`)
738
757
  if (withStrip) o.say(`ok: ${stripFile}`)
@@ -88,6 +88,12 @@ export async function loudness(file: string): Promise<{ lufs: number; truePeak:
88
88
  return { lufs, truePeak }
89
89
  }
90
90
 
91
+ /** each channel's RMS level in dB, in channel order; a silent channel -120 */
92
+ export async function channelLevels(file: string): Promise<number[]> {
93
+ const log = await ffmpeg(['-nostats', '-loglevel', 'info', '-i', file, '-map', '0:a', '-af', 'astats=measure_overall=none:measure_perchannel=RMS_level', '-f', 'null', '-'])
94
+ return [...log.matchAll(/RMS level dB: (\S+)/g)].map((m) => (m[1] === '-inf' ? -120 : Math.max(-120, Number(m[1]))))
95
+ }
96
+
91
97
  /** loudness() of a file that never changes under its name (a cached render), kept beside it */
92
98
  export async function loudnessKept(file: string): Promise<{ lufs: number; truePeak: number }> {
93
99
  const json = `${file}.loudness.json`
@@ -137,6 +137,14 @@ export interface Vertical {
137
137
  outro: 'card' | 'none' | { clip: string }
138
138
  }
139
139
 
140
+ /** a thin band of words across the top of every frame (`band "<text>" [over]`): in a strip of its own, the picture
141
+ * scaled under it so it covers nothing; `over`: laid over the picture's top instead */
142
+ export interface Band {
143
+ line: number
144
+ text: string
145
+ over: boolean
146
+ }
147
+
140
148
  /** the size a vertical short films at when the file names none */
141
149
  export const VERTICAL_SIZE: [number, number] = [1080, 1920]
142
150
 
@@ -216,6 +224,9 @@ export interface SoundRun {
216
224
  reads?: string[]
217
225
  /** the work runs on another machine (ElevenLabs, the comfy box): it never waits on this machine's load */
218
226
  remote?: true
227
+ /** the work is a second of ffmpeg on this machine (his take levelled): it never waits on the load either, which is
228
+ * for a render that loads it (FluidSynth) */
229
+ light?: true
219
230
  }
220
231
 
221
232
  export interface Sfx {
@@ -410,6 +421,8 @@ export interface Trailer {
410
421
  timelineAt: number | null
411
422
  /** the cut is a vertical short (`vertical`), finished with the brand's lockup, watermark and end card */
412
423
  vertical: Vertical | null
424
+ /** the band across the top of every frame (`band "<text>"`); null: none */
425
+ band: Band | null
413
426
  /** the global process whose url a `film url` route resolves against (`base <id>`); null: the repo's one */
414
427
  base: string | null
415
428
  /** the music variants the file names, and the one it was read as (null: it names none) */
@@ -1065,7 +1078,7 @@ export function parseTrailer(text: string, o: ParseOptions = {}): { trailer: Tra
1065
1078
  const verbs = o.verbs ?? null
1066
1079
  const variants = variantsOf(text)
1067
1080
  const variant = o.variant ?? variants[0] ?? null
1068
- 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 }
1081
+ 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, band: null, base: null, variants, variant }
1069
1082
  /** a music line of another variant plays elsewhere; one of this variant takes the place of the line with none */
1070
1083
  const mine = (m: Music, had: Music | null, what: string): boolean => {
1071
1084
  if (m.variant !== undefined && m.variant !== variant) return false
@@ -1286,6 +1299,14 @@ export function parseTrailer(text: string, o: ParseOptions = {}): { trailer: Tra
1286
1299
  t.vertical = { line: n, outro: (p.outro as Vertical['outro'] | undefined) ?? 'card', ...(p.mark ? { mark: p.mark as 'left' | 'right' } : {}) }
1287
1300
  break
1288
1301
  }
1302
+ case 'band': {
1303
+ once('band')
1304
+ const [text, ...more] = rest
1305
+ if (!text?.quoted || text.text.trim() === '' || more.some((w) => w.quoted || w.text !== 'over') || more.length > 1)
1306
+ bad(`band wants its words in quotes, then over or nothing (band "WIP - alpha version"), got ${rest.map((w) => (w.quoted ? `"${w.text}"` : w.text)).join(' ') || 'nothing'}`)
1307
+ t.band = { line: n, text: text!.text, over: more.length === 1 }
1308
+ break
1309
+ }
1289
1310
  case 'preset': {
1290
1311
  const name = word('preset', rest[0], /^[a-z][a-z0-9-]*$/)
1291
1312
  if (presets.has(name)) bad(`preset ${name} is already a preset of this file`)
@@ -1336,7 +1357,7 @@ export function parseTrailer(text: string, o: ParseOptions = {}): { trailer: Tra
1336
1357
  break
1337
1358
  }
1338
1359
  default:
1339
- 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)`)
1360
+ bad(`unknown word ${head.text} before the first shot (trailer, size, fps, music, duck, master, fade-in, vertical, band, base, preset, score, track, drums, section, defaults, shot)`)
1340
1361
  }
1341
1362
  continue
1342
1363
  }
@@ -51,6 +51,9 @@ export interface StitchInput {
51
51
  /** each voice line's file and its length, shot by shot */
52
52
  voices: { file: string; seconds: number }[][]
53
53
  look: TrailerLook
54
+ /** the band across the top of every frame: its PNG (the frame's width, `h` tall); `over` the picture, else in a
55
+ * strip of its own with the picture scaled under it */
56
+ band?: { file: string; h: number; over: boolean }
54
57
  }
55
58
 
56
59
  const n3 = (x: number): string => (+x.toFixed(4)).toString()
@@ -293,7 +296,7 @@ export function titleMotions(t: Pick<Trailer, 'shots' | 'fps'> & Parameters<type
293
296
 
294
297
  /** the ffmpeg arguments that render a piece's frames, no sound, and the row of its shots' middle frames for the
295
298
  * contact strip (`thumbs`, when a middle falls in it) */
296
- export function pieceArgs(a: Pick<StitchInput, 't' | 'sources' | 'titles' | 'look'>, p: Piece, out: string, encoder: Encoder = 'draft', thumbs?: string): string[] {
299
+ export function pieceArgs(a: Pick<StitchInput, 't' | 'sources' | 'titles' | 'look' | 'band'>, p: Piece, out: string, encoder: Encoder = 'draft', thumbs?: string): string[] {
297
300
  const { t } = a
298
301
  const [W, H] = t.size
299
302
  const fps = t.fps
@@ -492,6 +495,14 @@ export function pieceArgs(a: Pick<StitchInput, 't' | 'sources' | 'titles' | 'loo
492
495
  cur = `v${i}_${j}`
493
496
  })
494
497
  })
498
+ // the band over every frame, titles and the ending included; in its own strip the picture is scaled under it,
499
+ // centred, so the band covers no face and no row of a page
500
+ if (a.band) {
501
+ const k = input('-i', a.band.file)
502
+ const under = a.band.over ? '' : `scale=${even((W * (H - a.band.h)) / H)}:${H - a.band.h},pad=${W}:${H}:(ow-iw)/2:${a.band.h}:color=${ff(a.look.edge)},setsar=1,`
503
+ graph.push(`[${cur}]${under}format=yuv420p[under]`, `[under][${k}:v]overlay=x=0:y=0:eof_action=repeat[band]`)
504
+ cur = 'band'
505
+ }
495
506
  graph.push(`[${cur}]trim=end_frame=${p.to - base},format=yuv420p,${TAGS}[vout]`)
496
507
 
497
508
  // the contact strip's row: the middle frame of each shot whose middle is in the piece, side by side
@@ -0,0 +1,75 @@
1
+ // a cut's plan and its takes' facts on disk (wiki tools/trailer/index.md, Shot states): the plan the lanes write through
2
+ // `sk trailer plan`, `.shipkit/trailer-plan/<trailer>/<cut>.json`, and the takes as the last build or check read them,
3
+ // `.shipkit/cache/trailer-takes/<trailer>--<cut>.json`, so the hub reads both without loading a cut. A plan write
4
+ // holds the file's lock over its read and write: two lanes marking at once both land
5
+ import { existsSync, mkdirSync, readFileSync } from 'node:fs'
6
+ import { basename, dirname, join } from 'node:path'
7
+ import { LAYOUT } from '../core/layout.ts'
8
+ import { atomicWrite, withFileLock } from '../core/locked-write.ts'
9
+ import { isApproved, type ReviewItem, verdictOf } from '../review/model.ts'
10
+ import { type CardAnswer, markShots, parsePlan, type CutPlan, type PlanEntry, type TakeFacts } from './shot-state.ts'
11
+
12
+ export const planFile = (root: string, trailer: string, cut: string): string => join(root, LAYOUT.trailerPlan, trailer, `${cut}.json`)
13
+ export const factsFile = (root: string, trailer: string, cut: string): string => join(root, LAYOUT.cache, 'trailer-takes', `${trailer}--${cut}.json`)
14
+
15
+ /** a loaded cut's trailer folder and cut: `trailer/<trailer>/<cut>.trailer` */
16
+ export const cutIdOf = (file: string): { trailer: string; cut: string } => ({ trailer: basename(dirname(file)), cut: basename(file, '.trailer') })
17
+
18
+ /** the cut's plan, empty when no lane wrote one; a file that does not parse fails loud */
19
+ export function readPlan(root: string, trailer: string, cut: string): CutPlan {
20
+ const f = planFile(root, trailer, cut)
21
+ if (!existsSync(f)) return { shots: {} }
22
+ try {
23
+ return parsePlan(readFileSync(f, 'utf8'))
24
+ } catch (e) {
25
+ throw new Error(`${f}: ${(e as Error).message} (sk trailer plan writes it; delete it to start the plan again)`)
26
+ }
27
+ }
28
+
29
+ /** these shots marked in the cut's plan, or their entries dropped (`mark` null); the plan as written */
30
+ export function writePlan(root: string, trailer: string, cut: string, shots: readonly string[], mark: Omit<PlanEntry, 'at'> | null, at = new Date().toISOString()): CutPlan {
31
+ const f = planFile(root, trailer, cut)
32
+ mkdirSync(dirname(f), { recursive: true })
33
+ for (let i = 0; i < 40; i++) {
34
+ const got = withFileLock(f, () => {
35
+ const next = markShots(readPlan(root, trailer, cut), shots, mark, at)
36
+ atomicWrite(f, `${JSON.stringify(next, null, 2)}\n`)
37
+ return next
38
+ })
39
+ if (got.ok) return got.value
40
+ Bun.sleepSync(50)
41
+ }
42
+ throw new Error(`${f} stayed locked by another writer for 2 s: nothing written`)
43
+ }
44
+
45
+ /** the owner's answer on each card a plan names, read from the review store only when one names a card */
46
+ export async function cardAnswers(root: string, plan: CutPlan): Promise<(id: string) => CardAnswer | null> {
47
+ const ids = new Set(Object.values(plan.shots).flatMap((e) => (e.card ? [e.card] : [])))
48
+ if (ids.size === 0) return () => null
49
+ const { readItem, storeDir } = await import('../review/store.ts')
50
+ const got = new Map([...ids].map((id) => [id, answerOf(readItem(storeDir(root), id))]))
51
+ return (id) => got.get(id) ?? null
52
+ }
53
+
54
+ /** a card's answer as a shot's state reads it: null while he has not answered, or when the store has no such card */
55
+ export function answerOf(x: ReviewItem | null): CardAnswer | null {
56
+ const v = x ? verdictOf(x) : null
57
+ return v ? { status: v.status, approved: isApproved(v.status) } : null
58
+ }
59
+
60
+ export function readFacts(root: string, trailer: string, cut: string): TakeFacts | null {
61
+ const f = factsFile(root, trailer, cut)
62
+ if (!existsSync(f)) return null
63
+ try {
64
+ return JSON.parse(readFileSync(f, 'utf8')) as TakeFacts
65
+ } catch {
66
+ // a cache file torn by hand: the next check writes it again
67
+ return null
68
+ }
69
+ }
70
+
71
+ export function writeFacts(root: string, trailer: string, cut: string, facts: TakeFacts): void {
72
+ const f = factsFile(root, trailer, cut)
73
+ mkdirSync(dirname(f), { recursive: true })
74
+ atomicWrite(f, `${JSON.stringify(facts)}\n`)
75
+ }