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
@@ -36,7 +36,8 @@ import { CheckPass } from './check-pass.ts'
36
36
  import type { ReadSet } from './read-set.ts'
37
37
  import { RepoView } from '../ledger/repo-view.ts'
38
38
  import { parallelCap } from './parallel.ts'
39
- import { machinePool, SLOT_HELD_ENV, takeSlot, type SlotPool } from './slots.ts'
39
+ import { machinePool, SLOT_CORES_ENV, SLOT_HELD_ENV, SLOTS_LINE, takeFreeSlots, takeSlot, type SlotPool } from './slots.ts'
40
+ import { slotsWanted } from '../suite/suite-cores.ts'
40
41
  import { budgetLine, machineLoad } from './budget.ts'
41
42
  import { killTree, spawnWithTimeout } from './spawn-timeout.ts'
42
43
  import { FOREVER_MS, formatLine, parseWireOutput, type Line } from './wire.ts'
@@ -70,6 +71,9 @@ const MAX_EXTRA = 20
70
71
  * record show more checks at once than ever ran */
71
72
  const clock = (): number => Math.floor(performance.timeOrigin + performance.now())
72
73
 
74
+ /** a check whose kept runs all ended under this takes no machine slot */
75
+ export const SHORT_CHECK_MS = 2000
76
+
73
77
  export type CheckBody = Pick<CheckDef, 'run' | 'cmd' | 'env' | 'cwd'>
74
78
 
75
79
  /** one check, resolved: everything the runner needs and nothing it does not.
@@ -180,6 +184,8 @@ export type RunChecksOpts = {
180
184
  childEnv?: Record<string, string | undefined>
181
185
  bail?: boolean
182
186
  maxParallel?: number
187
+ /** what a check's newest kept runs took, newest first: the ledger's by default. A scheduling hint, never a verdict */
188
+ lastRuns?: (id: string) => number[]
183
189
  /** the machine pool every measured check takes a slot from (core/slots.ts).
184
190
  * Omitted: this machine's pool. null: no pool, the in process cap alone */
185
191
  pool?: SlotPool | null
@@ -438,6 +444,8 @@ let runSeq = 0
438
444
 
439
445
  type Live = RunnableCheck & CheckResult & {
440
446
  startedAt: number
447
+ /** the machine slots its body runs on: one, more for a suite run's workers */
448
+ cores: number
441
449
  /** when its body stopped, stamped BEFORE its slot goes back: a row must
442
450
  * never outlast the slot, or another process starting on it overlaps */
443
451
  endedAt: number
@@ -508,7 +516,7 @@ export async function runChecks(o: RunChecksOpts): Promise<RunChecksSummary> {
508
516
  const runDir = openRunDir(o.logDir)
509
517
  const checks: Live[] = sel.selected.map((u) => ({
510
518
  ...u,
511
- status: 'skip', advisory: false, replayed: false, ms: 0, exitCode: null, lines: [], problems: [], lastLine: '', note: '', startedAt: 0, endedAt: 0, unmeasured: false, attached: false, reads: null, untracked: null, waiverFiles: [], synthetic: false, tail: '', extra: [],
519
+ status: 'skip', advisory: false, replayed: false, ms: 0, exitCode: null, lines: [], problems: [], lastLine: '', note: '', startedAt: 0, endedAt: 0, unmeasured: false, attached: false, cores: 1, reads: null, untracked: null, waiverFiles: [], synthetic: false, tail: '', extra: [],
512
520
  logPath: u.body.cmd != null ? join(runDir, `${u.id.replace(/[^a-zA-Z0-9-]/g, '_')}.log`) : null,
513
521
  }))
514
522
  const selectedIds = new Set(checks.map((u) => u.id))
@@ -519,6 +527,44 @@ export async function runChecks(o: RunChecksOpts): Promise<RunChecksSummary> {
519
527
  const cap = o.maxParallel ?? parallelCap()
520
528
  const pool = o.pool === undefined ? machinePool() : o.pool
521
529
  let slotWaitSaid = false
530
+ // what this check's newest kept runs took: the hint that tells a short check from a long one. No verdict reads it
531
+ const lastRunsMemo = new Map<string, number[]>()
532
+ const lastRuns = (id: string): number[] => {
533
+ let v = lastRunsMemo.get(id)
534
+ if (v == null) { try { v = o.lastRuns?.(id) ?? o.ledger?.lastRuns(id) ?? [] } catch { v = [] } lastRunsMemo.set(id, v) }
535
+ return v
536
+ }
537
+ const wantsMemo = new Map<string, number>()
538
+ const slotsOf = (u: Live): number => {
539
+ let v = wantsMemo.get(u.id)
540
+ if (v == null) { v = slotsWanted(u.body.cmd, u.body.cwd ?? o.root); wantsMemo.set(u.id, v) }
541
+ return v
542
+ }
543
+ /** a check whose kept runs were all short takes no slot: it costs less than its own wait, and a one second
544
+ * lint waited minutes behind another repo's suite. A suite check whose selection reached nothing is one too */
545
+ const isShort = (u: Live): boolean => {
546
+ const runs = lastRuns(u.id)
547
+ return runs.length > 0 && Math.max(...runs) < SHORT_CHECK_MS
548
+ }
549
+ /** the longest check starts first, so it never sets the gate's time from the back of the queue. A check with no
550
+ * kept run (a new one, or one no key describes) counts as the longest: nobody knows what it costs */
551
+ const lengthOf = (id: string): number => { const runs = lastRuns(id); return runs.length === 0 ? Infinity : Math.max(...runs) }
552
+ const longestFirst = (a: string, b: string): number => { const [x, y] = [lengthOf(a), lengthOf(b)]; return x === y ? 0 : y > x ? 1 : -1 }
553
+ // the free slots a suite check holds beside its own, by check id: its process says when it needs fewer
554
+ const extraSlots = new Map<string, { keep: (n: number) => void }>()
555
+ let slotTurn: Promise<unknown> = Promise.resolve()
556
+ const inTurn = <T>(fn: () => Promise<T>): Promise<T> => {
557
+ const p = slotTurn.then(fn, fn)
558
+ slotTurn = p.catch(() => {})
559
+ return p
560
+ }
561
+ // the wall this run spent behind the pool, split by whether anything of its own ran meanwhile
562
+ const wait = { waiting: 0, measuring: 0, at: 0, idleMs: 0, queuedMs: 0, behind: '' }
563
+ const waitMark = (): void => {
564
+ const now = clock()
565
+ if (wait.at > 0 && wait.waiting > 0) { if (wait.measuring === 0) wait.idleMs += now - wait.at; else wait.queuedMs += now - wait.at }
566
+ wait.at = now
567
+ }
522
568
  let interrupted = false
523
569
  let bailed = false
524
570
  const procs = new Map<string, ReturnType<typeof Bun.spawn>>()
@@ -668,7 +714,7 @@ export async function runChecks(o: RunChecksOpts): Promise<RunChecksSummary> {
668
714
  const r = await spawnWithTimeout(cmd, {
669
715
  timeoutMs: u.timeoutMs,
670
716
  // a child runs on this check's slot and takes none of its own
671
- env: { ...process.env, ...o.childEnv, ...u.body.env, [SLOT_HELD_ENV]: '1', [CHECK_ID_ENV]: u.id },
717
+ env: { ...process.env, ...o.childEnv, ...u.body.env, [SLOT_HELD_ENV]: '1', [SLOT_CORES_ENV]: String(u.cores), [CHECK_ID_ENV]: u.id },
672
718
  cwd: u.body.cwd ?? o.root,
673
719
  onSpawn: (proc) => {
674
720
  try { fd = openSync(u.logPath!, 'a') } catch (e) { logProblem = (e as Error).message }
@@ -678,6 +724,8 @@ export async function runChecks(o: RunChecksOpts): Promise<RunChecksSummary> {
678
724
  logWrite(text)
679
725
  for (const raw of text.split(/\r?\n/)) {
680
726
  const s = stripAnsi(raw).trim()
727
+ const slots = SLOTS_LINE.exec(s)
728
+ if (slots != null) { extraSlots.get(u.id)?.keep(Math.max(0, Number(slots[1]) - 1)); continue }
681
729
  if (s !== '') u.lastLine = s.slice(0, 200)
682
730
  }
683
731
  },
@@ -816,19 +864,33 @@ export async function runChecks(o: RunChecksOpts): Promise<RunChecksSummary> {
816
864
  const measureAndKeep = async (u: Live): Promise<void> => {
817
865
  // a machine slot for the body, and only the body: a replay or an
818
866
  // attached wait runs nothing, so it holds none
819
- const slot = pool == null ? null : await takeSlot(pool, { repo: o.config.name, check: u.id }, {
820
- abort: () => interrupted || bailed,
821
- onWait: (held, why) => {
822
- if (slotWaitSaid) return
823
- slotWaitSaid = true
824
- const who = held.slice(0, 3).map((h) => `${h.repo}/${h.check} pid ${h.pid}`).join(', ')
825
- emit({ kind: 'ok', text: `waiting for a machine slot: ${held.length} held, ${why}${who === '' ? '' : ` (${who}${held.length > 3 ? ', …' : ''})`}` })
826
- },
867
+ const who = { repo: o.config.name, check: u.id }
868
+ const queue = pool != null && !isShort(u)
869
+ if (queue) { waitMark(); wait.waiting++ }
870
+ // one check of this run asks the pool at a time, in the order they started (the longest first), and a suite
871
+ // run adds its free slots in the same turn: a freed slot never goes to a shorter check of the same run
872
+ const got = !queue ? null : await inTurn(async () => {
873
+ const slot = await takeSlot(pool!, who, {
874
+ abort: () => interrupted || bailed,
875
+ onWait: (held, why) => {
876
+ const holders = held.filter((h) => h.pid !== process.pid).slice(0, 3).map((h) => `${h.repo}/${h.check} pid ${h.pid}`).join(', ')
877
+ if (wait.behind === '' && holders !== '') wait.behind = holders
878
+ if (slotWaitSaid) return
879
+ slotWaitSaid = true
880
+ const shown = held.slice(0, 3).map((h) => `${h.repo}/${h.check} pid ${h.pid}`).join(', ')
881
+ emit({ kind: 'ok', text: `waiting for a machine slot: ${held.length} held, ${why}${shown === '' ? '' : ` (${shown}${held.length > 3 ? ', …' : ''})`}` })
882
+ },
883
+ })
884
+ return slot == null ? null : { slot, more: takeFreeSlots(pool!, who, slotsOf(u) - 1) }
827
885
  })
828
- if (pool != null && slot == null) { u.status = 'skip'; u.note = bailed ? 'bailed' : 'interrupted'; u.lines = []; u.unmeasured = true; return }
886
+ if (queue) { waitMark(); wait.waiting-- }
887
+ if (queue && got == null) { u.status = 'skip'; u.note = bailed ? 'bailed' : 'interrupted'; u.lines = []; u.unmeasured = true; return }
888
+ u.cores = 1 + (got?.more.count ?? 0)
829
889
  // its time starts when it runs, so a row never counts the queue
830
890
  u.startedAt = clock()
831
- try { await measure(u) } finally { u.endedAt = clock(); slot?.release() }
891
+ waitMark(); wait.measuring++
892
+ if (got != null) extraSlots.set(u.id, got.more)
893
+ try { await measure(u) } finally { u.endedAt = clock(); waitMark(); wait.measuring--; extraSlots.delete(u.id); got?.more.release(); got?.slot.release() }
832
894
  // the headline is built BEFORE anything is remembered: a check
833
895
  // whose result is stored empty replays as a line nobody can tell
834
896
  // from a measurement
@@ -897,8 +959,10 @@ export async function runChecks(o: RunChecksOpts): Promise<RunChecksSummary> {
897
959
  break
898
960
  }
899
961
  let started = false
900
- for (const id of [...queued]) {
901
- if (running.size >= cap) break
962
+ for (const id of [...queued].sort(longestFirst)) {
963
+ // a check waiting for a machine slot runs nothing, so it holds no place: `cap` long checks waiting
964
+ // on a full pool kept a short check, which needs no slot, from starting
965
+ if (running.size - wait.waiting >= cap) break
902
966
  const u = byId.get(id)!
903
967
  const st = depState(u)
904
968
  if (st === 'dead') { queued.delete(id); finish(u); started = true }
@@ -924,6 +988,13 @@ export async function runChecks(o: RunChecksOpts): Promise<RunChecksSummary> {
924
988
  for (const u of checks) if (!results.some((r) => r.id === u.id)) report(u, { id: u.id, status: 'skip', advisory: false, replayed: false, ms: 0, exitCode: null, lines: [], problems: [], lastLine: u.lastLine, note: u.note, logPath: u.logPath })
925
989
  const order = new Map(o.checks.map((u, i) => [u.id, i]))
926
990
  results.sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0))
991
+ // the wait is said apart from the work, so a reader names the right cause of a long run
992
+ waitMark()
993
+ if (wait.idleMs + wait.queuedMs >= 1000) {
994
+ const secs = (ms: number): string => `${(ms / 1000).toFixed(1)}s`
995
+ const parts = [...(wait.idleMs >= 100 ? [`${secs(wait.idleMs)} with nothing of this run running`] : []), ...(wait.queuedMs >= 100 ? [`${secs(wait.queuedMs)} with checks queued while others ran`] : [])]
996
+ emit({ kind: 'ok', text: `waited for a machine slot: ${parts.join(', ')}${wait.behind === '' ? '' : ` (first held by ${wait.behind})`}. The checks' own times are above` })
997
+ }
927
998
  const blocked = results.filter((r) => r.status === 'fail' && !r.advisory)
928
999
  const skipped = results.filter((r) => r.status === 'skip' && r.note !== '' && r.note !== 'off')
929
1000
  if (blocked.length > 0) emit({ kind: 'fail', text: `${blocked.length}/${results.length} failed: ${blocked.map((r) => r.id).join(', ')}` })
@@ -15,6 +15,11 @@
15
15
  // surprise files in its docs tree. The page's read-modify-write runs under
16
16
  // the shared file lock (core/locked-write). Rows whose repo path no longer
17
17
  // exists are pruned from the page and from the machine db.
18
+ //
19
+ // Two Macs land into one tracked page, so each writes and prunes only its own
20
+ // block (`on <machine>`): a row of another Mac names a path this one lacks,
21
+ // and pruning it here would undo that Mac's landing every day. The block from
22
+ // before the per Mac markers gives each Mac the rows under its own home.
18
23
  import { existsSync, readFileSync } from 'fs'
19
24
  import { homedir } from 'os'
20
25
  import { join, resolve } from 'path'
@@ -24,9 +29,14 @@ import { isLinkedWorktree } from './git-root.ts'
24
29
  import { machineCommit } from './machine-commit.ts'
25
30
  import { machineDelete, machineGet, machineList, machineSet } from './machine-db.ts'
26
31
  import { LIB_VERSION } from './lib-version.ts'
32
+ import { machineName } from '../home/machine-host.ts'
27
33
 
28
- const BEGIN = '<!-- >>> shipkit local-projects — machine-written, edit outside the markers -->'
29
- const END = '<!-- <<< shipkit local-projects -->'
34
+ /** the block before the per Mac markers */
35
+ const LEGACY_BEGIN = '<!-- >>> shipkit local-projects — machine-written, edit outside the markers -->'
36
+ const LEGACY_END = '<!-- <<< shipkit local-projects -->'
37
+ export const blockBegin = (machine: string): string => `<!-- >>> shipkit local-projects on ${machine} — machine-written, edit outside the markers -->`
38
+ export const blockEnd = (machine: string): string => `<!-- <<< shipkit local-projects on ${machine} -->`
39
+ const ANY_END = /^<!-- <<< shipkit local-projects( on .+)? -->$/
30
40
  const STALE_DAYS = 7
31
41
  /** the longest the page waits for a changed row: one commit a day at most */
32
42
  export const LAND_GAP_MS = 24 * 60 * 60 * 1000
@@ -100,10 +110,62 @@ function mergeRows(onPage: Row[], filed: Row[]): Row[] {
100
110
  return [...by.values()].filter((r) => existsSync(r.root)).sort((a, z) => a.name.localeCompare(z.name) || a.root.localeCompare(z.root))
101
111
  }
102
112
 
113
+ /** the block between two marker lines: [begin, end] indexes, null when absent, 'broken' when out of order */
114
+ function blockAt(lines: string[], begin: string, end: string): [number, number] | null | 'broken' {
115
+ const b = lines.indexOf(begin)
116
+ const e = lines.indexOf(end)
117
+ if (b === -1 && e === -1) return null
118
+ return b === -1 || e === -1 || e < b ? 'broken' : [b, e]
119
+ }
120
+
121
+ const rowsIn = (lines: string[], [b, e]: [number, number]): Row[] => lines.slice(b + 1, e).map(parseRow).filter((row): row is Row => row != null)
122
+
123
+ /** the page once this Mac's filed rows land in its own block; null when its markers are missing or out of order.
124
+ * The legacy block keeps the rows of another Mac and goes once it holds none */
125
+ export function landPage(text: string, filed: Row[], machine: string, home: string): string | null {
126
+ let lines = text.split('\n')
127
+ const legacy = blockAt(lines, LEGACY_BEGIN, LEGACY_END)
128
+ if (legacy === 'broken') return null
129
+ let carried: Row[] = []
130
+ if (legacy != null) {
131
+ const [b, e] = legacy
132
+ const rows = rowsIn(lines, legacy)
133
+ // this Mac's: under its home, or a repo it filed (a checkout on another volume)
134
+ const filedHere = new Set(filed.map((f) => f.root))
135
+ const mine = (r: Row): boolean => r.root === home || r.root.startsWith(`${home}/`) || filedHere.has(r.root)
136
+ const kept = rows.filter((r) => !mine(r))
137
+ if (kept.length > 0) {
138
+ carried = rows.filter(mine)
139
+ lines = [...lines.slice(0, b + 1), ...kept.map(rowLine), ...lines.slice(e)]
140
+ } else if (blockAt(lines, blockBegin(machine), blockEnd(machine)) == null) {
141
+ // every row is this Mac's: the block becomes its own, in place
142
+ lines = [...lines.slice(0, b), blockBegin(machine), ...lines.slice(b + 1, e), blockEnd(machine), ...lines.slice(e + 1)]
143
+ } else {
144
+ carried = rows
145
+ lines = [...lines.slice(0, b), ...lines.slice(e + 1)]
146
+ if (lines[b - 1] === '' && lines[b] === '') lines.splice(b, 1)
147
+ }
148
+ }
149
+ const own = blockAt(lines, blockBegin(machine), blockEnd(machine))
150
+ if (own === 'broken') return null
151
+ if (own != null) {
152
+ const block = mergeRows([...rowsIn(lines, own), ...carried], filed).map(rowLine)
153
+ return [...lines.slice(0, own[0] + 1), ...block, ...lines.slice(own[1])].join('\n')
154
+ }
155
+ // no block of this Mac yet: a new one right after the last block of any Mac, every line of it a marker or a row,
156
+ // so a docs repo's changelog gate reads the whole edit as machine-written
157
+ const ends = lines.flatMap((l, i) => (ANY_END.test(l) ? [i] : []))
158
+ if (ends.length === 0) return null
159
+ const at = ends[ends.length - 1]! + 1
160
+ return [...lines.slice(0, at), blockBegin(machine), ...mergeRows(carried, filed).map(rowLine), blockEnd(machine), ...lines.slice(at)].join('\n')
161
+ }
162
+
103
163
  /** render every filed row into its page and land each changed page as one
104
164
  * commit, at most once per LAND_GAP_MS. Returns what to print */
105
- export function landMotherhome(o: { now?: number; gapMs?: number } = {}): string[] {
165
+ export function landMotherhome(o: { now?: number; gapMs?: number; machine?: string; home?: string } = {}): string[] {
106
166
  const now = o.now ?? Date.now()
167
+ const machine = o.machine ?? machineName()
168
+ const home = o.home ?? homedir()
107
169
  const notes: string[] = []
108
170
  const filed = machineList<Filed>(ROW)
109
171
  for (const f of filed) if (!existsSync(f.value.root)) machineDelete(f.name)
@@ -116,12 +178,8 @@ export function landMotherhome(o: { now?: number; gapMs?: number } = {}): string
116
178
  if (last != null && now - last < (o.gapMs ?? LAND_GAP_MS)) continue
117
179
  const r = withFileLock(page, (): boolean => {
118
180
  const text = readFileSync(page, 'utf8')
119
- const lines = text.split('\n')
120
- const b = lines.indexOf(BEGIN)
121
- const e = lines.indexOf(END)
122
- if (b === -1 || e === -1 || e < b) { notes.push(`WARN motherhome: markers missing or out of order in ${page}, rows not written`); return false }
123
- const onPage = lines.slice(b + 1, e).map(parseRow).filter((row): row is Row => row != null)
124
- const next = [...lines.slice(0, b + 1), ...mergeRows(onPage, rows).map(rowLine), ...lines.slice(e)].join('\n')
181
+ const next = landPage(text, rows, machine, home)
182
+ if (next == null) { notes.push(`WARN motherhome: markers missing or out of order in ${page}, rows not written`); return false }
125
183
  if (next === text) return false
126
184
  atomicWrite(page, next)
127
185
  return true
package/src/core/slots.ts CHANGED
@@ -1,13 +1,20 @@
1
1
  // THE MACHINE POOL: every shipkit process on this machine (every repo, every
2
- // agent, the hub) measures at most parallelCap() checks at once. One lock file
3
- // per slot, `slot-<n>.lock` under ~/.cache/shipkit/slots/, taken through the
4
- // mutate lease's non blocking form (locked-write.ts tryLease): a slot whose
5
- // holder died is free at once, and a live holder heartbeats it.
2
+ // agent, the hub) shares parallelCap() slots. One lock file per slot,
3
+ // `slot-<n>.lock` under ~/.cache/shipkit/slots/, taken through the mutate
4
+ // lease's non blocking form (locked-write.ts tryLease): a slot whose holder
5
+ // died is free at once, and a live holder heartbeats it.
6
6
  //
7
- // A slot is a check, and a check is often a whole multi core tool (bun test
8
- // workers, linter threads, tsc), so slots alone never bound the CPU. Past the
9
- // cores the pool admits fewer slots in proportion to the 1 minute load, never
10
- // fewer than one (admittedSlots). A slot already held is never taken back.
7
+ // A SLOT IS ONE CORE'S WORTH OF WORK. A check holds one slot. A check that
8
+ // runs many processes at once (a suite run and its workers) adds one free slot
9
+ // per worker (takeFreeSlots) and never waits for them, so what the pool holds
10
+ // is close to what the machine burns. A check counted as one slot whatever it
11
+ // started put 30 to 60 test workers on 8 cores, and the load that followed
12
+ // closed the pool to one check for the whole machine.
13
+ //
14
+ // Work the pool cannot see (a browser, a bake, a dev server) still loads the
15
+ // machine, so past the cores the pool admits fewer slots in proportion to the
16
+ // 1 minute load, never fewer than half of them (admittedSlots). A slot already
17
+ // held is never taken back.
11
18
  //
12
19
  // The one constraint a reader breaks first: a process started BY a check
13
20
  // (SHIPKIT_SLOT_HELD=1 in its environment) takes no slot. It already runs on
@@ -25,6 +32,8 @@ import { PARALLEL_ENV, parallelCap, parallelCapInfo } from './parallel.ts'
25
32
  export const SLOTS_DIR_ENV = 'SHIPKIT_SLOTS_DIR'
26
33
  /** set for every process a check spawns: it runs on its parent's slot */
27
34
  export const SLOT_HELD_ENV = 'SHIPKIT_SLOT_HELD'
35
+ /** how many slots the check that spawned this process holds: the workers a suite run may start */
36
+ export const SLOT_CORES_ENV = 'SHIPKIT_SLOT_CORES'
28
37
 
29
38
  /** `load`: the reading that scales what the pool admits. Omitted: the whole
30
39
  * size, whatever the machine runs (a test's own pool) */
@@ -33,6 +42,8 @@ export type SlotPool = { dir: string; size: number; load?: () => MachineLoad }
33
42
  export type SlotHolder = { slot: number; pid: number; repo: string; check: string; since: number }
34
43
 
35
44
  const SLOT_POLL_MS = 25
45
+ /** a wait grows to this between two looks: sixty checks looking forty times a second burned a core to wait */
46
+ const SLOT_POLL_MAX_MS = 250
36
47
 
37
48
  export const poolDir = (): string => {
38
49
  const env = process.env[SLOTS_DIR_ENV]
@@ -80,10 +91,10 @@ export function machinePool(): SlotPool | null {
80
91
  }
81
92
 
82
93
  /** how many of `size` slots a machine at this load admits: all of them up to
83
- * a load of one per core, then size × cores / load, never below one. At 20
84
- * on 8 cores a pool of 8 admits 3, at 81 it admits 1 */
94
+ * a load of one per core, then size × cores / load, never below half. At 12
95
+ * on 8 cores a pool of 8 admits 5, from 16 it admits 4 */
85
96
  export const admittedSlots = (size: number, m: MachineLoad): number =>
86
- Math.max(1, Math.min(size, Math.floor((size * m.cores) / Math.max(m.cores, m.load1))))
97
+ Math.max(Math.ceil(size / 2), Math.min(size, Math.floor((size * m.cores) / Math.max(m.cores, m.load1))))
87
98
 
88
99
  const admitWords = (size: number, admitted: number, m: MachineLoad): string =>
89
100
  `the pool admits ${admitted} of its ${size} slots at load ${m.load1.toFixed(1)} on ${m.cores} cores`
@@ -131,6 +142,7 @@ export async function takeSlot(
131
142
  ): Promise<{ slot: number; release: () => void } | null> {
132
143
  mkdirSync(pool.dir, { recursive: true })
133
144
  let heard = false
145
+ let sleepMs = o.pollMs ?? SLOT_POLL_MS
134
146
  for (;;) {
135
147
  const m = pool.load?.() ?? null
136
148
  const admitted = m == null ? pool.size : admittedSlots(pool.size, m)
@@ -143,6 +155,31 @@ export async function takeSlot(
143
155
  heard = true
144
156
  o.onWait?.(poolOccupancy(pool).held, m != null && admitted < pool.size ? admitWords(pool.size, admitted, m) : `all ${pool.size} slots are held`)
145
157
  }
146
- await Bun.sleep(o.pollMs ?? SLOT_POLL_MS)
158
+ // an uneven sleep, so waiters that started together do not look together
159
+ await Bun.sleep(sleepMs * (0.5 + Math.random() / 2))
160
+ if (o.pollMs == null) sleepMs = Math.min(SLOT_POLL_MAX_MS, sleepMs * 1.5)
161
+ }
162
+ }
163
+
164
+ /** the line a check's process prints to say how many slots it uses from now on: its runner gives the rest back
165
+ * at once (`shipkit-slots: 1` once a suite run's parallel phase ended) */
166
+ export const SLOTS_LINE = /^shipkit-slots: (\d+)$/
167
+ export const slotsLine = (n: number): string => `shipkit-slots: ${n}`
168
+
169
+ /** up to `want` more slots, only the ones free right now, never a wait: what a
170
+ * check that holds one slot adds for the processes it runs at once. `keep(n)`
171
+ * gives back all but n of them */
172
+ export function takeFreeSlots(pool: SlotPool, who: { repo: string; check: string }, want: number): { count: number; keep: (n: number) => void; release: () => void } {
173
+ const leases: { release: () => void }[] = []
174
+ if (want > 0) {
175
+ mkdirSync(pool.dir, { recursive: true })
176
+ const m = pool.load?.() ?? null
177
+ const admitted = m == null ? pool.size : admittedSlots(pool.size, m)
178
+ for (let slot = 0; slot < admitted && leases.length < want; slot++) {
179
+ const lease = tryLease(join(pool.dir, `slot-${slot}`), who.check, { repo: who.repo, check: who.check })
180
+ if (lease != null) leases.push(lease)
181
+ }
147
182
  }
183
+ const keep = (n: number): void => { for (const l of leases.splice(Math.max(0, n))) l.release() }
184
+ return { count: leases.length, keep, release: () => keep(0) }
148
185
  }
@@ -22,6 +22,7 @@ import { isNamesInput } from '../ledger/git-key.ts'
22
22
  import { readTrace } from '../trace/read-trace.ts'
23
23
  import { dropTrace, learnBlind, traceUnavailable, tracedCommand } from '../trace/tracer.ts'
24
24
  import { spawnWithTimeout } from './spawn-timeout.ts'
25
+ import { SUITE_SELECT_ENV } from '../suite/reads-env.ts'
25
26
  import { gitBin } from './git-bin.ts'
26
27
  import { auditReportPath, auditedExtras, ignoredFor, pendingByTask, readAuditReport, type AuditReport, type AuditTask, type IgnoredInputs } from './audit-report.ts'
27
28
  import { addIgnoredInputs } from './ignored-block.ts'
@@ -137,7 +138,9 @@ export async function traceAudit(root: string, config: RepoConfig, o: { fresh?:
137
138
  const t = tracedCommand(u.body.cmd, cwd, env)
138
139
  if ('reason' in t) { tasks.push({ id: u.id, status: 'unaudited', why: t.reason, uncovered: [], propose: [] }); continue }
139
140
  try {
140
- await spawnWithTimeout(t.cmd, { timeoutMs: u.timeoutMs, env: { ...process.env, ...u.body.env, ...t.env }, cwd })
141
+ // every suite runs, with no selection: the selection's own walk of the tree (git status, a read of each
142
+ // dirty file) is no suite's read, and a suite it leaves out is a suite the audit never sees
143
+ await spawnWithTimeout(t.cmd, { timeoutMs: u.timeoutMs, env: { ...process.env, ...u.body.env, ...t.env, [SUITE_SELECT_ENV]: '0' }, cwd })
141
144
  const r = await readTrace(t.dir, root)
142
145
  if (r.reads == null) {
143
146
  const learned = r.blind.length > 0 ? learnBlind(r.blind) : null
package/src/drill/run.ts CHANGED
@@ -205,10 +205,13 @@ export function drillRun(lines: readonly string[], o: { transcript: string; root
205
205
  for (const e of eventsOf(entry)) {
206
206
  if (e.kind === 'use') {
207
207
  const shape = toolShape(e.name, e.detail)
208
- 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 }) })
208
+ 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 }), bg: false, bgEnd: null })
209
209
  } else if (e.kind === 'result') {
210
210
  const c = pending.get(e.id)
211
- if (c != null) Object.assign(c, { end: e.at, outcome: e.outcome, code: e.code, approval: e.perm === 'user', perm: e.perm })
211
+ if (c != null) Object.assign(c, { end: e.at, outcome: e.outcome, code: e.code, approval: e.perm === 'user', perm: e.perm, bg: e.bg })
212
+ } else if (e.kind === 'bgend') {
213
+ const c = pending.get(e.id)
214
+ if (c != null && (c.bgEnd == null || e.at < c.bgEnd)) c.bgEnd = e.at
212
215
  } else if (e.kind !== 'prompt') marks.push({ at: e.at, kind: e.kind })
213
216
  }
214
217
  }
@@ -300,6 +300,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
300
300
  web.navigationDelegate = self
301
301
  web.uiDelegate = self
302
302
  web.allowsBackForwardNavigationGestures = true
303
+ web.allowsMagnification = true
303
304
  web.pageZoom = zoom
304
305
  let frame = NSRect(x: 0, y: 0, width: 1400, height: 900)
305
306
  let win = NSWindow(contentRect: frame, styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)
@@ -4,7 +4,7 @@
4
4
  // machine resources).
5
5
  import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs'
6
6
  import { homedir } from 'os'
7
- import { join } from 'path'
7
+ import { dirname, join } from 'path'
8
8
  import { homeDir, pmLog } from './home-paths.ts'
9
9
 
10
10
  export const LABEL = 'com.shipkit.pm'
@@ -22,10 +22,18 @@ const esc = (s: string): string => s.replace(/&/g, '&amp;').replace(/</g, '&lt;'
22
22
  * every command, so any edit would restart pm. pm,
23
23
  * the daemon and the web each watch their own code and restart in place on
24
24
  * it (lib-watch.ts). PATH is the installing shell's, since launchd starts
25
- * with almost none and the daemon needs bun, git, ps, lsof and ssh.
25
+ * with almost none and the daemon needs bun, git, ps, lsof and ssh; agentPath
26
+ * adds the folders a shell with no rc file lacks (an `ssh mac cmd` install).
26
27
  * ProcessType Interactive: with none, launchd throttles the agent's disk
27
28
  * reads under load, every child inherits it, and a busy disk left the
28
29
  * daemon's boot reads minutes long while its port was already open */
30
+ /** the agent's PATH: the installing shell's, then bun's folder, ~/.local/bin (sk, the secret manager) and homebrew's,
31
+ * each once. An ssh command shell reads no rc file, and an agent installed from one ran with /usr/bin:/bin alone */
32
+ export function agentPath(shell: string | undefined, bun: string, home: string = homedir()): string {
33
+ const dirs = [...(shell ?? '').split(':'), dirname(bun), join(home, '.local/bin'), '/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin', '/usr/sbin', '/sbin']
34
+ return [...new Set(dirs.filter((d) => d !== ''))].join(':')
35
+ }
36
+
29
37
  export function renderPlist(o: { bun: string; cli: string; root: string; path: string; log: string }): string {
30
38
  const args = [o.bun, o.cli, 'pm'].map((a) => `\t\t<string>${esc(a)}</string>`).join('\n')
31
39
  return `<?xml version="1.0" encoding="UTF-8"?>
@@ -95,7 +103,7 @@ export async function installHome(o: { root: string; cli: string; print: (l: str
95
103
  mkdirSync(agentsDir(), { recursive: true })
96
104
  mkdirSync(homeDir(), { recursive: true })
97
105
  const log = pmLog()
98
- writeFileSync(file, renderPlist({ bun, cli: o.cli, root: o.root, path: process.env.PATH ?? '/usr/bin:/bin', log }))
106
+ writeFileSync(file, renderPlist({ bun, cli: o.cli, root: o.root, path: agentPath(process.env.PATH, bun), log }))
99
107
  // a loaded copy holds the old arguments: out first, then in
100
108
  await run(['bootout', `${domain()}/${LABEL}`])
101
109
  await run(['bootout', `${domain()}/${LEGACY_LABEL}`])
@@ -32,6 +32,7 @@ export const GIT_PAGE_MS = 7 * 24 * 3600_000
32
32
  import type { HouseView } from '../ledger/house-runs.ts'
33
33
  import { identitiesRoute } from '../identities/machine-route.ts'
34
34
  import { siteRoutes } from '../site/routes.ts'
35
+ import type { OtherMac } from './other-macs.ts'
35
36
 
36
37
  /** how often the daemon looks at every repo */
37
38
  export const TICK_MS = 2_000
@@ -48,6 +49,10 @@ export type HomeAnswer = {
48
49
  modernize: Record<string, ModernizeView>
49
50
  /** the daemon runs older code than its tree, and why (core/last-good.ts) */
50
51
  held?: string | null
52
+ /** the other Macs whose home answers on the tailnet (other-macs.ts) */
53
+ otherMacs?: OtherMac[]
54
+ /** this Mac's short tailnet name, shown beside them */
55
+ here?: string | null
51
56
  }
52
57
 
53
58
  export type HomeDeps = {
@@ -70,8 +75,10 @@ export type HomeDeps = {
70
75
  widgets?: Widgets
71
76
  /** brings a repo current (modernizeCmd); resolves to its exit code */
72
77
  modernize?: (repo: WiredRepo, log: string) => Promise<number>
73
- /** the machine's tailnet name, the house config's serve.publicHost: the one name besides localhost the web answers to */
74
- publicHost?: string
78
+ /** this Mac's tailnet name (machine-host.ts, serve.publicHost overriding it): the one name besides localhost the web answers to */
79
+ publicHost?: () => string | null
80
+ /** the other Macs' homes, the last answer at once */
81
+ otherMacs?: () => OtherMac[]
75
82
  }
76
83
 
77
84
  /** the sizes the app icon is drawn at: the phone's home screen, the manifest's two */
@@ -165,7 +172,7 @@ export function homeRoutes(d: HomeDeps) {
165
172
  const modernize: Record<string, ModernizeView> = {}
166
173
  for (const [k, m] of modernizing) modernize[k] = { status: m.status, code: m.code, tail: tailLines(m.log, 40) }
167
174
  const h = heldNow()
168
- return { version: LIB_VERSION, workers: d.hubs.views(repos), active: d.state.data.active, behind, modernize, held: h == null ? null : heldText(h) }
175
+ return { version: LIB_VERSION, workers: d.hubs.views(repos), active: d.state.data.active, behind, modernize, held: h == null ? null : heldText(h), otherMacs: d.otherMacs?.() ?? [], here: d.publicHost?.()?.split('.')[0] ?? null }
169
176
  }
170
177
 
171
178
  const icons = new Map<number, Promise<Uint8Array<ArrayBuffer> | null>>()
@@ -219,7 +226,7 @@ export function homeRoutes(d: HomeDeps) {
219
226
  // the web asks which page routes to serve: one per house repo
220
227
  if (path === '/api/home/repos.json') {
221
228
  if (repos.length === 0) await refresh()
222
- return Response.json({ repos: d.hubs.names(), hosts: d.publicHost == null ? [] : [d.publicHost] })
229
+ return Response.json({ repos: d.hubs.names(), hosts: [d.publicHost?.()].filter((h): h is string => h != null) })
223
230
  }
224
231
  // everything that waits on the owner in every repo, one list (inbox.ts)
225
232
  if (path === '/api/inbox') {
@@ -0,0 +1,65 @@
1
+ // this Mac's two names. `machineName` keys what one Mac writes beside another's in a store they share
2
+ // (a backup run, its block of a tracked page); `machinePublicHost` is the name its other devices reach it by.
3
+ // Two Macs never share a value of either, so neither is ever written in a repo both check out
4
+ // (tools/shipkit/home.md, Two machines). Both live in the machine db once read.
5
+ import { hostname } from 'os'
6
+ import { machineGet, machineSet } from '../core/machine-db.ts'
7
+
8
+ /** a host name without the `.local` of its Bonjour form */
9
+ export const hostLabel = (raw: string): string => raw.replace(/\.local$/i, '')
10
+
11
+ const NAME = 'machine-name'
12
+
13
+ /** this Mac's name, fixed the first time it is read (the system's host name then): macOS renames a host it meets
14
+ * twice on a network, and a block or a run keyed by a new name would orphan the old one */
15
+ export function machineName(): string {
16
+ const held = machineGet<string>(NAME)
17
+ if (held) return held
18
+ const name = hostLabel(hostname())
19
+ if (!/[A-Za-z0-9]/.test(name)) throw new Error(`this Mac's host name (${JSON.stringify(hostname())}) has no letter or digit to key its backups and blocks by: set one in System Settings, Sharing`)
20
+ machineSet(NAME, name)
21
+ return name
22
+ }
23
+
24
+ /** the tailscale cli: on PATH when its wrapper is installed, else inside the app */
25
+ export const TAILSCALE = ['tailscale', '/Applications/Tailscale.app/Contents/MacOS/Tailscale']
26
+
27
+ /** `Self.DNSName` of `tailscale status --json`, without its final dot; null when no tailscale answers */
28
+ export function readTailnetName(bins: string[] = TAILSCALE): string | null {
29
+ for (const bin of bins) {
30
+ try {
31
+ const p = Bun.spawnSync([bin, 'status', '--json'], { stdout: 'pipe', stderr: 'ignore', timeout: 3000 })
32
+ if (p.exitCode !== 0) continue
33
+ const name = (JSON.parse(p.stdout.toString()) as { Self?: { DNSName?: string } }).Self?.DNSName?.replace(/\.$/, '')
34
+ if (name) return name
35
+ } catch {
36
+ // a missing binary throws: the next one is tried
37
+ }
38
+ }
39
+ return null
40
+ }
41
+
42
+ const TAILNET = 'tailnet-name'
43
+ /** how long a process keeps "tailscale did not answer" before it asks again */
44
+ export const TAILNET_RETRY_MS = 60_000
45
+ let asked: { name: string | null; at: number } | undefined
46
+
47
+ /** this Mac's tailnet name: tailscale's answer, read once a process, else the last name it gave (kept in the machine
48
+ * db, since a device keeps its name while tailscale is stopped), asked again a minute later.
49
+ * `SHIPKIT_TAILNET_NAME` sets it, empty for none */
50
+ export function tailnetName(now: number = Date.now(), read: () => string | null = readTailnetName): string | null {
51
+ const env = process.env['SHIPKIT_TAILNET_NAME']
52
+ if (env !== undefined) return env === '' ? null : env
53
+ if (asked === undefined || (asked.name == null && now - asked.at >= TAILNET_RETRY_MS)) {
54
+ asked = { name: read(), at: now }
55
+ if (asked.name != null && machineGet<string>(TAILNET) !== asked.name) machineSet(TAILNET, asked.name)
56
+ }
57
+ return asked.name ?? machineGet<string>(TAILNET)
58
+ }
59
+
60
+ /** forget what this process asked, for a test */
61
+ export const forgetTailnetAnswer = (): void => void (asked = undefined)
62
+
63
+ /** the name a phone or another Mac uses for this one: the config's `serve.publicHost` (a single Mac's override), else
64
+ * its tailnet name */
65
+ export const machinePublicHost = (c: { serve?: { publicHost?: string } }): string | null => c.serve?.publicHost ?? tailnetName()