rvlib-shipkit 2.9.0 → 2.11.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 (75) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/package.json +1 -1
  3. package/src/cli/cmd_Media.ts +164 -0
  4. package/src/cli/cmd_Review.ts +2 -1
  5. package/src/cli/family-pages.ts +1 -0
  6. package/src/cli/registry.ts +2 -0
  7. package/src/collections/pings.ts +6 -4
  8. package/src/core/app-icon.ts +17 -4
  9. package/src/core/scratch-objects.ts +56 -0
  10. package/src/core/trace-audit.ts +13 -1
  11. package/src/home/home-paths.ts +4 -0
  12. package/src/home/home-routes.ts +36 -2
  13. package/src/home/hubs.ts +5 -0
  14. package/src/home/inbox-shape.ts +182 -0
  15. package/src/home/inbox.ts +48 -0
  16. package/src/home/run-daemon.ts +12 -2
  17. package/src/home/serve-web.ts +155 -16
  18. package/src/ledger/git-scan.ts +73 -25
  19. package/src/ledger/repo-view.ts +2 -22
  20. package/src/media-kinds.ts +7 -0
  21. package/src/media-store/content.ts +51 -0
  22. package/src/media-store/daemon.ts +91 -0
  23. package/src/media-store/db.ts +74 -0
  24. package/src/media-store/fact.ts +9 -0
  25. package/src/media-store/kind.ts +44 -0
  26. package/src/media-store/purge.ts +139 -0
  27. package/src/media-store/remote.ts +93 -0
  28. package/src/media-store/space.ts +124 -0
  29. package/src/media-store/sync.ts +101 -0
  30. package/src/media-store/upload.ts +98 -0
  31. package/src/repo-config.ts +4 -0
  32. package/src/review/anim.ts +6 -5
  33. package/src/review/cells.ts +552 -0
  34. package/src/review/format.ts +1 -1
  35. package/src/review/media-kind.ts +84 -0
  36. package/src/review/media-read.ts +48 -0
  37. package/src/review/model.ts +43 -5
  38. package/src/review/previews.ts +153 -0
  39. package/src/review/routes.ts +105 -47
  40. package/src/review/store.ts +106 -45
  41. package/src/review/trailer-desk.ts +79 -46
  42. package/src/review/trailer-media.ts +163 -0
  43. package/src/review/trailer-routes.ts +5 -2
  44. package/src/serve/hub-app/home-st.ts +39 -9
  45. package/src/serve/hub-app/home.html +2 -1
  46. package/src/serve/hub-app/hub-app.tsx +7 -23
  47. package/src/serve/hub-app/icons.tsx +2 -0
  48. package/src/serve/hub-app/inbox-st.ts +144 -0
  49. package/src/serve/hub-app/inbox-view.tsx +205 -0
  50. package/src/serve/hub-app/inbox.css +73 -0
  51. package/src/serve/hub-app/item-view.tsx +19 -0
  52. package/src/serve/hub-app/keys.ts +4 -3
  53. package/src/serve/hub-app/palette-st.ts +2 -1
  54. package/src/serve/hub-app/project-list.tsx +1 -0
  55. package/src/serve/hub-app/projects-svc.ts +1 -1
  56. package/src/serve/hub-app/repo-st.ts +1 -1
  57. package/src/serve/hub-app/review/kind-view.tsx +21 -22
  58. package/src/serve/hub-app/review/kit.tsx +11 -12
  59. package/src/serve/hub-app/review/review-board.tsx +15 -13
  60. package/src/serve/hub-app/review/review-cells.tsx +241 -0
  61. package/src/serve/hub-app/review/review-kit.ts +79 -0
  62. package/src/serve/hub-app/review/review-list.tsx +87 -122
  63. package/src/serve/hub-app/review/review-page.tsx +22 -79
  64. package/src/serve/hub-app/review/review-st.ts +269 -698
  65. package/src/serve/hub-app/review/review-thread.tsx +302 -0
  66. package/src/serve/hub-app/review/review-views.tsx +322 -253
  67. package/src/serve/hub-app/review/thread-st.ts +770 -0
  68. package/src/serve/hub-app/review.css +235 -91
  69. package/src/serve/hub-runtime.ts +9 -4
  70. package/src/serve/serve-hub.ts +4 -1
  71. package/src/serve/warm-cell.ts +6 -1
  72. package/src/trailer/footage.ts +6 -2
  73. package/src/trailer/passage.ts +4 -2
  74. package/src/trailer/prune.ts +6 -10
  75. package/src/serve/hub-app/review/review-answer.tsx +0 -249
package/CHANGELOG.md CHANGED
@@ -1,3 +1,26 @@
1
+ ## 2.11.0
2
+
3
+ - **One media store for any kind of media, and the trailer renders join it.** `src/review/space/` becomes `src/media-store/`, the machine's one store: a caller writes a `MediaKind` (where its files live in a repo, what they are, what stays on the disk) and adds it to `src/media-kinds.ts`; the store does the index, the upload, the signed URL, the fetch back and the purge. Keys are `<kind>/<sha256>.<ext>`. Review is the kind `review`, unchanged on the Space. The trailer renders are the kind `trailer`: each settled render's video and strip (the desk's clones in `.shipkit/cache/trailer-view/`, recorded by the daemon even when the desk never opened) and each kept version's own files go up; the newest render of each live cut and a render an open frame note was written on stay on the disk, the rest goes once quiet for 14 days and only after its bytes hash to its key. The desk plays a render the disk let go from a URL signed on the CDN edge; a new note fetches its video back; `sk trailer clip --version` fetches a version's video back. `sk trailer prune` no longer deletes views: an old render was lost there before it went up. A purge never deletes a file a process holds open. The verbs move: `sk media`, `sk media upload [--kind]`, `sk media purge [--kind] [--dry --list] [--auto on|off]` replace `sk review media`, `sk review media upload` and `sk review purge`; the daemon's switch is `media-purge-auto` (off until turned on). The house config key is `serve.mediaSpace`; the index file is `media.sqlite` (`SHIPKIT_MEDIA_DB`). The purge works six files at a time and sends a review image's previews with a PUT and a HEAD each, none when they are up: 524 ms a file down to 62 ms on a fake S3 at 40 ms a request. Page: build/shipkit/media-store.md.
4
+ - **Review media go up to a private S3 bucket, and the disk lets the old ones go.** Every media file of a card (image, clip, poster, sound, waveform, tile) is known by its sha256: `item.json` holds `media`, `{ sha, size, type }` per file name, written by every writer of the head, and filled on an old head at its next index. The bucket keeps each content once, `review/<sha256>.<ext>`, private: an upload never asks a public ACL, an anonymous read is refused (`tests/review-space/space-live.test.ts`, `SHIPKIT_SPACES_LIVE=1`). The house config names it, `serve.reviewSpace: { endpoint, bucket, region, cdn, secret }`, and its key pair is read through `credsReadCommand`. The daemon syncs each house repo's store after a write, uploads what waits (a HEAD first, then a HEAD of the same size before it counts as up, retried later on a failure with one line in its log). `GET /api/review/<id>/<name>` and the preview routes answer the disk's file, else a 302 to a URL signed for one hour on the CDN edge (signed for the origin host, which the edge checks it against). A tool that needs the bytes (a preview, `sk review anim`, a poster's lit frame) fetches the file back first, checked by its sha. `sk review media` counts per store what is on the disk, up, purged, waiting and gone; `sk review media upload [--repo] [--dry]` sends every waiting file now; `sk review purge [--dry] [--older <days>] [--repo]` deletes a file only when it is up and a HEAD answers its size, never one of an active thread or of a thread with a message in the last 14 days, and sends an image's previews up first. `sk review purge --auto on` lets the daemon purge on its own under 40 GB free (off by default).
5
+ - **One machine index for every review store.** The item reads move from the json file beside each store (`.shipkit/.review-index.shipkit.json`, rewritten whole on any change, removed now) into one sqlite file in the home's state folder (`~/.config/shipkit/home/review.sqlite`, `SHIPKIT_REVIEW_DB`), beside each media file's state and each object's. The reads are kept per code hash: two copies of the lib reading one store (the daemon's, a repo's own install) had thrown each other's index away, and each paid the whole read again (2.3 s on a store of 3330 items). Only moved rows are written. It is derived: deleted, it builds again from the files, a HEAD finding what is up.
6
+ - **A head is rewritten under its lock.** `add-view`, a draft's refresh, `ready` and the media facts go through `updateHead`: under the item's lock, from the file as it is then, so two writers never lose each other's change.
7
+
8
+ - **A gate scan stores no git object.** Every key's `git add` into the scratch index wrote each blob it hashed into the repo's object store, reachable from nothing, kept two weeks by gc: one game repo held 14.3 GiB of unreachable loose objects, a 172 MB blob per trailer render under a declared ignored dir. The scan's git runs, and the trailer's world stamp, now write into an object dir of their own that sees the repo's objects as an alternate, deleted when the run returns (`src/core/scratch-objects.ts`); the ids are the same, the whole tree's file list is read inside the scan. The traced audit no longer reads a dir a probe found above a file the task read as a listing, which had widened a lint's proposal to the whole `.shipkit/cache`. A store that already holds them: `git prune -n --expire=1.hour.ago` lists them, the same without `-n` removes them, objects of the last hour left to the commits in flight.
9
+ - **One inbox for every repo, installable on a phone.** `/inbox` on the home lists everything that waits on the owner across every house repo, newest first: the review cards and questions waiting on his answer, the open asks, what is red. Each row carries its repo's icon, a kind badge, the title, its age and the card's preview thumb; what is yellow and the raised items in the agents' hands sit in one folded « can wait » section. A tap opens the item in place with its repo's own views: a card in the review thread (the same column as the repo's review page), an ask or a check in its item view (`item-view.tsx`, now shared with the repo page). On a phone it is the home's first page, one pane at a time, back returning to the list where it was. `GET /api/inbox` on the daemon aggregates each repo's review thread index and its hub's warm rows, no store of its own: `?list=main|yellow`, `offset`, `limit`, an ETag (304 on a poll that changed nothing), counts per repo that match each repo's own badges. Measured on this machine (19 repos, 52 rows and 93 folded): 12 ms warm, 0.3 to 0.8 s on the first reads after a daemon restart.
10
+ - **The home opens through the tailnet name, and only through it.** Bun's dev server answered any Host but a loopback one with 403 « Blocked: Host header does not match the dev server », so the page never opened behind `tailscale serve`. The page bundle now runs on a loopback port of its own behind the web, which forwards to it, hot reload socket included, once the Host is a loopback name or the tailnet name the house declares (`serve.publicHost`, served to the web in `/api/home/repos.json`); any other Host gets 403. The page's files are gzipped for a browser that takes it (the dev bundle: 3.3 MB to 0.65 MB).
11
+ - **The home installs as an app.** `/manifest.webmanifest` (standalone, starts on `/inbox`), the house repo's icon edge to edge at 180, 192 and 512 px (`/api/home/icon/<px>.png`, `appIconPngs(…, 'square')`), the apple meta tags, the safe area kept clear. No service worker.
12
+ - **A ping opens its item.** A hub in the home pings with a link to the inbox on that item (`https://<publicHost>:<home port>/inbox?open=<repo>/<id>`), or on the list for several. `PingIo.link` is a function of what is pinged.
13
+
14
+ ## 2.10.0
15
+
16
+ - **Every old review card reads well as a thread, and his draft survives a new version.** A version that lands while he writes leaves his draft on the version he started it on (« move it to v4 / keep it on v3 »), a draft orphaned under an older version is found again, and what he types while an answer is on its way stays. The card opened with none named stays open when a poll reorders the list. An agent's word goes read when its cell shows with the tab visible, and `POST …/read` takes `{ of }` so only the words drawn are marked. The thread index is kept per store, so two repos' pages keep their 304s.
17
+ - **Views are lettered, never numbered: `3.A`, `3.B`, then `AA`.** In the page (sub cells, rows, contents, verdict notes, the pick) and the CLI (`[B voice 1]`, `view B added`).
18
+ - **The review card reads like a notebook.** A version's gutter carries a big sticky `v3`; each view has one sticky header row (its `3.A`, title, kind, labelled OK / Fix / No, its tools). A clip opened under its row has one clock (its own bar), the downloads say « save mp4 » and « show in Finder ». The minimap (the thin strip, the contents' head, a row under the title on the phone) shows every version and, under the one he answers, a mark per view coloured by his answer, and the card's head says « 3 of 5 views waiting for you ». His draft notes are listed under their view, marked a draft the verdict sends. Long agent texts fold to « more », runs of state changes say their count and time span, forks are links, an agent with no lane names its session, a verdict on a raised item says « on the note », a view whose media the store lost says so.
19
+ - **A clip that opens on black previews on a lit frame.** A black poster (a trailer fading in) is previewed from the first frame of its clip at 10, 25 or 50 % of its length that is not black, cached like every preview.
20
+ - **The review card reads as one chat of framed cells.** The open card is one thread top to bottom, the newest at the bottom, the column opening on the newest version (or the agent word he has not read, or the version an old link names), his answer box pinned under it. Every version, verdict, reply and note is a framed cell with a header bar (who, when, the kind, `v2`, fold, copy the id); a folded cell is its header and one line, and loads no media. Inside a version each view is its own numbered sub cell (`3.2`) with a big title and its kind, drawn as before (image, the four compare modes, clip, sound, gallery, option rows), and what each answer said on it (rectangles in his pink, reactions, words) sits right under it. A verdict points back at its version and lists his notes, each a click from its view. A contents strip lists every version, view, verdict and reply, a click unfolds and scrolls there: beside the cells on a wide column, else a thin strip of version pills that opens it as a sheet. One word box sends a verdict with his marks or a reply alone (⌘Enter); his draft starts empty on each version. The list reads `GET /api/review/threads` a page at a time, its search and filters asked of the server; the thread reads `GET /api/review/threads/<id>`; images come at the column's or the list's size, the full file only on zoom. On pkm-multi a card's title shows in 0.52 s warm (was 0.8 to 1.8 s) and 4.0 s cold (was 6.7 to 7.3 s), and a card open moves 0.24 to 0.5 MB of review data (was 9 MB and more). The phone shows the same thread one pane at a time, the verdicts and « Reply » in one row under the thumb. The old layout (`top`, `left`, `auto`, the answer column) is gone; `GET /api/review/board` serves the dispatcher's board; `GET /api/review` stays for pkm-multi's admin only.
21
+ - **A review card reads as one thread of cells, and the hub can fetch one page and one thread.** A supersedes chain (v1, v2, v3…) folds at read time into one thread, nothing rewritten: each version, verdict, reply, raised note and state change is a cell in time order, with a one line summary and its default fold (`src/review/cells.ts`). `GET /api/review/threads` answers one page of the list (the waiting cards first, handled ones with `handled=1`, `subject`, `whose`, `status`, `lane`, a search over every version and message, `offset`, `limit`), about 1 to 6 KB where the whole list was 1.1 MB gzipped. `GET /api/review/threads/<id>` answers one thread by any of its ids, an old version's included. Both carry an ETag.
22
+ - **Review previews: a thumb and a fit size, made once per image.** `GET /api/review/<id>/preview/thumb|fit/<name>`, a webp 480 or 1600 px wide, kept in `.shipkit/cache/review-previews/` instead of the store's `.thumbs/` (that folder can be deleted); the active cards' previews are made ahead in the background. `…/thumb/<name>` answers the thumb preview.
23
+
1
24
  ## 2.9.0
2
25
 
3
26
  - **`sk fleet --update` commits and pushes each bump.** Every repo the update moved gets one commit of package.json and its lock alone, by pathspec, through the repo's own hooks: `chore(deps): rvlib-shipkit <range>`, then the plain push of `sk fleet push`. A repo whose manifest held changes before the update, whose package.json moved more than the bump, mid-merge, mid-rebase, on a detached HEAD or nested in another repo is skipped, its bump left in the tree and the command to run printed. A refused hook, a failed push or a branch behind its upstream is a FAIL line, and the command exits 1. `--no-commit` leaves every bump in its tree, as before.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rvlib-shipkit",
3
- "version": "2.9.0",
3
+ "version": "2.11.0",
4
4
  "funding": "https://github.com/sponsors/rvion",
5
5
  "description": "All-in-one repo companion: ci gate (task DAG), auto-discovered health checks, release-contract fulfillness, asks queue, md-wiki tools, asset atelier, live tui",
6
6
  "license": "MIT",
@@ -0,0 +1,164 @@
1
+ // sk media: the machine's one media store (media-store/, wiki build/shipkit/media-store.md): what each kind of each repo
2
+ // holds on the disk and in the private Space, every waiting file sent up now, the disk freed of what the Space holds.
3
+ // Every module loads inside execute: the cli registers this file on every `sk` call
4
+ import { Command, Option } from 'clipanion'
5
+
6
+ const DETAILS = `the machine's one media store: every media file a kind names (review: a card's files; trailer: each render's video and strip, a kept version's own) is known by its sha256, goes up to the owner's private Space as <kind>/<sha256>.<ext>, and leaves the disk once the Space holds it and its kind no longer pins it; it comes back on demand. One sqlite index for the machine. Page: wiki build/shipkit/media-store.md`
7
+
8
+ type Ctx = { stdout: NodeJS.WritableStream; stderr: NodeJS.WritableStream }
9
+ type Kind = import('../media-store/kind.ts').MediaKind
10
+
11
+ interface Here {
12
+ out: (l: string) => void
13
+ err: (l: string) => void
14
+ /** each kind asked with its store in the repo asked, the kinds the repo holds none of left out */
15
+ stores: { kind: Kind; dir: string; root: string }[]
16
+ }
17
+
18
+ async function run(context: Ctx, o: { repo?: string | undefined; kind?: string | undefined }, body: (h: Here) => Promise<number>): Promise<number> {
19
+ const out = (l: string): void => void context.stdout.write(`${l}\n`)
20
+ const err = (l: string): void => void context.stderr.write(`${l}\n`)
21
+ try {
22
+ const { findRepoRoot } = await import('../ts/config.ts')
23
+ const { MEDIA_KINDS } = await import('../media-kinds.ts')
24
+ const { existsSync } = await import('node:fs')
25
+ const { basename, dirname, join } = await import('node:path')
26
+ const here = findRepoRoot(process.cwd())
27
+ const root = o.repo === undefined || o.repo === basename(here) ? here : join(dirname(here), o.repo)
28
+ if (!existsSync(root)) throw new Error(`no repo ${root}`)
29
+ const kinds = MEDIA_KINDS.filter((k) => o.kind === undefined || k.kind === o.kind)
30
+ if (kinds.length === 0) throw new Error(`--kind ${o.kind}? the kinds: ${MEDIA_KINDS.map((k) => k.kind).join(', ')}`)
31
+ const stores = kinds.flatMap((kind) => {
32
+ const dir = kind.storeOf(root)
33
+ return dir && existsSync(dir) ? [{ kind, dir, root }] : []
34
+ })
35
+ return await body({ out, err, stores })
36
+ } catch (e) {
37
+ err(`FAIL: media: ${e instanceof Error ? e.message : String(e)}`)
38
+ return 1
39
+ }
40
+ }
41
+
42
+ const repoOpt = (): string | undefined => Option.String('--repo', { description: 'a sibling repo by name, in place of this one' })
43
+ const kindOpt = (): string | undefined => Option.String('--kind', { description: 'one kind alone: review, trailer' })
44
+
45
+ export class MediaCommand extends Command {
46
+ static override paths = [['media']]
47
+ static override usage = Command.Usage({
48
+ category: 'Media',
49
+ description: 'the media store per repo and kind: on the disk, up in the Space, purged, waiting, gone',
50
+ details: `${DETAILS}\n\nThis repo's stores are synced into the index first, then every store the index knows prints its counts and bytes. A file is local (on the disk), up (in the Space), purged (up, gone from the disk), waiting (on the disk, not up yet) or gone (neither).`,
51
+ examples: [['where the media stand', 'sk media']],
52
+ })
53
+ async execute(): Promise<number> {
54
+ return run(this.context, {}, async (h) => {
55
+ const { syncKind, mediaCounts } = await import('../media-store/sync.ts')
56
+ const { mb } = await import('../media-store/upload.ts')
57
+ const { findRepoRoot } = await import('../ts/config.ts')
58
+ const { basename } = await import('node:path')
59
+ for (const s of h.stores) {
60
+ const r = await syncKind(s.kind, s.dir, { fill: 0 })
61
+ if (r.unknown > 0) h.out(`${s.kind.kind}: ${r.unknown} files this repo names are on neither the disk nor in the Space: deleted before they went up`)
62
+ if (r.left > 0) h.out(`${s.kind.kind}: ${r.left} files of this repo are not hashed yet: sk media upload hashes them`)
63
+ }
64
+ const n = (c: { n: number; bytes: number }): string => `${c.n} (${mb(c.bytes)})`
65
+ for (const c of mediaCounts()) {
66
+ h.out(`${basename(findRepoRoot(c.store))} ${c.kind} local ${n(c.local)} up ${n(c.up)} purged ${n(c.purged)} waiting ${n(c.waiting)} gone ${n(c.gone)}`)
67
+ if (c.failing.n > 0) h.out(` ${c.failing.n} failing uploads, the last error: ${c.failing.error}`)
68
+ }
69
+ return 0
70
+ })
71
+ }
72
+ }
73
+
74
+ export class MediaUploadCommand extends Command {
75
+ static override paths = [['media', 'upload']]
76
+ static override usage = Command.Usage({
77
+ category: 'Media',
78
+ description: 'every waiting file of the media store up to the Space now: resumable, dedup by sha',
79
+ details: `${DETAILS}\n\nThe files not hashed yet are hashed first. A file the Space already holds (same key, same size) is only marked up. The daemon does the same in the background; this runs it now, to the end.`,
80
+ examples: [['this repo', 'sk media upload'], ['what pkm-multi would send of its trailers', 'sk media upload --repo pkm-multi --kind trailer --dry']],
81
+ })
82
+ repo = repoOpt()
83
+ kind = kindOpt()
84
+ dry = Option.Boolean('--dry', false, { description: 'count what would go up, send nothing' })
85
+ jobs = Option.String('--jobs', { description: 'uploads at once (6)' })
86
+ async execute(): Promise<number> {
87
+ return run(this.context, { repo: this.repo, kind: this.kind }, async (h) => {
88
+ const { resolve } = await import('node:path')
89
+ const { syncKind } = await import('../media-store/sync.ts')
90
+ const { mb, uploadWaiting, waitingObjects } = await import('../media-store/upload.ts')
91
+ const { machineSpace } = await import('../media-store/space.ts')
92
+ let failed = 0
93
+ for (const st of h.stores) {
94
+ const t0 = Date.now()
95
+ const s = await syncKind(st.kind, st.dir, { fill: this.dry ? 0 : Infinity })
96
+ const waiting = waitingObjects({ store: resolve(st.dir), now: Number.MAX_SAFE_INTEGER })
97
+ const bytes = waiting.reduce((n, w) => n + w.size, 0)
98
+ h.out(`${st.kind.kind} ${st.dir}: ${s.files} files indexed${s.filled > 0 ? `, ${s.filled} hashed` : ''}${s.left > 0 ? `, ${s.left} not hashed (no --dry to hash them)` : ''}; ${waiting.length} objects waiting (${mb(bytes)})`)
99
+ if (this.dry || waiting.length === 0) continue
100
+ const { space, why } = await machineSpace()
101
+ if (!space) throw new Error(why)
102
+ const r = await uploadWaiting(space, { store: resolve(st.dir), jobs: Number(this.jobs ?? 6) || 6, now: Number.MAX_SAFE_INTEGER, say: h.out })
103
+ const sec = (Date.now() - t0) / 1000
104
+ h.out(`${r.up} up (${mb(r.bytes)}), ${r.there} already there, ${r.failed.length} failed, in ${sec.toFixed(0)} s${r.bytes > 0 ? ` (${mb(r.bytes / sec)}/s)` : ''}`)
105
+ for (const f of r.failed.slice(0, 5)) h.err(`FAIL: ${f.key}: ${f.error}`)
106
+ failed += r.failed.length
107
+ }
108
+ return failed > 0 ? 1 : 0
109
+ })
110
+ }
111
+ }
112
+
113
+ export class MediaPurgeCommand extends Command {
114
+ static override paths = [['media', 'purge']]
115
+ static override usage = Command.Usage({
116
+ category: 'Media',
117
+ description: 'free the disk of media the Space holds, never a file its kind pins or a recent one',
118
+ details: `${DETAILS}\n\nA file goes only when the index says it is up AND a HEAD answers its size AND its kind agrees (review sends an image's previews up first; trailer checks the file hashes to its key), and never while a process holds it open. Kept: what each kind pins (review: an active card; trailer: the newest render of each cut, a render an open frame note was written on) and every file used in the last --older days (14). Oldest first. A purged file comes back on demand. --auto on lets the daemon purge every kind on its own whenever the disk has under 40 GB free, until it is back over; --auto off stops it.`,
119
+ examples: [['what it would free', 'sk media purge --dry'], ['pkm-multi trailers, every file that would go', 'sk media purge --repo pkm-multi --kind trailer --dry --list'], ['the daemon purges under 40 GB free', 'sk media purge --auto on']],
120
+ })
121
+ repo = repoOpt()
122
+ kind = kindOpt()
123
+ dry = Option.Boolean('--dry', false, { description: 'print what it would free, delete nothing' })
124
+ list = Option.Boolean('--list', false, { description: 'with --dry: every file that would go, one line each' })
125
+ older = Option.String('--older', { description: 'keep the files used in the last <days> (14)' })
126
+ auto = Option.String('--auto', { description: 'on | off: the daemon purges on its own under 40 GB free' })
127
+ async execute(): Promise<number> {
128
+ return run(this.context, { repo: this.repo, kind: this.kind }, async (h) => {
129
+ const { autoPurgeOn, setAutoPurge } = await import('../media-store/daemon.ts')
130
+ if (this.auto !== undefined) {
131
+ if (this.auto !== 'on' && this.auto !== 'off') throw new Error('--auto on | off')
132
+ if (!setAutoPurge(this.auto === 'on')) throw new Error('the machine db did not take the switch')
133
+ h.out(`the daemon's purge of the media store under 40 GB free: ${this.auto}`)
134
+ return 0
135
+ }
136
+ const { freeBytes, purge, purgeCandidates, KEEP_DAYS } = await import('../media-store/purge.ts')
137
+ const { mb } = await import('../media-store/upload.ts')
138
+ const { machineSpace } = await import('../media-store/space.ts')
139
+ const { join } = await import('node:path')
140
+ const older = this.older === undefined ? KEEP_DAYS : Number(this.older)
141
+ if (!(older >= 0)) throw new Error('--older <days>: a number')
142
+ for (const st of h.stores) {
143
+ const { candidates, kept } = await purgeCandidates(st.kind, st.dir, { olderDays: older })
144
+ const bytes = candidates.reduce((n, c) => n + c.size, 0)
145
+ h.out(
146
+ `${st.kind.kind} ${st.dir}: ${candidates.length} files could go (${mb(bytes)}); kept on the disk while up: ${kept.n} files (${mb(kept.bytes)}), ${kept.pinned.n} of them pinned (${mb(kept.pinned.bytes)}); free now ${mb(freeBytes(st.dir))}; the daemon's purge: ${autoPurgeOn() ? 'on' : 'off'}`,
147
+ )
148
+ if (this.dry) {
149
+ if (this.list) for (const c of candidates) h.out(` ${join(st.dir, c.item, c.name)} ${mb(c.size)} used ${new Date(c.used).toISOString().slice(0, 10)}`)
150
+ continue
151
+ }
152
+ if (candidates.length === 0) continue
153
+ const { space, why } = await machineSpace()
154
+ if (!space) throw new Error(why)
155
+ const r = await purge(st.kind, st.dir, space, candidates, { say: h.out })
156
+ h.out(`${r.files} files purged, ${mb(r.freed)} freed${r.refused.length > 0 ? `, ${r.refused.length} kept: the Space or the kind did not confirm them` : ''}`)
157
+ for (const f of r.refused.slice(0, 5)) h.err(`WARN ${f.key}: ${f.why}`)
158
+ }
159
+ return 0
160
+ })
161
+ }
162
+ }
163
+
164
+ export const MEDIA_COMMANDS = [MediaCommand, MediaUploadCommand, MediaPurgeCommand]
@@ -289,7 +289,8 @@ export class ReviewAddViewCommand extends Command {
289
289
  if (note !== undefined) v.note = note
290
290
  const extra = h.unit?.addView ? await h.unit.addView(v, repoFlags) : {}
291
291
  const item = await addView(h.dir, id, v, extra)
292
- h.out(`${id}: view ${item.views.length} "${label}" added`)
292
+ const { viewLetter } = await import('../review/model.ts')
293
+ h.out(`${id}: view ${viewLetter(item.views.length - 1)} "${label}" added`)
293
294
  return 0
294
295
  })
295
296
  }
@@ -10,6 +10,7 @@ export const FAMILY_PAGES: Readonly<Record<string, string>> = {
10
10
  Gate: 'build/shipkit.md',
11
11
  Health: 'build/shipkit.md',
12
12
  Home: 'build/shipkit/home.md',
13
+ Media: 'build/shipkit/media-store.md',
13
14
  Refactor: 'build/typescript.md',
14
15
  Review: 'build/shipkit/review.md',
15
16
  Scaffold: 'build/pocketbase.md',
@@ -45,6 +45,7 @@ import { StartCommand } from './cmd_Start.ts'
45
45
  import { TRAILER_COMMANDS } from './cmd_Trailer.ts'
46
46
  import { SOUND_COMMANDS } from './cmd_Sound.ts'
47
47
  import { REVIEW_COMMANDS } from './cmd_Review.ts'
48
+ import { MEDIA_COMMANDS } from './cmd_Media.ts'
48
49
  import { TuiCommand } from './cmd_Tui.ts'
49
50
  import { WikiLintCommand, WikiServeCommand } from './cmd_Wiki.ts'
50
51
 
@@ -85,6 +86,7 @@ export function buildCli(): Cli {
85
86
  for (const c of TRAILER_COMMANDS) cli.register(c)
86
87
  for (const c of SOUND_COMMANDS) cli.register(c)
87
88
  for (const c of REVIEW_COMMANDS) cli.register(c)
89
+ for (const c of MEDIA_COMMANDS) cli.register(c)
88
90
  cli.register(ServeCommand)
89
91
  cli.register(PmCommand)
90
92
  cli.register(DaemonCommand)
@@ -21,9 +21,10 @@ export type PingIo = {
21
21
  notifyCommand?: string
22
22
  /** additive desktop notification on macOS */
23
23
  osascript?: boolean
24
- /** hub URL appended to the message — the OFF-MACHINE form
25
- * (serve.publicHost); a phone can't resolve localhost */
26
- link?: string
24
+ /** the url appended to the message for what it pings, in the OFF-MACHINE
25
+ * form (serve.publicHost), a phone can't resolve localhost: the home's
26
+ * inbox on that one item, or on the list for several */
27
+ link?: (fresh: NeedItem[]) => string | undefined
27
28
  }
28
29
 
29
30
  const stateDir = (root: string): string | null => (existsSync(join(root, 'node_modules')) ? join(root, 'node_modules', '.cache', 'shipkit') : null)
@@ -88,7 +89,8 @@ export function pingTick(root: string, asksDir: string, needs: NeedItem[], io: P
88
89
  savePinged(root, state.ids)
89
90
  if (fresh.length === 0) return []
90
91
  const head = fresh.slice(0, 3).map((n) => n.text.slice(0, 80)).join(' · ')
91
- const message = `${fresh.length} new item(s) need you: ${head}${fresh.length > 3 ? ' · …' : ''}${io.link != null ? ` → ${io.link}` : ''}`
92
+ const link = io.link?.(fresh)
93
+ const message = `${fresh.length} new item(s) need you: ${head}${fresh.length > 3 ? ' · …' : ''}${link != null ? ` → ${link}` : ''}`
92
94
  // item texts come from repo data — strip shell-active chars before the template substitution
93
95
  const safe = message.replace(/[`$\\'"]/g, '')
94
96
  if (io.notifyCommand != null) io.run(['sh', '-c', io.notifyCommand.replaceAll('{message}', safe)])
@@ -135,16 +135,29 @@ export async function drawAppIcon(bytes: Uint8Array, id: Identity): Promise<{ ca
135
135
  }
136
136
 
137
137
  /** the icon as pngs, one per size asked, drawn once. `plate` crops the macOS
138
- * grid's margin away, the rounded plate edge to edge (the hub's rail) */
139
- export async function appIconPngs(bytes: Uint8Array, id: Identity, sizes: number[] = [ICON_PX], crop: 'canvas' | 'plate' = 'canvas'): Promise<Buffer[]> {
138
+ * grid's margin away, the rounded plate edge to edge (the hub's rail);
139
+ * `square` fills the plate's corners with its own edge colours, edge to edge
140
+ * with no transparency (a phone's home screen cuts its own corners) */
141
+ export async function appIconPngs(bytes: Uint8Array, id: Identity, sizes: number[] = [ICON_PX], crop: 'canvas' | 'plate' | 'square' = 'canvas'): Promise<Buffer[]> {
140
142
  const { canvas } = await drawAppIcon(bytes, id)
141
- const o = crop === 'plate' ? (ICON_PX - PLATE) / 2 : 0
142
- const side = crop === 'plate' ? PLATE : ICON_PX
143
+ const o = crop === 'canvas' ? 0 : (ICON_PX - PLATE) / 2
144
+ const side = crop === 'canvas' ? ICON_PX : PLATE
145
+ const edge = (y: number): string => {
146
+ const [r, g, b] = canvas.getContext('2d').getImageData(ICON_PX / 2, y, 1, 1).data
147
+ return `rgb(${r},${g},${b})`
148
+ }
143
149
  return sizes.map((px) => {
144
150
  if (px === ICON_PX && crop === 'canvas') return canvas.toBuffer('image/png')
145
151
  const small = createCanvas(px, px)
146
152
  const ctx = small.getContext('2d')
147
153
  ctx.imageSmoothingQuality = 'high'
154
+ if (crop === 'square') {
155
+ const g = ctx.createLinearGradient(0, 0, 0, px)
156
+ g.addColorStop(0, edge(o + 2))
157
+ g.addColorStop(1, edge(o + PLATE - 3))
158
+ ctx.fillStyle = g
159
+ ctx.fillRect(0, 0, px, px)
160
+ }
148
161
  ctx.drawImage(canvas, o, o, side, side, 0, 0, px, px)
149
162
  return small.toBuffer('image/png')
150
163
  })
@@ -0,0 +1,56 @@
1
+ // git that names content without keeping it. `git add` into a scratch index
2
+ // (a cache key, a world stamp) writes every blob it hashes into the repo's
3
+ // object store, where nothing reaches it and gc keeps it two weeks: measured
4
+ // in a game repo, 14.3 GiB of unreachable loose objects, one 172 MB blob per
5
+ // trailer render. A run under `env` writes its objects into a dir of its own,
6
+ // still finds the repo's objects through the alternates, and `drop` deletes
7
+ // what it wrote. An id read under `env` stays valid; an object it names may be
8
+ // gone once dropped, so a caller reads every tree it needs before the drop.
9
+ import { mkdirSync, readdirSync, rmSync } from 'fs'
10
+ import { delimiter, join } from 'path'
11
+ import { pidAlive } from '../ledger/live-runs.ts'
12
+ import { probeGitRoot } from './git-root.ts'
13
+
14
+ export type ScratchObjects = {
15
+ /** the object dir the run writes into */
16
+ dir: string
17
+ /** spread over a git run's environment */
18
+ env: Record<string, string>
19
+ /** delete what the run wrote */
20
+ drop: () => void
21
+ }
22
+
23
+ let seq = 0
24
+ const live = new Set<string>()
25
+
26
+ /** a fresh object dir under `parent` for the git runs of one scan of `root` */
27
+ export function scratchObjects(root: string, parent: string): ScratchObjects {
28
+ const g = probeGitRoot(root).root
29
+ if (g == null) throw new Error(`not a git repository: ${root}`)
30
+ const real = process.env.GIT_OBJECT_DIRECTORY ?? join(g.commonDir, 'objects')
31
+ sweepScratchObjects(parent)
32
+ const dir = join(parent, `sk-objects-${process.pid}-${seq++}`)
33
+ mkdirSync(dir, { recursive: true })
34
+ if (live.size === 0) process.on('exit', () => { for (const d of live) rmSync(d, { recursive: true, force: true }) })
35
+ live.add(dir)
36
+ const alternates = [real, process.env.GIT_ALTERNATE_OBJECT_DIRECTORIES].filter((x) => x != null && x !== '').join(delimiter)
37
+ return {
38
+ dir,
39
+ env: { GIT_OBJECT_DIRECTORY: dir, GIT_ALTERNATE_OBJECT_DIRECTORIES: alternates },
40
+ drop: () => {
41
+ live.delete(dir)
42
+ rmSync(dir, { recursive: true, force: true })
43
+ },
44
+ }
45
+ }
46
+
47
+ /** the object dirs of processes that are gone: a killed scan leaves its own */
48
+ export function sweepScratchObjects(parent: string): void {
49
+ let names: string[]
50
+ try { names = readdirSync(parent) } catch { return }
51
+ for (const f of names) {
52
+ const m = /^sk-objects-(\d+)-\d+$/.exec(f)
53
+ if (m == null || Number(m[1]) === process.pid || pidAlive(Number(m[1]))) continue
54
+ try { rmSync(join(parent, f), { recursive: true, force: true }) } catch { /* raced: gone either way */ }
55
+ }
56
+ }
@@ -70,6 +70,18 @@ export function proposeInputs(content: string[], listed: string[]): string[] {
70
70
  return [...bytes, ...tops.filter((d) => !bytes.some((b) => under(d, b))).map((d) => `${d}/**`)].sort()
71
71
  }
72
72
 
73
+ /** the dirs a task depends on as dirs: every one it listed, and every one a
74
+ * probe found that nothing else it read sits under. A resolver stats each
75
+ * ancestor of the file it opens (a game repo's lint: `.shipkit/cache`, then each
76
+ * dir down to the module), and that answer is implied by the file's own key;
77
+ * read as a listing, it widened the proposal to the whole cache dir, renders
78
+ * included */
79
+ export function dirsRead(listed: string[], probed: string[], files: string[]): string[] {
80
+ const ancestors = new Set<string>()
81
+ for (const p of [...files, ...listed, ...probed]) for (let d = posix.dirname(p); d !== '.' && d !== '/' && !ancestors.has(d); d = posix.dirname(d)) ancestors.add(d)
82
+ return [...new Set([...listed, ...probed.filter((d) => !ancestors.has(d))])]
83
+ }
84
+
73
85
  /** trace every gate task of the repo once and report what its key misses */
74
86
  export async function traceAudit(root: string, config: RepoConfig, o: { fresh?: boolean; now?: number; env?: Record<string, string | undefined> } = {}): Promise<AuditReport> {
75
87
  const now = o.now ?? Date.now()
@@ -98,7 +110,7 @@ export async function traceAudit(root: string, config: RepoConfig, o: { fresh?:
98
110
  // Finder rewrites .DS_Store at will, and no tool's verdict reads it
99
111
  const rel = (p: string): boolean => !p.startsWith('/') && p !== '.' && !p.split('/').includes('node_modules') && !p.startsWith('.git/') && posix.basename(p) !== '.DS_Store'
100
112
  const files = [...new Set([...Object.keys(r.reads.files), ...Object.keys(r.reads.sigs ?? {}), ...Object.entries(r.reads.exists).filter(([, k]) => k === 'file').map(([p]) => p)])].filter(rel)
101
- const dirs = [...new Set([...Object.keys(r.reads.dirs ?? {}), ...Object.entries(r.reads.exists).filter(([, k]) => k === 'dir').map(([p]) => p)])].filter(rel)
113
+ const dirs = dirsRead(Object.keys(r.reads.dirs ?? {}).filter(rel), Object.entries(r.reads.exists).filter(([, k]) => k === 'dir').map(([p]) => p).filter(rel), files)
102
114
  const ignored = gitIgnored(root, [...files, ...dirs])
103
115
  const extras = ignoredFor(config.ignoredInputs, u.id)
104
116
  const missF = files.filter((p) => ignored.has(p) && !covered(p, false, extras))
@@ -65,6 +65,10 @@ export const stateFile = (dir: string): string => join(dir, 'state.json')
65
65
  /** the url prefix of a repo's hub on the home */
66
66
  export const hubBase = (name: string): string => `/r/${encodeURIComponent(name)}`
67
67
 
68
+ /** the home as the machine's other devices reach it: its tailnet name, behind \`tailscale serve --https=<home port>\`,
69
+ * which proxies to the web on 127.0.0.1 */
70
+ export const publicHome = (host: string, port = homePort()): string => `https://${host}:${port}`
71
+
68
72
  /** the home page's url as a local client reaches it (the web) */
69
73
  export const homeUrl = (port = homePort()): string => `http://127.0.0.1:${port}`
70
74
 
@@ -3,7 +3,7 @@
3
3
  // decides WHEN a hub loads and never what is true: every verdict still comes
4
4
  // from each repo's own runner and ledger. The machine resources are pm's
5
5
  // (run-pm.ts), and the page reaches them through the web at /api/pm/*.
6
- import { existsSync } from 'fs'
6
+ import { existsSync, readFileSync } from 'fs'
7
7
  import { dirname, join } from 'path'
8
8
  import { fileURLToPath } from 'url'
9
9
  import { installedVersion, isBehind } from '../fleet/scan-fleet.ts'
@@ -22,6 +22,8 @@ import { devRepos, InsightsCache, type Scope } from './insights.ts'
22
22
  import { GLOBAL_CONTEXT_EVERY_MS, houseContext, writeIfChanged } from './global-context.ts'
23
23
  import { HouseRuns } from '../serve/house-runs.ts'
24
24
  import { pushFleet } from '../fleet/push-fleet.ts'
25
+ import { appIconOf, appIconPngs, identityOfRoot } from '../core/app-icon.ts'
26
+ import { inboxResponse } from './inbox.ts'
25
27
 
26
28
  /** how far back a repo's git page lists its commits */
27
29
  export const GIT_PAGE_MS = 7 * 24 * 3600_000
@@ -64,8 +66,13 @@ export type HomeDeps = {
64
66
  widgets?: Widgets
65
67
  /** brings a repo current (modernizeCmd); resolves to its exit code */
66
68
  modernize?: (repo: WiredRepo, log: string) => Promise<number>
69
+ /** the machine's tailnet name, the house config's serve.publicHost: the one name besides localhost the web answers to */
70
+ publicHost?: string
67
71
  }
68
72
 
73
+ /** the sizes the app icon is drawn at: the phone's home screen, the manifest's two */
74
+ export const ICON_SIZES = [180, 192, 512] as const
75
+
69
76
  const CLI = fileURLToPath(new URL('../cli.ts', import.meta.url))
70
77
 
71
78
  /** what bringing a repo current runs: its first install when it has none,
@@ -164,6 +171,18 @@ export function homeRoutes(d: HomeDeps) {
164
171
  return { version: LIB_VERSION, workers: d.hubs.views(repos), active: d.state.data.active, behind, modernize, held: h == null ? null : heldText(h) }
165
172
  }
166
173
 
174
+ const icons = new Map<number, Promise<Uint8Array<ArrayBuffer> | null>>()
175
+ /** drawn once per size for the life of the daemon, from the house repo's mark */
176
+ const iconPng = (px: number): Promise<Uint8Array<ArrayBuffer> | null> => {
177
+ let p = icons.get(px)
178
+ if (p == null) {
179
+ const mark = appIconOf(d.root)
180
+ p = mark == null ? Promise.resolve(null) : appIconPngs(readFileSync(mark), identityOfRoot(d.root), [px], 'square').then(([b]) => new Uint8Array(b!))
181
+ icons.set(px, p)
182
+ }
183
+ return p
184
+ }
185
+
167
186
  const find = (name: unknown): WiredRepo | null => repos.find((r) => r.name === name) ?? null
168
187
  const body = async (req: Request): Promise<Record<string, unknown>> => (await req.json().catch(() => ({}))) as Record<string, unknown>
169
188
 
@@ -187,7 +206,22 @@ export function homeRoutes(d: HomeDeps) {
187
206
  // the web asks which page routes to serve: one per house repo
188
207
  if (path === '/api/home/repos.json') {
189
208
  if (repos.length === 0) await refresh()
190
- return Response.json({ repos: d.hubs.names() })
209
+ return Response.json({ repos: d.hubs.names(), hosts: d.publicHost == null ? [] : [d.publicHost] })
210
+ }
211
+ // everything that waits on the owner in every repo, one list (inbox.ts)
212
+ if (path === '/api/inbox') {
213
+ if (repos.length === 0) await refresh()
214
+ const down = d.hubs.views(repos).filter((v) => v.status !== 'up').map((v) => ({ repo: v.repo, why: `its hub is ${v.status}${v.note != null ? `: ${v.note}` : ''}` }))
215
+ return inboxResponse(req, d.hubs, down)
216
+ }
217
+ // the house's app icon, edge to edge: the home as an app on a phone
218
+ const icon = /^\/api\/home\/icon\/(\d+)\.png$/.exec(path)
219
+ if (icon != null) {
220
+ const px = Number(icon[1]) as (typeof ICON_SIZES)[number]
221
+ if (!ICON_SIZES.includes(px)) return new Response(`the icon is drawn at ${ICON_SIZES.join(', ')} px`, { status: 404 })
222
+ const png = await iconPng(px)
223
+ if (png == null) return new Response('the house repo has no mark to draw its icon from', { status: 404 })
224
+ return new Response(png, { headers: { 'content-type': 'image/png', 'cache-control': 'max-age=86400' } })
191
225
  }
192
226
  if (path === '/api/home/planned.json') {
193
227
  if (repos.length === 0) await refresh()
package/src/home/hubs.ts CHANGED
@@ -258,6 +258,11 @@ export class Hubs {
258
258
  return [...this.entries.keys()]
259
259
  }
260
260
 
261
+ /** every hub that is up, with its repo: what the inbox reads */
262
+ loaded(): { repo: WiredRepo; rt: LoadedHub }[] {
263
+ return [...this.entries.values()].flatMap((e) => (e.rt == null ? [] : [{ repo: e.repo, rt: e.rt }]))
264
+ }
265
+
261
266
  private view(e: Entry): WorkerView {
262
267
  const blocked = hubBlocker(e.repo.path) ?? (e.status === 'crashed' && notInstalled(e.repo.path) ? NOT_INSTALLED : null)
263
268
  return {