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
@@ -40,11 +40,17 @@ export interface Space {
40
40
  /** the object's size, null when it is not there; throws on any other answer */
41
41
  head(key: string): Promise<{ size: number } | null>
42
42
  /** a GET URL good for `seconds`, on the CDN edge when the Space has one: signed for the origin host, which the edge
43
- * checks it against (a URL signed for the edge's own host answers SignatureDoesNotMatch) */
44
- signed(key: string, seconds?: number): string
43
+ * checks it against (a URL signed for the edge's own host answers SignatureDoesNotMatch). `as` signs a download
44
+ * under that file name: `response-content-disposition` and `response-content-type` ride in the signed query */
45
+ signed(key: string, seconds?: number, as?: { name: string; type: string }): string
45
46
  /** the object written at `to`, through a file beside it renamed: no reader sees half of it */
46
47
  get(key: string, to: string): Promise<void>
47
- delete(key: string): Promise<void>
48
+ /** every object under the prefix, with its size, page after page (ListObjectsV2) */
49
+ list(prefix: string): Promise<{ key: string; size: number }[]>
50
+ /** the bucket's versioning: `Enabled`, `Suspended`, or `off` when it was never turned on (GetBucketVersioning) */
51
+ versioning(): Promise<'Enabled' | 'Suspended' | 'off'>
52
+ /** turns versioning on, so an object deleted or overwritten from outside keeps its older version (PutBucketVersioning) */
53
+ enableVersioning(): Promise<void>
48
54
  }
49
55
 
50
56
  const missing = (e: unknown): boolean => {
@@ -52,6 +58,41 @@ const missing = (e: unknown): boolean => {
52
58
  return x.code === 'NoSuchKey' || x.code === 'NotFound' || /\b404\b|NoSuchKey|not found/i.test(`${x.name ?? ''} ${x.message ?? ''}`)
53
59
  }
54
60
 
61
+ /** the longest a signed URL can last: the SigV4 limit */
62
+ export const SIGNED_MAX_S = 7 * 86_400
63
+
64
+ /** `attachment` under the name: a plain ascii fallback, the exact name in `filename*` when it is not ascii */
65
+ export function attachment(name: string): string {
66
+ const plain = name.replace(/[^\x20-\x7e]|["\\]/g, '_')
67
+ return plain === name ? `attachment; filename="${name}"` : `attachment; filename="${plain}"; filename*=UTF-8''${encodeURIComponent(name)}`
68
+ }
69
+
70
+ const hex = (b: ArrayBuffer | Uint8Array): string => Buffer.from(b instanceof Uint8Array ? b : new Uint8Array(b)).toString('hex')
71
+ const sha256 = (s: string): string => new Bun.CryptoHasher('sha256').update(s).digest('hex')
72
+ const hmac = (key: string | Uint8Array, s: string): Uint8Array => new Uint8Array(new Bun.CryptoHasher('sha256', key).update(s).digest())
73
+
74
+ /** one bucket call Bun's S3 client has no verb for, signed by hand (SigV4, header auth): `?<sub>` on the bucket */
75
+ async function bucketCall(c: SpaceConfig, method: 'GET' | 'PUT', sub: string, body = ''): Promise<string> {
76
+ const url = new URL(c.path === true ? `${c.endpoint}/${c.bucket}` : `${c.endpoint}/`)
77
+ url.search = sub
78
+ const now = new Date().toISOString().replace(/[-:]|\.\d{3}/g, '')
79
+ const day = now.slice(0, 8)
80
+ const payload = sha256(body)
81
+ const headers: Record<string, string> = { host: url.host, 'x-amz-content-sha256': payload, 'x-amz-date': now }
82
+ const names = Object.keys(headers).sort()
83
+ const canonical = [method, url.pathname, `${sub}=`, ...names.map((n) => `${n}:${headers[n]}`), '', names.join(';'), payload].join('\n')
84
+ const scope = `${day}/${c.region}/s3/aws4_request`
85
+ const toSign = ['AWS4-HMAC-SHA256', now, scope, sha256(canonical)].join('\n')
86
+ const k = hmac(hmac(hmac(hmac(`AWS4${c.creds.secretAccessKey}`, day), c.region), 's3'), 'aws4_request')
87
+ const auth = `AWS4-HMAC-SHA256 Credential=${c.creds.accessKeyId}/${scope}, SignedHeaders=${names.join(';')}, Signature=${hex(hmac(k, toSign))}`
88
+ const { host: _, ...sent } = headers
89
+ const md5: Record<string, string> = body !== '' ? { 'Content-MD5': new Bun.CryptoHasher('md5').update(body).digest('base64') } : {}
90
+ const r = await fetch(url, { method, headers: { ...sent, ...md5, Authorization: auth }, ...(body !== '' ? { body } : {}) })
91
+ const text = await r.text()
92
+ if (!r.ok) throw new Error(`${method} ?${sub} on ${c.bucket}: ${r.status} ${/<Code>([^<]+)<\/Code>/.exec(text)?.[1] ?? text.slice(0, 200)}`)
93
+ return text
94
+ }
95
+
55
96
  export function spaceOf(c: SpaceConfig): Space {
56
97
  const client = new S3Client({ ...c.creds, bucket: c.bucket, region: c.region, endpoint: c.endpoint, virtualHostedStyle: c.path !== true })
57
98
  const origin = new URL(c.endpoint).host
@@ -70,8 +111,8 @@ export function spaceOf(c: SpaceConfig): Space {
70
111
  throw e
71
112
  }
72
113
  },
73
- signed(key, seconds = SIGNED_S) {
74
- const url = new URL(client.presign(key, { expiresIn: seconds, method: 'GET' }))
114
+ signed(key, seconds = SIGNED_S, as) {
115
+ const url = new URL(client.presign(key, { expiresIn: seconds, method: 'GET', ...(as ? { contentDisposition: attachment(as.name), type: as.type } : {}) }))
75
116
  if (edge && url.host === origin) url.host = edge
76
117
  return url.toString()
77
118
  },
@@ -85,8 +126,22 @@ export function spaceOf(c: SpaceConfig): Space {
85
126
  rmSync(tmp, { force: true })
86
127
  }
87
128
  },
88
- async delete(key) {
89
- await client.delete(key)
129
+ async list(prefix) {
130
+ const out: { key: string; size: number }[] = []
131
+ let token: string | undefined
132
+ do {
133
+ const page = await client.list({ prefix, maxKeys: 1000, ...(token ? { continuationToken: token } : {}) })
134
+ for (const o of page.contents ?? []) out.push({ key: o.key, size: o.size ?? 0 })
135
+ token = page.isTruncated ? page.nextContinuationToken : undefined
136
+ } while (token)
137
+ return out
138
+ },
139
+ async versioning() {
140
+ const s = /<Status>([^<]+)<\/Status>/.exec(await bucketCall(c, 'GET', 'versioning'))?.[1]
141
+ return s === 'Enabled' || s === 'Suspended' ? s : 'off'
142
+ },
143
+ async enableVersioning() {
144
+ await bucketCall(c, 'PUT', 'versioning', '<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Status>Enabled</Status></VersioningConfiguration>')
90
145
  },
91
146
  }
92
147
  }
@@ -95,7 +150,14 @@ let held: Promise<{ space: Space | null; why: string }> | null = null
95
150
 
96
151
  /** the machine's Space, from the house config and its key, read once per process; null with the reason when there is none */
97
152
  export function machineSpace(): Promise<{ space: Space | null; why: string }> {
98
- held ??= (async () => {
153
+ held ??= spaceFromHouse()
154
+ return held
155
+ }
156
+
157
+ /** the house's Space signed with the key pair of `secret` (the config's own key when none is given), read anew: a one
158
+ * time key with more rights (turning versioning on) never replaces the machine's held one */
159
+ export function spaceFromHouse(secret?: string): Promise<{ space: Space | null; why: string }> {
160
+ return (async () => {
99
161
  if (process.env.SHIPKIT_SPACES === 'off') return { space: null, why: 'SHIPKIT_SPACES=off' }
100
162
  const { houseRootOf } = await import('../home/home-start.ts')
101
163
  const { loadRepoConfig } = await import('../repo-config.ts')
@@ -105,17 +167,17 @@ export function machineSpace(): Promise<{ space: Space | null; why: string }> {
105
167
  const r = c.serve?.mediaSpace
106
168
  if (!r) return { space: null, why: `the house config (${house}) names no serve.mediaSpace` }
107
169
  if (!c.credsReadCommand) return { space: null, why: `the house config (${house}) declares no credsReadCommand to read ${r.secret}` }
170
+ const name = secret ?? r.secret
108
171
  let v = ''
109
172
  try {
110
- v = readSecret(c.credsReadCommand, r.secret)
173
+ v = readSecret(c.credsReadCommand, name)
111
174
  } catch (e) {
112
175
  return { space: null, why: (e as Error).message }
113
176
  }
114
177
  const at = v.indexOf(':')
115
- if (at <= 0) return { space: null, why: `the secret ${r.secret} is no KEY:SECRET pair` }
178
+ if (at <= 0) return { space: null, why: `the secret ${name} is no KEY:SECRET pair` }
116
179
  return { space: spaceOf({ ...r, cdn: r.cdn ?? null, creds: { accessKeyId: v.slice(0, at), secretAccessKey: v.slice(at + 1) } }), why: '' }
117
180
  })().catch((e: unknown) => ({ space: null, why: `the house config does not load: ${(e as Error).message}` }))
118
- return held
119
181
  }
120
182
 
121
183
  /** a test's own Space in place of the machine's; undefined gives the machine's back */
@@ -0,0 +1,35 @@
1
+ // a repo page's request sent on to the repo's process and streamed back (wiki build/shipkit/project-pages.md, The
2
+ // proxy): the daemon's hub route and the web's direct path both go through here. Light on purpose: the web imports it
3
+ /** what names the browser or this hop: the page's process sees a plain local client */
4
+ const DROP = new Set(['host', 'origin', 'referer', 'sec-fetch-site', 'sec-fetch-mode', 'sec-fetch-dest', 'connection', 'keep-alive', 'content-length'])
5
+ const NO_STORE = { 'cache-control': 'no-store' }
6
+
7
+ export const PAGE_DOWN_HEADER = 'x-shipkit-page'
8
+
9
+ /** a page's request, sent on to its process and streamed back: `target` the page's url plus the rest. The process down
10
+ * answers 502 with PAGE_DOWN_HEADER, which the hub's frame reads as « start it » */
11
+ export async function forwardPage(req: Request, target: string, id: string, process: string | undefined, srv: { timeout: (req: Request, seconds: number) => void } | undefined): Promise<Response> {
12
+ const headers = new Headers()
13
+ req.headers.forEach((v, k) => { if (!DROP.has(k)) headers.set(k, v) })
14
+ // a live channel stays silent between reloads: never cut
15
+ srv?.timeout(req, 0)
16
+ const body = req.method === 'GET' || req.method === 'HEAD' ? undefined : await req.arrayBuffer()
17
+ try {
18
+ const r = await fetch(`${target}${new URL(req.url).search}`, { method: req.method, headers, body, redirect: 'manual', decompress: false } as RequestInit)
19
+ const out = new Headers(r.headers)
20
+ out.delete('content-length')
21
+ out.delete('transfer-encoding')
22
+ out.delete('connection')
23
+ return new Response(r.body, { status: r.status, statusText: r.statusText, headers: out })
24
+ } catch (e) {
25
+ const text = `the page ${id} does not answer on ${target} (${(e as Error).message})${process ? `: sk gp start ${process}` : ''}`
26
+ return new Response(text, { status: 502, headers: { 'content-type': 'text/plain; charset=utf-8', [PAGE_DOWN_HEADER]: 'down', ...NO_STORE } })
27
+ }
28
+ }
29
+
30
+ /** `/page/<id>/<rest>` of a hub: the page and the rest of its path, or null; a bare `/page/<id>` has rest null */
31
+ export function pagePath(path: string): { id: string; rest: string | null } | null {
32
+ const m = /^\/page\/([a-z][a-z0-9-]*)(\/.*)?$/.exec(path)
33
+ return m == null ? null : { id: m[1]!, rest: m[2] === undefined ? null : m[2].slice(1) }
34
+ }
35
+
@@ -0,0 +1,118 @@
1
+ // the page side of a repo page's frame (wiki build/shipkit/project-pages.md, The frame contract): the one module a
2
+ // repo's page bundles to live in the hub. No framework, no hub code beyond the keys table. Framed, it speaks the
3
+ // `{ shipkit: <verb> }` messages on its origin; alone at its own url, it keeps the keys in its own address, so the
4
+ // page works the same either way
5
+ import { pageKey, pageLetterKey, sectionKey } from '../serve/hub-app/keys.ts'
6
+
7
+ export type FrameTheme = 'dark' | 'light'
8
+ export type FrameBadge = { count: number; tone?: 'red' | 'warn' | null; title?: string }
9
+
10
+ export interface FrameOpts {
11
+ /** the page's state as url keys: from the hub's address, or the page's own; the page applies them */
12
+ onKeys(keys: string): void
13
+ onTheme?(theme: FrameTheme): void
14
+ /** the identity the repo speaks as (its `speaksAs`, else the machine's default), null with none; alone: never called */
15
+ onIdentity?(identity: string | null): void
16
+ /** shown (true) or hidden (false): a page stops its sound */
17
+ onFocus?(on: boolean): void
18
+ /** a relative path of the page's process sending `reload` when its bundle moved (an EventSource). Open only while
19
+ * the page shows: a browser holds six connections to one origin, and the hub needs them. On each open it carries
20
+ * `?build=<the page's module script>`, so the process can say at once that the page runs an older build */
21
+ live?: string
22
+ /** a plain message of the live channel (no event name): the page's own events, its data as sent */
23
+ onLive?(data: string): void
24
+ }
25
+
26
+ export interface PageFrame {
27
+ /** in the hub's frame, or alone at its url */
28
+ readonly framed: boolean
29
+ /** the page's state moved: the hub's address follows in place */
30
+ setKeys(keys: string): void
31
+ setTitle(title: string, badge?: FrameBadge | null): void
32
+ /** another hub page, by its address (`#page:review:<id>`) */
33
+ open(hash: string): void
34
+ stop(): void
35
+ }
36
+
37
+ type KeyLike = Pick<KeyboardEvent, 'key' | 'code' | 'altKey' | 'shiftKey' | 'metaKey' | 'ctrlKey'>
38
+
39
+ /** a key the hub owns: its ⌥ sections, a page's ⌥⇧ letter, the home's ⌘ keys */
40
+ export const hubOwns = (e: KeyLike): boolean => sectionKey(e) != null || pageLetterKey(e) != null || pageKey(e) != null
41
+
42
+ export function frameClient(o: FrameOpts): PageFrame {
43
+ const framed = typeof window !== 'undefined' && window.parent !== window
44
+ const origin = location.origin
45
+ const up = (m: Record<string, unknown>): void => { if (framed) window.parent.postMessage({ ...m }, origin) }
46
+ let last = framed ? '' : location.search.replace(/^\?/, '')
47
+ let live: EventSource | null = null
48
+ const openLive = (): void => {
49
+ if (o.live == null || live != null) return
50
+ const build = document.querySelector('script[type="module"][src]')?.getAttribute('src') ?? ''
51
+ live = new EventSource(`${o.live}?build=${encodeURIComponent(build)}`)
52
+ live.addEventListener('reload', () => location.reload())
53
+ if (o.onLive != null) live.onmessage = (e: MessageEvent<string>) => o.onLive?.(e.data)
54
+ }
55
+ const closeLive = (): void => {
56
+ live?.close()
57
+ live = null
58
+ }
59
+
60
+ const onMessage = (e: MessageEvent): void => {
61
+ if (e.source !== window.parent || e.origin !== origin) return
62
+ const m = (e.data ?? {}) as { shipkit?: unknown; keys?: unknown; theme?: unknown; identity?: unknown; on?: unknown }
63
+ if ((m.shipkit === 'hello' || m.shipkit === 'keys') && typeof m.keys === 'string') {
64
+ last = m.keys
65
+ o.onKeys(m.keys)
66
+ }
67
+ if ((m.shipkit === 'hello' || m.shipkit === 'theme') && (m.theme === 'dark' || m.theme === 'light')) o.onTheme?.(m.theme)
68
+ if ((m.shipkit === 'hello' || m.shipkit === 'identity') && (typeof m.identity === 'string' || m.identity === null)) o.onIdentity?.(m.identity)
69
+ if ((m.shipkit === 'hello' || m.shipkit === 'focus') && typeof m.on === 'boolean') {
70
+ if (m.on) openLive()
71
+ else closeLive()
72
+ o.onFocus?.(m.on)
73
+ }
74
+ }
75
+ // after the page's own handlers: a key it took stays its own
76
+ const onKey = (e: KeyboardEvent): void => {
77
+ if (e.defaultPrevented || !hubOwns(e)) return
78
+ e.preventDefault()
79
+ up({ shipkit: 'key', key: e.key, code: e.code, altKey: e.altKey, shiftKey: e.shiftKey, metaKey: e.metaKey, ctrlKey: e.ctrlKey })
80
+ }
81
+ const mq = framed ? null : window.matchMedia('(prefers-color-scheme: dark)')
82
+ const onScheme = (e: MediaQueryListEvent): void => o.onTheme?.(e.matches ? 'dark' : 'light')
83
+ if (framed) {
84
+ window.addEventListener('message', onMessage)
85
+ window.addEventListener('keydown', onKey)
86
+ up({ shipkit: 'ready' })
87
+ } else {
88
+ openLive()
89
+ o.onKeys(last)
90
+ if (mq != null) {
91
+ o.onTheme?.(mq.matches ? 'dark' : 'light')
92
+ mq.addEventListener('change', onScheme)
93
+ }
94
+ }
95
+
96
+ return {
97
+ framed,
98
+ setKeys(keys) {
99
+ if (keys === last) return
100
+ last = keys
101
+ if (framed) up({ shipkit: 'keys', keys })
102
+ else history.replaceState(history.state, '', `${location.pathname}${keys ? `?${keys}` : ''}${location.hash}`)
103
+ },
104
+ setTitle(title, badge) {
105
+ if (framed) up({ shipkit: 'title', title, ...(badge === undefined ? {} : { badge }) })
106
+ else document.title = title
107
+ },
108
+ open(hash) {
109
+ up({ shipkit: 'open', hash })
110
+ },
111
+ stop() {
112
+ window.removeEventListener('message', onMessage)
113
+ window.removeEventListener('keydown', onKey)
114
+ mq?.removeEventListener('change', onScheme)
115
+ closeLive()
116
+ },
117
+ }
118
+ }
@@ -0,0 +1,29 @@
1
+ // a repo's own pages on the hub (wiki build/shipkit/project-pages.md): their list, and the proxy that serves each one
2
+ // from the repo's process under the hub's origin, `/page/<id>/<rest>` to `<url><rest>`, streamed both ways. The one
3
+ // constraint a reader breaks first: a page must use relative paths, an absolute one reaches the hub, never the page
4
+ import { forwardPage, pagePath } from './forward.ts'
5
+ import { loadPages, type PageRow } from './unit.ts'
6
+
7
+ const NO_STORE = { 'cache-control': 'no-store' }
8
+
9
+ /** the repo's pages, or why they do not load */
10
+ async function list(root: string): Promise<{ pages: PageRow[]; problem: string | null }> {
11
+ try {
12
+ return { pages: await loadPages(root), problem: null }
13
+ } catch (e) {
14
+ return { pages: [], problem: (e as Error).message }
15
+ }
16
+ }
17
+
18
+ /** the pages' routes of the repo at `root`; null for any other path */
19
+ export async function pagesRoutes(root: string, req: Request, path: string, srv?: Bun.Server<unknown>): Promise<Response | null> {
20
+ if (path === '/api/pages.json') return Response.json(await list(root), { headers: NO_STORE })
21
+ const at = pagePath(path)
22
+ if (at == null) return null
23
+ // the page's own relative paths resolve from its folder
24
+ if (at.rest === null) return new Response(null, { status: 308, headers: { location: `${at.id}/${new URL(req.url).search}` } })
25
+ const { pages, problem } = await list(root)
26
+ const p = pages.find((x) => x.id === at.id)
27
+ if (p == null) return new Response(problem ?? `no page ${at.id} in this repo: a page({...}) unit declares one`, { status: 404, headers: NO_STORE })
28
+ return forwardPage(req, `${p.url}${at.rest}`, p.id, p.process, srv)
29
+ }
@@ -0,0 +1,92 @@
1
+ // a repo's own pages in its hub (wiki build/shipkit/project-pages.md): a `page({...})` unit of any `<name>.shipkit.ts`,
2
+ // one page or an array of them as the default export. Every unit file imports this module, so it stays light: the
3
+ // daemon reads the declarations and never the page's code
4
+ import { existsSync } from 'node:fs'
5
+ import { relative } from 'node:path'
6
+ import { importFresh } from '../core/discover-checks.ts'
7
+ import { unitFilesDeclaring } from '../core/unit-files.ts'
8
+
9
+ export interface PageDef {
10
+ /** the address part, `#page:<repo>/<id>`: a lowercase word */
11
+ id: string
12
+ /** the row's words */
13
+ title: string
14
+ /** a 20 unit stroked svg path, drawn as the hub's own icons */
15
+ icon: string
16
+ /** where the repo's process serves the page: a loopback http url ending in `/` */
17
+ url: string
18
+ /** the global process that serves it: the down page's start button */
19
+ process?: string
20
+ /** a path relative to `url` answering `{ count, tone?, title? }` */
21
+ badge?: string
22
+ /** ⌥⇧ + this letter opens it; else the first free letter of the title */
23
+ key?: string
24
+ /** it draws in WebGL: a hidden frame of it holds a context and its GPU memory, so fewer stay kept */
25
+ gl?: boolean
26
+ }
27
+
28
+ export type PageUnit = PageDef & { kind: 'page' }
29
+
30
+ /** a page as the hub's list serves it: its key settled, the file that declares it */
31
+ export type PageRow = Omit<PageDef, 'key'> & { key: string; file: string }
32
+
33
+ const WORD = /^[a-z][a-z0-9-]*$/
34
+ const LOOPBACK = /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?\/([^?#]*\/)?$/
35
+
36
+ /** why a page cannot be read, or null */
37
+ export function pageProblem(d: PageDef): string | null {
38
+ if (typeof d.id !== 'string' || !WORD.test(d.id)) return `page: id '${String(d.id)}' is a lowercase word`
39
+ if (typeof d.title !== 'string' || d.title.trim() === '') return `page ${d.id}: title is a text`
40
+ if (typeof d.icon !== 'string' || !/^M[\d\s.,MmLlHhVvCcSsQqTtAaZz-]+$/.test(d.icon)) return `page ${d.id}: icon is an svg path, starting with M`
41
+ if (typeof d.url !== 'string' || !LOOPBACK.test(d.url)) return `page ${d.id}: url '${String(d.url)}' is a loopback http url ending in /`
42
+ if (d.process !== undefined && (typeof d.process !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(d.process))) return `page ${d.id}: process '${String(d.process)}' is a global process id`
43
+ if (d.badge !== undefined && (typeof d.badge !== 'string' || d.badge.startsWith('/') || d.badge.includes('..') || d.badge === '')) return `page ${d.id}: badge '${String(d.badge)}' is a path relative to url`
44
+ if (d.key !== undefined && (typeof d.key !== 'string' || !/^[A-Z]$/.test(d.key))) return `page ${d.id}: key '${String(d.key)}' is one capital letter`
45
+ if (d.gl !== undefined && typeof d.gl !== 'boolean') return `page ${d.id}: gl is true or false`
46
+ return null
47
+ }
48
+
49
+ export function page(d: PageDef): PageUnit {
50
+ const why = pageProblem(d)
51
+ if (why !== null) throw new Error(why)
52
+ return { ...d, kind: 'page' }
53
+ }
54
+
55
+ /** each page's letter: its own, else the first letter of its title no earlier page took; null past 26 */
56
+ export function settleKeys(defs: readonly PageDef[]): (string | null)[] {
57
+ const taken = new Set(defs.flatMap((d) => (d.key === undefined ? [] : [d.key])))
58
+ return defs.map((d) => {
59
+ if (d.key !== undefined) return d.key
60
+ const letters = [...d.title.toUpperCase().normalize('NFD').replace(/[^A-Z]/g, ''), ...'ABCDEFGHIJKLMNOPQRSTUVWXYZ']
61
+ const free = letters.find((l) => !taken.has(l)) ?? null
62
+ if (free !== null) taken.add(free)
63
+ return free
64
+ })
65
+ }
66
+
67
+ const isPage = (u: unknown): u is PageUnit => typeof u === 'object' && u !== null && (u as { kind?: unknown }).kind === 'page'
68
+
69
+ /** the repo's pages in declaration order, files sorted; a wrong unit, a twice used id or key throws naming the files */
70
+ export async function loadPages(root: string): Promise<PageRow[]> {
71
+ if (!existsSync(root)) return []
72
+ const found: { file: string; def: PageDef }[] = []
73
+ for (const f of [...unitFilesDeclaring(root, 'page')].sort()) {
74
+ const d = (await importFresh(f)) as unknown
75
+ const file = relative(root, f)
76
+ for (const u of Array.isArray(d) ? d : [d]) {
77
+ if (!isPage(u)) continue
78
+ const why = pageProblem(u)
79
+ if (why !== null) throw new Error(`${file}: ${why}`)
80
+ const twin = found.find((x) => x.def.id === u.id || (u.key !== undefined && x.def.key === u.key))
81
+ if (twin) throw new Error(`two pages share ${twin.def.id === u.id ? `the id ${u.id}` : `the key ${u.key}`}: ${twin.file} and ${file}`)
82
+ found.push({ file, def: u })
83
+ }
84
+ }
85
+ const keys = settleKeys(found.map((x) => x.def))
86
+ return found.flatMap((x, i) => {
87
+ const key = keys[i]
88
+ if (key == null) return []
89
+ const d = x.def
90
+ return [{ id: d.id, title: d.title, icon: d.icon, url: d.url, ...(d.process ? { process: d.process } : {}), ...(d.badge ? { badge: d.badge } : {}), ...(d.gl === true ? { gl: true } : {}), key, file: x.file }]
91
+ })
92
+ }
@@ -17,6 +17,7 @@
17
17
  import { availableParallelism, loadavg } from 'os'
18
18
  import { CATCH_UP_BEAT_MS, resumeCatchUp, type CatchUpStore } from './catch-up.ts'
19
19
  import { nextDue, resolveCadence, resolveWhenInactive, stablePoint, type EveryValue, type LastResult, type PlanDecl } from './cadence.ts'
20
+ import { yieldLoop } from '../core/loop-watch.ts'
20
21
 
21
22
  export type PlanReason = 'changed' | 'scheduled' | 'late' | 'asked'
22
23
 
@@ -377,6 +378,17 @@ export class Planner {
377
378
  return out
378
379
  }
379
380
 
381
+ /** the last results of every repo whose look is due, read one repo at a time with the loop given back between
382
+ * two, so the sync reads of the run records never stand together (wiki build/shipkit/home.md, Nothing heavy on
383
+ * the daemon's loop). The host calls it before `tick`, which then finds them read */
384
+ async refresh(): Promise<void> {
385
+ for (const r of [...this.repos.values()]) {
386
+ if (this.now() - r.lastRead < LAST_EVERY_MS) continue
387
+ await yieldLoop()
388
+ if (this.repos.get(r.src.repo) === r) this.readLast(r)
389
+ }
390
+ }
391
+
380
392
  /** a batch is in flight */
381
393
  busy(): boolean {
382
394
  return this.running != null
@@ -16,6 +16,7 @@ import { planned } from '../core/runs.ts'
16
16
  import { ONCE, type LastResult } from './cadence.ts'
17
17
  import { openDb } from '../ledger/db.ts'
18
18
  import { readLastResults } from '../ledger/run-log.ts'
19
+ import { recordFileStamp } from '../ledger/record-kept.ts'
19
20
  import { gateBinary } from '../ledger/toolchain-identity.ts'
20
21
  import { populationOf } from '../problems/problem-line.ts'
21
22
  import { movedSince } from '../serve/tracked-watch.ts'
@@ -72,7 +73,10 @@ export function readLastCosts(path: string): Record<string, { at: number; ms: nu
72
73
  if (opened == null) return {}
73
74
  const out: Record<string, { at: number; ms: number }> = {}
74
75
  try {
75
- const rows = opened.db.query(`select id, max(at) as at, ms from runs where replayed = 0 group by id`).all() as { id: string; at: number; ms: number }[]
76
+ // per check id off the (id, at) index: a group by over every row held the daemon's loop on a large record
77
+ const rows = opened.db.query(`select r.id as id, r.at as at, r.ms as ms
78
+ from (select d.id as id, (select r2.rowid from runs r2 where r2.id = d.id and r2.replayed = 0 order by r2.at desc limit 1) as rid from (select distinct id from runs) d) x
79
+ join runs r on r.rowid = x.rid`).all() as { id: string; at: number; ms: number }[]
76
80
  for (const r of rows) out[r.id] = { at: Number(r.at), ms: Number(r.ms) }
77
81
  } catch {
78
82
  return {}
@@ -122,6 +126,16 @@ export function repoSource(d: RepoSourceDeps): PlanSource {
122
126
  const moved = new Set<string>()
123
127
  const facts = new Map<string, string>()
124
128
  const cache = (): WorldCache => ({ db: answersDb(d.root), ns: d.config().name, now: Date.now })
129
+ /** the three reads of the run record the plan looks at every LAST_EVERY_MS, read again only once the record moved:
130
+ * over a large record they are a sync read of every run (wiki build/shipkit/home.md, Nothing heavy on the daemon's
131
+ * loop) */
132
+ let held: { stamp: string; results: Record<string, LastResult>; costs: Record<string, { at: number; ms: number }>; gatedAt: number | null } | null = null
133
+ const readRecord = (): NonNullable<typeof held> => {
134
+ if (d.record === '') return { stamp: '', results: {}, costs: {}, gatedAt: null }
135
+ const stamp = recordFileStamp(d.record)
136
+ if (held?.stamp !== stamp) held = { stamp, results: readLastResults(d.record), costs: readLastCosts(d.record), gatedAt: lastStarted(d.record, { asked: true }) }
137
+ return held
138
+ }
125
139
  return {
126
140
  repo: d.repo,
127
141
  checks: async () => {
@@ -136,18 +150,18 @@ export function repoSource(d: RepoSourceDeps): PlanSource {
136
150
  return rows.map(planCheckOf)
137
151
  },
138
152
  last: () => {
139
- const all: Record<string, LastResult> = d.record === '' ? {} : readLastResults(d.record)
153
+ const read = readRecord()
154
+ const all: Record<string, LastResult> = { ...read.results }
140
155
  // a fact with no answer runs; one whose probe could not answer
141
156
  // retries on a backoff from its skip, never at each boot
142
157
  for (const id of unknown) {
143
158
  if (all[id]?.status === 'skip') all[id] = { ...all[id]!, unknown: true }
144
159
  else delete all[id]
145
160
  }
146
- const costs = d.record === '' ? {} : readLastCosts(d.record)
147
- for (const [id, cost] of Object.entries(costs)) if (all[id] != null) all[id] = { ...all[id]!, cost }
161
+ for (const [id, cost] of Object.entries(read.costs)) if (all[id] != null) all[id] = { ...all[id]!, cost }
148
162
  return all
149
163
  },
150
- gatedAt: () => (d.record === '' ? null : lastStarted(d.record, { asked: true })),
164
+ gatedAt: () => readRecord().gatedAt,
151
165
  changed: async () => {
152
166
  const decls = rows.map((r) => r.decl)
153
167
  if (decls.length === 0) return []
@@ -85,7 +85,7 @@ export type RawEntry = {
85
85
  /** queue-operation entries only */
86
86
  operation?: unknown
87
87
  content?: unknown
88
- message?: { role?: unknown; content?: unknown }
88
+ message?: { role?: unknown; content?: unknown; id?: unknown; model?: unknown; usage?: { input_tokens?: unknown; output_tokens?: unknown; cache_read_input_tokens?: unknown; cache_creation_input_tokens?: unknown } }
89
89
  toolUseResult?: unknown
90
90
  /** on a tool_result entry: who allowed the call (`config`, `user_temporary`, …) */
91
91
  permissionDecision?: { source?: unknown; reasonType?: unknown }
@@ -179,9 +179,41 @@ export function detailOf(name: string, input: unknown): string {
179
179
  if (name === 'Skill') return clip(str('skill'))
180
180
  if (name === 'WebFetch') return clip(str('url'))
181
181
  if (name === 'Monitor' || name === 'TaskOutput' || name === 'TaskStop') return clip(str('description') || str('task_id'))
182
+ if (name === 'Read' || name === 'Edit' || name === 'Write' || name === 'MultiEdit' || name === 'NotebookEdit') return clip(str('file_path') || str('notebook_path'))
183
+ if (name === 'Grep' || name === 'Glob') return clip([str('pattern'), str('path')].filter((s) => s !== '').join(' '))
182
184
  return ''
183
185
  }
184
186
 
187
+ /** one transcript line as an entry, or null for a line no reader wants (the
188
+ * same skip as readTranscriptLine): for a reader that needs more than events */
189
+ export function parseEntry(line: string): RawEntry | null {
190
+ if (line.startsWith('{"type":"') && !KEPT_TYPE_PREFIXES.some((p) => line.startsWith(p))) return null
191
+ try {
192
+ const parsed: unknown = JSON.parse(line)
193
+ return parsed != null && typeof parsed === 'object' ? (parsed as RawEntry) : null
194
+ } catch {
195
+ return null
196
+ }
197
+ }
198
+
199
+ export type Usage = { messageId: string; input: number; output: number; cacheRead: number; cacheWrite: number; model: string }
200
+
201
+ /** the token usage an assistant entry carries. The harness writes one entry per
202
+ * content block, each with the same message id and usage, so a reader counts
203
+ * each message id once */
204
+ export function usageOf(entry: RawEntry): Usage | null {
205
+ if (entry.type !== 'assistant') return null
206
+ const m = entry.message
207
+ const u = m?.usage
208
+ if (m == null || u == null || typeof m.id !== 'string') return null
209
+ const n = (v: unknown): number => (typeof v === 'number' ? v : 0)
210
+ return { messageId: m.id, input: n(u.input_tokens), output: n(u.output_tokens), cacheRead: n(u.cache_read_input_tokens), cacheWrite: n(u.cache_creation_input_tokens), model: typeof m.model === 'string' ? m.model : '' }
211
+ }
212
+
213
+ /** the text of a user entry, typed or not (a sub-agent's task prompt is a
214
+ * sidechain entry nobody typed), reminders stripped */
215
+ export const userTextOf = (entry: RawEntry): string | null => (entry.type === 'user' && entry.message?.role === 'user' ? userText(entry) : null)
216
+
185
217
  const resultText = (content: unknown): string => {
186
218
  if (typeof content === 'string') return content
187
219
  if (Array.isArray(content)) {
@@ -199,15 +231,8 @@ const KEPT_TYPE_PREFIXES = ['{"type":"user"', '{"type":"assistant"', '{"type":"q
199
231
  /** every event one transcript line holds; [] for anything else, a truncated
200
232
  * tail line of a live session included */
201
233
  export function readTranscriptLine(line: string): TranscriptEvent[] {
202
- if (line.startsWith('{"type":"') && !KEPT_TYPE_PREFIXES.some((p) => line.startsWith(p))) return []
203
- let parsed: unknown
204
- try {
205
- parsed = JSON.parse(line)
206
- } catch {
207
- return []
208
- }
209
- if (parsed == null || typeof parsed !== 'object') return []
210
- return eventsOf(parsed as RawEntry)
234
+ const entry = parseEntry(line)
235
+ return entry == null ? [] : eventsOf(entry)
211
236
  }
212
237
 
213
238
  export function eventsOf(entry: RawEntry): TranscriptEvent[] {