rvlib-shipkit 2.32.0 → 2.33.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 (54) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/package.json +1 -1
  3. package/src/advisors/advisor-view.ts +28 -7
  4. package/src/advisors/edge/api.ts +1 -30
  5. package/src/advisors/project.ts +3 -3
  6. package/src/advisors/sync.ts +7 -3
  7. package/src/advisors/users-router.ts +13 -11
  8. package/src/cli/cmd_Capacity.ts +6 -2
  9. package/src/cli/cmd_Ci.ts +2 -1
  10. package/src/cli/cmd_Shot.ts +26 -4
  11. package/src/cli.ts +13 -2
  12. package/src/core/admission.ts +268 -0
  13. package/src/core/code-lines.ts +36 -21
  14. package/src/core/machine-read.ts +5 -2
  15. package/src/core/peer-sk.ts +8 -0
  16. package/src/gate/admit-heavy.ts +150 -0
  17. package/src/gate/check-runner.ts +6 -0
  18. package/src/gate/head-gate.ts +1 -1
  19. package/src/gate/job-run.ts +2 -1
  20. package/src/gate/pre-commit-discovery.ts +6 -3
  21. package/src/gate/run-check.ts +3 -0
  22. package/src/gate/run-ci.ts +4 -0
  23. package/src/home/run-daemon.ts +3 -1
  24. package/src/hooks/commit-msg-run.ts +61 -0
  25. package/src/hooks/commit-run.ts +16 -166
  26. package/src/hooks/gate-outcome.ts +108 -0
  27. package/src/hooks/git-hook.ts +9 -9
  28. package/src/hooks/hook-config.ts +2 -1
  29. package/src/hooks/pre-commit-checks.ts +1 -1
  30. package/src/hooks/run-hooks.ts +2 -1
  31. package/src/hooks/shared-file.ts +3 -2
  32. package/src/plan/planner.ts +3 -2
  33. package/src/repo-config.ts +8 -1
  34. package/src/review/answer-kinds.ts +2 -0
  35. package/src/review/cells.ts +34 -7
  36. package/src/review/format.ts +1 -1
  37. package/src/review/model.ts +3 -3
  38. package/src/review/routes.ts +2 -28
  39. package/src/review/store-parties.ts +28 -0
  40. package/src/review/store.ts +9 -1
  41. package/src/review/thread-state.ts +9 -3
  42. package/src/secrets/copy.ts +4 -4
  43. package/src/serve/hub-app/dock-st.ts +1 -1
  44. package/src/serve/hub-app/review/question-views.tsx +28 -17
  45. package/src/serve/hub-app/review/review-host.ts +6 -2
  46. package/src/serve/hub-app/review/review-list.tsx +8 -5
  47. package/src/serve/hub-app/review/review-st.ts +2 -2
  48. package/src/serve/hub-app/review/review-views.tsx +10 -7
  49. package/src/serve/hub-app/review/thread-st.ts +17 -9
  50. package/src/serve/hub-app/review/tone-bar.tsx +27 -24
  51. package/src/serve/hub-app/review/tones.ts +18 -0
  52. package/src/serve/hub-app/review.css +11 -2
  53. package/src/shot/client.ts +2 -1
  54. package/src/shot/on-place.ts +141 -0
@@ -6,6 +6,8 @@
6
6
  // it runs with no bun watch and an edit of its own code restarts it in place
7
7
  // at once (lib-watch.ts): the new image follows the jobs still running. The
8
8
  // machine resources are pm's.
9
+ import { topUserWatch } from '../core/admission.ts'
10
+ import { readWho } from '../gate/admit-heavy.ts'
9
11
  import { loopWatch } from '../core/loop-watch.ts'
10
12
  import { MemoryWatch } from '../core/memory-watch.ts'
11
13
  import { fileURLToPath } from 'url'
@@ -120,7 +122,7 @@ export async function runDaemon(root: string, io: HomeIo, o: { port?: number } =
120
122
  const dir = homeDir()
121
123
  // the machine's one plan: every repo and check pair, ticked by the daemon.
122
124
  // Its catch up window lives in the machine db, so a restart in place keeps it
123
- const plan = new Planner({ catchUp: machineCatchUp, onError: (repo, e) => io.printErr(`WARN the plan of ${repo} broke: ${e.message}`) })
125
+ const plan = new Planner({ catchUp: machineCatchUp, who: topUserWatch(readWho), onError: (repo, e) => io.printErr(`WARN the plan of ${repo} broke: ${e.message}`) })
124
126
  // a repo's colour counts only the checks its plan holds today
125
127
  // a page asked of a repo's own app: said on the pages' stream, which exists once the daemon serves
126
128
  let askedPage: (repo: string) => void = () => {}
@@ -0,0 +1,61 @@
1
+ // the commit-msg gate: the shared message predicate, the leak guard on the message, the reflection trailers, then the
2
+ // repo's own. Apart from the pre-commit gates (hooks/commit-run.ts), so the commit-msg hook loads only these.
3
+ // the one constraint a reader breaks first: the hook has 20 ms from bun's start (hooks/hook-gates.ts)
4
+ import { readFileSync } from 'fs'
5
+ import { commitMessageOffenses, stripNonMessage } from './commit-message.ts'
6
+ import { runLeakGuard } from './leak-guard.ts'
7
+ import { hookGateOff } from './hook-gates.ts'
8
+ import { commandGate, hitLine, moduleGate, startTimes, timeRow, waivedLines, type GateOutcome, type Timed } from './gate-outcome.ts'
9
+ import type { HookConfig } from './hook-config.ts'
10
+
11
+ /** what a repo's commit-msg module gate is given */
12
+ export type CommitMsgCtx = { root: string; message: string; messageFile: string; config: HookConfig }
13
+
14
+ export async function runCommitMsgWith(root: string, config: HookConfig, messageFile: string, o: { since?: number; before?: Timed[] } = {}): Promise<GateOutcome[]> {
15
+ const since = o.since ?? performance.now()
16
+ const times = startTimes(since, o.before)
17
+ const h = config.hooks ?? {}
18
+ const out: GateOutcome[] = []
19
+ const message = readFileSync(messageFile, 'utf8')
20
+ if (hookGateOff(config, 'commit-message') == null) {
21
+ const languageOff = hookGateOff(config, 'commit-language') != null
22
+ const offenses = commitMessageOffenses(message, { languageAllow: h.languageAllow })
23
+ .filter((o) => o.kind !== 'language' || !languageOff)
24
+ out.push(offenses.length === 0
25
+ ? { id: 'commit-message', ok: true, lines: [`ok: commit message clean (no dash punctuation${languageOff ? '' : ', English'})`] }
26
+ : {
27
+ id: 'commit-message',
28
+ ok: false,
29
+ lines: [
30
+ `FAIL: commit message has ${offenses.length} offense(s)`,
31
+ ...offenses.map((o) => ` line ${o.line}: ${o.text.slice(0, 100)}\n ${o.why}`),
32
+ ],
33
+ })
34
+ }
35
+ // the leak guard also reads the MESSAGE, a private name pasted into a
36
+ // commit body is as public as one pasted into a file
37
+ if (hookGateOff(config, 'leak-guard') == null) {
38
+ const r = runLeakGuard(root, { keywordFile: h.keywordFile, staged: false, allow: h.leakAllow, text: [{ label: 'commit message', content: message }] })
39
+ if (r.status === 'hit')
40
+ out.push({ id: 'leak-guard', ok: false, lines: [`FAIL: leak-guard matched in the commit message`, ...r.hits.map(hitLine), ...waivedLines(r.waived)] })
41
+ else if (r.status === 'clean' && r.waived.length > 0)
42
+ out.push({ id: 'leak-guard', ok: true, lines: [`ok: leak-guard clean in the commit message (${r.waived.length} waived)`, ...waivedLines(r.waived)] })
43
+ }
44
+ if (hookGateOff(config, 'reflection-trailer') == null && /^(Fixes|Declines)-reflection:/im.test(message)) {
45
+ const t = performance.now()
46
+ const { machinePlaces, trailerErrors } = await import('../reflections/reflection-close.ts')
47
+ const places = await machinePlaces(root)
48
+ const errors = places === null ? ['no house repo on this machine: a reflection closes where its house is'] : trailerErrors(stripNonMessage(message), places)
49
+ out.push(errors.length === 0
50
+ ? { id: 'reflection-trailer', ok: true, lines: ['ok: reflection trailers name open reflections'] }
51
+ : { id: 'reflection-trailer', ok: false, lines: [`FAIL: reflection-trailer: ${errors.length} trailer(s) name no open reflection`, ...errors.map((e) => ` ${e}`)] })
52
+ times.push({ id: 'reflection-trailer', ms: performance.now() - t })
53
+ }
54
+ for (const g of h.commitMsg ?? []) {
55
+ const t = performance.now()
56
+ out.push('module' in g ? await moduleGate<CommitMsgCtx>(root, g, 'commitMsg', { root, message, messageFile, config }) : await commandGate(root, g, [messageFile], 60_000))
57
+ times.push({ id: g.id, ms: performance.now() - t, owner: 'repo' })
58
+ }
59
+ out.push(timeRow('commit-msg', performance.now() - since, times))
60
+ return out
61
+ }
@@ -1,27 +1,23 @@
1
- // the commit gates themselves, run by the commit hooks in ONE process: what the commit stages is read once
2
- // (hooks/staged.ts) and every gate reads that, the built-ins and the repo's own module gates alike.
1
+ // the pre-commit gates, run by the hook in ONE process: what the commit stages is read once (hooks/staged.ts) and
2
+ // every gate reads that, the built-ins and the repo's own module gates alike. The commit-msg gates are
3
+ // hooks/commit-msg-run.ts, what both share hooks/gate-outcome.ts.
3
4
  // the one constraint a reader breaks first: the hook has 20 ms from bun's start (hooks/hook-gates.ts), so this
4
5
  // module loads only what every commit needs; a gate that needs more imports it inside its own branch
5
- import { readFileSync, existsSync } from 'fs'
6
+ import { existsSync } from 'fs'
6
7
  import { join } from 'path'
7
- import { commitMessageOffenses, stripNonMessage } from './commit-message.ts'
8
- import { maskPattern, patternFingerprint, runLeakGuard, type LeakHit, type LeakWaiver } from './leak-guard.ts'
8
+ import { runLeakGuard } from './leak-guard.ts'
9
9
  import { runRootIdentity } from './root-identity.ts'
10
10
  import { BlobReader, patchesByFile, readStagedAsync, type StagedCommit } from './staged.ts'
11
11
  import { ALLOW_MASS_DELETE, runTreeShrink } from './tree-shrink.ts'
12
- import { HOOK_BUDGET_MS, hookGateOff, type HookGateId } from './hook-gates.ts'
12
+ import { hookGateOff, type HookGateId } from './hook-gates.ts'
13
+ import { commandGate, hitLine, importGate, moduleGate, startTimes, timeRow, waivedLines, type GateOutcome, type Timed } from './gate-outcome.ts'
13
14
  import { heavyInCommit } from '../social/media-limit.ts'
14
15
  import { LAYOUT } from '../core/layout.ts'
15
16
  import { gitRoot } from '../core/git-root.ts'
16
17
  import type { HookConfig } from './hook-config.ts'
17
18
  import type { RepoConfig } from '../repo-config.ts'
18
19
 
19
- /** `ms`: set on the hook's own time row (`hook-time`), which `report` folds into its last line */
20
- export type GateOutcome = { id: string; ok: boolean; lines: string[]; ms?: number }
21
-
22
- /** what a repo's module gate answers: `ok` false refuses the commit, and `lines` are printed when it fails or say
23
- * something other than `ok:` */
24
- export type GateVerdict = { ok: boolean; lines: string[] }
20
+ export { report, type GateOutcome, type GateVerdict, type Timed } from './gate-outcome.ts'
25
21
 
26
22
  /** what a repo's pre-commit module gate is given: the commit's one staged read, and reads of it that cost no spawn or
27
23
  * one for all their blobs */
@@ -39,35 +35,6 @@ export type PreCommitCtx = {
39
35
  config: HookConfig
40
36
  }
41
37
 
42
- /** what a repo's commit-msg module gate is given */
43
- export type CommitMsgCtx = { root: string; message: string; messageFile: string; config: HookConfig }
44
-
45
- /** a repo module gate: `module` names a file relative to the repo root that exports `preCommit` (or `commitMsg`) */
46
- type ModuleGate = { id: string; module: string }
47
-
48
- /** a hit line: the masked pattern plus its FINGERPRINT, which is the token a
49
- * waiver is written against, so nobody has to type the private word to
50
- * exempt it. The file rides along for a content hit; a staged-PATH hit adds
51
- * nothing, because there the path IS what matched. */
52
- const hitLine = (x: LeakHit): string =>
53
- ` ${x.where}${x.where === 'staged content' && x.file != null ? ` ${x.file}` : ''}: ${maskPattern(x.pattern)} [${patternFingerprint(x.pattern)}]${x.over == null ? '' : `, ${x.over.found} added where ${x.over.source} allows ${x.over.count}`}`
54
-
55
- /** what the allowlist let through, one line per waiver. An allowlist that
56
- * fires invisibly is a silent weakening, so a waived match is as loud as a
57
- * blocked one and carries the reason its author wrote. */
58
- function waivedLines(waived: LeakWaiver[]): string[] {
59
- const rows = new Map<string, { pattern: string; reason: string; source: string; targets: Set<string> }>()
60
- for (const w of waived) {
61
- const key = `${w.pattern} ${w.source}`
62
- const row = rows.get(key) ?? { pattern: w.pattern, reason: w.reason, source: w.source, targets: new Set<string>() }
63
- row.targets.add(w.file ?? w.where)
64
- rows.set(key, row)
65
- }
66
- return [...rows.values()].map(
67
- (r) => ` waived ${maskPattern(r.pattern)} [${patternFingerprint(r.pattern)}] in ${r.targets.size} target(s) — ${r.reason} (${r.source})`,
68
- )
69
- }
70
-
71
38
  export const COMFY_DRAFTS = '.comfy-ts/drafts/'
72
39
 
73
40
  /** the staged files the `blocked-paths` gate refuses. A repo DECLARED private
@@ -84,65 +51,6 @@ export const draftsOpen = (c: Pick<HookConfig, 'visibility'>): boolean => c.visi
84
51
 
85
52
  const REPLAY_MARKERS = ['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'rebase-merge', 'rebase-apply']
86
53
 
87
- /** a gate's time, in ms. `owner`: who may make it cheaper or move it out of the hook: the repo (its own gate, a
88
- * check that declares onPreCommit), `once` for what is read again once after its file changed (the check table,
89
- * the config), or no one (a built-in commit gate, the process start, the staged read) */
90
- export type Timed = { id: string; ms: number; owner?: 'repo' | 'once' }
91
-
92
- /** what ran before the gates, named where the caller timed it (the imports, the config read), the rest as `start` */
93
- function startTimes(since: number, before: Timed[] = []): Timed[] {
94
- const rest = performance.now() - since - before.reduce((a, t) => a + t.ms, 0)
95
- return [...before, ...(rest >= 1 ? [{ id: 'start', ms: rest }] : [])]
96
- }
97
-
98
- /** what to do about a hook over its budget, from its slowest items. Only a gate the repo owns is ever sent out of the
99
- * hook: a built-in (the leak guard first) never leaves it, whatever it costs */
100
- function overBudget(slowest: readonly Timed[]): string {
101
- const repo = slowest.find((t) => t.owner === 'repo')
102
- if (repo != null) return `make ${repo.id} cheaper, or move it to a ci task`
103
- if (slowest[0]?.owner === 'once') return `${slowest[0].id} was read again after its file changed: once, the next commit is back under it`
104
- return 'built-in gates never leave the hook: a large commit or a busy machine costs this, nothing is to move'
105
- }
106
-
107
- /** set it to print every gate's time on each commit */
108
- export const HOOK_TIMES = 'SHIPKIT_HOOK_TIMES'
109
-
110
- /** the hook's own time row: over the budget it WARNs naming the slowest gates, and `SHIPKIT_HOOK_TIMES=1` prints them
111
- * all. `start` is what ran before the gates: the process start, the imports, the config read */
112
- function timeRow(hook: string, elapsed: number, times: Timed[]): GateOutcome {
113
- const words = (ts: Timed[]): string => ts.map((t) => `${t.id} ${Math.round(t.ms)}ms`).join(', ')
114
- const lines: string[] = []
115
- if (elapsed > HOOK_BUDGET_MS) {
116
- const slowest = [...times].sort((a, b) => b.ms - a.ms).slice(0, 3)
117
- lines.push(`WARN ${hook} took ${Math.round(elapsed)}ms (budget ${HOOK_BUDGET_MS}ms), slowest: ${words(slowest)}: ${overBudget(slowest)} (tools/shipkit/commit-gates.md)`)
118
- }
119
- if (process.env[HOOK_TIMES] === '1') lines.push(` ${hook} times: ${words(times)}`)
120
- return { id: 'hook-time', ok: true, lines, ms: elapsed }
121
- }
122
-
123
- const failLines = (e: unknown): string[] => [` ${String(e instanceof Error ? e.message : e).split('\n')[0]!.slice(0, 300)}`]
124
-
125
- /** a module gate's file, imported; `loading`: its import already started (the hook starts it while git reads) */
126
- const importGate = (root: string, g: ModuleGate): Promise<Record<string, unknown>> => import(join(root, g.module)) as Promise<Record<string, unknown>>
127
-
128
- async function moduleGate<C>(root: string, g: ModuleGate, name: 'preCommit' | 'commitMsg', ctx: C, loading = importGate(root, g)): Promise<GateOutcome> {
129
- try {
130
- const mod = await loading
131
- const run = mod[name]
132
- if (typeof run !== 'function') return { id: g.id, ok: false, lines: [`FAIL: ${g.id}: ${g.module} exports no \`${name}\` function`] }
133
- const v = (await (run as (c: C) => GateVerdict | Promise<GateVerdict>)(ctx)) as GateVerdict
134
- return { id: g.id, ok: v.ok, lines: v.ok ? (v.lines.length === 0 ? [`ok: ${g.id}`] : v.lines) : [`FAIL: ${g.id}`, ...v.lines] }
135
- } catch (e) {
136
- return { id: g.id, ok: false, lines: [`FAIL: ${g.id} threw, so it judged nothing`, ...failLines(e)] }
137
- }
138
- }
139
-
140
- async function commandGate(root: string, g: { id: string; cmd: string[] }, extra: string[], timeoutMs: number): Promise<GateOutcome> {
141
- const { spawnWithTimeout } = await import('../core/spawn-timeout.ts')
142
- const r = await spawnWithTimeout([...g.cmd, ...extra], { cwd: root, timeoutMs })
143
- return { id: g.id, ok: r.code === 0, lines: r.code === 0 ? [`ok: ${g.id}`] : [`FAIL: ${g.id} (exit ${r.code})`, ...r.out.trim().split('\n').slice(-30).map((l) => ` ${l}`)] }
144
- }
145
-
146
54
  /** a promise whose rejection is seen where it is awaited, never as an unhandled one while other work runs first */
147
55
  const later = <T>(p: Promise<T>): Promise<T> => {
148
56
  p.catch(() => {})
@@ -171,7 +79,9 @@ export async function runPreCommitWith(root: string, config: HookConfig, full: (
171
79
  // only an agent's shell carries CLAUDECODE, and the shared-file gate judges nothing else: its module loads only then
172
80
  const agent = !off('shared-file') && process.env['CLAUDECODE'] === '1'
173
81
  const sharedModule = agent ? later(import('./shared-file.ts')) : null
174
- const checks = later(timed('checks at commit', () => runPreCommitChecks(root, config, full)))
82
+ // the table's module loads while git reads; its answer needs the staged names, and its time is its own
83
+ const discovery = later(import('../gate/pre-commit-discovery.ts'))
84
+ const checks = later(reading.catch(() => null).then((read) => timed('checks at commit', () => runPreCommitChecks(root, config, full, discovery, read?.names))))
175
85
  // the shared-file gate's reads that need no staged path, while git reads; an error is the gate's to report
176
86
  const prepared = sharedModule == null ? null : await timed('shared-file read', async () => {
177
87
  try {
@@ -339,11 +249,11 @@ export async function runPreCommitWith(root: string, config: HookConfig, full: (
339
249
  /** every `onPreCommit` check, run RAW on the working tree: no ledger, no
340
250
  * cache, no repair. A failure refuses the commit, a pass over its budget
341
251
  * warns by name and never blocks on time. The table answers « none » with
342
- * stats alone (gate/pre-commit-discovery.ts), and the check engine loads only
343
- * when one runs */
344
- async function runPreCommitChecks(root: string, config: HookConfig, full: () => Promise<RepoConfig>): Promise<{ outcomes: GateOutcome[]; table: TableState }> {
345
- const { declarationsTable, preCommitFromTable } = await import('../gate/pre-commit-discovery.ts')
346
- const known = await preCommitFromTable(root)
252
+ * stats alone (gate/pre-commit-discovery.ts), its walk read again only when the
253
+ * commit stages a unit file, and the check engine loads only when one runs */
254
+ async function runPreCommitChecks(root: string, config: HookConfig, full: () => Promise<RepoConfig>, discovery: Promise<typeof import('../gate/pre-commit-discovery.ts')>, names?: readonly string[]): Promise<{ outcomes: GateOutcome[]; table: TableState }> {
255
+ const { declarationsTable, preCommitFromTable } = await discovery
256
+ const known = await preCommitFromTable(root, names)
347
257
  if (known?.length === 0) return { outcomes: [], table: 'answered' }
348
258
  const { runPreCommitChecksFull } = await import('./pre-commit-checks.ts')
349
259
  const { outcomes, settled } = await runPreCommitChecksFull(root, config, full)
@@ -358,63 +268,3 @@ async function runPreCommitChecks(root: string, config: HookConfig, full: () =>
358
268
  /** how the check table answered: from stats alone, rebuilt once and answering the next commit, or rebuilt and still
359
269
  * unable to answer it (every commit pays the discovery) */
360
270
  type TableState = 'answered' | 'rebuilt' | 'unsettled'
361
-
362
- /** the commit-msg gate: the shared message predicate, then the repo's own. */
363
- export async function runCommitMsgWith(root: string, config: HookConfig, messageFile: string, o: { since?: number; before?: Timed[] } = {}): Promise<GateOutcome[]> {
364
- const since = o.since ?? performance.now()
365
- const times = startTimes(since, o.before)
366
- const h = config.hooks ?? {}
367
- const out: GateOutcome[] = []
368
- const message = readFileSync(messageFile, 'utf8')
369
- if (hookGateOff(config, 'commit-message') == null) {
370
- const languageOff = hookGateOff(config, 'commit-language') != null
371
- const offenses = commitMessageOffenses(message, { languageAllow: h.languageAllow })
372
- .filter((o) => o.kind !== 'language' || !languageOff)
373
- out.push(offenses.length === 0
374
- ? { id: 'commit-message', ok: true, lines: [`ok: commit message clean (no dash punctuation${languageOff ? '' : ', English'})`] }
375
- : {
376
- id: 'commit-message',
377
- ok: false,
378
- lines: [
379
- `FAIL: commit message has ${offenses.length} offense(s)`,
380
- ...offenses.map((o) => ` line ${o.line}: ${o.text.slice(0, 100)}\n ${o.why}`),
381
- ],
382
- })
383
- }
384
- // the leak guard also reads the MESSAGE, a private name pasted into a
385
- // commit body is as public as one pasted into a file
386
- if (hookGateOff(config, 'leak-guard') == null) {
387
- const r = runLeakGuard(root, { keywordFile: h.keywordFile, staged: false, allow: h.leakAllow, text: [{ label: 'commit message', content: message }] })
388
- if (r.status === 'hit')
389
- out.push({ id: 'leak-guard', ok: false, lines: [`FAIL: leak-guard matched in the commit message`, ...r.hits.map(hitLine), ...waivedLines(r.waived)] })
390
- else if (r.status === 'clean' && r.waived.length > 0)
391
- out.push({ id: 'leak-guard', ok: true, lines: [`ok: leak-guard clean in the commit message (${r.waived.length} waived)`, ...waivedLines(r.waived)] })
392
- }
393
- if (hookGateOff(config, 'reflection-trailer') == null && /^(Fixes|Declines)-reflection:/im.test(message)) {
394
- const t = performance.now()
395
- const { machinePlaces, trailerErrors } = await import('../reflections/reflection-close.ts')
396
- const places = await machinePlaces(root)
397
- const errors = places === null ? ['no house repo on this machine: a reflection closes where its house is'] : trailerErrors(stripNonMessage(message), places)
398
- out.push(errors.length === 0
399
- ? { id: 'reflection-trailer', ok: true, lines: ['ok: reflection trailers name open reflections'] }
400
- : { id: 'reflection-trailer', ok: false, lines: [`FAIL: reflection-trailer: ${errors.length} trailer(s) name no open reflection`, ...errors.map((e) => ` ${e}`)] })
401
- times.push({ id: 'reflection-trailer', ms: performance.now() - t })
402
- }
403
- for (const g of h.commitMsg ?? []) {
404
- const t = performance.now()
405
- out.push('module' in g ? await moduleGate<CommitMsgCtx>(root, g, 'commitMsg', { root, message, messageFile, config }) : await commandGate(root, g, [messageFile], 60_000))
406
- times.push({ id: g.id, ms: performance.now() - t, owner: 'repo' })
407
- }
408
- out.push(timeRow('commit-msg', performance.now() - since, times))
409
- return out
410
- }
411
-
412
- /** a gate that passed prints only what still needs a reader (a WARN, a waived
413
- * hit), so a clean commit costs one line, not one per gate */
414
- export const report = (out: GateOutcome[], write: (s: string) => void): number => {
415
- for (const g of out) for (const l of g.lines) if (!g.ok || !l.startsWith('ok: ')) write(`${l}\n`)
416
- const ok = out.every((g) => g.ok)
417
- const time = out.find((g) => g.id === 'hook-time')?.ms
418
- if (ok) write(`ok: ${out.filter((g) => g.id !== 'hook-time').length} commit gate(s) clean${time == null ? '' : ` in ${Math.round(time)}ms`}\n`)
419
- return ok ? 0 : 1
420
- }
@@ -0,0 +1,108 @@
1
+ // what both commit hooks share: a gate's outcome and its lines, the hook's time row, a repo's own gate run, and the
2
+ // report. Its own module so the commit-msg hook loads none of the pre-commit gates (hooks/commit-msg-run.ts).
3
+ // the one constraint a reader breaks first: every import here is paid by both hooks on every commit
4
+ import { join } from 'path'
5
+ import { maskPattern, patternFingerprint, type LeakHit, type LeakWaiver } from './leak-guard.ts'
6
+ import { HOOK_BUDGET_MS } from './hook-gates.ts'
7
+
8
+ /** `ms`: set on the hook's own time row (`hook-time`), which `report` folds into its last line */
9
+ export type GateOutcome = { id: string; ok: boolean; lines: string[]; ms?: number }
10
+
11
+ /** what a repo's module gate answers: `ok` false refuses the commit, and `lines` are printed when it fails or say
12
+ * something other than `ok:` */
13
+ export type GateVerdict = { ok: boolean; lines: string[] }
14
+
15
+ /** a repo module gate: `module` names a file relative to the repo root that exports `preCommit` (or `commitMsg`) */
16
+ export type ModuleGate = { id: string; module: string }
17
+
18
+ /** a gate's time, in ms. `owner`: who may make it cheaper or move it out of the hook: the repo (its own gate, a
19
+ * check that declares onPreCommit), `once` for what is read again once after its file changed (the check table,
20
+ * the config), or no one (a built-in commit gate, the process start, the staged read) */
21
+ export type Timed = { id: string; ms: number; owner?: 'repo' | 'once' }
22
+
23
+ /** a hit line: the masked pattern plus its FINGERPRINT, which is the token a
24
+ * waiver is written against, so nobody has to type the private word to
25
+ * exempt it. The file rides along for a content hit; a staged-PATH hit adds
26
+ * nothing, because there the path IS what matched. */
27
+ export const hitLine = (x: LeakHit): string =>
28
+ ` ${x.where}${x.where === 'staged content' && x.file != null ? ` ${x.file}` : ''}: ${maskPattern(x.pattern)} [${patternFingerprint(x.pattern)}]${x.over == null ? '' : `, ${x.over.found} added where ${x.over.source} allows ${x.over.count}`}`
29
+
30
+ /** what the allowlist let through, one line per waiver. An allowlist that
31
+ * fires invisibly is a silent weakening, so a waived match is as loud as a
32
+ * blocked one and carries the reason its author wrote. */
33
+ export function waivedLines(waived: LeakWaiver[]): string[] {
34
+ const rows = new Map<string, { pattern: string; reason: string; source: string; targets: Set<string> }>()
35
+ for (const w of waived) {
36
+ const key = `${w.pattern} ${w.source}`
37
+ const row = rows.get(key) ?? { pattern: w.pattern, reason: w.reason, source: w.source, targets: new Set<string>() }
38
+ row.targets.add(w.file ?? w.where)
39
+ rows.set(key, row)
40
+ }
41
+ return [...rows.values()].map(
42
+ (r) => ` waived ${maskPattern(r.pattern)} [${patternFingerprint(r.pattern)}] in ${r.targets.size} target(s) — ${r.reason} (${r.source})`,
43
+ )
44
+ }
45
+
46
+ /** what ran before the gates, named where the caller timed it (the imports, the config read), the rest as `start` */
47
+ export function startTimes(since: number, before: Timed[] = []): Timed[] {
48
+ const rest = performance.now() - since - before.reduce((a, t) => a + t.ms, 0)
49
+ return [...before, ...(rest >= 1 ? [{ id: 'start', ms: rest }] : [])]
50
+ }
51
+
52
+ /** what to do about a hook over its budget, from its slowest items. Only a gate the repo owns is ever sent out of the
53
+ * hook: a built-in (the leak guard first) never leaves it, whatever it costs */
54
+ function overBudget(slowest: readonly Timed[]): string {
55
+ const repo = slowest.find((t) => t.owner === 'repo')
56
+ if (repo != null) return `make ${repo.id} cheaper, or move it to a ci task`
57
+ if (slowest[0]?.owner === 'once') return `${slowest[0].id} was read again after its file changed: once, the next commit is back under it`
58
+ return 'built-in gates never leave the hook: a large commit or a busy machine costs this, nothing is to move'
59
+ }
60
+
61
+ /** set it to print every gate's time on each commit */
62
+ export const HOOK_TIMES = 'SHIPKIT_HOOK_TIMES'
63
+
64
+ /** the hook's own time row: over the budget it WARNs naming the slowest gates, and `SHIPKIT_HOOK_TIMES=1` prints them
65
+ * all. `start` is what ran before the gates: the process start, the imports, the config read */
66
+ export function timeRow(hook: string, elapsed: number, times: Timed[]): GateOutcome {
67
+ const words = (ts: Timed[]): string => ts.map((t) => `${t.id} ${Math.round(t.ms)}ms`).join(', ')
68
+ const lines: string[] = []
69
+ if (elapsed > HOOK_BUDGET_MS) {
70
+ const slowest = [...times].sort((a, b) => b.ms - a.ms).slice(0, 3)
71
+ lines.push(`WARN ${hook} took ${Math.round(elapsed)}ms (budget ${HOOK_BUDGET_MS}ms), slowest: ${words(slowest)}: ${overBudget(slowest)} (tools/shipkit/commit-gates.md)`)
72
+ }
73
+ if (process.env[HOOK_TIMES] === '1') lines.push(` ${hook} times: ${words(times)}`)
74
+ return { id: 'hook-time', ok: true, lines, ms: elapsed }
75
+ }
76
+
77
+ const failLines = (e: unknown): string[] => [` ${String(e instanceof Error ? e.message : e).split('\n')[0]!.slice(0, 300)}`]
78
+
79
+ /** a module gate's file, imported; the hook starts it while git reads */
80
+ export const importGate = (root: string, g: ModuleGate): Promise<Record<string, unknown>> => import(join(root, g.module)) as Promise<Record<string, unknown>>
81
+
82
+ export async function moduleGate<C>(root: string, g: ModuleGate, name: 'preCommit' | 'commitMsg', ctx: C, loading = importGate(root, g)): Promise<GateOutcome> {
83
+ try {
84
+ const mod = await loading
85
+ const run = mod[name]
86
+ if (typeof run !== 'function') return { id: g.id, ok: false, lines: [`FAIL: ${g.id}: ${g.module} exports no \`${name}\` function`] }
87
+ const v = (await (run as (c: C) => GateVerdict | Promise<GateVerdict>)(ctx)) as GateVerdict
88
+ return { id: g.id, ok: v.ok, lines: v.ok ? (v.lines.length === 0 ? [`ok: ${g.id}`] : v.lines) : [`FAIL: ${g.id}`, ...v.lines] }
89
+ } catch (e) {
90
+ return { id: g.id, ok: false, lines: [`FAIL: ${g.id} threw, so it judged nothing`, ...failLines(e)] }
91
+ }
92
+ }
93
+
94
+ export async function commandGate(root: string, g: { id: string; cmd: string[] }, extra: string[], timeoutMs: number): Promise<GateOutcome> {
95
+ const { spawnWithTimeout } = await import('../core/spawn-timeout.ts')
96
+ const r = await spawnWithTimeout([...g.cmd, ...extra], { cwd: root, timeoutMs })
97
+ return { id: g.id, ok: r.code === 0, lines: r.code === 0 ? [`ok: ${g.id}`] : [`FAIL: ${g.id} (exit ${r.code})`, ...r.out.trim().split('\n').slice(-30).map((l) => ` ${l}`)] }
98
+ }
99
+
100
+ /** a gate that passed prints only what still needs a reader (a WARN, a waived
101
+ * hit), so a clean commit costs one line, not one per gate */
102
+ export const report = (out: GateOutcome[], write: (s: string) => void): number => {
103
+ for (const g of out) for (const l of g.lines) if (!g.ok || !l.startsWith('ok: ')) write(`${l}\n`)
104
+ const ok = out.every((g) => g.ok)
105
+ const time = out.find((g) => g.id === 'hook-time')?.ms
106
+ if (ok) write(`ok: ${out.filter((g) => g.id !== 'hook-time').length} commit gate(s) clean${time == null ? '' : ` in ${Math.round(time)}ms`}\n`)
107
+ return ok ? 0 : 1
108
+ }
@@ -6,7 +6,7 @@
6
6
  import { existsSync, realpathSync, writeSync } from 'fs'
7
7
  import { join } from 'path'
8
8
  import { readStagedAsync, STAGED_STDIN, stagedFromStdin } from './staged.ts'
9
- import type { Timed } from './commit-run.ts'
9
+ import type { Timed } from './gate-outcome.ts'
10
10
 
11
11
  // the process start and the static import, before the first line runs
12
12
  const loaded = performance.now()
@@ -24,25 +24,25 @@ async function oneCopy(): Promise<void> {
24
24
  ;(await import('../core/one-lib.ts')).installOneLib()
25
25
  }
26
26
 
27
- /** the gates and the config fields, loaded while git runs; `before`: what that took, for the hook's time line */
28
- async function load() {
27
+ /** one hook's gates and the config fields, loaded while git runs; `before`: what that took, for the hook's time line */
28
+ async function load<G>(gates: () => Promise<G>) {
29
29
  await oneCopy()
30
- const [gates, { loadHookConfig }] = await Promise.all([import('./commit-run.ts'), import('./hook-config.ts')])
30
+ const [g, { loadHookConfig }, { report }] = await Promise.all([gates(), import('./hook-config.ts'), import('./gate-outcome.ts')])
31
31
  const imported = performance.now()
32
32
  const c = await loadHookConfig(root)
33
33
  const before: Timed[] = [{ id: 'boot', ms: loaded }, { id: 'imports', ms: imported - loaded }, c.fromCopy ? { id: 'config', ms: performance.now() - imported } : { id: 'config load', ms: performance.now() - imported, ...(c.wrote ? { owner: 'once' as const } : {}) }]
34
- return { gates, config: c.config, full: c.full, before }
34
+ return { gates: g, report, config: c.config, full: c.full, before }
35
35
  }
36
36
 
37
37
  if (hook === 'pre-commit') {
38
38
  // the hook body pipes git's read in (hooks/run-hooks.ts): git ran while bun started. Run by hand, it reads git itself
39
39
  const staged = file === STAGED_STDIN ? stagedFromStdin(root) : readStagedAsync(root)
40
40
  staged.catch(() => {})
41
- const { gates, config, full, before } = await load()
42
- process.exitCode = gates.report(await gates.runPreCommitWith(root, config, full, { since: 0, before, staged }), write)
41
+ const { gates, report, config, full, before } = await load(() => import('./commit-run.ts'))
42
+ process.exitCode = report(await gates.runPreCommitWith(root, config, full, { since: 0, before, staged }), write)
43
43
  } else if (hook === 'commit-msg' && file != null) {
44
- const { gates, config, before } = await load()
45
- process.exitCode = gates.report(await gates.runCommitMsgWith(root, config, file, { since: 0, before }), write)
44
+ const { gates, report, config, before } = await load(() => import('./commit-msg-run.ts'))
45
+ process.exitCode = report(await gates.runCommitMsgWith(root, config, file, { since: 0, before }), write)
46
46
  } else {
47
47
  console.error(`usage: bun ${import.meta.path} pre-commit | commit-msg <message file>`)
48
48
  process.exitCode = 2
@@ -8,7 +8,6 @@
8
8
  // when repo.config.ts itself changes (or the copy is dropped); a field that is not plain data is never copied, and
9
9
  // such a config is loaded whole on every commit
10
10
  import { mkdirSync, readFileSync } from 'fs'
11
- import { atomicWrite } from '../core/atomic-write.ts'
12
11
  import { dirname, join } from 'path'
13
12
  import { gitRoot } from '../core/git-root.ts'
14
13
  import type { RepoConfig } from '../repo-config.ts'
@@ -93,6 +92,8 @@ export async function loadHookConfig(root: string): Promise<{ config: HookConfig
93
92
  const keys = Object.keys(copies.copies)
94
93
  for (const k of keys.slice(0, Math.max(0, keys.length - COPIES_MAX))) delete copies.copies[k]
95
94
  mkdirSync(dirname(copy), { recursive: true })
95
+ // loaded only here: a commit that reads the copy writes nothing
96
+ const { atomicWrite } = await import('../core/atomic-write.ts')
96
97
  atomicWrite(copy, JSON.stringify(copies))
97
98
  wrote = true
98
99
  } catch {
@@ -9,7 +9,7 @@ import { runCheckBody, type CheckDef } from '../check.ts'
9
9
  import { repoOff } from '../core/when.ts'
10
10
  import { formatLine } from '../core/wire.ts'
11
11
  import type { RepoConfig } from '../repo-config.ts'
12
- import type { GateOutcome } from './commit-run.ts'
12
+ import type { GateOutcome } from './gate-outcome.ts'
13
13
  import type { HookConfig } from './hook-config.ts'
14
14
 
15
15
  /** the checks that declare `onPreCommit` and apply here, with their budget */
@@ -15,7 +15,8 @@ import { FOREIGN_HOOKS, FOREIGN_WHY, isForeign } from '../core/foreign.ts'
15
15
  import type { RepoConfig } from '../repo-config.ts'
16
16
  import { gitBin } from '../core/git-bin.ts'
17
17
  import { HOOK_BUDGET_MS, hookGateOff, type HookGateId } from './hook-gates.ts'
18
- import { blockedStaged, COMFY_DRAFTS, draftsOpen, runCommitMsgWith, runPreCommitWith, type GateOutcome } from './commit-run.ts'
18
+ import { blockedStaged, COMFY_DRAFTS, draftsOpen, runPreCommitWith, type GateOutcome } from './commit-run.ts'
19
+ import { runCommitMsgWith } from './commit-msg-run.ts'
19
20
  import type { PreCommitCheck } from './pre-commit-checks.ts'
20
21
  import { DIFF_FLAGS, STAGED_END, STAGED_STDIN } from './staged.ts'
21
22
 
@@ -10,14 +10,12 @@
10
10
  import { readFileSync, realpathSync, statSync } from 'fs'
11
11
  import { homedir } from 'os'
12
12
  import { basename, dirname, join } from 'path'
13
- import { sessionRecords } from '../agent-time/claude-sessions.ts'
14
13
  import { laneNameOf } from '../agent-time/lane-name.ts'
15
14
  import { gitBin } from '../core/git-bin.ts'
16
15
  import { EDIT_MATCHER, hasEditGuard } from './edit-guard.ts'
17
16
  import { heldNow, markJudged, type Committing } from './held-calls.ts'
18
17
  import type { Staged } from './staged.ts'
19
18
  import { readWrites, seenOf, writerKey, writesByName, type Write, type Writer } from './write-log.ts'
20
- import { pidAlive } from '../core/pid-alive.ts'
21
19
 
22
20
  /** the joint commit two lanes agreed on: the other writers, by the names the refusal prints */
23
21
  export const COMMIT_WITH = 'SHIPKIT_COMMIT_WITH'
@@ -53,6 +51,9 @@ export function writerState(w: Writer, lastNote = 0): WriterState {
53
51
  const transcript = w.tp == null ? null : w.a == null ? w.tp : join(w.tp.replace(/\.jsonl$/, ''), 'subagents', `agent-${w.a}.jsonl`)
54
52
  let heard = lastNote
55
53
  try { if (transcript != null) heard = Math.max(heard, statSync(transcript).mtimeMs) } catch { /* no transcript: its notes date it */ }
54
+ // loaded here, never at the module's import: only a contested file asks it, and a commit with none loads none of it
55
+ const { sessionRecords } = require('../agent-time/claude-sessions.ts') as typeof import('../agent-time/claude-sessions.ts')
56
+ const { pidAlive } = require('../core/pid-alive.ts') as typeof import('../core/pid-alive.ts')
56
57
  const records = sessionRecords(config)
57
58
  if (records.length === 0) return { state: 'unknown', heard }
58
59
  const live = records.filter((r) => r.sessionId === w.s && pidAlive(r.pid))
@@ -166,7 +166,7 @@ export class Planner {
166
166
  * the window it had (catch-up.ts) */
167
167
  private readonly bootAt: number
168
168
 
169
- constructor(private o: { now?: () => number; timers?: PlanTimers; quietMs?: number; maxWaitMs?: number; machine?: () => MachineLoad; catchUp?: CatchUpStore; onError?: (repo: string, e: Error) => void } = {}) {
169
+ constructor(private o: { now?: () => number; timers?: PlanTimers; quietMs?: number; maxWaitMs?: number; machine?: () => MachineLoad; /** the biggest user of the CPU in a few words, named on the held line (core/admission.ts topUserWatch) */ who?: () => string | null; catchUp?: CatchUpStore; onError?: (repo: string, e: Error) => void } = {}) {
170
170
  this.now = o.now ?? Date.now
171
171
  this.catchUp = o.catchUp ?? null
172
172
  this.bootAt = this.catchUp != null ? resumeCatchUp(this.now(), this.catchUp) : this.now()
@@ -421,7 +421,8 @@ export class Planner {
421
421
  if (effectiveLoad(m) > LOAD_MAX * Math.max(1, m.cores)) {
422
422
  due = due.filter((x) => x.reason === 'asked')
423
423
  if (due.length === 0) {
424
- this.holdReason = `held: ${machineWords(m)}`
424
+ const top = this.o.who?.() ?? null
425
+ this.holdReason = `held: ${machineWords(m)}${top == null ? '' : `, most by ${top}`}`
425
426
  return null
426
427
  }
427
428
  }
@@ -21,6 +21,7 @@ import { RETIRED_CHECK_IDS } from './core/retired-checks.ts'
21
21
  import { normalizeVendored, vendoredOfText, vendoredProblem } from './core/vendored.ts'
22
22
  import { foreignOfText } from './core/foreign.ts'
23
23
  import { budgetValueProblem } from './core/budget.ts'
24
+ import { heavyProblem } from './core/admission.ts'
24
25
  import { browsersProblem } from './core/slots.ts'
25
26
  import { leakAllowProblems } from './hooks/leak-guard.ts'
26
27
  import type { HooksConfig } from './hooks/run-hooks.ts'
@@ -416,6 +417,10 @@ export type RepoConfig = {
416
417
  * slow suites the quick tier leaves out, and the suites that cannot run in
417
418
  * parallel, each with its reason. suite/judge-suites.ts */
418
419
  tests?: TestsConfig
420
+ /** sk command lines that wait while the machine is full, like ['trailer', 'assets gen']: each matches the argv it
421
+ * starts, and waits with a line every 10 s that names who uses the CPU, until its bound, then runs with a WARN.
422
+ * The gate's heavy checks, a clip, a loop of shots and sk smoke wait without being listed. core/admission.ts */
423
+ heavy?: string[]
419
424
  /** the live dashboard, `shipkit tui`. */
420
425
  tui?: {
421
426
  /** extra dashboard panels, appended after the built-in build steps and checks panels (`shipkit tui`) */
@@ -451,7 +456,7 @@ export type RepoConfig = {
451
456
  logDir?: string
452
457
  }
453
458
 
454
- const KNOWN_KEYS = new Set(['name', 'id', 'venues', 'social', 'speaksAs', 'backup', 'annex','docsBase', 'defaults', 'asks', 'creds', 'credsCommand', 'credsReadCommand', 'retired', 'notifyCommand', 'contracts', 'gitignore', 'ignoredInputs', 'untrackGenerated', 'nested', 'off', 'budgets', 'instantHooks', 'visibility', 'privateApps', 'ownerRepo', 'archived', 'foreign', 'onSave', 'history', 'reviewer', 'oneWayIn', 'release', 'units', 'notReleasable', 'vendored', 'hooks', 'tui', 'serve', 'recorder', 'identity', 'guiColor', 'appIcon', 'logDir', 'smoke', 'tests', 'browsers', 'start'])
459
+ const KNOWN_KEYS = new Set(['name', 'id', 'venues', 'social', 'speaksAs', 'backup', 'annex','docsBase', 'defaults', 'asks', 'creds', 'credsCommand', 'credsReadCommand', 'retired', 'notifyCommand', 'contracts', 'gitignore', 'ignoredInputs', 'untrackGenerated', 'nested', 'off', 'budgets', 'instantHooks', 'visibility', 'privateApps', 'ownerRepo', 'archived', 'foreign', 'onSave', 'history', 'reviewer', 'oneWayIn', 'release', 'units', 'notReleasable', 'vendored', 'hooks', 'tui', 'serve', 'recorder', 'identity', 'guiColor', 'appIcon', 'logDir', 'smoke', 'tests', 'browsers', 'heavy', 'start'])
455
460
 
456
461
  /** a key that is gone, and what to write instead */
457
462
  const REMOVED_KEYS: Record<string, string> = {
@@ -580,6 +585,8 @@ export function defineRepo(c: RepoConfig): RepoConfig {
580
585
  if (c.smoke != null) validateSmokeConfig(c.smoke)
581
586
  const browsers = browsersProblem(c.browsers)
582
587
  if (browsers != null) throw new Error(`defineRepo: ${browsers}`)
588
+ const heavy = heavyProblem(c.heavy)
589
+ if (heavy != null) throw new Error(`defineRepo: ${heavy}`)
583
590
  // a malformed skip list would let sk start wire the checkout it exists to leave alone
584
591
  if (c.start !== undefined) {
585
592
  const skip = (c.start as { skip?: unknown }).skip
@@ -194,6 +194,8 @@ export function kindCellAsk(thread: readonly Message[], m: Message) {
194
194
  ...(valued?.answer ? { value: { text: valued.answer.value ?? '', at: valued.at, ...(valued.answer.opens !== undefined ? { opens: valued.answer.opens } : {}), ...(valued.answer.view !== undefined ? { view: valued.answer.view } : {}) } } : {}),
195
195
  ...(m.ask?.secret ? { secret: { name: m.ask.secret.name, ...(m.ask.secret.login ? { login: true } : {}), ...(stored ? { stored: stored.at } : {}) } } : {}),
196
196
  ...(none !== undefined ? { none } : {}),
197
+ // his your call or no answer from the question's row (store.ts answerAsk `tone`)
198
+ ...(none !== undefined && last?.verdict !== undefined ? { tone: last.verdict } : {}),
197
199
  }
198
200
  }
199
201