rvlib-shipkit 2.22.1 → 2.24.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 (139) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/package.json +1 -1
  3. package/src/agent-time/render.ts +28 -14
  4. package/src/agent-time/report.ts +46 -25
  5. package/src/agent-time/store.ts +30 -10
  6. package/src/agent-time/timeline.ts +43 -15
  7. package/src/annex/annex.ts +3 -0
  8. package/src/annex/born.ts +464 -0
  9. package/src/annex/flush.ts +46 -0
  10. package/src/annex/offload.ts +171 -38
  11. package/src/annex/snapshots.ts +53 -0
  12. package/src/annex/tidy.ts +368 -0
  13. package/src/asks/asks-queue.ts +32 -11
  14. package/src/checks/SK041-annex-links.check.ts +4 -2
  15. package/src/checks/SK043-scratch-on-the-mac.check.ts +45 -0
  16. package/src/checks/SK044-behind-upstream.check.ts +38 -0
  17. package/src/cli/cmd_Annex.ts +60 -9
  18. package/src/cli/cmd_Asks.ts +2 -0
  19. package/src/cli/cmd_Backup.ts +7 -5
  20. package/src/cli/cmd_Bump.ts +1 -0
  21. package/src/cli/cmd_Capacity.ts +26 -0
  22. package/src/cli/cmd_Check.ts +1 -0
  23. package/src/cli/cmd_Checks.ts +1 -0
  24. package/src/cli/cmd_Ci.ts +1 -0
  25. package/src/cli/cmd_Commands.ts +50 -14
  26. package/src/cli/cmd_Home.ts +0 -1
  27. package/src/cli/cmd_Hooks.ts +1 -0
  28. package/src/cli/cmd_Mv.ts +1 -0
  29. package/src/cli/cmd_Rec.ts +17 -7
  30. package/src/cli/cmd_Reflect.ts +1 -0
  31. package/src/cli/cmd_Releases.ts +1 -0
  32. package/src/cli/cmd_Review.ts +124 -17
  33. package/src/cli/cmd_Secret.ts +41 -2
  34. package/src/cli/cmd_Shot.ts +1 -0
  35. package/src/cli/cmd_Status.ts +1 -0
  36. package/src/cli/cmd_Time.ts +3 -1
  37. package/src/cli/cmd_Tmp.ts +82 -0
  38. package/src/cli/cmd_Wiki.ts +1 -0
  39. package/src/cli/registry.ts +13 -1
  40. package/src/collections/pings.ts +1 -1
  41. package/src/core/capacity.ts +71 -0
  42. package/src/core/check-runner.ts +86 -15
  43. package/src/core/machine-db.ts +8 -0
  44. package/src/core/motherhome.ts +67 -9
  45. package/src/core/slots.ts +49 -12
  46. package/src/core/trace-audit.ts +4 -1
  47. package/src/drill/run.ts +5 -2
  48. package/src/home/daemon-jobs.ts +10 -3
  49. package/src/home/global-units.ts +3 -0
  50. package/src/home/gui-app/ShipkitGui.swift +1 -0
  51. package/src/home/home-launchd.ts +11 -3
  52. package/src/home/home-routes.ts +11 -4
  53. package/src/home/machine-host.ts +65 -0
  54. package/src/home/machine-stores.ts +30 -4
  55. package/src/home/machine-temp.ts +493 -0
  56. package/src/home/other-macs.ts +74 -0
  57. package/src/home/pm.ts +4 -1
  58. package/src/home/run-daemon.ts +10 -2
  59. package/src/home/run-pm.ts +1 -0
  60. package/src/home/serve-web.ts +2 -2
  61. package/src/home/via-hub.ts +6 -1
  62. package/src/identities/identities.ts +92 -24
  63. package/src/init-repo.ts +7 -3
  64. package/src/ledger/ledger.ts +6 -0
  65. package/src/ledger/store.ts +6 -0
  66. package/src/media-store/backup/keys.ts +21 -6
  67. package/src/media-store/backup/manifest.ts +52 -11
  68. package/src/media-store/backup/restore.ts +17 -10
  69. package/src/media-store/backup/run.ts +5 -2
  70. package/src/media-store/backup/sources.ts +2 -1
  71. package/src/media-store/daemon.ts +2 -2
  72. package/src/media-store/purge.ts +4 -0
  73. package/src/mv/mv-md.ts +121 -42
  74. package/src/recordings/load.ts +3 -3
  75. package/src/recordings/model.ts +7 -0
  76. package/src/recordings/open.ts +12 -0
  77. package/src/recordings/presets.ts +12 -5
  78. package/src/recordings/recorder-app/Capture.swift +34 -5
  79. package/src/recordings/recorder-app/Clip.swift +126 -17
  80. package/src/recordings/recorder-app/Editor.swift +177 -7
  81. package/src/recordings/recorder-app/Hud.swift +189 -0
  82. package/src/recordings/recorder-app/Tray.swift +179 -36
  83. package/src/recordings/recorder-app/icon.svg +16 -0
  84. package/src/recordings/recorder-app/main.swift +349 -18
  85. package/src/recordings/recorder-app.ts +8 -4
  86. package/src/recordings/recorder.shipkit.ts +2 -1
  87. package/src/recordings/routes.ts +52 -6
  88. package/src/recordings/run-recorder.ts +2 -1
  89. package/src/recordings/share.ts +27 -0
  90. package/src/recordings/take.ts +36 -4
  91. package/src/recordings/view.ts +11 -0
  92. package/src/reflect/transcript.ts +56 -11
  93. package/src/releases/from-card.ts +45 -3
  94. package/src/releases/model.ts +6 -0
  95. package/src/releases/store.ts +8 -1
  96. package/src/repo-config.ts +14 -4
  97. package/src/review/cells.ts +24 -3
  98. package/src/review/format.ts +33 -9
  99. package/src/review/media-kind.ts +14 -11
  100. package/src/review/media-read.ts +6 -5
  101. package/src/review/model.ts +104 -7
  102. package/src/review/paste.ts +2 -1
  103. package/src/review/previews.ts +123 -36
  104. package/src/review/routes.ts +29 -18
  105. package/src/review/store.ts +74 -12
  106. package/src/review/threads.ts +7 -5
  107. package/src/secrets/copy.ts +110 -0
  108. package/src/secrets/list.ts +17 -7
  109. package/src/serve/hub-app/home-strip.css +5 -0
  110. package/src/serve/hub-app/home-strip.tsx +18 -0
  111. package/src/serve/hub-app/hub-app.tsx +2 -1
  112. package/src/serve/hub-app/hub.css +18 -0
  113. package/src/serve/hub-app/inbox.css +1 -0
  114. package/src/serve/hub-app/pull-refresh.tsx +88 -0
  115. package/src/serve/hub-app/recordings-st.ts +135 -24
  116. package/src/serve/hub-app/recordings-view.tsx +293 -54
  117. package/src/serve/hub-app/recordings.css +77 -24
  118. package/src/serve/hub-app/review/review-cells.tsx +52 -13
  119. package/src/serve/hub-app/review/review-list.tsx +6 -1
  120. package/src/serve/hub-app/review/review-st.ts +6 -5
  121. package/src/serve/hub-app/review/review-thread.tsx +3 -1
  122. package/src/serve/hub-app/review/review-views.tsx +18 -11
  123. package/src/serve/hub-app/review/thread-st.ts +82 -14
  124. package/src/serve/hub-app/review.css +15 -2
  125. package/src/serve/hub-runtime.ts +2 -1
  126. package/src/serve/run-serve.ts +4 -2
  127. package/src/serve/serve-hub.ts +9 -2
  128. package/src/shipkit-files.ts +5 -0
  129. package/src/social/drafts.ts +4 -3
  130. package/src/social/load.ts +7 -2
  131. package/src/social/publish/discord.ts +10 -3
  132. package/src/suite/child-tools.ts +45 -0
  133. package/src/suite/judge-suites.ts +10 -22
  134. package/src/suite/select.ts +83 -8
  135. package/src/suite/suite-cli.ts +38 -14
  136. package/src/suite/suite-cores.ts +68 -0
  137. package/src/suite/suite-reads-preload.ts +8 -6
  138. package/src/ts/config.ts +44 -0
  139. package/src/ts/rename.ts +11 -1
@@ -62,6 +62,7 @@ import type { projectGutter } from './project-gutter-route.ts'
62
62
  import { defaultHubPort } from './hub-port.ts'
63
63
  import { LAYOUT } from '../core/layout.ts'
64
64
  import { storeDir, storeStamp } from '../review/store.ts'
65
+ import { machinePublicHost } from '../home/machine-host.ts'
65
66
  export { defaultHubPort }
66
67
 
67
68
  export type ServeIo = { print: (l: string) => void; printErr: (l: string) => void }
@@ -414,7 +415,7 @@ export async function resolveHubDeps(root: string, boot: RepoConfig, io: ServeIo
414
415
  // a silent one reads as no blockers at all
415
416
  pingTick: (needs) =>
416
417
  pingTick(root, c.asks?.dir ?? LAYOUT.asks, needs, {
417
- link: o?.link ?? (() => (c.serve?.publicHost != null ? `http://${c.serve.publicHost}:${port}${o?.base ?? ''}/?f=needs` : undefined)),
418
+ link: o?.link ?? (() => { const h = machinePublicHost(c); return h != null ? `http://${h}:${port}${o?.base ?? ''}/?f=needs` : undefined }),
418
419
  run: (cmd) => {
419
420
  const p = Bun.spawn(cmd, { stdout: 'ignore', stderr: 'pipe' })
420
421
  void p.exited.then(async (code) => {
@@ -19,6 +19,7 @@ import { homeRepo } from './project-gutter.ts'
19
19
  import { serveHub } from './serve-hub.ts'
20
20
  import { StaleRestart } from './stale-restart.ts'
21
21
  import { Planner } from '../plan/planner.ts'
22
+ import { machinePublicHost } from '../home/machine-host.ts'
22
23
 
23
24
  export type { ServeIo }
24
25
 
@@ -107,8 +108,9 @@ export async function runServe(root: string, io: ServeIo, o?: { port?: number })
107
108
  // a page that cannot refresh itself looks identical to a broken one,
108
109
  // and the only tell is that every change needs a reload key
109
110
  if (!hub.liveReload) io.print(`WARN the page will not refresh itself: NODE_ENV=production strips bun hot reload, unset it and restart the hub`)
110
- // the off-machine door (phone, other machines) — publicHost is config
111
- if (c.serve?.publicHost != null) io.print(` phone: http://${c.serve.publicHost}:${hub.server.port}/`)
111
+ // the off-machine door (phone, other machines): this Mac's own name
112
+ const publicHost = machinePublicHost(c)
113
+ if (publicHost != null) io.print(` phone: http://${publicHost}:${hub.server.port}/`)
112
114
  // said once at boot, so a silent phone is never mistaken for no blockers
113
115
  if (c.notifyCommand != null && isLinkedWorktree(root)) io.print(` pings: off, this is a linked worktree (only the main checkout's hub notifies)`)
114
116
  // a lib that moved under this process (under bun --watch the version
@@ -4,7 +4,7 @@
4
4
  // is the routing alone, under a base path; serveHub puts it behind a
5
5
  // Bun.serve of its own. Resolving WHAT to mount from repo.config is
6
6
  // hub-runtime.ts's job.
7
- import { existsSync } from 'fs'
7
+ import { existsSync, realpathSync } from 'fs'
8
8
  import { join } from 'path'
9
9
  import { positionsFile } from 'rvlib-shipkit/src/wiki/graph-positions.ts'
10
10
  import { pageOf, searchWiki } from 'rvlib-shipkit/src/wiki/graph-pages.ts'
@@ -61,6 +61,9 @@ export type ComfyDeps = {
61
61
  box: () => ComfyBox
62
62
  stop: () => void
63
63
  }
64
+ /** a path as the disk resolves it, so `/tmp` and `/private/tmp` are one tree */
65
+ const sameTree = (p: string): string => { try { return realpathSync(p) } catch { return p } }
66
+
64
67
  export type HubDeps = {
65
68
  root: string
66
69
  name: string
@@ -234,8 +237,12 @@ export function hubHandler(d: HubDeps, o: { base?: string; projects?: Gutter } =
234
237
  // click opens the home on that repo, or VS Code while none runs
235
238
  if (path === '/api/home-url') return Response.json({ port: homePort(), up: await homeUp() })
236
239
  if (path === '/api/run' && req.method === 'POST' && d.runCli != null) {
237
- const b = (await req.json().catch(() => ({}))) as { kind?: string; opts?: Record<string, unknown> }
240
+ const b = (await req.json().catch(() => ({}))) as { kind?: string; opts?: Record<string, unknown>; root?: string }
238
241
  if (b.kind !== 'ci' && b.kind !== 'check') return new Response('kind must be ci or check', { status: 400 })
242
+ // a hub is found by its folder's NAME, and a clone elsewhere
243
+ // shares it: the gate runs only for the tree this hub serves
244
+ if (b.root == null || sameTree(b.root) !== sameTree(d.root))
245
+ return new Response(`the home's ${d.name} hub serves ${d.root}, not ${b.root ?? 'an unnamed tree'}`, { status: 421 })
239
246
  const runCli = d.runCli
240
247
  // a gate can stay silent for minutes (queued, or one long tsc):
241
248
  // Bun would cut the connection after its idle timeout
@@ -75,6 +75,10 @@ export type GlobalProcessDef = {
75
75
  /** what its card wears: an emoji, or a repo-relative image path
76
76
  * (png, svg, ico, jpg, webp). Absent: the declaring repo's own icon */
77
77
  icon?: string
78
+ /** pm starts it when pm itself starts cold (no daemon left to adopt: a login, a reboot, a kill), for a
79
+ * process that is only useful while always up (a hotkey owner). A pm
80
+ * restart in place keeps the owner's switch */
81
+ atLogin?: boolean
78
82
  }
79
83
 
80
84
  export type WidgetDef = {
@@ -117,6 +121,7 @@ export function globalProcessProblem(d: GlobalProcessDef): string | null {
117
121
  if (d.app !== undefined && (typeof d.app !== 'string' || d.app.trim() === '' || /^\.|[/:]/.test(d.app))) return `${at}: app is a file name: not empty, no leading dot, no / or :`
118
122
  if (d.probe != null && !httpUrl(d.probe)) return `${at}: probe must be an http url`
119
123
  if (d.down != null && d.probe == null && d.url == null) return `${at}: a bring-up (one with down) needs probe or url, the only truth of whether it is up`
124
+ if (d.atLogin !== undefined && typeof d.atLogin !== 'boolean') return `${at}: atLogin is true or false`
120
125
  if (d.icon !== undefined) {
121
126
  const why = iconProblem(d.icon)
122
127
  if (why != null) return `${at}: ${why}`
@@ -8,10 +8,11 @@ import { parseFrontmatter } from './md.ts'
8
8
 
9
9
  /** the headings a draft holds besides its platforms */
10
10
  const OWN = ['Angle', 'Posted'] as const
11
- const OPTIONS = ['name', 'place', 'title', 'media', 'rating', 'pin', 'outro', 'mark', 'tags', 'tier'] as const
11
+ const OPTIONS = ['name', 'place', 'title', 'media', 'rating', 'pin', 'embeds', 'outro', 'mark', 'tags', 'tier'] as const
12
12
  type Option = (typeof OPTIONS)[number]
13
- /** the options whose value is one of a few words: a vertical's end and its watermark's corner, words a project reads */
14
- const WORDS: Partial<Record<Option, readonly string[]>> = { outro: ['montage', 'short', 'none'], mark: ['left', 'right'] }
13
+ /** the options whose value is one of a few words: a vertical's end and its watermark's corner, words a project reads;
14
+ * `embeds: none`, no preview card under its links */
15
+ const WORDS: Partial<Record<Option, readonly string[]>> = { outro: ['montage', 'short', 'none'], mark: ['left', 'right'], embeds: ['none'] }
15
16
 
16
17
  const HEADING = /^## (.+?)[ \t]*$/gm
17
18
  const PLATFORM = /^([a-z0-9-]+)(?:\s*\((.*)\))?$/
@@ -4,7 +4,7 @@
4
4
  import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
5
5
  import { join, relative, resolve, sep } from 'node:path'
6
6
  import { LAYOUT } from '../core/layout.ts'
7
- import { speakerOf, type Account, type Identities, type Identity } from '../identities/identities.ts'
7
+ import { filledText, speakerOf, type Account, type Identities, type Identity } from '../identities/identities.ts'
8
8
  import { isPostRating, POST_RATINGS, takes, type PostRating } from '../identities/rating.ts'
9
9
  import { fileList, groupKeys, mediaNames, parseDraft, renderedTrailer, resolveMedia, tagList, topicList, type Topic } from './drafts.ts'
10
10
  import { compose, fillLink, messageLength } from './compose.ts'
@@ -90,6 +90,8 @@ export type SocialPost = {
90
90
  /** the account's write page, prefilled when it takes {text}; null when it names none */
91
91
  href: string | null
92
92
  pin: boolean
93
+ /** the venue draws a preview card under each link (`embeds: none` turns them off: a list of links) */
94
+ embeds: boolean
93
95
  /** the key of the heading its text comes from: its own, or its group's (`short`, `short/<name>`) */
94
96
  from: string
95
97
  /** the links under a vertical message's text, counted and copied with it; empty elsewhere */
@@ -357,7 +359,9 @@ export function loadDesk(root: string, ids: Identities, o: { speaksAs?: string |
357
359
  }
358
360
  const footer = from.split('/')[0] === VERTICAL ? footerText : ''
359
361
  const tags = tagList(s.options.tags)
360
- const made = compose(a.id, { text: s.text, tags, footer }, { max: a.max, saturday })
362
+ // `[[row]]` is that account's row (its `[[links]]`), so a list the identity keeps never goes stale in a draft
363
+ const filled = filledText(s.text, a.rows, `${file}: ## ${key}`, errors)
364
+ const made = compose(a.id, { text: filled, tags, footer }, { max: a.max, saturday })
361
365
  const at = a.places.find((x) => x.id === place)
362
366
  // a Discord place is a channel of its server's layout; with no layout, checked when the bot posts
363
367
  if (place !== '' && !places.some((x) => x.id === place) && (a.id !== 'discord' || hasLayout(a)))
@@ -389,6 +393,7 @@ export function loadDesk(root: string, ids: Identities, o: { speaksAs?: string |
389
393
  href: write === '' ? null : fillLink(write, { url: '', title, text: made.text }),
390
394
  prefilled: write.includes('{text}'),
391
395
  pin: s.options.pin === 'true',
396
+ embeds: s.options.embeds !== 'none',
392
397
  from,
393
398
  footer,
394
399
  rating,
@@ -57,21 +57,28 @@ export function discordContent(text: string, channels: readonly Channel[]): stri
57
57
  return withoutTags(linked)
58
58
  }
59
59
 
60
+ /** Discord's message flag that drops the preview cards under its links */
61
+ const SUPPRESS_EMBEDS = 1 << 2
62
+
63
+ /** a message as Discord takes it, posted or edited: no mention pings, its links' cards only when `embeds`; an edit
64
+ * sets the flag too, so a draft that changes it changes the posted message */
65
+ export const discordPayload = (content: string, embeds: boolean): Record<string, unknown> => ({ content, allowed_mentions: { parse: [] }, flags: embeds ? 0 : SUPPRESS_EMBEDS })
66
+
60
67
  /** posts a message on the identity's Discord server; its link, which the caller records */
61
68
  export async function postDiscord(a: Account, post: SocialPost): Promise<string> {
62
69
  if (a.guild === '') throw new Error(`${a.file}: no guild, the server's id`)
63
70
  if (post.text === '') throw new Error(`${post.slug}: its ## ${post.from} is empty`)
64
71
  const channels = await call<Channel[]>(a, 'GET', `/guilds/${a.guild}/channels`)
65
- const content = discordContent(post.text, channels)
72
+ const payload = discordPayload(discordContent(post.text, channels), post.embeds)
66
73
  if (post.posted) {
67
74
  const ids = new RegExp(`^https://discord\\.com/channels/${a.guild}/(\\d+)/(\\d+)$`).exec(post.posted)
68
75
  if (ids == null) throw new Error(`${post.slug}: posted "${post.posted}" is no message link of the server`)
69
- await call(a, 'PATCH', `/channels/${ids[1]}/messages/${ids[2]}`, JSON.stringify({ content, allowed_mentions: { parse: [] } }))
76
+ await call(a, 'PATCH', `/channels/${ids[1]}/messages/${ids[2]}`, JSON.stringify(payload))
70
77
  return post.posted
71
78
  }
72
79
  const target = channels.find((x) => x.type === TEXT && same(channelKey(x.name), post.place))
73
80
  if (target == null) throw new Error(`${post.slug}: place "${post.place}" is no text channel of the server`)
74
- const msg = await postMessage(a, target.id, { content, allowed_mentions: { parse: [] } }, post.media?.path ?? null, post.alt)
81
+ const msg = await postMessage(a, target.id, payload, post.media?.path ?? null, post.alt)
75
82
  if (post.pin) await call(a, 'PUT', `/channels/${target.id}/pins/${msg.id}`)
76
83
  return `https://discord.com/channels/${a.guild}/${target.id}/${msg.id}`
77
84
  }
@@ -0,0 +1,45 @@
1
+ // what the read recorder may trust of a child process that is not bun: a tool that opens no file whatever its folder,
2
+ // and the folder a git child works in. Imported by the recorder preload, so it imports nothing of the repo
3
+ import { isAbsolute, join } from 'node:path'
4
+
5
+ // they read the kernel's tables, never a file: the process list, the sockets, the tool paths
6
+ const NO_FILE = new Set(['ps', 'pgrep', 'uname', 'sw_vers', 'whoami', 'id', 'hostname', 'vm_stat', 'sysctl'])
7
+
8
+ /** the child opens no file of any repo, whatever its folder and environment */
9
+ export function readsNoFile(argv: readonly string[]): boolean {
10
+ const tool = argv[0]?.split('/').pop()
11
+ if (tool == null || tool === '') return false
12
+ if (NO_FILE.has(tool)) return true
13
+ // a socket query only: every word an option, so no path is listed
14
+ if (tool === 'lsof') return argv.slice(1).every((a) => a.startsWith('-'))
15
+ // an archive unpacked from stdin: it writes where -C points and opens no file
16
+ if (tool === 'tar') return argv.includes('-x') && argv[argv.indexOf('-f') + 1] === '-'
17
+ // a lookup of a tool's path, never a run of it
18
+ if (tool === 'xcrun') return argv.length === 3 && (argv[1] === '--find' || argv[1] === '-f')
19
+ return false
20
+ }
21
+
22
+ /** the folder the child works in: git's leading `-C <dir>` options, tar's leading `-C <dir>` when every other path it
23
+ * names is absolute or `.` (a relative archive name would still resolve in the spawn's folder), else the spawn's own */
24
+ export function childCwd(argv: readonly string[], cwd: string): string {
25
+ const tool = argv[0]?.split('/').pop()
26
+ if (tool === 'tar') {
27
+ const dir = argv[1] === '-C' ? argv[2] : undefined
28
+ if (dir == null || !isAbsolute(dir)) return cwd
29
+ const rest = argv.slice(3).filter((a) => !a.startsWith('-'))
30
+ return rest.every((a) => a === '.' || isAbsolute(a)) && !argv.slice(3).includes('-C') ? dir : cwd
31
+ }
32
+ if (tool !== 'git') return cwd
33
+ let at = cwd
34
+ for (let i = 1; i < argv.length; i++) {
35
+ const a = argv[i]!
36
+ if (!a.startsWith('-')) break
37
+ if (a === '-c') i++
38
+ else if (a === '-C') {
39
+ const d = argv[++i]
40
+ if (d == null) return cwd
41
+ at = isAbsolute(d) ? d : join(at, d)
42
+ }
43
+ }
44
+ return at
45
+ }
@@ -169,22 +169,6 @@ export function planPhases(p: { tests: TestsConfig; tier: 'quick' | 'full'; rawA
169
169
  }
170
170
  }
171
171
 
172
- /** how many `--parallel` workers one suite run takes. Every test check runs
173
- * on one slot of the machine pool (core/slots.ts), so a run sized to every
174
- * core while four other checks do the same puts five times the cores to
175
- * work. A run takes its own slot's share of the cores plus the share of
176
- * every slot free when it starts, never more than the cores, and never
177
- * fewer than half of them: the count is fixed for the whole run, and a gate
178
- * starts it while its first burst of short checks holds the pool, so the
179
- * share alone left the longest suite on two workers long after that burst
180
- * ended. Measured on 8 cores: two workers 12.2s, four 7.6s, eight 7.0s */
181
- export function poolWorkers(p: { cores: number; size: number; held: number }): number {
182
- const size = Math.max(1, p.size)
183
- const mine = Math.max(1, size - Math.max(1, p.held) + 1)
184
- const floor = Math.max(2, Math.floor(p.cores / 2))
185
- return Math.max(floor, Math.min(p.cores, Math.round((p.cores * mine) / size)))
186
- }
187
-
188
172
  type Timed = { file: string; ms: number }
189
173
 
190
174
  export function judgeSuites(p: { timings: Record<string, number>; tests: TestsConfig; tier: 'quick' | 'full'; red?: string[] }): { over: Timed[]; noLongerSlow: Timed[]; slowest: Timed[] } {
@@ -246,11 +230,12 @@ export const waitAllowance = (budgetMs: number, load: MachineLoad): number => {
246
230
  export type SuiteWork = { instructions: number; pInstructions: number; cpuMs: number; pCpuMs: number; otherCpuMs: number; childCpuMs: number }
247
231
  /** the main thread's own rate needs this much time on a performance core */
248
232
  export const OWN_RATE_MIN_MS = 20
249
- /** a suite's CPU as if its main thread ran on a performance core: its time
250
- * there, plus what it retired on an efficiency core converted at the rate
251
- * it ran on a performance core when it ran long enough there, never faster
252
- * than `instrPerMs` (calibrate.ts conversionRate, the low end of real
253
- * suites), and never more than the main thread's own CPU. The other threads
233
+ /** a suite's CPU as if its main thread ran on a performance core of a quiet
234
+ * machine: its time there, plus what it retired on an efficiency core
235
+ * converted at the rate it ran on a performance core when it ran long enough
236
+ * there, never faster than `instrPerMs` (calibrate.ts conversionRate, the low
237
+ * end of real suites), never more than the main thread's own CPU, and never
238
+ * more than all its instructions at `instrPerMs`. The other threads
254
239
  * and the children are charged their CPU as it is: a reaped child or an
255
240
  * ended thread has no count left to read, so a suite that spawns keeps the
256
241
  * CPU of what it spawned, and a lone run whose figure is mostly its
@@ -261,7 +246,10 @@ export function coreMs(w: SuiteWork, instrPerMs: number | null): number | null {
261
246
  const own = w.pCpuMs >= OWN_RATE_MIN_MS ? w.pInstructions / w.pCpuMs : null
262
247
  const rate = own != null && instrPerMs != null ? Math.min(own, instrPerMs) : own ?? instrPerMs
263
248
  if (eInstructions > 0 && (rate == null || rate <= 0)) return null
264
- const main = eInstructions === 0 ? w.pCpuMs : Math.min(w.pCpuMs + eInstructions / rate!, w.cpuMs)
249
+ const converted = eInstructions === 0 ? w.pCpuMs : Math.min(w.pCpuMs + eInstructions / rate!, w.cpuMs)
250
+ // a loaded machine runs a performance core slower too (frequency, shared caches, memory bandwidth), so the
251
+ // thread is never charged more than its instructions at the machine's rate, measured quiet
252
+ const main = instrPerMs != null && instrPerMs > 0 ? Math.min(converted, w.instructions / instrPerMs) : converted
265
253
  return main + w.otherCpuMs + w.childCpuMs
266
254
  }
267
255
 
@@ -30,10 +30,10 @@ import { gitBin } from '../core/git-bin.ts'
30
30
  import { blobOid, listingHash } from '../core/read-set.ts'
31
31
  import { shipkitRoot } from '../ledger/db.ts'
32
32
  import { extractSpecs, resolveSpec } from '../ts/source-graph.ts'
33
- import { type RvtConfig } from '../ts/config.ts'
33
+ import { type RvtConfig, workspacePackages } from '../ts/config.ts'
34
34
  import { BETWEEN_TESTS, BUN_RULE, inDotDir } from './judge-suites.ts'
35
35
 
36
- export const SELECT_VERSION = 5
36
+ export const SELECT_VERSION = 6
37
37
 
38
38
  /** what the recorder charged to one module, repo-relative: r a file read, d a
39
39
  * dir listed, g a tree walked, o a spawn nobody records, l a module loaded at
@@ -98,8 +98,42 @@ const statSig = (abs: string): string | null => {
98
98
  }
99
99
  }
100
100
 
101
+ type Workspace = { name: string; dir: string; exports?: unknown }
102
+
103
+ /** a workspace package's specifier through its `exports` (`.`, `./ui`, `./src/*`), repo-relative, or null */
104
+ export function exportTarget(spec: string, ws: readonly Workspace[]): string | null {
105
+ const w = ws.find((p) => spec === p.name || spec.startsWith(`${p.name}/`))
106
+ if (w == null || w.exports == null) return null
107
+ const sub = `.${spec.slice(w.name.length)}`
108
+ const map: Record<string, unknown> = typeof w.exports === 'string' || Array.isArray(w.exports) ? { '.': w.exports } : (w.exports as Record<string, unknown>)
109
+ const pick = (v: unknown): string | null => {
110
+ if (typeof v === 'string') return v
111
+ if (Array.isArray(v)) return v.map(pick).find((x) => x != null) ?? null
112
+ if (v != null && typeof v === 'object') for (const k of ['bun', 'import', 'default', 'require', 'types']) if (k in v) return pick((v as Record<string, unknown>)[k])
113
+ return null
114
+ }
115
+ let to = map[sub] !== undefined ? pick(map[sub]) : null
116
+ if (to == null) {
117
+ for (const [k, v] of Object.entries(map)) {
118
+ const star = k.indexOf('*')
119
+ if (star < 0 || !sub.startsWith(k.slice(0, star)) || !sub.endsWith(k.slice(star + 1))) continue
120
+ const t = pick(v)
121
+ if (t != null) to = t.replace('*', sub.slice(star, sub.length - (k.length - star - 1)))
122
+ break
123
+ }
124
+ }
125
+ return to == null ? null : posix.normalize(posix.join(w.dir, to))
126
+ }
127
+
128
+ /** the walk's config: the source roots' packages, plus each workspace package outside them, imported by its name */
129
+ const graphConfig = (cfg: RvtConfig): { cfg: RvtConfig; ws: Workspace[] } => {
130
+ const ws = workspacePackages(cfg.root, cfg.vendored ?? [])
131
+ const extra = ws.filter((w) => !cfg.packages.some((p) => p.dir === w.dir || p.name === w.name))
132
+ return { cfg: { ...cfg, packages: [...cfg.packages, ...extra.map(({ name, dir }) => ({ name, dir }))].sort((a, b) => b.dir.length - a.dir.length) }, ws }
133
+ }
134
+
101
135
  /** parse one file, from the manifest when its stat signature held */
102
- function entryOf(cfg: RvtConfig, file: string, old: GraphEntry | undefined): GraphEntry | null {
136
+ function entryOf(cfg: RvtConfig, ws: readonly Workspace[], file: string, old: GraphEntry | undefined): GraphEntry | null {
103
137
  const abs = join(cfg.root, file)
104
138
  const sig = statSig(abs)
105
139
  if (sig == null) return null
@@ -121,7 +155,8 @@ function entryOf(cfg: RvtConfig, file: string, old: GraphEntry | undefined): Gra
121
155
  // runs when called, and the recorder sees it then, with who called
122
156
  for (const raw of extractSpecs(text, { dynamic: false })) {
123
157
  const spec = raw.replace(/\?.*$/, '')
124
- const target = resolveSpec(cfg, file, spec, has)
158
+ const exported = exportTarget(spec, ws)
159
+ const target = exported != null && has(exported) ? exported : resolveSpec(cfg, file, spec, has)
125
160
  if (target != null && target !== file) deps.add(target)
126
161
  }
127
162
  return { sig, deps: [...new Set([...deps, ...link])].sort() }
@@ -129,13 +164,14 @@ function entryOf(cfg: RvtConfig, file: string, old: GraphEntry | undefined): Gra
129
164
 
130
165
  /** every file the entries reach by import, parsed through the manifest. The
131
166
  * returned map is the new manifest: only what this walk reached */
132
- export function walkGraph(cfg: RvtConfig, entries: string[], manifest: Record<string, GraphEntry>): Record<string, GraphEntry> {
167
+ export function walkGraph(config: RvtConfig, entries: string[], manifest: Record<string, GraphEntry>): Record<string, GraphEntry> {
168
+ const { cfg, ws } = graphConfig(config)
133
169
  const out: Record<string, GraphEntry> = {}
134
170
  const todo = [...entries]
135
171
  while (todo.length > 0) {
136
172
  const f = todo.pop()!
137
173
  if (out[f] != null) continue
138
- const e = entryOf(cfg, f, manifest[f])
174
+ const e = entryOf(cfg, ws, f, manifest[f])
139
175
  if (e == null) continue
140
176
  out[f] = e
141
177
  for (const d of e.deps) if (out[d] == null) todo.push(d)
@@ -188,6 +224,12 @@ const listing = (abs: string, deep: boolean): string | null => {
188
224
  * one status, no index write), every recorded read git does not see, and a
189
225
  * hash of every recorded listing and walked tree */
190
226
  export function snapshot(top: string, modules: Record<string, ModuleReads>): Record<string, string> {
227
+ const tree = treeSnapshot(top)
228
+ return { ...tree, ...extras(top, modules, tree) }
229
+ }
230
+
231
+ /** what git tracks or would add, as blob ids: the part of a snapshot no read names */
232
+ export function treeSnapshot(top: string): Record<string, string> {
191
233
  const snap: Record<string, string> = {}
192
234
  for (const line of git(top, ['ls-files', '-s', '-z']).split('\0')) {
193
235
  const tab = line.indexOf('\t')
@@ -207,7 +249,27 @@ export function snapshot(top: string, modules: Record<string, ModuleReads>): Rec
207
249
  delete snap[path]
208
250
  }
209
251
  }
210
- return { ...snap, ...extras(top, modules, snap) }
252
+ return snap
253
+ }
254
+
255
+ /** every key a read names: the files read, the listings and the walked trees */
256
+ const readKeys = (modules: Record<string, ModuleReads>): Set<string> => {
257
+ const out = new Set<string>()
258
+ for (const m of Object.values(modules)) {
259
+ for (const r of m.r ?? []) out.add(r)
260
+ for (const d of m.d ?? []) out.add(listKey(d))
261
+ for (const g of m.g ?? []) out.add(treeKey(g))
262
+ }
263
+ return out
264
+ }
265
+
266
+ /** the snapshot the next run diffs against: the one this run started from, less the keys only a read it no longer
267
+ * records named (a full run replaces the reads, and a file git ignores then leaves every snapshot: kept, it would
268
+ * read as removed), plus what `fresh` adds for the reads first recorded by this run */
269
+ export function baseAfter(tree: Record<string, string>, startedFrom: Record<string, string>, modules: Record<string, ModuleReads>, fresh: (have: Record<string, string>) => Record<string, string>): Record<string, string> {
270
+ const read = readKeys(modules)
271
+ const kept = Object.fromEntries(Object.entries(startedFrom).filter(([k]) => tree[k] != null || read.has(k)))
272
+ return { ...kept, ...fresh(kept) }
211
273
  }
212
274
 
213
275
  /** the recorded reads git does not see, and every recorded listing and walked
@@ -314,6 +376,18 @@ export const isRunConfig = (path: string, envFiles: string[]): boolean =>
314
376
  /** a file bun's test runner runs: `*.test.*`, `*_test.*`, `*.spec.*`, `*_spec.*` in js or ts */
315
377
  export const isBunSuite = (path: string): boolean => /[._](test|spec)\.[cm]?[jt]sx?$/.test(path)
316
378
 
379
+ const TEXT_FORM = /\.(md|mdx|txt|[cm]?[jt]sx?|json|jsonc|ya?ml|toml|csv|html|css|svg)$/
380
+
381
+ /** a changed file only a hooked read can open, so an unclaimed one was read by no
382
+ * suite: a doc outside the preload dirs (a preload's own load goes unrecorded),
383
+ * or a text file in a dot folder, where bun finds no suite and no import goes
384
+ * unrecorded. a native reader (a database, an image library) is never ruled out */
385
+ export const noUnseenReader = (path: string, preloadDirs: string[]): boolean => {
386
+ if (preloadDirs.some((d) => d === '.' || path.startsWith(`${d}/`))) return false
387
+ if (/\.mdx?$/.test(path)) return true
388
+ return inDotDir(path) && TEXT_FORM.test(path)
389
+ }
390
+
317
391
  export function selectSuites(o: {
318
392
  suites: string[]
319
393
  preloads: string[]
@@ -343,7 +417,8 @@ export function selectSuites(o: {
343
417
  const claimed = (c: string): boolean =>
344
418
  c.endsWith('/') || c.endsWith('/**') || o.graph[c] != null || readSet.has(c) || lists.has(posix.dirname(c)) || trees.some((t) => c.startsWith(t))
345
419
  const under = (c: string): boolean => (o.roots ?? []).some((r) => r === '' || r === '.' || c.startsWith(`${r}/`))
346
- for (const c of o.changed) if (!claimed(c) && under(c)) return { all: true, why: `${c} changed, and neither an import nor a recorded read claims it` }
420
+ const preloadDirs = o.preloads.map((p) => posix.dirname(p))
421
+ for (const c of o.changed) if (!claimed(c) && under(c) && !noUnseenReader(c, preloadDirs)) return { all: true, why: `${c} changed, and neither an import nor a recorded read claims it` }
347
422
  // a changed file moves every module that loads it with itself, and one a
348
423
  // preload loads moves every suite: the preload ran it before any suite
349
424
  const importersOf = (withRuntime: boolean): Map<string, string[]> => {
@@ -9,20 +9,21 @@
9
9
  import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
10
10
  import { availableParallelism, tmpdir } from 'os'
11
11
  import { machineLoad } from '../core/budget.ts'
12
- import { join, posix } from 'path'
12
+ import { basename, join, posix } from 'path'
13
13
  import { FULL_TESTS_ENV } from '../ledger/gate-checks.ts'
14
14
  import { CHECK_ID_ENV, recordSuites, type SuitePhase } from '../ledger/suite-log.ts'
15
15
  import { killTree } from '../core/spawn-timeout.ts'
16
16
  import { parallelCap } from '../core/parallel.ts'
17
- import { poolDir, poolOccupancy } from '../core/slots.ts'
17
+ import { poolDir, SLOT_CORES_ENV, SLOT_HELD_ENV, slotsLine, takeFreeSlots } from '../core/slots.ts'
18
+ import { keptWorkMs, mostWorkers, workersFor, workersToStart } from './suite-cores.ts'
18
19
  import { keepTimings, seedTimings, timingsHome } from './kept-timings.ts'
19
20
  import { SUITE_READS_ENV, SUITE_ROOT_ENV, SUITE_SELECT_ENV } from './reads-env.ts'
20
- import { changedKeys, dropStaticEdges, extras, isBunSuite, envFilesOf, foldReads, loadErrorModules, loadState, preloadsOf, saveState, selectStatePath, selectSuites, snapshot, suiteFiles, taintedSuites, walkGraph, type GraphEntry, type Selection, type SelectState } from './select.ts'
21
+ import { baseAfter, changedKeys, dropStaticEdges, extras, isBunSuite, envFilesOf, foldReads, loadErrorModules, loadState, preloadsOf, saveState, selectStatePath, selectSuites, suiteFiles, taintedSuites, treeSnapshot, walkGraph, type GraphEntry, type Selection, type SelectState } from './select.ts'
21
22
  import { gitRoot } from '../core/git-root.ts'
22
23
  import { runReaches, type TestRun } from './test-units.ts'
23
24
  import { loadConfig } from '../ts/config.ts'
24
25
  import { conversionRate, machineRate } from './calibrate.ts'
25
- import { aloneRunsNeeded, bunfigTest, coreMs, cpuAllowance, loadShare, type SuiteWork, type BunfigTest, readPhaseCpu, SUITE_CPU_ENV, type AloneRun, type Confirmed, confirmOver, crashedWorkers, interruptedSuites, overWords, ranAs, retryAlone, smallerRun, stallWords, DEFAULT_BUDGET_MS, FULL_CEILING_MS, failedSuites, failLines, judgeSuites, normSuitePath, parseSuiteFlags, planPhases, QUICK_CEILING_MS, poolWorkers, redWords } from './judge-suites.ts'
26
+ import { aloneRunsNeeded, bunfigTest, coreMs, cpuAllowance, loadShare, type SuiteWork, type BunfigTest, readPhaseCpu, SUITE_CPU_ENV, type AloneRun, type Confirmed, confirmOver, crashedWorkers, interruptedSuites, overWords, ranAs, retryAlone, smallerRun, stallWords, DEFAULT_BUDGET_MS, FULL_CEILING_MS, failedSuites, failLines, judgeSuites, normSuitePath, parseSuiteFlags, planPhases, QUICK_CEILING_MS, redWords } from './judge-suites.ts'
26
27
 
27
28
  type Phase = { code: number; signal: string | null; stalled: boolean; out: string; timings: Record<string, number>; cpuMs: number | null }
28
29
 
@@ -90,6 +91,21 @@ const lastCount = (out: string, re: RegExp): number => Number([...out.matchAll(r
90
91
  /** what the selection carries from before the run to after it */
91
92
  type SelectCtx = { sel: Selecting | null; /** the suites that ran and passed, time included */ ran: string[]; tier: 'quick' | 'full'; /** every suite ran to its end, red or green: no phase stalled or was killed */ complete: boolean; /** what every phase printed */ out: string }
92
93
 
94
+ /** the workers the parallel phase starts and the slots behind them. Inside a check the runner already holds them
95
+ * (SHIPKIT_SLOT_CORES). A run someone started by hand takes the free ones itself and never waits */
96
+ function coresFor(p: { need: number; who: { repo: string; check: string } }): { workers: number; release: () => void } {
97
+ if (process.env[SLOT_HELD_ENV] === '1') {
98
+ const granted = Number(process.env[SLOT_CORES_ENV])
99
+ const slots = Number.isInteger(granted) && granted >= 1 ? granted : 1
100
+ // the runner sized the slots on the whole unit; this run says what the suites it starts use, and gives
101
+ // the rest back once the phase ended (the serial phase and a lone rerun run one suite at a time)
102
+ if (slots > 1) console.log(slotsLine(Math.min(slots, p.need)))
103
+ return { workers: workersToStart(p.need, slots), release: () => { if (slots > 1) console.log(slotsLine(1)) } }
104
+ }
105
+ const own = takeFreeSlots({ dir: poolDir(), size: parallelCap(), load: machineLoad }, p.who, p.need)
106
+ return { workers: workersToStart(p.need, own.count), release: own.release }
107
+ }
108
+
93
109
  export async function suiteCli(argv: string[]): Promise<number> {
94
110
  const ctx: SelectCtx = { sel: null, ran: [], tier: 'quick', complete: false, out: '' }
95
111
  try {
@@ -131,12 +147,10 @@ async function runSuites(argv: string[], ctx: SelectCtx): Promise<number> {
131
147
  // bun drops these the moment any ignore reaches its command line
132
148
  const bunfig = bunfigTest(existsSync('bunfig.toml') ? readFileSync('bunfig.toml', 'utf8') : null)
133
149
  if (bunfig.error != null) { console.log(`FAIL: ${bunfig.error}`); return 1 }
134
- // the pool is read, never taken: this process runs on its check's slot
150
+ // the plan names the most a run asks for; the count it starts is set once the suites to run are known (coresFor)
135
151
  const cores = availableParallelism()
136
- const held = parallel ? poolOccupancy({ dir: poolDir(), size: parallelCap() }).held.length : 0
137
- const pool = parallel ? poolWorkers({ cores, size: parallelCap(), held }) : undefined
138
- const plan = planPhases({ tests, tier, rawArgs, parallel, noIsolate: helpText.includes('--no-isolate'), configIgnores: bunfig.ignores, workers: pool })
139
- const { workers } = plan
152
+ const plan = planPhases({ tests, tier, rawArgs, parallel, noIsolate: helpText.includes('--no-isolate'), configIgnores: bunfig.ignores, workers: parallel ? mostWorkers(cores) : undefined })
153
+ let workers = plan.workers
140
154
  const dir = mkdtempSync(join(tmpdir(), 'shipkit-suite-'))
141
155
  const tmp = join(dir, 'temp')
142
156
  mkdirSync(tmp)
@@ -189,8 +203,15 @@ async function runSuites(argv: string[], ctx: SelectCtx): Promise<number> {
189
203
  return files.length === 0 ? null : [...plan.alone, ...files]
190
204
  })()
191
205
  const parallelEmpty = pickedSet != null && parallelArgs.length === plan.parallel.length
206
+ // the workers follow the suites this phase starts, and the slots held for them
207
+ const held = plan.workers == null || parallelEmpty ? null : coresFor({
208
+ need: Math.min(plan.workers, workersFor(kept == null ? null : keptWorkMs(join(dir, 'parallel.json'), pickedSet == null ? undefined : new Set([...pickedSet].filter((f) => !serialSet.has(f)))), cores)),
209
+ who: { repo: basename(process.cwd()), check: process.env[CHECK_ID_ENV] ?? (unit === '' ? 'test' : `test:${unit}`) },
210
+ })
211
+ if (held != null) workers = held.workers
212
+ const phaseArgs = held == null ? parallelArgs : parallelArgs.map((a) => (/^--parallel(=\d+)?$/.test(a) ? `--parallel=${held.workers}` : a))
192
213
  const p1At = Date.now()
193
- const p1 = parallelEmpty ? { ...NO_PHASE } : await runPhase(parallelArgs, timed ? join(dir, 'parallel.json') : null, ceilingMs, tmp, true, cpuFile, rec)
214
+ const p1 = parallelEmpty ? { ...NO_PHASE } : await runPhase(phaseArgs, timed ? join(dir, 'parallel.json') : null, ceilingMs, tmp, true, cpuFile, rec).finally(() => held?.release())
194
215
  const p1Ms = Date.now() - p1At
195
216
  // bun merges what it read into what it writes, so a suite deleted since
196
217
  // the last run is judged and kept only if the workers say it ran here
@@ -335,7 +356,7 @@ async function runSuites(argv: string[], ctx: SelectCtx): Promise<number> {
335
356
  if (fails.length > 0) { console.log(fails[0]); return 1 }
336
357
  const serialCount = serialArgs != null ? phaseFiles(serialArgs, rawArgs).length : 0
337
358
  const chosen = ctx.sel?.picked != null ? `, the ${ctx.sel.picked.length} of ${ctx.sel.total} a change reaches` : ''
338
- console.log(`ok: Ran ${ran} tests across ${Object.keys(timings).length || '?'} suites${chosen}, ${parallel ? `parallel on ${workers} workers` : 'one at a time'}${serialCount > 0 ? ` then ${serialCount} serial` : ''}, ${tier} tier, ${ranAs(plan.parallel, rawArgs)}${slowest}`)
359
+ console.log(`ok: Ran ${ran} tests across ${Object.keys(timings).length || '?'} suites${chosen}, ${parallel ? `parallel on ${workers} workers` : 'one at a time'}${serialCount > 0 ? ` then ${serialCount} serial` : ''}, ${tier} tier, ${ranAs(phaseArgs, rawArgs)}${slowest}`)
339
360
  return 0
340
361
  } finally {
341
362
  rmSync(dir, { recursive: true, force: true })
@@ -349,6 +370,8 @@ type Selecting = {
349
370
  rec: Recording
350
371
  statePath: string
351
372
  state: SelectState
373
+ /** what git saw when the run started, the part of `now` no read names */
374
+ tree: Record<string, string>
352
375
  now: Record<string, string>
353
376
  graph: Record<string, GraphEntry>
354
377
  preloads: string[]
@@ -408,9 +431,10 @@ function prepareSelection(o: { tests: TestsConfigLike; tier: 'quick' | 'full'; r
408
431
  const loads = Object.values(state.modules).flatMap((m) => m.l ?? [])
409
432
  const graph = walkGraph(cfg, [...suites.map(toTop), ...preloads, ...loads], state.graph)
410
433
  const started = Date.now()
411
- const now = snapshot(top, state.modules)
434
+ const tree = treeSnapshot(top)
435
+ const now = { ...tree, ...extras(top, state.modules, tree) }
412
436
  const rec: Recording = { file: join(tmpdir(), `shipkit-reads-${process.pid}-${Date.now()}.tsv`), top }
413
- const base = { rec, statePath, state, now, started, graph, preloads, cwdRel, allSuites: suites.map(toTop), total: suites.length, notes, changed: 0 }
437
+ const base = { rec, statePath, state, tree, now, started, graph, preloads, cwdRel, allSuites: suites.map(toTop), total: suites.length, notes, changed: 0 }
414
438
  if (o.tier !== 'quick') return { ...base, picked: null }
415
439
  const pos = positional(o.rawArgs)
416
440
  if (pos != null) { notes.push(`note: every suite runs: the test script names ${pos}, which a selection would override`); return { ...base, picked: null } }
@@ -455,7 +479,7 @@ function finishSelection(sel: Selecting, passed: string[], replace: boolean, out
455
479
  const dirty = [...new Set([...before, ...picked.filter((s) => !ok.has(s) || tainted.has(s))])].sort()
456
480
  // a read first recorded by this run joins the snapshot it started from,
457
481
  // unless its path moved since the start
458
- const base = { ...sel.now, ...extras(sel.rec.top, modules, sel.now, sel.started) }
482
+ const base = baseAfter(sel.tree, sel.now, modules, (have) => extras(sel.rec.top, modules, have, sel.started))
459
483
  saveState(sel.statePath, { ...sel.state, base, dirty, modules, recorded, graph: sel.graph, bun: Bun.version })
460
484
  return null
461
485
  } catch (e) {
@@ -0,0 +1,68 @@
1
+ // HOW MANY WORKERS A SUITE RUN STARTS, and how many slots of the machine pool
2
+ // it asks for (core/slots.ts: a slot is one core's worth of work). The count
3
+ // follows the work: the kept durations of the suites the run will start. A
4
+ // worker pays its own start and its own load of the import closure, so a
5
+ // short run on many workers burns more CPU for the same wall.
6
+ //
7
+ // The one constraint a reader breaks first: a run starts the workers it holds
8
+ // slots for, and at least two when its work asks for two. bun fixes the count
9
+ // for the whole run, and a long suite left on one worker sets the gate's time
10
+ // alone (a phase bound by process spawns took 20 to 46s on two workers, 7.6s
11
+ // on four).
12
+ import { readFileSync } from 'fs'
13
+ import { availableParallelism } from 'os'
14
+ import { normSuitePath } from './judge-suites.ts'
15
+ import { timingsHome } from './kept-timings.ts'
16
+
17
+ /** the suite time one worker is worth starting for */
18
+ export const WORKER_WORK_MS = 4000
19
+
20
+ /** the most workers one run asks for: half the cores. Measured on 8 cores: two workers 12.2s, four 7.6s, eight 7.0s */
21
+ export const mostWorkers = (cores: number): number => Math.max(1, Math.floor(cores / 2))
22
+
23
+ /** the workers this much suite time asks for. null: nothing kept yet, so the most */
24
+ export function workersFor(workMs: number | null, cores: number): number {
25
+ const most = mostWorkers(cores)
26
+ return workMs == null ? most : Math.max(1, Math.min(most, Math.ceil(workMs / WORKER_WORK_MS)))
27
+ }
28
+
29
+ /** the workers a run starts: what it holds slots for, never more than its work asks, and two when it asks for two */
30
+ export const workersToStart = (need: number, slots: number): number => Math.max(Math.min(need, Math.max(1, slots)), Math.min(2, need))
31
+
32
+ /** the kept durations summed, over every suite or over `only`. null when nothing readable is kept. A suite of
33
+ * `only` with no kept duration counts as one worker's worth: it is new, and nobody knows what it costs */
34
+ export function keptWorkMs(file: string, only?: ReadonlySet<string>): number | null {
35
+ let files: Record<string, unknown>
36
+ try {
37
+ const parsed = JSON.parse(readFileSync(file, 'utf8')) as { files?: unknown }
38
+ if (parsed?.files == null || typeof parsed.files !== 'object' || Array.isArray(parsed.files)) return null
39
+ files = parsed.files as Record<string, unknown>
40
+ } catch {
41
+ return null
42
+ }
43
+ const ms = new Map<string, number>()
44
+ for (const [f, v] of Object.entries(files)) {
45
+ const n = typeof v === 'number' ? v : Number((v as { ms?: unknown } | null)?.ms)
46
+ if (Number.isFinite(n)) ms.set(normSuitePath(f), n)
47
+ }
48
+ if (only == null) return ms.size === 0 ? null : [...ms.values()].reduce((a, b) => a + b, 0)
49
+ let sum = 0
50
+ for (const f of only) sum += ms.get(normSuitePath(f)) ?? WORKER_WORK_MS
51
+ return sum
52
+ }
53
+
54
+ /** the unit a suite runner command runs (`''` for the root), null when the command is not the suite runner */
55
+ export function suiteUnitOf(cmd: readonly string[] | undefined): string | null {
56
+ if (cmd == null) return null
57
+ const at = cmd.findIndex((a) => /(?:^|\/)suite-cli\.ts$/.test(a))
58
+ if (at < 0) return null
59
+ for (let i = at + 1; i < cmd.length && cmd[i] !== '--'; i++) if (cmd[i] === '--unit') return cmd[i + 1] ?? ''
60
+ return ''
61
+ }
62
+
63
+ /** the slots a check asks the pool for: the workers its whole unit asks for when it runs the suite runner, else one */
64
+ export function slotsWanted(cmd: readonly string[] | undefined, cwd: string, cores: number = availableParallelism()): number {
65
+ const unit = suiteUnitOf(cmd)
66
+ if (unit == null) return 1
67
+ try { return workersFor(keptWorkMs(timingsHome(cwd, unit)), cores) } catch { return mostWorkers(cores) }
68
+ }