rvlib-shipkit 2.15.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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,11 @@
1
+ ## 2.16.0
2
+
3
+ - **A drill runs cold in a sealed copy.** `sk drill clone <task folder>` makes a copy of the repo with no way back to it and prints the headless command that runs it, `sk drill finish <copy>` records the run (patch, report, leaks, done command) and trashes the copy, `sk drill calibrate` proves the card's done command fails on the base and passes on the reference, and `sk drill compare` says keep or revert, never keeping an unjudged or worse run.
4
+ - **`sk media put --public` publishes a file anyone downloads.** It goes up under `public/<label>/<sha256>.<ext>` with a public-read ACL and prints a permanent URL on the CDN edge; nobody lists the bucket, and every object outside `public/` stays private, its ACL decided by its key alone. A public file is never purged from the disk, `public` is no label for a plain put, and `--public --link` is refused. A put of many files sends 8 at a time and still prints them in the order named.
5
+ - **A shipkit suite run without its preload is refused the machine's real home.** Run from another folder, the suite skipped its temp home and a test that deletes the media index deleted the real one; `homeDir()` now throws under the suite unless a home is set, the fix named.
6
+ - **SK038: a repo names the identity it speaks as.** On a machine with identities, `repo.config.ts` without `speaksAs`, or with an id the machine does not hold, fails, and the message lists the ids to pick from. A repo that names none no longer falls to the default identity silently. With no identities on the machine it passes.
7
+ - **`sk identities` says why a repo list is empty.** Archived repos show apart (`archived: …`), a repo naming no `speaksAs` is a FAIL line that exits 1, and run outside a folder of house repos it notes that none can be seen from there. `--json` adds `archived`, `unnamed` and `seen`.
8
+
1
9
  ## 2.15.0
2
10
 
3
11
  - **`sk drill clean <run folder>`** moves a recorded drill run folder to the trash, never deletes it, and refuses a folder that is not a drill copy: a git repo of its own, one commit named « drill base », no remote. `--dry-run` says what would move.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rvlib-shipkit",
3
- "version": "2.15.0",
3
+ "version": "2.16.0",
4
4
  "funding": "https://github.com/sponsors/rvion",
5
5
  "description": "All-in-one repo companion: ci gate (task DAG), auto-discovered health checks, release-contract fulfillness, asks queue, md-wiki tools, asset atelier, live tui",
6
6
  "license": "MIT",
@@ -0,0 +1,66 @@
1
+ // SK038 speaks as: on a machine with identities (a house), every repo names the identity it
2
+ // speaks as, `speaksAs` in repo.config.ts, and that identity exists. A repo that names none
3
+ // would speak as the default one, a choice nobody made, so it fails instead. Outside a house,
4
+ // or with a house that holds none (a stranger, a CI box), there is nothing to name, and it
5
+ // passes; an identities folder named by SHIPKIT_IDENTITIES_DIR that is missing fails.
6
+ import { existsSync, readdirSync } from 'fs'
7
+ import { join } from 'path'
8
+ import { check } from '../check.ts'
9
+ import { CONFIG_FILE } from '../core/identity.ts'
10
+ import { LAYOUT } from '../core/layout.ts'
11
+ import { houseRootOf } from '../home/home-start.ts'
12
+ import { speaksAsOfText } from '../social/house.ts'
13
+
14
+ const FIX = "add `speaksAs: '<id>'` to defineRepo in repo.config.ts, an id `sk identities` lists"
15
+
16
+ export type MachineIds = { ids: string[] } | { none: string } | { broken: string }
17
+
18
+ /** the identity ids of this machine's house, sorted, or why there are none, or a named folder that is missing */
19
+ export function machineIdentityIds(root: string): MachineIds {
20
+ const env = process.env['SHIPKIT_IDENTITIES_DIR']
21
+ if (env != null && env !== '' && !existsSync(env)) return { broken: `SHIPKIT_IDENTITIES_DIR names ${env}, which does not exist` }
22
+ const house = env ? null : houseRootOf(root)
23
+ if (!env && house == null) return { none: 'not a house repo: no identities to name' }
24
+ const dir = env || join(house!, LAYOUT.identities)
25
+ const ids = existsSync(dir)
26
+ ? readdirSync(dir, { withFileTypes: true })
27
+ .filter((e) => e.isDirectory() && existsSync(join(dir, e.name, 'identity.md')))
28
+ .map((e) => e.name)
29
+ .sort()
30
+ : []
31
+ return ids.length === 0 ? { none: 'the house holds no identity' } : { ids }
32
+ }
33
+
34
+ /** what is wrong with a config's speaksAs against the machine's ids, null when it is fine */
35
+ export function speaksAsProblem(configText: string, ids: string[]): string | null {
36
+ const id = speaksAsOfText(configText)
37
+ if (id == null) return `${CONFIG_FILE} names no speaksAs: every repo on this machine says which identity it speaks as (${ids.join(', ')})`
38
+ if (!ids.includes(id)) return `${CONFIG_FILE}: speaksAs '${id}' is no identity of this machine (${ids.join(', ')})`
39
+ return null
40
+ }
41
+
42
+ export const speaksAs = check({
43
+ id: 'SK038',
44
+ blocking: true,
45
+ title: 'speaks as',
46
+ description: 'repo.config.ts names the identity the repo speaks as, one this machine holds',
47
+ owner: 'tools/shipkit/social-identities.md',
48
+ runs: { onPreCommit: false, onCi: true, onFull: true, onRelease: true, onHealth: true, onSave: 'moved', onClock: false },
49
+ // the config, and which identities this machine holds
50
+ cache: { by: 'files', inputs: [CONFIG_FILE], key: (env) => JSON.stringify(machineIdentityIds(env.root)) },
51
+ fix: 'none',
52
+ applies: 'always',
53
+ run: (c) => {
54
+ const m = machineIdentityIds(c.root)
55
+ if ('broken' in m) return c.fail(m.broken, 'point it at the identities folder, or unset it')
56
+ if ('none' in m) return c.ok(m.none)
57
+ const { ids } = m
58
+ const text = c.read(CONFIG_FILE)
59
+ if (text == null) return c.note(`no ${CONFIG_FILE}`)
60
+ const why = speaksAsProblem(text, ids)
61
+ if (why != null) return c.fail(why, FIX)
62
+ c.ok(`speaks as ${speaksAsOfText(text)}`)
63
+ },
64
+ })
65
+
66
+ export default speaksAs
@@ -1,8 +1,9 @@
1
- // `sk drill`: the records of a measured drill (wiki meta/speed-up-agents/index.md). report = one run's transcript
2
- // as run<n>.json + run<n>.md, verdict = the judged quality added to a run, compare = every run of a drill side
3
- // by side. It reads transcripts and writes files; it never starts an agent (core/agent-spawn.ts). Exit 0 with
4
- // the files written, 1 when a transcript or a run is missing or an argument does not parse, 2 on a bad verdict or --out.
5
- // clean = a run folder moved to the trash once it is recorded, refused unless it is a drill copy.
1
+ // `sk drill`: a measured drill (wiki meta/speed-up-agents/index.md). clone = a sealed copy for one run and the
2
+ // command that runs it cold, finish = that run recorded (patch, report, done cmd) and its copy trashed, calibrate =
3
+ // the card's done cmd proven on the base and the reference, report = one transcript as run<n>.json + run<n>.md,
4
+ // verdict = the judged quality added to a run, compare = every run side by side with the keep or revert line,
5
+ // clean = a copy moved to the trash. It never starts an agent (core/agent-spawn.ts): the session runs the printed
6
+ // command. Exit 0 when done, 1 when something is missing or a check fails, 2 on a bad argument.
6
7
  import { Command, Option } from 'clipanion'
7
8
  import { existsSync, readdirSync, readFileSync, writeFileSync } from 'fs'
8
9
  import { basename, dirname, join, resolve } from 'path'
@@ -23,6 +24,13 @@ async function findTranscript(ref: string): Promise<string | null> {
23
24
  return null
24
25
  }
25
26
 
27
+ const projectRoots = async (): Promise<string[]> => {
28
+ const { discoverConfigRoots } = await import('../reflect/prompt-corpus.ts')
29
+ return discoverConfigRoots().map((r) => r.projects)
30
+ }
31
+ const expand = (p: string): string => resolve(p.replace(/^~(?=\/)/, process.env.HOME ?? '~'))
32
+ const short = (sha: string): string => sha.slice(0, 10)
33
+
26
34
  const writeRun = async (outBase: string, run: import('../drill/run.ts').DrillRun): Promise<void> => {
27
35
  const { renderRun } = await import('../drill/render.ts')
28
36
  writeFileSync(`${outBase}.json`, JSON.stringify(run, null, 2) + '\n')
@@ -103,7 +111,8 @@ export class DrillVerdictCommand extends Command {
103
111
  err.write(`FAIL: ${v}\n`)
104
112
  return 2
105
113
  }
106
- const run = JSON.parse(readFileSync(this.run, 'utf8')) as import('../drill/run.ts').DrillRun
114
+ const { normalizeRun } = await import('../drill/run.ts')
115
+ const run = normalizeRun(JSON.parse(readFileSync(this.run, 'utf8')))
107
116
  await writeRun(resolve(this.run).replace(/\.json$/, ''), { ...run, verdict: v })
108
117
  this.context.stdout.write(`ok: ${this.run}: done ${v.done}, quality ${v.quality}, tests ${v.tests}, design ${v.design}\n`)
109
118
  return 0
@@ -114,7 +123,7 @@ export class DrillCompareCommand extends Command {
114
123
  static override paths = [['drill', 'compare']]
115
124
  static override usage = Command.Usage({
116
125
  category: 'Drill',
117
- description: 'every run of a drill side by side in compare.md: deltas, verdicts, when each md page was read',
126
+ description: 'every run of a drill side by side in compare.md: keep or revert, the gate, deltas, pages read',
118
127
  details: 'Reads the run<n>.json records of one task folder in run order and writes compare.md beside them. Flags a run whose prompt differs from the first. A ratio always reads up from 1: "1.7x more", never "0.6x fewer".',
119
128
  examples: [['one task of a speed-up drill', 'sk drill compare .shipkit/plans/20261104-speed-up/form']],
120
129
  })
@@ -137,10 +146,13 @@ export class DrillCompareCommand extends Command {
137
146
  return 1
138
147
  }
139
148
  const { renderCompare } = await import('../drill/render.ts')
140
- const runs = labels.map((label) => ({ label, run: JSON.parse(readFileSync(join(dir, `${label}.json`), 'utf8')) as import('../drill/run.ts').DrillRun }))
149
+ const { normalizeRun } = await import('../drill/run.ts')
150
+ const { groupsOf, scoreOf } = await import('../drill/score.ts')
151
+ const runs = labels.map((label) => ({ label, run: normalizeRun(JSON.parse(readFileSync(join(dir, `${label}.json`), 'utf8'))) }))
141
152
  const out = join(dir, 'compare.md')
142
153
  writeFileSync(out, renderCompare(basename(dir), runs))
143
- this.context.stdout.write(`ok: ${out}: ${runs.length} runs\n`)
154
+ const score = scoreOf(groupsOf(runs))
155
+ this.context.stdout.write(`ok: ${out}: ${runs.length} runs, ${score.verdict}: ${score.why}\n`)
144
156
  return 0
145
157
  }
146
158
  }
@@ -150,10 +162,10 @@ export class DrillCleanCommand extends Command {
150
162
  static override usage = Command.Usage({
151
163
  category: 'Drill',
152
164
  description: 'a recorded drill run folder moved to the trash, never deleted, refused unless it is a drill copy',
153
- details: 'A drill copy is a git repo of its own (no worktree) holding one commit named « drill base » and no remote. Anything else is refused with the reason, so a wrong path never moves. The folder lands in the trash under its name and the time, to put back by hand. --dry-run says what would move. Exit 0 when every folder moved, 1 when one was refused.',
165
+ details: 'A drill copy is a git repo of its own (no worktree) with no remote: a sealed copy (its record in .git/drill.json, `sk drill finish` trashes it itself), or an older copy holding one commit named « drill base ». Anything else is refused with the reason, so a wrong path never moves. The folder lands in the trash under its name and the time, to put back by hand. --dry-run says what would move. Exit 0 when every folder moved, 1 when one was refused.',
154
166
  examples: [
155
- ['one run, once its report is written', 'sk drill clean ~/drills/app--form'],
156
- ['see first', 'sk drill clean ~/drills/app--form ~/drills/app--list --dry-run'],
167
+ ['a sealed copy left by --keep', 'sk drill clean /var/folders/xx/T/app-Ab12Cd'],
168
+ ['see first', 'sk drill clean /var/folders/xx/T/app-Ab12Cd --dry-run'],
157
169
  ],
158
170
  })
159
171
  dirs = Option.Rest({ required: 1, name: 'run folder' })
@@ -172,3 +184,198 @@ export class DrillCleanCommand extends Command {
172
184
  return refused === 0 ? 0 : 1
173
185
  }
174
186
  }
187
+
188
+ export class DrillCloneCommand extends Command {
189
+ static override paths = [['drill', 'clone']]
190
+ static override usage = Command.Usage({
191
+ category: 'Drill',
192
+ description: 'a sealed copy of the repo for one cold run, and the headless command that runs it',
193
+ details: [
194
+ 'Reads the task folder\'s drill.md (its task text, its base). The copy lands in a temp folder named after the repo only, as one commit with the base\'s own message, author and date. --setup lays CLAUDE.md, AGENTS.md, agent/ and .claude/ of another sha over the base (wiki/ too when the repo is the house that hosts the wiki).',
195
+ 'Every drill folder under .shipkit/plans is removed, lines naming the drill are dropped, and the copy fails loud if a card or a run patch is left. Every file gets the commit time, deps come from a frozen install. The house repo reads its own wiki; a repo that includes the house wiki reads the live one, or a sealed copy of it with --wiki <sha>. No secret is copied.',
196
+ 'It prints the command the session runs: a headless claude in the copy, denied the web, the remote, the main repo and the transcripts. It never starts it. Then `sk drill finish <copy>`.',
197
+ ].join(' '),
198
+ examples: [
199
+ ['round 1, the card\'s base', 'sk drill clone .shipkit/plans/20261105-speed-up/deploy'],
200
+ ['round 2, the setup of the commit under test over the same base', 'sk drill clone .shipkit/plans/20261105-speed-up/deploy --setup 2be02cd3'],
201
+ ],
202
+ })
203
+ task = Option.String({ required: true, name: 'task folder' })
204
+ base = Option.String('--base', { description: 'the commit the copy holds; default: the card\'s base row' })
205
+ setup = Option.String('--setup', { description: 'the commit whose setup files the run sees; default: the base' })
206
+ wiki = Option.String('--wiki', { description: 'a house commit whose wiki the run reads instead of the live one' })
207
+ install = Option.Boolean('--install', true, { description: 'a frozen bun install in the copy (--no-install skips it)' })
208
+
209
+ async execute(): Promise<number> {
210
+ const err = this.context.stderr
211
+ const task = expand(this.task)
212
+ const { readCard } = await import('../drill/finish.ts')
213
+ const card = await readCard(task)
214
+ if (typeof card === 'string') {
215
+ err.write(`FAIL: ${card}\n`)
216
+ return 1
217
+ }
218
+ const base = this.base ?? card.base
219
+ if (base == null) {
220
+ err.write('FAIL: no base: give --base <sha>, or a `base` row in the card\n')
221
+ return 1
222
+ }
223
+ const { gitRoot } = await import('../core/git-root.ts')
224
+ const repo = gitRoot(task)?.top
225
+ if (repo == null) {
226
+ err.write(`FAIL: ${this.task} is not inside a git repo\n`)
227
+ return 1
228
+ }
229
+ const { houseRootOf } = await import('../home/home-start.ts')
230
+ const { seal, PROMPT, SETTINGS } = await import('../drill/seal.ts')
231
+ try {
232
+ const s = seal({ repo, task, base, setup: this.setup, wiki: this.wiki, house: houseRootOf(repo), prompt: card.task, install: this.install, configRoots: await projectRoots() })
233
+ const out = this.context.stdout
234
+ out.write(`ok: sealed copy ${s.dir}: base ${short(s.meta.base)}, setup ${short(s.meta.setup)}, setup key ${s.meta.setupKey}, wiki ${s.meta.wiki.mode}\n`)
235
+ for (const n of s.notes) out.write(`${n}\n`)
236
+ if ((process.env.ANTHROPIC_API_KEY ?? '') !== '') out.write('💸 ANTHROPIC_API_KEY is set: a headless run bills the API, not the plan. Unset it in the run\'s shell\n')
237
+ out.write(`run it cold, from the session, in the background (the run sees only the task text):\n (cd ${s.dir} && claude -p --permission-mode auto --permission-prompts none --settings ${SETTINGS} < ${PROMPT})\nthen: sk drill finish ${s.dir}\n`)
238
+ return 0
239
+ } catch (e) {
240
+ err.write(`FAIL: ${(e as Error).message}\n`)
241
+ return 1
242
+ }
243
+ }
244
+ }
245
+
246
+ export class DrillFinishCommand extends Command {
247
+ static override paths = [['drill', 'finish']]
248
+ static override usage = Command.Usage({
249
+ category: 'Drill',
250
+ description: 'one run recorded from its sealed copy: patch, report, leaks, done cmd, then the copy trashed',
251
+ details: [
252
+ 'Finds the one headless session started in the copy (or the sub-agent named by --agent, a smoke run never scored with cold ones), writes run<n>.patch against the copy\'s first commit, run<n>.json and run<n>.md in the task folder, then runs the card\'s done cmd in the copy and holds the patch against its forbid globs.',
253
+ 'The copy and its wiki copy go to the trash unless --keep.',
254
+ ].join(' '),
255
+ examples: [
256
+ ['after a cold run', 'sk drill finish /var/folders/xx/T/app-Ab12Cd'],
257
+ ['after a sub-agent smoke run', 'sk drill finish /var/folders/xx/T/app-Ab12Cd --agent a7e0f9cd61f44cfb4'],
258
+ ],
259
+ })
260
+ copy = Option.String({ required: true, name: 'copy' })
261
+ agent = Option.String('--agent', { description: 'the sub-agent id of a smoke run' })
262
+ keep = Option.Boolean('--keep', false, { description: 'leave the copy in place' })
263
+
264
+ async execute(): Promise<number> {
265
+ const err = this.context.stderr
266
+ const out = this.context.stdout
267
+ const copy = expand(this.copy)
268
+ const { readMeta } = await import('../drill/seal.ts')
269
+ const meta = existsSync(copy) ? readMeta(copy) : null
270
+ if (meta == null) {
271
+ err.write(`FAIL: ${this.copy} is not a sealed drill copy: no .git/drill.json (sk drill clone makes one)\n`)
272
+ return 1
273
+ }
274
+ const f = await import('../drill/finish.ts')
275
+ const card = await f.readCard(meta.task)
276
+ if (typeof card === 'string') {
277
+ err.write(`FAIL: ${card}\n`)
278
+ return 1
279
+ }
280
+ let transcript: string | null
281
+ if (this.agent != null) transcript = await findTranscript(this.agent)
282
+ else {
283
+ const found = f.coldTranscripts(copy, await projectRoots())
284
+ if (found.length > 1) {
285
+ err.write(`FAIL: ${found.length} sessions ran in the copy, one run is one session:\n${found.map((t) => ` ${t}`).join('\n')}\n`)
286
+ return 1
287
+ }
288
+ transcript = found[0] ?? null
289
+ }
290
+ if (transcript == null) {
291
+ err.write(`FAIL: no transcript: ${this.agent == null ? 'no headless session ran in the copy yet' : `no sub-agent ${this.agent}`}\n`)
292
+ return 1
293
+ }
294
+ const n = f.nextRun(meta.task)
295
+ const base = join(meta.task, `run${n}`)
296
+ const { patch, agentCommits } = f.runPatch(copy)
297
+ f.writePatch(`${base}.patch`, patch)
298
+ const { drillRun, patchStats } = await import('../drill/run.ts')
299
+ const { loadMasker } = await import('../agent-time/mask.ts')
300
+ const { forbidHits } = await import('../drill/card.ts')
301
+ const mask = loadMasker(meta.repo)
302
+ const run = drillRun(readFileSync(transcript, 'utf8').split('\n'), { transcript: transcript.replace(process.env.HOME ?? '\0', '~'), root: copy, patch, mask, private: meta.private })
303
+ const wiki = meta.wiki.mode === 'copy' ? `copy ${short(meta.wiki.sha)}` : meta.wiki.mode === 'live' ? `live ${meta.wiki.tree.slice(0, 10)}${meta.wiki.dirty ? ' dirty' : ''}` : meta.wiki.mode
304
+ const recorded = {
305
+ ...run,
306
+ mode: this.agent == null ? ('cold' as const) : ('subagent' as const),
307
+ setup: { base: meta.base, setup: meta.setup, key: meta.setupKey, wiki },
308
+ done: card.doneCmd == null ? null : f.runDone(copy, card.doneCmd, mask),
309
+ forbidHits: forbidHits(patchStats(patch).paths, card.forbid),
310
+ }
311
+ await writeRun(base, recorded)
312
+ const { gateOf } = await import('../drill/score.ts')
313
+ const gate = gateOf(recorded)
314
+ out.write(`ok: ${base}.json, .md and .patch: ${run.calls} calls, ${Math.round(run.wall / 1000)}s, gate ${gate.length === 0 ? 'passed' : `fails (${gate.join(', ')})`}\n`)
315
+ if (agentCommits > 0) out.write(`the run made ${agentCommits} commits: the patch holds them\n`)
316
+ if (this.keep) return 0
317
+ const { cleanDrillCopy, notAWikiCopy } = await import('../drill/clean.ts')
318
+ let refused = 0
319
+ for (const r of [cleanDrillCopy(copy), ...(meta.wiki.mode === 'copy' ? [cleanDrillCopy(meta.wiki.dir, { check: notAWikiCopy })] : [])]) {
320
+ if ('refused' in r) {
321
+ refused++
322
+ err.write(`REFUSE: ${r.dir} ${r.refused}: left in place\n`)
323
+ } else out.write(`moved ${r.dir} → ${r.to}\n`)
324
+ }
325
+ return refused === 0 ? 0 : 1
326
+ }
327
+ }
328
+
329
+ export class DrillCalibrateCommand extends Command {
330
+ static override paths = [['drill', 'calibrate']]
331
+ static override usage = Command.Usage({
332
+ category: 'Drill',
333
+ description: 'the card\'s done cmd proven before round 1: it fails on the base and passes on the reference',
334
+ details: 'Seals one copy at the card\'s base and one at its reference, runs the done cmd in each, and trashes both. A done cmd that passes on the base measures nothing; one that fails on the reference fails a right answer. Exit 0 when both hold, 1 otherwise with the output tail. Read the reference diff too: a done cmd that checks a name only the reference uses fails another right answer.',
335
+ examples: [['once per card', 'sk drill calibrate .shipkit/plans/20261105-speed-up/deploy']],
336
+ })
337
+ task = Option.String({ required: true, name: 'task folder' })
338
+ install = Option.Boolean('--install', true, { description: 'a frozen bun install in each copy (--no-install skips it)' })
339
+
340
+ async execute(): Promise<number> {
341
+ const err = this.context.stderr
342
+ const out = this.context.stdout
343
+ const task = expand(this.task)
344
+ const f = await import('../drill/finish.ts')
345
+ const card = await f.readCard(task)
346
+ if (typeof card === 'string') {
347
+ err.write(`FAIL: ${card}\n`)
348
+ return 1
349
+ }
350
+ if (card.base == null || card.reference == null || card.doneCmd == null) {
351
+ err.write('FAIL: calibrate needs the card rows base, reference and done cmd\n')
352
+ return 1
353
+ }
354
+ const { gitRoot } = await import('../core/git-root.ts')
355
+ const repo = gitRoot(task)?.top
356
+ if (repo == null) {
357
+ err.write(`FAIL: ${this.task} is not inside a git repo\n`)
358
+ return 1
359
+ }
360
+ const { houseRootOf } = await import('../home/home-start.ts')
361
+ const { seal } = await import('../drill/seal.ts')
362
+ const { cleanDrillCopy } = await import('../drill/clean.ts')
363
+ const roots = await projectRoots()
364
+ let ok = true
365
+ for (const [label, sha, want] of [['base', card.base, false], ['reference', card.reference, true]] as const) {
366
+ try {
367
+ const s = seal({ repo, task, base: sha, house: houseRootOf(repo), prompt: '', install: this.install, configRoots: roots })
368
+ const r = f.runDone(s.dir, card.doneCmd)
369
+ cleanDrillCopy(s.dir)
370
+ const held = (r.exit === 0) === want
371
+ ok &&= held
372
+ out.write(`${held ? 'ok' : 'FAIL'}: ${label} ${short(sha)}: exit ${r.exit} in ${Math.round(r.ms / 1000)}s, ${want ? 'must pass' : 'must fail'}\n`)
373
+ if (!held) out.write(`${r.tail}\n`)
374
+ } catch (e) {
375
+ ok = false
376
+ err.write(`FAIL: ${label} ${short(sha)}: ${(e as Error).message}\n`)
377
+ }
378
+ }
379
+ return ok ? 0 : 1
380
+ }
381
+ }
@@ -162,37 +162,63 @@ export class MediaPurgeCommand extends Command {
162
162
  }
163
163
  }
164
164
 
165
+ /** files a put sends at once: each waits on a HEAD, a PUT and a HEAD, so one at a time spends the put on round trips */
166
+ const PUT_JOBS = 8
167
+
165
168
  const PUT_DETAILS = `The one way an agent of any repo keeps a file in the owner's private Space: never call the Space client directly. Each file is kept by its content as <label>/<sha256>.<ext>, private: its index row (its repo, its place, its original name) first, then the upload, checked by a HEAD of its size; a content the Space already holds is only marked. The object never expires and nothing deletes it from the Space; the file stays on the disk, purgeable by the usual rules (sk media purge). A link is signed on the CDN edge and downloads under the file's name; it lasts at most 7d, the SigV4 limit of a signed URL, and sk media link makes a new one at any time. Page: wiki tools/shipkit/media-store.md, Put a file from any repo`
166
169
 
167
170
  export class MediaPutCommand extends Command {
168
171
  static override paths = [['media', 'put']]
169
172
  static override usage = Command.Usage({
170
173
  category: 'Media',
171
- description: 'keep files in the private Space by content, a signed link at most 7 days',
172
- details: `${PUT_DETAILS}\n\n--json prints one line a file: { key, sha, size, name, url, expires }, url and expires only with --link.`,
174
+ description: 'keep files in the Space by content: a signed link, 7 days at most; --public, a URL for all',
175
+ details: `${PUT_DETAILS}\n\n--public puts each file under public/<label>/<sha256>.<ext> instead, with a permanent URL anyone downloads and nobody lists; the file is never purged from the disk. Page: wiki tools/shipkit/media-store.md, Publish a file anyone downloads.\n\n--json prints one line a file: { key, sha, size, name, url, expires }: url and expires with --link, url alone with --public. Files go up ${PUT_JOBS} at a time, a line each as it lands.`,
173
176
  examples: [
174
177
  ['a file, its key printed', 'sk media put notes.txt'],
175
178
  ['release zips, a week long link each, as json', 'sk media put dist/a.zip dist/b.zip --kind private-build --link 7d --json'],
179
+ ['voice clips anyone downloads, their URLs as json', 'sk media put --public --kind game-voices voices/fr/*.opus --json'],
176
180
  ],
177
181
  })
178
182
  kind = Option.String('--kind', { description: 'the label, the key prefix: lowercase letters, digits, dashes (files)' })
179
183
  link = Option.String('--link', { description: 'a signed link for this long: 30m, 2h, 7d (at most 7d)' })
184
+ public = Option.Boolean('--public', false, { description: 'under public/<label>/: a permanent URL anyone downloads, nobody lists' })
180
185
  json = Option.Boolean('--json', false, { description: 'one JSON line a file' })
181
186
  files = Option.Rest({ required: 1 })
182
187
  async execute(): Promise<number> {
183
188
  return run(this.context, {}, async (h) => {
184
189
  const { durationS, linkMedia, putMedia } = await import('../media-store/put.ts')
185
190
  const { mb } = await import('../media-store/upload.ts')
191
+ if (this.public && this.link !== undefined) throw new Error('--public and --link: a public file has a permanent URL, no link to sign')
186
192
  const seconds = this.link === undefined ? null : durationS(this.link)
187
- for (const f of this.files) {
188
- const p = await putMedia(f, { ...(this.kind !== undefined ? { kind: this.kind } : {}) })
193
+ const failed: string[] = []
194
+ const one = async (f: string): Promise<string> => {
195
+ const p = await putMedia(f, { ...(this.kind !== undefined ? { kind: this.kind } : {}), public: this.public })
189
196
  const l = seconds === null ? null : await linkMedia(p.key, { seconds, name: p.name })
190
- if (this.json) h.out(JSON.stringify({ key: p.key, sha: p.sha, size: p.size, name: p.name, ...(l ? { url: l.url, expires: l.expires } : {}) }))
191
- else {
192
- h.out(`${p.key} ${p.name} ${mb(p.size)} ${p.sent ? 'up' : 'already in the Space'}`)
193
- if (l) h.out(` ${l.url}\n expires ${l.expires}`)
197
+ const url = l?.url ?? p.url
198
+ if (this.json) return JSON.stringify({ key: p.key, sha: p.sha, size: p.size, name: p.name, ...(url ? { url } : {}), ...(l ? { expires: l.expires } : {}) })
199
+ return `${p.key} ${p.name} ${mb(p.size)} ${p.sent ? 'up' : 'already in the Space'}${url ? `\n ${url}${l ? `\n expires ${l.expires}` : ''}` : ''}`
200
+ }
201
+ // lines print in the order the files were named, each once every file before it landed
202
+ const lines: (string | null | undefined)[] = []
203
+ let next = 0
204
+ let shown = 0
205
+ const flush = (): void => {
206
+ for (; shown < lines.length && lines[shown] !== undefined; shown++) if (lines[shown] !== null) h.out(lines[shown]!)
207
+ }
208
+ const work = async (): Promise<void> => {
209
+ for (let i = next++; i < this.files.length; i = next++) {
210
+ const f = this.files[i]!
211
+ try {
212
+ lines[i] = await one(f)
213
+ } catch (e) {
214
+ lines[i] = null
215
+ failed.push(`${f}: ${(e as Error).message}`)
216
+ }
217
+ flush()
194
218
  }
195
219
  }
220
+ await Promise.all(Array.from({ length: Math.min(PUT_JOBS, this.files.length) }, work))
221
+ if (failed.length > 0) throw new Error(`${failed.length} of ${this.files.length} not put:\n${failed.join('\n')}`)
196
222
  return 0
197
223
  })
198
224
  }
@@ -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
  }
@@ -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'
@@ -145,6 +145,9 @@ export function buildCli(): Cli {
145
145
  cli.register(DrillVerdictCommand)
146
146
  cli.register(DrillCompareCommand)
147
147
  cli.register(DrillCleanCommand)
148
+ cli.register(DrillCloneCommand)
149
+ cli.register(DrillFinishCommand)
150
+ cli.register(DrillCalibrateCommand)
148
151
  cli.register(ConfigKeysCommand)
149
152
 
150
153
  return cli
@@ -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(/\..*/, '')