rvlib-shipkit 2.23.0 → 2.25.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 (150) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/package.json +1 -1
  3. package/src/agent-time/live.ts +153 -0
  4. package/src/agent-time/render.ts +28 -14
  5. package/src/agent-time/report.ts +46 -25
  6. package/src/agent-time/store.ts +30 -10
  7. package/src/agent-time/timeline.ts +43 -15
  8. package/src/annex/offload.ts +16 -7
  9. package/src/asks/asks-queue.ts +32 -11
  10. package/src/check.ts +3 -1
  11. package/src/checks/SK004-gitignore-policy.check.ts +32 -11
  12. package/src/checks/SK027-agent-wiki-links.check.ts +1 -1
  13. package/src/checks/SK033-global-contribution.check.ts +1 -1
  14. package/src/checks/SK036-draft-media-size.check.ts +1 -1
  15. package/src/checks/SK040-release-words.check.ts +1 -1
  16. package/src/checks/SK042-post-kinds.check.ts +1 -1
  17. package/src/checks/SK044-behind-upstream.check.ts +38 -0
  18. package/src/cli/cmd_Annex.ts +12 -7
  19. package/src/cli/cmd_Asks.ts +2 -0
  20. package/src/cli/cmd_Assets.ts +5 -5
  21. package/src/cli/cmd_Backup.ts +16 -8
  22. package/src/cli/cmd_Bump.ts +1 -0
  23. package/src/cli/cmd_Capacity.ts +30 -0
  24. package/src/cli/cmd_Check.ts +1 -0
  25. package/src/cli/cmd_Checks.ts +13 -1
  26. package/src/cli/cmd_Ci.ts +3 -2
  27. package/src/cli/cmd_Commands.ts +61 -16
  28. package/src/cli/cmd_ConfigKeys.ts +17 -0
  29. package/src/cli/cmd_Home.ts +1 -30
  30. package/src/cli/cmd_Hooks.ts +1 -0
  31. package/src/cli/cmd_Keys.ts +4 -1
  32. package/src/cli/cmd_Lanes.ts +35 -0
  33. package/src/cli/cmd_Mv.ts +7 -7
  34. package/src/cli/cmd_Rec.ts +22 -7
  35. package/src/cli/cmd_Reflect.ts +1 -0
  36. package/src/cli/cmd_Releases.ts +1 -0
  37. package/src/cli/cmd_Review.ts +200 -49
  38. package/src/cli/cmd_Secret.ts +41 -2
  39. package/src/cli/cmd_Shot.ts +16 -4
  40. package/src/cli/cmd_Status.ts +7 -5
  41. package/src/cli/cmd_Time.ts +13 -5
  42. package/src/cli/cmd_Tmp.ts +82 -0
  43. package/src/cli/cmd_Veille.ts +10 -6
  44. package/src/cli/cmd_Wiki.ts +1 -0
  45. package/src/cli/family-help.ts +136 -0
  46. package/src/cli/family-pages.ts +0 -19
  47. package/src/cli/kit/calls.ts +35 -0
  48. package/src/cli/kit/project-cli.ts +2 -12
  49. package/src/cli/registry.ts +52 -7
  50. package/src/cli.ts +8 -4
  51. package/src/collections/pings.ts +1 -1
  52. package/src/core/capacity.ts +127 -0
  53. package/src/core/check-runner.ts +91 -16
  54. package/src/core/floor-resolve.ts +6 -2
  55. package/src/core/floor.ts +6 -2
  56. package/src/core/history-files.ts +18 -0
  57. package/src/core/jobs.ts +35 -16
  58. package/src/core/layout.ts +2 -2
  59. package/src/core/motherhome.ts +67 -9
  60. package/src/core/nearest.ts +16 -0
  61. package/src/core/remove-tree.ts +19 -0
  62. package/src/core/runs.ts +12 -3
  63. package/src/core/slots.ts +49 -12
  64. package/src/core/throwaway-worktree.ts +22 -4
  65. package/src/core/trace-audit.ts +21 -5
  66. package/src/drill/run.ts +5 -2
  67. package/src/home/daemon-jobs.ts +41 -4
  68. package/src/home/gui-app/ShipkitGui.swift +1 -0
  69. package/src/home/home-launchd.ts +11 -3
  70. package/src/home/home-routes.ts +11 -4
  71. package/src/home/machine-host.ts +65 -0
  72. package/src/home/machine-stores.ts +19 -17
  73. package/src/home/machine-temp.ts +485 -0
  74. package/src/home/other-macs.ts +74 -0
  75. package/src/home/run-daemon.ts +10 -2
  76. package/src/home/serve-web.ts +2 -2
  77. package/src/home/via-hub.ts +6 -1
  78. package/src/init-repo.ts +7 -3
  79. package/src/ledger/gate-checks.ts +3 -2
  80. package/src/ledger/git-key.ts +25 -4
  81. package/src/ledger/git-scan.ts +10 -0
  82. package/src/ledger/ledger.ts +6 -0
  83. package/src/ledger/store.ts +6 -0
  84. package/src/media-store/backup/daemon.ts +92 -20
  85. package/src/media-store/backup/keys.ts +21 -6
  86. package/src/media-store/backup/manifest.ts +52 -11
  87. package/src/media-store/backup/restore.ts +17 -10
  88. package/src/media-store/backup/run.ts +26 -17
  89. package/src/media-store/backup/sources.ts +168 -22
  90. package/src/media-store/backup/watch.ts +106 -0
  91. package/src/media-store/daemon.ts +36 -8
  92. package/src/media-store/hand.ts +3 -1
  93. package/src/mv/mv-md.ts +167 -56
  94. package/src/pb/run-pb.ts +2 -10
  95. package/src/plan/repo-source.ts +25 -14
  96. package/src/recordings/model.ts +1 -1
  97. package/src/reflect/transcript.ts +56 -11
  98. package/src/release/run-bump.ts +3 -2
  99. package/src/release/run-release.ts +12 -4
  100. package/src/releases/from-card.ts +45 -3
  101. package/src/releases/model.ts +6 -0
  102. package/src/releases/store.ts +8 -1
  103. package/src/repo-config.ts +5 -3
  104. package/src/review/cells.ts +26 -4
  105. package/src/review/format.ts +34 -10
  106. package/src/review/media-kind.ts +14 -11
  107. package/src/review/media-read.ts +6 -5
  108. package/src/review/model.ts +85 -4
  109. package/src/review/paste.ts +2 -1
  110. package/src/review/previews.ts +123 -36
  111. package/src/review/routes.ts +29 -18
  112. package/src/review/store.ts +89 -19
  113. package/src/review/threads.ts +7 -5
  114. package/src/review/trailer-model.ts +2 -2
  115. package/src/secrets/copy.ts +110 -0
  116. package/src/secrets/list.ts +17 -7
  117. package/src/serve/hub-app/home-strip.css +5 -0
  118. package/src/serve/hub-app/home-strip.tsx +18 -0
  119. package/src/serve/hub-app/hub-app.tsx +2 -1
  120. package/src/serve/hub-app/hub.css +14 -0
  121. package/src/serve/hub-app/inbox.css +1 -0
  122. package/src/serve/hub-app/pull-refresh.tsx +88 -0
  123. package/src/serve/hub-app/review/review-cells.tsx +52 -13
  124. package/src/serve/hub-app/review/review-list.tsx +6 -1
  125. package/src/serve/hub-app/review/review-st.ts +6 -5
  126. package/src/serve/hub-app/review/review-thread.tsx +3 -1
  127. package/src/serve/hub-app/review/review-views.tsx +18 -11
  128. package/src/serve/hub-app/review/thread-st.ts +82 -14
  129. package/src/serve/hub-app/review.css +15 -2
  130. package/src/serve/hub-runtime.ts +2 -1
  131. package/src/serve/run-serve.ts +4 -2
  132. package/src/serve/serve-hub.ts +9 -2
  133. package/src/shot/client.ts +4 -2
  134. package/src/shot/serve-shot.ts +71 -2
  135. package/src/shot/shooter.ts +65 -11
  136. package/src/shot/shot-ask.ts +32 -9
  137. package/src/suite/child-tools.ts +45 -0
  138. package/src/suite/judge-suites.ts +10 -22
  139. package/src/suite/select.ts +95 -9
  140. package/src/suite/suite-cli.ts +38 -14
  141. package/src/suite/suite-cores.ts +68 -0
  142. package/src/suite/suite-reads-preload.ts +8 -6
  143. package/src/suite/test-units.ts +31 -12
  144. package/src/trailer/graph.ts +2 -1
  145. package/src/ts/config.ts +21 -0
  146. package/src/ts/rename.ts +37 -13
  147. package/src/ts/workspaces.ts +45 -0
  148. package/src/wiki/run-wiki.ts +7 -2
  149. package/src/wiki/scan-md.ts +2 -1
  150. package/src/home/claude-temp.ts +0 -139
@@ -0,0 +1,127 @@
1
+ // HOW MANY LANES A REPO RUNS NOW, read from the machine: its cores, its
2
+ // 1 minute load and the agents writing right now (every account, every repo).
3
+ // No fixed cap: each repo adjusts its own count, and the answer moves with
4
+ // what the machine runs.
5
+ //
6
+ // The one constraint a reader breaks first: the answer is never zero. One
7
+ // lane always runs, a maximum the owner gave replaces the number, and only a
8
+ // dying machine (a load of twice its cores) holds a lane back. A tool that
9
+ // said WAIT at a load of 9 on 8 cores stopped five lanes the owner had
10
+ // allowed, for 25 minutes.
11
+ import { availableParallelism, loadavg } from 'os'
12
+ import { dirname } from 'path'
13
+ import { liveRow, oneRowAnAgent } from '../agent-time/live.ts'
14
+ import { listTranscripts, type TranscriptFile } from '../agent-time/store.ts'
15
+ import { gitBin } from './git-bin.ts'
16
+ import { gitRoot } from './git-root.ts'
17
+
18
+ /** an agent is live when its transcript was written this recently */
19
+ export const LIVE_WINDOW_MS = 3 * 60 * 1000
20
+ /** the machine is dying at this many times its cores of load: no lane starts, a maximum included */
21
+ export const DYING_LOAD = 2
22
+
23
+ export type LiveAgents = { sessions: number; lanes: number; byProject: [project: string, agents: number][]; /** agents live in the window whose turn ended: they hold no core */ idle?: number }
24
+
25
+ /** the sessions and sub-agents whose transcript moved inside the window */
26
+ export function liveAgents(files: readonly TranscriptFile[], now: number, windowMs = LIVE_WINDOW_MS): LiveAgents {
27
+ const live = files.filter((f) => now - f.mtime <= windowMs)
28
+ const by = new Map<string, number>()
29
+ for (const f of live) by.set(f.project, (by.get(f.project) ?? 0) + 1)
30
+ return {
31
+ sessions: live.filter((f) => f.agent === '').length,
32
+ lanes: live.filter((f) => f.agent !== '').length,
33
+ byProject: [...by].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)),
34
+ }
35
+ }
36
+
37
+ /** the transcript folder name of a work tree: its path with every character that is no letter or digit as a dash */
38
+ export const projectSlug = (top: string): string => top.replace(/[^a-zA-Z0-9]/g, '-')
39
+
40
+ /** the live lanes of one repo: the transcript folders of its work trees, by their exact names. A name that only
41
+ * starts the same is another repo */
42
+ export function lanesOf(files: readonly TranscriptFile[], slugs: ReadonlySet<string>, now: number, windowMs = LIVE_WINDOW_MS): number {
43
+ return files.filter((f) => f.agent !== '' && now - f.mtime <= windowMs && slugs.has(f.project)).length
44
+ }
45
+
46
+ /** every work tree of the repo `top` is in, as git lists them: the main one and each linked one */
47
+ export function workTrees(top: string): string[] {
48
+ try {
49
+ const p = Bun.spawnSync([gitBin(), 'worktree', 'list', '--porcelain'], { cwd: top, stdout: 'pipe', stderr: 'ignore' })
50
+ const paths = p.stdout.toString().split('\n').filter((l) => l.startsWith('worktree ')).map((l) => l.slice('worktree '.length))
51
+ return paths.length > 0 ? paths : [top]
52
+ } catch {
53
+ return [top]
54
+ }
55
+ }
56
+
57
+ /** the kernel says memory is critical (darwin, level 4): a machine can die of memory with idle cores */
58
+ export function memoryCritical(): boolean {
59
+ if (process.platform !== 'darwin') return false
60
+ try {
61
+ return Number(Bun.spawnSync(['sysctl', '-n', 'kern.memorystatus_vm_pressure_level'], { stdout: 'pipe', stderr: 'ignore' }).stdout.toString().trim()) >= 4
62
+ } catch {
63
+ return false
64
+ }
65
+ }
66
+
67
+ export type Capacity = {
68
+ cores: number
69
+ /** the 1 minute load: it follows the machine within a minute, where the 5 minute one held a lane back long after the others had ended */
70
+ load: number
71
+ /** the agents live on the machine, sessions and lanes: each counts for at least one core, whatever the load says */
72
+ agents: number
73
+ /** the lanes this repo has live now */
74
+ mine: number
75
+ /** the load is at twice the cores or more, or memory is critical: nothing starts */
76
+ dying: boolean
77
+ /** the lanes this repo runs now: its live ones plus one a free core, never under one, the maximum when one is given */
78
+ lanes: number
79
+ /** how many it can start now */
80
+ more: number
81
+ /** the maximum the owner gave, when the caller passed one */
82
+ max: number | null
83
+ }
84
+
85
+ export function capacityOf(p: { cores: number; load1: number; agents: number; mine: number; max?: number | null; memoryCritical?: boolean }): Capacity {
86
+ const dying = p.load1 >= p.cores * DYING_LOAD || p.memoryCritical === true
87
+ const max = p.max ?? null
88
+ // a lane in its model turn loads nothing here, so the load alone would hand out the same free cores at every
89
+ // ask: each live agent holds a core, and the load counts only where it is the larger
90
+ const free = Math.floor(p.cores - Math.max(p.load1, p.agents))
91
+ const lanes = max ?? Math.max(1, p.mine + free)
92
+ return { cores: p.cores, load: p.load1, agents: p.agents, mine: p.mine, dying, lanes, more: dying ? 0 : Math.max(0, lanes - p.mine), max }
93
+ }
94
+
95
+ /** the machine read now, for the repo `cwd` stands in */
96
+ export function readCapacity(cwd: string, max: number | null = null, now = Date.now()): { capacity: Capacity; live: LiveAgents; repo: string } {
97
+ // an agent whose turn ended holds no core: a lane that handed back, a session that waits for its user
98
+ const recent = oneRowAnAgent(listTranscripts().filter((f) => now - f.mtime <= LIVE_WINDOW_MS))
99
+ const files = recent.filter((f) => liveRow(f, { calls: false }).state.kind !== 'ended')
100
+ const root = gitRoot(cwd)
101
+ // a linked worktree counts with its repo: the common dir's parent is the main work tree
102
+ const top = root == null ? cwd : dirname(root.commonDir)
103
+ const live: LiveAgents = { ...liveAgents(files, now), idle: recent.length - files.length }
104
+ const [load1 = 0] = loadavg()
105
+ const mine = lanesOf(files, new Set(workTrees(top).map(projectSlug)), now)
106
+ return { capacity: capacityOf({ cores: availableParallelism(), load1, agents: live.sessions + live.lanes, mine, max, memoryCritical: memoryCritical() }), live, repo: top.split('/').at(-1) ?? top }
107
+ }
108
+
109
+ const one = (n: number): string => n.toFixed(1)
110
+ const plural = (n: number, word: string): string => `${n} ${word}${n === 1 ? '' : 's'}`
111
+
112
+ /** the answer in three lines: the machine, this repo, what to do */
113
+ export function capacityLines(c: Capacity, live: LiveAgents, repo: string): string[] {
114
+ const who = live.byProject.slice(0, 5).map(([p, n]) => `${p.replace(/^.*-dev-/, '')} ${n}`).join(', ')
115
+ const verdict = c.dying
116
+ ? `STOP: the machine is dying: ${c.load >= c.cores * DYING_LOAD ? `load ${one(c.load)} on ${c.cores} cores, ${DYING_LOAD} times its cores or more` : 'its memory is critical'}. Start no lane${c.max != null ? `, the maximum of ${c.max} included` : ''}: run the next step yourself, and ask again before each next step`
117
+ : c.max != null
118
+ ? `ok: run up to ${plural(c.lanes, 'lane')}, the maximum given: start ${c.more} more`
119
+ : c.more > 0
120
+ ? `ok: run up to ${plural(c.lanes, 'lane')} now: start ${c.more} more (${c.cores} cores, ${c.agents} held by live agents, load ${one(c.load)})`
121
+ : `ok: keep ${plural(c.mine, 'lane')} and start none now: ${c.load >= c.cores + 0.05 ? `the load is ${one(c.load - c.cores)} over the ${c.cores} cores` : c.agents >= c.cores ? `${c.agents} live agents hold the ${c.cores} cores` : `the load is at the ${c.cores} cores`}. Ask again when a lane ends`
122
+ return [
123
+ `machine: ${c.cores} cores, load ${one(c.load)} (1 min), ${plural(live.sessions + live.lanes, 'agent')} at work (${plural(live.sessions, 'session')}, ${plural(live.lanes, 'lane')})${who === '' ? '' : `: ${who}`}${(live.idle ?? 0) > 0 ? `; ${live.idle} more ${live.idle === 1 ? 'waits' : 'wait'}, turn ended, and ${live.idle === 1 ? 'holds' : 'hold'} no core` : ''}`,
124
+ `${repo}: ${plural(c.mine, 'lane')} at work`,
125
+ verdict,
126
+ ]
127
+ }
@@ -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'
@@ -49,6 +50,7 @@ import { liveStateOf } from '../ledger/live-runs.ts'
49
50
  import { CHECK_ID_ENV } from '../ledger/suite-log.ts'
50
51
  import { rememberWorld, replayWorld, worldKeyOf, type WorldCache } from '../ledger/world-cache.ts'
51
52
  import { extractProblems } from '../problems/extract.ts'
53
+ import { nearest } from './nearest.ts'
52
54
 
53
55
  /** the first line of a check that ran in this run, stamped with its cost. A
54
56
  * world answer carries its keep in a stamp already, so the cost joins it */
@@ -70,6 +72,9 @@ const MAX_EXTRA = 20
70
72
  * record show more checks at once than ever ran */
71
73
  const clock = (): number => Math.floor(performance.timeOrigin + performance.now())
72
74
 
75
+ /** a check whose kept runs all ended under this takes no machine slot */
76
+ export const SHORT_CHECK_MS = 2000
77
+
73
78
  export type CheckBody = Pick<CheckDef, 'run' | 'cmd' | 'env' | 'cwd'>
74
79
 
75
80
  /** one check, resolved: everything the runner needs and nothing it does not.
@@ -180,6 +185,8 @@ export type RunChecksOpts = {
180
185
  childEnv?: Record<string, string | undefined>
181
186
  bail?: boolean
182
187
  maxParallel?: number
188
+ /** what a check's newest kept runs took, newest first: the ledger's by default. A scheduling hint, never a verdict */
189
+ lastRuns?: (id: string) => number[]
183
190
  /** the machine pool every measured check takes a slot from (core/slots.ts).
184
191
  * Omitted: this machine's pool. null: no pool, the in process cap alone */
185
192
  pool?: SlotPool | null
@@ -305,7 +312,10 @@ export function selectChecks(o: Pick<RunChecksOpts, 'checks' | 'audience' | 'ful
305
312
  const onlyIds: string[] = []
306
313
  for (const [raw, groups] of [...(o.onlyIds ?? []).map((r) => [r, true] as const), ...(o.withIds ?? []).map((r) => [r, false] as const)]) {
307
314
  const ids = resolve(raw, groups)
308
- if (ids == null) errors.push(`unknown check id${groups ? ' or group' : ''} '${raw}'`)
315
+ if (ids == null) {
316
+ const close = nearest(raw, o.checks.map((u) => u.id))
317
+ errors.push(`unknown check id${groups ? ' or group' : ''} '${raw}': ${close.length > 0 ? `did you mean ${close.join(', ')} ?` : '`shipkit checks` lists every id'}`)
318
+ }
309
319
  else for (const id of ids) { named.add(id); if (groups) onlyIds.push(id) }
310
320
  }
311
321
  // a dep cycle must die loud at select time, not hang the loop
@@ -438,6 +448,8 @@ let runSeq = 0
438
448
 
439
449
  type Live = RunnableCheck & CheckResult & {
440
450
  startedAt: number
451
+ /** the machine slots its body runs on: one, more for a suite run's workers */
452
+ cores: number
441
453
  /** when its body stopped, stamped BEFORE its slot goes back: a row must
442
454
  * never outlast the slot, or another process starting on it overlaps */
443
455
  endedAt: number
@@ -508,7 +520,7 @@ export async function runChecks(o: RunChecksOpts): Promise<RunChecksSummary> {
508
520
  const runDir = openRunDir(o.logDir)
509
521
  const checks: Live[] = sel.selected.map((u) => ({
510
522
  ...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: [],
523
+ 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
524
  logPath: u.body.cmd != null ? join(runDir, `${u.id.replace(/[^a-zA-Z0-9-]/g, '_')}.log`) : null,
513
525
  }))
514
526
  const selectedIds = new Set(checks.map((u) => u.id))
@@ -519,6 +531,44 @@ export async function runChecks(o: RunChecksOpts): Promise<RunChecksSummary> {
519
531
  const cap = o.maxParallel ?? parallelCap()
520
532
  const pool = o.pool === undefined ? machinePool() : o.pool
521
533
  let slotWaitSaid = false
534
+ // what this check's newest kept runs took: the hint that tells a short check from a long one. No verdict reads it
535
+ const lastRunsMemo = new Map<string, number[]>()
536
+ const lastRuns = (id: string): number[] => {
537
+ let v = lastRunsMemo.get(id)
538
+ if (v == null) { try { v = o.lastRuns?.(id) ?? o.ledger?.lastRuns(id) ?? [] } catch { v = [] } lastRunsMemo.set(id, v) }
539
+ return v
540
+ }
541
+ const wantsMemo = new Map<string, number>()
542
+ const slotsOf = (u: Live): number => {
543
+ let v = wantsMemo.get(u.id)
544
+ if (v == null) { v = slotsWanted(u.body.cmd, u.body.cwd ?? o.root); wantsMemo.set(u.id, v) }
545
+ return v
546
+ }
547
+ /** a check whose kept runs were all short takes no slot: it costs less than its own wait, and a one second
548
+ * lint waited minutes behind another repo's suite. A suite check whose selection reached nothing is one too */
549
+ const isShort = (u: Live): boolean => {
550
+ const runs = lastRuns(u.id)
551
+ return runs.length > 0 && Math.max(...runs) < SHORT_CHECK_MS
552
+ }
553
+ /** the longest check starts first, so it never sets the gate's time from the back of the queue. A check with no
554
+ * kept run (a new one, or one no key describes) counts as the longest: nobody knows what it costs */
555
+ const lengthOf = (id: string): number => { const runs = lastRuns(id); return runs.length === 0 ? Infinity : Math.max(...runs) }
556
+ const longestFirst = (a: string, b: string): number => { const [x, y] = [lengthOf(a), lengthOf(b)]; return x === y ? 0 : y > x ? 1 : -1 }
557
+ // the free slots a suite check holds beside its own, by check id: its process says when it needs fewer
558
+ const extraSlots = new Map<string, { keep: (n: number) => void }>()
559
+ let slotTurn: Promise<unknown> = Promise.resolve()
560
+ const inTurn = <T>(fn: () => Promise<T>): Promise<T> => {
561
+ const p = slotTurn.then(fn, fn)
562
+ slotTurn = p.catch(() => {})
563
+ return p
564
+ }
565
+ // the wall this run spent behind the pool, split by whether anything of its own ran meanwhile
566
+ const wait = { waiting: 0, measuring: 0, at: 0, idleMs: 0, queuedMs: 0, behind: '' }
567
+ const waitMark = (): void => {
568
+ const now = clock()
569
+ if (wait.at > 0 && wait.waiting > 0) { if (wait.measuring === 0) wait.idleMs += now - wait.at; else wait.queuedMs += now - wait.at }
570
+ wait.at = now
571
+ }
522
572
  let interrupted = false
523
573
  let bailed = false
524
574
  const procs = new Map<string, ReturnType<typeof Bun.spawn>>()
@@ -668,7 +718,7 @@ export async function runChecks(o: RunChecksOpts): Promise<RunChecksSummary> {
668
718
  const r = await spawnWithTimeout(cmd, {
669
719
  timeoutMs: u.timeoutMs,
670
720
  // 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 },
721
+ env: { ...process.env, ...o.childEnv, ...u.body.env, [SLOT_HELD_ENV]: '1', [SLOT_CORES_ENV]: String(u.cores), [CHECK_ID_ENV]: u.id },
672
722
  cwd: u.body.cwd ?? o.root,
673
723
  onSpawn: (proc) => {
674
724
  try { fd = openSync(u.logPath!, 'a') } catch (e) { logProblem = (e as Error).message }
@@ -678,6 +728,8 @@ export async function runChecks(o: RunChecksOpts): Promise<RunChecksSummary> {
678
728
  logWrite(text)
679
729
  for (const raw of text.split(/\r?\n/)) {
680
730
  const s = stripAnsi(raw).trim()
731
+ const slots = SLOTS_LINE.exec(s)
732
+ if (slots != null) { extraSlots.get(u.id)?.keep(Math.max(0, Number(slots[1]) - 1)); continue }
681
733
  if (s !== '') u.lastLine = s.slice(0, 200)
682
734
  }
683
735
  },
@@ -816,19 +868,33 @@ export async function runChecks(o: RunChecksOpts): Promise<RunChecksSummary> {
816
868
  const measureAndKeep = async (u: Live): Promise<void> => {
817
869
  // a machine slot for the body, and only the body: a replay or an
818
870
  // 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
- },
871
+ const who = { repo: o.config.name, check: u.id }
872
+ const queue = pool != null && !isShort(u)
873
+ if (queue) { waitMark(); wait.waiting++ }
874
+ // one check of this run asks the pool at a time, in the order they started (the longest first), and a suite
875
+ // run adds its free slots in the same turn: a freed slot never goes to a shorter check of the same run
876
+ const got = !queue ? null : await inTurn(async () => {
877
+ const slot = await takeSlot(pool!, who, {
878
+ abort: () => interrupted || bailed,
879
+ onWait: (held, why) => {
880
+ const holders = held.filter((h) => h.pid !== process.pid).slice(0, 3).map((h) => `${h.repo}/${h.check} pid ${h.pid}`).join(', ')
881
+ if (wait.behind === '' && holders !== '') wait.behind = holders
882
+ if (slotWaitSaid) return
883
+ slotWaitSaid = true
884
+ const shown = held.slice(0, 3).map((h) => `${h.repo}/${h.check} pid ${h.pid}`).join(', ')
885
+ emit({ kind: 'ok', text: `waiting for a machine slot: ${held.length} held, ${why}${shown === '' ? '' : ` (${shown}${held.length > 3 ? ', …' : ''})`}` })
886
+ },
887
+ })
888
+ return slot == null ? null : { slot, more: takeFreeSlots(pool!, who, slotsOf(u) - 1) }
827
889
  })
828
- if (pool != null && slot == null) { u.status = 'skip'; u.note = bailed ? 'bailed' : 'interrupted'; u.lines = []; u.unmeasured = true; return }
890
+ if (queue) { waitMark(); wait.waiting-- }
891
+ if (queue && got == null) { u.status = 'skip'; u.note = bailed ? 'bailed' : 'interrupted'; u.lines = []; u.unmeasured = true; return }
892
+ u.cores = 1 + (got?.more.count ?? 0)
829
893
  // its time starts when it runs, so a row never counts the queue
830
894
  u.startedAt = clock()
831
- try { await measure(u) } finally { u.endedAt = clock(); slot?.release() }
895
+ waitMark(); wait.measuring++
896
+ if (got != null) extraSlots.set(u.id, got.more)
897
+ try { await measure(u) } finally { u.endedAt = clock(); waitMark(); wait.measuring--; extraSlots.delete(u.id); got?.more.release(); got?.slot.release() }
832
898
  // the headline is built BEFORE anything is remembered: a check
833
899
  // whose result is stored empty replays as a line nobody can tell
834
900
  // from a measurement
@@ -897,8 +963,10 @@ export async function runChecks(o: RunChecksOpts): Promise<RunChecksSummary> {
897
963
  break
898
964
  }
899
965
  let started = false
900
- for (const id of [...queued]) {
901
- if (running.size >= cap) break
966
+ for (const id of [...queued].sort(longestFirst)) {
967
+ // a check waiting for a machine slot runs nothing, so it holds no place: `cap` long checks waiting
968
+ // on a full pool kept a short check, which needs no slot, from starting
969
+ if (running.size - wait.waiting >= cap) break
902
970
  const u = byId.get(id)!
903
971
  const st = depState(u)
904
972
  if (st === 'dead') { queued.delete(id); finish(u); started = true }
@@ -924,6 +992,13 @@ export async function runChecks(o: RunChecksOpts): Promise<RunChecksSummary> {
924
992
  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
993
  const order = new Map(o.checks.map((u, i) => [u.id, i]))
926
994
  results.sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0))
995
+ // the wait is said apart from the work, so a reader names the right cause of a long run
996
+ waitMark()
997
+ if (wait.idleMs + wait.queuedMs >= 1000) {
998
+ const secs = (ms: number): string => `${(ms / 1000).toFixed(1)}s`
999
+ 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`] : [])]
1000
+ emit({ kind: 'ok', text: `waited for a machine slot: ${parts.join(', ')}${wait.behind === '' ? '' : ` (first held by ${wait.behind})`}. The checks' own times are above` })
1001
+ }
927
1002
  const blocked = results.filter((r) => r.status === 'fail' && !r.advisory)
928
1003
  const skipped = results.filter((r) => r.status === 'skip' && r.note !== '' && r.note !== 'off')
929
1004
  if (blocked.length > 0) emit({ kind: 'fail', text: `${blocked.length}/${results.length} failed: ${blocked.map((r) => r.id).join(', ')}` })
@@ -19,6 +19,7 @@ import { rawName, slotBody } from './canonical-scripts.ts'
19
19
  import type { CheckCtx } from './check-ctx.ts'
20
20
  import { checkUnitReader, type UnitReader } from '../release/unit-resolve.ts'
21
21
  import { parseJsonc } from '../ts/jsonc.ts'
22
+ import { workspacePackagesOf } from '../ts/workspaces.ts'
22
23
  import { gateCheckCmd, tscFallbackNote } from '../ts/gate-typecheck.ts'
23
24
  import { parseBunTestScript, suiteFlags } from '../suite/judge-suites.ts'
24
25
  import { declaredTestUnits, siblingUnits, testCheckId, unitIgnores, unitTestBody, unitTsconfig, type TestUnitDecl } from '../suite/test-units.ts'
@@ -31,7 +32,9 @@ import { normalizeVendored } from './vendored.ts'
31
32
  /** how the floor reads the repo, by repo-relative path, plus the lookups
32
33
  * outside it: a binary on PATH, and the bun version (default: the bun
33
34
  * running shipkit) */
34
- export type FloorReader = UnitReader & { which: (bin: string) => string | null; bunVersion?: string }
35
+ /** `subdirs`: the dir names directly inside a repo-relative dir ('' is the root),
36
+ * to expand the workspace globs */
37
+ export type FloorReader = UnitReader & { which: (bin: string) => string | null; subdirs: (rel: string) => string[]; bunVersion?: string }
35
38
 
36
39
  /** the check context as a floor reader. A PATH lookup is not a repo read, so
37
40
  * it marks the answer untracked, and only the tsc fallback of a bun with no
@@ -39,6 +42,7 @@ export type FloorReader = UnitReader & { which: (bin: string) => string | null;
39
42
  export function checkFloorReader(c: CheckCtx): FloorReader {
40
43
  return {
41
44
  ...checkUnitReader(c),
45
+ subdirs: (rel) => c.entries(rel).filter((e) => e.kind === 'dir').map((e) => e.name),
42
46
  which: (bin) => {
43
47
  c.untrack(`looked ${bin} up on PATH, outside the repo`)
44
48
  return Bun.which(bin)
@@ -285,7 +289,7 @@ export function resolveFloor(c: RepoConfig, root: string, io: FloorReader): Floo
285
289
  if (typeof b === 'string') unfilled.push({ id, reason: slot.kind === 'routed-empty' ? `script '${id}' routes to shipkit and there is no '${rawName(id)}' body to run` : b })
286
290
  else { tasks.push(decorate(b.task)); sources[id] = b.source }
287
291
  }
288
- const siblings = siblingUnits(subs, io.text)
292
+ const siblings = siblingUnits(subs, io.text, workspacePackagesOf(io.text, io.subdirs, (c.vendored ?? []).map(normalizeVendored)))
289
293
  for (const t of unitTestTasks(root, io, subs, siblings, notes, unfilled)) { tasks.push(t); sources[t.id] = 'unit' }
290
294
  for (const t of unitTypecheckTasks(root, io, subs, siblings, notes, unfilled)) { tasks.push(t); sources[t.id] = 'unit' }
291
295
  return { tasks, disabled, unfilled, sources, notes }
package/src/core/floor.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // the floor as read from the disk: plain fs behind core/floor-resolve.ts, which
2
2
  // owns the resolution. Every caller outside a check resolves here; a check
3
3
  // resolves through its context (checkFloorReader) so it stays keyed on its reads.
4
- import { existsSync } from 'fs'
4
+ import { existsSync, readdirSync } from 'fs'
5
5
  import { join } from 'path'
6
6
  import { gitBin } from './git-bin.ts'
7
7
  import { fsUnitReader } from '../release/units.ts'
@@ -11,7 +11,11 @@ import type { RepoConfig } from '../repo-config.ts'
11
11
 
12
12
  export * from './floor-resolve.ts'
13
13
 
14
- export const fsFloorReader = (root: string): FloorReader => ({ ...fsUnitReader(root), which: (bin) => Bun.which(bin) })
14
+ export const fsFloorReader = (root: string): FloorReader => ({
15
+ ...fsUnitReader(root),
16
+ subdirs: (rel) => { try { return readdirSync(join(root, rel), { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name) } catch { return [] } },
17
+ which: (bin) => Bun.which(bin),
18
+ })
15
19
 
16
20
  export function resolveFloor(c: RepoConfig, root: string, io: FloorReader = fsFloorReader(root)): FloorResolution {
17
21
  return resolveWith(c, root, io)
@@ -0,0 +1,18 @@
1
+ // the files that record what was true when they were written: a plan, a
2
+ // changelog, a journal. A rename leaves them as written, and a link in one
3
+ // may name a path that is gone, as long as git once held it.
4
+ import { gitBin } from './git-bin.ts'
5
+
6
+ /** a repo relative path of a plan, a changelog or a journal: a file or a folder named so */
7
+ export const isHistoryFile = (rel: string): boolean =>
8
+ rel.startsWith('.shipkit/plans/') || rel.split('/').some((s) => /^(?:changelog|journal)(?:$|[.\-_/])/i.test(s))
9
+
10
+ /** whether git ever held a file whose path is `token` or ends with `/token`, on any branch of the repo at `cwd` */
11
+ export function onceAPath(cwd: string, token: string): boolean {
12
+ try {
13
+ const p = Bun.spawnSync([gitBin(), 'log', '-1', '--format=%h', '--all', '--', `:(glob)**/${token}`, `:(glob)${token}`], { cwd, stdout: 'pipe', stderr: 'ignore' })
14
+ return p.exitCode === 0 && p.stdout.toString().trim() !== ''
15
+ } catch {
16
+ return false
17
+ }
18
+ }
package/src/core/jobs.ts CHANGED
@@ -19,6 +19,8 @@ import { fmtStamp } from './wire.ts'
19
19
 
20
20
  /** status exit code while the run has no verdict yet */
21
21
  export const STILL_RUNNING = 3
22
+ /** how long `status --wait` holds: a run that goes on past it is asked again */
23
+ export const WAIT_CAP_MS = 10 * 60 * 1000
22
24
 
23
25
  export type JobKind = 'ci' | 'check'
24
26
  export type Job = { id: string; pid: number; args: string[]; startedAt: number; kind?: JobKind }
@@ -92,7 +94,7 @@ export function startDetached(root: string, o: { cli: string; args: string[] }):
92
94
  pid,
93
95
  lines: [
94
96
  `ok: gate started in the background as ${id} (pid ${pid}): ${ciLine(o.args)}`,
95
- ` fix: shipkit status ${id} prints it, and exits ${STILL_RUNNING} until it has a verdict`,
97
+ ` fix: shipkit status ${id} --wait returns when it has a verdict (without --wait: the run so far, exit ${STILL_RUNNING} until then)`,
96
98
  ],
97
99
  }
98
100
  }
@@ -128,42 +130,59 @@ export function recordExit(root: string, id: string, code: number): void {
128
130
  atomicWrite(join(dir, 'exit.json'), JSON.stringify({ code, finishedAt: Date.now() } satisfies Exit))
129
131
  }
130
132
 
131
- function latestJob(root: string): string | null {
133
+ /** the latest run of this checkout. `own`: one a `--detach` started, never a job of the daemon */
134
+ function latestJob(root: string, own: boolean): Job | null {
132
135
  let best: Job | null = null
133
136
  try {
134
137
  for (const name of readdirSync(join(root, JOBS))) {
135
138
  const j = readJson<Job>(join(root, JOBS, name, 'job.json'))
136
- if (j != null && (best == null || j.startedAt > best.startedAt)) best = j
139
+ if (j == null || (own && existsSync(jobOpts(root, name)))) continue
140
+ if (best == null || j.startedAt > best.startedAt) best = j
137
141
  }
138
142
  } catch { return null }
139
- return best?.id ?? null
143
+ return best
140
144
  }
141
145
 
142
- /** the run's wire lines so far, then one line on where it stands. The code is
143
- * the gate's own exit code once it has one, STILL_RUNNING before, 1 for a
144
- * run that died without a verdict, 2 for an id nobody started here. */
146
+ /** one line on where the run stands, then its wire lines so far: the first
147
+ * line is the answer. The code is the gate's own exit code once it has one,
148
+ * STILL_RUNNING before, 1 for a run that died without a verdict, 2 for an id
149
+ * nobody started here. With no id: the latest run a `--detach` started, since
150
+ * a job of the daemon is nobody's question. */
145
151
  export function jobStatus(root: string, id?: string): { code: number; lines: string[] } {
146
- const want = id ?? latestJob(root)
152
+ const want = id ?? latestJob(root, true)?.id
147
153
  if (want == null) return { code: 2, lines: ['FAIL: no detached run in this checkout yet', ' fix: shipkit ci --detach starts one'] }
148
154
  const dir = jobDir(root, want)
149
155
  const job = readJson<Job>(join(dir, 'job.json'))
150
156
  if (job == null) return { code: 2, lines: [`FAIL: no detached run '${want}' in this checkout`, ` fix: shipkit status (no id) shows the latest one`] }
151
- const lines = [`ok: run ${job.id}: ${ciLine(job.args, job.kind)} (pid ${job.pid}, started ${fmtStamp(job.startedAt)})`]
157
+ const what = `${ciLine(job.args, job.kind)} (pid ${job.pid}, started ${fmtStamp(job.startedAt)})`
152
158
  let out = ''
153
159
  try { out = readFileSync(join(dir, 'out.log'), 'utf8') } catch { /* nothing printed yet */ }
154
- lines.push(...out.split('\n').filter((l) => l !== ''))
160
+ const wire = out.split('\n').filter((l) => l !== '')
155
161
  const exit = (): Exit | null => readJson<Exit>(join(dir, 'exit.json'))
156
162
  let e = exit()
157
- if (e == null && alive(job.pid)) {
158
- lines.push(`skip: run ${job.id} still running (${((Date.now() - job.startedAt) / 1000).toFixed(1)}s so far), status exits ${STILL_RUNNING} until it has a verdict`)
159
- return { code: STILL_RUNNING, lines }
163
+ if (e == null && jobAlive(job.pid)) {
164
+ return { code: STILL_RUNNING, lines: [`skip: run ${job.id} still running (${((Date.now() - job.startedAt) / 1000).toFixed(1)}s so far), status exits ${STILL_RUNNING} until it has a verdict: ${what}`, ...wire] }
160
165
  }
161
166
  // it may have written its verdict between the two reads
162
167
  e ??= exit()
163
- if (e == null) return { code: 1, lines: [...lines, `FAIL: run ${job.id} died without a verdict (pid ${job.pid} is gone)`, ` fix: ${ciLine(job.args, job.kind)}`] }
168
+ if (e == null) return { code: 1, lines: [`FAIL: run ${job.id} died without a verdict (pid ${job.pid} is gone): ${what}`, ` fix: ${ciLine(job.args, job.kind)}`, ...wire] }
164
169
  const took = `${((e.finishedAt - job.startedAt) / 1000).toFixed(1)}s`
165
- lines.push(e.code === 0 ? `ok: run ${job.id} finished green in ${took}` : `FAIL: run ${job.id} finished red (exit ${e.code}) in ${took}`)
166
- return { code: e.code, lines }
170
+ const verdict = e.code === 0 ? `ok: run ${job.id} finished green in ${took}` : `FAIL: run ${job.id} finished red (exit ${e.code}) in ${took}`
171
+ return { code: e.code, lines: [`${verdict}: ${what}`, ...wire] }
172
+ }
173
+
174
+ /** the status of a run once it has a verdict: one call that returns when the
175
+ * run ends, in place of a poll every few seconds. Past the cap it answers
176
+ * STILL_RUNNING like a plain status. */
177
+ export async function waitStatus(root: string, id?: string, o: { capMs?: number; pollMs?: number } = {}): Promise<{ code: number; lines: string[] }> {
178
+ const want = id ?? latestJob(root, true)?.id
179
+ const until = Date.now() + (o.capMs ?? WAIT_CAP_MS)
180
+ const pending = (): boolean => {
181
+ const j = want == null ? null : readJob(root, want)
182
+ return j != null && readExit(root, j.id) == null && jobAlive(j.pid)
183
+ }
184
+ while (pending() && Date.now() < until) await Bun.sleep(o.pollMs ?? 250)
185
+ return jobStatus(root, want)
167
186
  }
168
187
 
169
188
  /** finished runs older than a week go, then the oldest past the count cap;
@@ -37,8 +37,8 @@ export const LAYOUT = {
37
37
  // the social folder (contract v3): one folder a draft, the week's rhythm. The SK004 block re-includes it in a
38
38
  // private repo only, like plans (wiki tools/shipkit/social.md)
39
39
  social: sk('social'),
40
- // the owner's own voice: his takes of a trailer's lines, one a text (trailer/sound/takes.ts). The SK004 block
41
- // re-includes it in a private repo only: a recording is his voice
40
+ // the owner's own voice: his takes of a trailer's lines, one a text (trailer/sound/takes.ts). Local in every
41
+ // repo: the SK004 block never re-includes it, a recording is his voice
42
42
  voice: sk('voice'),
43
43
  // local: the facts (sha, size, type) of every draft media, so a file the disk let go keeps its key in the media
44
44
  // store (wiki tools/shipkit/social.md, Media)
@@ -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