rvlib-shipkit 2.15.0 → 2.17.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 (45) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/package.json +1 -1
  3. package/src/assets/kit-config.ts +19 -1
  4. package/src/assets/run-assets.ts +18 -0
  5. package/src/checks/SK038-speaks-as.check.ts +66 -0
  6. package/src/cli/cmd_Drill.ts +219 -12
  7. package/src/cli/cmd_Media.ts +34 -8
  8. package/src/cli/cmd_Review.ts +22 -7
  9. package/src/cli/cmd_Secret.ts +127 -0
  10. package/src/cli/cmd_Social.ts +19 -9
  11. package/src/cli/cmd_Wiki.ts +4 -4
  12. package/src/cli/family-pages.ts +1 -0
  13. package/src/cli/registry.ts +8 -1
  14. package/src/core/scope.ts +42 -0
  15. package/src/drill/card.ts +65 -0
  16. package/src/drill/clean.ts +17 -6
  17. package/src/drill/finish.ts +67 -0
  18. package/src/drill/render.ts +21 -2
  19. package/src/drill/run.ts +51 -2
  20. package/src/drill/score.ts +68 -0
  21. package/src/drill/seal.ts +259 -0
  22. package/src/home/home-paths.ts +10 -1
  23. package/src/init-repo.ts +14 -4
  24. package/src/media-store/content.ts +1 -1
  25. package/src/media-store/hand.ts +6 -1
  26. package/src/media-store/put.ts +11 -7
  27. package/src/media-store/space.ts +17 -3
  28. package/src/repo-config.ts +4 -1
  29. package/src/review/auto.ts +7 -2
  30. package/src/review/cells.ts +1 -1
  31. package/src/review/format.ts +2 -2
  32. package/src/review/model.ts +46 -13
  33. package/src/review/previews.ts +1 -1
  34. package/src/review/routes.ts +11 -0
  35. package/src/review/store.ts +18 -10
  36. package/src/secrets/list.ts +40 -0
  37. package/src/serve/hub-app/cols-svc.ts +2 -1
  38. package/src/serve/hub-app/review/review-kit.ts +4 -0
  39. package/src/serve/hub-app/review/review-st.ts +40 -3
  40. package/src/serve/hub-app/review/review-views.tsx +145 -64
  41. package/src/serve/hub-app/review/thread-st.ts +76 -16
  42. package/src/serve/hub-app/review.css +17 -2
  43. package/src/shipkit.ts +1 -1
  44. package/src/social/house.ts +7 -5
  45. package/src/wiki/run-wiki.ts +13 -3
@@ -0,0 +1,127 @@
1
+ // shipkit secret — the secrets of the repo you stand in, and the reads and
2
+ // writes through the house's secret manager (`credsReadCommand`, `credsCommand`).
3
+ // Logic in secrets/list.ts. A value only ever goes to stdout of `get`/`account`.
4
+ import { Command, Option } from 'clipanion'
5
+ import { existsSync } from 'fs'
6
+ import { basename, join } from 'path'
7
+ import { gitRoot } from '../core/git-root.ts'
8
+ import { houseRootOf } from '../home/home-start.ts'
9
+ import { loadIdentities, speakerOf } from '../identities/identities.ts'
10
+ import { loadRepoConfig, type RepoConfig } from '../repo-config.ts'
11
+ import { presence, secretsFor } from '../secrets/list.ts'
12
+ import { secretArgv } from '../smoke/run-smoke.ts'
13
+
14
+ type Where = { repos: string[]; identity: string | null; own: RepoConfig | null; house: RepoConfig | null }
15
+
16
+ async function where(cwd: string): Promise<Where> {
17
+ const root = gitRoot(cwd)?.top ?? cwd
18
+ const own = existsSync(join(root, 'repo.config.ts')) ? await loadRepoConfig(root) : null
19
+ const houseRoot = houseRootOf(cwd)
20
+ const house = houseRoot == null ? null : houseRoot === root ? own : await loadRepoConfig(houseRoot).catch(() => null)
21
+ const identity = speakerOf(own?.speaksAs, await loadIdentities({ cwd }))?.id ?? null
22
+ return { repos: [...new Set([own?.name ?? basename(root), basename(root)])], identity, own, house }
23
+ }
24
+
25
+ /** a refusal the command prints as one line and exits 1 on, never a stack */
26
+ class Refused extends Error {}
27
+
28
+ const template = (w: Where, key: 'credsReadCommand' | 'credsCommand'): string => {
29
+ const t = w.own?.[key] ?? w.house?.[key]
30
+ if (w.own == null && w.house == null) throw new Refused('FAIL not inside a house repo: run it from a repo that loads the house wiki')
31
+ if (t == null || t.trim() === '') throw new Refused(`FAIL no ${key} in this repo's repo.config.ts nor the house's: nothing knows how to reach the secret manager`)
32
+ return t
33
+ }
34
+
35
+ /** runs a verb, printing a refusal as its one line */
36
+ async function refusing(stderr: NodeJS.WritableStream, run: () => Promise<number>): Promise<number> {
37
+ try {
38
+ return await run()
39
+ } catch (e) {
40
+ if (!(e instanceof Refused)) throw e
41
+ stderr.write(`${e.message}\n`)
42
+ return 1
43
+ }
44
+ }
45
+
46
+ export class SecretListCommand extends Command {
47
+ static override paths = [['secret', 'list'], ['secret']]
48
+
49
+ static override usage = Command.Usage({
50
+ category: 'Secrets',
51
+ description: "the secrets for this repo: its own, its identity's, then those for every repo",
52
+ examples: [
53
+ ['the secrets for this repo, and which are missing', 'sk secret list'],
54
+ ['every row of the registry, with its scope', 'sk secret list --all'],
55
+ ],
56
+ })
57
+
58
+ all = Option.Boolean('--all', false, { description: 'every registry row, the ones out of scope marked' })
59
+ json = Option.Boolean('--json', false, { description: 'one json array, no presence read' })
60
+
61
+ async execute(): Promise<number> {
62
+ return refusing(this.context.stderr, () => this.list())
63
+ }
64
+
65
+ private async list(): Promise<number> {
66
+ const w = await where(process.cwd())
67
+ // in the house repo its own creds ARE the registry, each row with the scope it declares
68
+ const inHouse = w.house != null && w.house === w.own
69
+ const rows = secretsFor({ asker: w, own: inHouse ? [] : (w.own?.creds ?? []), house: w.house?.creds ?? [], all: this.all })
70
+ if (this.json) {
71
+ this.context.stdout.write(`${JSON.stringify(rows)}\n`)
72
+ return 0
73
+ }
74
+ const has = await presence(template(w, 'credsReadCommand'), rows.filter((r) => r.inScope).map((r) => r.name))
75
+ const say = (l: string): void => void this.context.stdout.write(`${l}\n`)
76
+ const mine = rows.filter((r) => r.mine).length
77
+ say(`${w.repos[0]} speaks as ${w.identity ?? 'no identity'}: ${rows.filter((r) => r.inScope).length} secrets, ${mine} for this repo or identity`)
78
+ const pad = (k: 'name' | 'for'): number => Math.max(...rows.map((r) => r[k].length))
79
+ for (const r of rows) {
80
+ const p = has.get(r.name)
81
+ const mark = !r.inScope ? 'out ' : p === true ? 'ok ' : 'MISS'
82
+ const fix = p === false ? ` → sk secret set ${r.name}` : ''
83
+ say(`${mark} ${r.name.padEnd(pad('name'))} ${r.level.padEnd(5)} ${r.for.padEnd(pad('for'))} ${(r.service ?? '').slice(0, 40)}${fix}`)
84
+ }
85
+ return 0
86
+ }
87
+ }
88
+
89
+ export class SecretReadCommand extends Command {
90
+ static override paths = [['secret', 'get'], ['secret', 'account']]
91
+
92
+ static override usage = Command.Usage({
93
+ category: 'Secrets',
94
+ description: 'print a secret (get) or the account stored with it (account), through the house secret manager',
95
+ examples: [['a token', 'sk secret get rv/cloudflare/api-token'], ['the login stored with it', 'sk secret account rv/pockethost/account']],
96
+ })
97
+
98
+ name = Option.String()
99
+
100
+ async execute(): Promise<number> {
101
+ const field = this.path[1] === 'account' ? 'account' : 'get'
102
+ return refusing(this.context.stderr, async () => {
103
+ const argv = secretArgv(template(await where(process.cwd()), 'credsReadCommand'), this.name, field)
104
+ return Bun.spawnSync(argv, { stdout: 'inherit', stderr: 'inherit' }).exitCode ?? 1
105
+ })
106
+ }
107
+ }
108
+
109
+ export class SecretSetCommand extends Command {
110
+ static override paths = [['secret', 'set']]
111
+
112
+ static override usage = Command.Usage({
113
+ category: 'Secrets',
114
+ description: 'store a secret and its account through the house secret manager: it prompts, or reads stdin',
115
+ examples: [['store a token', 'sk secret set rv/npm/token'], ['with its login', 'sk secret set rv/pockethost/account me@example.com']],
116
+ })
117
+
118
+ name = Option.String()
119
+ account = Option.String({ required: false })
120
+
121
+ async execute(): Promise<number> {
122
+ return refusing(this.context.stderr, async () => {
123
+ const argv = [...template(await where(process.cwd()), 'credsCommand').trim().split(/\s+/).map((x) => x.replaceAll('{name}', this.name)), ...(this.account != null ? [this.account] : [])]
124
+ return Bun.spawnSync(argv, { stdin: 'inherit', stdout: 'inherit', stderr: 'inherit' }).exitCode ?? 1
125
+ })
126
+ }
127
+ }
@@ -192,7 +192,7 @@ class IdentitiesCommand extends Command {
192
192
  static override usage = Command.Usage({
193
193
  category: 'Social',
194
194
  description: 'every identity of the machine: its accounts online over its accounts, and the repos speaking as it',
195
- details: "One folder an identity in the house repo's .shipkit/identities/. A repo names its own with speaksAs in repo.config.ts; the default identity speaks for a repo that names none. Page: wiki tools/shipkit/social.md",
195
+ details: "One folder an identity in the house repo's .shipkit/identities/. Every repo names its own with speaksAs in repo.config.ts (SK038 fails one that names none). Each identity lists the repos seen from here that speak as it, archived ones apart; seen from outside a folder of house repos, it lists none and says so. Page: wiki tools/shipkit/social.md",
196
196
  examples: [['every identity', 'sk identities'], ['as json', 'sk identities --json']],
197
197
  })
198
198
  json = Option.Boolean('--json', false, { description: 'one json object' })
@@ -201,24 +201,34 @@ class IdentitiesCommand extends Command {
201
201
  const { loadIdentities, speakerOf } = await import('../identities/identities.ts')
202
202
  const { houseRepoRoots } = await import('../social/house.ts')
203
203
  const ids = await loadIdentities()
204
- const repos = await houseRepoRoots()
204
+ const all = await houseRepoRoots(process.cwd(), { archived: true })
205
205
  const by = new Map<string, string[]>()
206
- for (const r of repos) {
207
- const id = speakerOf(r.speaksAs, ids)?.id ?? '(none)'
208
- by.set(id, [...(by.get(id) ?? []), r.name])
206
+ const old = new Map<string, string[]>()
207
+ const unnamed: string[] = []
208
+ for (const r of all) {
209
+ if (r.speaksAs == null) {
210
+ if (r.archived !== true) unnamed.push(r.name)
211
+ continue
212
+ }
213
+ const id = speakerOf(r.speaksAs, ids)?.id ?? `(unknown ${r.speaksAs})`
214
+ const into = r.archived === true ? old : by
215
+ into.set(id, [...(into.get(id) ?? []), r.name])
209
216
  }
210
217
  if (this.json) {
211
- say(this.context)(JSON.stringify({ dir: ids.dir, identities: ids.identities.map((i) => ({ id: i.id, name: i.name, default: i.default, site: i.site, accounts: i.accounts.map((a) => ({ id: a.id, handle: a.handle, live: a.live })), repos: by.get(i.id) ?? [] })), errors: ids.errors }))
212
- return ids.errors.length ? 1 : 0
218
+ say(this.context)(JSON.stringify({ dir: ids.dir, identities: ids.identities.map((i) => ({ id: i.id, name: i.name, default: i.default, site: i.site, accounts: i.accounts.map((a) => ({ id: a.id, handle: a.handle, live: a.live })), repos: by.get(i.id) ?? [], archived: old.get(i.id) ?? [] })), unnamed, seen: all.length, errors: ids.errors }))
219
+ return ids.errors.length || unnamed.length ? 1 : 0
213
220
  }
214
221
  for (const i of ids.identities) {
215
222
  const online = i.accounts.filter((a) => a.live !== '')
216
223
  say(this.context)(`${i.id}${i.default ? ' (default)' : ''} ${i.name} ${online.length}/${i.accounts.length} accounts online${i.site ? ` ${i.site}` : ''}`)
217
224
  say(this.context)(` online: ${online.map((a) => `${a.id} ${a.handle}`).join(', ') || 'none'}`)
218
- say(this.context)(` repos: ${(by.get(i.id) ?? []).join(', ') || 'none'}`)
225
+ const archived = old.get(i.id) ?? []
226
+ say(this.context)(` repos: ${(by.get(i.id) ?? []).join(', ') || 'none'}${archived.length > 0 ? `; archived: ${archived.join(', ')}` : ''}`)
219
227
  }
228
+ if (all.length === 0) say(this.context)(`note: no house repo seen from ${process.cwd()}, so every identity lists none: run it from a repo beside the house`)
229
+ if (unnamed.length > 0) say(this.context)(`FAIL: ${unnamed.length} repo(s) name no speaksAs (SK038): ${unnamed.join(', ')}`)
220
230
  for (const e of ids.errors) say(this.context)(`FAIL: ${e}`)
221
- return ids.errors.length ? 1 : 0
231
+ return ids.errors.length || unnamed.length ? 1 : 0
222
232
  })
223
233
  }
224
234
  }
@@ -10,12 +10,12 @@ export class WikiServeCommand extends Command {
10
10
  category: 'Wiki',
11
11
  description: 'live md link-graph server — reload = rescan',
12
12
  examples: [
13
- ['serve the cwd wiki', 'sk wiki serve'],
13
+ ['serve the repo wiki', 'sk wiki serve'],
14
14
  ['serve a subtree on a port', 'sk wiki serve --root agent --index process.md --port 6162'],
15
15
  ],
16
16
  })
17
17
 
18
- root = Option.String('--root', '.', { description: 'wiki root directory' })
18
+ root = Option.String('--root', { required: false, description: 'wiki root directory (default: wiki/, else the agent folder, else the cwd)' })
19
19
  port = Option.String('--port', '6161', { description: 'server port' })
20
20
  title = Option.String('--title', { required: false, description: 'page title shown in the graph header' })
21
21
  index = Option.String('--index', { required: false, description: 'entrypoint page (default: index.md AND README.md)' })
@@ -38,12 +38,12 @@ export class WikiLintCommand extends Command {
38
38
  category: 'Wiki',
39
39
  description: 'fail on orphan pages and dangling refs (exit 1)',
40
40
  examples: [
41
- ['lint the cwd wiki', 'sk wiki lint'],
41
+ ['lint the repo wiki', 'sk wiki lint'],
42
42
  ['lint a subtree', 'sk wiki lint --root agent --index process.md'],
43
43
  ],
44
44
  })
45
45
 
46
- root = Option.String('--root', '.', { description: 'wiki root directory' })
46
+ root = Option.String('--root', { required: false, description: 'wiki root directory (default: wiki/, else the agent folder, else the cwd)' })
47
47
  index = Option.String('--index', { required: false, description: 'entrypoint page (default: index.md AND README.md)' })
48
48
  skip = Option.String('--skip', { required: false, description: 'comma-separated dir names to exclude from the scan' })
49
49
 
@@ -15,6 +15,7 @@ export const FAMILY_PAGES: Readonly<Record<string, string>> = {
15
15
  Refactor: 'patterns/typescript/index.md',
16
16
  Review: 'tools/shipkit/review.md',
17
17
  Scaffold: 'patterns/pocketbase/index.md',
18
+ Secrets: 'services/secrets/index.md',
18
19
  Serve: 'tools/shipkit/home.md',
19
20
  Setup: 'patterns/rv-conventions/index.md',
20
21
  Social: 'tools/shipkit/social.md',
@@ -9,7 +9,7 @@ import { AssetsAddCommand, AssetsCheckCommand, AssetsFillCommand, AssetsGenComma
9
9
  import { BumpCommand } from './cmd_Bump.ts'
10
10
  import { CallsCommand } from './cmd_Calls.ts'
11
11
  import { TimeCommand } from './cmd_Time.ts'
12
- import { DrillCleanCommand, DrillCompareCommand, DrillReportCommand, DrillVerdictCommand } from './cmd_Drill.ts'
12
+ import { DrillCalibrateCommand, DrillCleanCommand, DrillCloneCommand, DrillCompareCommand, DrillFinishCommand, DrillReportCommand, DrillVerdictCommand } from './cmd_Drill.ts'
13
13
  import { CheckCommand } from './cmd_Check.ts'
14
14
  import { CommandsCommand } from './cmd_Commands.ts'
15
15
  import { withFamilyPage } from './family-pages.ts'
@@ -51,6 +51,7 @@ import { MEDIA_COMMANDS } from './cmd_Media.ts'
51
51
  import { BACKUP_COMMANDS } from './cmd_Backup.ts'
52
52
  import { VEILLE_COMMANDS } from './cmd_Veille.ts'
53
53
  import { TuiCommand } from './cmd_Tui.ts'
54
+ import { SecretListCommand, SecretReadCommand, SecretSetCommand } from './cmd_Secret.ts'
54
55
  import { WikiLintCommand, WikiServeCommand } from './cmd_Wiki.ts'
55
56
 
56
57
 
@@ -108,6 +109,9 @@ export function buildCli(): Cli {
108
109
  cli.register(AskNewCommand)
109
110
  cli.register(WikiServeCommand)
110
111
  cli.register(WikiLintCommand)
112
+ cli.register(SecretListCommand)
113
+ cli.register(SecretReadCommand)
114
+ cli.register(SecretSetCommand)
111
115
  cli.register(AssetsFillCommand)
112
116
  cli.register(AssetsAddCommand)
113
117
  cli.register(AssetsGenCommand)
@@ -145,6 +149,9 @@ export function buildCli(): Cli {
145
149
  cli.register(DrillVerdictCommand)
146
150
  cli.register(DrillCompareCommand)
147
151
  cli.register(DrillCleanCommand)
152
+ cli.register(DrillCloneCommand)
153
+ cli.register(DrillFinishCommand)
154
+ cli.register(DrillCalibrateCommand)
148
155
  cli.register(ConfigKeysCommand)
149
156
 
150
157
  return cli
@@ -0,0 +1,42 @@
1
+ // who a house resource is for: some repos, some identities, or every repo.
2
+ // One type and one reader, so a secret and anything scoped later answer alike.
3
+ // The md form, one cell: `all`, or `repo:<name>` and `identity:<id>` joined by commas.
4
+
5
+ /** absent or empty = every repo */
6
+ export type Scope = {
7
+ /** repo names, as `repo.config.ts` names them or as their folder is called */
8
+ repos?: string[]
9
+ /** identity ids, as `speaksAs` names them */
10
+ identities?: string[]
11
+ }
12
+
13
+ /** the repo asking: every name it answers to (its config name, its folder), and the identity it speaks as */
14
+ export type Asker = { repos: string[]; identity: string | null }
15
+
16
+ const listed = (xs: string[] | undefined): boolean => (xs ?? []).length > 0
17
+
18
+ export const scopesAll = (s: Scope | undefined): boolean => s == null || (!listed(s.repos) && !listed(s.identities))
19
+
20
+ /** in scope when the scope is for all, names the repo, or names its identity */
21
+ export function inScope(s: Scope | undefined, a: Asker): boolean {
22
+ if (scopesAll(s)) return true
23
+ return (s!.repos ?? []).some((r) => a.repos.includes(r)) || (a.identity != null && (s!.identities ?? []).includes(a.identity))
24
+ }
25
+
26
+ /** the md cell as a scope; throws on a token that is neither `all`, `repo:` nor `identity:` */
27
+ export function parseScope(cell: string): Scope {
28
+ const text = cell.replaceAll('`', '').trim()
29
+ if (text === '' || text === 'all') return {}
30
+ const s: Scope = {}
31
+ for (const raw of text.split(',')) {
32
+ const t = raw.trim()
33
+ const m = /^(repo|identity):([a-z0-9][a-z0-9._-]*)$/.exec(t)
34
+ if (m == null) throw new Error(`scope "${cell}": "${t}" is not repo:<name> or identity:<id> (or all)`)
35
+ const key = m[1] === 'repo' ? 'repos' : 'identities'
36
+ ;(s[key] ??= []).push(m[2]!)
37
+ }
38
+ return s
39
+ }
40
+
41
+ export const scopeText = (s: Scope | undefined): string =>
42
+ scopesAll(s) ? 'all' : [...(s!.repos ?? []).map((r) => `repo:${r}`), ...(s!.identities ?? []).map((i) => `identity:${i}`)].join(', ')
@@ -0,0 +1,65 @@
1
+ // a drill card (`drill.md` in a task folder, wiki meta/speed-up-agents/index.md): the task text sent to every run, and
2
+ // the rows the commands read. Pure: md in, a card out. The page is written by hand, so every error names its fix.
3
+
4
+ export type Card = {
5
+ /** the exact text a run gets, nothing added */
6
+ task: string
7
+ base: string | null
8
+ reference: string | null
9
+ /** globs a good run never touches, held against the patch */
10
+ forbid: string[]
11
+ /** one shell line run in the clone after the run, exit 0 = done */
12
+ doneCmd: string | null
13
+ }
14
+
15
+ const unwrap = (v: string): string => v.trim().replace(/^`(.*)`$/s, '$1').trim()
16
+ const none = (v: string | undefined): boolean => v == null || v === '' || /^(none|-)$/i.test(v)
17
+
18
+ /** the rows of every `| field | value |` table, the field lowercased, `\|` read as a pipe */
19
+ function rows(md: string): Map<string, string> {
20
+ const out = new Map<string, string>()
21
+ for (const line of md.split('\n')) {
22
+ if (!line.startsWith('|')) continue
23
+ const cells = line
24
+ .replace(/\\\|/g, '\u0000')
25
+ .split('|')
26
+ .slice(1, -1)
27
+ .map((c) => c.replace(/\u0000/g, '|').trim())
28
+ const [k, v] = cells
29
+ if (k == null || v == null || /^-+$/.test(k) || k.toLowerCase() === 'field') continue
30
+ out.set(k.toLowerCase(), v)
31
+ }
32
+ return out
33
+ }
34
+
35
+ /** the card, or why it is not one */
36
+ export function parseCard(md: string): Card | string {
37
+ const head = /^##\s+task\b.*$/im.exec(md)
38
+ if (head == null) return 'no `## task` heading: the task text goes in a fenced block under it'
39
+ const fenced = /^```[^\n]*\n([\s\S]*?)\n```/m.exec(md.slice(head.index + head[0].length))
40
+ const task = fenced?.[1]?.trim() ?? ''
41
+ if (task === '') return 'the `## task` heading has no fenced block with the task text'
42
+ const r = rows(md)
43
+ const sha = (k: string): string | null => {
44
+ const v = r.get(k)
45
+ return none(v) ? null : unwrap(v as string).split(/\s/)[0] ?? null
46
+ }
47
+ const forbid = r.get('forbid')
48
+ const done = r.get('done cmd')
49
+ return {
50
+ task,
51
+ base: sha('base'),
52
+ reference: sha('reference'),
53
+ forbid: none(forbid)
54
+ ? []
55
+ : (forbid as string)
56
+ .split(',')
57
+ .map(unwrap)
58
+ .filter((g) => g !== ''),
59
+ doneCmd: none(done) ? null : unwrap(done as string),
60
+ }
61
+ }
62
+
63
+ /** the patch paths a forbid glob matches */
64
+ export const forbidHits = (paths: readonly string[], globs: readonly string[]): string[] =>
65
+ paths.filter((p) => globs.some((g) => new Bun.Glob(g).match(p)))
@@ -1,7 +1,7 @@
1
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, one commit named « drill base », no remote), so a wrong path is refused, and a
3
- // moved folder can be put back. a move across disks fails loud, it never falls back to a delete.
4
- import { existsSync, lstatSync, mkdirSync, realpathSync, renameSync } from 'fs'
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
5
  import { homedir } from 'os'
6
6
  import { basename, dirname, join, resolve } from 'path'
7
7
  import { gitBin } from '../core/git-bin.ts'
@@ -27,20 +27,31 @@ export function notADrillCopy(dir: string): string | null {
27
27
  if (!existsSync(join(abs, '.git')) || !lstatSync(join(abs, '.git')).isDirectory()) return 'has no .git folder of its own'
28
28
  const top = git(abs, ['rev-parse', '--show-toplevel'])
29
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
30
33
  const count = git(abs, ['rev-list', '--count', '--all'])
31
34
  if (count !== '1') return `holds ${count ?? 'no'} commits, a drill copy holds one`
32
35
  const subject = git(abs, ['log', '-1', '--format=%s'])
33
36
  if (subject !== DRILL_BASE) return `its commit is « ${subject ?? ''} », not « ${DRILL_BASE} »`
34
- if ((git(abs, ['remote']) ?? '') !== '') return 'has a git remote'
35
37
  return null
36
38
  }
37
39
 
38
40
  export type CleanResult = { dir: string; to: string } | { dir: string; refused: string }
39
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
+
40
51
  /** moves one drill copy into `trash` under a free name; dry = report only */
41
- export function cleanDrillCopy(dir: string, opts: { trash?: string; dry?: boolean; now?: Date } = {}): CleanResult {
52
+ export function cleanDrillCopy(dir: string, opts: { trash?: string; dry?: boolean; now?: Date; check?: (dir: string) => string | null } = {}): CleanResult {
42
53
  const abs = resolve(dir)
43
- const why = notADrillCopy(abs)
54
+ const why = (opts.check ?? notADrillCopy)(abs)
44
55
  if (why != null) return { dir: abs, refused: why }
45
56
  const trash = opts.trash ?? trashDir()
46
57
  const stamp = (opts.now ?? new Date()).toISOString().replace(/[-:]/g, '').replace(/\..*/, '')
@@ -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) {