rvlib-shipkit 2.12.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 (290) hide show
  1. package/CHANGELOG.md +48 -13
  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 +7 -5
  20. package/src/cli/cmd_Review.ts +4 -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 +5 -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 +53 -4
  68. package/src/home/inbox.ts +16 -1
  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 +104 -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 +2 -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/daemon.ts +56 -70
  100. package/src/media-store/put.ts +4 -2
  101. package/src/media-store/space.ts +23 -4
  102. package/src/pages/forward.ts +35 -0
  103. package/src/pages/frame-client.ts +118 -0
  104. package/src/pages/routes.ts +29 -0
  105. package/src/pages/unit.ts +92 -0
  106. package/src/plan/planner.ts +12 -0
  107. package/src/plan/repo-source.ts +19 -5
  108. package/src/reflect/transcript.ts +35 -10
  109. package/src/release/public-clean.ts +301 -0
  110. package/src/release/published-here.ts +22 -0
  111. package/src/release/run-bump.ts +2 -1
  112. package/src/release/run-release.ts +4 -1
  113. package/src/repo-config.ts +53 -2
  114. package/src/review/http.ts +16 -2
  115. package/src/review/model.ts +15 -4
  116. package/src/review/notes.ts +77 -0
  117. package/src/review/project.ts +6 -38
  118. package/src/review/routes.ts +4 -12
  119. package/src/review/store.ts +41 -1
  120. package/src/review/trailer-media.ts +7 -4
  121. package/src/review/trailer-shots.ts +21 -4
  122. package/src/review/unit.ts +1 -1
  123. package/src/scaffold/files/agent-handoff.md +3 -0
  124. package/src/scaffold/files/agent-index.md +4 -12
  125. package/src/scaffold/project-scaffold.ts +5 -4
  126. package/src/serve/embed.ts +1 -1
  127. package/src/serve/hub-app/col-card.tsx +3 -17
  128. package/src/serve/hub-app/col-tables-view.tsx +2 -1
  129. package/src/serve/hub-app/cols-svc.ts +0 -13
  130. package/src/serve/hub-app/dock-st.ts +4 -2
  131. package/src/serve/hub-app/dock-view.tsx +2 -0
  132. package/src/serve/hub-app/frames-st.ts +35 -0
  133. package/src/serve/hub-app/hash-route.ts +64 -1
  134. package/src/serve/hub-app/home-st.ts +31 -7
  135. package/src/serve/hub-app/home-strip.css +9 -1
  136. package/src/serve/hub-app/home-strip.tsx +7 -6
  137. package/src/serve/hub-app/home.html +5 -0
  138. package/src/serve/hub-app/hub-app.tsx +49 -5
  139. package/src/serve/hub-app/hub.css +29 -11
  140. package/src/serve/hub-app/icons.tsx +16 -1
  141. package/src/serve/hub-app/identities-st.ts +210 -0
  142. package/src/serve/hub-app/identities-view.tsx +352 -0
  143. package/src/serve/hub-app/identities.css +48 -0
  144. package/src/serve/hub-app/identity-address.ts +52 -0
  145. package/src/serve/hub-app/inbox-st.ts +59 -6
  146. package/src/serve/hub-app/inbox-view.tsx +48 -6
  147. package/src/serve/hub-app/inbox.css +12 -1
  148. package/src/serve/hub-app/index.html +3 -0
  149. package/src/serve/hub-app/keys.ts +10 -2
  150. package/src/serve/hub-app/list-walk.ts +89 -0
  151. package/src/serve/hub-app/machine-st.ts +12 -0
  152. package/src/serve/hub-app/media-view.tsx +2 -1
  153. package/src/serve/hub-app/pages-frames.tsx +134 -0
  154. package/src/serve/hub-app/pages-svc.ts +111 -0
  155. package/src/serve/hub-app/palette-st.ts +18 -3
  156. package/src/serve/hub-app/palette-view.tsx +9 -2
  157. package/src/serve/hub-app/planned-view.tsx +2 -1
  158. package/src/serve/hub-app/project-list.css +18 -14
  159. package/src/serve/hub-app/project-list.tsx +88 -49
  160. package/src/serve/hub-app/projects-svc.ts +33 -3
  161. package/src/serve/hub-app/repo-sections.ts +19 -2
  162. package/src/serve/hub-app/repo-st.ts +75 -19
  163. package/src/serve/hub-app/review/review-cells.tsx +3 -3
  164. package/src/serve/hub-app/review/review-kit.ts +30 -7
  165. package/src/serve/hub-app/review/review-page.tsx +1 -1
  166. package/src/serve/hub-app/review/review-st.ts +19 -8
  167. package/src/serve/hub-app/review/review-thread.tsx +11 -9
  168. package/src/serve/hub-app/review/review-views.tsx +84 -19
  169. package/src/serve/hub-app/review/thread-st.ts +1 -10
  170. package/src/serve/hub-app/review/trailer-page.tsx +2 -1
  171. package/src/serve/hub-app/review.css +17 -8
  172. package/src/serve/hub-app/site/site-part.tsx +173 -0
  173. package/src/serve/hub-app/site/site-st.ts +157 -0
  174. package/src/serve/hub-app/site.css +35 -0
  175. package/src/serve/hub-app/social/calendar.tsx +182 -0
  176. package/src/serve/hub-app/social/comms-page.tsx +306 -0
  177. package/src/serve/hub-app/social/kit.tsx +244 -0
  178. package/src/serve/hub-app/social/post-card.tsx +456 -0
  179. package/src/serve/hub-app/social/problems.tsx +60 -0
  180. package/src/serve/hub-app/social/social-model.ts +154 -0
  181. package/src/serve/hub-app/social/social-page.tsx +674 -0
  182. package/src/serve/hub-app/social/social-st.ts +986 -0
  183. package/src/serve/hub-app/social.css +289 -0
  184. package/src/serve/hub-app/stores/stores-page.tsx +311 -0
  185. package/src/serve/hub-app/stores/stores-st.ts +286 -0
  186. package/src/serve/hub-app/stores.css +54 -0
  187. package/src/serve/hub-app/timeline-geometry.ts +1 -1
  188. package/src/serve/hub-app/timeline-view.tsx +3 -2
  189. package/src/serve/hub-app/tree-build.ts +6 -0
  190. package/src/serve/hub-app/tree-row.tsx +27 -4
  191. package/src/serve/hub-app/tree-svc.ts +18 -49
  192. package/src/serve/hub-app/veille/veille-page.tsx +514 -0
  193. package/src/serve/hub-app/veille/veille-st.ts +443 -0
  194. package/src/serve/hub-app/veille.css +84 -0
  195. package/src/serve/hub-runtime.ts +14 -9
  196. package/src/serve/project-gutter-route.ts +44 -12
  197. package/src/serve/run-lanes.ts +7 -4
  198. package/src/serve/same-origin.ts +1 -1
  199. package/src/serve/serve-hub.ts +20 -12
  200. package/src/serve/tracked-watch.ts +24 -3
  201. package/src/serve/warm-cell.ts +5 -1
  202. package/src/shipkit-files.ts +15 -4
  203. package/src/shipkit.ts +0 -1
  204. package/src/shot/box.ts +162 -0
  205. package/src/shot/browser-slot.ts +62 -0
  206. package/src/shot/client.ts +43 -7
  207. package/src/shot/clip-encoder.ts +93 -12
  208. package/src/shot/film-box.ts +188 -0
  209. package/src/shot/shooter.ts +50 -15
  210. package/src/shot/shot-ask.ts +10 -2
  211. package/src/shot/stepped-clip.ts +5 -4
  212. package/src/site/desk.ts +242 -0
  213. package/src/site/routes.ts +66 -0
  214. package/src/site/unit.ts +62 -0
  215. package/src/social/brands.ts +22 -0
  216. package/src/social/compose.ts +97 -0
  217. package/src/social/desk-index.ts +123 -0
  218. package/src/social/desk-wire.ts +64 -0
  219. package/src/social/drafts.ts +183 -0
  220. package/src/social/house.ts +24 -0
  221. package/src/social/load.ts +319 -0
  222. package/src/social/md.ts +70 -0
  223. package/src/social/media-facts.ts +53 -0
  224. package/src/social/media-kind.ts +189 -0
  225. package/src/social/media-limit.ts +42 -0
  226. package/src/social/media-of.ts +30 -0
  227. package/src/social/migrate.ts +123 -0
  228. package/src/social/open.ts +17 -0
  229. package/src/social/post-url.ts +158 -0
  230. package/src/social/presence.ts +332 -0
  231. package/src/social/public-read.ts +53 -0
  232. package/src/social/publish/bluesky.ts +168 -0
  233. package/src/social/publish/discord.ts +76 -0
  234. package/src/social/publish/index.ts +24 -0
  235. package/src/social/publish/secret.ts +13 -0
  236. package/src/social/push.ts +31 -0
  237. package/src/social/richtext.ts +37 -0
  238. package/src/social/routes.ts +180 -0
  239. package/src/social/stats.ts +134 -0
  240. package/src/social/text.ts +267 -0
  241. package/src/social/tracker-route.ts +39 -0
  242. package/src/social/tracker.ts +255 -0
  243. package/src/social/unit.ts +53 -0
  244. package/src/social/writes.ts +130 -0
  245. package/src/start-repo.ts +14 -9
  246. package/src/stores/collection.ts +27 -0
  247. package/src/stores/desk.ts +336 -0
  248. package/src/stores/model.ts +187 -0
  249. package/src/stores/routes.ts +126 -0
  250. package/src/stores/unit.ts +57 -0
  251. package/src/suite/calibrate.ts +127 -0
  252. package/src/suite/core-counters.ts +91 -0
  253. package/src/suite/judge-suites.ts +94 -34
  254. package/src/suite/suite-cli.ts +44 -10
  255. package/src/suite/suite-cpu-preload.ts +34 -9
  256. package/src/trailer/adapter.ts +4 -0
  257. package/src/trailer/build.ts +42 -11
  258. package/src/trailer/ffmpeg.ts +11 -0
  259. package/src/trailer/footage.ts +30 -13
  260. package/src/trailer/grammar.ts +18 -2
  261. package/src/trailer/graph.ts +28 -6
  262. package/src/trailer/passage.ts +17 -5
  263. package/src/trailer/plan.ts +74 -3
  264. package/src/trailer/stitch.ts +67 -26
  265. package/src/trailer/url.ts +1 -1
  266. package/src/trailer/versions.ts +24 -0
  267. package/src/ts/gate-typecheck.ts +32 -0
  268. package/src/ts/typecheck-cli.ts +9 -11
  269. package/src/tui/tui-app.tsx +0 -1
  270. package/src/veille/asks.ts +155 -0
  271. package/src/veille/auto.ts +31 -0
  272. package/src/veille/batch.ts +27 -0
  273. package/src/veille/chrome.ts +127 -0
  274. package/src/veille/collection.ts +28 -0
  275. package/src/veille/desk.ts +242 -0
  276. package/src/veille/identity.ts +80 -0
  277. package/src/veille/import.ts +68 -0
  278. package/src/veille/log.ts +183 -0
  279. package/src/veille/platforms.ts +118 -0
  280. package/src/veille/reads.ts +66 -0
  281. package/src/veille/replied.ts +110 -0
  282. package/src/veille/routes.ts +185 -0
  283. package/src/veille/service.ts +81 -0
  284. package/src/veille/watch.ts +116 -0
  285. package/src/veille/worth.ts +46 -0
  286. package/src/wiki/scan-md.ts +18 -0
  287. package/src/collections/posts.ts +0 -142
  288. package/src/contracts/manifests/social.contract.ts +0 -20
  289. package/src/scaffold/files/agent-coding.md +0 -35
  290. package/src/ts/typecheck-cache.ts +0 -11
@@ -0,0 +1,140 @@
1
+ // the md views of drill runs (drill/run.ts): one page per run, one comparison across the runs of a drill.
2
+ // Generated from the json every time, never edited by hand. Markers are the house legend only.
3
+ import type { DrillRun } from './run.ts'
4
+
5
+ const secs = (ms: number | null): string => (ms == null ? '-' : `${Math.round(ms / 1000)}`)
6
+ const clock = (ms: number | null): string => {
7
+ if (ms == null) return '-'
8
+ const s = Math.round(ms / 1000)
9
+ return `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}`
10
+ }
11
+ const big = (n: number): string => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}k` : String(n))
12
+ const cell = (s: string): string => s.replace(/\|/g, '\\|').replace(/\n/g, ' ')
13
+ const fence = (s: string): string => '```\n' + s.replace(/```/g, "'''") + '\n```'
14
+
15
+ export function renderRun(r: DrillRun, label: string): string {
16
+ const out: string[] = [`<!-- generated by \`sk drill report\` from ${r.transcript}, never edited by hand -->`, '', `# drill run: ${label}`, '']
17
+ out.push('## prompt (exact)', '', fence(r.prompt), '', '## TLDR', '')
18
+ out.push(
19
+ r.verdict == null
20
+ ? '- 🔶 no verdict yet: `sk drill verdict` judges the run against its card'
21
+ : `- ${r.verdict.design === 'ok' && r.verdict.quality >= 4 ? '✅' : '🔶'} verdict: done ${r.verdict.done}, quality ${r.verdict.quality}/5, tests ${r.verdict.tests}, design ${r.verdict.design}${r.verdict.note === '' ? '' : `: ${r.verdict.note}`}`,
22
+ )
23
+ out.push(r.docs.length === 0 ? '- 🔶 no md page read: the setup under test never reached the run' : `- ${r.docs.length} md pages read, the first at ${clock(r.firstDoc)}; first write at ${clock(r.firstWrite)}, first check at ${clock(r.firstCheck)}`)
24
+ if (r.errors > 0) out.push(`- 🔶 ${r.errors} failed calls (listed below)`)
25
+ out.push(`- wall ${clock(r.wall)}, ${r.turns} turns, ${r.calls} tool calls, ${r.searches} searches, ${big(r.tokens.total)} tokens, context at end ${big(r.tokens.contextAtEnd)}`)
26
+ out.push('', '## numbers', '', '| metric | value |', '|---|---|')
27
+ const phase = (a: number | null, b: number | null): string => (a == null ? '-' : clock((b ?? r.wall) - a))
28
+ const rows: [string, string][] = [
29
+ ['wall / model / tools', `${clock(r.wall)} / ${clock(r.model)} / ${clock(r.tools)}`],
30
+ ['phases: explore (start → first write)', clock(r.firstWrite ?? r.wall)],
31
+ ['phases: build (first write → first check)', r.firstWrite == null || r.firstCheck == null ? '-' : phase(r.firstWrite, r.firstCheck)],
32
+ ['phases: verify (first check → end)', phase(r.firstCheck, null)],
33
+ ['turns / tool calls / failed', `${r.turns} / ${r.calls} / ${r.errors}`],
34
+ ['searches / reads / sent in parallel', `${r.searches} / ${r.reads} / ${r.parallel}`],
35
+ ['tokens: input / output', `${big(r.tokens.input)} / ${big(r.tokens.output)}`],
36
+ ['tokens: cache read / cache write', `${big(r.tokens.cacheRead)} / ${big(r.tokens.cacheWrite)}`],
37
+ ['context at end', big(r.tokens.contextAtEnd)],
38
+ ['models', r.models.join(', ') || '-'],
39
+ ]
40
+ if (r.patch != null) rows.push(['patch: files / + / − / new / tests / docs', `${r.patch.files} / ${r.patch.added} / ${r.patch.removed} / ${r.patch.newFiles} / ${r.patch.testFiles} / ${r.patch.docFiles}`])
41
+ for (const [k, v] of rows) out.push(`| ${k} | ${v} |`)
42
+ out.push('', '## md pages read', '', '`@` includes load before turn 1 and never show here.', '')
43
+ if (r.docs.length === 0) out.push('none')
44
+ else {
45
+ out.push('| at | page | reader | reads |', '|---|---|---|---|')
46
+ for (const d of r.docs) out.push(`| ${clock(d.first)} | ${cell(d.path)} | ${d.reader} | ${d.reads} |`)
47
+ }
48
+ out.push('', '## per tool', '', '| tool | calls | failed | time |', '|---|---|---|---|')
49
+ for (const t of r.perTool) out.push(`| ${t.tool} | ${t.calls} | ${t.errors} | ${clock(t.ms)} |`)
50
+ out.push('', '## per command shape', '', '| shape | calls | failed | time |', '|---|---|---|---|')
51
+ for (const t of r.perShape) out.push(`| ${cell(t.shape)} | ${t.calls} | ${t.errors} | ${clock(t.ms)} |`)
52
+ out.push('', '## files written (Edit, Write)', '')
53
+ out.push(r.written.length === 0 ? 'none' : r.written.map((w) => `- ${w}`).join('\n'))
54
+ if (r.patch != null) out.push('', '## files in the patch', '', r.patch.paths.length === 0 ? 'none' : r.patch.paths.map((p) => `- ${p}`).join('\n'))
55
+ out.push('', '## failed calls', '')
56
+ out.push(r.failures.length === 0 ? 'none' : r.failures.map((f) => `- 🔶 ${clock(f.at)} ${f.tool} (${f.outcome}): \`${f.detail.replace(/`/g, "'")}\``).join('\n'))
57
+ out.push('', '## final report', '', fence(r.finalReport), '')
58
+ return out.join('\n')
59
+ }
60
+
61
+ type Row = { label: string; get: (r: DrillRun) => number | null; fmt?: (n: number) => string }
62
+
63
+ const ROWS: Row[] = [
64
+ { label: 'wall (s)', get: (r) => r.wall, fmt: (n) => secs(n) },
65
+ { label: 'model (s)', get: (r) => r.model, fmt: (n) => secs(n) },
66
+ { label: 'turns', get: (r) => r.turns },
67
+ { label: 'tool calls', get: (r) => r.calls },
68
+ { label: 'failed calls', get: (r) => r.errors },
69
+ { label: 'searches', get: (r) => r.searches },
70
+ { label: 'reads', get: (r) => r.reads },
71
+ { label: 'md pages read', get: (r) => r.docs.length },
72
+ { label: 'first md page (s)', get: (r) => r.firstDoc, fmt: (n) => secs(n) },
73
+ { label: 'first write (s)', get: (r) => r.firstWrite, fmt: (n) => secs(n) },
74
+ { label: 'first check (s)', get: (r) => r.firstCheck, fmt: (n) => secs(n) },
75
+ { label: 'tokens total', get: (r) => r.tokens.total, fmt: big },
76
+ { label: 'context at end', get: (r) => r.tokens.contextAtEnd, fmt: big },
77
+ { label: 'patch: files', get: (r) => r.patch?.files ?? null },
78
+ { label: 'patch: lines + / −', get: (r) => (r.patch == null ? null : r.patch.added + r.patch.removed) },
79
+ { label: 'patch: test files', get: (r) => r.patch?.testFiles ?? null },
80
+ { label: 'verdict: quality (1-5)', get: (r) => r.verdict?.quality ?? null },
81
+ { label: 'verdict: design ok (1) or wrong (0)', get: (r) => (r.verdict == null ? null : r.verdict.design === 'ok' ? 1 : 0) },
82
+ { label: 'verdict: tests ran (2), written (1), none (0)', get: (r) => (r.verdict == null ? null : { ran: 2, written: 1, none: 0 }[r.verdict.tests]) },
83
+ ]
84
+
85
+ /** under 5% apart, two runs read as the same: one run's noise is larger than that */
86
+ const SAME = 1.05
87
+ /** better by more than the noise: a lower count, a shorter wall */
88
+ const better = (a: number, b: number): boolean => b * SAME < a
89
+
90
+ /** "62 → 50, 1.2x fewer": the ratio always reads up from 1, so a regression never reads "0.6x faster" */
91
+ export function delta(a: number | null, b: number | null, fmt: (n: number) => string = String): string {
92
+ if (a == null || b == null) return '-'
93
+ if (fmt(a) === fmt(b)) return `${fmt(a)} → ${fmt(b)}, same`
94
+ if (a === 0 || b === 0) return `${fmt(a)} → ${fmt(b)}`
95
+ const ratio = Math.max(a, b) / Math.min(a, b)
96
+ if (ratio < SAME) return `${fmt(a)} → ${fmt(b)}, about the same`
97
+ return `${fmt(a)} → ${fmt(b)}, ${ratio.toFixed(1)}x ${b < a ? 'fewer' : 'more'}`
98
+ }
99
+
100
+ const bars = (title: string, labels: string[], values: number[]): string =>
101
+ ['```mermaid', 'xychart-beta', ` title "${title}"`, ` x-axis [${labels.map((l) => `"${l}"`).join(', ')}]`, ` y-axis 0 --> ${Math.max(1, ...values)}`, ` bar [${values.join(', ')}]`, '```'].join('\n')
102
+
103
+ /** every run of a drill side by side, run order as given */
104
+ export function renderCompare(name: string, runs: { label: string; run: DrillRun }[]): string {
105
+ const out: string[] = [`<!-- generated by \`sk drill compare\` from ${runs.map((r) => `${r.label}.json`).join(', ')}, never edited by hand -->`, '', `# drill compare: ${name}`, '']
106
+ const first = runs[0]
107
+ const lastRun = runs[runs.length - 1]
108
+ if (first == null || lastRun == null) return [...out, 'no run.', ''].join('\n')
109
+ const a = first.run
110
+ const z = lastRun.run
111
+ const mismatch = runs.filter((r) => r.run.prompt !== a.prompt).map((r) => r.label)
112
+ out.push('## TLDR', '')
113
+ const prev = runs.length > 2 ? runs[runs.length - 2] : undefined
114
+ out.push(`- ${better(a.calls, z.calls) ? '✅' : '🔶'} tool calls ${first.label} → ${lastRun.label}: ${delta(a.calls, z.calls)}`)
115
+ if (prev != null) out.push(`- ${better(prev.run.calls, z.calls) ? '✅' : '🔶'} tool calls ${prev.label} → ${lastRun.label}, what the stop rule reads: ${delta(prev.run.calls, z.calls)}`)
116
+ out.push(`- ${better(a.wall, z.wall) ? '✅' : '🔶'} wall (s): ${delta(a.wall, z.wall, secs)}`)
117
+ out.push(`- ${better(a.tokens.total, z.tokens.total) ? '✅' : '🔶'} tokens: ${delta(a.tokens.total, z.tokens.total, big)}`)
118
+ const qa = a.verdict?.quality
119
+ const qz = z.verdict?.quality
120
+ out.push(qa == null || qz == null ? '- 🔶 a verdict is missing: a saving with no verdict is not a saving (`sk drill verdict`)' : `- ${qz >= qa ? '✅' : '🔶'} quality ${qa} → ${qz}, design ${a.verdict?.design} → ${z.verdict?.design}`)
121
+ out.push(mismatch.length === 0 ? '- ✅ every run got the same prompt' : `- 🔶 the prompt differs from ${first.label} in: ${mismatch.join(', ')}`)
122
+ const prevHead = prev == null ? '' : ` ${prev.label} → ${lastRun.label} |`
123
+ out.push('', '## metrics', '', `| metric | ${runs.map((r) => r.label).join(' | ')} | ${first.label} → ${lastRun.label} |${prevHead}`, `|---|${runs.map(() => '---|').join('')}---|${prev == null ? '' : '---|'}`)
124
+ for (const row of ROWS) {
125
+ const vals = runs.map((r) => row.get(r.run))
126
+ if (vals.every((v) => v == null)) continue
127
+ const fmt = row.fmt ?? String
128
+ const prevCell = prev == null ? '' : ` ${delta(vals[vals.length - 2] ?? null, vals[vals.length - 1] ?? null, fmt)} |`
129
+ out.push(`| ${row.label} | ${vals.map((v) => (v == null ? '-' : fmt(v))).join(' | ')} | ${delta(vals[0] ?? null, vals[vals.length - 1] ?? null, fmt)} |${prevCell}`)
130
+ }
131
+ const labels = runs.map((r) => r.label)
132
+ out.push('', '## charts', '', bars('tool calls', labels, runs.map((r) => r.run.calls)), '', bars('wall (s)', labels, runs.map((r) => Math.round(r.run.wall / 1000))), '', bars('tokens (k)', labels, runs.map((r) => Math.round(r.run.tokens.total / 1000))), '')
133
+ const docs = [...new Set(runs.flatMap((r) => r.run.docs.map((d) => d.path)))]
134
+ if (docs.length > 0) {
135
+ out.push('## when each md page was first read (mm:ss, - = never)', '', `| page | ${labels.join(' | ')} |`, `|---|${labels.map(() => '---|').join('')}`)
136
+ for (const p of docs) out.push(`| ${cell(p)} | ${runs.map((r) => clock(r.run.docs.find((d) => d.path === p)?.first ?? null)).join(' | ')} |`)
137
+ out.push('')
138
+ }
139
+ return out.join('\n')
140
+ }
@@ -0,0 +1,269 @@
1
+ // one drill run, read from its Claude Code transcript (wiki build/speed-up-agents.md): what it did, in
2
+ // which order, at what cost, through the same transcript reader and timeline as `sk time`. Pure: lines in,
3
+ // a record out, so a test feeds it a fixture. The record is json first; the md is a view of it, regenerated,
4
+ // never edited by hand, so a number copied into a card cannot drift from its source.
5
+ import { callMs, closeCalls, IDLE_MS, wallBreakdown, type Call, type Mark } from '../agent-time/timeline.ts'
6
+ import { isReadOnly, parallelFlags } from '../agent-time/turns.ts'
7
+ import { shellWords, statements, stripHeredocs, toolShape } from '../agent-time/shape.ts'
8
+ import { eventsOf, parseEntry, usageOf, userTextOf, type Outcome, type RawEntry } from '../reflect/transcript.ts'
9
+
10
+ export const RUN_VERSION = 1
11
+
12
+ export type Verdict = { done: string; quality: number; tests: 'ran' | 'written' | 'none'; design: 'ok' | 'wrong'; note: string }
13
+
14
+ export type DocRead = { path: string; first: number; reads: number; reader: string }
15
+
16
+ export type PatchStats = { files: number; added: number; removed: number; newFiles: number; testFiles: number; docFiles: number; paths: string[] }
17
+
18
+ export type DrillRun = {
19
+ version: number
20
+ transcript: string
21
+ prompt: string
22
+ start: string
23
+ /** all durations in ms; every "first" is an offset from the start, null when it never happened */
24
+ wall: number
25
+ model: number
26
+ tools: number
27
+ turns: number
28
+ calls: number
29
+ errors: number
30
+ searches: number
31
+ reads: number
32
+ parallel: number
33
+ firstDoc: number | null
34
+ firstWrite: number | null
35
+ /** the first check after the first write (any check when nothing was written): explore, build, verify cut there */
36
+ firstCheck: number | null
37
+ tokens: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number; contextAtEnd: number }
38
+ models: string[]
39
+ docs: DocRead[]
40
+ perTool: { tool: string; calls: number; errors: number; ms: number }[]
41
+ perShape: { shape: string; calls: number; errors: number; ms: number }[]
42
+ written: string[]
43
+ failures: { at: number; tool: string; detail: string; outcome: Outcome }[]
44
+ finalReport: string
45
+ patch: PatchStats | null
46
+ verdict: Verdict | null
47
+ }
48
+
49
+ const WRITE_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
50
+ const SEARCH_TOOLS = new Set(['Grep', 'Glob'])
51
+ const SEARCH_SHAPE = /^(grep|rg|git grep|find|ag)\b/
52
+ /** what counts as checking the work: a test run, the gate, a typecheck, a lint */
53
+ const CHECK_SHAPE = /^(sk ci|shipkit ci|bun test|bun run test|bun check|bun run check|bun lint|bun run lint|npx tsc|tsc|vitest|jest)\b/
54
+ /** programs that show a file's content; the first word after their flags is a pattern or a script, never a file */
55
+ const CONTENT_READERS = new Set(['cat', 'head', 'tail', 'less', 'more', 'bat', 'nl'])
56
+ const PATTERN_FIRST = new Set(['sed', 'awk', 'grep', 'rg'])
57
+ /** a word with these is a glob or a pattern, never one page */
58
+ const NOT_A_PATH = /[*?[\]{}\\$]/
59
+ const QUOTED = /'[^']*'|"(?:\\.|[^"\\])*"/g
60
+ const REDIRECT = /(?:^|[^<>&0-9])\d?>{1,2}\s*([^\s;&|<>]+)/g
61
+ const TEE = /(?:^|[|;&]\s*)tee\s+(?:-\S+\s+)*([^\s;&|<>]+)/g
62
+ const FINAL_MAX = 3000
63
+
64
+ /** the files a reading Bash statement shows the content of; [] for `wc`, `ls`, `git status` and the like */
65
+ function contentPaths(segment: string): string[] {
66
+ const words = shellWords(segment.trim())
67
+ let i = 0
68
+ while (words[i] != null && /^(nice|time|command|env)$/.test(words[i] as string)) i++
69
+ const prog = words[i] ?? ''
70
+ let args = words.slice(i + 1)
71
+ if (prog === 'git') {
72
+ while (args[0] === '-C' || args[0] === '-c') args = args.slice(2)
73
+ if (args[0] !== 'show' && args[0] !== 'diff') return []
74
+ args = args.slice(1).map((w) => w.slice(w.indexOf(':') + 1))
75
+ } else if (!CONTENT_READERS.has(prog) && !PATTERN_FIRST.has(prog)) return []
76
+ const files = args.filter((w) => !w.startsWith('-')).map((w) => w.replace(/^\$HOME(?=\/)/, '~'))
77
+ return (PATTERN_FIRST.has(prog) ? files.slice(1) : files).filter((w) => w.endsWith('.md') && !NOT_A_PATH.test(w))
78
+ }
79
+
80
+ /** the md files a call read, each once, with how: the Read tool by its path, a content reader by every page it names */
81
+ function docsOf(c: Call): { path: string; reader: string }[] {
82
+ if (c.tool === 'Read') return c.cmd.endsWith('.md') ? [{ path: c.cmd, reader: 'Read' }] : []
83
+ if (c.tool !== 'Bash' || !c.read) return []
84
+ const out = new Map<string, string>()
85
+ for (const s of statements(c.cmd)) for (const p of contentPaths(s)) if (!out.has(p)) out.set(p, `Bash ${shellWords(s.trim())[0] ?? ''}`)
86
+ return [...out].map(([path, reader]) => ({ path, reader }))
87
+ }
88
+
89
+ /** the files a Bash command writes: redirect targets (quoted text and /dev/null left out), `tee` args, an in place edit's last arg */
90
+ function bashTargets(cmd: string): string[] {
91
+ const out: string[] = []
92
+ // the whole command, heredoc bodies and quoted text out: statements() keeps only each pipeline's head
93
+ const bare = stripHeredocs(cmd).replace(QUOTED, "''")
94
+ for (const m of bare.matchAll(REDIRECT)) if (m[1] != null && m[1] !== '/dev/null' && !m[1].startsWith('&')) out.push(m[1])
95
+ for (const m of bare.matchAll(TEE)) if (m[1] != null) out.push(m[1])
96
+ for (const s of statements(cmd)) {
97
+ const words = shellWords(s.trim())
98
+ const prog = words[0] ?? ''
99
+ if ((prog === 'sed' && words.some((w) => w.startsWith('-i'))) || (prog === 'perl' && words.some((w) => /^-p?i/.test(w)))) {
100
+ const last = words[words.length - 1]
101
+ if (last != null) out.push(last)
102
+ }
103
+ }
104
+ return out
105
+ }
106
+
107
+ /** the stats of a unified diff, the kind `git diff --cached` writes */
108
+ export function patchStats(patch: string): PatchStats {
109
+ const paths: string[] = []
110
+ let added = 0
111
+ let removed = 0
112
+ let newFiles = 0
113
+ for (const line of patch.split('\n')) {
114
+ const head = /^diff --git a\/(\S+) b\/(\S+)/.exec(line)
115
+ if (head?.[2] != null) paths.push(head[2])
116
+ else if (line.startsWith('new file mode')) newFiles++
117
+ else if (line.startsWith('+') && !line.startsWith('+++')) added++
118
+ else if (line.startsWith('-') && !line.startsWith('---')) removed++
119
+ }
120
+ return { files: paths.length, added, removed, newFiles, testFiles: paths.filter((p) => /\.(test|spec)\.[jt]sx?$/.test(p)).length, docFiles: paths.filter((p) => p.endsWith('.md')).length, paths }
121
+ }
122
+
123
+ /** the run a transcript records. `root` is the run folder: its prefix is cut from every path, so two runs in two folders compare */
124
+ export function drillRun(lines: readonly string[], o: { transcript: string; root?: string; home?: string; patch?: string; mask?: (s: string) => string }): DrillRun {
125
+ const mask = o.mask ?? ((s: string) => s)
126
+ const home = o.home ?? process.env.HOME ?? ''
127
+ /** one spelling per file: `~/` and `$HOME/` expanded, then the run folder cut, so `Read` and `cat` of one page are one row */
128
+ const rel = (raw: string): string => {
129
+ const p = home !== '' ? raw.replace(/^(~|\$HOME)(?=\/)/, home) : raw
130
+ return o.root != null && p.startsWith(`${o.root}/`) ? p.slice(o.root.length + 1) : p
131
+ }
132
+ /** a write counts when it lands in the run: with a run folder, a relative target or one under it; a scratch file elsewhere is not the work */
133
+ const inRun = (target: string): boolean => {
134
+ if (o.root == null) return target !== ''
135
+ const t = rel(target)
136
+ return t !== '' && !t.startsWith('/') && !t.startsWith('~')
137
+ }
138
+ const writesOf = (c: Call): boolean => (WRITE_TOOLS.has(c.tool) ? inRun(c.cmd) : c.tool === 'Bash' && !c.read && bashTargets(c.cmd).some(inRun))
139
+ const pending = new Map<string, Call>()
140
+ const marks: Mark[] = []
141
+ const usage = new Map<string, NonNullable<ReturnType<typeof usageOf>>>()
142
+ let prompt: string | null = null
143
+ let finalReport = ''
144
+ let first = Infinity
145
+ let last = -Infinity
146
+ for (const line of lines) {
147
+ const entry: RawEntry | null = parseEntry(line)
148
+ if (entry == null) continue
149
+ const at = typeof entry.timestamp === 'string' ? Date.parse(entry.timestamp) : NaN
150
+ if (!Number.isNaN(at)) {
151
+ first = Math.min(first, at)
152
+ last = Math.max(last, at)
153
+ }
154
+ if (prompt == null && entry.type === 'user') {
155
+ const t = userTextOf(entry)
156
+ if (t != null && t !== '') prompt = t
157
+ }
158
+ const u = usageOf(entry)
159
+ if (u != null) usage.set(u.messageId, u)
160
+ if (entry.type === 'assistant' && Array.isArray(entry.message?.content)) {
161
+ for (const b of entry.message.content as { type?: unknown; text?: unknown; name?: unknown; input?: { message?: unknown } }[]) {
162
+ if (b?.type === 'text' && typeof b.text === 'string' && b.text.trim() !== '') finalReport = b.text
163
+ // a sub-agent hands its report back through a tool call, not a text block
164
+ else if (b?.type === 'tool_use' && b.name === 'SubagentHandback' && typeof b.input?.message === 'string') finalReport = b.input.message
165
+ }
166
+ }
167
+ for (const e of eventsOf(entry)) {
168
+ if (e.kind === 'use') {
169
+ const shape = toolShape(e.name, e.detail)
170
+ pending.set(e.id, { id: e.id, start: e.at, end: null, tool: e.name, shape, cmd: e.detail, outcome: null, code: null, approval: false, perm: '', read: isReadOnly({ tool: e.name, shape, cmd: e.detail }) })
171
+ } else if (e.kind === 'result') {
172
+ const c = pending.get(e.id)
173
+ if (c != null) Object.assign(c, { end: e.at, outcome: e.outcome, code: e.code, approval: e.perm === 'user', perm: e.perm })
174
+ } else if (e.kind !== 'prompt') marks.push({ at: e.at, kind: e.kind })
175
+ }
176
+ }
177
+ const start = Number.isFinite(first) ? first : 0
178
+ const calls = closeCalls({ calls: [...pending.values()], marks })
179
+ const wall = Number.isFinite(last) ? Math.max(0, last - start) : 0
180
+ const b = wallBreakdown({ calls: [...pending.values()], marks }, -Infinity, Infinity, IDLE_MS, calls)
181
+ const off = (at: number | undefined): number | null => (at == null ? null : Math.max(0, at - start))
182
+
183
+ const docs = new Map<string, DocRead>()
184
+ for (const c of calls)
185
+ for (const d of docsOf(c)) {
186
+ const path = rel(d.path)
187
+ const seen = docs.get(path)
188
+ if (seen == null) docs.set(path, { path, first: off(c.start) ?? 0, reads: 1, reader: d.reader })
189
+ else seen.reads++
190
+ }
191
+ const tally = (key: (c: (typeof calls)[number]) => string): { key: string; calls: number; errors: number; ms: number }[] => {
192
+ const m = new Map<string, { key: string; calls: number; errors: number; ms: number }>()
193
+ for (const c of calls) {
194
+ const k = key(c)
195
+ const row = m.get(k) ?? { key: k, calls: 0, errors: 0, ms: 0 }
196
+ row.calls++
197
+ if (c.outcome != null && c.outcome !== 'ok') row.errors++
198
+ row.ms += callMs(c)
199
+ m.set(k, row)
200
+ }
201
+ return [...m.values()].sort((x, y) => y.calls - x.calls || y.ms - x.ms)
202
+ }
203
+ const u = [...usage.values()]
204
+ const sum = (f: (x: (typeof u)[number]) => number): number => u.reduce((n, x) => n + f(x), 0)
205
+ const lastUsage = u[u.length - 1]
206
+ const isSearch = (c: Call): boolean => SEARCH_TOOLS.has(c.tool) || (c.tool === 'Bash' && SEARCH_SHAPE.test(c.shape))
207
+ const docList = [...docs.values()].sort((x, y) => x.first - y.first)
208
+ const firstWrite = calls.find(writesOf)
209
+ return {
210
+ version: RUN_VERSION,
211
+ transcript: o.transcript,
212
+ prompt: mask(prompt ?? ''),
213
+ start: new Date(start).toISOString(),
214
+ wall,
215
+ model: b.model,
216
+ tools: b.tools + b.approval + b.subagent,
217
+ turns: usage.size,
218
+ calls: calls.length,
219
+ errors: calls.filter((c) => c.outcome != null && c.outcome !== 'ok').length,
220
+ searches: calls.filter(isSearch).length,
221
+ reads: calls.filter((c) => c.read).length,
222
+ parallel: parallelFlags(calls).filter(Boolean).length,
223
+ firstDoc: docList[0]?.first ?? null,
224
+ firstWrite: off(firstWrite?.start),
225
+ firstCheck: off(calls.find((c) => c.tool === 'Bash' && CHECK_SHAPE.test(c.shape) && (firstWrite == null || c.start >= firstWrite.start))?.start),
226
+ tokens: {
227
+ input: sum((x) => x.input),
228
+ output: sum((x) => x.output),
229
+ cacheRead: sum((x) => x.cacheRead),
230
+ cacheWrite: sum((x) => x.cacheWrite),
231
+ total: sum((x) => x.input + x.output + x.cacheRead + x.cacheWrite),
232
+ contextAtEnd: lastUsage == null ? 0 : lastUsage.input + lastUsage.cacheRead + lastUsage.cacheWrite,
233
+ },
234
+ models: [...new Set(u.map((x) => x.model).filter((m) => m !== ''))],
235
+ docs: docList,
236
+ perTool: tally((c) => c.tool).map(({ key, ...r }) => ({ tool: key, ...r })),
237
+ perShape: tally((c) => c.shape).map(({ key, ...r }) => ({ shape: mask(key), ...r })),
238
+ written: [...new Set(calls.filter((c) => WRITE_TOOLS.has(c.tool) && inRun(c.cmd)).map((c) => rel(c.cmd)))],
239
+ failures: calls.filter((c) => c.outcome != null && c.outcome !== 'ok').map((c) => ({ at: off(c.start) ?? 0, tool: c.tool, detail: mask(rel(c.cmd)).slice(0, 160), outcome: c.outcome as Outcome })),
240
+ finalReport: mask(finalReport).slice(0, FINAL_MAX),
241
+ patch: o.patch == null ? null : patchStats(o.patch),
242
+ verdict: null,
243
+ }
244
+ }
245
+
246
+ /** `done=3/3,quality=4,tests=ran,design=ok[,note=…]`, every field checked; the error names the bad one */
247
+ export function parseVerdict(text: string): Verdict | string {
248
+ const kv = new Map(
249
+ text
250
+ .split(',')
251
+ .map((p) => p.trim())
252
+ .filter((p) => p !== '')
253
+ .map((p) => {
254
+ const i = p.indexOf('=')
255
+ return [i < 0 ? p : p.slice(0, i).trim(), i < 0 ? '' : p.slice(i + 1).trim()] as const
256
+ }),
257
+ )
258
+ const done = kv.get('done') ?? ''
259
+ if (!/^\d+\/\d+$/.test(done)) return `done=${done}: the items done over the items expected, like 3/3`
260
+ const quality = Number(kv.get('quality'))
261
+ if (!Number.isInteger(quality) || quality < 1 || quality > 5) return `quality=${kv.get('quality') ?? ''}: a whole number from 1 to 5`
262
+ const tests = kv.get('tests')
263
+ if (tests !== 'ran' && tests !== 'written' && tests !== 'none') return `tests=${tests ?? ''}: ran, written or none`
264
+ const design = kv.get('design')
265
+ if (design !== 'ok' && design !== 'wrong') return `design=${design ?? ''}: ok or wrong`
266
+ const unknown = [...kv.keys()].filter((k) => !['done', 'quality', 'tests', 'design', 'note'].includes(k))
267
+ if (unknown.length > 0) return `${unknown.join(', ')}: the fields are done, quality, tests, design, note`
268
+ return { done, quality, tests, design, note: kv.get('note') ?? '' }
269
+ }
@@ -16,6 +16,7 @@ import { isArchived } from '../core/archived.ts'
16
16
  import { isLinkedWorktree } from '../core/git-root.ts'
17
17
  import { detectPackageManager, isRefusal } from '../core/package-manager.ts'
18
18
  import { isBreaking, isLinkedInstall, pinFloor } from '../core/update-policy.ts'
19
+ import { publishedHere } from '../release/published-here.ts'
19
20
 
20
21
  export type Pkg = { name?: string; version?: string; dependencies?: Record<string, string>; devDependencies?: Record<string, string> }
21
22
 
@@ -130,11 +131,11 @@ export async function resolveLatest(repos: FleetRepo[], fetchLatest: (name: stri
130
131
  const latest = new Map<string, string | null>()
131
132
  await Promise.all(
132
133
  [...names].map(async (n) => {
133
- try {
134
- latest.set(n, await fetchLatest(n))
135
- } catch {
136
- latest.set(n, null)
137
- }
134
+ let registry: string | null = null
135
+ try { registry = await fetchLatest(n) } catch { /* the registry did not answer */ }
136
+ // a version this machine just published beats the registry's cached latest
137
+ const here = publishedHere(n)
138
+ latest.set(n, here != null && (registry == null || isBehind(registry, here)) ? here : registry)
138
139
  }),
139
140
  )
140
141
  for (const r of repos) {
@@ -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
+ }