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.
- package/CHANGELOG.md +19 -0
- package/package.json +1 -1
- package/src/assets/kit-config.ts +19 -1
- package/src/assets/run-assets.ts +18 -0
- package/src/checks/SK038-speaks-as.check.ts +66 -0
- package/src/cli/cmd_Drill.ts +219 -12
- package/src/cli/cmd_Media.ts +34 -8
- package/src/cli/cmd_Review.ts +22 -7
- package/src/cli/cmd_Secret.ts +127 -0
- package/src/cli/cmd_Social.ts +19 -9
- package/src/cli/cmd_Wiki.ts +4 -4
- package/src/cli/family-pages.ts +1 -0
- package/src/cli/registry.ts +8 -1
- package/src/core/scope.ts +42 -0
- package/src/drill/card.ts +65 -0
- package/src/drill/clean.ts +17 -6
- package/src/drill/finish.ts +67 -0
- package/src/drill/render.ts +21 -2
- package/src/drill/run.ts +51 -2
- package/src/drill/score.ts +68 -0
- package/src/drill/seal.ts +259 -0
- package/src/home/home-paths.ts +10 -1
- package/src/init-repo.ts +14 -4
- package/src/media-store/content.ts +1 -1
- package/src/media-store/hand.ts +6 -1
- package/src/media-store/put.ts +11 -7
- package/src/media-store/space.ts +17 -3
- package/src/repo-config.ts +4 -1
- package/src/review/auto.ts +7 -2
- package/src/review/cells.ts +1 -1
- package/src/review/format.ts +2 -2
- package/src/review/model.ts +46 -13
- package/src/review/previews.ts +1 -1
- package/src/review/routes.ts +11 -0
- package/src/review/store.ts +18 -10
- package/src/secrets/list.ts +40 -0
- package/src/serve/hub-app/cols-svc.ts +2 -1
- package/src/serve/hub-app/review/review-kit.ts +4 -0
- package/src/serve/hub-app/review/review-st.ts +40 -3
- package/src/serve/hub-app/review/review-views.tsx +145 -64
- package/src/serve/hub-app/review/thread-st.ts +76 -16
- package/src/serve/hub-app/review.css +17 -2
- package/src/shipkit.ts +1 -1
- package/src/social/house.ts +7 -5
- package/src/wiki/run-wiki.ts +13 -3
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 =
|
|
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
|
+
|
package/src/home/home-paths.ts
CHANGED
|
@@ -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 =>
|
|
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
|
package/src/init-repo.ts
CHANGED
|
@@ -22,12 +22,18 @@ import { gitignorePolicy } from './checks/SK004-gitignore-policy.check.ts'
|
|
|
22
22
|
// repo's comment style, not to this file's. Dash punctuation is banned there
|
|
23
23
|
// and a scaffold is the one comment nobody rewrites, so it teaches the style
|
|
24
24
|
// of whatever wrote it. `DASH_PUNCTUATION` plus a test gate the shape.
|
|
25
|
-
|
|
25
|
+
/** the speaksAs line: the machine's default identity written out when it has identities (SK038 needs one), else a hint */
|
|
26
|
+
const speaksAsLine = (speaksAs: string | null): string =>
|
|
27
|
+
speaksAs == null
|
|
28
|
+
? " // speaksAs: 'me', // the identity that speaks for this repo (sk identities), required once the machine has identities (SK038)"
|
|
29
|
+
: ` speaksAs: '${speaksAs}', // the identity that speaks for this repo (sk identities), required here (SK038)`
|
|
30
|
+
|
|
31
|
+
const CONFIG_TEMPLATE = (name: string, speaksAs: string | null = null): string => `import { defineRepo } from 'rvlib-shipkit'
|
|
26
32
|
|
|
27
33
|
export default defineRepo({
|
|
28
34
|
name: '${name}',
|
|
29
35
|
venues: [], // e.g. ['itch', 'steam'], selects which .shipkit/<venue>/ contracts are REQUIRED
|
|
30
|
-
|
|
36
|
+
${speaksAsLine(speaksAs)}
|
|
31
37
|
tasks: [], // repo commit-gate tasks; deps double as race guards
|
|
32
38
|
// lint, typecheck, imports:check and cycles are cached on the tracked tree.
|
|
33
39
|
// \`test\` runs every time until you say what it reads, because an
|
|
@@ -51,7 +57,7 @@ export const DASH_PUNCTUATION = /[—–]|(?<=\s)-(?=\s)/
|
|
|
51
57
|
|
|
52
58
|
/** the scaffolded config, for a gate that this text stays writable into a repo
|
|
53
59
|
* that bans the dash. Exported because the template itself is private. */
|
|
54
|
-
export const scaffoldedConfig = (name: string): string => CONFIG_TEMPLATE(name)
|
|
60
|
+
export const scaffoldedConfig = (name: string, speaksAs: string | null = null): string => CONFIG_TEMPLATE(name, speaksAs)
|
|
55
61
|
|
|
56
62
|
export type InitOpts = {
|
|
57
63
|
/** in-repo-source consumers: path to shipkit's cli.ts — scripts become `bun <path> <cmd>` instead of `shipkit <cmd>` */
|
|
@@ -111,7 +117,11 @@ export async function initRepo(root: string, opts: InitOpts = {}): Promise<numbe
|
|
|
111
117
|
const pkgRaw = readFileSync(pkgPath, 'utf8')
|
|
112
118
|
const pkg = JSON.parse(pkgRaw) as { name?: string; scripts?: Record<string, string> }
|
|
113
119
|
const name = repoName(root, opts.name, pkg.name)
|
|
114
|
-
|
|
120
|
+
// on a machine with identities the new repo names the default one: a line he changes, never a silent fallback
|
|
121
|
+
const { loadIdentities } = await import('./identities/identities.ts')
|
|
122
|
+
const ids = await loadIdentities({ cwd: root })
|
|
123
|
+
const speaker = ids.identities.find((i) => i.default)?.id ?? ids.identities[0]?.id ?? null
|
|
124
|
+
writeFileSync(configPath, CONFIG_TEMPLATE(name, speaker))
|
|
115
125
|
p('ok: repo.config.ts created')
|
|
116
126
|
const indent = pkgRaw.match(/^(\s+)"/m)?.[1] ?? ' '
|
|
117
127
|
pkg.scripts ??= {}
|
|
@@ -58,4 +58,4 @@ export async function factsOf(folder: string, names: readonly string[], keep: Re
|
|
|
58
58
|
export const mediaKey = (kind: string, f: Pick<MediaFact, 'sha'>, name: string): string => `${kind}/${f.sha}${extname(name).toLowerCase()}`
|
|
59
59
|
|
|
60
60
|
/** the sha a key names, null when it is no content key */
|
|
61
|
-
export const shaOfKey = (key: string): string | null => /^[a-z0-9-]+\/([0-9a-f]{64})(?:\.|$)/.exec(key)?.[1] ?? null
|
|
61
|
+
export const shaOfKey = (key: string): string | null => /^(?:public\/)?[a-z0-9-]+\/([0-9a-f]{64})(?:\.|$)/.exec(key)?.[1] ?? null
|
package/src/media-store/hand.ts
CHANGED
|
@@ -6,11 +6,15 @@ import { join, resolve } from 'node:path'
|
|
|
6
6
|
import { shaOf, shaOfKey, typeOf } from './content.ts'
|
|
7
7
|
import { mediaDb } from './db.ts'
|
|
8
8
|
import type { MediaKind, MediaRow } from './kind.ts'
|
|
9
|
+
import { PUBLIC_PREFIX } from './space.ts'
|
|
9
10
|
|
|
10
11
|
/** a label `sk media put` takes: the key prefix in the Space */
|
|
11
12
|
export const LABEL = /^[a-z0-9-]+$/
|
|
12
13
|
export const DEFAULT_LABEL = 'files'
|
|
13
14
|
|
|
15
|
+
/** the label every `public/<label>/` key reads as (the first segment of its key) */
|
|
16
|
+
export const PUBLIC_LABEL = PUBLIC_PREFIX.slice(0, -1)
|
|
17
|
+
|
|
14
18
|
/** the stores the index holds rows of under this label */
|
|
15
19
|
function storesOf(label: string): string[] {
|
|
16
20
|
const db = mediaDb()
|
|
@@ -48,7 +52,8 @@ export function handKind(label: string): MediaKind {
|
|
|
48
52
|
return { rows, filled: 0, left: 0 }
|
|
49
53
|
},
|
|
50
54
|
async holds(store) {
|
|
51
|
-
|
|
55
|
+
// a public file is the repo's working copy, its URL is for those without one: never purged
|
|
56
|
+
return (row) => ({ pinned: label === PUBLIC_LABEL, used: statSync(join(store, row.item, row.name), { throwIfNoEntry: false })?.mtimeMs })
|
|
52
57
|
},
|
|
53
58
|
async beforePurge(store, _space, row) {
|
|
54
59
|
const sha = await shaOf(join(store, row.item, row.name))
|
package/src/media-store/put.ts
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
// a file put in the store by hand, and a fresh link to anything it holds (wiki tools/shipkit/media-store.md, Put a file
|
|
2
|
-
// from any repo): the one way a repo's agent keeps a file in the private Space
|
|
2
|
+
// from any repo): the one way a repo's agent keeps a file in the private Space, or publishes one under `public/`. The index row is written before the
|
|
3
3
|
// upload, so a failed upload waits for the daemon like any other; a link lasts at most 7 days, the object for good
|
|
4
4
|
import { realpathSync, statSync } from 'node:fs'
|
|
5
5
|
import { basename, dirname, join, relative } from 'node:path'
|
|
6
6
|
import { findRepoRoot } from '../ts/config.ts'
|
|
7
7
|
import { factOf, mediaKey, shaOf, shaOfKey, typeOf } from './content.ts'
|
|
8
8
|
import { mediaDb } from './db.ts'
|
|
9
|
-
import { DEFAULT_LABEL, LABEL } from './hand.ts'
|
|
9
|
+
import { DEFAULT_LABEL, LABEL, PUBLIC_LABEL } from './hand.ts'
|
|
10
10
|
import { confirmedUp } from './remote.ts'
|
|
11
|
-
import { machineSpace, SIGNED_MAX_S } from './space.ts'
|
|
11
|
+
import { machineSpace, PUBLIC_PREFIX, SIGNED_MAX_S } from './space.ts'
|
|
12
12
|
import { uploadOne } from './upload.ts'
|
|
13
13
|
|
|
14
14
|
/** a duration as seconds: `90s`, `30m`, `2h`, `7d`, or a bare number of seconds; never over 7 days */
|
|
@@ -29,6 +29,8 @@ export interface Put {
|
|
|
29
29
|
name: string
|
|
30
30
|
/** false: the Space already held this content */
|
|
31
31
|
sent: boolean
|
|
32
|
+
/** the permanent URL of a public put */
|
|
33
|
+
url?: string
|
|
32
34
|
}
|
|
33
35
|
|
|
34
36
|
export interface Link {
|
|
@@ -56,17 +58,19 @@ function placeOf(file: string): { store: string; item: string; name: string } {
|
|
|
56
58
|
return { store, item: relative(store, dirname(real)), name: basename(real) }
|
|
57
59
|
}
|
|
58
60
|
|
|
59
|
-
/** the file kept by its content under the label: its index row first, then up at once, checked by a HEAD
|
|
60
|
-
|
|
61
|
+
/** the file kept by its content under the label: its index row first, then up at once, checked by a HEAD. `public`: under
|
|
62
|
+
* `public/<label>/`, read by anyone through its URL, never purged from the disk */
|
|
63
|
+
export async function putMedia(file: string, o: { kind?: string; public?: boolean } = {}): Promise<Put> {
|
|
61
64
|
const label = o.kind ?? DEFAULT_LABEL
|
|
62
65
|
if (!LABEL.test(label)) throw new Error(`--kind ${label}: a label is lowercase letters, digits and dashes`)
|
|
66
|
+
if (label === PUBLIC_LABEL) throw new Error(`--kind ${label}: the public folder is --public, under a label of its own`)
|
|
63
67
|
if ((await codeLabels()).has(label)) throw new Error(`--kind ${label}: that kind's files come from its own scan, never a hand put; pick another label`)
|
|
64
68
|
const st = statSync(file, { throwIfNoEntry: false })
|
|
65
69
|
if (!st?.isFile()) throw new Error(`${file}: no such file`)
|
|
66
70
|
const at = placeOf(file)
|
|
67
71
|
const path = join(at.store, at.item, at.name)
|
|
68
72
|
const fact = await factOf(path)
|
|
69
|
-
const key = mediaKey(label, fact, at.name)
|
|
73
|
+
const key = mediaKey(o.public ? `${PUBLIC_PREFIX}${label}` : label, fact, at.name)
|
|
70
74
|
const db = mediaDb()
|
|
71
75
|
if (!db) throw new Error('the media index does not open: nothing is put without its record')
|
|
72
76
|
db.transaction(() => {
|
|
@@ -76,7 +80,7 @@ export async function putMedia(file: string, o: { kind?: string } = {}): Promise
|
|
|
76
80
|
const { space, why } = await machineSpace()
|
|
77
81
|
if (!space) throw new Error(`${key} recorded, not up: ${why}; the daemon sends it once the Space answers`)
|
|
78
82
|
const sent = await uploadOne(space, { key, size: fact.size, path })
|
|
79
|
-
return { key, sha: fact.sha, size: fact.size, name: at.name, sent }
|
|
83
|
+
return { key, sha: fact.sha, size: fact.size, name: at.name, sent, ...(o.public ? { url: space.publicUrl(key) } : {}) }
|
|
80
84
|
}
|
|
81
85
|
|
|
82
86
|
/** the key a reference names: a key, a sha (or 12 hex of one), or a file the store holds */
|
package/src/media-store/space.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// the private S3 bucket that keeps every media file of the machine's store (wiki tools/shipkit/media-store.md), named by
|
|
2
|
-
// the house config's `serve.mediaSpace`. Every object is PRIVATE
|
|
3
|
-
//
|
|
2
|
+
// the house config's `serve.mediaSpace`. Every object is PRIVATE but those under `public/`, and the key alone decides
|
|
3
|
+
// (`aclOf`); never a bucket policy, never a public listing. A page reads a private one through a URL signed for one hour,
|
|
4
|
+
// on the CDN edge. The key pair (`KEY:SECRET`) is read through the house's
|
|
4
5
|
// `credsReadCommand`, held in memory only: never written to a file, never printed
|
|
5
6
|
import { S3Client } from 'bun'
|
|
6
7
|
import { mkdirSync, renameSync, rmSync } from 'node:fs'
|
|
@@ -33,6 +34,12 @@ export interface SpaceConfig {
|
|
|
33
34
|
/** how long a signed URL stays good */
|
|
34
35
|
export const SIGNED_S = 3600
|
|
35
36
|
|
|
37
|
+
/** the folder whose objects anyone downloads by URL: nobody lists it (wiki tools/shipkit/media-store.md, Publish a file) */
|
|
38
|
+
export const PUBLIC_PREFIX = 'public/'
|
|
39
|
+
|
|
40
|
+
/** the ACL a key goes up with: public-read under `public/`, private everywhere else */
|
|
41
|
+
export const aclOf = (key: string): 'public-read' | 'private' => (key.startsWith(PUBLIC_PREFIX) ? 'public-read' : 'private')
|
|
42
|
+
|
|
36
43
|
export interface Space {
|
|
37
44
|
/** where the objects live, for a line a person reads (never a credential) */
|
|
38
45
|
readonly where: string
|
|
@@ -43,6 +50,8 @@ export interface Space {
|
|
|
43
50
|
* checks it against (a URL signed for the edge's own host answers SignatureDoesNotMatch). `as` signs a download
|
|
44
51
|
* under that file name: `response-content-disposition` and `response-content-type` ride in the signed query */
|
|
45
52
|
signed(key: string, seconds?: number, as?: { name: string; type: string }): string
|
|
53
|
+
/** the permanent URL of a `public/` object, on the CDN edge when the Space has one; throws for any other key */
|
|
54
|
+
publicUrl(key: string): string
|
|
46
55
|
/** the object written at `to`, through a file beside it renamed: no reader sees half of it */
|
|
47
56
|
get(key: string, to: string): Promise<void>
|
|
48
57
|
/** every object under the prefix, with its size, page after page (ListObjectsV2) */
|
|
@@ -100,7 +109,7 @@ export function spaceOf(c: SpaceConfig): Space {
|
|
|
100
109
|
return {
|
|
101
110
|
where: `${c.cdn ?? c.endpoint} (${c.bucket})`,
|
|
102
111
|
async put(key, file, type) {
|
|
103
|
-
await client.write(key, Bun.file(file), { type, acl:
|
|
112
|
+
await client.write(key, Bun.file(file), { type, acl: aclOf(key) })
|
|
104
113
|
},
|
|
105
114
|
async head(key) {
|
|
106
115
|
try {
|
|
@@ -116,6 +125,11 @@ export function spaceOf(c: SpaceConfig): Space {
|
|
|
116
125
|
if (edge && url.host === origin) url.host = edge
|
|
117
126
|
return url.toString()
|
|
118
127
|
},
|
|
128
|
+
publicUrl(key) {
|
|
129
|
+
if (aclOf(key) !== 'public-read') throw new Error(`${key}: private, it has no public URL (sk media link signs one)`)
|
|
130
|
+
const base = c.cdn ?? (c.path === true ? `${c.endpoint}/${c.bucket}` : c.endpoint)
|
|
131
|
+
return `${base.replace(/\/$/, '')}/${key}`
|
|
132
|
+
},
|
|
119
133
|
async get(key, to) {
|
|
120
134
|
mkdirSync(dirname(to), { recursive: true })
|
|
121
135
|
const tmp = `${to}.${process.pid}.get`
|