rvlib-shipkit 2.14.0 → 2.16.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.
@@ -0,0 +1,65 @@
1
+ // a drill run folder leaves for the trash, never for rm: the folder is checked to BE a drill copy first
2
+ // (a git repo of its own with no remote, and either the sealed copy's record in .git (drill/seal.ts) or one
3
+ // commit named « drill base »), so a wrong path is refused, and a moved folder can be put back. a move across disks fails loud, it never falls back to a delete.
4
+ import { existsSync, lstatSync, mkdirSync, readdirSync, realpathSync, renameSync } from 'fs'
5
+ import { homedir } from 'os'
6
+ import { basename, dirname, join, resolve } from 'path'
7
+ import { gitBin } from '../core/git-bin.ts'
8
+
9
+ export const DRILL_BASE = 'drill base'
10
+
11
+ export const trashDir = (): string =>
12
+ process.platform === 'darwin' ? join(homedir(), '.Trash') : join(process.env.XDG_DATA_HOME ?? join(homedir(), '.local/share'), 'Trash/files')
13
+
14
+ const git = (dir: string, args: string[]): string | null => {
15
+ const p = Bun.spawnSync([gitBin(), '-C', dir, ...args], { stdout: 'pipe', stderr: 'ignore' })
16
+ return p.exitCode === 0 ? p.stdout.toString().trim() : null
17
+ }
18
+
19
+ /** why `dir` is not a drill copy, or null when it is one */
20
+ export function notADrillCopy(dir: string): string | null {
21
+ const abs = resolve(dir)
22
+ if (!existsSync(abs)) return 'does not exist'
23
+ if (lstatSync(abs).isSymbolicLink()) return 'is a symlink'
24
+ if (!lstatSync(abs).isDirectory()) return 'is not a folder'
25
+ if (abs === homedir() || dirname(abs) === abs) return 'is the home or the root folder'
26
+ // a worktree's .git is a file that points into another repo's refs
27
+ if (!existsSync(join(abs, '.git')) || !lstatSync(join(abs, '.git')).isDirectory()) return 'has no .git folder of its own'
28
+ const top = git(abs, ['rev-parse', '--show-toplevel'])
29
+ if (top == null || realpathSync(top) !== realpathSync(abs)) return 'is not the top of its git repo'
30
+ if ((git(abs, ['remote']) ?? '') !== '') return 'has a git remote'
31
+ // a sealed copy keeps the base's own commit message, and a run may commit on top of it
32
+ if (existsSync(join(abs, '.git/drill.json'))) return null
33
+ const count = git(abs, ['rev-list', '--count', '--all'])
34
+ if (count !== '1') return `holds ${count ?? 'no'} commits, a drill copy holds one`
35
+ const subject = git(abs, ['log', '-1', '--format=%s'])
36
+ if (subject !== DRILL_BASE) return `its commit is « ${subject ?? ''} », not « ${DRILL_BASE} »`
37
+ return null
38
+ }
39
+
40
+ export type CleanResult = { dir: string; to: string } | { dir: string; refused: string }
41
+
42
+ /** why `dir` is not the sealed wiki copy a drill run read (a folder holding only `wiki/`), or null when it is one */
43
+ export function notAWikiCopy(dir: string): string | null {
44
+ const abs = resolve(dir)
45
+ if (!existsSync(abs)) return 'does not exist'
46
+ if (lstatSync(abs).isSymbolicLink() || !lstatSync(abs).isDirectory()) return 'is not a plain folder'
47
+ const entries = readdirSync(abs)
48
+ return entries.length === 1 && entries[0] === 'wiki' ? null : 'holds more than a wiki/ folder'
49
+ }
50
+
51
+ /** moves one drill copy into `trash` under a free name; dry = report only */
52
+ export function cleanDrillCopy(dir: string, opts: { trash?: string; dry?: boolean; now?: Date; check?: (dir: string) => string | null } = {}): CleanResult {
53
+ const abs = resolve(dir)
54
+ const why = (opts.check ?? notADrillCopy)(abs)
55
+ if (why != null) return { dir: abs, refused: why }
56
+ const trash = opts.trash ?? trashDir()
57
+ const stamp = (opts.now ?? new Date()).toISOString().replace(/[-:]/g, '').replace(/\..*/, '')
58
+ let to = join(trash, `${basename(abs)}-${stamp}`)
59
+ for (let i = 2; existsSync(to); i++) to = join(trash, `${basename(abs)}-${stamp}-${i}`)
60
+ if (opts.dry !== true) {
61
+ mkdirSync(trash, { recursive: true })
62
+ renameSync(abs, to)
63
+ }
64
+ return { dir: abs, to }
65
+ }
@@ -0,0 +1,67 @@
1
+ // the end of one drill run (wiki meta/speed-up-agents/index.md): the run's work kept as a patch against the copy's one
2
+ // commit, its transcript read into run<n>.json and .md, the card's done cmd run in the copy, then the copy trashed.
3
+ // The order matters: the patch is written before the done cmd runs, so a done cmd that writes files never lands in it.
4
+ import { existsSync, readdirSync, readFileSync, realpathSync, writeFileSync } from 'fs'
5
+ import { join } from 'path'
6
+ import { gitBin } from '../core/git-bin.ts'
7
+ import type { Card } from './card.ts'
8
+ import type { DoneResult } from './run.ts'
9
+
10
+ /** a folder name the way Claude Code names a session's project folder: every char but a letter or a digit is a dash */
11
+ export const projectSlug = (abs: string): string => abs.replace(/[^a-zA-Z0-9]/g, '-')
12
+
13
+ /** the transcripts of the headless sessions started in `dir`, under every config root */
14
+ export function coldTranscripts(dir: string, projectRoots: readonly string[]): string[] {
15
+ const slugs = new Set([projectSlug(dir), projectSlug(realpathSync(dir))])
16
+ const out: string[] = []
17
+ for (const root of projectRoots) {
18
+ for (const s of slugs) {
19
+ const d = join(root, s)
20
+ if (!existsSync(d)) continue
21
+ for (const f of readdirSync(d)) if (f.endsWith('.jsonl')) out.push(join(d, f))
22
+ }
23
+ }
24
+ return out
25
+ }
26
+
27
+ const git = (dir: string, args: string[]): string => {
28
+ const p = Bun.spawnSync([gitBin(), '-C', dir, ...args], { stdout: 'pipe', stderr: 'pipe' })
29
+ if (p.exitCode !== 0) throw new Error(`git ${args.join(' ')}: ${p.stderr.toString().trim()}`)
30
+ return p.stdout.toString()
31
+ }
32
+
33
+ /** the run's whole work against the copy's first commit, new files included, a commit the run made included */
34
+ export function runPatch(dir: string): { patch: string; agentCommits: number } {
35
+ const root = git(dir, ['rev-list', '--max-parents=0', 'HEAD']).trim().split('\n')[0] ?? ''
36
+ git(dir, ['add', '-A'])
37
+ return { patch: git(dir, ['diff', '--cached', '--binary', root]), agentCommits: Number(git(dir, ['rev-list', '--count', 'HEAD']).trim()) - 1 }
38
+ }
39
+
40
+ export const DONE_TIMEOUT_MS = 600_000
41
+ const TAIL_LINES = 30
42
+
43
+ /** the card's done cmd in `dir`, exit 0 = done; its output tail kept for the report */
44
+ export function runDone(dir: string, cmd: string, mask: (s: string) => string = (s) => s): DoneResult {
45
+ const t0 = performance.now()
46
+ const p = Bun.spawnSync(['bash', '-c', cmd], { cwd: dir, stdout: 'pipe', stderr: 'pipe', timeout: DONE_TIMEOUT_MS })
47
+ const out = (p.stdout.toString() + p.stderr.toString()).trimEnd().split('\n').slice(-TAIL_LINES).join('\n')
48
+ return { cmd, exit: p.exitCode ?? 124, ms: Math.round(performance.now() - t0), tail: mask(out.split(dir).join('.')) }
49
+ }
50
+
51
+ /** the next free run number of a task folder */
52
+ export function nextRun(task: string): number {
53
+ const taken = readdirSync(task)
54
+ .map((f) => /^run(\d+)\.(json|patch|md)$/.exec(f)?.[1])
55
+ .filter((n): n is string => n != null)
56
+ .map(Number)
57
+ return Math.max(0, ...taken) + 1
58
+ }
59
+
60
+ export const readCard = async (task: string): Promise<Card | string> => {
61
+ const f = join(task, 'drill.md')
62
+ if (!existsSync(f)) return `no drill.md in ${task}: write the card first (wiki meta/speed-up-agents/index.md, the card)`
63
+ const { parseCard } = await import('./card.ts')
64
+ return parseCard(readFileSync(f, 'utf8'))
65
+ }
66
+
67
+ export const writePatch = (file: string, patch: string): void => writeFileSync(file, patch)
@@ -1,6 +1,7 @@
1
1
  // the md views of drill runs (drill/run.ts): one page per run, one comparison across the runs of a drill.
2
2
  // Generated from the json every time, never edited by hand. Markers are the house legend only.
3
3
  import type { DrillRun } from './run.ts'
4
+ import { gateOf, groupsOf, scoreOf } from './score.ts'
4
5
 
5
6
  const secs = (ms: number | null): string => (ms == null ? '-' : `${Math.round(ms / 1000)}`)
6
7
  const clock = (ms: number | null): string => {
@@ -13,13 +14,16 @@ const cell = (s: string): string => s.replace(/\|/g, '\\|').replace(/\n/g, ' ')
13
14
  const fence = (s: string): string => '```\n' + s.replace(/```/g, "'''") + '\n```'
14
15
 
15
16
  export function renderRun(r: DrillRun, label: string): string {
16
- const out: string[] = [`<!-- generated by \`sk drill report\` from ${r.transcript}, never edited by hand -->`, '', `# drill run: ${label}`, '']
17
+ const out: string[] = [`<!-- generated by \`sk drill\` from ${r.transcript}, never edited by hand -->`, '', `# drill run: ${label}`, '']
17
18
  out.push('## prompt (exact)', '', fence(r.prompt), '', '## TLDR', '')
18
19
  out.push(
19
20
  r.verdict == null
20
21
  ? '- 🔶 no verdict yet: `sk drill verdict` judges the run against its card'
21
22
  : `- ${r.verdict.design === 'ok' && r.verdict.quality >= 4 ? '✅' : '🔶'} verdict: done ${r.verdict.done}, quality ${r.verdict.quality}/5, tests ${r.verdict.tests}, design ${r.verdict.design}${r.verdict.note === '' ? '' : `: ${r.verdict.note}`}`,
22
23
  )
24
+ const gate = gateOf(r)
25
+ out.push(gate.length === 0 ? '- ✅ gate: done cmd passed, no forbidden path, no leak' : `- 🔶 gate fails: ${gate.join(', ')}`)
26
+ out.push(r.mode == null ? '- 🔶 recorded without a sealed copy: no mode, no setup key' : `- ${r.mode === 'cold' ? '✅ cold run' : '🔶 sub-agent run, a smoke test only'}, setup ${r.setup?.key ?? '-'} (base ${r.setup?.base.slice(0, 10) ?? '-'}, setup ${r.setup?.setup.slice(0, 10) ?? '-'}, wiki ${r.setup?.wiki ?? '-'})`)
23
27
  out.push(r.docs.length === 0 ? '- 🔶 no md page read: the setup under test never reached the run' : `- ${r.docs.length} md pages read, the first at ${clock(r.firstDoc)}; first write at ${clock(r.firstWrite)}, first check at ${clock(r.firstCheck)}`)
24
28
  if (r.errors > 0) out.push(`- 🔶 ${r.errors} failed calls (listed below)`)
25
29
  out.push(`- wall ${clock(r.wall)}, ${r.turns} turns, ${r.calls} tool calls, ${r.searches} searches, ${big(r.tokens.total)} tokens, context at end ${big(r.tokens.contextAtEnd)}`)
@@ -52,6 +56,11 @@ export function renderRun(r: DrillRun, label: string): string {
52
56
  out.push('', '## files written (Edit, Write)', '')
53
57
  out.push(r.written.length === 0 ? 'none' : r.written.map((w) => `- ${w}`).join('\n'))
54
58
  if (r.patch != null) out.push('', '## files in the patch', '', r.patch.paths.length === 0 ? 'none' : r.patch.paths.map((p) => `- ${p}`).join('\n'))
59
+ out.push('', '## leaks', '', 'Reads of the main repo, the transcripts, the drill record, the web or a remote. One fails the gate.', '')
60
+ out.push(r.leaks.length === 0 ? 'none' : r.leaks.map((l) => `- 🔶 ${clock(l.at)} ${l.tool} (${l.kind}): \`${l.detail.replace(/`/g, "'")}\``).join('\n'))
61
+ out.push('', '## done cmd', '')
62
+ out.push(r.done == null ? 'not run: the card has no `done cmd` row, or the run was recorded without `sk drill finish`' : [`- ${r.done.exit === 0 ? '✅' : '🔶'} exit ${r.done.exit} in ${secs(r.done.ms)}s: \`${r.done.cmd.replace(/`/g, "'")}\``, '', fence(r.done.tail)].join('\n'))
63
+ if (r.forbidHits.length > 0) out.push('', '## forbidden paths touched', '', r.forbidHits.map((p) => `- 🔶 ${p}`).join('\n'))
55
64
  out.push('', '## failed calls', '')
56
65
  out.push(r.failures.length === 0 ? 'none' : r.failures.map((f) => `- 🔶 ${clock(f.at)} ${f.tool} (${f.outcome}): \`${f.detail.replace(/`/g, "'")}\``).join('\n'))
57
66
  out.push('', '## final report', '', fence(r.finalReport), '')
@@ -110,15 +119,25 @@ export function renderCompare(name: string, runs: { label: string; run: DrillRun
110
119
  const z = lastRun.run
111
120
  const mismatch = runs.filter((r) => r.run.prompt !== a.prompt).map((r) => r.label)
112
121
  out.push('## TLDR', '')
122
+ const groups = groupsOf(runs)
123
+ const score = scoreOf(groups)
124
+ const mark = { keep: '✅', revert: '🔶', inconclusive: '🔶', baseline: '🔶' }[score.verdict]
125
+ out.push(`- ${mark} ${score.verdict}: ${score.why}`)
126
+ const models = new Set(runs.map((r) => r.run.models.join('+')))
127
+ if (models.size > 1) out.push(`- 🔶 the runs used different models (${[...models].join(', ')}): their numbers do not compare`)
113
128
  const prev = runs.length > 2 ? runs[runs.length - 2] : undefined
114
129
  out.push(`- ${better(a.calls, z.calls) ? '✅' : '🔶'} tool calls ${first.label} → ${lastRun.label}: ${delta(a.calls, z.calls)}`)
115
- if (prev != null) out.push(`- ${better(prev.run.calls, z.calls) ? '✅' : '🔶'} tool calls ${prev.label} → ${lastRun.label}, what the stop rule reads: ${delta(prev.run.calls, z.calls)}`)
130
+ if (prev != null) out.push(`- ${better(prev.run.calls, z.calls) ? '✅' : '🔶'} tool calls ${prev.label} → ${lastRun.label}, the last two runs: ${delta(prev.run.calls, z.calls)}`)
116
131
  out.push(`- ${better(a.wall, z.wall) ? '✅' : '🔶'} wall (s): ${delta(a.wall, z.wall, secs)}`)
117
132
  out.push(`- ${better(a.tokens.total, z.tokens.total) ? '✅' : '🔶'} tokens: ${delta(a.tokens.total, z.tokens.total, big)}`)
118
133
  const qa = a.verdict?.quality
119
134
  const qz = z.verdict?.quality
120
135
  out.push(qa == null || qz == null ? '- 🔶 a verdict is missing: a saving with no verdict is not a saving (`sk drill verdict`)' : `- ${qz >= qa ? '✅' : '🔶'} quality ${qa} → ${qz}, design ${a.verdict?.design} → ${z.verdict?.design}`)
121
136
  out.push(mismatch.length === 0 ? '- ✅ every run got the same prompt' : `- 🔶 the prompt differs from ${first.label} in: ${mismatch.join(', ')}`)
137
+ out.push('', '## setups', '', 'Runs group by mode and setup key. The score holds the last group against the first group of its mode.', '', '| group | runs | gate passed | tool calls |', '|---|---|---|---|')
138
+ for (const g of groups) out.push(`| ${g.key} | ${g.labels.join(', ')} | ${g.runs.filter((r) => gateOf(r).length === 0).length}/${g.runs.length} | ${g.runs.map((r) => r.calls).join(', ')} |`)
139
+ const fails = runs.filter((r) => gateOf(r.run).length > 0)
140
+ if (fails.length > 0) out.push('', ...fails.map((r) => `- 🔶 ${r.label} fails the gate: ${gateOf(r.run).join(', ')}`))
122
141
  const prevHead = prev == null ? '' : ` ${prev.label} → ${lastRun.label} |`
123
142
  out.push('', '## metrics', '', `| metric | ${runs.map((r) => r.label).join(' | ')} | ${first.label} → ${lastRun.label} |${prevHead}`, `|---|${runs.map(() => '---|').join('')}---|${prev == null ? '' : '---|'}`)
124
143
  for (const row of ROWS) {
package/src/drill/run.ts CHANGED
@@ -7,12 +7,21 @@ import { isReadOnly, parallelFlags } from '../agent-time/turns.ts'
7
7
  import { shellWords, statements, stripHeredocs, toolShape } from '../agent-time/shape.ts'
8
8
  import { eventsOf, parseEntry, usageOf, userTextOf, type Outcome, type RawEntry } from '../reflect/transcript.ts'
9
9
 
10
- export const RUN_VERSION = 1
10
+ export const RUN_VERSION = 2
11
11
 
12
12
  export type Verdict = { done: string; quality: number; tests: 'ran' | 'written' | 'none'; design: 'ok' | 'wrong'; note: string }
13
13
 
14
14
  export type DocRead = { path: string; first: number; reads: number; reader: string }
15
15
 
16
+ /** a call that reached what the run must not see: the main repo, transcripts, the drill record, the web, the remote */
17
+ export type Leak = { at: number; tool: string; kind: 'private' | 'drill' | 'web' | 'remote'; detail: string }
18
+
19
+ /** how the run was started: a headless session in a sealed copy, or a sub-agent of a session (a smoke run, never scored with cold ones) */
20
+ export type RunMode = 'cold' | 'subagent'
21
+
22
+ /** the card's done cmd, run in the copy once the run ended */
23
+ export type DoneResult = { cmd: string; exit: number; ms: number; tail: string }
24
+
16
25
  export type PatchStats = { files: number; added: number; removed: number; newFiles: number; testFiles: number; docFiles: number; paths: string[] }
17
26
 
18
27
  export type DrillRun = {
@@ -44,6 +53,12 @@ export type DrillRun = {
44
53
  finalReport: string
45
54
  patch: PatchStats | null
46
55
  verdict: Verdict | null
56
+ /** null on a run recorded without a sealed copy */
57
+ mode: RunMode | null
58
+ setup: { base: string; setup: string; key: string; wiki: string } | null
59
+ leaks: Leak[]
60
+ done: DoneResult | null
61
+ forbidHits: string[]
47
62
  }
48
63
 
49
64
  const WRITE_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
@@ -104,6 +119,29 @@ function bashTargets(cmd: string): string[] {
104
119
  return out
105
120
  }
106
121
 
122
+ const REMOTE_GIT = new Set(['push', 'pull', 'fetch', 'clone', 'remote', 'ls-remote'])
123
+
124
+ /** the calls that reached a private path, the drill record, the web or a remote. `priv` holds absolute folders */
125
+ export function leaksOf(calls: readonly Call[], priv: readonly string[], home: string, start: number): Leak[] {
126
+ const spell = priv
127
+ .flatMap((p) => (p.startsWith(`${home}/`) ? [p, `~${p.slice(home.length)}`, `$HOME${p.slice(home.length)}`] : [p]))
128
+ .map((p) => new RegExp(`${p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\w-]|\\.\\w)`))
129
+ const out: Leak[] = []
130
+ for (const c of calls) {
131
+ const at = Math.max(0, c.start - start)
132
+ const detail = c.cmd.slice(0, 160)
133
+ if (c.tool === 'WebFetch' || c.tool === 'WebSearch') out.push({ at, tool: c.tool, kind: 'web', detail })
134
+ else if (c.tool === 'Bash' && statements(c.cmd).some((s) => {
135
+ const w = shellWords(s.trim())
136
+ return w[0] === 'gh' || (w[0] === 'git' && REMOTE_GIT.has(w.find((x, i) => i > 0 && !x.startsWith('-') && w[i - 1] !== '-C' && w[i - 1] !== '-c') ?? ''))
137
+ }))
138
+ out.push({ at, tool: c.tool, kind: 'remote', detail })
139
+ else if (/\.git\/drill[-.]/.test(c.cmd)) out.push({ at, tool: c.tool, kind: 'drill', detail })
140
+ else if (spell.some((re) => re.test(c.cmd))) out.push({ at, tool: c.tool, kind: 'private', detail })
141
+ }
142
+ return out
143
+ }
144
+
107
145
  /** the stats of a unified diff, the kind `git diff --cached` writes */
108
146
  export function patchStats(patch: string): PatchStats {
109
147
  const paths: string[] = []
@@ -121,7 +159,7 @@ export function patchStats(patch: string): PatchStats {
121
159
  }
122
160
 
123
161
  /** the run a transcript records. `root` is the run folder: its prefix is cut from every path, so two runs in two folders compare */
124
- export function drillRun(lines: readonly string[], o: { transcript: string; root?: string; home?: string; patch?: string; mask?: (s: string) => string }): DrillRun {
162
+ export function drillRun(lines: readonly string[], o: { transcript: string; root?: string; home?: string; patch?: string; mask?: (s: string) => string; private?: readonly string[] }): DrillRun {
125
163
  const mask = o.mask ?? ((s: string) => s)
126
164
  const home = o.home ?? process.env.HOME ?? ''
127
165
  /** one spelling per file: `~/` and `$HOME/` expanded, then the run folder cut, so `Read` and `cat` of one page are one row */
@@ -240,9 +278,20 @@ export function drillRun(lines: readonly string[], o: { transcript: string; root
240
278
  finalReport: mask(finalReport).slice(0, FINAL_MAX),
241
279
  patch: o.patch == null ? null : patchStats(o.patch),
242
280
  verdict: null,
281
+ mode: null,
282
+ setup: null,
283
+ leaks: leaksOf(calls, o.private ?? [], home, start).map((l) => ({ ...l, detail: mask(rel(l.detail)) })),
284
+ done: null,
285
+ forbidHits: [],
243
286
  }
244
287
  }
245
288
 
289
+ /** a run record read back: a record written before a field existed gets its empty value */
290
+ export const normalizeRun = (raw: unknown): DrillRun => {
291
+ const r = raw as Partial<DrillRun> & DrillRun
292
+ return { ...r, mode: r.mode ?? null, setup: r.setup ?? null, leaks: r.leaks ?? [], done: r.done ?? null, forbidHits: r.forbidHits ?? [] }
293
+ }
294
+
246
295
  /** `done=3/3,quality=4,tests=ran,design=ok[,note=…]`, every field checked; the error names the bad one */
247
296
  export function parseVerdict(text: string): Verdict | string {
248
297
  const kv = new Map(
@@ -0,0 +1,68 @@
1
+ // keep or revert a setup change, from its runs (wiki meta/speed-up-agents/index.md, Drill again). Runs group by mode
2
+ // and setup key: a cold run and a sub-agent run never share a group, and two shas with the same setup files share one.
3
+ // A saving counts only when every candidate run passes the gate, every run has a verdict, the candidate's median
4
+ // quality holds, and its median calls sit under the whole baseline range: one run per setup is an anecdote, so a
5
+ // group needs two. The thresholds are chosen, not measured.
6
+ import type { DrillRun } from './run.ts'
7
+
8
+ /** why a run fails the gate, [] when it passes */
9
+ export function gateOf(r: DrillRun): string[] {
10
+ const why: string[] = []
11
+ if (r.done == null) why.push('no done cmd result')
12
+ else if (r.done.exit !== 0) why.push(`done cmd exit ${r.done.exit}`)
13
+ if (r.verdict?.design === 'wrong') why.push('design wrong')
14
+ if (r.forbidHits.length > 0) why.push(`${r.forbidHits.length} forbidden paths`)
15
+ if (r.leaks.length > 0) why.push(`${r.leaks.length} leaks`)
16
+ return why
17
+ }
18
+
19
+ export const groupKey = (r: DrillRun): string => `${r.mode ?? 'unknown'}:${r.setup?.key ?? 'unknown'}`
20
+
21
+ export type Group = { key: string; labels: string[]; runs: DrillRun[] }
22
+
23
+ /** groups in order of their first run */
24
+ export function groupsOf(runs: readonly { label: string; run: DrillRun }[]): Group[] {
25
+ const out = new Map<string, Group>()
26
+ for (const { label, run } of runs) {
27
+ const k = groupKey(run)
28
+ const g = out.get(k) ?? { key: k, labels: [], runs: [] }
29
+ g.labels.push(label)
30
+ g.runs.push(run)
31
+ out.set(k, g)
32
+ }
33
+ return [...out.values()]
34
+ }
35
+
36
+ const median = (xs: readonly number[]): number => {
37
+ const s = [...xs].sort((a, b) => a - b)
38
+ const m = Math.floor(s.length / 2)
39
+ return s.length % 2 === 1 ? (s[m] as number) : ((s[m - 1] as number) + (s[m] as number)) / 2
40
+ }
41
+
42
+ export type Score = { verdict: 'keep' | 'revert' | 'inconclusive' | 'baseline'; why: string; baseline: Group | null; candidate: Group | null }
43
+
44
+ /** the last group against the first group of the same mode */
45
+ export function scoreOf(groups: readonly Group[]): Score {
46
+ const candidate = groups[groups.length - 1] ?? null
47
+ if (candidate == null) return { verdict: 'baseline', why: 'no run', baseline: null, candidate }
48
+ const mode = candidate.key.split(':')[0]
49
+ const baseline = groups.find((g) => g !== candidate && g.key.split(':')[0] === mode) ?? null
50
+ if (baseline == null) return { verdict: 'baseline', why: `one ${mode} setup only: this is the baseline`, baseline, candidate }
51
+ if (mode === 'unknown') return { verdict: 'inconclusive', why: 'runs recorded without a sealed copy carry no setup key', baseline, candidate }
52
+ if (baseline.runs.length < 2 || candidate.runs.length < 2) return { verdict: 'inconclusive', why: 'two runs per setup at least: one run is an anecdote', baseline, candidate }
53
+ const failed = candidate.runs.filter((r) => gateOf(r).length > 0).length
54
+ if (failed > 0) return { verdict: 'revert', why: `${failed} of ${candidate.runs.length} candidate runs fail the gate`, baseline, candidate }
55
+ // a faster run with a worse result is no saving: quality is judged by hand, so a run with no verdict decides nothing
56
+ const unjudged = [...baseline.runs, ...candidate.runs].filter((r) => r.verdict == null).length
57
+ if (unjudged > 0) return { verdict: 'inconclusive', why: `${unjudged} runs have no verdict yet: sk drill verdict judges each one`, baseline, candidate }
58
+ const qb = median(baseline.runs.map((r) => r.verdict?.quality ?? 0))
59
+ const qc = median(candidate.runs.map((r) => r.verdict?.quality ?? 0))
60
+ if (qc < qb) return { verdict: 'revert', why: `candidate quality ${qc}, under the baseline's ${qb}`, baseline, candidate }
61
+ const calls = baseline.runs.map((r) => r.calls)
62
+ const med = median(candidate.runs.map((r) => r.calls))
63
+ const lo = Math.min(...calls)
64
+ const hi = Math.max(...calls)
65
+ if (med < lo) return { verdict: 'keep', why: `candidate median ${med} calls, under the baseline range ${lo} to ${hi}`, baseline, candidate }
66
+ if (med > hi) return { verdict: 'revert', why: `candidate median ${med} calls, above the baseline range ${lo} to ${hi}`, baseline, candidate }
67
+ return { verdict: 'inconclusive', why: `candidate median ${med} calls, inside the baseline range ${lo} to ${hi}: revert, or ask to raise the run cap`, baseline, candidate }
68
+ }
@@ -0,0 +1,259 @@
1
+ // a sealed drill copy (wiki meta/speed-up-agents/index.md, How a run goes): the repo at one commit, in a temp folder
2
+ // with a neutral name, where nothing points at the change under test or at the answer. One commit with the base's
3
+ // own message, author and date; the setup of another sha laid over it; every drill folder gone and checked gone;
4
+ // lines naming the drill dropped; one mtime for every file; a real frozen install. What the run must never read is
5
+ // denied in a settings file the headless run loads, and every such read is still listed as a leak in its report.
6
+ // The run itself is started by the session, never from here (core/agent-spawn.ts).
7
+ import { createHash } from 'crypto'
8
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, utimesSync, writeFileSync } from 'fs'
9
+ import { homedir, tmpdir } from 'os'
10
+ import { basename, dirname, join, relative, resolve } from 'path'
11
+ import { gitBin } from '../core/git-bin.ts'
12
+
13
+ export const META = '.git/drill.json'
14
+ export const PROMPT = '.git/drill-prompt.txt'
15
+ export const SETTINGS = '.git/drill-settings.json'
16
+ /** the files an agent reads as its setup, laid over the base from the setup sha */
17
+ export const SETUP_PATHS = ['CLAUDE.md', 'AGENTS.md', 'agent', '.claude']
18
+
19
+ export type SealMeta = {
20
+ version: 1
21
+ /** the task folder, its card and its runs; absolute */
22
+ task: string
23
+ repo: string
24
+ /** the house checkout whose wiki the repo's CLAUDE.md includes, null when it includes none */
25
+ house: string | null
26
+ base: string
27
+ setup: string
28
+ /** how the run reads the house wiki: its own copy (the repo is the house), a sealed copy at a sha, or the live tree */
29
+ wiki: { mode: 'own' } | { mode: 'copy'; sha: string; dir: string } | { mode: 'live'; tree: string; dirty: boolean } | { mode: 'none' }
30
+ /** a hash of every setup file the run sees: runs with one key ran one setup */
31
+ setupKey: string
32
+ prompt: string
33
+ created: string
34
+ /** the paths a run must never read: the main repo, the transcripts, older drill copies */
35
+ private: string[]
36
+ }
37
+
38
+ const run = (argv: string[], o: { cwd?: string; stdin?: Uint8Array; env?: Record<string, string> } = {}): { code: number; out: Uint8Array; err: string } => {
39
+ const p = Bun.spawnSync(argv, { cwd: o.cwd, stdin: o.stdin, stdout: 'pipe', stderr: 'pipe', env: o.env == null ? undefined : { ...process.env, ...o.env } })
40
+ return { code: p.exitCode ?? 1, out: p.stdout, err: p.stderr.toString().trim() }
41
+ }
42
+ const git = (dir: string, args: string[], o: { stdin?: Uint8Array; env?: Record<string, string> } = {}): string => {
43
+ const r = run([gitBin(), '-C', dir, ...args], o)
44
+ if (r.code !== 0) throw new Error(`git ${args.join(' ')}: ${r.err}`)
45
+ return new TextDecoder().decode(r.out).trim()
46
+ }
47
+ const gitOk = (dir: string, args: string[]): boolean => run([gitBin(), '-C', dir, ...args]).code === 0
48
+
49
+ /** `git archive <sha> [paths]` unpacked into `dir` */
50
+ function unpack(repo: string, sha: string, dir: string, paths: string[] = []): void {
51
+ const a = run([gitBin(), '-C', repo, 'archive', sha, ...paths])
52
+ if (a.code !== 0) throw new Error(`git archive ${sha} ${paths.join(' ')}: ${a.err}`)
53
+ const t = run(['tar', '-x', '-C', dir], { stdin: a.out })
54
+ if (t.code !== 0) throw new Error(`tar -x into ${dir}: ${t.err}`)
55
+ }
56
+
57
+ /** every file and folder under `dir`, `.git` and `node_modules` left out, deepest first */
58
+ function walk(dir: string): { path: string; isDir: boolean }[] {
59
+ const out: { path: string; isDir: boolean }[] = []
60
+ const go = (d: string): void => {
61
+ for (const e of readdirSync(d, { withFileTypes: true })) {
62
+ if (e.name === '.git' || e.name === 'node_modules') continue
63
+ const p = join(d, e.name)
64
+ if (e.isDirectory()) {
65
+ go(p)
66
+ out.push({ path: p, isDir: true })
67
+ } else if (e.isFile()) out.push({ path: p, isDir: false })
68
+ }
69
+ }
70
+ go(dir)
71
+ return out
72
+ }
73
+
74
+ /** the three spellings an md page uses for one absolute folder */
75
+ export const spellings = (abs: string, home: string): string[] => (abs.startsWith(`${home}/`) ? [abs, `~${abs.slice(home.length)}`, `$HOME${abs.slice(home.length)}`] : [abs])
76
+
77
+ const escape = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
78
+
79
+ /** text with every spelling of `from` (a folder) moved to `to`, a longer folder name left alone */
80
+ export const rewriteFolder = (text: string, from: string, to: string, home: string): string =>
81
+ spellings(from, home).reduce((t, s) => t.replace(new RegExp(`${escape(s)}(?![\\w-]|\\.\\w)`, 'g'), to), text)
82
+
83
+ /** the settings a headless run loads: no web, no remote, no read of a private path */
84
+ export function denySettings(priv: readonly string[]): { permissions: { deny: string[] } } {
85
+ const deny = ['WebFetch', 'WebSearch', 'Bash(gh *)', 'Bash(git push *)', 'Bash(git pull *)', 'Bash(git fetch *)', 'Bash(git clone *)', 'Bash(git remote *)']
86
+ // a Read rule covers every reading tool, an Edit rule every editing one; the harness ignores the others
87
+ for (const p of priv) deny.push(`Read(/${p}/**)`, `Edit(/${p}/**)`)
88
+ return { permissions: { deny } }
89
+ }
90
+
91
+ export const setupKeyOf = (parts: readonly string[]): string => createHash('sha256').update(parts.join('\n')).digest('hex').slice(0, 12)
92
+
93
+ /** the folders under `.shipkit/plans` that hold drills: their cards and patches are answers */
94
+ const drillFolders = (dir: string): string[] => {
95
+ const plans = join(dir, '.shipkit/plans')
96
+ if (!existsSync(plans)) return []
97
+ return readdirSync(plans, { withFileTypes: true })
98
+ .filter((e) => e.isDirectory() && /speed-up|drill/i.test(e.name))
99
+ .map((e) => join(plans, e.name))
100
+ }
101
+
102
+ /** what in a sealed tree still gives a drill away */
103
+ export const drillLeftovers = (paths: readonly string[]): string[] => paths.filter((p) => /(^|\/)drill\.md$/.test(p) || /(^|\/)run\d+\.(patch|json)$/.test(p))
104
+
105
+ export type SealOptions = {
106
+ repo: string
107
+ task: string
108
+ base: string
109
+ setup?: string
110
+ /** a house sha whose wiki the run reads instead of the live tree */
111
+ wiki?: string
112
+ house: string | null
113
+ prompt: string
114
+ install: boolean
115
+ configRoots: string[]
116
+ home?: string
117
+ tmp?: string
118
+ }
119
+
120
+ export type Sealed = { dir: string; meta: SealMeta; notes: string[] }
121
+
122
+ export function seal(o: SealOptions): Sealed {
123
+ const home = o.home ?? homedir()
124
+ const repo = realpathSync(o.repo)
125
+ const notes: string[] = []
126
+ const base = git(repo, ['rev-parse', '--verify', `${o.base}^{commit}`])
127
+ const setup = o.setup == null ? base : git(repo, ['rev-parse', '--verify', `${o.setup}^{commit}`])
128
+ const house = o.house == null ? null : realpathSync(o.house)
129
+ const own = house != null && house === repo
130
+ const setupPaths = own ? [...SETUP_PATHS, 'wiki'] : SETUP_PATHS
131
+ const dir = realpathSync(mkdtempSync(join(o.tmp ?? tmpdir(), `${basename(repo)}-`)))
132
+ unpack(repo, base, dir)
133
+ if (setup !== base) {
134
+ const present = setupPaths.filter((p) => gitOk(repo, ['cat-file', '-e', `${setup}:${p}`]))
135
+ for (const p of setupPaths) rmSync(join(dir, p), { recursive: true, force: true })
136
+ if (present.length > 0) unpack(repo, setup, dir, present)
137
+ }
138
+
139
+ const taskRel = relative(repo, realpathSync(o.task))
140
+ const drillRel = dirname(taskRel)
141
+ if (taskRel.startsWith('..') || drillRel === '.') throw new Error(`the task folder ${o.task} must sit in a drill folder inside ${repo}`)
142
+ for (const d of new Set([join(dir, drillRel), ...drillFolders(dir)])) rmSync(d, { recursive: true, force: true })
143
+
144
+ let wiki: SealMeta['wiki'] = { mode: 'none' }
145
+ const wikiDirs: string[] = []
146
+ const mdFiles = (root: string): string[] => walk(root).filter((f) => !f.isDir && f.path.endsWith('.md')).map((f) => f.path)
147
+ const rewrite = (files: string[], from: string, to: string): void => {
148
+ for (const f of files) {
149
+ const t = readFileSync(f, 'utf8')
150
+ const r = rewriteFolder(t, from, to, home)
151
+ if (r !== t) writeFileSync(f, r)
152
+ }
153
+ }
154
+ if (house != null && own) {
155
+ rewrite(mdFiles(dir), house, dir)
156
+ wiki = { mode: 'own' }
157
+ } else if (house != null && o.wiki != null) {
158
+ const sha = git(house, ['rev-parse', '--verify', `${o.wiki}^{commit}`])
159
+ const w = realpathSync(mkdtempSync(join(o.tmp ?? tmpdir(), 'w-')))
160
+ unpack(house, sha, w, ['wiki'])
161
+ rewrite([...mdFiles(dir), ...mdFiles(w)], join(house, 'wiki'), join(w, 'wiki'))
162
+ wikiDirs.push(w)
163
+ wiki = { mode: 'copy', sha, dir: w }
164
+ } else if (house != null) {
165
+ const tree = git(house, ['rev-parse', 'HEAD:wiki'])
166
+ const untracked = git(house, ['ls-files', '--others', '--exclude-standard', '--', 'wiki']).split('\n').filter((f) => f !== '')
167
+ const diff = [git(house, ['diff', 'HEAD', '--', 'wiki']), ...untracked.map((f) => `${f}\n${readFileSync(join(house, f), 'utf8')}`)].join('\n').trim()
168
+ wiki = { mode: 'live', tree: diff === '' ? tree : `${tree}+${setupKeyOf([diff])}`, dirty: diff !== '' }
169
+ if (diff !== '') notes.push('🔶 the live house wiki has uncommitted edits: they are part of this run\'s setup, and its setup key says so')
170
+ }
171
+
172
+ // a doc line naming the drill folder points at the cards: drop it. In code a dropped line can break the base, so
173
+ // code that names it fails loud instead
174
+ const needles = [drillRel, basename(drillRel)].filter((n) => n.length >= 8)
175
+ let dropped = 0
176
+ const inCode: string[] = []
177
+ for (const f of walk(dir)) {
178
+ if (f.isDir || statSync(f.path).size > 2_000_000) continue
179
+ const t = readFileSync(f.path)
180
+ if (t.includes(0)) continue
181
+ const lines = t.toString('utf8').split('\n')
182
+ const kept = lines.filter((l) => !needles.some((n) => l.includes(n)))
183
+ if (kept.length === lines.length) continue
184
+ if (!/\.(md|txt)$/.test(f.path)) inCode.push(relative(dir, f.path))
185
+ else {
186
+ dropped += lines.length - kept.length
187
+ writeFileSync(f.path, kept.join('\n'))
188
+ }
189
+ }
190
+ if (inCode.length > 0) throw new Error(`files that are not docs name the drill folder: ${inCode.slice(0, 5).join(', ')}`)
191
+ if (dropped > 0) notes.push(`${dropped} doc lines naming the drill folder dropped`)
192
+ if (/drill|speed-up/i.test(git(repo, ['log', '-1', '--format=%B', base]))) notes.push('🔶 the base commit message names a drill, and the copy keeps it: the run can read it in git log')
193
+ const left = drillLeftovers(walk(dir).map((f) => relative(dir, f.path)))
194
+ if (left.length > 0) throw new Error(`drill material left in the copy: ${left.slice(0, 5).join(', ')}: move it under .shipkit/plans/<date>-speed-up/`)
195
+
196
+ const when = git(repo, ['log', '-1', '--format=%aI', base])
197
+ const stamp = new Date(when)
198
+ const touch = (root: string): void => {
199
+ for (const f of walk(root)) utimesSync(f.path, stamp, stamp)
200
+ utimesSync(root, stamp, stamp)
201
+ }
202
+ touch(dir)
203
+ for (const w of wikiDirs) touch(w)
204
+
205
+ const [name, email] = [git(repo, ['log', '-1', '--format=%an', base]), git(repo, ['log', '-1', '--format=%ae', base])]
206
+ const cname = git(repo, ['log', '-1', '--format=%cn', base])
207
+ const cemail = git(repo, ['log', '-1', '--format=%ce', base])
208
+ const cdate = git(repo, ['log', '-1', '--format=%cI', base])
209
+ git(dir, ['init', '-q', '-b', 'main'])
210
+ writeFileSync(join(dir, '.git/info/exclude'), 'node_modules\n')
211
+ git(dir, ['add', '-A'])
212
+ git(dir, ['-c', 'core.hooksPath=/dev/null', '-c', 'commit.gpgsign=false', 'commit', '-q', '-F', '-'], {
213
+ stdin: new TextEncoder().encode(git(repo, ['log', '-1', '--format=%B', base])),
214
+ env: { GIT_AUTHOR_NAME: name, GIT_AUTHOR_EMAIL: email, GIT_AUTHOR_DATE: when, GIT_COMMITTER_NAME: cname, GIT_COMMITTER_EMAIL: cemail, GIT_COMMITTER_DATE: cdate },
215
+ })
216
+
217
+ if (o.install) {
218
+ if (existsSync(join(dir, 'bun.lock')) || existsSync(join(dir, 'bun.lockb'))) {
219
+ const r = run(['bun', 'install', '--frozen-lockfile'], { cwd: dir })
220
+ if (r.code !== 0) throw new Error(`bun install --frozen-lockfile in the copy: ${r.err.split('\n').slice(-5).join(' ')}`)
221
+ } else if (existsSync(join(dir, 'package.json'))) notes.push('🔶 no bun lockfile at the base: deps not installed')
222
+ }
223
+ utimesSync(dir, stamp, stamp)
224
+
225
+ const setupParts = setupPaths.map((p) => {
226
+ const r = run([gitBin(), '-C', repo, 'rev-parse', `${setup}:${p}`])
227
+ return `${p}:${r.code === 0 ? new TextDecoder().decode(r.out).trim() : 'absent'}`
228
+ })
229
+ const wikiPart = wiki.mode === 'copy' ? `wiki:${git(house as string, ['rev-parse', `${wiki.sha}:wiki`])}` : wiki.mode === 'live' ? `wiki:${wiki.tree}` : `wiki:${wiki.mode}`
230
+ // an older copy left in the temp folder (--keep, a refused trash) holds earlier runs' work
231
+ const tmp = dirname(dir)
232
+ const older = readdirSync(tmp)
233
+ .filter((n) => n.startsWith(`${basename(repo)}-`) && join(tmp, n) !== dir && existsSync(join(tmp, n, META)))
234
+ .map((n) => join(tmp, n))
235
+ const priv = [repo, ...o.configRoots, join(home, 'drills'), ...older, ...(wiki.mode === 'copy' && house != null ? [join(house, 'wiki')] : [])]
236
+ const meta: SealMeta = {
237
+ version: 1,
238
+ task: realpathSync(o.task),
239
+ repo,
240
+ house,
241
+ base,
242
+ setup,
243
+ wiki,
244
+ setupKey: setupKeyOf([...setupParts, wikiPart]),
245
+ prompt: o.prompt,
246
+ created: new Date().toISOString(),
247
+ private: [...new Set(priv)],
248
+ }
249
+ writeFileSync(join(dir, META), JSON.stringify(meta, null, 2) + '\n')
250
+ writeFileSync(join(dir, PROMPT), o.prompt + '\n')
251
+ writeFileSync(join(dir, SETTINGS), JSON.stringify(denySettings(meta.private), null, 2) + '\n')
252
+ return { dir, meta, notes }
253
+ }
254
+
255
+ export const readMeta = (dir: string): SealMeta | null => {
256
+ const f = join(resolve(dir), META)
257
+ return existsSync(f) ? (JSON.parse(readFileSync(f, 'utf8')) as SealMeta) : null
258
+ }
259
+
@@ -41,8 +41,17 @@ export async function pmUp(port = pmPort(), timeoutMs = 400): Promise<boolean> {
41
41
  }
42
42
  }
43
43
 
44
+ /** shipkit's own suite run without its preload (tests/_setup.ts gives each run a temp home): it would read, write and
45
+ * delete the machine's real home, its media index included */
46
+ const suiteOnRealHome = (): boolean => process.env.NODE_ENV === 'test' && /\/rvlib-shipkit\/tests\//.test(Bun.main)
47
+
44
48
  /** beside the rail order file (project-gutter-route.ts ORDER_FILE) */
45
- export const homeDir = (): string => process.env.SHIPKIT_HOME_DIR ?? join(homedir(), '.config', 'shipkit', 'home')
49
+ export const homeDir = (): string => {
50
+ const dir = process.env.SHIPKIT_HOME_DIR
51
+ if (dir) return dir
52
+ if (suiteOnRealHome()) throw new Error(`${Bun.main}: a shipkit suite reached the machine's real home; run it from packages/rvlib-shipkit (its bunfig preload gives the run a temp home) or through sk ci --only test`)
53
+ return join(homedir(), '.config', 'shipkit', 'home')
54
+ }
46
55
 
47
56
  /** set in the home process, so every process it starts (a check's child, a
48
57
  * repo's declared process) runs its gate and its hub in process, never back