rvlib-shipkit 2.23.0 → 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 (97) hide show
  1. package/CHANGELOG.md +25 -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/asks/asks-queue.ts +32 -11
  8. package/src/checks/SK044-behind-upstream.check.ts +38 -0
  9. package/src/cli/cmd_Asks.ts +2 -0
  10. package/src/cli/cmd_Backup.ts +7 -5
  11. package/src/cli/cmd_Bump.ts +1 -0
  12. package/src/cli/cmd_Capacity.ts +26 -0
  13. package/src/cli/cmd_Check.ts +1 -0
  14. package/src/cli/cmd_Checks.ts +1 -0
  15. package/src/cli/cmd_Ci.ts +1 -0
  16. package/src/cli/cmd_Commands.ts +50 -14
  17. package/src/cli/cmd_Home.ts +0 -29
  18. package/src/cli/cmd_Hooks.ts +1 -0
  19. package/src/cli/cmd_Mv.ts +1 -0
  20. package/src/cli/cmd_Reflect.ts +1 -0
  21. package/src/cli/cmd_Releases.ts +1 -0
  22. package/src/cli/cmd_Review.ts +97 -14
  23. package/src/cli/cmd_Secret.ts +41 -2
  24. package/src/cli/cmd_Shot.ts +1 -0
  25. package/src/cli/cmd_Status.ts +1 -0
  26. package/src/cli/cmd_Time.ts +3 -1
  27. package/src/cli/cmd_Tmp.ts +82 -0
  28. package/src/cli/cmd_Wiki.ts +1 -0
  29. package/src/cli/registry.ts +13 -1
  30. package/src/collections/pings.ts +1 -1
  31. package/src/core/capacity.ts +71 -0
  32. package/src/core/check-runner.ts +86 -15
  33. package/src/core/motherhome.ts +67 -9
  34. package/src/core/slots.ts +49 -12
  35. package/src/core/trace-audit.ts +4 -1
  36. package/src/drill/run.ts +5 -2
  37. package/src/home/gui-app/ShipkitGui.swift +1 -0
  38. package/src/home/home-launchd.ts +11 -3
  39. package/src/home/home-routes.ts +11 -4
  40. package/src/home/machine-host.ts +65 -0
  41. package/src/home/machine-stores.ts +19 -17
  42. package/src/home/machine-temp.ts +493 -0
  43. package/src/home/other-macs.ts +74 -0
  44. package/src/home/run-daemon.ts +10 -2
  45. package/src/home/serve-web.ts +2 -2
  46. package/src/home/via-hub.ts +6 -1
  47. package/src/init-repo.ts +7 -3
  48. package/src/ledger/ledger.ts +6 -0
  49. package/src/ledger/store.ts +6 -0
  50. package/src/media-store/backup/keys.ts +21 -6
  51. package/src/media-store/backup/manifest.ts +52 -11
  52. package/src/media-store/backup/restore.ts +17 -10
  53. package/src/media-store/backup/run.ts +5 -2
  54. package/src/media-store/backup/sources.ts +2 -1
  55. package/src/mv/mv-md.ts +121 -42
  56. package/src/reflect/transcript.ts +56 -11
  57. package/src/releases/from-card.ts +45 -3
  58. package/src/releases/model.ts +6 -0
  59. package/src/releases/store.ts +8 -1
  60. package/src/repo-config.ts +5 -3
  61. package/src/review/cells.ts +24 -3
  62. package/src/review/format.ts +33 -9
  63. package/src/review/media-kind.ts +14 -11
  64. package/src/review/media-read.ts +6 -5
  65. package/src/review/model.ts +71 -3
  66. package/src/review/paste.ts +2 -1
  67. package/src/review/previews.ts +123 -36
  68. package/src/review/routes.ts +29 -18
  69. package/src/review/store.ts +74 -12
  70. package/src/review/threads.ts +7 -5
  71. package/src/secrets/copy.ts +110 -0
  72. package/src/secrets/list.ts +17 -7
  73. package/src/serve/hub-app/home-strip.css +5 -0
  74. package/src/serve/hub-app/home-strip.tsx +18 -0
  75. package/src/serve/hub-app/hub-app.tsx +2 -1
  76. package/src/serve/hub-app/hub.css +14 -0
  77. package/src/serve/hub-app/inbox.css +1 -0
  78. package/src/serve/hub-app/pull-refresh.tsx +88 -0
  79. package/src/serve/hub-app/review/review-cells.tsx +52 -13
  80. package/src/serve/hub-app/review/review-list.tsx +6 -1
  81. package/src/serve/hub-app/review/review-st.ts +6 -5
  82. package/src/serve/hub-app/review/review-thread.tsx +3 -1
  83. package/src/serve/hub-app/review/review-views.tsx +18 -11
  84. package/src/serve/hub-app/review/thread-st.ts +82 -14
  85. package/src/serve/hub-app/review.css +15 -2
  86. package/src/serve/hub-runtime.ts +2 -1
  87. package/src/serve/run-serve.ts +4 -2
  88. package/src/serve/serve-hub.ts +9 -2
  89. package/src/suite/child-tools.ts +45 -0
  90. package/src/suite/judge-suites.ts +10 -22
  91. package/src/suite/select.ts +83 -8
  92. package/src/suite/suite-cli.ts +38 -14
  93. package/src/suite/suite-cores.ts +68 -0
  94. package/src/suite/suite-reads-preload.ts +8 -6
  95. package/src/ts/config.ts +44 -0
  96. package/src/ts/rename.ts +11 -1
  97. package/src/home/claude-temp.ts +0 -139
@@ -144,9 +144,11 @@ export class ThreadSt {
144
144
  full: Record<string, boolean> = {}
145
145
  /** an option row folded or unfolded by hand, by `<item>#<view>` */
146
146
  openRows: Record<string, boolean> = {}
147
+ /** his hint being typed on an agent's update, by the update's cell id */
148
+ hints: Record<string, string> = {}
147
149
  busy = false
148
- /** the verdict he just gave: shown as chosen the moment he clicks, while the store takes it */
149
- sending: { on: string; status: ReviewStatus } | null = null
150
+ /** the verdict he just gave (null: the one he took back): shown the moment he clicks, while the store takes it */
151
+ sending: { on: string; status: ReviewStatus | null } | null = null
150
152
  private readonly clips = new Map<string, ClipSt>()
151
153
  /** a trailer card's player, by its version's id */
152
154
  private readonly trailers = new Map<string, TrailerSt>()
@@ -431,7 +433,10 @@ export class ThreadSt {
431
433
  if (h?.kind !== 'version' || h.item.wip) return []
432
434
  const sent = this.verdictsOn(h.id).findLast((v) => v.current)
433
435
  const choice = isChoice(h.item)
434
- return h.item.views.map((v, i) => {
436
+ // an older update's picture is history: only the newest one waits for his answer
437
+ const ups = this.updateViewsOf(h.id)
438
+ const past = new Set(ups.slice(0, -1))
439
+ return h.item.views.flatMap((v, i) => (past.has(i) ? [] : [{ v, i }])).map(({ v, i }) => {
435
440
  const own = this.reactionOf(i)
436
441
  const given = sent?.reactions.find((r) => r.view === i && r.tile === undefined)
437
442
  const r = own ?? given
@@ -444,6 +449,11 @@ export class ThreadSt {
444
449
  })
445
450
  }
446
451
 
452
+ /** the views of an item its agent's updates hold, oldest update first: they draw in the update's cell */
453
+ updateViewsOf(on: string): number[] {
454
+ return this.cells.flatMap((c) => (c.kind === 'reply' && c.on === on && c.update?.view !== undefined ? [c.update.view] : []))
455
+ }
456
+
447
457
  /** the views of that version still waiting for his answer, of all its views: « 3 of 5 views waiting for you » */
448
458
  get waitingViews(): { waiting: number; of: number } | null {
449
459
  const marks = this.viewMarks
@@ -456,8 +466,8 @@ export class ThreadSt {
456
466
  /** the verdicts on one version, oldest first */
457
467
  /** the verdict a version shows as chosen: the one being sent, else its current one */
458
468
  chosenOn(id: string): ReviewStatus | undefined {
459
- if (this.sending?.on === id) return this.sending.status
460
- return this.verdictsOn(id).findLast((x) => x.current)?.verdict
469
+ if (this.sending?.on === id) return this.sending.status ?? undefined
470
+ return this.currentVerdict(id)?.verdict
461
471
  }
462
472
 
463
473
  verdictsOn(id: string): VerdictCell[] {
@@ -693,10 +703,15 @@ export class ThreadSt {
693
703
  return [...(this.draft.reactions ?? [])].sort((a, b) => a.view - b.view || (a.tile ?? -1) - (b.tile ?? -1))
694
704
  }
695
705
 
696
- /** « pick »: that option is his answer, sent at once as an approval; his stars and words go with it */
706
+ /** « pick »: that option is his answer, sent at once as an approval; his stars and words go with it. The option he
707
+ * picked, clicked again, takes the pick back */
697
708
  async choose(view: number): Promise<void> {
698
709
  const h = this.head
699
710
  if (h?.kind !== 'version' || !isChoice(h.item)) return
711
+ if (this.holdsPick(h.id, view)) {
712
+ this.edit(({ pick: _, ...d }) => d)
713
+ return this.takeBack()
714
+ }
700
715
  this.edit((d) => ({ ...d, pick: view }))
701
716
  await this.submit('approved')
702
717
  }
@@ -847,7 +862,19 @@ export class ThreadSt {
847
862
 
848
863
  // ── what he sends ──
849
864
 
850
- /** V, F, R, A: the draft goes to the newest version as the owner's verdict */
865
+ /** the verdict that holds on a version now, as sent: what a click on the lit verdict takes back */
866
+ private currentVerdict(id: string): VerdictCell | undefined {
867
+ return this.verdictsOn(id).findLast((x) => x.current)
868
+ }
869
+
870
+ /** that option is the pick his answer holds: a click on it takes it back */
871
+ holdsPick(id: string, view: number): boolean {
872
+ const v = this.currentVerdict(id)
873
+ return v?.verdict === 'approved' && v.pick === view
874
+ }
875
+
876
+ /** V, F, R, A: the draft goes to the newest version as the owner's verdict. The verdict that holds already, clicked
877
+ * again, is taken back instead (a new pick on a choice is a new answer) */
851
878
  async submit(status: ReviewStatus): Promise<void> {
852
879
  const h = this.head
853
880
  if (!h || this.busy) return
@@ -860,20 +887,36 @@ export class ThreadSt {
860
887
  return
861
888
  }
862
889
  const d = this.draft
863
- const head = this.data?.head ?? h.id
864
- this.busy = true
865
- this.error = null
866
- this.sending = { on: h.id, status }
867
- this.rv.setAnswering(head, status)
868
- try {
890
+ const held = this.currentVerdict(h.id)
891
+ if (held?.verdict === status && (d.pick === undefined || d.pick === held.pick)) return this.takeBack()
892
+ await this.send(h.id, status, async () => {
869
893
  const pick = isChoice(h.item) && isApproved(status) && d.pick !== undefined ? { pick: d.pick } : {}
870
894
  await postJson(this.rv.url(`/api/review/${h.id}/feedback`), { status, comment: d.comment, rects: d.rects, reactions: d.reactions ?? [], ...pick })
871
895
  runInAction(() => this.settle(h.id, d))
896
+ })
897
+ }
898
+
899
+ /** a click on his lit verdict: he takes it back, and the card waits for his answer again (the old verdict stays in
900
+ * the thread, an agent's watch hears it); his draft stays as it is */
901
+ async takeBack(): Promise<void> {
902
+ const h = this.head
903
+ if (h?.kind !== 'version' || this.busy || !this.currentVerdict(h.id)) return
904
+ await this.send(h.id, null, () => postJson(this.rv.url(`/api/review/${h.id}/reopen`), {}))
905
+ }
906
+
907
+ /** one answer on its way: shown at once on the card and its row, the truth again once the store took it or refused */
908
+ private async send(on: string, status: ReviewStatus | null, post: () => Promise<unknown>): Promise<void> {
909
+ const head = this.data?.head ?? on
910
+ this.busy = true
911
+ this.error = null
912
+ this.sending = { on, status }
913
+ this.rv.setAnswering(head, status ?? 'pending')
914
+ try {
915
+ await post()
872
916
  await this.rv.answered()
873
917
  } catch (e) {
874
918
  runInAction(() => (this.error = (e as Error).message))
875
919
  } finally {
876
- // the store's answer is in by now, or the send failed: either way what shows is the truth again
877
920
  runInAction(() => {
878
921
  this.busy = false
879
922
  this.sending = null
@@ -905,6 +948,31 @@ export class ThreadSt {
905
948
  }
906
949
  }
907
950
 
951
+ setHint(cellId: string, text: string): void {
952
+ this.hints[cellId] = text
953
+ }
954
+
955
+ /** Enter or « hint »: his few words on one update go to its item as a reply naming it; the card stays as it is */
956
+ async sendHint(c: { id: string; on: string }): Promise<void> {
957
+ const sent = this.hints[c.id] ?? ''
958
+ const text = sent.trim()
959
+ const re = c.id.slice(c.on.length + 1)
960
+ if (!text || this.busy) return
961
+ this.busy = true
962
+ this.error = null
963
+ try {
964
+ await postJson(this.rv.url(`/api/review/${c.on}/reply`), { text, re })
965
+ runInAction(() => {
966
+ if (this.hints[c.id] === sent) delete this.hints[c.id]
967
+ })
968
+ await this.rv.answered()
969
+ } catch (e) {
970
+ runInAction(() => (this.error = (e as Error).message))
971
+ } finally {
972
+ runInAction(() => (this.busy = false))
973
+ }
974
+ }
975
+
908
976
  /** the agent words he has not read, by cell id: the page sends them read once each shows on his screen */
909
977
  get unreadCells(): string[] {
910
978
  return this.cells.filter((c) => (c.kind === 'reply' || c.kind === 'note') && c.party === 'agent' && !c.read && c.id.includes('/')).map((c) => c.id)
@@ -79,9 +79,18 @@
79
79
  color:var(--bg);background:var(--tone,var(--dim));white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:120px}
80
80
  .rv-badge.outline{background:none;color:var(--ink);border:1px solid var(--line)}
81
81
  .rv-about{font-size:11px;color:var(--dim);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0}
82
+ /* an agent's update: where the work stands, at a glance; its tone the state's */
83
+ .up-broken{--tone:var(--red)}
84
+ .up-better{--tone:var(--warn)}
85
+ .up-fixed{--tone:var(--ok)}
86
+ .rv-rowupdate{font-size:11.5px;line-height:1.35;margin-top:var(--s0);color:var(--ink);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
87
+ .rv-rowupdate b{color:var(--tone);text-transform:uppercase;font-size:10px;letter-spacing:.04em;margin-right:var(--s1)}
88
+ .rv-hint{display:flex;gap:var(--s1);margin-top:var(--s2)}
89
+ .rv-hint input{flex:1;min-width:0;font-size:13px}
82
90
  /* a narrow list: the title on its own line on top, a smaller image under it beside the badges */
83
91
  @container (max-width:250px){
84
- .rv-row{display:grid;grid-template-columns:40px minmax(0,1fr);grid-template-areas:"title title" "thumb meta" "rework rework";align-items:center;column-gap:var(--s2);row-gap:var(--s1)}
92
+ .rv-row{display:grid;grid-template-columns:40px minmax(0,1fr);grid-template-areas:"title title" "thumb meta" "update update" "rework rework";align-items:center;column-gap:var(--s2);row-gap:var(--s1)}
93
+ .rv-row .rv-rowupdate{grid-area:update;margin-top:0}
85
94
  .rv-row .rv-rowbody{display:contents}
86
95
  .rv-row .rv-rowtitle{grid-area:title}
87
96
  .rv-row .rv-thumb{grid-area:thumb;width:40px;height:40px}
@@ -218,6 +227,10 @@
218
227
  .rv-verdict{padding:var(--s1) var(--s3);font-size:13px;border-color:color-mix(in srgb,var(--tone) 60%,var(--line))}
219
228
  .rv-verdict .rv-vglyph{color:var(--tone);font-weight:800}
220
229
  .rv-verdict.chosen{background:color-mix(in srgb,var(--tone) 22%,var(--panel));border-color:var(--tone)}
230
+ /* the lit verdict or pick is a toggle: its ↺ says a click takes it back, and a hover shows it lifting */
231
+ .rv-undo{opacity:.7;font-weight:700}
232
+ .rv-verdict.chosen:hover:not(:disabled),.rv-pick.on:hover:not(:disabled){border-style:dashed;background:var(--panel)}
233
+ .rv-pick.on:hover:not(:disabled){color:var(--ok)}
221
234
  .rv-send{padding:var(--s1) var(--s4)}
222
235
 
223
236
  /* ── a version's views: each a sub cell, its number and title big, its kind, then what was said on it ── */
@@ -259,7 +272,7 @@ span.rv-react{display:inline-block;border:1px solid;border-radius:4px}
259
272
  .rv-over:has(.rv-note){z-index:5}
260
273
  .rv-frame{position:relative;width:100%;max-width:100%;border-radius:4px;border:1px solid var(--line);overflow:hidden;
261
274
  background:repeating-conic-gradient(var(--chk1) 0 25%,var(--chk2) 0 50%) 0 0/16px 16px}
262
- .rv-frame.swipe{cursor:ew-resize;touch-action:none}
275
+ .rv-frame.swipe{cursor:ew-resize;touch-action:pan-y pinch-zoom}
263
276
  .rv-fill{position:absolute;inset:0}
264
277
  .rv-caption{font-size:11px;color:var(--dim)}
265
278
  .rv-caption.mod,.rv-modcap{color:var(--k2)}
@@ -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
@@ -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[]> => {