rvlib-shipkit 2.32.0 → 2.34.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 (76) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/package.json +1 -1
  3. package/src/advisors/advisor-view.ts +29 -7
  4. package/src/advisors/edge/api.ts +1 -30
  5. package/src/advisors/project.ts +3 -3
  6. package/src/advisors/sync.ts +11 -4
  7. package/src/advisors/users-router.ts +13 -11
  8. package/src/cli/cmd_BackupTargets.ts +49 -8
  9. package/src/cli/cmd_Capacity.ts +6 -2
  10. package/src/cli/cmd_Ci.ts +2 -1
  11. package/src/cli/cmd_Media.ts +1 -1
  12. package/src/cli/cmd_Shot.ts +26 -4
  13. package/src/cli/cmd_Start.ts +3 -3
  14. package/src/cli.ts +13 -2
  15. package/src/core/admission.ts +268 -0
  16. package/src/core/code-lines.ts +36 -21
  17. package/src/core/machine-read.ts +5 -2
  18. package/src/core/memory-watch.ts +1 -1
  19. package/src/core/peer-sk.ts +8 -0
  20. package/src/gate/admit-heavy.ts +150 -0
  21. package/src/gate/check-runner.ts +6 -0
  22. package/src/gate/gate-checks.ts +7 -5
  23. package/src/gate/head-gate.ts +1 -1
  24. package/src/gate/job-run.ts +2 -1
  25. package/src/gate/pre-commit-discovery.ts +6 -3
  26. package/src/gate/run-check.ts +3 -0
  27. package/src/gate/run-ci.ts +4 -0
  28. package/src/home/backup-status.ts +41 -13
  29. package/src/home/backup-verdict.ts +1 -0
  30. package/src/home/daemon-jobs.ts +5 -0
  31. package/src/home/home-routes.ts +3 -2
  32. package/src/home/house-bucket.ts +14 -0
  33. package/src/home/run-daemon.ts +3 -1
  34. package/src/home/this-house.ts +68 -0
  35. package/src/home/via-hub.ts +2 -1
  36. package/src/hooks/commit-msg-run.ts +61 -0
  37. package/src/hooks/commit-run.ts +16 -166
  38. package/src/hooks/gate-outcome.ts +108 -0
  39. package/src/hooks/git-hook.ts +9 -9
  40. package/src/hooks/hook-config.ts +2 -1
  41. package/src/hooks/pre-commit-checks.ts +1 -1
  42. package/src/hooks/run-hooks.ts +2 -1
  43. package/src/hooks/shared-file.ts +3 -2
  44. package/src/hq/backup-targets.ts +58 -5
  45. package/src/hq/hq-local.ts +1 -1
  46. package/src/media-store/backup/bucket-target.ts +58 -0
  47. package/src/media-store/backup/target-send.ts +7 -4
  48. package/src/media-store/space.ts +2 -0
  49. package/src/plan/planner.ts +3 -2
  50. package/src/repo-config.ts +8 -1
  51. package/src/review/answer-kinds.ts +2 -0
  52. package/src/review/cells.ts +40 -9
  53. package/src/review/format.ts +1 -1
  54. package/src/review/model.ts +3 -3
  55. package/src/review/routes.ts +2 -28
  56. package/src/review/store-parties.ts +28 -0
  57. package/src/review/store.ts +11 -2
  58. package/src/review/thread-state.ts +9 -3
  59. package/src/scaffold/project-scaffold.ts +2 -2
  60. package/src/secrets/copy.ts +4 -4
  61. package/src/serve/hub-app/auto-text.tsx +3 -1
  62. package/src/serve/hub-app/dock-st.ts +1 -1
  63. package/src/serve/hub-app/review/question-views.tsx +28 -17
  64. package/src/serve/hub-app/review/review-host.ts +6 -2
  65. package/src/serve/hub-app/review/review-list.tsx +8 -5
  66. package/src/serve/hub-app/review/review-st.ts +2 -2
  67. package/src/serve/hub-app/review/review-thread.tsx +2 -1
  68. package/src/serve/hub-app/review/review-views.tsx +10 -7
  69. package/src/serve/hub-app/review/thread-st.ts +25 -11
  70. package/src/serve/hub-app/review/tone-bar.tsx +29 -24
  71. package/src/serve/hub-app/review/tones.ts +18 -0
  72. package/src/serve/hub-app/review.css +11 -2
  73. package/src/setup-house.ts +1 -7
  74. package/src/shot/client.ts +2 -1
  75. package/src/shot/on-place.ts +141 -0
  76. package/src/start-repo.ts +27 -30
package/src/cli.ts CHANGED
@@ -58,6 +58,14 @@ async function headGate(raw: string[]): Promise<number | null> {
58
58
  return o === null ? null : await m.runHeadGate(process.cwd(), { ...o, print: (l) => process.stdout.write(`${l}\n`) })
59
59
  }
60
60
 
61
+ /** a heavy line waits while the machine is full (gate/admit-heavy.ts; `sk ci` waits inside the gate, before its
62
+ * first heavy check that misses the cache); a module that fails to load lets it run */
63
+ async function admitHeavy(argv: readonly string[]): Promise<void> {
64
+ let m
65
+ try { m = await import('./gate/admit-heavy.ts') } catch { return }
66
+ await m.admitLine(argv, process.cwd())
67
+ }
68
+
61
69
  /** true for the one line the inbox hook is wired as, `sk thread inbox --hook`, nothing else on it */
62
70
  export const isInboxHookLine = (raw: readonly string[]): boolean => raw.length === 3 && raw[0] === 'thread' && raw[1] === 'inbox' && raw[2] === '--hook'
63
71
 
@@ -97,8 +105,10 @@ if (import.meta.main) {
97
105
  call.matched('line' in line ? commandPath(() => line.line.command) : 'help', performance.now() - t0)
98
106
  const pm = pmAsked(argv)
99
107
  await b.takeBackAtBoot()
100
- if ('line' in line) process.exitCode = await line.line.run()
101
- else console.log(line.version)
108
+ if ('line' in line) {
109
+ await admitHeavy(argv)
110
+ process.exitCode = await line.line.run()
111
+ } else console.log(line.version)
102
112
  await pm
103
113
  } else {
104
114
  let cli = b.cli!
@@ -112,6 +122,7 @@ if (import.meta.main) {
112
122
  call.matched(commandPath(() => cli.process(run)), performance.now() - t0)
113
123
  const pm = pmAsked(run)
114
124
  await b.takeBackAtBoot()
125
+ await admitHeavy(run)
115
126
  await cli.runExit(run)
116
127
  await pm
117
128
  }
@@ -0,0 +1,268 @@
1
+ // THE ADMISSION GATE FOR HEAVY WORK: before a heavy sk command (a clip, a loop of
2
+ // shots, sk smoke, a command the repo declares in repo.config.ts `heavy`) and
3
+ // before the first heavy check an asked gate runs (heavyCheck), a full machine
4
+ // makes it wait, one line every 10 s that names who uses the CPU, grouped by repo
5
+ // and by Claude session (one `ps`, the session files of Claude Code). Past the
6
+ // bound it runs anyway, with a WARN, and a bound reached against a user outside sk
7
+ // lets the next ones run at once while that user leads. The readings and the
8
+ // entries: gate/admit-heavy.ts.
9
+ //
10
+ // the one constraint a reader breaks first: this file reads nothing, every
11
+ // reading comes in as an argument, so a test drives the wait on a fake clock.
12
+ import { basename } from 'path'
13
+ import { effectiveLoad, machineWords, type MachineLoad } from './machine-busy.ts'
14
+
15
+ /** the machine is full past this many times its cores of load, once its CPU is taken (effectiveLoad) */
16
+ export const FULL_FACTOR = 1.5
17
+ /** how long a heavy command waits at most, in seconds, unless SHIPKIT_ADMIT_WAIT_S says another (0: never waits):
18
+ * under the 120 s an agent's foreground call lives, so a wait ends in a verdict, never in a killed call */
19
+ export const ADMIT_BOUND_S = 80
20
+ export const ADMIT_WAIT_ENV = 'SHIPKIT_ADMIT_WAIT_S'
21
+ /** a waiter says one line this often */
22
+ export const SAY_EVERY_MS = 10_000
23
+ /** a waiter looks at the machine again about this often, give or take a quarter, so waiters never look together */
24
+ export const LOOK_EVERY_MS = 2_000
25
+ /** a still is heavy once the command that runs it (its parent process: a script, a shell loop) asked this many
26
+ * inside SHOT_LOOP_MS: a loop of shots. An agent's calls one by one each have their own parent */
27
+ export const SHOT_LOOP_COUNT = 3
28
+ export const SHOT_LOOP_MS = 60_000
29
+
30
+ export const isFull = (m: MachineLoad): boolean => effectiveLoad(m) > FULL_FACTOR * m.cores
31
+
32
+ export type PsRow = { pid: number; ppid: number; cpu: number; args: string }
33
+
34
+ /** `ps -Axo pid=,ppid=,%cpu=,args=` read into rows; a line that is not one is skipped */
35
+ export function parsePs(text: string): PsRow[] {
36
+ const out: PsRow[] = []
37
+ for (const line of text.split('\n')) {
38
+ const m = /^\s*(\d+)\s+(\d+)\s+([\d.]+)\s+(.*)$/.exec(line)
39
+ if (m != null) out.push({ pid: Number(m[1]), ppid: Number(m[2]), cpu: Number(m[3]), args: m[4]!.trim() })
40
+ }
41
+ return out
42
+ }
43
+
44
+ /** a Claude Code process: the folder its session runs in, and its name */
45
+ export type SessionProc = { cwd: string; name: string }
46
+
47
+ /** `sk`: the lead is the toolkit's own work, which ends; outside sk, waiting lowers no load */
48
+ export type Lead = { pid: number; what: string; cpu: number; sk: boolean }
49
+ /** one user of the CPU: a repo, or a program outside every repo; `cpu` in % of one core */
50
+ export type UseGroup = { who: string; cpu: number; leads: Lead[]; sessions: { name: string; pid: number; cpu: number }[] }
51
+
52
+ const RUNTIMES = /^(bun|node|deno|python3?|ruby|tsx)$/
53
+ /** a shell or a wrapper (timeout, nice): never the command that leads the work under it */
54
+ const SHELLS = /^-?(sh|bash|zsh|fish|dash|timeout|gtimeout|nice|env|caffeinate)$/
55
+ /** the program a process runs: a macOS app by its bundle (its name has spaces, its helpers sit inside it); `(bun)` is
56
+ * how ps names one that is exiting */
57
+ const prog = (args: string): string => /\/([^/]+?)\.app\//.exec(args.split(/ --?\w/)[0] ?? '')?.[1] ?? basename(args.split(/\s+/)[0] ?? '').replace(/^\((.+)\)$/, '$1')
58
+ const isShell = (args: string): boolean => SHELLS.test(prog(args))
59
+
60
+ /** what a process runs, in a few words: `bun cli.ts shoot`, `chrome-headless-shell`, `WindowServer` */
61
+ export function describe(args: string): string {
62
+ const t = args.split(/\s+/).filter((x) => x !== '')
63
+ const head = prog(args)
64
+ const words = [head]
65
+ let i = 1
66
+ if (RUNTIMES.test(head)) {
67
+ while (i < t.length && t[i]!.startsWith('-')) i++
68
+ if (i < t.length) words.push(basename(t[i++]!))
69
+ }
70
+ const next = t[i]
71
+ if (next != null && /^[a-z][\w:-]{0,19}$/.test(next)) words.push(next)
72
+ return words.join(' ').slice(0, 48)
73
+ }
74
+
75
+ /** the repo a path of the command names: a folder under `<home>/dev/`. A path into a published lib of the house
76
+ * (`packages/rvlib-…`) is the toolkit running for someone else, so it names `shipkit` only when nothing else does */
77
+ export function repoInArgs(args: string, home: string): string | null {
78
+ const re = new RegExp(`${home.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/dev/([\\w.-]+)(/[^\\s'"]*)?`, 'g')
79
+ let lib: string | null = null
80
+ for (const m of args.matchAll(re)) {
81
+ if (/^\/packages\/rvlib-/.test(m[2] ?? '')) lib ??= 'shipkit'
82
+ else return m[1]!
83
+ }
84
+ return lib
85
+ }
86
+
87
+ /** the repo a folder is in: its name under `<home>/dev/`, a worktree of it included, else the folder's own name */
88
+ export const repoOfDir = (cwd: string, home: string): string => {
89
+ const m = new RegExp(`^${home.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/dev/([\\w.-]+)`).exec(cwd)
90
+ return m?.[1] ?? basename(cwd)
91
+ }
92
+
93
+ /** every process's CPU grouped by who it works for: the Claude session above it (its folder's repo), else the repo
94
+ * a path of its command or of a parent's names, else its program. `lead`: the command that started the work, the
95
+ * highest one under the session that is no shell, or the process that names the repo */
96
+ export function whoUses(rows: readonly PsRow[], sessions: ReadonlyMap<number, SessionProc>, o: { home: string; self?: number }): UseGroup[] {
97
+ const by = new Map(rows.map((r) => [r.pid, r]))
98
+ const groups = new Map<string, { cpu: number; leads: Map<number, Lead>; sessions: Map<number, { name: string; pid: number; cpu: number }> }>()
99
+ for (const row of rows) {
100
+ if (!(row.cpu > 0) || row.pid === o.self || /^\/?(bin\/)?ps -Axo/.test(row.args)) continue
101
+ let session: number | null = null
102
+ let named: { repo: string; at: PsRow } | null = null
103
+ let lead = row
104
+ let cur: PsRow | undefined = row
105
+ for (let depth = 0; cur != null && depth < 64; depth++) {
106
+ if (sessions.has(cur.pid)) {
107
+ session = cur.pid
108
+ break
109
+ }
110
+ if (named == null || named.repo === 'shipkit') {
111
+ const r = repoInArgs(cur.args, o.home)
112
+ if (r != null && (named == null || r !== 'shipkit')) named = { repo: r, at: cur }
113
+ }
114
+ if (!isShell(cur.args)) lead = cur
115
+ if (cur.ppid <= 1) break
116
+ cur = by.get(cur.ppid)
117
+ }
118
+ const s = session == null ? null : sessions.get(session)!
119
+ const who = s != null ? repoOfDir(s.cwd, o.home) : named?.repo ?? prog(row.args)
120
+ if (s == null) lead = named?.at ?? row
121
+ let g = groups.get(who)
122
+ if (g == null) groups.set(who, (g = { cpu: 0, leads: new Map(), sessions: new Map() }))
123
+ g.cpu += row.cpu
124
+ const l = g.leads.get(lead.pid) ?? { pid: lead.pid, what: describe(lead.args), cpu: 0, sk: lead.args.includes('/packages/rvlib-shipkit/') }
125
+ l.cpu += row.cpu
126
+ g.leads.set(lead.pid, l)
127
+ if (s != null && session != null) {
128
+ const e = g.sessions.get(session) ?? { name: s.name, pid: session, cpu: 0 }
129
+ e.cpu += row.cpu
130
+ g.sessions.set(session, e)
131
+ }
132
+ }
133
+ const desc = <T extends { cpu: number }>(a: T, b: T): number => b.cpu - a.cpu
134
+ return [...groups].map(([who, g]) => ({ who, cpu: g.cpu, leads: [...g.leads.values()].sort(desc), sessions: [...g.sessions.values()].sort(desc) })).sort(desc)
135
+ }
136
+
137
+ const pct = (n: number): string => `${Math.round(n)} %`
138
+
139
+ /** the users a waiting line names: the biggest few, the command that leads each big one */
140
+ export function whoWords(groups: readonly UseGroup[], n = 3): string {
141
+ const shown = groups.filter((g) => g.cpu >= 10).slice(0, n)
142
+ if (shown.length === 0) return 'no process holds 10 % of a core'
143
+ return shown.map((g) => `${g.who} ${pct(g.cpu)}${g.cpu >= 50 && g.leads[0] != null ? ` (${g.leads[0].what}, pid ${g.leads[0].pid})` : ''}`).join(', ')
144
+ }
145
+
146
+ /** the table `sk capacity` prints: a line a user, its leading commands and its sessions */
147
+ export function whoLines(groups: readonly UseGroup[]): string[] {
148
+ const shown = groups.filter((g) => g.cpu >= 10).slice(0, 6)
149
+ if (shown.length === 0) return ['who uses the CPU: no process holds 10 % of a core']
150
+ return [
151
+ 'who uses the CPU (ps, 100 % is one core):',
152
+ ...shown.map((g) => {
153
+ const leads = g.leads.slice(0, 3).map((l) => `${l.what} (pid ${l.pid}) ${pct(l.cpu)}`).join(', ')
154
+ const ses = g.sessions.slice(0, 3).map((s) => `${s.name} ${pct(s.cpu)}`).join(', ')
155
+ return ` ${g.who} ${pct(g.cpu)}: ${leads}${ses === '' ? '' : `; session ${ses}`}`
156
+ }),
157
+ ]
158
+ }
159
+
160
+ export type Look = { m: MachineLoad; groups: UseGroup[] | null }
161
+
162
+ /** what remembers that a wait reached its bound, and who held the CPU then (a small file of the home dir) */
163
+ export type AdmitMemo = { read: () => string | null; write: (key: string | null) => void }
164
+
165
+ export type AdmitDeps = { look: () => Promise<Look>; now: () => number; sleep: (ms: number) => Promise<void>; say: (line: string) => void; boundMs: number; memo?: AdmitMemo; random?: () => number }
166
+
167
+ const secs = (ms: number): string => (ms >= 60_000 && ms % 60_000 === 0 ? `${ms / 60_000} min` : `${Math.round(ms / 1000)} s`)
168
+
169
+ /** the top user outside sk, as the memo keeps it, or null when sk's own work leads (it ends, so a wait helps) */
170
+ export function outsideTop(groups: readonly UseGroup[] | null): string | null {
171
+ const g = groups?.[0]
172
+ const lead = g?.leads[0]
173
+ return g == null || lead == null || lead.sk || g.cpu < 100 ? null : `${g.who}/${lead.pid}`
174
+ }
175
+
176
+ /** wait while the machine is full, a line every SAY_EVERY_MS naming who uses it; past `boundMs`, a WARN and run.
177
+ * A wait that reached its bound is remembered with the top user outside sk: while that user still leads, the next
178
+ * heavy command runs at once with the WARN, since waiting lowers no load sk does not own.
179
+ * `free`: it ran at once, silent; `waited`: the machine made room; `over`: it runs on a full machine */
180
+ export async function admit(what: string, d: AdmitDeps): Promise<'free' | 'waited' | 'over'> {
181
+ let l = await d.look()
182
+ if (!isFull(l.m)) {
183
+ d.memo?.write(null)
184
+ return 'free'
185
+ }
186
+ const top = outsideTop(l.groups)
187
+ const kept = d.memo?.read() ?? null
188
+ if (kept != null && kept !== top) d.memo?.write(null)
189
+ if (top != null && kept === top) {
190
+ d.say(`WARN the machine is full (${machineWords(l.m)}): ${whoWords(l.groups ?? [])}, who held it through the last wait's bound too; ${what} runs now, since waiting lowers no load sk does not own`)
191
+ return 'over'
192
+ }
193
+ const start = d.now()
194
+ let said = -Infinity
195
+ for (;;) {
196
+ const waited = d.now() - start
197
+ const who = l.groups == null ? '' : `: ${whoWords(l.groups)}`
198
+ if (waited >= d.boundMs) {
199
+ d.say(`WARN the machine stayed full for ${secs(d.boundMs)} (${machineWords(l.m)})${who}; ${what} runs anyway`)
200
+ d.memo?.write(outsideTop(l.groups))
201
+ return 'over'
202
+ }
203
+ if (waited - said >= SAY_EVERY_MS) {
204
+ said = waited
205
+ d.say(`waiting: the machine is full (${machineWords(l.m)})${who}; ${what} starts when it has room, ${secs(d.boundMs)} at most${waited > 0 ? `, ${secs(waited)} so far` : ' (run it in the background, never in a loop)'}`)
206
+ }
207
+ await d.sleep(Math.min(LOOK_EVERY_MS * (0.75 + (d.random ?? Math.random)() / 2), d.boundMs - waited))
208
+ l = await d.look()
209
+ if (!isFull(l.m)) {
210
+ d.memo?.write(null)
211
+ d.say(`ok: the machine has room again (${machineWords(l.m)}) after ${secs(d.now() - start)}: ${what} starts`)
212
+ return 'waited'
213
+ }
214
+ }
215
+ }
216
+
217
+ /** the bound a waiter takes: SHIPKIT_ADMIT_WAIT_S, else ADMIT_BOUND_S */
218
+ export function boundMs(env: Record<string, string | undefined> = process.env): number {
219
+ const v = env[ADMIT_WAIT_ENV]
220
+ const n = v == null || v === '' ? NaN : Number(v)
221
+ return (Number.isFinite(n) && n >= 0 ? n : ADMIT_BOUND_S) * 1000
222
+ }
223
+
224
+ /** a check that waits on a full machine before it runs (gate/check-runner.ts): a test tier, a browser check, the
225
+ * local PocketBase bench */
226
+ const HEAVY_CHECK = /^(test|smoke|e2e|shot)(:|$)|browser|^pb-playground(:|$)/
227
+ export const heavyCheck = (id: string): boolean => HEAVY_CHECK.test(id)
228
+
229
+ /** what a built in heavy line is called, `shot-still` for a still (heavy in a loop only), or null when it is light: a
230
+ * clip, sk smoke. `sk ci` waits inside the gate, before its first heavy check that misses the cache (heavyCheck) */
231
+ export function builtInHeavy(argv: readonly string[]): string | null {
232
+ const [cmd] = argv
233
+ if (cmd === 'shot') return argv.includes('--video') ? 'sk shot --video' : 'shot-still'
234
+ if (cmd === 'smoke') return 'sk smoke'
235
+ return null
236
+ }
237
+
238
+ /** the line `heavy` declares that this argv starts with: `trailer` matches `sk trailer …`, `assets gen` its own */
239
+ export function declaredHeavy(argv: readonly string[], heavy: readonly string[]): string | null {
240
+ for (const h of heavy) {
241
+ const words = h.trim().split(/\s+/)
242
+ if (words.length > 0 && words[0] !== '' && words.every((w, i) => argv[i] === w)) return `sk ${words.join(' ')}`
243
+ }
244
+ return null
245
+ }
246
+
247
+ /** why `heavy` in repo.config.ts is refused, or null when it holds */
248
+ export function heavyProblem(v: unknown): string | null {
249
+ if (v === undefined) return null
250
+ if (!Array.isArray(v) || v.some((x) => typeof x !== 'string' || x.trim() === '')) return `heavy is a list of sk command lines that wait while the machine is full, like ['trailer', 'assets gen'], got ${JSON.stringify(v)}`
251
+ return null
252
+ }
253
+
254
+ /** the biggest user of the CPU in a few words, read again at most every 10 s in the background: what the hub's held
255
+ * line names. Never waits: the first call starts a read and answers null */
256
+ export function topUserWatch(read: () => Promise<UseGroup[]>, now: () => number = Date.now): () => string | null {
257
+ let value: string | null = null
258
+ let at = -Infinity
259
+ let reading = false
260
+ return () => {
261
+ if (!reading && now() - at >= 10_000) {
262
+ reading = true
263
+ at = now()
264
+ void read().then((g) => { value = g.some((x) => x.cpu >= 10) ? whoWords(g, 1) : null }, () => { value = null }).finally(() => { reading = false })
265
+ }
266
+ return value
267
+ }
268
+ }
@@ -6,8 +6,21 @@
6
6
  // punctuator or a keyword like `return`); a miss can open a false comment, so
7
7
  // a guard that must never go blind also reads the raw line (core/hard-reset.ts).
8
8
 
9
- /** what ends the code before a `/` that opens a regex literal rather than a division (empty: the line starts) */
10
- const REGEX_BEFORE = /(?:^|[(,=:[!&|?{};+\-*%<>~^]|\b(?:return|typeof|case|in|of|yield|await|void|delete|throw|else|do|instanceof|new))$/
9
+ const PUNCT = new Set('(,=:[!&|?{};+-*%<>~^')
10
+ const KEYWORDS = new Set(['return', 'typeof', 'case', 'in', 'of', 'yield', 'await', 'void', 'delete', 'throw', 'else', 'do', 'instanceof', 'new'])
11
+ const isWord = (c: number): boolean => (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c === 95
12
+ const isSpace = (c: number): boolean => c === 32 || c === 9 || c === 13 || c === 11 || c === 12 || c === 160 || c === 0xfeff || (c >= 0x2000 && c <= 0x200a) || c === 0x2028 || c === 0x2029 || c === 0x202f || c === 0x205f || c === 0x3000 || c === 0x1680
13
+
14
+ /** whether the code before a `/` (`head` then `line` up to `end`) ends where a regex literal starts rather than a division */
15
+ function regexBefore(head: string, line: string, from: number, end: number): boolean {
16
+ const s = head + line.slice(from, end)
17
+ let j = s.length - 1
18
+ while (j >= 0 && isSpace(s.charCodeAt(j))) j--
19
+ if (j < 0 || PUNCT.has(s[j]!)) return true
20
+ let k = j
21
+ while (k >= 0 && isWord(s.charCodeAt(k))) k--
22
+ return k < j && KEYWORDS.has(s.slice(k + 1, j + 1))
23
+ }
11
24
 
12
25
  export function codeLines(src: string): string[] {
13
26
  const out: string[] = []
@@ -15,35 +28,37 @@ export function codeLines(src: string): string[] {
15
28
  let inClass = false
16
29
  for (const line of src.split('\n')) {
17
30
  if (state === "'" || state === '"' || state === 'regex') state = 'code'
18
- let kept = ''
19
- for (let i = 0; i < line.length; i++) {
20
- const c = line[i]!
21
- const next = line[i + 1]
31
+ // kept = head + line.slice(from, i): runs of the line outside block comments
32
+ let head = ''
33
+ let from = 0
34
+ let i = 0
35
+ const n = line.length
36
+ for (; i < n; i++) {
37
+ const c = line.charCodeAt(i)
22
38
  if (state === 'block') {
23
- if (c === '*' && next === '/') { state = 'code'; i++ }
39
+ if (c === 42 && line.charCodeAt(i + 1) === 47) { state = 'code'; i++; from = i + 1 }
24
40
  continue
25
41
  }
26
42
  if (state === 'regex') {
27
- kept += c
28
- if (c === '\\') { kept += next ?? ''; i++ }
29
- else if (c === '[') inClass = true
30
- else if (c === ']') inClass = false
31
- else if (c === '/' && !inClass) state = 'code'
43
+ if (c === 92) i++
44
+ else if (c === 91) inClass = true
45
+ else if (c === 93) inClass = false
46
+ else if (c === 47 && !inClass) state = 'code'
32
47
  continue
33
48
  }
34
49
  if (state !== 'code') {
35
- kept += c
36
- if (c === '\\') { kept += next ?? ''; i++ }
37
- else if (c === state) state = 'code'
50
+ if (c === 92) i++
51
+ else if (c === state.charCodeAt(0)) state = 'code'
38
52
  continue
39
53
  }
40
- if (c === '/' && next === '/') break
41
- if (c === '/' && next === '*') { state = 'block'; i++; continue }
42
- if (c === '/' && REGEX_BEFORE.test(kept.trimEnd())) { state = 'regex'; inClass = false; kept += c; continue }
43
- if (c === "'" || c === '"' || c === '`') state = c
44
- kept += c
54
+ if (c === 47) {
55
+ const next = line.charCodeAt(i + 1)
56
+ if (next === 47) break
57
+ if (next === 42) { head += line.slice(from, i); state = 'block'; i++; continue }
58
+ if (regexBefore(head, line, from, i)) { state = 'regex'; inClass = false; continue }
59
+ } else if (c === 39 || c === 34 || c === 96) state = c === 39 ? "'" : c === 34 ? '"' : '`'
45
60
  }
46
- out.push(kept)
61
+ out.push(state === 'block' ? head : head + line.slice(from, Math.min(i, n)))
47
62
  }
48
63
  return out
49
64
  }
@@ -20,10 +20,13 @@ export const PUBLISHED_FRESH_MS = 15_000
20
20
  /** how often a long lived process publishes */
21
21
  export const PUBLISH_EVERY_MS = 5_000
22
22
 
23
- const publishedFile = (): string | null => {
24
- try { return join(homeDir(), 'machine-busy.json') } catch { return null }
23
+ /** a small file of the machine's state in the home dir, or null where there is none */
24
+ export const homeStateFile = (name: string): string | null => {
25
+ try { return join(homeDir(), name) } catch { return null }
25
26
  }
26
27
 
28
+ const publishedFile = (): string | null => homeStateFile('machine-busy.json')
29
+
27
30
  /** the cores in use a long lived process published, while fresh and for these cores */
28
31
  export function readPublished(file: string, cores: number, now = Date.now()): number | null {
29
32
  try {
@@ -15,7 +15,7 @@ export const MEMORY_EVERY_MS = 10 * 60_000
15
15
  export const MEMORY_STEP = 0.1
16
16
 
17
17
  /** what the daemon may hold, as its footprint: steady, and in its first BOOT_MS while every hub warms */
18
- export const MEMORY_BUDGET = { steady: 500 * 2 ** 20, boot: 1024 * 2 ** 20 }
18
+ export const MEMORY_BUDGET = { steady: 750 * 2 ** 20, boot: 1024 * 2 ** 20 }
19
19
  export const BOOT_MS = 5 * 60_000
20
20
  export const BUDGET_EVERY_MS = 30_000
21
21
  /** the machine db row of the daemon's last pass over its budget */
@@ -0,0 +1,8 @@
1
+ // a shipkit command on another place of the house over ssh: from its house checkout at the same place under its home,
2
+ // the tools' folders named, since an ssh command shell reads no rc file
3
+
4
+ /** a word quoted for the peer's sh */
5
+ export const shq = (s: string): string => `'${s.replaceAll("'", `'\\''`)}'`
6
+
7
+ /** the line the peer's shell runs for `sk <args>`, args already quoted */
8
+ export const peerSk = (houseRel: string, args: string): string => `cd ~/${houseRel} && PATH="$HOME/.local/bin:$HOME/.bun/bin:$PATH" sk ${args}`
@@ -0,0 +1,150 @@
1
+ // THE ADMISSION GATE'S READINGS (the judge: core/admission.ts): one ps of the
2
+ // machine, the session files of Claude Code, the load, the memo of a wait that
3
+ // reached its bound, and the two entries: every sk command before it runs
4
+ // (cli.ts admitLine), and an asked gate before its first heavy check that misses
5
+ // the cache (check-runner.ts, through runCi's `admit`). A release never waits:
6
+ // sk bump runs its gate in its own process, with no `admit`.
7
+ //
8
+ // the one constraint a reader breaks first: the calm path is os.loadavg alone,
9
+ // with no spawn and no file read, since every sk command passes here: the rest
10
+ // of what it reads loads by await import, past that line.
11
+ import { readFileSync } from 'fs'
12
+ import { availableParallelism, homedir, loadavg } from 'os'
13
+ import { dirname, join, resolve } from 'path'
14
+ import { admit, boundMs, builtInHeavy, declaredHeavy, FULL_FACTOR, isFull, parsePs, SHOT_LOOP_COUNT, SHOT_LOOP_MS, whoUses, type AdmitMemo, type Look, type SessionProc, type UseGroup } from '../core/admission.ts'
15
+ import { SLOT_HELD_ENV } from '../core/slot-env.ts'
16
+
17
+ /** the Claude Code processes of this machine, by pid: the session files every config folder holds */
18
+ async function sessionProcs(): Promise<Map<number, SessionProc>> {
19
+ const [{ configDirs }, { everyRecord }] = await Promise.all([import('../agent-time/store.ts'), import('../agent-time/claude-sessions.ts')])
20
+ return new Map(everyRecord(configDirs()).map((r) => [r.pid, { cwd: r.cwd, name: r.name !== '' ? r.name : r.sessionId.slice(0, 8) }]))
21
+ }
22
+
23
+ /** one ps of every process, empty when it cannot run */
24
+ export async function readPs(): Promise<string> {
25
+ try {
26
+ const p = Bun.spawn(['ps', '-Axo', 'pid=,ppid=,%cpu=,args='], { stdout: 'pipe', stderr: 'ignore', env: { ...process.env, LC_ALL: 'C' } })
27
+ const [out, code] = await Promise.all([new Response(p.stdout).text(), p.exited])
28
+ return code === 0 ? out : ''
29
+ } catch {
30
+ return ''
31
+ }
32
+ }
33
+
34
+ /** who uses the CPU now, read with one ps */
35
+ export async function readWho(): Promise<UseGroup[]> {
36
+ const [ps, sessions] = await Promise.all([readPs(), sessionProcs().catch(() => new Map<number, SessionProc>())])
37
+ return whoUses(parsePs(ps), sessions, { home: homedir(), self: process.pid })
38
+ }
39
+
40
+ /** the machine as the gate reads it: the 1 minute load alone while it is under FULL_FACTOR times the cores, else the
41
+ * cores in use (the daemon's smoothed reading when fresh, else the ps sum) and who uses them */
42
+ export async function lookNow(): Promise<Look> {
43
+ if (process.env['SHIPKIT_MACHINE_LOAD'] != null) {
44
+ const { machineLoad } = await import('../core/machine-read.ts')
45
+ const m = machineLoad()
46
+ return { m, groups: isFull(m) ? await readWho() : null }
47
+ }
48
+ const cores = availableParallelism()
49
+ const load1 = loadavg()[0] ?? 0
50
+ if (load1 <= FULL_FACTOR * cores) return { m: { load1, cores }, groups: null }
51
+ const groups = await readWho()
52
+ let busy: number | null = null
53
+ try {
54
+ const { homeStateFile, readPublished } = await import('../core/machine-read.ts')
55
+ const file = homeStateFile('machine-busy.json')
56
+ busy = file == null ? null : readPublished(file, cores)
57
+ } catch { /* no home: the ps sum */ }
58
+ busy ??= Math.min(cores, groups.reduce((s, g) => s + g.cpu, 0) / 100)
59
+ return { m: { load1, cores, busy }, groups }
60
+ }
61
+
62
+ const readJson = <T>(file: string, empty: T): T => {
63
+ try { return JSON.parse(readFileSync(file, 'utf8')) as T } catch { return empty }
64
+ }
65
+
66
+ /** the memo of the last wait that reached its bound: who held the CPU then, in the home dir */
67
+ async function memoFile(): Promise<AdmitMemo | null> {
68
+ const [{ homeStateFile }, { atomicWrite }] = await Promise.all([import('../core/machine-read.ts'), import('../core/locked-write.ts')])
69
+ const file = homeStateFile('admission-over.json')
70
+ if (file == null) return null
71
+ return {
72
+ read: () => readJson<{ top?: unknown }>(file, {}).top as string | null ?? null,
73
+ write: (top) => {
74
+ if (top === (readJson<{ top?: unknown }>(file, {}).top ?? null)) return
75
+ try { atomicWrite(file, JSON.stringify({ top, at: Date.now() })) } catch { /* a read only home: every wait is a first one */ }
76
+ },
77
+ }
78
+ }
79
+
80
+ /** a still now from the command that runs it (this process's parent): true once it is the SHOT_LOOP_COUNT-th inside
81
+ * SHOT_LOOP_MS. Recorded only on a full machine, the one place the count is read */
82
+ export async function shotLoop(parent: number, now = Date.now()): Promise<boolean> {
83
+ const [{ homeStateFile }, { atomicWrite }] = await Promise.all([import('../core/machine-read.ts'), import('../core/locked-write.ts')])
84
+ const file = homeStateFile('admission-shots.json')
85
+ if (file == null) return false
86
+ const key = String(parent)
87
+ const all = readJson<Record<string, number[]>>(file, {})
88
+ const mine = [...(all[key] ?? []).filter((t) => now - t < SHOT_LOOP_MS), now]
89
+ const kept: Record<string, number[]> = { [key]: mine }
90
+ for (const [k, ts] of Object.entries(all)) if (k !== key && ts.some((t) => now - t < SHOT_LOOP_MS)) kept[k] = ts
91
+ try { atomicWrite(file, JSON.stringify(kept)) } catch { /* a read only home: no loop is seen */ }
92
+ return mine.length >= SHOT_LOOP_COUNT
93
+ }
94
+
95
+ /** the nearest folder at or above `from` holding a repo.config.ts */
96
+ function configRoot(from: string): string | null {
97
+ for (let d = resolve(from); ; d = dirname(d)) {
98
+ try { readFileSync(join(d, 'repo.config.ts')); return d } catch { /* go up */ }
99
+ if (dirname(d) === d) return null
100
+ }
101
+ }
102
+
103
+ const stderrSay = (l: string): void => void process.stderr.write(`${l}\n`)
104
+
105
+ /** a process a check started runs on its parent's admission; CI and a zero bound never wait */
106
+ const exempt = (): boolean => process.env['CI'] != null || process.env[SLOT_HELD_ENV] === '1' || boundMs() === 0
107
+
108
+ /** wait for room once the first look found the machine full, the memo read and written */
109
+ async function waitFor(what: string, first: Look, say: (l: string) => void): Promise<void> {
110
+ let seen = false
111
+ const memo = await memoFile().catch(() => null)
112
+ await admit(what, { look: async () => (seen ? lookNow() : ((seen = true), first)), now: () => Date.now(), sleep: (ms) => Bun.sleep(ms), say, boundMs: boundMs(), ...(memo != null ? { memo } : {}) })
113
+ }
114
+
115
+ /** THE ENTRY every sk command passes: a heavy line on a full machine waits (admit); anything else returns at once.
116
+ * Never throws: a gate that breaks warns and lets the command run */
117
+ export async function admitLine(argv: readonly string[], cwd: string, say: (l: string) => void = stderrSay): Promise<void> {
118
+ try {
119
+ if (argv.includes('--help') || argv.includes('-h') || exempt()) return
120
+ const first = await lookNow()
121
+ if (!isFull(first.m)) return
122
+ let what = builtInHeavy(argv)
123
+ if (what == null && argv[0] !== 'ci') {
124
+ const root = configRoot(cwd)
125
+ if (root == null) return
126
+ const { loadRepoConfig } = await import('../repo-config.ts')
127
+ what = declaredHeavy(argv, (await loadRepoConfig(root)).heavy ?? [])
128
+ }
129
+ if (what == null) return
130
+ if (what === 'shot-still') {
131
+ if (!(await shotLoop(process.ppid))) return
132
+ what = 'a loop of sk shot'
133
+ }
134
+ await waitFor(what, first, say)
135
+ } catch (e) {
136
+ say(`WARN the admission gate broke, the command runs: ${e instanceof Error ? e.message : String(e)}`)
137
+ }
138
+ }
139
+
140
+ /** an asked gate's admission, before its first heavy check that misses the cache (check-runner.ts beforeHeavy):
141
+ * a gate whose every answer is cached never waits. Never throws */
142
+ export async function admitCheck(id: string, say: (l: string) => void): Promise<void> {
143
+ try {
144
+ if (exempt()) return
145
+ const first = await lookNow()
146
+ if (isFull(first.m)) await waitFor(`the gate's ${id}`, first, say)
147
+ } catch (e) {
148
+ say(`WARN the admission gate broke, the gate runs: ${e instanceof Error ? e.message : String(e)}`)
149
+ }
150
+ }
@@ -30,6 +30,7 @@
30
30
  // status, whether it replayed, whether it can block, what it cost.
31
31
  import { closeSync, existsSync, mkdirSync, openSync, writeSync } from 'fs'
32
32
  import { basename, isAbsolute, join, relative } from 'path'
33
+ import { heavyCheck } from '../core/admission.ts'
33
34
  import { shareRun } from '../core/attach.ts'
34
35
  import { CheckCtx } from '../core/check-ctx.ts'
35
36
  import { CheckPass } from '../core/check-pass.ts'
@@ -167,6 +168,9 @@ export type CheckEvent = {
167
168
  export type Audience = 'gate' | 'health'
168
169
 
169
170
  export type RunChecksOpts = {
171
+ /** awaited once, before the body of the first heavy check (core/admission.ts heavyCheck): a replay, an attached
172
+ * answer and a light check never wait on it */
173
+ beforeHeavy?: (id: string) => Promise<void>
170
174
  checks: RunnableCheck[]
171
175
  root: string
172
176
  config: CheckEnv['config']
@@ -819,6 +823,7 @@ export async function runChecks(o: RunChecksOpts): Promise<RunChecksSummary> {
819
823
  /** ONE measurement per in flight question: an asker whose exact key
820
824
  * another run is measuring right now waits for that answer instead of
821
825
  * running the tool a second time (core/attach.ts) */
826
+ let admitted: Promise<void> | null = null
822
827
  const measureShared = async (u: Live): Promise<void> => {
823
828
  const slot = o.ledger?.attachSlot(u.id) ?? null
824
829
  if (slot == null) return await measureAndKeep(u)
@@ -841,6 +846,7 @@ export async function runChecks(o: RunChecksOpts): Promise<RunChecksSummary> {
841
846
  const measureAndKeep = async (u: Live): Promise<void> => {
842
847
  // a machine slot for the body, and only the body: a replay or an
843
848
  // attached wait runs nothing, so it holds none
849
+ if (o.beforeHeavy != null && heavyCheck(u.id)) await (admitted ??= o.beforeHeavy(u.id))
844
850
  const who = { repo: o.config.name, check: u.id }
845
851
  const queue = pool != null && !isShort(u)
846
852
  if (queue) { waitMark(); wait.waiting++ }
@@ -248,12 +248,14 @@ function derivedRuns(o: { gate: boolean; build: boolean; inputs?: string[]; ttl?
248
248
  }
249
249
 
250
250
  /** the cache half of a check file, as the key layer reads it */
251
- function declOfCache(cache: CacheDecl, env: CheckEnv): { inputs?: string[]; optional?: string[]; ttl?: string; never?: string; key?: string; reads?: boolean } {
251
+ function declOfCache(cache: CacheDecl, env: CheckEnv, off: string | null): { inputs?: string[]; optional?: string[]; ttl?: string; never?: string; key?: string; reads?: boolean } {
252
+ // a check that is off answers its reason, whatever its key would read: none is computed
253
+ const key = off == null && 'key' in cache ? cache.key?.(env) : undefined
252
254
  switch (cache.by) {
253
- case 'files': return { inputs: cache.inputs, optional: cache.optional, key: cache.key?.(env) }
255
+ case 'files': return { inputs: cache.inputs, optional: cache.optional, key }
254
256
  case 'reads': return { reads: true }
255
- case 'ttl': return { ttl: cache.span, key: cache.key?.(env) }
256
- case 'fact': return { ttl: FOREVER, key: cache.key(env) }
257
+ case 'ttl': return { ttl: cache.span, key }
258
+ case 'fact': return { ttl: FOREVER, key }
257
259
  case 'never': return { never: cache.why }
258
260
  }
259
261
  }
@@ -404,7 +406,7 @@ export async function composeChecks(root: string, c: RepoConfig, o: ComposeOpts
404
406
  for (const u of checks) {
405
407
  if (++n % COMPOSE_STEP === 0) await yieldLoop()
406
408
  const runs = fileRuns(u.def, u.id, c, env, foreign)
407
- const cache = declOfCache(u.def.cache, env)
409
+ const cache = declOfCache(u.def.cache, env, runs.off)
408
410
  // a body keyed on what it reads through its context (git-key.ts
409
411
  // READS). The tier is part of that question: a body can read the env,
410
412
  // and a quick answer must never stand in for a full one. Any module
@@ -28,7 +28,7 @@ import { OWN_LIB } from '../core/last-good.ts'
28
28
  import type { CiOpts } from './run-ci.ts'
29
29
 
30
30
  /** the options a working gate passes on to the gate of HEAD: what selects and shows checks, never what repairs */
31
- export type HeadGateOpts = Pick<CiOpts, 'bail' | 'json' | 'skipGroups' | 'withIds' | 'onlyIds' | 'fresh' | 'tests' | 'verbose'> & { print: (l: string) => void }
31
+ export type HeadGateOpts = Pick<CiOpts, 'admit' | 'bail' | 'json' | 'skipGroups' | 'withIds' | 'onlyIds' | 'fresh' | 'tests' | 'verbose'> & { print: (l: string) => void }
32
32
 
33
33
  /** the toolkit that runs the checks: its cli, and where it comes from in words */
34
34
  export type Kit = { cli: string; from: string }