rvlib-shipkit 2.11.0 → 2.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (298) hide show
  1. package/CHANGELOG.md +56 -12
  2. package/README.md +1 -1
  3. package/package.json +4 -2
  4. package/src/agent-time/store.ts +2 -2
  5. package/src/check.ts +1 -1
  6. package/src/checks/SK001-package-json-shape.check.ts +4 -0
  7. package/src/checks/SK003-claude-md-shape.check.ts +1 -1
  8. package/src/checks/SK004-gitignore-policy.check.ts +27 -2
  9. package/src/checks/SK005-rvlib-versions.check.ts +1 -1
  10. package/src/checks/SK008-reviewer-agent.check.ts +2 -2
  11. package/src/checks/SK012-config-barrel-import.check.ts +1 -1
  12. package/src/checks/SK015-nested-repo.check.ts +1 -1
  13. package/src/checks/SK035-public-clean.check.ts +46 -0
  14. package/src/checks/SK036-draft-media-size.check.ts +28 -0
  15. package/src/cli/cmd_Backup.ts +152 -0
  16. package/src/cli/cmd_Ci.ts +8 -11
  17. package/src/cli/cmd_Drill.ts +145 -0
  18. package/src/cli/cmd_Home.ts +50 -3
  19. package/src/cli/cmd_Media.ts +96 -5
  20. package/src/cli/cmd_Review.ts +8 -2
  21. package/src/cli/cmd_Shot.ts +5 -2
  22. package/src/cli/cmd_Smoke.ts +4 -1
  23. package/src/cli/cmd_Social.ts +226 -0
  24. package/src/cli/cmd_Start.ts +1 -1
  25. package/src/cli/cmd_Time.ts +1 -1
  26. package/src/cli/cmd_Trailer.ts +9 -2
  27. package/src/cli/cmd_Veille.ts +173 -0
  28. package/src/cli/family-pages.ts +3 -0
  29. package/src/cli/registry.ts +13 -2
  30. package/src/cli.ts +5 -2
  31. package/src/collections/actions.ts +1 -49
  32. package/src/collections/checks.ts +2 -1
  33. package/src/collections/collection-types.ts +11 -2
  34. package/src/collections/providers.ts +4 -4
  35. package/src/collections/review.ts +2 -1
  36. package/src/collections/tests.ts +19 -8
  37. package/src/contracts/apply-contracts.ts +1 -3
  38. package/src/contracts/contract-manifests.ts +2 -3
  39. package/src/contracts/contract-types.ts +0 -1
  40. package/src/contracts/contracts-engine.ts +0 -3
  41. package/src/core/app-icon.ts +9 -3
  42. package/src/core/bun-builtins.ts +2 -2
  43. package/src/core/discover-checks.ts +37 -5
  44. package/src/core/fix-scope.ts +4 -2
  45. package/src/core/floor-resolve.ts +68 -48
  46. package/src/core/floor.ts +9 -0
  47. package/src/core/git-root.ts +24 -0
  48. package/src/core/last-good.ts +3 -1
  49. package/src/core/layout.ts +8 -0
  50. package/src/core/log-stamp.ts +36 -0
  51. package/src/core/loop-watch.ts +93 -0
  52. package/src/core/machine-link.ts +134 -0
  53. package/src/core/memory-watch.ts +41 -0
  54. package/src/core/one-way-in-policy.ts +27 -19
  55. package/src/core/run-ci.ts +6 -8
  56. package/src/core/run-fixers.ts +9 -9
  57. package/src/core/slots.ts +21 -0
  58. package/src/core/tree-rev.ts +60 -0
  59. package/src/core/unit-files.ts +42 -0
  60. package/src/drill/render.ts +140 -0
  61. package/src/drill/run.ts +269 -0
  62. package/src/fleet/scan-fleet.ts +6 -5
  63. package/src/home/daemon-jobs.ts +201 -0
  64. package/src/home/global-context.ts +34 -1
  65. package/src/home/home-routes.ts +22 -15
  66. package/src/home/hubs.ts +10 -3
  67. package/src/home/inbox-shape.ts +61 -6
  68. package/src/home/inbox.ts +75 -4
  69. package/src/home/lib-watch.ts +10 -3
  70. package/src/home/machine-stores.ts +15 -29
  71. package/src/home/run-daemon.ts +15 -18
  72. package/src/home/run-pm.ts +2 -0
  73. package/src/home/serve-daemon.ts +4 -3
  74. package/src/home/serve-web.ts +110 -1
  75. package/src/hooks/commit-message.ts +28 -19
  76. package/src/hooks/leak-guard.ts +10 -3
  77. package/src/hooks/run-hooks.ts +2 -6
  78. package/src/identities/identities.ts +334 -0
  79. package/src/identities/machine-route.ts +126 -0
  80. package/src/identities/machine.ts +62 -0
  81. package/src/init-repo.ts +1 -1
  82. package/src/ledger/check-stats.ts +10 -9
  83. package/src/ledger/gate-checks.ts +32 -1
  84. package/src/ledger/record-kept.ts +112 -0
  85. package/src/ledger/repo-view.ts +10 -0
  86. package/src/ledger/run-log.ts +17 -12
  87. package/src/ledger/run-timeline.ts +8 -4
  88. package/src/ledger/store.ts +7 -0
  89. package/src/ledger/suite-log.ts +17 -13
  90. package/src/media-kinds.ts +9 -1
  91. package/src/media-store/backup/daemon.ts +73 -0
  92. package/src/media-store/backup/keys.ts +25 -0
  93. package/src/media-store/backup/manifest.ts +193 -0
  94. package/src/media-store/backup/restore.ts +192 -0
  95. package/src/media-store/backup/run.ts +278 -0
  96. package/src/media-store/backup/secret.ts +86 -0
  97. package/src/media-store/backup/snapshot.ts +64 -0
  98. package/src/media-store/backup/sources.ts +199 -0
  99. package/src/media-store/content.ts +11 -1
  100. package/src/media-store/daemon.ts +56 -70
  101. package/src/media-store/hand.ts +58 -0
  102. package/src/media-store/put.ts +122 -0
  103. package/src/media-store/space.ts +73 -11
  104. package/src/pages/forward.ts +35 -0
  105. package/src/pages/frame-client.ts +118 -0
  106. package/src/pages/routes.ts +29 -0
  107. package/src/pages/unit.ts +92 -0
  108. package/src/plan/planner.ts +12 -0
  109. package/src/plan/repo-source.ts +19 -5
  110. package/src/reflect/transcript.ts +35 -10
  111. package/src/release/public-clean.ts +301 -0
  112. package/src/release/published-here.ts +22 -0
  113. package/src/release/run-bump.ts +2 -1
  114. package/src/release/run-release.ts +4 -1
  115. package/src/repo-config.ts +53 -2
  116. package/src/review/http.ts +16 -2
  117. package/src/review/media-kind.ts +3 -3
  118. package/src/review/media-read.ts +3 -3
  119. package/src/review/model.ts +24 -5
  120. package/src/review/notes.ts +77 -0
  121. package/src/review/project.ts +6 -38
  122. package/src/review/routes.ts +8 -13
  123. package/src/review/store.ts +46 -4
  124. package/src/review/trailer-media.ts +24 -3
  125. package/src/review/trailer-shots.ts +106 -0
  126. package/src/review/unit.ts +1 -1
  127. package/src/scaffold/files/agent-handoff.md +3 -0
  128. package/src/scaffold/files/agent-index.md +4 -12
  129. package/src/scaffold/project-scaffold.ts +5 -4
  130. package/src/serve/embed.ts +1 -1
  131. package/src/serve/hub-app/col-card.tsx +3 -17
  132. package/src/serve/hub-app/col-tables-view.tsx +2 -1
  133. package/src/serve/hub-app/cols-svc.ts +12 -14
  134. package/src/serve/hub-app/dock-st.ts +4 -2
  135. package/src/serve/hub-app/dock-view.tsx +2 -0
  136. package/src/serve/hub-app/frames-st.ts +35 -0
  137. package/src/serve/hub-app/hash-route.ts +64 -1
  138. package/src/serve/hub-app/home-st.ts +31 -7
  139. package/src/serve/hub-app/home-strip.css +9 -1
  140. package/src/serve/hub-app/home-strip.tsx +7 -6
  141. package/src/serve/hub-app/home.html +5 -0
  142. package/src/serve/hub-app/hub-app.tsx +49 -5
  143. package/src/serve/hub-app/hub.css +29 -11
  144. package/src/serve/hub-app/icons.tsx +16 -1
  145. package/src/serve/hub-app/identities-st.ts +210 -0
  146. package/src/serve/hub-app/identities-view.tsx +352 -0
  147. package/src/serve/hub-app/identities.css +48 -0
  148. package/src/serve/hub-app/identity-address.ts +52 -0
  149. package/src/serve/hub-app/inbox-st.ts +59 -6
  150. package/src/serve/hub-app/inbox-view.tsx +48 -6
  151. package/src/serve/hub-app/inbox.css +12 -1
  152. package/src/serve/hub-app/index.html +3 -0
  153. package/src/serve/hub-app/keys.ts +10 -2
  154. package/src/serve/hub-app/list-walk.ts +89 -0
  155. package/src/serve/hub-app/machine-st.ts +12 -0
  156. package/src/serve/hub-app/media-view.tsx +2 -1
  157. package/src/serve/hub-app/pages-frames.tsx +134 -0
  158. package/src/serve/hub-app/pages-svc.ts +111 -0
  159. package/src/serve/hub-app/palette-st.ts +18 -3
  160. package/src/serve/hub-app/palette-view.tsx +9 -2
  161. package/src/serve/hub-app/planned-view.tsx +2 -1
  162. package/src/serve/hub-app/project-list.css +18 -14
  163. package/src/serve/hub-app/project-list.tsx +88 -49
  164. package/src/serve/hub-app/projects-svc.ts +33 -3
  165. package/src/serve/hub-app/repo-sections.ts +19 -2
  166. package/src/serve/hub-app/repo-st.ts +75 -19
  167. package/src/serve/hub-app/review/review-cells.tsx +3 -3
  168. package/src/serve/hub-app/review/review-kit.ts +30 -7
  169. package/src/serve/hub-app/review/review-page.tsx +1 -1
  170. package/src/serve/hub-app/review/review-st.ts +33 -11
  171. package/src/serve/hub-app/review/review-thread.tsx +11 -9
  172. package/src/serve/hub-app/review/review-views.tsx +84 -19
  173. package/src/serve/hub-app/review/thread-st.ts +1 -10
  174. package/src/serve/hub-app/review/trailer-page.tsx +2 -1
  175. package/src/serve/hub-app/review.css +17 -8
  176. package/src/serve/hub-app/site/site-part.tsx +173 -0
  177. package/src/serve/hub-app/site/site-st.ts +157 -0
  178. package/src/serve/hub-app/site.css +35 -0
  179. package/src/serve/hub-app/social/calendar.tsx +182 -0
  180. package/src/serve/hub-app/social/comms-page.tsx +306 -0
  181. package/src/serve/hub-app/social/kit.tsx +244 -0
  182. package/src/serve/hub-app/social/post-card.tsx +456 -0
  183. package/src/serve/hub-app/social/problems.tsx +60 -0
  184. package/src/serve/hub-app/social/social-model.ts +154 -0
  185. package/src/serve/hub-app/social/social-page.tsx +674 -0
  186. package/src/serve/hub-app/social/social-st.ts +986 -0
  187. package/src/serve/hub-app/social.css +289 -0
  188. package/src/serve/hub-app/stores/stores-page.tsx +311 -0
  189. package/src/serve/hub-app/stores/stores-st.ts +286 -0
  190. package/src/serve/hub-app/stores.css +54 -0
  191. package/src/serve/hub-app/test-view.tsx +9 -2
  192. package/src/serve/hub-app/tests-svc.ts +16 -1
  193. package/src/serve/hub-app/timeline-geometry.ts +1 -1
  194. package/src/serve/hub-app/timeline-view.tsx +3 -2
  195. package/src/serve/hub-app/tree-build.ts +6 -0
  196. package/src/serve/hub-app/tree-row.tsx +27 -4
  197. package/src/serve/hub-app/tree-svc.ts +18 -49
  198. package/src/serve/hub-app/veille/veille-page.tsx +514 -0
  199. package/src/serve/hub-app/veille/veille-st.ts +443 -0
  200. package/src/serve/hub-app/veille.css +84 -0
  201. package/src/serve/hub-runtime.ts +14 -9
  202. package/src/serve/project-gutter-route.ts +44 -12
  203. package/src/serve/resources-wire.ts +48 -0
  204. package/src/serve/run-lanes.ts +7 -4
  205. package/src/serve/same-origin.ts +1 -1
  206. package/src/serve/serve-hub.ts +27 -18
  207. package/src/serve/tracked-watch.ts +24 -3
  208. package/src/serve/warm-cell.ts +5 -1
  209. package/src/shipkit-files.ts +15 -4
  210. package/src/shipkit.ts +0 -1
  211. package/src/shot/box.ts +162 -0
  212. package/src/shot/browser-slot.ts +62 -0
  213. package/src/shot/client.ts +43 -7
  214. package/src/shot/clip-encoder.ts +93 -12
  215. package/src/shot/film-box.ts +188 -0
  216. package/src/shot/shooter.ts +50 -15
  217. package/src/shot/shot-ask.ts +10 -2
  218. package/src/shot/stepped-clip.ts +5 -4
  219. package/src/site/desk.ts +242 -0
  220. package/src/site/routes.ts +66 -0
  221. package/src/site/unit.ts +62 -0
  222. package/src/social/brands.ts +22 -0
  223. package/src/social/compose.ts +97 -0
  224. package/src/social/desk-index.ts +123 -0
  225. package/src/social/desk-wire.ts +64 -0
  226. package/src/social/drafts.ts +183 -0
  227. package/src/social/house.ts +24 -0
  228. package/src/social/load.ts +319 -0
  229. package/src/social/md.ts +70 -0
  230. package/src/social/media-facts.ts +53 -0
  231. package/src/social/media-kind.ts +189 -0
  232. package/src/social/media-limit.ts +42 -0
  233. package/src/social/media-of.ts +30 -0
  234. package/src/social/migrate.ts +123 -0
  235. package/src/social/open.ts +17 -0
  236. package/src/social/post-url.ts +158 -0
  237. package/src/social/presence.ts +332 -0
  238. package/src/social/public-read.ts +53 -0
  239. package/src/social/publish/bluesky.ts +168 -0
  240. package/src/social/publish/discord.ts +76 -0
  241. package/src/social/publish/index.ts +24 -0
  242. package/src/social/publish/secret.ts +13 -0
  243. package/src/social/push.ts +31 -0
  244. package/src/social/richtext.ts +37 -0
  245. package/src/social/routes.ts +180 -0
  246. package/src/social/stats.ts +134 -0
  247. package/src/social/text.ts +267 -0
  248. package/src/social/tracker-route.ts +39 -0
  249. package/src/social/tracker.ts +255 -0
  250. package/src/social/unit.ts +53 -0
  251. package/src/social/writes.ts +130 -0
  252. package/src/start-repo.ts +14 -9
  253. package/src/stores/collection.ts +27 -0
  254. package/src/stores/desk.ts +336 -0
  255. package/src/stores/model.ts +187 -0
  256. package/src/stores/routes.ts +126 -0
  257. package/src/stores/unit.ts +57 -0
  258. package/src/suite/calibrate.ts +127 -0
  259. package/src/suite/core-counters.ts +91 -0
  260. package/src/suite/judge-suites.ts +94 -34
  261. package/src/suite/suite-cli.ts +44 -10
  262. package/src/suite/suite-cpu-preload.ts +34 -9
  263. package/src/trailer/adapter.ts +4 -0
  264. package/src/trailer/build.ts +42 -11
  265. package/src/trailer/ffmpeg.ts +11 -0
  266. package/src/trailer/footage.ts +30 -13
  267. package/src/trailer/grammar.ts +18 -2
  268. package/src/trailer/graph.ts +28 -6
  269. package/src/trailer/passage.ts +21 -6
  270. package/src/trailer/plan.ts +74 -3
  271. package/src/trailer/shelf.ts +16 -0
  272. package/src/trailer/stitch.ts +67 -26
  273. package/src/trailer/url.ts +1 -1
  274. package/src/trailer/versions.ts +24 -0
  275. package/src/ts/gate-typecheck.ts +32 -0
  276. package/src/ts/typecheck-cli.ts +9 -11
  277. package/src/tui/tui-app.tsx +0 -1
  278. package/src/veille/asks.ts +155 -0
  279. package/src/veille/auto.ts +31 -0
  280. package/src/veille/batch.ts +27 -0
  281. package/src/veille/chrome.ts +127 -0
  282. package/src/veille/collection.ts +28 -0
  283. package/src/veille/desk.ts +242 -0
  284. package/src/veille/identity.ts +80 -0
  285. package/src/veille/import.ts +68 -0
  286. package/src/veille/log.ts +183 -0
  287. package/src/veille/platforms.ts +118 -0
  288. package/src/veille/reads.ts +66 -0
  289. package/src/veille/replied.ts +110 -0
  290. package/src/veille/routes.ts +185 -0
  291. package/src/veille/service.ts +81 -0
  292. package/src/veille/watch.ts +116 -0
  293. package/src/veille/worth.ts +46 -0
  294. package/src/wiki/scan-md.ts +18 -0
  295. package/src/collections/posts.ts +0 -142
  296. package/src/contracts/manifests/social.contract.ts +0 -20
  297. package/src/scaffold/files/agent-coding.md +0 -35
  298. package/src/ts/typecheck-cache.ts +0 -11
@@ -0,0 +1,201 @@
1
+ // THE DAEMON'S BACKGROUND JOBS, OFF ITS LOOP (wiki build/shipkit/home.md, Nothing heavy on the daemon's loop): the
2
+ // backup, the retention sweep, the media store and the house's global context each run as a child process (`sk daemon job <id>`, niced), started
3
+ // detached with its pid in a file, its lines appended to the daemon's log. The daemon only starts it and reads the
4
+ // pid: an in place restart adopts a child still running and never starts a second one. What a job remembers between
5
+ // two runs lives in the machine db, so a restart never redoes a job's work.
6
+ //
7
+ // the one constraint a reader breaks first: a job's body never runs in the daemon's process. The daemon's loop answers
8
+ // every page; a sync walk, a VACUUM or a hash pass there holds every page with it (tests/daemon-jobs.test.ts)
9
+ import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'
10
+ import { join } from 'node:path'
11
+ import { machineGet } from '../core/machine-db.ts'
12
+ import { loopWatch } from '../core/loop-watch.ts'
13
+ import { BACKUP_EVERY_MS } from '../media-store/backup/daemon.ts'
14
+ import { MEDIA_EVERY_MS } from '../media-store/daemon.ts'
15
+ import { SWEEP_EVERY_MS, SWEPT_AT } from './machine-stores.ts'
16
+ import { contextSourcesStamp, GLOBAL_CONTEXT_DONE, GLOBAL_CONTEXT_EVERY_MS, GLOBAL_CONTEXT_MAX_MS } from './global-context.ts'
17
+
18
+ export type JobId = 'backup' | 'retention sweep' | 'media store' | 'global context'
19
+
20
+ export interface DaemonJob {
21
+ id: JobId
22
+ /** the daemon looks this often: a look starts the child unless one runs or `due` says no */
23
+ everyMs: number
24
+ /** the first look after a boot: the repos load first */
25
+ firstMs: number
26
+ /** a cheap read in the daemon (a stat, never a walk; async when it gives the loop back between two): false skips
27
+ * the child for this look. `root` is the house repo the children run in */
28
+ due?: (now: number, root: string) => boolean | Promise<boolean>
29
+ }
30
+
31
+ /** a child gets this long; past it, it is killed and said */
32
+ export const JOB_MAX_MS = 60 * 60_000
33
+ /** the niceness of every job child: the pages and the agents' tools go first */
34
+ export const JOB_NICE = 15
35
+
36
+ export const DAEMON_JOBS: readonly DaemonJob[] = [
37
+ { id: 'media store', everyMs: MEDIA_EVERY_MS, firstMs: 15_000 },
38
+ { id: 'retention sweep', everyMs: 5 * 60_000, firstMs: 10_000, due: (now) => now - (machineGet<number>(SWEPT_AT) ?? 0) >= SWEEP_EVERY_MS },
39
+ { id: 'backup', everyMs: BACKUP_EVERY_MS, firstMs: BACKUP_EVERY_MS },
40
+ // the house's generated context: its unit files are imported to be read, a second of compile the loop never pays
41
+ { id: 'global context', everyMs: GLOBAL_CONTEXT_EVERY_MS, firstMs: 30_000, due: async (now, root) => contextDue(now, await contextSourcesStamp(root)) },
42
+ ]
43
+
44
+ /** the context is due when its sources' stamp moved since the last write, or that write is old */
45
+ export function contextDue(now: number, stamp: string | null): boolean {
46
+ if (stamp == null) return false
47
+ const done = machineGet<{ stamp: string; at: number }>(GLOBAL_CONTEXT_DONE)
48
+ return done == null || done.stamp !== stamp || now - done.at >= GLOBAL_CONTEXT_MAX_MS
49
+ }
50
+
51
+ export const isJobId = (s: string): s is JobId => DAEMON_JOBS.some((j) => j.id === s)
52
+
53
+ /** the file name of a job: `retention sweep` → `retention-sweep` */
54
+ const slug = (id: JobId): string => id.replace(/\s+/g, '-')
55
+
56
+ // a subshell runs the niced child and writes its exit code: the pid echoed is the subshell's, alive while the job runs
57
+ const LAUNCH = 'set -m; ( nice -n "$2" "${@:4}"; echo $? >"$3" ) >>"$1" 2>&1 </dev/null & echo $!'
58
+
59
+ export interface JobsDeps {
60
+ /** the cli the child runs (`src/cli.ts`) */
61
+ cli: string
62
+ /** where the child runs: the house repo */
63
+ cwd: string
64
+ /** pid and exit files */
65
+ dir: string
66
+ /** the daemon's log: the child appends its own stamped lines */
67
+ log: string
68
+ printErr: (l: string) => void
69
+ env?: Record<string, string>
70
+ now?: () => number
71
+ alive?: (pid: number) => boolean
72
+ }
73
+
74
+ const aliveReal = (pid: number): boolean => {
75
+ try {
76
+ process.kill(pid, 0)
77
+ return true
78
+ } catch (e) {
79
+ return (e as { code?: string }).code === 'EPERM'
80
+ }
81
+ }
82
+
83
+ export interface Jobs {
84
+ stop(): void
85
+ /** one look at a job now: starts its child when none runs and it is due; resolves once that child is gone */
86
+ run(id: JobId, o?: { force?: boolean }): Promise<number | null>
87
+ }
88
+
89
+ export function startJobs(d: JobsDeps, jobs: readonly DaemonJob[] = DAEMON_JOBS, o: { timers?: boolean } = {}): Jobs {
90
+ const now = d.now ?? Date.now
91
+ const alive = d.alive ?? aliveReal
92
+ mkdirSync(d.dir, { recursive: true })
93
+ const pidFile = (id: JobId): string => join(d.dir, `${slug(id)}.pid`)
94
+ const exitFile = (id: JobId): string => join(d.dir, `${slug(id)}.exit`)
95
+ const startedAt = new Map<JobId, number>()
96
+
97
+ /** the pid of the job's child that still runs, else null; a finished child's failure said once */
98
+ const running = (id: JobId): number | null => {
99
+ const f = pidFile(id)
100
+ if (!existsSync(f)) return null
101
+ const pid = Number(readFileSync(f, 'utf8').trim())
102
+ if (pid > 0 && alive(pid)) {
103
+ const at = startedAt.get(id)
104
+ if (at != null && now() - at > JOB_MAX_MS) {
105
+ try { process.kill(-pid, 'SIGKILL') } catch { try { process.kill(pid, 'SIGKILL') } catch { /* gone */ } }
106
+ d.printErr(`WARN daemon job ${id}: still running after ${JOB_MAX_MS / 60_000} min, killed`)
107
+ } else return pid
108
+ }
109
+ rmSync(f, { force: true })
110
+ const code = existsSync(exitFile(id)) ? Number(readFileSync(exitFile(id), 'utf8').trim()) : null
111
+ rmSync(exitFile(id), { force: true })
112
+ if (code != null && code !== 0) d.printErr(`WARN daemon job ${id}: its child exited ${code}, its lines above say why`)
113
+ return null
114
+ }
115
+
116
+ const launch = async (job: DaemonJob): Promise<number | null> => {
117
+ const end = loopWatch.span(`${job.id} (start)`)
118
+ try {
119
+ const cmd = [process.execPath, d.cli, 'daemon', 'job', job.id]
120
+ const p = Bun.spawn(['/bin/bash', '-c', LAUNCH, 'launch', d.log, String(JOB_NICE), exitFile(job.id), ...cmd], { cwd: d.cwd, env: { ...process.env, ...d.env }, stdout: 'pipe', stderr: 'pipe' })
121
+ const [out, err] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text()])
122
+ const pid = Number(out.trim())
123
+ if ((await p.exited) !== 0 || !Number.isInteger(pid) || pid <= 0) {
124
+ d.printErr(`WARN daemon job ${job.id}: the launch shell failed: ${err.trim()}`)
125
+ return null
126
+ }
127
+ await Bun.write(pidFile(job.id), String(pid))
128
+ startedAt.set(job.id, now())
129
+ return pid
130
+ } finally {
131
+ end()
132
+ }
133
+ }
134
+
135
+ const look = async (job: DaemonJob, force: boolean): Promise<number | null> => {
136
+ if (running(job.id) != null) return null
137
+ const due = job.due
138
+ if (!force && due != null && !(await loopWatch.spanned(`${job.id} (due)`, () => due(now(), d.cwd)))) return null
139
+ return launch(job)
140
+ }
141
+
142
+ const timers: ReturnType<typeof setTimeout>[] = []
143
+ if (o.timers !== false)
144
+ for (const job of jobs) {
145
+ const tick = (): void => void look(job, false).catch((e) => d.printErr(`WARN daemon job ${job.id}: ${(e as Error).message}`))
146
+ const first = setTimeout(() => {
147
+ tick()
148
+ const every = setInterval(tick, job.everyMs)
149
+ every.unref()
150
+ timers.push(every)
151
+ }, job.firstMs)
152
+ first.unref()
153
+ timers.push(first)
154
+ }
155
+
156
+ return {
157
+ stop: () => {
158
+ for (const t of timers) clearTimeout(t)
159
+ },
160
+ async run(id, ro = {}) {
161
+ const job = jobs.find((j) => j.id === id)
162
+ if (job == null) throw new Error(`no daemon job ${id}`)
163
+ const pid = await look(job, ro.force === true)
164
+ if (pid == null) return null
165
+ while (running(id) != null) await Bun.sleep(50)
166
+ return pid
167
+ },
168
+ }
169
+ }
170
+
171
+ /** what a job does, in the child: `sk daemon job <id>` runs it. Each body imports its modules here, never at the top */
172
+ export async function runJobBody(id: JobId, o: { root: string; home: string; print: (l: string) => void; printErr: (l: string) => void }): Promise<void> {
173
+ const { houseRepos } = await import('../serve/project-gutter.ts')
174
+ const house = houseRepos(o.root, o.home)
175
+ if (house.index == null) throw new Error(`${o.root} includes no house wiki index: no repos to work on`)
176
+ const repos = house.repos.map((r) => r.path)
177
+ if (id === 'backup') {
178
+ const { backupTick } = await import('../media-store/backup/daemon.ts')
179
+ const { machineSpace } = await import('../media-store/space.ts')
180
+ return backupTick({ home: o.home, repos: [...repos, ...house.archived.map((r) => r.path)], space: machineSpace, print: o.print, printErr: o.printErr })
181
+ }
182
+ if (id === 'media store') {
183
+ const { mediaTick } = await import('../media-store/daemon.ts')
184
+ const { mediaKinds } = await import('../media-kinds.ts')
185
+ return mediaTick({ roots: repos, kinds: mediaKinds, print: o.print, printErr: o.printErr })
186
+ }
187
+ if (id === 'global context') {
188
+ const { contextSourcesStamp, houseContext, writeIfChanged } = await import('./global-context.ts')
189
+ const { machineSet } = await import('../core/machine-db.ts')
190
+ // the stamp before the read: a source that moves during it moves the stamp again, and the next look writes
191
+ const stamp = await contextSourcesStamp(o.root, o.home)
192
+ const c = await houseContext(o.root, o.home)
193
+ if (c != null && writeIfChanged(c.path, c.text)) o.print(`ok: wrote ${c.path}`)
194
+ machineSet(GLOBAL_CONTEXT_DONE, { stamp, at: Date.now() })
195
+ return
196
+ }
197
+ const { sweepTick } = await import('./machine-stores.ts')
198
+ const { homeDir } = await import('./home-paths.ts')
199
+ const { landMotherhome } = await import('../core/motherhome.ts')
200
+ return sweepTick({ roots: repos, dir: homeDir(), printErr: o.printErr, also: (now) => { for (const n of landMotherhome({ now })) o.printErr(n) } })
201
+ }
@@ -6,11 +6,14 @@
6
6
  //
7
7
  // the one constraint a reader breaks first: it is in every session's context,
8
8
  // so a contribution over its cap is cut here, and SK033 fails in its repo.
9
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
9
+ import { createHash } from 'crypto'
10
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'fs'
10
11
  import { homedir } from 'os'
11
12
  import { dirname, join } from 'path'
12
13
  import { CONTRIBUTION_FILE, CONTRIBUTION_MAX_BYTES, CONTRIBUTION_MAX_LINES, contributionBody, contributionOver, loadsContext } from '../core/global-contribution.ts'
13
14
  import { KEYWORD_FILE } from '../core/layout.ts'
15
+ import { yieldLoop } from '../core/loop-watch.ts'
16
+ import { repoUnitFiles } from '../core/discover-checks.ts'
14
17
  import { evaluateLeak, globalKeywordFile, maskPattern, parsePatterns } from '../hooks/leak-guard.ts'
15
18
  import { homeRepo, houseRepos } from '../serve/project-gutter.ts'
16
19
  import { scanGlobalUnits, type GlobalProcessDecl } from './global-units.ts'
@@ -131,6 +134,36 @@ export function houseLeak(houseRoot: string): Leak | null {
131
134
  }
132
135
  }
133
136
 
137
+ const stampOf = (f: string): string => {
138
+ try {
139
+ const st = statSync(f)
140
+ return `${st.mtimeMs}:${st.size}`
141
+ } catch {
142
+ return '-'
143
+ }
144
+ }
145
+
146
+ /** the outside of every source the file is made of, one repo at a time with the loop given back between two: the
147
+ * house index, the keyword lists, the file itself, and each repo's package.json, contribution and unit files. A stat
148
+ * each (the unit list is the walk the hubs keep), so the daemon looks every minute and starts the writer only when it
149
+ * moved. What a unit module imports is not in it: GLOBAL_CONTEXT_MAX_MS bounds that */
150
+ export async function contextSourcesStamp(root: string, home: string = homedir()): Promise<string | null> {
151
+ const h = houseRepos(homeRepo(root), home)
152
+ if (h.index == null) return null
153
+ const parts = [h.index, stampOf(h.index), stampOf(globalContextPath(h.index)), ...[globalKeywordFile(), join(h.home, KEYWORD_FILE)].map((f) => (f == null ? '-' : stampOf(f)))]
154
+ for (const r of h.repos) {
155
+ await yieldLoop()
156
+ parts.push(r.path, stampOf(join(r.path, 'package.json')), stampOf(join(r.path, CONTRIBUTION_FILE)))
157
+ for (const f of repoUnitFiles(r.path)) parts.push(f, stampOf(f))
158
+ }
159
+ return createHash('sha256').update(parts.join('\n')).digest('hex').slice(0, 16)
160
+ }
161
+
162
+ /** the sources' stamp the last write was made from (machine db), and when */
163
+ export const GLOBAL_CONTEXT_DONE = 'global-context-done'
164
+ /** a write at least this often, whatever the stamp says: a unit module's own imports are not in it */
165
+ export const GLOBAL_CONTEXT_MAX_MS = 6 * 3600_000
166
+
134
167
  /** THE computation, for the house the repo at `root` belongs to: where the
135
168
  * file goes and what it holds. The cli and the daemon both call it. Null
136
169
  * when `root` includes no house index, or one that does not load the file */
@@ -3,6 +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 { loopWatch } from '../core/loop-watch.ts'
6
7
  import { existsSync, readFileSync } from 'fs'
7
8
  import { dirname, join } from 'path'
8
9
  import { fileURLToPath } from 'url'
@@ -19,15 +20,18 @@ import type { Planner, PlanRow } from '../plan/planner.ts'
19
20
  import type { Widgets, WidgetView } from './widgets.ts'
20
21
  import { ActivityCache, repoActivity, windowMinutes } from './activity.ts'
21
22
  import { devRepos, InsightsCache, type Scope } from './insights.ts'
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
25
  import { appIconOf, appIconPngs, identityOfRoot } from '../core/app-icon.ts'
26
26
  import { inboxResponse } from './inbox.ts'
27
+ import { veilleBatchRoute } from '../veille/batch.ts'
28
+ import { postTrackerRoute } from '../social/tracker-route.ts'
27
29
 
28
30
  /** how far back a repo's git page lists its commits */
29
31
  export const GIT_PAGE_MS = 7 * 24 * 3600_000
30
32
  import type { HouseView } from '../ledger/house-runs.ts'
33
+ import { identitiesRoute } from '../identities/machine-route.ts'
34
+ import { siteRoutes } from '../site/routes.ts'
31
35
 
32
36
  /** how often the daemon looks at every repo */
33
37
  export const TICK_MS = 2_000
@@ -138,25 +142,18 @@ export function homeRoutes(d: HomeDeps) {
138
142
  }
139
143
 
140
144
  let active = new Set<string>()
141
- let contextAt = -Infinity
142
145
  if (d.plan != null) d.plan.active = (name) => active.has(name)
143
146
 
144
147
  async function tick(): Promise<void> {
145
- await refresh()
148
+ await loopWatch.spanned('tick: projects', refresh)
146
149
  active = activeSet(rows, d.state.data.active, rows.find((r) => r.path === d.root)?.name ?? d.name)
147
- // the plan's clock: one look per tick, and it starts at most one batch
148
- d.plan?.tick()
149
- // the house's generated context: rewritten only when a source moved,
150
- // and never held on
151
- if (Date.now() - contextAt >= GLOBAL_CONTEXT_EVERY_MS) {
152
- contextAt = Date.now()
153
- void houseContext(d.root)
154
- .then((c) => { if (c != null && writeIfChanged(c.path, c.text)) console.log(`ok: wrote ${c.path}`) })
155
- .catch((e) => console.error(`WARN the global context could not be written: ${(e as Error).message}`))
156
- }
150
+ // the plan's clock: one look per tick, and it starts at most one batch. The run records it looks at are read
151
+ // first, one repo at a time
152
+ await loopWatch.spanned('tick: plan records', () => d.plan?.refresh())
153
+ loopWatch.timed('tick: plan', () => d.plan?.tick())
157
154
  // a widget render never holds the tick back
158
- void d.widgets?.tick(repos.map((r) => ({ name: r.name, path: r.path }))).catch((e) => console.error(`WARN the widgets broke: ${(e as Error).message}`))
159
- await d.hubs.tick(active)
155
+ void loopWatch.spanned('tick: widgets', () => d.widgets?.tick(repos.map((r) => ({ name: r.name, path: r.path })))).catch((e) => console.error(`WARN the widgets broke: ${(e as Error).message}`))
156
+ await loopWatch.spanned('tick: hubs', () => d.hubs.tick(active))
160
157
  }
161
158
 
162
159
  function answer(): HomeAnswer {
@@ -196,8 +193,18 @@ export function homeRoutes(d: HomeDeps) {
196
193
  if (path === '/hub.json')
197
194
  // the identity a client probes (homeUp), through the web or here
198
195
  return Response.json({ hub: 'shipkit-home', name: d.name, root: d.root, version: LIB_VERSION, held: heldNow() == null ? null : heldText(heldNow()!) }, { headers: { 'access-control-allow-origin': '*' } })
196
+ // the Veille extension's batches, from an identity's Chrome profile: its own header guard (veille/batch.ts)
197
+ const batch = await veilleBatchRoute(req, path)
198
+ if (batch != null) return batch
199
+ // the post tracker's half of the same extension: its own header guard (social/tracker-route.ts)
200
+ const tracked = await postTrackerRoute(req, path)
201
+ if (tracked != null) return tracked
199
202
  if (!sameOrigin(req)) return new Response('refused: a request that changes something must come from the home page', { status: 403 })
200
203
  if (path.startsWith('/api/projects')) return d.gutter.handle(req, path)
204
+ // who speaks for each repo, and where its data lives (identities/machine-route.ts)
205
+ if (path.startsWith('/api/home/identities')) return identitiesRoute(req, path, d.root)
206
+ // each identity's website: its pages, its preview, what changed since its deploy (site/routes.ts)
207
+ if (path.startsWith('/api/home/sites/')) return siteRoutes(req, path, d.root)
201
208
  // the activity page's push button: every house repo with unpushed commits, never a force (fleet/push-fleet.ts)
202
209
  if (path === '/api/home/push-all' && req.method === 'POST') {
203
210
  if (repos.length === 0) await refresh()
package/src/home/hubs.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  // which each loaded hub joins. An edit of a repo config reloads that repo's
9
9
  // hub alone, once its gate is done: the daemon runs with no bun watch, so one
10
10
  // repo's edit never restarts the others (lib-watch.ts).
11
+ import { loopWatch } from '../core/loop-watch.ts'
11
12
  import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'fs'
12
13
  import { dirname, join } from 'path'
13
14
  import type { WiredRepo } from '../serve/project-gutter.ts'
@@ -17,6 +18,9 @@ import { capLog, tailLines, type ProcStatus } from './supervise.ts'
17
18
  import { hubBase, hubLog } from './home-paths.ts'
18
19
  import { NOT_INSTALLED } from './home-words.ts'
19
20
 
21
+ /** the loop given back to the pages before each hub load of the queue */
22
+ export const LOAD_GAP_MS = 20
23
+
20
24
  /** what the home needs of a loaded hub */
21
25
  export type LoadedHub = Pick<HubRuntime, 'handler' | 'start' | 'stop' | 'ping' | 'busy'> & { uses: string[] }
22
26
 
@@ -120,6 +124,8 @@ export class Hubs {
120
124
  if (e.loading != null) return e.loading
121
125
  this.set(e, 'starting')
122
126
  const run = this.queue.then(async () => {
127
+ // a load is a burst of sync work (a config import, a tree walk): the loop goes back to the pages between two
128
+ await new Promise((r) => setTimeout(r, LOAD_GAP_MS))
123
129
  const blocked = hubBlocker(e.repo.path)
124
130
  if (blocked != null) {
125
131
  this.set(e, 'down', blocked)
@@ -127,16 +133,17 @@ export class Hubs {
127
133
  }
128
134
  const io = this.io(e)
129
135
  try {
130
- if (this.o.prepare != null) await this.o.prepare(e.repo, io).catch((err) => io.printErr(`WARN ${e.repo.name}: ${(err as Error).message}`))
136
+ const prepare = this.o.prepare
137
+ if (prepare != null) await loopWatch.spanned(`hub prepare: ${e.repo.name}`, () => prepare(e.repo, io)).catch((err) => io.printErr(`WARN ${e.repo.name}: ${(err as Error).message}`))
131
138
  e.stamp = configStamp(e.repo.path)
132
- const rt = await this.o.load(e.repo, io, { fresh: fresh || e.loads > 0 })
139
+ const rt = await loopWatch.spanned(`hub load: ${e.repo.name}`, () => this.o.load(e.repo, io, { fresh: fresh || e.loads > 0 }))
133
140
  // a stop by hand came while it loaded, and wins
134
141
  if (e.held) {
135
142
  rt.stop()
136
143
  this.set(e, 'down', 'stopped by hand')
137
144
  return
138
145
  }
139
- rt.start()
146
+ loopWatch.timed(`hub start: ${e.repo.name}`, () => rt.start())
140
147
  e.rt = rt
141
148
  e.loads++
142
149
  this.set(e, 'up')
@@ -15,6 +15,14 @@ export type InboxKind = 'card' | 'question' | 'ask' | 'need' | 'raised'
15
15
  export type InboxTone = 'review' | 'red' | 'yellow'
16
16
  /** the main list (what waits on him) or the folded one (what can wait, what he can only read) */
17
17
  export type InboxList = 'main' | 'yellow'
18
+ /** the review store's rows only (the default), or every row, the checks and asks included */
19
+ export type InboxShow = 'cards' | 'all'
20
+ /** what the rows group by: each one on or off on its own, nested in this order */
21
+ export const INBOX_GROUPS = ['repo', 'kind', 'lane'] as const
22
+ export type InboxGroup = (typeof INBOX_GROUPS)[number]
23
+
24
+ /** a row the review store gives: a card, a question, an item raised in it */
25
+ export const isCardKind = (k: InboxKind): boolean => k === 'card' || k === 'question' || k === 'raised'
18
26
 
19
27
  export interface InboxRow {
20
28
  /** `<repo>/<id>`, one per row of the whole inbox */
@@ -31,6 +39,8 @@ export interface InboxRow {
31
39
  title: string
32
40
  /** one more line: the lane and the versions, the need's sentence */
33
41
  sub?: string
42
+ /** the lane the card belongs to; a need has none */
43
+ lane?: string
34
44
  /** epoch ms of its newest move, null when nothing dates it */
35
45
  at: number | null
36
46
  /** the review preview thumb, on the home's origin */
@@ -44,6 +54,8 @@ export interface InboxSource {
44
54
  repo: string
45
55
  review: { tag: string; ix: ThreadIndex } | null
46
56
  needs: Resource[]
57
+ /** epoch ms of its last commit when that is older than `QUIET_DAYS`: its red rows can wait */
58
+ quietSince?: number | null
47
59
  }
48
60
 
49
61
  export interface InboxAnswer {
@@ -53,7 +65,11 @@ export interface InboxAnswer {
53
65
  total: number
54
66
  offset: number
55
67
  limit: number
68
+ /** the rows of each list the page shows */
56
69
  counts: Record<InboxList, number>
70
+ /** the rows of each list with every kind: what « all » would show */
71
+ all: Record<InboxList, number>
72
+ show: InboxShow
57
73
  /** per repo, the rows of each list: its own badges count the same */
58
74
  repos: Record<string, Record<InboxList, number>>
59
75
  /** a repo whose items are not here, and why (its hub is down, a read broke) */
@@ -61,6 +77,8 @@ export interface InboxAnswer {
61
77
  }
62
78
 
63
79
  export const INBOX_PAGE = 50
80
+ /** a repo with no commit for this long is quiet: nobody works there, its red checks fold into « can wait » */
81
+ export const QUIET_DAYS = 7
64
82
  export const INBOX_MAX = 500
65
83
 
66
84
  /** where a repo's hub answers on the home */
@@ -94,6 +112,7 @@ function reviewRow(repo: string, r: ThreadRow, kind: InboxKind, tone: InboxTone)
94
112
  tone,
95
113
  title: r.title,
96
114
  ...(sub !== '' ? { sub } : {}),
115
+ ...(r.lane ? { lane: r.lane } : {}),
97
116
  at: Number.isFinite(at) ? at : null,
98
117
  thumb: r.thumb != null && IMAGE.test(r.thumb) ? `${hubOf(repo)}/api/review/${r.head}/preview/thumb/${r.thumb}` : null,
99
118
  open: inboxAddress(repo, r.head),
@@ -124,7 +143,7 @@ function needRow(repo: string, n: Resource, dated: Dated): InboxRow {
124
143
  }
125
144
 
126
145
  /** one repo's rows: the main list (the cards and questions waiting on him, the asks, what is red) and the folded one
127
- * (what is yellow, the raised items in the agents' hands) */
146
+ * (what is yellow, the raised items in the agents' hands, what is red in a quiet repo) */
128
147
  export function repoRows(s: InboxSource, dated: Dated): Record<InboxList, InboxRow[]> {
129
148
  const out: Record<InboxList, InboxRow[]> = { main: [], yellow: [] }
130
149
  for (const { row } of s.review?.ix.entries ?? []) {
@@ -134,7 +153,9 @@ export function repoRows(s: InboxSource, dated: Dated): Record<InboxList, InboxR
134
153
  for (const n of s.needs) {
135
154
  if (n.severity == null || n.collection === REVIEW_COL || n.askOwned === true) continue
136
155
  const r = needRow(s.repo, n, dated)
137
- out[r.kind === 'ask' || r.tone === 'red' ? 'main' : 'yellow'].push(r)
156
+ const quiet = s.quietSince != null && r.kind !== 'ask' && r.tone === 'red'
157
+ if (quiet) r.sub = [`quiet repo, last commit ${new Date(s.quietSince!).toISOString().slice(0, 10)}`, r.sub].filter((x) => x != null).join(' · ')
158
+ out[!quiet && (r.kind === 'ask' || r.tone === 'red') ? 'main' : 'yellow'].push(r)
138
159
  }
139
160
  return out
140
161
  }
@@ -158,25 +179,59 @@ export function inboxRows<S extends InboxSource>(sources: readonly S[], dated: (
158
179
  }
159
180
 
160
181
  /** the query from a url's search: a value out of range is its default */
161
- export function inboxQuery(p: URLSearchParams): { list: InboxList; offset: number; limit: number } {
182
+ export function inboxQuery(p: URLSearchParams): { list: InboxList; show: InboxShow; offset: number; limit: number } {
162
183
  const n = (k: string, d: number, max: number): number => {
163
184
  const v = Number(p.get(k) || NaN)
164
185
  return Number.isInteger(v) && v >= 0 ? Math.min(v, max) : d
165
186
  }
166
- return { list: p.get('list') === 'yellow' ? 'yellow' : 'main', offset: n('offset', 0, Number.MAX_SAFE_INTEGER), limit: Math.max(1, n('limit', INBOX_PAGE, INBOX_MAX)) }
187
+ return { list: p.get('list') === 'yellow' ? 'yellow' : 'main', show: p.get('show') === 'all' ? 'all' : 'cards', offset: n('offset', 0, Number.MAX_SAFE_INTEGER), limit: Math.max(1, n('limit', INBOX_PAGE, INBOX_MAX)) }
167
188
  }
168
189
 
169
190
  /** one page of one list */
170
191
  export function inboxPage(all: ReturnType<typeof inboxRows>, q: ReturnType<typeof inboxQuery>, missing: InboxAnswer['missing']): InboxAnswer {
171
- const rows = all[q.list]
192
+ // the kinds filter before the page cuts, so a card past the first page is never lost behind a check
193
+ const shown = (l: InboxList): InboxRow[] => (q.show === 'all' ? all[l] : all[l].filter((r) => isCardKind(r.kind)))
194
+ const rows = shown(q.list)
172
195
  return {
173
196
  list: q.list,
174
197
  rows: rows.slice(q.offset, q.offset + q.limit),
175
198
  total: rows.length,
176
199
  offset: q.offset,
177
200
  limit: q.limit,
178
- counts: { main: all.main.length, yellow: all.yellow.length },
201
+ counts: { main: shown('main').length, yellow: shown('yellow').length },
202
+ all: { main: all.main.length, yellow: all.yellow.length },
203
+ show: q.show,
179
204
  repos: all.repos,
180
205
  missing,
181
206
  }
182
207
  }
208
+
209
+ const KIND_LABEL: Record<InboxKind, string> = { card: 'cards', question: 'questions', ask: 'asks', need: 'needs', raised: 'raised' }
210
+
211
+ /** a group of rows: its words, its rows' count, then its rows or its inner groups */
212
+ export type InboxGroupNode = { key: string; label: string; n: number; rows: InboxRow[]; groups: InboxGroupNode[] | null }
213
+
214
+ const groupOf = (r: InboxRow, by: InboxGroup): string => (by === 'repo' ? r.repo : by === 'kind' ? KIND_LABEL[r.kind] : r.lane ?? 'no lane')
215
+
216
+ /** the rows grouped by each axis that is on, nested repo then kind then lane; a group keeps its rows' order, and the
217
+ * groups come in the order their first row comes (newest first). No axis on: one group of every row */
218
+ export function groupRows(rows: readonly InboxRow[], on: readonly InboxGroup[], prefix = ''): InboxGroupNode[] {
219
+ const axes = INBOX_GROUPS.filter((g) => on.includes(g))
220
+ const [by, ...rest] = axes
221
+ if (by == null) return [{ key: prefix || 'all', label: '', n: rows.length, rows: [...rows], groups: null }]
222
+ const order: string[] = []
223
+ const of = new Map<string, InboxRow[]>()
224
+ for (const r of rows) {
225
+ const k = groupOf(r, by)
226
+ if (!of.has(k)) {
227
+ of.set(k, [])
228
+ order.push(k)
229
+ }
230
+ of.get(k)!.push(r)
231
+ }
232
+ return order.map((k) => {
233
+ const rs = of.get(k)!
234
+ const key = `${prefix}${by}:${k}/`
235
+ return { key, label: k, n: rs.length, rows: rs, groups: rest.length > 0 ? groupRows(rs, rest, key) : null }
236
+ })
237
+ }
package/src/home/inbox.ts CHANGED
@@ -6,7 +6,60 @@ import { join } from 'path'
6
6
  import type { Resource } from '../collections/collection-types.ts'
7
7
  import { storeIndex } from '../review/routes.ts'
8
8
  import type { Hubs } from './hubs.ts'
9
- import { inboxPage, inboxQuery, inboxRows, type Dated, type InboxAnswer, type InboxSource } from './inbox-shape.ts'
9
+ import { inboxPage, inboxQuery, inboxRows, QUIET_DAYS, type Dated, type InboxAnswer, type InboxSource } from './inbox-shape.ts'
10
+
11
+ const COMMIT_TTL = 10 * 60_000
12
+ /** a subject this many repos share is a sweep over the house (a toolkit bump, a doc pass), never work on the repo */
13
+ const SWEEP_REPOS = 3
14
+ const LOG_DEPTH = 200
15
+
16
+ /** one commit of a repo's log: when, and its subject with the numbers taken out (`rvlib-shipkit ^2.11.0` and
17
+ * `rvlib-shipkit 2.10.0` are one sweep) */
18
+ export interface LogLine {
19
+ at: number
20
+ subject: string
21
+ }
22
+
23
+ const logs = new Map<string, { asked: number; lines: Promise<LogLine[] | null> }>()
24
+
25
+ /** a repo's newest commits on HEAD, asked of git at most once every 10 minutes; null when git cannot say */
26
+ export function recentCommits(root: string, now = Date.now()): Promise<LogLine[] | null> {
27
+ const hit = logs.get(root)
28
+ if (hit != null && now - hit.asked < COMMIT_TTL) return hit.lines
29
+ const lines = (async () => {
30
+ try {
31
+ const p = Bun.spawn(['git', 'log', `-${LOG_DEPTH}`, '--format=%ct%x09%s', 'HEAD'], { cwd: root, stdout: 'pipe', stderr: 'ignore' })
32
+ const out = await new Response(p.stdout).text()
33
+ if ((await p.exited) !== 0) return null
34
+ return out.split('\n').flatMap((l) => {
35
+ const tab = l.indexOf('\t')
36
+ const at = Number(l.slice(0, tab)) * 1000
37
+ return tab > 0 && Number.isFinite(at) ? [{ at, subject: l.slice(tab + 1).toLowerCase().replace(/[\d^~.]+/g, '') }] : []
38
+ })
39
+ } catch {
40
+ return null
41
+ }
42
+ })()
43
+ logs.set(root, { asked: now, lines })
44
+ return lines
45
+ }
46
+
47
+ /** per repo, its last commit of its own when the repo is quiet (none for `QUIET_DAYS`), else null. A commit whose
48
+ * subject `SWEEP_REPOS` repos share is a sweep and never counts; a repo git cannot read is never quiet */
49
+ export function quietOf(byRepo: ReadonlyMap<string, LogLine[] | null>, now = Date.now()): Map<string, number | null> {
50
+ const seen = new Map<string, Set<string>>()
51
+ for (const [repo, lines] of byRepo) for (const l of lines ?? []) seen.set(l.subject, (seen.get(l.subject) ?? new Set()).add(repo))
52
+ const out = new Map<string, number | null>()
53
+ for (const [repo, lines] of byRepo) {
54
+ if (lines == null || lines.length === 0) {
55
+ out.set(repo, null)
56
+ continue
57
+ }
58
+ const own = lines.find((l) => (seen.get(l.subject)?.size ?? 0) < SWEEP_REPOS) ?? lines[lines.length - 1]!
59
+ out.set(repo, now - own.at > QUIET_DAYS * 86_400_000 ? own.at : null)
60
+ }
61
+ return out
62
+ }
10
63
 
11
64
  /** a need's file dated: an ask by its birth (its front matter keeps only the day), any other file by its last write */
12
65
  export const datedIn = (root: string): Dated => (n: Resource) => {
@@ -19,20 +72,38 @@ export const datedIn = (root: string): Dated => (n: Resource) => {
19
72
  }
20
73
  }
21
74
 
75
+ /** one read of every hub's rows is shared by every page that asks within this long */
76
+ export const INBOX_SHARE_MS = 1_000
77
+ const shared = new WeakMap<object, { end: number | null; read: ReturnType<typeof readSources> }>()
78
+
79
+ /** what every hub that is up holds; concurrent pages (windows, the phone) share one read while it runs and for
80
+ * INBOX_SHARE_MS after it ended */
81
+ export function inboxSources(hubs: Pick<Hubs, 'loaded'>, now: () => number = Date.now): ReturnType<typeof readSources> {
82
+ const held = shared.get(hubs)
83
+ if (held != null && (held.end == null || now() - held.end < INBOX_SHARE_MS)) return held.read
84
+ const entry: { end: number | null; read: ReturnType<typeof readSources> } = { end: null, read: readSources(hubs) }
85
+ shared.set(hubs, entry)
86
+ entry.read.then(() => { entry.end = now() }, () => { if (shared.get(hubs) === entry) shared.delete(hubs) })
87
+ return entry.read
88
+ }
89
+
22
90
  /** what every hub that is up holds, read in parallel; a repo whose read broke is named, never dropped silently */
23
- export async function inboxSources(hubs: Pick<Hubs, 'loaded'>): Promise<{ sources: (InboxSource & { root: string })[]; missing: InboxAnswer['missing'] }> {
91
+ async function readSources(hubs: Pick<Hubs, 'loaded'>): Promise<{ sources: (InboxSource & { root: string })[]; missing: InboxAnswer['missing'] }> {
24
92
  const missing: InboxAnswer['missing'] = []
25
93
  const read = await Promise.all(
26
94
  hubs.loaded().map(async ({ repo, rt }) => {
27
95
  try {
28
- return { repo: repo.name, root: repo.path, review: storeIndex(repo.path), needs: await rt.handler.needs() }
96
+ const [needs, log] = await Promise.all([rt.handler.needs(), recentCommits(repo.path)])
97
+ return { repo: repo.name, root: repo.path, review: storeIndex(repo.path), needs, log }
29
98
  } catch (e) {
30
99
  missing.push({ repo: repo.name, why: `its items could not be read: ${(e as Error).message}` })
31
100
  return null
32
101
  }
33
102
  }),
34
103
  )
35
- return { sources: read.filter((s) => s != null), missing }
104
+ const ok = read.filter((s) => s != null)
105
+ const quiet = quietOf(new Map(ok.map((s) => [s.repo, s.log])))
106
+ return { sources: ok.map(({ log: _, ...s }) => ({ ...s, quietSince: quiet.get(s.repo) ?? null })), missing }
36
107
  }
37
108
 
38
109
  /** one page of the inbox, 304 when the page holds this answer already; gzipped when the browser takes it */