rvlib-shipkit 2.18.0 → 2.19.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 (46) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/package.json +1 -1
  3. package/src/asks/asks-queue.ts +63 -10
  4. package/src/cli/cmd_Asks.ts +3 -1
  5. package/src/cli/cmd_GlobalProcesses.ts +34 -11
  6. package/src/cli/cmd_Home.ts +38 -2
  7. package/src/cli/cmd_Secret.ts +4 -30
  8. package/src/cli/cmd_Social.ts +40 -1
  9. package/src/cli/cmd_Trailer.ts +15 -3
  10. package/src/cli/registry.ts +2 -1
  11. package/src/collections/actions.ts +29 -1
  12. package/src/collections/collection-types.ts +2 -0
  13. package/src/collections/providers.ts +1 -1
  14. package/src/home/home-paths.ts +5 -1
  15. package/src/home/home-start.ts +12 -12
  16. package/src/home/run-daemon.ts +11 -2
  17. package/src/home/run-pm.ts +9 -1
  18. package/src/home/supervise.ts +3 -1
  19. package/src/identities/identities.ts +22 -5
  20. package/src/review/http.ts +7 -2
  21. package/src/review/store.ts +81 -19
  22. package/src/secrets/manager.ts +59 -0
  23. package/src/secrets/name.ts +2 -0
  24. package/src/serve/hub-app/col-card.tsx +10 -0
  25. package/src/serve/hub-app/cols-svc.ts +37 -6
  26. package/src/serve/hub-app/hub.css +1 -0
  27. package/src/serve/hub-app/social/identity-pictures.ts +74 -0
  28. package/src/serve/hub-app/social/social-page.tsx +77 -37
  29. package/src/serve/hub-app/social.css +8 -3
  30. package/src/serve/serve-hub.ts +12 -2
  31. package/src/social/discord-layout.ts +239 -0
  32. package/src/social/md.ts +14 -6
  33. package/src/social/publish/discord.ts +3 -2
  34. package/src/social/routes.ts +3 -3
  35. package/src/stores/routes.ts +2 -2
  36. package/src/suite/judge-suites.ts +1 -1
  37. package/src/suite/suite-cli.ts +5 -5
  38. package/src/trailer/build.ts +75 -50
  39. package/src/trailer/draft.ts +28 -0
  40. package/src/trailer/footage.ts +4 -2
  41. package/src/trailer/grammar.ts +11 -9
  42. package/src/trailer/graph.ts +32 -9
  43. package/src/trailer/profile.ts +35 -0
  44. package/src/trailer/prune.ts +15 -10
  45. package/src/trailer/stitch.ts +22 -10
  46. package/src/trailer/titles.ts +47 -2
@@ -20,7 +20,7 @@ import { ensureIdentity } from '../core/identity.ts'
20
20
  import { homedir } from 'os'
21
21
  import { join } from 'path'
22
22
  import { startBeat } from './beat.ts'
23
- import { childBeat, childLog, daemonPort, homeDir, homePort, homeUp, hubBase, publicHome, WORKER_ENV } from './home-paths.ts'
23
+ import { childBeat, childLog, daemonPort, homeDir, homePort, homeUp, houseOfIndex, hubBase, publicHome, WORKER_ENV } from './home-paths.ts'
24
24
  import { inboxAddress } from './inbox-shape.ts'
25
25
  import { HomeState } from './home-state.ts'
26
26
  import { Hubs } from './hubs.ts'
@@ -44,7 +44,16 @@ export async function runDaemon(root: string, io: HomeIo, o: { port?: number } =
44
44
  const own = o.port ?? daemonPort()
45
45
  // the port a page reaches every hub on: the web's
46
46
  const port = homePort()
47
- const house = houseRepos(root, homedir())
47
+ const seen = houseRepos(root, homedir())
48
+ // started in another folder (a house repo, a folder inside one): the daemon runs from the house repo, whose config
49
+ // it loads, never from the folder it started in
50
+ const top = seen.index == null ? null : houseOfIndex(seen.index)
51
+ const moved = top != null && top !== root
52
+ if (moved) {
53
+ io.print(`note: the daemon started in ${root}, so it runs from the house repo ${top}`)
54
+ root = top
55
+ }
56
+ const house = moved ? houseRepos(root, homedir()) : seen
48
57
  if (house.index == null) {
49
58
  io.printErr(`FAIL: ${root} includes no house wiki index in its CLAUDE.md, so the daemon has no repos to load. Run it from the repo that hosts the house wiki`)
50
59
  return 1
@@ -7,7 +7,7 @@
7
7
  // against pm's own 20.
8
8
  import { stampConsole } from '../core/log-stamp.ts'
9
9
  import { fileURLToPath } from 'url'
10
- import { daemonPort, homeDir, homePort, homeUp, homeUrl, pmPort, pmUp, WORKER_ENV } from './home-paths.ts'
10
+ import { daemonPort, homeDir, homePort, homeUp, homeUrl, houseOfIndex, pmPort, pmUp, WORKER_ENV } from './home-paths.ts'
11
11
  import { reloadOnOwnCode } from './lib-watch.ts'
12
12
  import { Pm, PM_TICK_MS, type Role } from './pm.ts'
13
13
  import { Resources } from './resources.ts'
@@ -81,6 +81,14 @@ export async function runPm(root: string, io: HomeIo, o: { port?: number } = {})
81
81
  let c: PmConfig
82
82
  try {
83
83
  c = await readPmConfig(root)
84
+ // started from another folder (a house repo, a folder inside one): pm and its children run from the house
85
+ // repo, never from the folder pm started in, where the daemon finds no repo config
86
+ const house = c.index == null ? null : houseOfIndex(c.index)
87
+ if (house != null && house !== root) {
88
+ io.print(`note: pm started in ${root}, so it runs from the house repo ${house}`)
89
+ root = house
90
+ c = await readPmConfig(root)
91
+ }
84
92
  } catch (e) {
85
93
  io.printErr(`FAIL: ${(e as Error).message}`)
86
94
  return 1
@@ -52,6 +52,8 @@ export type ProcView = {
52
52
  note: string | null
53
53
  /** up, and started by something else: not ours to stop */
54
54
  external: boolean
55
+ /** what the owner last asked for */
56
+ want: 'up' | 'down'
55
57
  }
56
58
 
57
59
  export type SuperviseDeps = {
@@ -361,7 +363,7 @@ export class Proc {
361
363
  }
362
364
 
363
365
  view(): ProcView {
364
- return { id: this.spec.id, status: this.status, pid: this.pid, since: this.since, restarts: this.crashes.length, note: this.note, external: this.external }
366
+ return { id: this.spec.id, status: this.status, pid: this.pid, since: this.since, restarts: this.crashes.length, note: this.note, external: this.external, want: this.want }
365
367
  }
366
368
  }
367
369
 
@@ -71,7 +71,8 @@ export type Account = {
71
71
  places: Place[]
72
72
  }
73
73
 
74
- export type Picture = { file: string; w: number | null; h: number | null }
74
+ /** one picture: the file shown, its size, and the same picture in its other formats (an svg beside its png) */
75
+ export type Picture = { file: string; w: number | null; h: number | null; also: string[] }
75
76
 
76
77
  /** a company as the forms ask it: `legal.md`, and the private rows of the gitignored `legal.local.md` */
77
78
  export type Legal = {
@@ -199,19 +200,35 @@ function imageSize(abs: string): { w: number | null; h: number | null } {
199
200
  return { w: null, h: null }
200
201
  }
201
202
 
202
- /** the pictures of each `pictures` folder, each folder the largest first: a folder under `files`, or a `~/…` or
203
- * absolute one elsewhere on the disk (a repo's own files the identity names), its pictures named by that path */
203
+ /** the formats a picture is shown by, the first one its folder holds; the others are its `also` */
204
+ const SHOWN = ['jpg', 'png', 'webp', 'mp4', 'svg']
205
+ /** the identity's own folder of pictures, listed first whether `pictures` names it or not */
206
+ const OWN = 'pictures'
207
+
208
+ /** the pictures of its own folder then of each `pictures` folder, each folder the largest first, one picture per name
209
+ * with its other formats: a folder under `files`, or a `~/…` or absolute one elsewhere on the disk (a repo's own files
210
+ * the identity names), its pictures named by that path */
204
211
  function pictures(files: string | null, dirs: string, file: string, errors: string[]): Picture[] {
205
212
  if (files == null) return []
213
+ const named = dirs.split(',').map((d) => d.trim().replace(/\/+$/, '')).filter(Boolean)
206
214
  const out: Picture[] = []
207
- for (const dir of dirs.split(',').map((d) => d.trim()).filter(Boolean)) {
215
+ for (const dir of [...(named.includes(OWN) || !existsSync(join(files, OWN)) ? [] : [OWN]), ...named]) {
208
216
  const abs = dir.startsWith('~/') || isAbsolute(dir) ? home(dir) : join(files, dir)
209
217
  if (!existsSync(abs)) {
210
218
  errors.push(`${file}: pictures "${dir}" is no folder on this disk`)
211
219
  continue
212
220
  }
221
+ const byName = new Map<string, string[]>()
222
+ for (const f of readdirSync(abs).sort()) {
223
+ const m = /^(.+)\.(\w+)$/.exec(f)
224
+ if (m == null || !SHOWN.includes(m[2]!)) continue
225
+ byName.set(m[1]!, [...(byName.get(m[1]!) ?? []), m[2]!])
226
+ }
213
227
  const here: Picture[] = []
214
- for (const f of readdirSync(abs).sort()) if (/\.(png|jpg|webp|mp4)$/.test(f)) here.push({ file: `${dir}/${f}`, ...imageSize(join(abs, f)) })
228
+ for (const [name, exts] of byName) {
229
+ const [shown, ...rest] = [...exts].sort((x, y) => SHOWN.indexOf(x) - SHOWN.indexOf(y))
230
+ here.push({ file: `${dir}/${name}.${shown}`, ...imageSize(join(abs, `${name}.${shown}`)), also: rest.map((e) => `${dir}/${name}.${e}`) })
231
+ }
215
232
  out.push(...here.sort((x, y) => (y.w ?? 0) * (y.h ?? 0) - (x.w ?? 0) * (x.h ?? 0)))
216
233
  }
217
234
  return out
@@ -2,10 +2,13 @@
2
2
  // answer under its ETag, a file with byte ranges
3
3
  import { extname } from 'node:path'
4
4
 
5
- export const TYPES: Record<string, string> = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.webm': 'video/webm', '.mp4': 'video/mp4', '.ico': 'image/x-icon' }
5
+ export const TYPES: Record<string, string> = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.svg': 'image/svg+xml', '.webm': 'video/webm', '.mp4': 'video/mp4', '.ico': 'image/x-icon' }
6
6
  export const NO_STORE = { 'Cache-Control': 'no-store' }
7
7
  /** an item's files never change once written, nor a kept render under its version: a phone keeps what it fetched */
8
8
  export const KEEP = { 'Cache-Control': 'private, max-age=86400' }
9
+ /** a file rebuilt in place under its name (an identity's picture, a store's asset): the page asks each time, and a
10
+ * 304 answers while its size and mtime hold */
11
+ export const FRESH = { 'Cache-Control': 'no-cache' }
9
12
 
10
13
  /** a json answer under its ETag: 304 when the page holds it, gzipped when the page takes it and it is worth it. A
11
14
  * caller that keeps the answer passes `held`, the zip made once for every page that asks the same tag */
@@ -27,7 +30,9 @@ export async function ranged(req: Request, path: string, headers: Record<string,
27
30
  const file = Bun.file(path)
28
31
  if (!(await file.exists())) return bad(`no ${path.split('/').pop()}`, 404)
29
32
  const size = file.size
30
- const head = { 'Content-Type': TYPES[extname(path).toLowerCase()] ?? 'application/octet-stream', 'Accept-Ranges': 'bytes', ...headers }
33
+ const tag = headers === FRESH ? `"${size.toString(36)}-${Math.round(file.lastModified).toString(36)}"` : null
34
+ if (tag && req.headers.get('If-None-Match') === tag) return new Response(null, { status: 304, headers: { ...FRESH, ETag: tag } })
35
+ const head = { 'Content-Type': TYPES[extname(path).toLowerCase()] ?? 'application/octet-stream', 'Accept-Ranges': 'bytes', ...headers, ...(tag ? { ETag: tag } : {}) }
31
36
  const range = /^bytes=(\d*)-(\d*)$/.exec(req.headers.get('range') ?? '')
32
37
  if (!range) return new Response(file, { headers: { ...head, 'Content-Length': String(size) } })
33
38
  const start = range[1] ? Number(range[1]) : Math.max(0, size - Number(range[2]))
@@ -605,8 +605,8 @@ const CODE_KEEP_MS = 7 * 24 * 3600_000
605
605
  const READ_STEP = 250
606
606
 
607
607
  /** every item of the store, through the machine index (space/db.ts): an item whose stamp moved is read again */
608
- function readRaws(dir: string): ReadAll {
609
- const steps = readRawsSteps(dir)
608
+ function readRaws(dir: string, stamps?: Map<string, string>): ReadAll {
609
+ const steps = readRawsSteps(dir, stamps)
610
610
  for (;;) {
611
611
  const r = steps.next()
612
612
  if (r.done) return r.value
@@ -615,8 +615,8 @@ function readRaws(dir: string): ReadAll {
615
615
 
616
616
  /** the same read, the loop given back every READ_STEP items: a cold store of thousands of items is seconds of parsing
617
617
  * (wiki tools/shipkit/home.md, Nothing heavy on the daemon's loop) */
618
- async function readRawsAsync(dir: string): Promise<ReadAll> {
619
- const steps = readRawsSteps(dir)
618
+ async function readRawsAsync(dir: string, stamps?: Map<string, string>): Promise<ReadAll> {
619
+ const steps = readRawsSteps(dir, stamps)
620
620
  for (;;) {
621
621
  const r = steps.next()
622
622
  if (r.done) return r.value
@@ -624,8 +624,8 @@ async function readRawsAsync(dir: string): Promise<ReadAll> {
624
624
  }
625
625
  }
626
626
 
627
- /** the one read, in steps: it yields between two of them, and returns the store */
628
- function* readRawsSteps(dir: string): Generator<void, ReadAll, void> {
627
+ /** the one read, in steps: it yields between two of them, and returns the store. `stamps` hears each item's stamp */
628
+ function* readRawsSteps(dir: string, stamps?: Map<string, string>): Generator<void, ReadAll, void> {
629
629
  const out: ReadAll = { items: [], broken: [] }
630
630
  if (!existsSync(dir)) return out
631
631
  const store = resolve(dir)
@@ -650,6 +650,7 @@ function* readRawsSteps(dir: string): Generator<void, ReadAll, void> {
650
650
  if (++n % READ_STEP === 0) yield
651
651
  seen.add(id)
652
652
  const stamp = stampOf(join(dir, id))
653
+ stamps?.set(id, stamp)
653
654
  const held = was.get(id)
654
655
  let read: Read | null = null
655
656
  if (held && held.stamp === stamp)
@@ -1005,12 +1006,59 @@ export async function readyItem(dir: string, id: string, o: { image?: string; no
1005
1006
  }
1006
1007
 
1007
1008
  /** a store watched by this process: `moved` counts the writes under it, by any process; `dirty` names the items they
1008
- * touched since the last read, `held` every item as last read (null until a first whole read); null once the watch failed */
1009
+ * touched since the last read, `held` every item as last read (null until a first whole read); null once the watch
1010
+ * failed. `folder`, `stamps`, `swept` and `rev` are the disk check under the watch (verify) */
1009
1011
  interface Watched {
1010
1012
  moved: number
1011
1013
  dirty: Set<string>
1012
1014
  held: Map<string, Read> | null
1013
1015
  all: ReadAll | null
1016
+ folder: string
1017
+ stamps: Map<string, string>
1018
+ swept: number
1019
+ rev: number
1020
+ }
1021
+
1022
+ /** how often a read stats every item of a watched store, for a write inside an item its watch missed (17 ms on 3333) */
1023
+ export const SWEEP_MS = 10_000
1024
+
1025
+ const folderStamp = (key: string): string => {
1026
+ const s = statSync(key, { bigint: true, throwIfNoEntry: false })
1027
+ return s ? `${s.ctimeNs}.${s.ino}` : '-'
1028
+ }
1029
+
1030
+ /** the disk checked under the watch, which goes silent under load (FSEvents drops events) and must never freeze the
1031
+ * list: each call stats the store folder (1 µs), which a card's arrival or removal moves (a rename in it), and every
1032
+ * SWEEP_MS the stamp of each item. What moved unheard goes dirty and moves the ETag */
1033
+ function verify(key: string, w: Watched, now: number): void {
1034
+ if (!w.held) return
1035
+ let found = false
1036
+ const mark = (id: string): void => {
1037
+ if (w.dirty.has(id)) return
1038
+ w.dirty.add(id)
1039
+ found = true
1040
+ }
1041
+ const folder = folderStamp(key)
1042
+ if (folder !== w.folder) {
1043
+ w.folder = folder
1044
+ const ids = new Set(readdirSync(key).filter((n) => !n.startsWith('.')))
1045
+ for (const id of ids) if (!w.held.has(id)) mark(id)
1046
+ for (const id of w.held.keys()) if (!ids.has(id)) mark(id)
1047
+ }
1048
+ if (now - w.swept >= SWEEP_MS) {
1049
+ w.swept = now
1050
+ for (const [id, stamp] of w.stamps) if (stampOf(join(key, id)) !== stamp) mark(id)
1051
+ }
1052
+ if (found) w.rev++
1053
+ }
1054
+
1055
+ /** a whole read's result kept as the watch's view: its items, their stamps, the folder as it was before the read */
1056
+ function hold(w: Watched, all: ReadAll, folder: string, stamps: Map<string, string>, now: number): void {
1057
+ w.held = new Map<string, Read>([...all.items.map((x) => [x.item.id, { x }] as const), ...all.broken.map((b) => [b.id, { error: b.error }] as const)])
1058
+ w.all = all
1059
+ w.folder = folder
1060
+ w.stamps = stamps
1061
+ w.swept = now
1014
1062
  }
1015
1063
  const watched = new Map<string, Watched | null>()
1016
1064
  const BOOT = Date.now().toString(36)
@@ -1025,7 +1073,7 @@ function touched(path: string): void {
1025
1073
  function watchOf(dir: string): Watched | null {
1026
1074
  const key = resolve(dir)
1027
1075
  if (watched.has(key)) return watched.get(key) ?? null
1028
- const w: Watched = { moved: 0, dirty: new Set(), held: null, all: null }
1076
+ const w: Watched = { moved: 0, dirty: new Set(), held: null, all: null, folder: '', stamps: new Map(), swept: 0, rev: 0 }
1029
1077
  try {
1030
1078
  // an item's lock is no change of the list
1031
1079
  const watcher = watch(key, { recursive: true }, (_, name) => {
@@ -1052,17 +1100,21 @@ export async function warmStore(dir: string): Promise<void> {
1052
1100
  if (!w || (w.held && w.all)) return
1053
1101
  // what moved before the read is in it; what moves during it stays dirty, read again by the next reader
1054
1102
  w.dirty.clear()
1055
- const all = await readRawsAsync(dir)
1103
+ const folder = folderStamp(resolve(dir))
1104
+ const stamps = new Map<string, string>()
1105
+ const all = await readRawsAsync(dir, stamps)
1056
1106
  if (w.held && w.all) return
1057
- w.held = new Map<string, Read>([...all.items.map((x) => [x.item.id, { x }] as const), ...all.broken.map((b) => [b.id, { error: b.error }] as const)])
1058
- w.all = all
1107
+ hold(w, all, folder, stamps, Date.now())
1059
1108
  }
1060
1109
 
1061
- /** changes when anything the list is built from changes: watched, a count of writes; else a scan. The list's ETag */
1062
- export function storeStamp(dir: string): string {
1110
+ /** changes when anything the list is built from changes: watched, a count of writes and what the disk check found;
1111
+ * else a scan. The list's ETag */
1112
+ export function storeStamp(dir: string, now = Date.now()): string {
1063
1113
  if (!existsSync(dir)) return 'none'
1064
1114
  const w = watchOf(dir)
1065
- return w ? `${BOOT}.${w.moved}.${wrote}` : scanStamp(dir)
1115
+ if (!w) return scanStamp(dir)
1116
+ verify(resolve(dir), w, now)
1117
+ return `${BOOT}.${w.moved}.${w.rev}.${wrote}`
1066
1118
  }
1067
1119
 
1068
1120
  /** the store's stamp and who listens (the live watchers' pids), so a watch that starts or dies moves it too */
@@ -1097,18 +1149,28 @@ function readRawsCached(dir: string): ReadAll {
1097
1149
  if (cached?.dir !== dir || cached.tag !== tag) cached = { dir, tag, all: readRaws(dir) }
1098
1150
  return cached.all
1099
1151
  }
1152
+ const key = resolve(dir)
1153
+ const now = Date.now()
1100
1154
  if (!w.held || !w.all) {
1101
1155
  w.dirty.clear()
1102
- const all = readRaws(dir)
1103
- w.held = new Map<string, Read>([...all.items.map((x) => [x.item.id, { x }] as const), ...all.broken.map((b) => [b.id, { error: b.error }] as const)])
1104
- w.all = all
1156
+ const folder = folderStamp(key)
1157
+ const stamps = new Map<string, string>()
1158
+ const all = readRaws(dir, stamps)
1159
+ hold(w, all, folder, stamps, now)
1105
1160
  return all
1106
1161
  }
1162
+ verify(key, w, now)
1107
1163
  if (w.dirty.size === 0) return w.all
1108
1164
  for (const id of w.dirty) {
1109
1165
  if (id === '' || id.startsWith('.')) continue
1110
- if (existsSync(join(dir, id))) w.held.set(id, readOne(dir, id))
1111
- else w.held.delete(id)
1166
+ if (existsSync(join(dir, id))) {
1167
+ // stamped before the read: a write during it moves the stamp again
1168
+ w.stamps.set(id, stampOf(join(dir, id)))
1169
+ w.held.set(id, readOne(dir, id))
1170
+ } else {
1171
+ w.held.delete(id)
1172
+ w.stamps.delete(id)
1173
+ }
1112
1174
  }
1113
1175
  w.dirty.clear()
1114
1176
  const out: ReadAll = { items: [], broken: [] }
@@ -0,0 +1,59 @@
1
+ // the house secret manager as a repo config spells it: `credsCommand` writes,
2
+ // `credsReadCommand` reads, the repo's own line before the house's. Every
3
+ // write goes through `storeArgv`: `sk secret set` with the terminal on stdin,
4
+ // the hub with the pasted value on stdin. A value never rides argv, a log or
5
+ // an answer: a failure line comes back with it replaced by ‹value›.
6
+ import { existsSync } from 'fs'
7
+ import { basename, join } from 'path'
8
+ import { gitRoot } from '../core/git-root.ts'
9
+ import { houseRootOf } from '../home/home-start.ts'
10
+ import { loadIdentities, speakerOf } from '../identities/identities.ts'
11
+ import { loadRepoConfig, type RepoConfig } from '../repo-config.ts'
12
+
13
+ export type SecretsWhere = { repos: string[]; identity: string | null; own: RepoConfig | null; house: RepoConfig | null }
14
+
15
+ export async function secretsWhere(cwd: string): Promise<SecretsWhere> {
16
+ const root = gitRoot(cwd)?.top ?? cwd
17
+ const own = existsSync(join(root, 'repo.config.ts')) ? await loadRepoConfig(root) : null
18
+ const houseRoot = houseRootOf(cwd)
19
+ const house = houseRoot == null ? null : houseRoot === root ? own : await loadRepoConfig(houseRoot).catch(() => null)
20
+ const identity = speakerOf(own?.speaksAs, await loadIdentities({ cwd }))?.id ?? null
21
+ return { repos: [...new Set([own?.name ?? basename(root), basename(root)])], identity, own, house }
22
+ }
23
+
24
+ /** a refusal said as one line, never a stack */
25
+ export class NoManager extends Error {}
26
+
27
+ export function managerTemplate(w: SecretsWhere, key: 'credsReadCommand' | 'credsCommand'): string {
28
+ const t = w.own?.[key] ?? w.house?.[key]
29
+ if (w.own == null && w.house == null) throw new NoManager('FAIL not inside a house repo: run it from a repo that loads the house wiki')
30
+ if (t == null || t.trim() === '') throw new NoManager(`FAIL no ${key} in this repo's repo.config.ts nor the house's: nothing knows how to reach the secret manager`)
31
+ return t
32
+ }
33
+
34
+ /** the one argv every write runs; the value goes on its stdin */
35
+ export const storeArgv = (template: string, name: string, account?: string): string[] =>
36
+ [...template.trim().split(/\s+/).map((x) => x.replaceAll('{name}', name)), ...(account != null ? [account] : [])]
37
+
38
+ export type Stored = { ok: true } | { ok: false; why: string }
39
+ export type SecretStore = (name: string, value: string) => Promise<Stored>
40
+
41
+ /** every place the value shows in a line, replaced */
42
+ export const redact = (text: string, value: string): string => (value === '' ? text : text.replaceAll(value, '‹value›'))
43
+
44
+ /** a store through the repo's `credsCommand`, as `sk secret set` runs it, the value on stdin */
45
+ export function managerStore(cwd: string): SecretStore {
46
+ return async (name, value) => {
47
+ let template: string
48
+ try {
49
+ template = managerTemplate(await secretsWhere(cwd), 'credsCommand')
50
+ } catch (e) {
51
+ return { ok: false, why: (e as Error).message }
52
+ }
53
+ const p = Bun.spawn(storeArgv(template, name), { cwd, env: process.env, stdin: new Blob([value]), stdout: 'ignore', stderr: 'pipe' })
54
+ const err = await new Response(p.stderr).text()
55
+ if ((await p.exited) === 0) return { ok: true }
56
+ const tail = err.trim().split('\n').slice(-2).join(' ')
57
+ return { ok: false, why: redact(`${template.trim().split(/\s+/)[0]} exited ${p.exitCode}${tail !== '' ? `: ${tail}` : ''}`, value) }
58
+ }
59
+ }
@@ -0,0 +1,2 @@
1
+ /** a secret name the manager may be handed: no leading dash (it would read as a flag), no space, no shell sign */
2
+ export const SECRET_NAME = /^[A-Za-z0-9][A-Za-z0-9._@/-]*$/
@@ -68,6 +68,16 @@ export const ColCard = observer(({ app, col, id }: { app: RepoSt; col: string; i
68
68
  ) : null}
69
69
  {i.artifact?.url != null ? <div className="row"><a href={i.artifact.url} target="_blank" rel="noreferrer">mint ↗</a></div> : null}
70
70
  {i.artifact?.steps != null ? <div className="row"><div>{i.artifact.steps.map((s, n) => <span key={n}>{n + 1}. {s}<br /></span>)}</div></div> : null}
71
+ {/* a credential ask takes its value here: a password field per secret it names, sent once, never shown */}
72
+ {askFile != null && i.severity != null ? (i.ask?.secrets ?? []).map((name) => (
73
+ <div className="row" key={name}>
74
+ <input type="password" autoComplete="off" spellCheck={false} placeholder={`paste the token for ${name}`} value={c.secretDrafts.get(name) ?? ''}
75
+ onChange={(e) => c.setSecretDraft(name, e.target.value)}
76
+ onKeyDown={(e) => { if (e.key === 'Enter') void c.storeSecret(askFile, name) }} />
77
+ <button onClick={() => void c.storeSecret(askFile, name)}>store</button>
78
+ </div>
79
+ )) : null}
80
+ {c.secretNote !== '' ? <div className="said">✓ {c.secretNote}</div> : null}
71
81
  {askFile != null && i.severity != null ? (
72
82
  <div className="row">
73
83
  <input placeholder="proof URL (optional)" value={c.proofDraft} onChange={(e) => runInAction(() => { c.proofDraft = e.target.value })} />
@@ -7,6 +7,7 @@ import { makeAutoObservable, runInAction } from 'mobx'
7
7
  import type { RepoSt } from './repo-st.ts'
8
8
  import type { Col, ColMeta, HubProblem, Resource } from './hub-types.ts'
9
9
  import type { PlanRow } from '../../plan/planner.ts'
10
+ import type { SecretAnswer } from '../../collections/actions.ts'
10
11
  import { readScreen, SCREEN_WRITE_MS, writeScreen } from './screen-cache.ts'
11
12
  import { ownTrouble, reach } from './reach.ts'
12
13
 
@@ -58,6 +59,10 @@ export class ColsSvc {
58
59
  actErr = ''
59
60
  remarkDraft = ''
60
61
  proofDraft = ''
62
+ /** a value pasted under a credential ask, by secret name: in memory only, never kept, gone once sent */
63
+ secretDrafts = new Map<string, string>()
64
+ /** what the last store answered: stored, then the check's verdict */
65
+ secretNote = ''
61
66
  /** user fold choices win; default = open when the section holds needs */
62
67
  foldOverride = new Map<string, boolean>()
63
68
  /** the viewer's fold choices on the table groups (`checks:pass`,
@@ -245,30 +250,56 @@ export class ColsSvc {
245
250
  this.actErr = ''
246
251
  this.remarkDraft = ''
247
252
  this.proofDraft = ''
253
+ this.secretDrafts.clear()
254
+ this.secretNote = ''
248
255
  }
249
256
 
250
- private async act(path: string, body: Record<string, unknown>): Promise<boolean> {
257
+ /** the act's json answer, null when it failed (actErr says why) */
258
+ private async act<T = unknown>(path: string, body: Record<string, unknown>): Promise<T | null> {
251
259
  this.actErr = ''
252
260
  try {
253
261
  const r = await reach(this.st.url(`/api/act/${path}`), { method: 'POST', body: JSON.stringify(body) })
254
262
  if (!r.ok) throw new Error(await r.text())
263
+ const answer = (await r.json()) as T
255
264
  await this.poll(true)
256
- return true
265
+ return answer
257
266
  } catch (e) {
258
267
  runInAction(() => { this.actErr = ownTrouble(e, this.st.home.machine) })
259
- return false
268
+ return null
260
269
  }
261
270
  }
262
271
 
263
- askDone(file: string): Promise<boolean> {
272
+ async askDone(file: string): Promise<boolean> {
264
273
  const url = this.proofDraft.trim()
265
- return url !== '' ? this.act('ask-proof', { file, url }) : this.act('ask-done', { file })
274
+ return (await (url !== '' ? this.act('ask-proof', { file, url }) : this.act('ask-done', { file }))) != null
266
275
  }
267
276
  async remark(body: Record<string, unknown>): Promise<void> {
268
277
  const text = this.remarkDraft.trim()
269
278
  if (text === '') return
270
279
  // draft survives a failed send, so nothing typed is ever erased
271
280
  const ok = await this.act('remark', { ...body, text })
272
- if (ok) runInAction(() => { this.remarkDraft = '' })
281
+ if (ok != null) runInAction(() => { this.remarkDraft = '' })
282
+ }
283
+
284
+ setSecretDraft(name: string, value: string): void {
285
+ this.secretDrafts.set(name, value)
286
+ }
287
+
288
+ /** the pasted value goes to the hub once and leaves the page: the field
289
+ * clears whatever the answer, a failure included */
290
+ async storeSecret(file: string, name: string): Promise<void> {
291
+ const value = this.secretDrafts.get(name) ?? ''
292
+ if (value.trim() === '') return
293
+ this.secretDrafts.delete(name)
294
+ this.secretNote = ''
295
+ const a = await this.act<SecretAnswer>('ask-secret', { file, name, value })
296
+ if (a == null) return
297
+ runInAction(() => {
298
+ // a passing check archived the ask: its page is now the done one
299
+ if (a.check === 'passed') this.select('asks', `ask:done/${file}`)
300
+ this.secretNote = a.check === 'passed' ? `stored ${a.stored}: the check passes, the ask is archived`
301
+ : a.check === 'none' ? `stored ${a.stored}: this ask has no check, click done once every value is in`
302
+ : `stored ${a.stored}, but the check still fails: ${a.why}`
303
+ })
273
304
  }
274
305
  }
@@ -437,6 +437,7 @@ kbd{background:var(--panel2);border:1px solid var(--line);border-radius:4px;padd
437
437
  .colcard .cand{background:var(--bg);border:1px solid var(--line);border-radius:3px;padding:var(--s2) var(--s3);margin-top:var(--s2)}
438
438
  .colcard .candhint{color:var(--dim);font-size:12.5px;white-space:pre-wrap}
439
439
  .colcard .err,.assetrem .err{color:var(--red);margin-top:var(--s2);font-size:12.5px}
440
+ .colcard .said{color:var(--ok);margin-top:var(--s2);font-size:12.5px}
440
441
  .colcard a{color:var(--accent)}
441
442
 
442
443
  /* ONE GATE CHECK's page: small widgets on a responsive grid, each answering
@@ -0,0 +1,74 @@
1
+ // an identity's pictures as the hub shows them (wiki tools/shipkit/social-identities.md, Identities): what a picture's
2
+ // name says (`avatar-<name>[-round]`, `banner-<venue>-<rating>-<variant>`), the banners by venue, which account's row
3
+ // names each one, the rows of an account's rating. Pure, no browser
4
+ import { fileName, type DeskAccount, type DeskIdentity, type Picture, type Row } from './social-model.ts'
5
+
6
+ export const RATINGS: readonly string[] = ['sfw', 'nsfw']
7
+
8
+ /** the picture a path names, by its shown file or one of its other formats */
9
+ export const pictureOf = (i: DeskIdentity, file: string): Picture => i.pictures.find((p) => p.file === file || p.also.includes(file)) ?? { file, w: null, h: null, also: [] }
10
+
11
+ /** a row's pictures, one each however many of its formats the row names */
12
+ export function rowPictures(i: DeskIdentity, files: readonly string[]): Picture[] {
13
+ const out: Picture[] = []
14
+ for (const f of files) {
15
+ const p = pictureOf(i, f)
16
+ if (!out.some((x) => x.file === p.file)) out.push(p)
17
+ }
18
+ return out
19
+ }
20
+
21
+ export type Facts = { kind: 'avatar' | 'banner' | 'other'; venue: string; rating: string; label: string }
22
+
23
+ /** what a picture's name says; its label the words after its kind, venue and identity: « sfw · a », « nsfw · round » */
24
+ export function factsOf(file: string, identity: string): Facts {
25
+ const name = fileName(file).replace(/\.\w+$/, '')
26
+ const [head = '', ...tokens] = name.split('-')
27
+ if (head !== 'avatar' && head !== 'banner') return { kind: 'other', venue: '', rating: '', label: name }
28
+ const r = tokens.findIndex((t) => RATINGS.includes(t))
29
+ const venue = head === 'banner' && r > 0 ? tokens.slice(0, r).join('-') : ''
30
+ const words = (venue === '' ? tokens : tokens.slice(r)).filter((t) => t !== identity)
31
+ return { kind: head, venue, rating: r === -1 ? '' : tokens[r]!, label: words.join(' · ') || head }
32
+ }
33
+
34
+ /** the banners by venue, in the order of the identity's accounts, then the venues no account names, then the
35
+ * banners whose name says no venue; each group named by its account: « Discord · splash » */
36
+ export function bannerGroups(i: DeskIdentity): { venue: string; title: string; pictures: Picture[] }[] {
37
+ const groups = new Map<string, Picture[]>()
38
+ for (const p of i.pictures) {
39
+ const f = factsOf(p.file, i.id)
40
+ if (f.kind === 'banner') groups.set(f.venue, [...(groups.get(f.venue) ?? []), p])
41
+ }
42
+ const rank = (venue: string): number => {
43
+ if (venue === '') return Number.MAX_SAFE_INTEGER
44
+ const n = i.accounts.findIndex((a) => a.id === venue.split('-')[0])
45
+ return n === -1 ? i.accounts.length : n
46
+ }
47
+ const title = (venue: string): string => {
48
+ if (venue === '') return 'banners'
49
+ const [first = '', ...rest] = venue.split('-')
50
+ return [i.accounts.find((a) => a.id === first)?.name ?? first, ...rest].join(' · ')
51
+ }
52
+ return [...groups]
53
+ .sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b))
54
+ .map(([venue, pictures]) => ({ venue, title: title(venue), pictures: pictures.sort((x, y) => x.file.localeCompare(y.file)) }))
55
+ }
56
+
57
+ /** an account's own rows: the ones the identity's profile does not give it as they are */
58
+ const ownRows = (i: DeskIdentity, a: DeskAccount): Row[] => a.rows.filter((r) => !i.rows.some((s) => s.field === r.field && s.value === r.value))
59
+
60
+ /** every account whose own row names the picture: « X banner », « Discord icon » */
61
+ export const usedBy = (i: DeskIdentity, p: Picture): string[] =>
62
+ i.accounts.flatMap((a) => ownRows(i, a).filter((r) => r.files.some((f) => f === p.file || p.also.includes(f))).map((r) => `${a.name} ${r.field}`))
63
+
64
+ /** the account's `rating` row, its first word: `sfw`, `nsfw`, or '' when it names none */
65
+ export const ratingOf = (a: DeskAccount): string => (a.rows.find((r) => r.field === 'rating')?.value.trim().split(/\s/)[0] ?? '').toLowerCase()
66
+
67
+ /** a row for the other rating, `avatar nsfw` on an sfw account: not this venue's */
68
+ export function otherRating(field: string, rating: string): boolean {
69
+ const last = field.trim().split(/\s+/).pop() ?? ''
70
+ return rating !== '' && RATINGS.includes(last) && last !== rating
71
+ }
72
+
73
+ /** a row's value is more than its paths: a note to show under its pictures */
74
+ export const hasNote = (r: Row): boolean => r.value.replace(/,/g, ' ').split(/\s+/).filter(Boolean).join(' ') !== r.files.join(' ')