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
@@ -32,7 +32,7 @@ export const NO_CHECK = 'in no check'
32
32
  * section a row lives under (hub-app/tree-build.ts KIND_SECTION). There is no
33
33
  * catch all kind: a row belongs to an owner, and what belongs to the hub
34
34
  * itself is its status (serve/hub-problems.ts), never a row */
35
- export const RESOURCE_TYPES = ['ask', 'secret', 'asset', 'post', 'workflow', 'wiki', 'contract', 'check', 'test', 'reflection', 'process', 'command', 'card', 'cut', 'store', 'release', 'veille', 'message'] as const
35
+ export const RESOURCE_TYPES = ['ask', 'secret', 'asset', 'post', 'workflow', 'wiki', 'contract', 'check', 'test', 'reflection', 'process', 'command', 'card', 'cut', 'voice', 'store', 'release', 'veille', 'message'] as const
36
36
 
37
37
  /** the collection of the review cards that wait on him (collections/review.ts) */
38
38
  export const REVIEW_COL = 'review'
@@ -1,13 +1,16 @@
1
1
  // the review store and the trailer cuts as tree rows (wiki tools/shipkit/review.md). Under the review section, one row a
2
2
  // card that waits on HIM (the owner's verdict, his answer to a question): yellow, so `sk needs` lists it too. Under the trailer
3
- // section, one row a cut, its open frame notes in the slot: they wait on agents, never on him, so a cut is never yellow.
4
- // Each collection exists only where the repo has its folder, so a repo with none draws the section greyed
3
+ // section, one row a cut, its open frame notes in the slot: they wait on agents, never on him, so a cut is never yellow;
4
+ // and one yellow row a line of his own voice he has not recorded yet (the page's Voices). Each collection exists only where the repo has its folder, so a repo with none draws the section greyed
5
5
  import { existsSync } from 'node:fs'
6
6
  import { join } from 'node:path'
7
7
  import { STATUS_LABEL, isFrame, stateOf, type ReviewItem } from '../review/model.ts'
8
8
  import { readAllCached, storeDir, storeStamp, warmStore } from '../review/store.ts'
9
9
  import { statusOf, waitingOnOwner, type Thread } from '../review/threads.ts'
10
10
  import { cutsOf, trailerIds } from '../review/trailer-desk.ts'
11
+ import { voicesDesk } from '../review/trailer-voices.ts'
12
+ import { recordVoices } from '../trailer/sound/brand.ts'
13
+ import { brandSound } from '../trailer/sound/index.ts'
11
14
  import { REVIEW_COL, TRAILER_COL, type Collection, type Instance } from './collection-types.ts'
12
15
 
13
16
  const waiting = new Map<string, { stamp: string; threads: Thread[]; items: ReviewItem[] }>()
@@ -66,7 +69,23 @@ export function trailersCollection(root: string): Collection | null {
66
69
  const s = x.item.subject
67
70
  if (isFrame(s) && stateOf(x, false).state !== 'closed') open.set(`${s.trailer}/${s.cut}`, (open.get(`${s.trailer}/${s.cut}`) ?? 0) + 1)
68
71
  }
69
- return ids.flatMap((id) =>
72
+ // a line of his recorded voice with no take waits on him: yellow, one row a text
73
+ const voices: Instance[] = []
74
+ const brand = await brandSound(root).catch(() => undefined)
75
+ if (recordVoices(brand).length > 0)
76
+ for (const id of ids)
77
+ for (const l of (await voicesDesk(root, id, brand))?.lines ?? [])
78
+ if (l.mine && !l.take)
79
+ voices.push({
80
+ id: `voice:${id}/${l.key}`,
81
+ text: `${id}: "${l.words}" waits for your voice`,
82
+ label: l.words.length > 48 ? `${l.words.slice(0, 47).trimEnd()}…` : l.words,
83
+ slot: 'to record',
84
+ type: 'voice',
85
+ path: l.uses[0]?.file ?? `trailer/${id}`,
86
+ severity: 'yellow',
87
+ })
88
+ return [...voices, ...ids.flatMap((id) =>
70
89
  cutsOf(join(root, 'trailer', id)).map((c): Instance => {
71
90
  const n = open.get(`${id}/${c.cut}`) ?? 0
72
91
  const rendered = existsSync(join(root, 'trailer', id, 'out', `${c.name}.mp4`))
@@ -80,7 +99,7 @@ export function trailersCollection(root: string): Collection | null {
80
99
  state: rendered ? 'idle' : 'quiet',
81
100
  }
82
101
  }),
83
- )
102
+ )]
84
103
  },
85
104
  }
86
105
  }
@@ -37,6 +37,9 @@ export const LAYOUT = {
37
37
  // the social folder (contract v3): one folder a draft, the week's rhythm. The SK004 block re-includes it in a
38
38
  // private repo only, like plans (wiki tools/shipkit/social.md)
39
39
  social: sk('social'),
40
+ // the owner's own voice: his takes of a trailer's lines, one a text (trailer/sound/takes.ts). The SK004 block
41
+ // re-includes it in a private repo only: a recording is his voice
42
+ voice: sk('voice'),
40
43
  // local: the facts (sha, size, type) of every draft media, so a file the disk let go keeps its key in the media
41
44
  // store (wiki tools/shipkit/social.md, Media)
42
45
  socialMedia: sk('social-media.json'),
@@ -53,6 +56,9 @@ export const LAYOUT = {
53
56
  tmp: sk('tmp'),
54
57
  // a CLI's call log, `<cli>-calls.jsonl`: local, never tracked
55
58
  logs: sk('logs'),
59
+ // local: what the lanes plan for each shot of a cut, `<trailer>/<cut>.json` (trailer/shot-plan.ts). It speaks of
60
+ // this machine's takes, which live in the cache, and lanes rewrite it many times an hour
61
+ trailerPlan: sk('trailer-plan'),
56
62
  // holds no app: a process app lives in ~/Applications, and the apps job removes any shipkit bundle here (home/process-apps.ts)
57
63
  wrapper: sk('wrapper'),
58
64
  // generated on every run
@@ -173,6 +173,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
173
173
 
174
174
  func applicationDidFinishLaunching(_ note: Notification) {
175
175
  if CommandLine.arguments.contains("--self-test-find") { return selfTestFind() }
176
+ if CommandLine.arguments.contains("--self-test-mic") { return selfTestMic() }
176
177
  if CommandLine.arguments.contains("--self-test-panels") { return selfTestPanels() }
177
178
  if CommandLine.arguments.contains("--self-test-download") { return selfTestDownload() }
178
179
  if CommandLine.arguments.contains("--self-test-badge") { return selfTestBadge() }
@@ -345,6 +346,32 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
345
346
  web.loadHTMLString("<p>one needle, two needle</p>", baseURL: nil)
346
347
  }
347
348
 
349
+ // `--self-test-mic`: a window's own web view on a page of the machine, then on a page of another host, each
350
+ // printing whether the page can reach the microphone api (`getUserMedia`); no capture is asked, so no prompt
351
+ func selfTestMic() {
352
+ let web = WKWebView(frame: NSRect(x: 0, y: 0, width: 400, height: 300), configuration: webConfig())
353
+ web.navigationDelegate = self
354
+ web.uiDelegate = self
355
+ windows.append(NSWindow(contentRect: NSRect(x: -4000, y: -4000, width: 400, height: 300), styleMask: [.titled], backing: .buffered, defer: false))
356
+ windows.last?.contentView = web
357
+ let probe = "typeof (navigator.mediaDevices && navigator.mediaDevices.getUserMedia)"
358
+ onLoad = { _ in
359
+ web.evaluateJavaScript(probe) { local, _ in
360
+ print("local=\(local as? String ?? "error")")
361
+ self.onLoad = { _ in
362
+ web.evaluateJavaScript(probe) { other, _ in
363
+ print("other=\(other as? String ?? "error")")
364
+ exit((local as? String) == "function" ? 0 : 1)
365
+ }
366
+ }
367
+ web.loadHTMLString("<p>other</p>", baseURL: URL(string: "http://example.invalid/"))
368
+ }
369
+ }
370
+ // the page the test serves on the machine, loaded over http as a window loads the home
371
+ let served = CommandLine.arguments.last.flatMap { URL(string: $0) }.flatMap { $0.scheme == "http" ? $0 : nil }
372
+ if let url = served { web.load(URLRequest(url: url)) } else { web.loadHTMLString("<p>local</p>", baseURL: URL(string: "http://127.0.0.1:9/")) }
373
+ }
374
+
348
375
  /** hears every js panel once it shows: the self test answers it */
349
376
  var onPanel: ((NSAlert) -> Void)?
350
377
 
@@ -740,6 +767,14 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
740
767
  // WebKit throws when a handler is dropped or called twice: `panel` calls
741
768
  // `done` exactly once on every path
742
769
 
770
+ // a page of the machine asks for the microphone (the trailer page records a voice line): granted, the system's
771
+ // own prompt (NSMicrophoneUsageDescription) still asks the owner once; any other ask goes to WebKit's prompt
772
+ @available(macOS 12.0, *)
773
+ func webView(_ web: WKWebView, requestMediaCapturePermissionFor origin: WKSecurityOrigin, initiatedByFrame frame: WKFrameInfo, type: WKMediaCaptureType, decisionHandler: @escaping (WKPermissionDecision) -> Void) {
774
+ let local = origin.host == "127.0.0.1" || origin.host == "localhost" || origin.host == startURL.host
775
+ decisionHandler(local && type == .microphone ? .grant : .prompt)
776
+ }
777
+
743
778
  /** one js panel: a sheet on the page's window, a modal where there is
744
779
  * none. Return is OK, esc is Cancel; `done` hears whether OK was pressed */
745
780
  func panel(_ web: WKWebView, _ message: String, cancel: Bool, field: NSTextField? = nil, done: @escaping (Bool) -> Void) {
@@ -63,6 +63,7 @@ export function infoPlist(o: Omit<AppSpec, 'app' | 'icon' | 'identity'>): string
63
63
  \t<key>CFBundleVersion</key><string>${xml(o.version)}</string>
64
64
  ${o.url == null ? '' : `\t<key>ShipkitStartURL</key><string>${xml(o.url)}</string>\n`}\t<key>LSMinimumSystemVersion</key><string>12.0</string>
65
65
  \t<key>NSHighResolutionCapable</key><true/>
66
+ \t<key>NSMicrophoneUsageDescription</key><string>A page you open here records your voice, a trailer's lines for one.</string>
66
67
  \t<key>NSAppTransportSecurity</key>${atsOf(o.url)}
67
68
  </dict>
68
69
  </plist>
@@ -0,0 +1,112 @@
1
+ // a global process, or one of pm's own roles, switched through the running pm
2
+ // and followed until its probe settles it. Lib code, not a command: the daemon
3
+ // reaches it (a take starts the dev server it films), so it never lives in
4
+ // src/cli/, which no role's graph may hold (home/lib-watch.ts).
5
+ import { pmUrl } from './home-paths.ts'
6
+ import { ROLES, type PmAnswer, type Role } from './pm.ts'
7
+ import type { ResourceView } from './resources.ts'
8
+
9
+ /** pm's status answer, or null when it does not answer */
10
+ export async function askPm(url = pmUrl()): Promise<PmAnswer | null> {
11
+ try {
12
+ const r = await fetch(`${url}/api/pm/status.json`, { signal: AbortSignal.timeout(1_500) })
13
+ if (!r.ok) return null
14
+ const j = (await r.json()) as PmAnswer
15
+ return j.pm === 'shipkit-pm' ? j : null
16
+ } catch {
17
+ return null
18
+ }
19
+ }
20
+
21
+ export type SwitchAct = 'start' | 'stop' | 'restart'
22
+
23
+ /** what a switch follows, the same on a global process and on one of pm's own roles (the daemon, the web) */
24
+ export type SwitchView = Pick<ResourceView, 'status' | 'pid' | 'want' | 'note' | 'tail'>
25
+
26
+ export type SwitchDeps = {
27
+ /** pm's answer to the switch: null when it took it, else why not */
28
+ post: (id: string, act: SwitchAct | 'open' | 'chrome' | 'app') => Promise<string | null>
29
+ /** the process as pm sees it now, null when pm does not answer */
30
+ view: (id: string) => Promise<SwitchView | null>
31
+ sleep: (ms: number) => Promise<void>
32
+ now: () => number
33
+ log: (line: string) => void
34
+ }
35
+
36
+ /** the longest a switch is followed: a bring-up polls its health for minutes */
37
+ export const SWITCH_WAIT_MS = 10 * 60_000
38
+ const SWITCH_POLL_MS = 1_000
39
+ /** how long the state the switch left counts as pm not having acted yet */
40
+ export const SWITCH_GRACE_MS = 30_000
41
+
42
+ /** flip a global process, or one of pm's own roles, through pm, then follow
43
+ * pm's state until its probe settles it: 0 once it is up (or down for stop),
44
+ * 1 otherwise. A restart is up only on a new pid: the old one still answers
45
+ * until pm stops it (pm stops the web after its answer is out). The
46
+ * launcher's exit code proves nothing, pm's probe does */
47
+ export async function switchProcess(id: string, act: SwitchAct, d: SwitchDeps, waitMs = SWITCH_WAIT_MS): Promise<number> {
48
+ const before = act === 'restart' ? ((await d.view(id))?.pid ?? null) : null
49
+ const refused = await d.post(id, act)
50
+ if (refused != null) {
51
+ d.log(`FAIL ${act} ${id}: ${refused}`)
52
+ return 1
53
+ }
54
+ const want = act === 'stop' ? 'down' : 'up'
55
+ const start = d.now()
56
+ const end = start + waitMs
57
+ let said = ''
58
+ for (;;) {
59
+ const v = await d.view(id)
60
+ if (v == null) {
61
+ d.log(`FAIL pm stopped answering while ${id} was switched ${want}: shipkit gp`)
62
+ return 1
63
+ }
64
+ if (v.status !== said) {
65
+ said = v.status
66
+ d.log(`${id}: ${v.status}`)
67
+ }
68
+ // the state it is leaving, read just after the switch, is pm not there yet
69
+ const graced = d.now() - start < SWITCH_GRACE_MS
70
+ const leaving = v.status === (want === 'up' ? 'down' : 'up') && graced
71
+ const old = before != null && v.pid === before
72
+ const moving = v.status === 'starting' || v.status === 'stopping' || v.want !== want || leaving || (old && graced)
73
+ if (!moving) {
74
+ if (old && v.status === 'up') {
75
+ d.log(`FAIL ${id} still runs pid ${before} ${Math.round(SWITCH_GRACE_MS / 1000)}s after the restart: pm did not restart it`)
76
+ return 1
77
+ }
78
+ if (v.status === want) return 0
79
+ d.log(`FAIL ${id} is ${v.status}, not ${want}${v.note == null ? '' : `: ${v.note}`}`)
80
+ for (const l of v.tail.slice(-10)) d.log(` log: ${l}`)
81
+ return 1
82
+ }
83
+ if (d.now() >= end) {
84
+ d.log(`FAIL ${id} still ${v.status} after ${Math.round(waitMs / 1000)}s: shipkit gp shows where it stands`)
85
+ return 1
86
+ }
87
+ await d.sleep(SWITCH_POLL_MS)
88
+ }
89
+ }
90
+
91
+ const isRole = (id: string): id is Role => (ROLES as string[]).includes(id)
92
+
93
+ /** the switch against the running pm: pm's own roles (the daemon, the web) through its child api, every other id a
94
+ * global process */
95
+ export const pmSwitchDeps = (log: (line: string) => void, url = pmUrl()): SwitchDeps => ({
96
+ post: async (id, act) => {
97
+ try {
98
+ const r = await fetch(`${url}/api/pm/${isRole(id) ? 'child' : 'resource'}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id, act }), signal: AbortSignal.timeout(5_000) })
99
+ return r.ok ? null : await r.text()
100
+ } catch (e) {
101
+ return `pm does not answer on ${url} (${(e as Error).message}): shipkit pm install`
102
+ }
103
+ },
104
+ view: async (id) => {
105
+ const a = await askPm(url)
106
+ if (a == null) return null
107
+ return (isRole(id) ? a.children.find((c) => c.id === id) : a.resources.find((r) => r.id === id)) ?? null
108
+ },
109
+ sleep: (ms) => Bun.sleep(ms),
110
+ now: () => Date.now(),
111
+ log,
112
+ })
@@ -278,8 +278,10 @@ function imageSize(abs: string): { w: number | null; h: number | null } {
278
278
  const SHOWN = ['jpg', 'png', 'webp', 'mp4', 'svg']
279
279
  /** the identity's own folder of pictures, listed first whether `pictures` names it or not */
280
280
  const OWN = 'pictures'
281
+ /** its folders by kind; its other folders (src, art, fonts, candidates) are how they are made, never listed */
282
+ const KINDS = ['avatars', 'banners', 'tiers']
281
283
 
282
- /** the pictures of its own folder then of each `pictures` folder, each folder the largest first, one picture per name
284
+ /** the pictures of its own folder (and its kind folders) then of each `pictures` folder, each folder the largest first, one picture per name
283
285
  * with its other formats: a folder under `files`, or a `~/…` or absolute one elsewhere on the disk (a repo's own files
284
286
  * the identity names), its pictures named by that path */
285
287
  function pictures(files: string | null, dirs: string, file: string, errors: string[]): Picture[] {
@@ -293,11 +295,14 @@ function pictures(files: string | null, dirs: string, file: string, errors: stri
293
295
  continue
294
296
  }
295
297
  const byName = new Map<string, string[]>()
296
- for (const f of readdirSync(abs).sort()) {
297
- const m = /^(.+)\.(\w+)$/.exec(f)
298
- if (m == null || !SHOWN.includes(m[2]!)) continue
299
- byName.set(m[1]!, [...(byName.get(m[1]!) ?? []), m[2]!])
300
- }
298
+ const subs = dir === OWN ? KINDS.filter((k) => existsSync(join(abs, k))) : []
299
+ for (const sub of ['', ...subs])
300
+ for (const f of readdirSync(join(abs, sub)).sort()) {
301
+ const m = /^(.+)\.(\w+)$/.exec(f)
302
+ if (m == null || !SHOWN.includes(m[2]!)) continue
303
+ const name = sub === '' ? m[1]! : `${sub}/${m[1]!}`
304
+ byName.set(name, [...(byName.get(name) ?? []), m[2]!])
305
+ }
301
306
  const here: Picture[] = []
302
307
  for (const [name, exts] of byName) {
303
308
  const [shown, ...rest] = [...exts].sort((x, y) => SHOWN.indexOf(x) - SHOWN.indexOf(y))
@@ -34,14 +34,14 @@ export function briefOf(s: Store, kind: string, run: string, who: string): strin
34
34
  const gs = personas.filter((p) => p.kind === 'gatekeeper')
35
35
  if (!gs.length) throw new Error('messages: no gatekeeper in personas.md')
36
36
  return [
37
- `You play ${gs.length} gatekeepers in a message test, each judged on its own. Read ONLY ${join(dir, 'packets', `${gs[0]!.id}.md`)}. Open no other file.`,
37
+ `You play ${gs.length} gatekeepers in a message test, each judged on its own: ${gs.map((g) => g.id).join(', ')}. Read ONLY ${join(dir, 'packets', `${gs[0]!.id}.md`)}: that one sheet holds the lines every one of them judges. Open no other file.`,
38
38
  '',
39
39
  ...para(b.gatekeepers),
40
40
  ...gs.map((g) => `- **${g.id}**: ${g.who}`),
41
41
  '',
42
- `For each one, judge EVERY line and write a JSON array of {"id", "verdict", "words": what drives it or ""} to ${join(dir, 'verdicts', '<id>.json')} with the Write tool. Be realistic: reserve the harsh verdicts for what would truly trigger them.`,
42
+ `For each one, judge EVERY line and write a JSON array of {"id", "verdict", "words": what drives it or ""} with the Write tool, one file a gatekeeper: ${gs.map((g) => join(dir, 'verdicts', `${g.id}.json`)).join(', ')}. Be realistic: reserve the harsh verdicts for what would truly trigger them.`,
43
43
  '',
44
- 'Reply with one line a gatekeeper: the ids it refuses, then the ids it flags.',
44
+ `Reply with ${gs.length} lines, one a gatekeeper: its id, the ids it refuses, then the ids it flags.`,
45
45
  ].join('\n')
46
46
  }
47
47
  if (kind === 'judge') {
@@ -50,6 +50,8 @@ export function matrix(messages: Message[], personas: Persona[], dir: string): s
50
50
  for (const f of jsonsIn(join(dir, 'judged'))) for (const j of readJson<Judged[]>(join(dir, 'judged', f))) judged.set(`${j.id}/${j.persona}`, j)
51
51
  const verdicts = new Map<string, Map<string, Verdict>>()
52
52
  for (const f of jsonsIn(join(dir, 'verdicts'))) verdicts.set(f.slice(0, -5), new Map(readJson<Verdict[]>(join(dir, 'verdicts', f)).map((v) => [v.id, v])))
53
+ const unjudged = verdicts.size ? personas.filter((p) => p.kind === 'gatekeeper' && !verdicts.has(p.id)).map((p) => p.id) : []
54
+ if (unjudged.length) throw new Error(`messages: no verdicts of ${unjudged.join(', ')} in ${join(dir, 'verdicts')}: the gatekeepers brief writes one file a gatekeeper`)
53
55
 
54
56
  const cell = (c: Candidate, p: string): number | undefined => {
55
57
  const r = readings.get(p)?.get(c.id)
@@ -4,8 +4,9 @@
4
4
  import { itemOfRef, storeDir } from '../review/store.ts'
5
5
  import { publicProblems } from '../social/unit.ts'
6
6
  import { commitPaths } from '../social/writes.ts'
7
- import { cardParts, versionsOf } from './from-card.ts'
8
- import { changesOf, emptyRelease, NEXT, type Change, type ReleaseKind } from './model.ts'
7
+ import { isPostRating, POST_RATINGS, type PostRating } from '../identities/rating.ts'
8
+ import { cardParts, versionsOf, withShot } from './from-card.ts'
9
+ import { changesOf, emptyRelease, isClip, NEXT, type Change, type ReleaseKind, type Shot } from './model.ts'
9
10
  import { keepPicture } from './pictures.ts'
10
11
  import { addChange, readRelease, undeclaredReleases, writeRelease } from './store.ts'
11
12
 
@@ -15,6 +16,10 @@ export interface AddAsk {
15
16
  text?: string
16
17
  bullets?: string[]
17
18
  image?: string
19
+ /** a still of what it looked like before, the tab beside its picture */
20
+ before?: string
21
+ /** the rating of the shot it writes; with no new picture, of the change's one unrated shot */
22
+ rating?: string
18
23
  card?: string
19
24
  commit?: string
20
25
  kind?: string
@@ -31,6 +36,8 @@ async function guarded(root: string, what: string, texts: string[]): Promise<voi
31
36
  /** next.md written with the ask: its kind and title, and one change; the file written */
32
37
  export async function addByHand(root: string, a: AddAsk): Promise<string> {
33
38
  if (a.kind !== undefined && !KINDS.includes(a.kind)) throw new Error(`--kind ${a.kind}: major, minor or patch`)
39
+ if (a.rating !== undefined && !isPostRating(a.rating)) throw new Error(`--rating ${a.rating}: one of ${POST_RATINGS.join(', ')}`)
40
+ const rating = (a.rating as PostRating | undefined) ?? null
34
41
  const change = a.category !== undefined || a.title !== undefined || a.card !== undefined
35
42
  if (!change && a.kind === undefined && a.heading === undefined) throw new Error('nothing to write: a change (a category and a title, or --card), or --kind, or --release-title')
36
43
  const why = await undeclaredReleases(root)
@@ -54,11 +61,32 @@ export async function addByHand(root: string, a: AddAsk): Promise<string> {
54
61
  // the change of the same card, else of the same title: what the hand does not give, the card included, is kept
55
62
  const all = next ? changesOf(next) : []
56
63
  const had = (given != null ? all.find((ch) => ch.card === given) : undefined) ?? all.find((ch) => ch.title === title)
57
- const c: Change = { title, text: a.text ?? had?.text ?? '', bullets: a.bullets ?? had?.bullets ?? [], picture: had?.picture ?? null, card: given ?? had?.card ?? null, commit: a.commit ?? x?.item.commit ?? had?.commit ?? null }
64
+ const c: Change = { title, text: a.text ?? had?.text ?? '', bullets: a.bullets ?? had?.bullets ?? [], shots: had?.shots ?? [], card: given ?? had?.card ?? null, commit: a.commit ?? x?.item.commit ?? had?.commit ?? null }
65
+ if (a.before !== undefined && isClip(a.before)) throw new Error(`--before ${a.before}: a before is a still (png, jpg, webp), not a clip`)
66
+ // the shot a --before or a --rating alone lands on: the change's one unrated shot, else its one shot
67
+ const unrated = c.shots.filter((s) => s.picture.rating == null)
68
+ const target = (): Shot => {
69
+ const s = unrated.length === 1 ? unrated[0] : c.shots.length === 1 ? c.shots[0] : undefined
70
+ if (!s) throw new Error(`"${c.title}" has ${c.shots.length === 0 ? 'no picture' : `${c.shots.length} shots`}: give --image with it`)
71
+ return s
72
+ }
58
73
  // the words first: a refused change uploads no picture
59
74
  await guarded(root, `"${c.title}"`, [category, c.title, c.text, ...c.bullets])
60
- if (a.image !== undefined) c.picture = { url: await keepPicture(root, a.image), alt: c.title }
61
- else if (x) c.picture = (await cardParts(root, x, c.title)).picture ?? c.picture
75
+ // a new picture takes the place of the shot of its rating, its old before gone unless the hand gives its own
76
+ let wrote: Shot | null = null
77
+ if (a.image !== undefined) wrote = { picture: { url: await keepPicture(root, a.image), alt: c.title, rating }, before: null }
78
+ else if (x) wrote = (await cardParts(root, x, c.title, rating)).shot
79
+ if (wrote) c.shots = withShot(c.shots, wrote)
80
+ else if (rating != null) {
81
+ const s = target()
82
+ wrote = { picture: { ...s.picture, rating }, before: s.before && { ...s.before, rating } }
83
+ c.shots = c.shots.map((t) => (t === s ? wrote! : t))
84
+ }
85
+ if (a.before !== undefined) {
86
+ const s = wrote ?? target()
87
+ const next: Shot = { picture: s.picture, before: { url: await keepPicture(root, a.before), alt: c.title, rating: rating ?? s.picture.rating } }
88
+ c.shots = c.shots.map((t) => (t.picture.url === s.picture.url ? next : t))
89
+ }
62
90
  file = addChange(root, category, c).file
63
91
  }
64
92
  commitPaths([file!], `releases: next.md takes ${a.title ?? a.card ?? 'its heading'}`)
@@ -0,0 +1,31 @@
1
+ // whether a pair's before earns its tab (wiki tools/shipkit/units.md, The release files): both stills read at a
2
+ // card's width in grey. The thresholds were measured on 21 real card pairs: an all black before spreads 0, the
3
+ // pairs that look the same differ 0.4 to 9.5 on average, the real changes 28 to 72
4
+ import sharp from 'sharp'
5
+
6
+ /** the width both stills are read at: a release card's, where a small change disappears */
7
+ const WIDTH = 320
8
+ /** under this spread of its grey values (of 255) a before is one flat colour: an all black frame */
9
+ export const BLANK_SPREAD = 4
10
+ /** under this mean difference from the after (of 255) a before shows nothing the after does not */
11
+ export const SAME_DIFF = 16
12
+
13
+ const grey = async (file: string, w: number, h: number): Promise<Buffer> => sharp(file).removeAlpha().resize(w, h, { fit: 'fill' }).greyscale().raw().toBuffer()
14
+
15
+ /** why a before stays out of the release: `blank`, `same`, or null when its tab shows a real difference */
16
+ export async function idleBefore(before: string, after: string): Promise<'blank' | 'same' | null> {
17
+ const m = await sharp(after).metadata()
18
+ const h = Math.max(1, Math.round((WIDTH * (m.height ?? WIDTH)) / Math.max(1, m.width ?? WIDTH)))
19
+ const [b, a] = await Promise.all([grey(before, WIDTH, h), grey(after, WIDTH, h)])
20
+ let sum = 0
21
+ for (const v of b) sum += v
22
+ const mean = sum / b.length
23
+ let spread = 0
24
+ let diff = 0
25
+ for (let i = 0; i < b.length; i++) {
26
+ spread += (b[i]! - mean) ** 2
27
+ diff += Math.abs(b[i]! - a[i]!)
28
+ }
29
+ if (Math.sqrt(spread / b.length) < BLANK_SPREAD) return 'blank'
30
+ return diff / b.length < SAME_DIFF ? 'same' : null
31
+ }
@@ -1,15 +1,19 @@
1
1
  // a change written from a review card (wiki tools/shipkit/review.md, A change for the release): the card carries its
2
- // public line (`--changelog "<category>: <line>"`), and the owner's approval adds it to next.md with the card's after picture,
3
- // kept private in the Space. The card named is the thread's first version, so a later version approved again replaces
4
- // its change instead of adding a second one
2
+ // public line (`--changelog "<category>: <line>"`), and the owner's approval adds it to next.md with the card's media
3
+ // (a pair of images as its after and its before, two stills, never a video; a clip as it is, else its image), kept
4
+ // private in the Space. The card named is the thread's first version, so a later version approved again replaces its
5
+ // change instead of adding a second
5
6
  import { ensureLocal } from '../review/media-read.ts'
6
7
  import { isApproved, verdictOf, type Item, type ReviewItem } from '../review/model.ts'
7
8
  import { stageablesOf } from '../review/stage-card.ts'
8
- import { readItem, storeDir } from '../review/store.ts'
9
+ import { readAll, readItem, storeDir } from '../review/store.ts'
10
+ import { threadOfItem, threadsOf } from '../review/threads.ts'
9
11
  import { commitPaths } from '../social/writes.ts'
10
- import { NEXT, type Change } from './model.ts'
12
+ import { idleBefore } from './before.ts'
13
+ import type { PostRating } from '../identities/rating.ts'
14
+ import { changesOf, isClip, NEXT, ratingOf, type Change, type Picture, type Shot } from './model.ts'
11
15
  import { keepPicture } from './pictures.ts'
12
- import { addChange, readRelease, undeclaredReleases } from './store.ts'
16
+ import { addChange, readRelease, undeclaredReleases, writeRelease } from './store.ts'
13
17
 
14
18
  /** the versions of a card, newest first, following `supersedes` */
15
19
  export function versionsOf(dir: string, x: ReviewItem): Item[] {
@@ -23,26 +27,61 @@ export function versionsOf(dir: string, x: ReviewItem): Item[] {
23
27
  return out
24
28
  }
25
29
 
26
- /** the file that stands for the change: the after of a pair, else the first image or clip */
27
- async function pictureOf(dir: string, i: Item): Promise<string | null> {
28
- const pick = stageablesOf(i, 1).find((s) => s.side !== 'before' && s.side !== 'wipe')
29
- return pick ? ensureLocal(dir, i.id, pick.file) : null
30
+ /** a card's first media is a pair of images, the one shape that lends a change a before */
31
+ const isImagePair = (i: Item): boolean => stageablesOf(i, 1).some((s) => s.side === 'before' && s.kind === 'image')
32
+
33
+ /** the files that stand for the change: a pair of images as its after and its before (null when blank or the same as
34
+ * the after, `idle` says which), a clip or a pair of clips' after as it is, else the first image */
35
+ async function mediaOf(dir: string, i: Item): Promise<{ after: string; before: string | null; idle: 'blank' | 'same' | null } | null> {
36
+ const all = stageablesOf(i, 1)
37
+ const pick = all.find((s) => s.side !== 'before' && s.side !== 'wipe')
38
+ if (!pick) return null
39
+ const after = await ensureLocal(dir, i.id, pick.file)
40
+ if (!after) return null
41
+ const b = pick.side === 'after' && pick.kind === 'image' ? all.find((s) => s.side === 'before' && s.view === pick.view) : undefined
42
+ const before = b ? await ensureLocal(dir, i.id, b.file) : null
43
+ if (!before) return { after, before: null, idle: null }
44
+ const idle = await idleBefore(before, after)
45
+ return { after, before: idle ? null : before, idle }
30
46
  }
31
47
 
32
- /** what a card lends a change whatever its line: its newest version's picture kept private, the thread's first id, its
33
- * commit */
34
- export async function cardParts(root: string, x: ReviewItem, alt: string): Promise<Pick<Change, 'picture' | 'card' | 'commit'>> {
35
- const dir = storeDir(root)
36
- const file = await pictureOf(dir, x.item)
37
- const url = file ? await keepPicture(root, file) : null
38
- return { picture: url ? { url, alt } : null, card: versionsOf(dir, x).at(-1)!.id, commit: x.item.commit ?? null }
48
+ /** a card's media kept private in the Space, as one shot of a change rated `rating` (null: unrated) */
49
+ async function keptMedia(root: string, i: Item, alt: string, rating: PostRating | null): Promise<{ shot: Shot | null; idle: 'blank' | 'same' | null }> {
50
+ const m = await mediaOf(storeDir(root), i)
51
+ if (!m) return { shot: null, idle: null }
52
+ const picture: Picture = { url: await keepPicture(root, m.after), alt, rating }
53
+ return { shot: { picture, before: m.before ? { url: await keepPicture(root, m.before), alt, rating } : null }, idle: m.idle }
54
+ }
55
+
56
+ /** the rating a card's media lands with: its changelog line's `--rating`, else unrated */
57
+ const cardRating = (root: string, x: ReviewItem): PostRating | null => versionsOf(storeDir(root), x).find((v) => v.changelog)?.changelog?.rating ?? null
58
+
59
+ /** what a card lends a change whatever its line: its newest version's shot kept private, rated `rating` when a hand
60
+ * gives one, else as the card says, the thread's first id, its commit */
61
+ export async function cardParts(root: string, x: ReviewItem, alt: string, rating: PostRating | null = null): Promise<{ shot: Shot | null; card: string; commit: string | null }> {
62
+ const { shot } = await keptMedia(root, x.item, alt, rating ?? cardRating(root, x))
63
+ return { shot, card: versionsOf(storeDir(root), x).at(-1)!.id, commit: x.item.commit ?? null }
64
+ }
65
+
66
+ /** a change's shots once a card's shot comes in: it takes the place of the shot it reads the same rating as, the others
67
+ * stay (a safe retake beside an nsfw card, by hand); an unrated card picture whose file did not change keeps the
68
+ * rating it had */
69
+ export function withShot(had: readonly Shot[], shot: Shot | null): Shot[] {
70
+ if (!shot) return [...had]
71
+ const same = had.find((s) => s.picture.url === shot.picture.url)
72
+ const rated: Shot =
73
+ shot.picture.rating == null && same?.picture.rating != null
74
+ ? { picture: { ...shot.picture, rating: same.picture.rating }, before: shot.before && { ...shot.before, rating: shot.before.rating ?? (shot.before.url === same.before?.url ? same.before.rating : null) } }
75
+ : shot
76
+ return [rated, ...had.filter((s) => s.picture.url !== rated.picture.url && ratingOf(s.picture) !== ratingOf(rated.picture))]
39
77
  }
40
78
 
41
79
  /** the change a card adds to next: its line and its parts; null for a card with no changelog line */
42
80
  export async function changeOfCard(root: string, x: ReviewItem): Promise<{ category: string; change: Change } | null> {
43
81
  const line = versionsOf(storeDir(root), x).find((v) => v.changelog)?.changelog
44
82
  if (!line) return null
45
- return { category: line.category, change: { title: line.line, text: '', bullets: [], ...(await cardParts(root, x, line.line)) } }
83
+ const { shot, card, commit } = await cardParts(root, x, line.line)
84
+ return { category: line.category, change: { title: line.line, text: '', bullets: [], shots: shot ? [shot] : [], card, commit } }
46
85
  }
47
86
 
48
87
  /** after the owner's verdict: an approved card with a changelog line goes into next.md, committed; the next.md path,
@@ -59,8 +98,54 @@ export async function onVerdict(root: string, id: string): Promise<string | null
59
98
  const had = readRelease(root, NEXT)
60
99
  ?.categories.flatMap((k) => k.changes)
61
100
  .find((ch) => ch.card === c.change.card)
62
- const change = had ? { ...c.change, text: had.text, bullets: had.bullets } : c.change
101
+ const change = had ? { ...c.change, text: had.text, bullets: had.bullets, shots: withShot(had.shots, c.change.shots[0] ?? null) } : c.change
63
102
  const { file } = addChange(root, c.category, change)
64
103
  commitPaths([file], `releases: next takes the change of the card ${c.change.card}`)
65
104
  return file
66
105
  }
106
+
107
+ /** the version of a card's thread a change stands for: its newest approved one, else its newest */
108
+ function approvedOf(dir: string, id: string): ReviewItem | null {
109
+ const t = threadOfItem(id, threadsOf(readAll(dir).items))
110
+ if (!t) return readItem(dir, id)
111
+ return t.versions.find((v) => isApproved(verdictOf(v)?.status ?? 'rejected')) ?? t.head
112
+ }
113
+
114
+ /** what a refresh did to one change: its stills, and its before dropped as blank or the same as the after */
115
+ export interface Refreshed {
116
+ title: string
117
+ before: 'kept' | 'blank' | 'same' | 'none'
118
+ }
119
+
120
+ /** every change of next.md still showing a pair's wipe (a clip, from a card whose media is two images) takes that
121
+ * card's stills, its after and its before; any other picture stays, a retake by hand included. The changes moved, and
122
+ * the file written and committed unless `dry` (null when nothing moved) */
123
+ export async function refreshFromCards(root: string, o: { dry?: boolean } = {}): Promise<{ file: string | null; moved: Refreshed[] }> {
124
+ const why = await undeclaredReleases(root)
125
+ if (why) throw new Error(why)
126
+ const next = readRelease(root, NEXT)
127
+ if (!next) return { file: null, moved: [] }
128
+ const dir = storeDir(root)
129
+ const done = new Map<Change, Change>()
130
+ const moved: Refreshed[] = []
131
+ for (const ch of changesOf(next)) {
132
+ const wipe = ch.shots.find((s) => isClip(s.picture.url))
133
+ if (ch.card == null || !wipe) continue
134
+ const x = approvedOf(dir, ch.card)
135
+ if (!x) throw new Error(`"${ch.title}": its card ${ch.card} is not in the store`)
136
+ if (!isImagePair(x.item)) continue
137
+ if (o.dry) {
138
+ moved.push({ title: ch.title, before: 'none' })
139
+ continue
140
+ }
141
+ // the stills show what the wipe showed: its rating stays
142
+ const m = await keptMedia(root, x.item, wipe.picture.alt, wipe.picture.rating)
143
+ done.set(ch, { ...ch, shots: ch.shots.flatMap((s) => (s !== wipe ? [s] : m.shot ? [m.shot] : [])) })
144
+ moved.push({ title: ch.title, before: m.shot?.before ? 'kept' : (m.idle ?? 'none') })
145
+ }
146
+ if (o.dry || moved.length === 0) return { file: null, moved }
147
+ const release = { ...next, categories: next.categories.map((c) => ({ ...c, changes: c.changes.map((ch) => done.get(ch) ?? ch) })) }
148
+ const file = writeRelease(root, release)
149
+ commitPaths([file], `releases: next shows its cards' stills, not their wipes (${moved.length} changes)`)
150
+ return { file, moved }
151
+ }