rvlib-shipkit 2.33.0 → 2.34.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,25 @@
1
+ ## 2.34.0
2
+
3
+ ### Added
4
+
5
+ - **A backup target can be any S3 bucket**: `sk backup targets add <id> --endpoint <origin> --bucket <name> --key-id <secret> --key-secret <secret>` (MinIO, R2, any server; the row names the two secrets of its key, never a value), `check` writes one object and reads it back, `get` writes the newest copy of a store back to a folder, checked against its sha.
6
+ - **An advisor's ok that waits for the owner lights their answer bar**: a click on it adds a note to it, never a second ok.
7
+
8
+ ### Changed
9
+
10
+ - **`sk start` writes this machine's own house** as line 1 of a new repo's CLAUDE.md (the house its pm runs from, else the one `sk setup` made beside the repos), and puts the repo beside it. The package names no house of its own. A house `sk setup` made writes no `.claude/` policy files.
11
+ - **A machine with no backup set up yet says so in one orange line**: no red band, no notification, no vault row where no vault runs.
12
+ - **Seeded backup targets are named by their provider** (`do-space`, `cf-r2`), else `space` and `space-copy`.
13
+ - **The daemon's steady memory budget is 750 MB** (was 500 MB); its boot budget stays 1 GB.
14
+
15
+ ### Fixed
16
+
17
+ - **`SHIPKIT_TEST_SELECT=1 sk ci` selects suites** when the daemon runs the gate: the switch now reaches the job.
18
+ - **The thread store compiles under an ES2022 lib**: four native `findLast` calls use the package's own helper, so a repo whose tsconfig stops at ES2022 types against shipkit again.
19
+ - **No owner facts in the help texts**: an ask number, secret names and a machine's name left three help lines.
20
+
21
+ Nothing of a newcomer's first run was proven from zero in a container: no container runtime ran.
22
+
1
23
  ## 2.33.0
2
24
 
3
25
  ### Added
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rvlib-shipkit",
3
- "version": "2.33.0",
3
+ "version": "2.34.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",
@@ -232,6 +232,7 @@ const REPLY: Rules<ReplyCell> = {
232
232
  instructions: 'drop',
233
233
  step: 'drop',
234
234
  linked: 'drop',
235
+ advice: table({ status: 'token', on: 'id' }),
235
236
  }
236
237
  const NOTE: Rules<NoteCell> = { ...BASE, item: table(ITEM), text: 'text', rects: always([]), image: 'file', files: REPLY.files, rate: 'drop', read: 'bool' }
237
238
  const EVENT: Rules<EventCell> = { ...BASE, op: 'token', note: 'drop', topic: 'drop', commit: 'drop', trace: table(TRACE) }
@@ -125,7 +125,10 @@ function pendingCells(s: OwnerState, x: Share, thread: Thread, view: AdvisorThre
125
125
  .map((a) => {
126
126
  const what = a.kind === 'pick' ? `I pick option ${(a.option ?? 0) + 1}` : (ADVICE_WORDS[a.kind] ?? '')
127
127
  const text = [what, namedFiles(a.text ?? '', a.files ?? [])].filter((w) => w !== '').join(': ')
128
- return { kind: 'reply' as const, id: adviceCell(view.head, a.id), on: view.head, at: a.at, who: ADVISOR_WHO, party: 'owner' as const, summary: text, open: true, text: a.state === 'pending' ? `${text}\n\nwaits for ${owner}` : text, read: true } satisfies ReplyCell
128
+ // their ok or fix that waits: their bar on that version draws it lit, so a second click adds a note, never a second ok
129
+ const tone: NonNullable<ReplyCell['advice']>['status'] | null = a.kind === 'approve' ? 'approved' : a.kind === 'change' ? 'approved-with-fix' : null
130
+ const advice = a.state === 'pending' && tone !== null && a.item !== undefined ? { advice: { status: tone, on: opaqueItem(x.id, a.item) } } : {}
131
+ return { kind: 'reply' as const, id: adviceCell(view.head, a.id), on: view.head, at: a.at, who: ADVISOR_WHO, party: 'owner' as const, summary: text, open: true, text: a.state === 'pending' ? `${text}\n\nwaits for ${owner}` : text, read: true, ...advice } satisfies ReplyCell
129
132
  })
130
133
  }
131
134
 
@@ -51,7 +51,7 @@ export class BackupStatusCommand extends Command {
51
51
  }
52
52
  }
53
53
 
54
- const TARGETS_DETAILS = `the places the house's backups go, one row each in the hq: an s3 bucket the house config owns (serve.mediaSpace, the Space; serve.spaceCopy, its second place) or a machine of the tailnet over ssh (its host and a folder under its home). No row holds a secret: a bucket's key stays in the vault under the names the config gives. The first list fills an empty table with the Space, the second place and the thread copy's peer. Every store goes to every target that is on (sk backup status says how each one stands); rm removes the row only, never what the target holds. Page: wiki tools/shipkit/media-store-backup.md, Targets`
54
+ const TARGETS_DETAILS = `the places the house's backups go, one row each in the hq: a bucket of any S3 server (its origin, its bucket, the names of the two secrets of its key), an s3 bucket the house config owns (serve.mediaSpace, the Space; serve.spaceCopy, its second place) or a machine over ssh (its host and a folder under its home). No row holds a secret: a key is two secrets, stored first (sk secret set), named by the row. The first list fills an empty table with the buckets the config names. check writes one small object and reads it back; get writes the newest copy of a store back into a folder, its bytes compared with the sha they went up with. Every store goes to every target that is on (sk backup status says how each one stands); rm removes the row only, never what the target holds. Page: wiki tools/shipkit/media-store-backup.md, Targets`
55
55
 
56
56
  type Answer = { targets?: import('../hq/backup-targets.ts').BackupTarget[]; refused?: string; removed?: boolean } & Partial<import('../hq/backup-targets.ts').BackupTarget>
57
57
 
@@ -60,16 +60,25 @@ async function admin(path: string, body: unknown = {}): Promise<Answer> {
60
60
  return askHqAdmin<Answer>(path, body)
61
61
  }
62
62
 
63
- const where = (t: import('../hq/backup-targets.ts').BackupTarget): string => (t.address.kind === 'ssh' ? `ssh ${t.address.host}:${t.address.folder}` : `s3, the bucket of serve.${t.address.config}`)
63
+ const where = (t: import('../hq/backup-targets.ts').BackupTarget): string => (t.address.kind === 'ssh' ? `ssh ${t.address.host}:${t.address.folder}` : 'config' in t.address ? `s3, the bucket of serve.${t.address.config}` : `s3, ${t.address.bucket} at ${t.address.endpoint}`)
64
64
 
65
65
  export class BackupTargetsCommand extends Command {
66
66
  static override paths = [['backup', 'targets']]
67
- static override usage = Command.Usage({ category: 'Media', description: 'the places the backups go, stored in the hq: buckets and machines over ssh', details: TARGETS_DETAILS, examples: [['the list', 'sk backup targets'], ['a machine', 'sk backup targets add nas --ssh nas --folder ~/backups --label "the NAS"'], ['switch one off', 'sk backup targets off nas']] })
68
- verb = Option.String({ required: false, name: 'ls | add | on | off | rm' })
67
+ static override usage = Command.Usage({ category: 'Media', description: 'the places the backups go, stored in the hq: buckets and machines over ssh', details: TARGETS_DETAILS, examples: [['the list', 'sk backup targets'], ['a bucket', 'sk backup targets add mine --endpoint https://s3.example.com --bucket my-backups --region us-east-1 --key-id backup/id --key-secret backup/secret'], ['does it take and give back an object', 'sk backup targets check mine'], ['the newest copy of the hq, back on the disk', 'sk backup targets get mine --to ~/restored'], ['a machine', 'sk backup targets add nas --ssh nas --folder ~/backups --label "the NAS"'], ['switch one off', 'sk backup targets off nas']] })
68
+ verb = Option.String({ required: false, name: 'ls | add | check | get | on | off | rm' })
69
69
  id = Option.String({ required: false, name: 'id' })
70
- ssh = Option.String('--ssh', { description: 'add: the ssh host of the tailnet' })
70
+ ssh = Option.String('--ssh', { description: 'add: the ssh host' })
71
71
  folder = Option.String('--folder', { description: 'add: the folder under its home, ~/a/b' })
72
72
  s3 = Option.String('--s3', { description: 'add: mediaSpace or spaceCopy, the config key that owns the bucket' })
73
+ endpoint = Option.String('--endpoint', { description: 'add: the origin of an S3 server, https://s3.example.com' })
74
+ bucket = Option.String('--bucket', { description: 'add: its bucket' })
75
+ region = Option.String('--region', { description: 'add: its region (auto when absent)' })
76
+ hostStyle = Option.Boolean('--bucket-in-host', false, { description: 'add: the bucket is in the endpoint\'s host already; absent, it goes in the path, which MinIO and R2 want' })
77
+ keyId = Option.String('--key-id', { description: 'add: the secret that holds the access key id' })
78
+ keySecret = Option.String('--key-secret', { description: 'add: the secret that holds the secret access key' })
79
+ store = Option.String('--store', 'hq', { description: 'get: hq or vault' })
80
+ to = Option.String('--to', { description: 'get: the folder the copy lands in' })
81
+ machine = Option.String('--machine', { description: "get: another machine's copies, by its name; this one's when absent" })
73
82
  label = Option.String('--label', { description: 'add: the name the status shows' })
74
83
  async execute(): Promise<number> {
75
84
  const err = (l: string): number => (this.context.stderr.write(`FAIL: backup targets: ${l}\n`), 1)
@@ -93,14 +102,46 @@ export class BackupTargetsCommand extends Command {
93
102
  this.context.stdout.write(r.removed ? `ok: ${this.id} is no longer a target; what it holds stays there\n` : `ok: no target ${this.id}\n`)
94
103
  return 0
95
104
  }
105
+ if (verb === 'check' || verb === 'get') {
106
+ const list = await admin('/api/home/hq/targets')
107
+ if (list.refused != null) return err(list.refused)
108
+ const { ownBucket } = await import('../hq/backup-targets.ts')
109
+ const t = (list.targets ?? []).find((x) => x.id === this.id)
110
+ const own = t == null ? null : ownBucket(t.address)
111
+ if (t == null) return err(`no target ${this.id} (sk backup targets)`)
112
+ if (own == null) return err(`${this.id} is no bucket added by hand: sk backup status says how it stands`)
113
+ const [{ bucketProblem, getNewest }, { houseBucket }] = await Promise.all([import('../media-store/backup/bucket-target.ts'), import('../home/house-bucket.ts')])
114
+ const c = await houseBucket(own)
115
+ if ('why' in c) return err(c.why)
116
+ const { machineName } = await import('../home/machine-host.ts')
117
+ const machine = this.machine ?? machineName()
118
+ if (verb === 'check') {
119
+ const why = await bucketProblem(c, machine)
120
+ if (why != null) return err(`${t.label}: ${why}`)
121
+ this.context.stdout.write(`ok: ${t.label} took one object and gave the same bytes back\n`)
122
+ return 0
123
+ }
124
+ if (this.to == null) return err(`get takes --to <folder>`)
125
+ if (this.store !== 'hq' && this.store !== 'vault') return err('--store: hq or vault')
126
+ const { resolve } = await import('node:path')
127
+ try {
128
+ const r = await getNewest(c, { store: this.store, machine, to: resolve(this.to) })
129
+ this.context.stdout.write(`ok: ${r.file}, ${r.bytes} bytes, from ${r.key}, its sha the one it went up with\n`)
130
+ return 0
131
+ } catch (e) {
132
+ return err((e as Error).message)
133
+ }
134
+ }
96
135
  if (verb === 'add') {
97
- const address = this.ssh != null ? { kind: 'ssh', host: this.ssh, folder: this.folder ?? '~/.shipkit' } : this.s3 != null ? { kind: 's3', config: this.s3 } : null
98
- if (address == null) return err('add takes --ssh <host> [--folder ~/dir] or --s3 mediaSpace|spaceCopy')
136
+ if (this.endpoint != null && (this.bucket == null || this.keyId == null || this.keySecret == null)) return err('add --endpoint takes --bucket, --key-id and --key-secret: the last two name the secrets of its key (sk secret set <name> stores one)')
137
+ const bucket = this.endpoint == null ? null : { kind: 's3', endpoint: this.endpoint.replace(/\/$/, ''), bucket: this.bucket, region: this.region ?? 'auto', ...(this.hostStyle ? {} : { path: true }), key: { accessKeyId: this.keyId, secretAccessKey: this.keySecret } }
138
+ const address = bucket != null ? bucket : this.ssh != null ? { kind: 'ssh', host: this.ssh, folder: this.folder ?? '~/.shipkit' } : this.s3 != null ? { kind: 's3', config: this.s3 } : null
139
+ if (address == null) return err('add takes --endpoint <origin> --bucket <name> --key-id <secret> --key-secret <secret>, --ssh <host> [--folder ~/dir], or --s3 mediaSpace|spaceCopy')
99
140
  const r = await admin('/api/home/hq/targets/put', { id: this.id, label: this.label ?? this.id, address })
100
141
  if (r.refused != null) return err(r.refused)
101
142
  this.context.stdout.write(`ok: ${this.id} added (${r.address == null ? '' : where(r as import('../hq/backup-targets.ts').BackupTarget)}); the next look of the daemon sends to it\n`)
102
143
  return 0
103
144
  }
104
- return err(`${verb}: ls, add, on, off or rm`)
145
+ return err(`${verb}: ls, add, check, get, on, off or rm`)
105
146
  }
106
147
  }
@@ -260,7 +260,7 @@ export class MediaVersioningCommand extends Command {
260
260
  details: `PutBucketVersioning, then GetBucketVersioning to confirm: an object deleted or overwritten from the DigitalOcean dashboard or by a stray key keeps its older version. DigitalOcean offers it through the S3 API only. Once on, it can only be suspended, never turned off. The house key is limited to the bucket's objects and cannot change it: --key names a full access key pair kept once in the keychain for this call. Page: wiki tools/shipkit/media-store.md, Versioning`,
261
261
  examples: [
262
262
  ['turn it on', 'sk media versioning'],
263
- ['turn it on with a one time full access key', 'sk media versioning --key-id rv/shipkit/spaces-admin-access-key-id --key-secret rv/shipkit/spaces-admin-secret-access-key'],
263
+ ['turn it on with a one time full access key', 'sk media versioning --key-id demo/spaces-admin-id --key-secret demo/spaces-admin-secret'],
264
264
  ['read it', 'sk media versioning --check'],
265
265
  ],
266
266
  })
@@ -48,7 +48,7 @@ export class ShotCommand extends Command {
48
48
  category: 'Serve',
49
49
  description: 'a webp of any url through the warm browser (a png with --out x.png), or an mp4 clip with --video',
50
50
  details:
51
- 'one warm headless chromium for the whole machine (the `shot` global process, started when down). A still reuses the warm page when it already shows the url, so a warm shot answers in about 0.1 s. A page with `<meta name="shot-ready" content="wait">` is shot once it sets content="ready"; any other page --wait ms after its load; a page that navigates while it loads (a sign in that redirects) gets its wait again where it lands. --full shoots the whole page at the width of the viewport: one file while the page fits the tallest side of its format (webp 16383 px, jpg and png 65535), else tiles in that format, <name>-1, <name>-2… top to bottom, every one printed, so nothing of the page is lost and the format stays the one asked (a jpg instead of a webp would change what the caller asked for, a cut would drop the end of the page); a whole page stops at 131072 px, the cut said in the note. A file of this machine is a url too (its path, or file://). --video films a page that is a canvas through its WebCodecs encoder (H.264 muxed with no second encode), and any other page as chromium paints it (its screencast, encoded by ffmpeg as the frames arrive); --dom films the page even when a canvas fills it. --step <hook> films frame by frame: before each frame the page draws its time t (seconds) in `await window[hook](t)`, then its ready mark, so a slow page films smooth at its fps; a canvas page is encoded by its own WebCodecs at the exact time n / fps, any other page a screenshot a frame. A still with --step is the page drawn at --at s. A session: cookies follow every shot (one jar in memory for the whole machine), the local storage of a page does not: a shot at another viewport, a clip and the idle close (60 s) each start with an empty one, as two browser contexts do. So when an app keeps its session in local storage, open its sign in at the viewport you shoot at; a request the page sees answered 401 or 403 prints its own WARN line. A theme: --theme <hub theme> draws the page with that prefers-color-scheme and the hub reads its `hub:theme` as that theme, written nowhere, so the next shot keeps none; with no flag every shot of the machine takes serve.shotTheme of the house config. Another place: --on <place> runs the same shot on a machine that reports to the hq (sk machines), over ssh, by its own `sk shot` from its house checkout, so its warm browser draws the page and its localhost is its own; each file comes back to --out and leaves its /tmp. A place that does not answer ssh, has no shot service or runs a shipkit whose sk shot refuses the ask fails in one line with the fix. wm, the GPU box, runs no shipkit place (no daemon, no pm, no shot service): --on wm is refused; a repo whose repo.config.ts names it in browsers.box already films on it with a plain sk shot.',
51
+ 'one warm headless chromium for the whole machine (the `shot` global process, started when down). A still reuses the warm page when it already shows the url, so a warm shot answers in about 0.1 s. A page with `<meta name="shot-ready" content="wait">` is shot once it sets content="ready"; any other page --wait ms after its load; a page that navigates while it loads (a sign in that redirects) gets its wait again where it lands. --full shoots the whole page at the width of the viewport: one file while the page fits the tallest side of its format (webp 16383 px, jpg and png 65535), else tiles in that format, <name>-1, <name>-2… top to bottom, every one printed, so nothing of the page is lost and the format stays the one asked (a jpg instead of a webp would change what the caller asked for, a cut would drop the end of the page); a whole page stops at 131072 px, the cut said in the note. A file of this machine is a url too (its path, or file://). --video films a page that is a canvas through its WebCodecs encoder (H.264 muxed with no second encode), and any other page as chromium paints it (its screencast, encoded by ffmpeg as the frames arrive); --dom films the page even when a canvas fills it. --step <hook> films frame by frame: before each frame the page draws its time t (seconds) in `await window[hook](t)`, then its ready mark, so a slow page films smooth at its fps; a canvas page is encoded by its own WebCodecs at the exact time n / fps, any other page a screenshot a frame. A still with --step is the page drawn at --at s. A session: cookies follow every shot (one jar in memory for the whole machine), the local storage of a page does not: a shot at another viewport, a clip and the idle close (60 s) each start with an empty one, as two browser contexts do. So when an app keeps its session in local storage, open its sign in at the viewport you shoot at; a request the page sees answered 401 or 403 prints its own WARN line. A theme: --theme <hub theme> draws the page with that prefers-color-scheme and the hub reads its `hub:theme` as that theme, written nowhere, so the next shot keeps none; with no flag every shot of the machine takes serve.shotTheme of the house config. Another place: --on <place> runs the same shot on a machine that reports to the hq (sk machines), over ssh, by its own `sk shot` from its house checkout, so its warm browser draws the page and its localhost is its own; each file comes back to --out and leaves its /tmp. A place that does not answer ssh, has no shot service or runs a shipkit whose sk shot refuses the ask fails in one line with the fix. A box with no shipkit place (no daemon, no pm, no shot service, a GPU box for one) is refused; a repo whose repo.config.ts names such a box in browsers.box already films on it with a plain sk shot.',
52
52
  examples: [
53
53
  ['a still of a running dev server', 'sk shot localhost:5173/'],
54
54
  ['a whole tall page at a phone width', 'sk shot :5173/guest --viewport 390,844 --full --out shots/guest.png'],
@@ -75,7 +75,7 @@ export class ShotCommand extends Command {
75
75
  step = Option.String('--step', { description: 'a window function the page draws time t (s) in: a clip steps it frame by frame, a still draws --at' })
76
76
  at = Option.String('--at', { description: 'with --step, the time a still is drawn at (default 0)' })
77
77
  theme = Option.String('--theme', { description: 'dark, dim, grey or light: the page drawn in that hub theme, this shot only (default the house config serve.shotTheme)' })
78
- on = Option.String('--on', { description: 'another place of the house (sk machines): the shot runs in its own warm browser, its localhost is its own, the file comes back to --out; wm, a box with no shipkit place, is refused' })
78
+ on = Option.String('--on', { description: 'another place of the house (sk machines): the shot runs in its own warm browser, its localhost is its own, the file comes back to --out; a box with no shipkit place is refused' })
79
79
  json = Option.Boolean('--json', false, { description: 'one json line: out, ms, phases, errors, note, via, and tiles when a whole page is tiled' })
80
80
 
81
81
  async execute(): Promise<number> {
@@ -10,7 +10,7 @@ export class StartCommand extends Command {
10
10
  static override usage = Command.Usage({
11
11
  category: 'Setup',
12
12
  description: 'create or enter ~/dev/<name>, ready to work in: a private github repo and a push unless --no-github',
13
- details: 'create (or enter) ~/dev/<name> from ANY cwd, READY to work in. On any dir with no commit history it writes the day-one shape (package.json + src/index.ts + the project CLI on the kit (src/cli.ts, src/cli/cmd_Dev.ts, the cli script and a bin of the repo name) + lint/typecheck, tsconfig, .vscode tasks + settings, the verify skill, an agent/ wiki, .shipkit/reflections), installs the toolchain, wires shipkit (repo.config.ts via init), and runs the whole bootstrap chain: git init, first commit, PRIVATE github repo, push. Loose files ride in that first commit, and only a repo with real history is left as it is. Writes are create-only for files, additive for package.json scripts and .gitignore. CLAUDE.md is the house template on its own (its identity line comes at the first gate, SK003) (HOUSE_INCLUDE in src/start-repo.ts: the base wiki include, then `@./agent/index.md`, and --include overrides it), applied only on a machine where the house index exists, and the agent route lands last whenever the repo has agent/index.md. The house lines also opt the repo into the .claude/ policy files (a pre-approved shell allowlist + the attribution silencer), so a start with no house widens no agent permissions. Prints the dir on stdout so a shell alias can cd there. cwd-only sibling: `shipkit init`',
13
+ details: 'create (or enter) ~/dev/<name> from ANY cwd, READY to work in. On any dir with no commit history it writes the day-one shape (package.json + src/index.ts + the project CLI on the kit (src/cli.ts, src/cli/cmd_Dev.ts, the cli script and a bin of the repo name) + lint/typecheck, tsconfig, .vscode tasks + settings, the verify skill, an agent/ wiki, .shipkit/reflections), installs the toolchain, wires shipkit (repo.config.ts via init), and runs the whole bootstrap chain: git init, first commit, PRIVATE github repo, push. Loose files ride in that first commit, and only a repo with real history is left as it is. Writes are create-only for files, additive for package.json scripts and .gitignore. CLAUDE.md is the house template on its own (its identity line comes at the first gate, SK003) (the house of this machine first, then `@./agent/index.md`, and --include overrides it), applied only on a machine that has a house (`sk setup` makes one), and the agent route lands last whenever the repo has agent/index.md. The house lines also opt the repo into the .claude/ policy files (a pre-approved shell allowlist + the attribution silencer), so a start with no house widens no agent permissions. Prints the dir on stdout so a shell alias can cd there. cwd-only sibling: `shipkit init`',
14
14
  examples: [
15
15
  ['create or enter ~/dev/pong: dir, package.json, shipkit wiring, git, first commit, private github repo, push, the CLAUDE.md include lines', 'sk start pong'],
16
16
  ['another house: replace the include lines', "sk start pong --include '@~/wiki/index.md' --include '@./agent/index.md'"],
@@ -22,8 +22,8 @@ export class StartCommand extends Command {
22
22
  })
23
23
 
24
24
  name = Option.String()
25
- root = Option.String('--root', { description: 'parent dir for repos (default ~/dev)' })
26
- include = Option.Array('--include', { description: 'line CLAUDE.md must carry, repeatable, order kept. Omitted: the house template (HOUSE_INCLUDE in src/start-repo.ts), the base wiki include then `@./agent/index.md`, and on a machine without that wiki the agent route alone' })
25
+ root = Option.String('--root', { description: 'parent dir for repos (default the folder the house sits in, ~/dev with no house)' })
26
+ include = Option.Array('--include', { description: 'line CLAUDE.md must carry, repeatable, order kept. Omitted: the house of this machine, then `@./agent/index.md`; on a machine with no house the agent route alone' })
27
27
  alsoOk = Option.Array('--also-ok', { description: 'alternative lines satisfying the first --include — never double-add. Omitted: `@./CLAUDE.local.md`, the public-repo indirection' })
28
28
  skip = Option.Array('--skip', { description: 'repo names shipkit never touches: no CLAUDE.md include, no wiring. Omitted: start.skip in the house config' })
29
29
  github = Option.Boolean('--github', { description: 'ON by default when a repo is being STARTED (a dir this run created, or one with a package.json): it gets a PRIVATE github repo wired as origin, and the first commit is pushed to it. Pass --github to force it for a pre-existing folder, --no-github to keep everything local, the first commit included (SHIPKIT_NO_GITHUB=1 does it for every run)' })
@@ -15,7 +15,7 @@ export const MEMORY_EVERY_MS = 10 * 60_000
15
15
  export const MEMORY_STEP = 0.1
16
16
 
17
17
  /** what the daemon may hold, as its footprint: steady, and in its first BOOT_MS while every hub warms */
18
- export const MEMORY_BUDGET = { steady: 500 * 2 ** 20, boot: 1024 * 2 ** 20 }
18
+ export const MEMORY_BUDGET = { steady: 750 * 2 ** 20, boot: 1024 * 2 ** 20 }
19
19
  export const BOOT_MS = 5 * 60_000
20
20
  export const BUDGET_EVERY_MS = 30_000
21
21
  /** the machine db row of the daemon's last pass over its budget */
@@ -248,12 +248,14 @@ function derivedRuns(o: { gate: boolean; build: boolean; inputs?: string[]; ttl?
248
248
  }
249
249
 
250
250
  /** the cache half of a check file, as the key layer reads it */
251
- function declOfCache(cache: CacheDecl, env: CheckEnv): { inputs?: string[]; optional?: string[]; ttl?: string; never?: string; key?: string; reads?: boolean } {
251
+ function declOfCache(cache: CacheDecl, env: CheckEnv, off: string | null): { inputs?: string[]; optional?: string[]; ttl?: string; never?: string; key?: string; reads?: boolean } {
252
+ // a check that is off answers its reason, whatever its key would read: none is computed
253
+ const key = off == null && 'key' in cache ? cache.key?.(env) : undefined
252
254
  switch (cache.by) {
253
- case 'files': return { inputs: cache.inputs, optional: cache.optional, key: cache.key?.(env) }
255
+ case 'files': return { inputs: cache.inputs, optional: cache.optional, key }
254
256
  case 'reads': return { reads: true }
255
- case 'ttl': return { ttl: cache.span, key: cache.key?.(env) }
256
- case 'fact': return { ttl: FOREVER, key: cache.key(env) }
257
+ case 'ttl': return { ttl: cache.span, key }
258
+ case 'fact': return { ttl: FOREVER, key }
257
259
  case 'never': return { never: cache.why }
258
260
  }
259
261
  }
@@ -404,7 +406,7 @@ export async function composeChecks(root: string, c: RepoConfig, o: ComposeOpts
404
406
  for (const u of checks) {
405
407
  if (++n % COMPOSE_STEP === 0) await yieldLoop()
406
408
  const runs = fileRuns(u.def, u.id, c, env, foreign)
407
- const cache = declOfCache(u.def.cache, env)
409
+ const cache = declOfCache(u.def.cache, env, runs.off)
408
410
  // a body keyed on what it reads through its context (git-key.ts
409
411
  // READS). The tier is part of that question: a body can read the env,
410
412
  // and a quick answer must never stand in for a full one. Any module
@@ -10,7 +10,7 @@
10
10
  // machine is red whatever else is green, and the headline is the cells': a cell not proven is never green
11
11
  import { machineGet, machineSet } from '../core/machine-db.ts'
12
12
  import { ageWords } from '../core/words.ts'
13
- import type { BackupTarget } from '../hq/backup-targets.ts'
13
+ import { configBucket, ownBucket, type BackupTarget } from '../hq/backup-targets.ts'
14
14
  import { type Drill, healthWords, REPLICA_BEHIND_MS, replicaLag, type ReplicaHealth, type ReplicaPlace } from '../hq/replica.ts'
15
15
  import type { TargetSent } from '../media-store/backup/target-send.ts'
16
16
  import { timeMachineFacts, type TimeMachineFacts } from '../media-store/backup/facts.ts'
@@ -30,7 +30,7 @@ export type Place = { id: string; label: string; where: string; kind: 'mac' | 'd
30
30
  export type StoreRow = { row: string; id: StoreId; machine: string; name: string; what: string; state: CellState; line: string; stale?: true }
31
31
  /** `machine`: where the judgement was made (the hq's machine), `at` its time. `client`: set where a client drew it,
32
32
  * read from the hq; `stale` says the hq did not answer and how old the table is: never green, never red then */
33
- export type BackupStatus = { at: number; machine: string; places: Place[]; stores: StoreRow[]; cells: Cell[]; alarms: string[]; worst: CellState; client?: { machine: string; readAt: number }; stale?: string }
33
+ export type BackupStatus = { notSetUp?: true; at: number; machine: string; places: Place[]; stores: StoreRow[]; cells: Cell[]; alarms: string[]; worst: CellState; client?: { machine: string; readAt: number }; stale?: string }
34
34
 
35
35
  /** the red cells that ring the band and the alarm: a store with no working copy rings too; another red cell (a copy
36
36
  * behind while another works) is red in the matrix only */
@@ -59,6 +59,11 @@ export type BackupInputs = {
59
59
  vaultNear: { count: number; newest: number | null }
60
60
  timeMachine: TimeMachineFacts
61
61
  secondPlaceKey: boolean | null
62
+ /** a vault runs on this machine, or ran: false is a keychain only machine, which has no vault to copy. Unsaid: true */
63
+ vault?: boolean
64
+ /** a target, a copy or a drill was ever kept here, or the config names a place: false is a machine where no backup
65
+ * was set up yet, which is said once and rings no band. Unsaid: true */
66
+ setUp?: boolean
62
67
  }
63
68
 
64
69
  const ago = (at: number, now: number): string => `${ageWords(at, now)}`
@@ -113,9 +118,9 @@ function cellOf(store: StoreId, p: Place, d: BackupInputs, machine: string): Dra
113
118
  const c = (state: CellState, short: string, text: string, proof: string | null = null, fix: string | null = null): Draft => ({ state, short, text, proof, fix })
114
119
  const shortOf = (state: CellState, at: number): string => (state === 'danger' ? `${ago(at, now)}, stale` : ago(at, now))
115
120
  const target = d.targets.find((x) => x.id === p.id)
116
- const space = target?.address.kind === 's3' && target.address.config === 'mediaSpace'
121
+ const space = target != null && configBucket(target.address) === 'mediaSpace'
117
122
  // the Space is at its provider, on no disk of a machine: its one copy off it is the second place
118
- if (store === 'space' && !(target?.address.kind === 's3' && !space)) return c('dim', space ? 'itself' : 'not here', space ? 'the Space itself, at its provider' : `the Space is not copied to ${p.label}: its copy off its provider is the second place`)
123
+ if (store === 'space' && !(target != null && configBucket(target.address) === 'spaceCopy')) return c('dim', space ? 'itself' : 'not here', space ? 'the Space itself, at its provider' : `the Space is not copied to ${p.label}: its copy off its provider is the second place`)
119
124
  if (p.kind === 'mac') {
120
125
  if (store === 'vault') return c('dim', 'live', `the live vault on ${machine}${d.vaultNear.count > 0 ? `, ${d.vaultNear.count} sealed snapshots beside it${d.vaultNear.newest == null ? '' : `, the newest ${ago(d.vaultNear.newest, now)}`}` : ''}`, 'the same disk: no help if it dies')
121
126
  return c('dim', 'live', `the live hq.sqlite on ${machine}`, 'the same disk: no help if it dies')
@@ -142,8 +147,8 @@ function cellOf(store: StoreId, p: Place, d: BackupInputs, machine: string): Dra
142
147
  }
143
148
  return stream === 'mediaSpace' ? streamCell(d) : notStreamed(stream)
144
149
  }
145
- const second = t.address.kind === 's3'
146
- if (second && d.secondPlaceKey === false) return c('warn', 'no key yet', 'no key yet: nothing goes there', null, 'ask 035: the three rv/shipkit/copy-* secrets')
150
+ const second = configBucket(t.address) === 'spaceCopy'
151
+ if (second && d.secondPlaceKey === false) return c('warn', 'no key yet', 'no key yet: nothing goes there', null, 'store the two secrets that serve.spaceCopy.key names (sk secret set)')
147
152
  if (second && store === 'hq' && stream === 'spaceCopy') return streamCell(d)
148
153
  if (store === 'vault') return sentCell(d.get<TargetSent>(`target-sent:vault:${p.id}`), now, BOUNDS.vault, BOUNDS.vault + 2 * H, 'sk daemon job backup targets')
149
154
  if (store === 'hq') return sentCell(d.get<TargetSent>(`target-sent:hq:${p.id}`), now, BOUNDS.hqCopy, BOUNDS.hqCopyDanger, 'sk daemon job backup targets')
@@ -152,7 +157,7 @@ function cellOf(store: StoreId, p: Place, d: BackupInputs, machine: string): Dra
152
157
  const proof = d.get<Proof>('space-copy-proof')
153
158
  const copy = (x: Draft): Draft => ({ ...x, of: 'space copy' })
154
159
  if (proof == null) return copy(d.get<boolean>('space-copy') === true ? c('warn', 'not yet', 'the first copy of the Space runs each night until it is whole: no proof yet', null, 'sk space') : c('warn', 'not yet', 'the Space is not copied there: the nightly copy is off', null, 'sk space copy --auto on'))
155
- const first = d.targets.find((x) => x.address.kind === 's3' && x.address.config === 'mediaSpace')?.label ?? 'the Space'
160
+ const first = d.targets.find((x) => configBucket(x.address) === 'mediaSpace')?.label ?? 'the Space'
156
161
  const of = `the nightly copy of ${first}`
157
162
  if (!proof.ok) return copy(c('danger', 'proof FAILED', `${of} failed its proof ${ago(proof.at, now)}`, proof.why[0] ?? 'the proof failed', 'sk space proof'))
158
163
  const age = now - proof.at
@@ -171,7 +176,11 @@ function cellOf(store: StoreId, p: Place, d: BackupInputs, machine: string): Dra
171
176
  return c('dim', 'not here', `nothing of ${store} goes to ${p.label}`)
172
177
  }
173
178
 
174
- const whereOf = (t: BackupTarget): string => (t.address.kind === 'ssh' ? `${t.address.host}:${t.address.folder}` : t.address.config === 'mediaSpace' ? 'the private Space (s3)' : 'the second place (s3)')
179
+ const whereOf = (t: BackupTarget): string => {
180
+ const own = ownBucket(t.address)
181
+ if (own != null) return `the bucket ${own.bucket} at ${new URL(own.endpoint).host} (s3)`
182
+ return t.address.kind === 'ssh' ? `${t.address.host}:${t.address.folder}` : configBucket(t.address) === 'mediaSpace' ? 'the private Space (s3)' : 'the second place (s3)'
183
+ }
175
184
 
176
185
  /** the table and its alarms: every cell, each row's verdict, every reason to be red */
177
186
  export function backupStatus(d: BackupInputs): BackupStatus {
@@ -190,6 +199,7 @@ export function backupStatus(d: BackupInputs): BackupStatus {
190
199
  const stores: StoreRow[] = []
191
200
  const alarms: string[] = []
192
201
  for (const s of STORES) {
202
+ if (s.id === 'vault' && d.vault === false) continue
193
203
  const row = `${judge}/${s.id}`
194
204
  const mine = places.map((p): Cell => {
195
205
  // a record that does not read leaves its cell orange, never the whole table thrown
@@ -209,15 +219,30 @@ export function backupStatus(d: BackupInputs): BackupStatus {
209
219
  // the Space is its provider's: its second copy missing is orange, a broken one red, never « no copy »
210
220
  const none = good.length === 0 && s.id !== 'space'
211
221
  // a copy there but not proven (never restored, behind) is said as such: the fix differs from a copy gone
212
- if (none) alarms.unshift(off.some((c) => c.state === 'warn') ? `${label}: NO proven copy off ${judge}` : `${label}: NO working copy off ${judge}`)
222
+ if (none && d.setUp !== false) alarms.unshift(off.some((c) => c.state === 'warn') ? `${label}: NO proven copy off ${judge}` : `${label}: NO working copy off ${judge}`)
213
223
  for (const c of off.filter((x) => x.state === 'danger' && BROKEN.has(x.short))) alarms.push(`${label} on ${places.find((p) => p.id === c.place)!.label}: ${c.text}`)
214
- const state: CellState = none ? 'danger' : off.some((c) => c.state === 'danger') ? 'danger' : off.some((c) => c.state === 'warn') || good.length === 0 ? 'warn' : 'ok'
224
+ const state: CellState = none && d.setUp === false ? 'warn' : none ? 'danger' : off.some((c) => c.state === 'danger') ? 'danger' : off.some((c) => c.state === 'warn') || good.length === 0 ? 'warn' : 'ok'
215
225
  stores.push({ row, id: s.id, machine: judge, name: s.name, what: s.what, state, line: `${good.length} of ${off.length} copies off ${judge} work` })
216
226
  }
217
227
  // the headline is the cells': a cell not proven (unknown, never drilled, behind) keeps it from green
218
228
  const unproven = cells.some((c) => c.state === 'warn' || c.state === 'danger') || stores.some((r) => r.state !== 'ok')
219
229
  const worst: CellState = alarms.length > 0 ? 'danger' : unproven ? 'warn' : 'ok'
220
- return { at: d.now, machine: judge, places, stores, cells, alarms, worst }
230
+ return { ...(d.setUp === false ? { notSetUp: true as const } : {}), at: d.now, machine: judge, places, stores, cells, alarms, worst }
231
+ }
232
+
233
+ /** whether the house config names a place for backups, or does not load: only a config read and empty says none was
234
+ * ever set up */
235
+ async function namesPlace(): Promise<boolean> {
236
+ try {
237
+ const { houseRootOf } = await import('./home-start.ts')
238
+ const { loadRepoConfig } = await import('../repo-config.ts')
239
+ const house = houseRootOf(process.cwd())
240
+ if (house == null) return true
241
+ const s = (await loadRepoConfig(house)).serve
242
+ return s?.mediaSpace != null || s?.spaceCopy != null || s?.hqReplica != null
243
+ } catch {
244
+ return true
245
+ }
221
246
  }
222
247
 
223
248
  /** every input, read on the machine that carries the hq: the targets of its hq, the kept records, Litestream's files,
@@ -254,7 +279,8 @@ export async function readBackupInputs(now = Date.now()): Promise<BackupInputs>
254
279
  } catch {
255
280
  count = 0
256
281
  }
257
- const second = machineGet<TargetSent>('target-sent:vault:cf-r2')
282
+ const copyId = targets.find((t) => configBucket(t.address) === 'spaceCopy')?.id
283
+ const second = copyId == null ? null : machineGet<TargetSent>(`target-sent:vault:${copyId}`)
258
284
  return {
259
285
  now,
260
286
  machine,
@@ -264,6 +290,8 @@ export async function readBackupInputs(now = Date.now()): Promise<BackupInputs>
264
290
  vaultNear: { count, newest },
265
291
  timeMachine: await timeMachineFacts(now),
266
292
  secondPlaceKey: second == null ? null : !('failed' in second && second.failed.startsWith('no key yet')),
293
+ vault: (await import('../secrets/read.ts')).vaultHere() || count > 0 || machineGet('vault-snapshot-sent') != null,
294
+ setUp: targets.length > 0 || folder != null || machineGet('vault-snapshot-sent') != null || machineGet('hq-drill') != null || (await namesPlace()),
267
295
  }
268
296
  }
269
297
 
@@ -295,7 +323,7 @@ export const alarmKeys = (s: BackupStatus): string[] =>
295
323
  s.stale != null
296
324
  ? []
297
325
  : [
298
- ...s.stores.filter((r) => r.stale !== true && r.id !== 'space' && !s.cells.some((c) => c.row === r.row && c.state === 'ok' && c.off)).map((r) => `${r.row}:none`),
326
+ ...s.stores.filter((r) => s.notSetUp !== true && r.stale !== true && r.id !== 'space' && !s.cells.some((c) => c.row === r.row && c.state === 'ok' && c.off)).map((r) => `${r.row}:none`),
299
327
  ...s.cells.filter((c) => c.state === 'danger' && BROKEN.has(c.short) && c.off && s.stores.find((r) => r.row === c.row)?.stale !== true).map((c) => `${c.row}@${c.place}`),
300
328
  ]
301
329
 
@@ -7,6 +7,7 @@ export const rowName = (r: Pick<StoreRow, 'name'>): string => r.name
7
7
 
8
8
  export function verdictWords(s: BackupStatus): string {
9
9
  if (s.stale != null) return `not read: ${s.stale}`
10
+ if (s.notSetUp === true) return 'no backup is set up yet: what this machine keeps is on its own disk alone'
10
11
  if (s.worst === 'danger') return 'a backup is NOT working'
11
12
  if (s.worst === 'warn') return 'not every copy is fresh and proven: the orange lines say what to fix'
12
13
  return 'every copy is fresh and proven'
@@ -67,6 +67,11 @@ async function targetsJob(now: number): Promise<string[]> {
67
67
  if ('why' in ends) return { why: `no key yet: ${ends.why}` }
68
68
  return { put: async (key, bytes) => void (await putStream(ends.to, key, new Blob([bytes.slice()]).stream(), { max: bytes.length })) }
69
69
  },
70
+ bucket: async (a) => {
71
+ const [{ bucketPut }, { houseBucket }] = await Promise.all([import('../media-store/backup/bucket-target.ts'), import('./house-bucket.ts')])
72
+ const c = await houseBucket(a)
73
+ return 'why' in c ? c : { put: (key, bytes) => bucketPut(c, key, bytes) }
74
+ },
70
75
  },
71
76
  })
72
77
  }
@@ -161,12 +161,13 @@ export const projectsOrder = (rows: readonly Pick<ProjectRow, 'name' | 'activity
161
161
  [...rows].sort((x, y) => (y.activity ?? -Infinity) - (x.activity ?? -Infinity) || x.name.localeCompare(y.name)).map((p) => p.name).join(',')
162
162
 
163
163
  /** the house's backup targets the first time: the buckets its config names */
164
- async function targetSeed(): Promise<{ mediaSpace: boolean; spaceCopy: boolean }> {
164
+ async function targetSeed(): Promise<import('../hq/backup-targets.ts').SeedFrom> {
165
165
  const { houseRootOf } = await import('./home-start.ts')
166
166
  const { loadRepoConfig } = await import('../repo-config.ts')
167
167
  const house = houseRootOf(process.cwd())
168
168
  const serve = house == null ? undefined : (await loadRepoConfig(house).catch(() => null))?.serve
169
- return { mediaSpace: serve?.mediaSpace != null, spaceCopy: serve?.spaceCopy != null }
169
+ const of = (b: { endpoint?: string; region: string } | undefined) => (b == null ? null : { region: b.region, ...(b.endpoint == null ? {} : { endpoint: b.endpoint }) })
170
+ return { mediaSpace: of(serve?.mediaSpace), spaceCopy: of(serve?.spaceCopy) }
170
171
  }
171
172
 
172
173
  export function homeRoutes(d: HomeDeps) {
@@ -0,0 +1,14 @@
1
+ // a bucket added by hand (media-store/backup/bucket-target.ts) with its key read on this machine: through the house's
2
+ // own secret manager where it declares one, else the house store
3
+ import type { BucketAddress } from '../hq/backup-targets.ts'
4
+ import { bucketConfig } from '../media-store/backup/bucket-target.ts'
5
+ import type { SpaceConfig } from '../media-store/space.ts'
6
+ import { loadRepoConfig } from '../repo-config.ts'
7
+ import { readThrough } from '../secrets/read.ts'
8
+ import { houseRootOf } from './home-start.ts'
9
+
10
+ export async function houseBucket(a: BucketAddress): Promise<SpaceConfig | { why: string }> {
11
+ const house = houseRootOf(process.cwd())
12
+ const template = house == null ? undefined : (await loadRepoConfig(house).catch(() => null))?.credsReadCommand
13
+ return bucketConfig(a, (name) => readThrough(template, name))
14
+ }
@@ -0,0 +1,68 @@
1
+ // which house this machine runs, seen from any folder: what `sk start` writes as line 1 of a new repo's CLAUDE.md, and
2
+ // where the house's `start.skip` is read. No house is named in this file: it ships on npm
3
+ import { existsSync, readdirSync, readFileSync, realpathSync } from 'fs'
4
+ import { homedir } from 'os'
5
+ import { dirname, join, relative, resolve, sep } from 'path'
6
+ import { homeRepo } from '../house/project-gutter.ts'
7
+ import { HOUSE_WIKI_INDEX, STARTER_MARK } from '../scaffold/starter-house.ts'
8
+ import { installedHouseRoot, plistPath } from './home-launchd.ts'
9
+
10
+ const inside = (p: string, root: string): boolean => p === root || p.startsWith(`${root}${sep}`)
11
+ const hosts = (dir: string): boolean => existsSync(join(dir, HOUSE_WIKI_INDEX)) && existsSync(join(dir, 'repo.config.ts'))
12
+
13
+ /** a house that `sk setup` made, whose owner chose no policy for their agents yet */
14
+ export function isStarterHouse(dir: string): boolean {
15
+ try {
16
+ return readFileSync(join(dir, 'README.md'), 'utf8').includes(STARTER_MARK)
17
+ } catch {
18
+ return false
19
+ }
20
+ }
21
+
22
+ /** the one house that `sk setup` made among the folders of `root`, null with none or several: none is guessed */
23
+ function starterHouseIn(root: string): string | null {
24
+ let names: string[]
25
+ try {
26
+ names = readdirSync(root)
27
+ } catch {
28
+ return null
29
+ }
30
+ const made = names.map((n) => join(root, n)).filter((d) => hosts(d) && isStarterHouse(d))
31
+ return made.length === 1 ? made[0]! : null
32
+ }
33
+
34
+ export type HouseLookup = {
35
+ home?: string
36
+ /** the folder the repos sit in, where a starter house is looked for */
37
+ root?: string
38
+ /** the checkout this lib runs from, a house when shipkit is developed in one. Injected by tests */
39
+ lib?: string
40
+ }
41
+
42
+ /** the house root of this machine: the one its pm runs from, else the checkout this lib runs from, else the one
43
+ * `sk setup` made beside the repos. The lib's checkout counts only under this home: a scratch home is another machine */
44
+ export function thisHouse(o: HouseLookup = {}): string | null {
45
+ const home = o.home ?? homedir()
46
+ const pm = installedHouseRoot(plistPath(home))
47
+ if (pm != null && hosts(pm)) return pm
48
+ const lib = homeRepo(resolve(o.lib ?? join(import.meta.dir, '../../../..')))
49
+ if (hosts(lib) && inside(lib, resolve(home))) return lib
50
+ return starterHouseIn(o.root ?? join(home, 'dev'))
51
+ }
52
+
53
+ /** the folder a new repo goes in: the house's own, since a house finds its repos among its siblings, else ~/dev */
54
+ export const reposRoot = (house: string | null, home: string): string => (house != null ? dirname(house) : join(home, 'dev'))
55
+
56
+ /** the line 1 a wired repo's CLAUDE.md carries: the house index, `~/` relative when it sits under the home */
57
+ export function houseLine(house: string, home: string): string {
58
+ const index = join(house, HOUSE_WIKI_INDEX)
59
+ const real = (p: string): string => {
60
+ try {
61
+ return realpathSync(p)
62
+ } catch {
63
+ return resolve(p)
64
+ }
65
+ }
66
+ // a home behind a symlink (/var → /private/var) would expand `~/` to another spelling of the path
67
+ return inside(index, home) && real(home) === home ? `@~/${relative(home, index)}` : `@${index}`
68
+ }
@@ -20,10 +20,11 @@ import { TRACE_ENV } from '../trace/tracer.ts'
20
20
  import { FRESH_ENV } from '../ledger/store.ts'
21
21
  import { LEDGER_ENV } from '../ledger/ledger.ts'
22
22
  import { PARALLEL_ENV } from '../core/parallel.ts'
23
+ import { SUITE_SELECT_ENV } from '../suite/reads-env.ts'
23
24
 
24
25
  /** the env switches a gate reads, which a terminal may set for one run: the
25
26
  * job the home starts runs with the daemon's env, so they travel with it */
26
- export const FORWARDED_ENV = [TRACE_ENV, FRESH_ENV, LEDGER_ENV, PARALLEL_ENV] as const
27
+ export const FORWARDED_ENV = [TRACE_ENV, FRESH_ENV, LEDGER_ENV, PARALLEL_ENV, SUITE_SELECT_ENV] as const
27
28
 
28
29
  /** the forwarded switches this env sets */
29
30
  export const forwardedEnv = (env: Env = process.env): Record<string, string> =>
@@ -3,31 +3,72 @@
3
3
  //
4
4
  // The constraint a reader breaks first: a row never holds a secret, and never a second copy of an address the house
5
5
  // config already owns. A bucket the config names (the Space, its second place) is a row that names that config key;
6
- // only a place with no other owner (an ssh machine, a bucket added by hand) holds its own address
6
+ // only a place with no other owner (an ssh machine, a bucket added by hand) holds its own address, and the names of the
7
+ // two secrets of its key
7
8
  import type { Database } from 'bun:sqlite'
9
+ import type { KeyPairNames } from '../secrets/key-pair.ts'
10
+ import { SECRET_NAME } from '../secrets/name.ts'
8
11
 
9
12
  /** where a target's address lives: a key of the house config's `serve`, or the row itself */
10
13
  export type TargetAddress =
11
14
  | { kind: 's3'; config: 'mediaSpace' | 'spaceCopy' }
15
+ | BucketAddress
12
16
  | { kind: 'ssh'; host: string; folder: string }
13
17
 
18
+ /** a bucket added by hand, at any S3 server: its origin, and the names of the two secrets of its key */
19
+ export type BucketAddress = {
20
+ kind: 's3'
21
+ /** the origin, the bucket in its host or in its path (`path`) */
22
+ endpoint: string
23
+ bucket: string
24
+ region: string
25
+ /** the bucket in the path, not the host: MinIO, R2 and any server at one origin want it */
26
+ path?: boolean
27
+ key: KeyPairNames
28
+ }
29
+
30
+ /** the bucket a row holds itself, null for a machine and for a bucket the house config owns */
31
+ export const ownBucket = (a: TargetAddress): BucketAddress | null => (a.kind === 's3' && !('config' in a) ? a : null)
32
+ /** the config key that owns a row's bucket, null for a machine and for a bucket the row holds itself */
33
+ export const configBucket = (a: TargetAddress): 'mediaSpace' | 'spaceCopy' | null => (a.kind === 's3' && 'config' in a ? a.config : null)
34
+
14
35
  export type BackupTarget = { id: string; label: string; on: boolean; at: number; address: TargetAddress }
15
36
 
16
37
  export const TARGETS_SCHEMA = 'create table if not exists backup_targets (id text primary key, label text not null, address text not null, on_ integer not null, at integer not null) without rowid;'
17
38
 
18
39
  const ID = /^[a-z0-9][a-z0-9-]{0,39}$/
40
+ const BUCKET = /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/
41
+ const REGION = /^[A-Za-z0-9-]{1,40}$/
19
42
  const HOST = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/
20
43
  /** a folder under the target's home: `~/` then plain names, never `..` */
21
44
  const FOLDER = /^~\/(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+$/
22
45
 
23
46
  /** why an address cannot be stored, null when it can */
24
47
  export function addressProblem(a: TargetAddress): string | null {
25
- if (a.kind === 's3') return a.config === 'mediaSpace' || a.config === 'spaceCopy' ? null : 'an s3 target names serve.mediaSpace or serve.spaceCopy'
48
+ if (a.kind === 's3') return 'config' in a ? (a.config === 'mediaSpace' || a.config === 'spaceCopy' ? null : 'an s3 target names serve.mediaSpace or serve.spaceCopy') : bucketProblemOf(a)
26
49
  if (!HOST.test(a.host)) return `${JSON.stringify(a.host)}: an ssh host of letters, digits, dots, dashes`
27
50
  if (!FOLDER.test(a.folder) || a.folder.split('/').includes('..')) return `${JSON.stringify(a.folder)}: a folder under the home, ~/a/b`
28
51
  return null
29
52
  }
30
53
 
54
+ const LOOPBACK = new Set(['127.0.0.1', 'localhost', '[::1]'])
55
+ /** why a bucket's address cannot be stored, null when it can: a copy of the house's data never goes over plain http */
56
+ function bucketProblemOf(a: BucketAddress): string | null {
57
+ let origin: URL
58
+ try {
59
+ origin = new URL(a.endpoint)
60
+ } catch {
61
+ return `${JSON.stringify(a.endpoint)}: the origin of an S3 server, https://s3.example.com`
62
+ }
63
+ if (origin.protocol !== 'https:' && !(origin.protocol === 'http:' && LOOPBACK.has(origin.hostname))) return `${a.endpoint}: not https`
64
+ if (origin.username !== '' || origin.password !== '') return 'the endpoint carries a password: store it as a secret and name it'
65
+ if (origin.origin !== a.endpoint.replace(/\/$/, '')) return `${a.endpoint}: the origin alone, ${origin.origin}, with no path`
66
+ if (!BUCKET.test(a.bucket)) return `${JSON.stringify(a.bucket)}: a bucket of 3 to 63 lowercase letters, digits, dots, dashes`
67
+ if (!REGION.test(a.region)) return `${JSON.stringify(a.region)}: a region of letters, digits, dashes (auto, us-east-1)`
68
+ for (const n of [a.key?.accessKeyId, a.key?.secretAccessKey]) if (typeof n !== 'string' || !SECRET_NAME.test(n)) return 'a bucket names the two secrets of its key: the access key id and the secret access key'
69
+ return null
70
+ }
71
+
31
72
  /** every target, in the order they were added */
32
73
  export function listTargets(db: Database): BackupTarget[] {
33
74
  const has = db.query("select 1 from sqlite_master where type = 'table' and name = 'backup_targets'").get() != null
@@ -57,9 +98,21 @@ export function removeTarget(db: Database, id: string): { removed: boolean } {
57
98
  return { removed: db.query('delete from backup_targets where id = ?').run(id).changes > 0 }
58
99
  }
59
100
 
101
+ /** what the config says of a bucket it names, for the first label of its row; null for a bucket it does not name */
102
+ export type SeedBucket = { endpoint?: string; region: string }
103
+ export type SeedFrom = { mediaSpace: SeedBucket | null; spaceCopy: SeedBucket | null }
104
+
105
+ /** the id and label a provider's bucket starts with, read from its origin; `auto` is the region of R2 alone */
106
+ function seedName(b: SeedBucket, other: { id: string; label: string }): { id: string; label: string } {
107
+ const host = b.endpoint == null || !URL.canParse(b.endpoint) ? '' : new URL(b.endpoint).hostname
108
+ if (host.endsWith('.digitaloceanspaces.com')) return { id: 'do-space', label: 'DigitalOcean Space' }
109
+ if (host.endsWith('.r2.cloudflarestorage.com') || (host === '' && b.region === 'auto')) return { id: 'cf-r2', label: 'Cloudflare R2' }
110
+ return other
111
+ }
112
+
60
113
  /** the house's targets the first time: the Space, and its second place when the config names one; a machine is added
61
114
  * by hand. Only into an empty table, so a row the owner removed never comes back by itself */
62
- export function seedTargets(db: Database, o: { mediaSpace: boolean; spaceCopy: boolean; now: number }): BackupTarget[] {
115
+ export function seedTargets(db: Database, o: SeedFrom & { now: number }): BackupTarget[] {
63
116
  if (listTargets(db).length > 0) return []
64
117
  const out: BackupTarget[] = []
65
118
  const put = (t: Parameters<typeof putTarget>[1], at: number): void => {
@@ -67,8 +120,8 @@ export function seedTargets(db: Database, o: { mediaSpace: boolean; spaceCopy: b
67
120
  if (!('refused' in r)) out.push(r)
68
121
  }
69
122
  db.transaction(() => {
70
- if (o.mediaSpace) put({ id: 'do-space', label: 'DigitalOcean Space', address: { kind: 's3', config: 'mediaSpace' } }, o.now)
71
- if (o.spaceCopy) put({ id: 'cf-r2', label: 'Cloudflare R2', address: { kind: 's3', config: 'spaceCopy' } }, o.now + 1)
123
+ if (o.mediaSpace) put({ ...seedName(o.mediaSpace, { id: 'space', label: 'the Space' }), address: { kind: 's3', config: 'mediaSpace' } }, o.now)
124
+ if (o.spaceCopy) put({ ...seedName(o.spaceCopy, { id: 'space-copy', label: 'the second place' }), address: { kind: 's3', config: 'spaceCopy' } }, o.now + 1)
72
125
  }).immediate()
73
126
  return out
74
127
  }
@@ -355,7 +355,7 @@ export function setHqPort(open: boolean): { open: boolean; port: number } | Refu
355
355
  * writer of its file: the door opened or closed, a join code for another machine, the end of a node, a prompt
356
356
  * forgotten, a switch wanted of another machine */
357
357
  /** what the first list of backup targets is seeded from, which the daemon reads in the house (backup-targets.ts) */
358
- export type TargetSeed = () => Promise<{ mediaSpace: boolean; spaceCopy: boolean }>
358
+ export type TargetSeed = () => Promise<import('./backup-targets.ts').SeedFrom>
359
359
 
360
360
  export async function hqAdminRoute(req: Request, path: string, now: number = Date.now(), o: { seed?: TargetSeed } = {}): Promise<Response | null> {
361
361
  if (!path.startsWith('/api/home/hq/') || req.method !== 'POST') return null
@@ -0,0 +1,58 @@
1
+ // a bucket added by hand as a place for copies (wiki tools/shipkit/media-store-backup.md, Targets): any S3 server, its
2
+ // address in the hq's row, its key pair read through the house store and held in memory only. A copy goes up under
3
+ // `_snapshots/<store>/<machine>/`, its name carrying 12 of its sha, and a copy read back is compared with that name.
4
+ import { mkdirSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+ import { atomicWrite } from '../../core/atomic-write.ts'
7
+ import type { BucketAddress } from '../../hq/backup-targets.ts'
8
+ import { readKeyPair } from '../../secrets/key-pair.ts'
9
+ import { putStream } from '../copy/stream.ts'
10
+ import { signedFetch, spaceOf, type SpaceConfig } from '../space.ts'
11
+ import { COPY_NAME, SAFE, sha256 } from './ssh-target.ts'
12
+
13
+ /** the bucket as a config the S3 calls sign with, or why it cannot be reached: a key half that is not stored */
14
+ export async function bucketConfig(a: BucketAddress, read: (name: string) => Promise<string>): Promise<SpaceConfig | { why: string }> {
15
+ try {
16
+ return { endpoint: a.endpoint, bucket: a.bucket, region: a.region, ...(a.path === true ? { path: true } : {}), cdn: null, creds: await readKeyPair(a.key, read) }
17
+ } catch (e) {
18
+ return { why: `no key yet: ${(e as Error).message}` }
19
+ }
20
+ }
21
+
22
+ export const bucketPut = async (c: SpaceConfig, key: string, bytes: Uint8Array): Promise<void> => void (await putStream(c, key, new Blob([bytes.slice()]).stream(), { max: bytes.length }))
23
+
24
+ /** the folder of one store's copies of one machine */
25
+ export const copiesDir = (store: string, machine: string): string => `_snapshots/${store}/${machine}/`
26
+
27
+ /** what a bucket answers to one small object written and read back: null when it gave the same bytes */
28
+ export async function bucketProblem(c: SpaceConfig, machine: string, now = Date.now()): Promise<string | null> {
29
+ if (!SAFE.test(machine)) return `${machine}: not a safe folder name`
30
+ const key = `${copiesDir('check', machine)}check.txt`
31
+ const bytes = new TextEncoder().encode(`shipkit ${now}\n`)
32
+ try {
33
+ await bucketPut(c, key, bytes)
34
+ const r = await signedFetch(c, 'GET', key, {})
35
+ if (!r.ok) return `it took an object and does not read it back: ${r.status}`
36
+ return sha256(new Uint8Array(await r.arrayBuffer())) === sha256(bytes) ? null : 'it gave other bytes back than the ones written'
37
+ } catch (e) {
38
+ return (e as Error).message
39
+ }
40
+ }
41
+
42
+ /** the newest copy of a store written back under `to`, its bytes compared with the sha its name carries; an `.gz` one
43
+ * is gunzipped beside it. Throws with its reason, and leaves no file of a copy that did not match */
44
+ export async function getNewest(c: SpaceConfig, o: { store: string; machine: string; to: string }): Promise<{ key: string; file: string; bytes: number }> {
45
+ const names = (await spaceOf(c).list(copiesDir(o.store, o.machine))).map((x) => x.key.slice(copiesDir(o.store, o.machine).length)).filter((n) => COPY_NAME.test(n)).sort()
46
+ const name = names.at(-1)
47
+ if (name == null) throw new Error(`no copy of ${o.store} from ${o.machine} in ${c.bucket}`)
48
+ const key = `${copiesDir(o.store, o.machine)}${name}`
49
+ const r = await signedFetch(c, 'GET', key, {})
50
+ if (!r.ok) throw new Error(`${key} does not read back: ${r.status}`)
51
+ const bytes = new Uint8Array(await r.arrayBuffer())
52
+ if (sha256(bytes).slice(0, 12) !== COPY_NAME.exec(name)![2]) throw new Error(`${key} came back with other bytes than the ones that went up`)
53
+ const out = name.endsWith('.gz') ? Bun.gunzipSync(bytes) : bytes
54
+ const file = join(o.to, `${o.store}-${name.replace(/\.gz$/, '')}`)
55
+ mkdirSync(o.to, { recursive: true })
56
+ atomicWrite(file, out, { mode: 0o600 })
57
+ return { key, file, bytes: out.length }
58
+ }
@@ -9,7 +9,7 @@ import { readdirSync, readFileSync, mkdtempSync, rmSync, statSync } from 'node:f
9
9
  import { tmpdir } from 'node:os'
10
10
  import { join } from 'node:path'
11
11
  import { machineGet, machineSet } from '../../core/machine-db.ts'
12
- import type { BackupTarget } from '../../hq/backup-targets.ts'
12
+ import { configBucket, ownBucket, type BackupTarget, type BucketAddress } from '../../hq/backup-targets.ts'
13
13
  import type { ReplicaPlace } from '../../hq/replica.ts'
14
14
  import type { BackupRetention } from './retention.ts'
15
15
  import { copyName, homeRelative, houseSsh, SAFE, sha256, sshPrune, sshPut, type Ssh } from './ssh-target.ts'
@@ -30,7 +30,7 @@ export const HQ_EVERY_MS = 60 * 60_000
30
30
  const RETRY_MS = 10 * 60_000
31
31
 
32
32
  /** the targets this job sends to: every one on, except the Space, which each store reaches its own way */
33
- export const sealedTargets = (targets: readonly BackupTarget[]): BackupTarget[] => targets.filter((t) => t.on && !(t.address.kind === 's3' && t.address.config === 'mediaSpace'))
33
+ export const sealedTargets = (targets: readonly BackupTarget[]): BackupTarget[] => targets.filter((t) => t.on && configBucket(t.address) !== 'mediaSpace')
34
34
 
35
35
  /** the vault's newest sealed snapshot beside it, null when none */
36
36
  export function newestVaultSnap(dir: string): { file: string; mtime: number } | null {
@@ -56,6 +56,8 @@ export type SendDeps = {
56
56
  policy: BackupRetention | null
57
57
  /** the second place's bucket, or why there is none (copy/config.ts houseCopy) */
58
58
  secondPlace: () => Promise<{ put: (key: string, bytes: Uint8Array) => Promise<void> } | { why: string }>
59
+ /** a bucket a row holds itself, or why it cannot be reached (bucket-target.ts) */
60
+ bucket: (a: BucketAddress) => Promise<{ put: (key: string, bytes: Uint8Array) => Promise<void> } | { why: string }>
59
61
  }
60
62
 
61
63
  /** one file of one store to one target, the send kept for the status. The line to print */
@@ -80,7 +82,8 @@ export async function sendTo(store: StoreId, t: BackupTarget, f: { name: string;
80
82
  if (d.policy != null) pruned = await sshPrune({ ssh, peer: t.address.host, dir, now: at, policy: d.policy }).then((n) => `, ${n} pruned`, (e: Error) => `; the old copies were not pruned: ${e.message}`)
81
83
  return `ok: ${store} to ${t.label}: ${t.address.host}:~/${dir}/${f.name}, ${(f.bytes.length / 1e6).toFixed(1)} MB, checked by its sha there${pruned}`
82
84
  }
83
- const place = await d.secondPlace()
85
+ const own = ownBucket(t.address)
86
+ const place = own == null ? await d.secondPlace() : await d.bucket(own)
84
87
  if ('why' in place) return fail(place.why)
85
88
  const key = `_snapshots/${store}/${d.machine}/${f.name}`
86
89
  await place.put(key, f.bytes)
@@ -95,7 +98,7 @@ export async function sendTo(store: StoreId, t: BackupTarget, f: { name: string;
95
98
  * hour old. Cheap: rows of the machine db and one directory read */
96
99
  export function targetsDue(targets: readonly BackupTarget[], o: { vaultDir: string | null; carriesHq: boolean; now: number; stream?: ReplicaPlace | null }): { vault: BackupTarget[]; hq: BackupTarget[] } {
97
100
  const to = sealedTargets(targets)
98
- const streamed = (t: BackupTarget): boolean => t.address.kind === 's3' && t.address.config === o.stream
101
+ const streamed = (t: BackupTarget): boolean => o.stream != null && configBucket(t.address) === o.stream
99
102
  const snap = o.vaultDir == null ? null : newestVaultSnap(o.vaultDir)
100
103
  return {
101
104
  vault: snap == null ? [] : to.filter((t) => vaultDueTo(lastSentTo('vault', t.id), snap.mtime, o.now)),
@@ -14,6 +14,8 @@ export interface MediaSpace {
14
14
  endpoint: string
15
15
  bucket: string
16
16
  region: string
17
+ /** the bucket in the path, not the host: MinIO and any server at one origin want it, its `endpoint` then the origin alone */
18
+ path?: boolean
17
19
  /** the CDN edge a signed URL is handed out on */
18
20
  cdn?: string
19
21
  /** the two secrets of its key, read through the house store */
@@ -2,6 +2,7 @@
2
2
  // reply, note and state change is one cell, in time order, built at read time from the store's files (a supersedes chain
3
3
  // folds into one thread, nothing is rewritten). The paged list's rows and its query. Pure and browser safe: the routes
4
4
  // send these shapes, the hub page draws them
5
+ import { findLast } from '../core/es2022.ts'
5
6
  import {
6
7
  type AnswerKind,
7
8
  canonicalAddress,
@@ -184,6 +185,9 @@ export interface ReplyCell extends CellOf<'reply'> {
184
185
  recap?: true
185
186
  /** his request for a recap */
186
187
  recapAsk?: true
188
+ /** a person's ok or fix on a version that waits for the owner, on their own view (advisors/sync.ts pendingCells): its
189
+ * tone and the version it judges, which their answer bar draws lit */
190
+ advice?: { status: 'approved' | 'approved-with-fix'; on: string }
187
191
  }
188
192
 
189
193
  export interface Linked {
@@ -390,11 +394,11 @@ function messageCells(x: ReviewItem, n: number, opening: Message | undefined, go
390
394
  const re = reOn ? { id: `${id}/${m.re}`, k: rk + 1, state: reOn.state } : undefined
391
395
  const said = update ? `${UPDATE_WORDS[update.state]}: ` : re ? `on update ${re.k}: ` : ''
392
396
  // the newest answer: a person with a direct pick may change theirs
393
- const reply = x.thread.findLast((y) => y.re === m.id && y.answer !== undefined && partyOf(y.who) === 'owner')
397
+ const reply = findLast(x.thread, (y) => y.re === m.id && y.answer !== undefined && partyOf(y.who) === 'owner')
394
398
  // the owner's words alone in a choice's own box answer it as none of the options; a plain reply never does
395
399
  const words = reply === undefined && m.ask ? answersTo(x.thread, m).find(wordsAlone) : undefined
396
400
  const answers = m.ask ? x.thread.filter((y) => y.re === m.id && y.answer?.option !== undefined) : []
397
- const ownerPick = answers.findLast((y) => y.who === 'owner')?.answer?.option
401
+ const ownerPick = findLast(answers, (y) => y.who === 'owner')?.answer?.option
398
402
  const people = new Map<string, PersonPick>()
399
403
  for (const y of m.ask ? x.thread : []) {
400
404
  if (y.who !== 'player' || y.at < m.at) continue
@@ -2,6 +2,7 @@
2
2
  // (item-rows.ts), its head and each message, never rewritten; its media wait in the spool beside that file (item-db.ts
3
3
  // spoolOf) until the media store sent them up. A view's files are written in a dot folder and land whole, so no reader
4
4
  // sees half of one. `io` is the one way in: every function here reads and writes through it
5
+ import { findLast } from '../core/es2022.ts'
5
6
  import { ownerCursorAt } from './owner-read.ts'
6
7
  import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
7
8
  import { basename, dirname, extname, join, resolve } from 'node:path'
@@ -1254,7 +1255,7 @@ export function postAction(dir: string, id: string, a: { name: string; text?: st
1254
1255
  const text = words === '' ? a.name : words
1255
1256
  const now = a.now ?? new Date()
1256
1257
  // the same click twice (a double click, a second press while the first was on its way): one act, the first one
1257
- const twice = x.thread.findLast((m) => m.action !== undefined && partyOf(m.who) === 'owner' && m.re === a.re)
1258
+ const twice = findLast(x.thread, (m) => m.action !== undefined && partyOf(m.who) === 'owner' && m.re === a.re)
1258
1259
  if (twice?.action?.name === a.name && twice.text === text && now.getTime() - Date.parse(twice.at) < SAME_ACT_MS) return twice
1259
1260
  return appendMessage(dir, id, { who: 'owner', action: { name: a.name }, text, ...(a.re !== undefined ? { re: a.re } : {}) }, { now })
1260
1261
  }
@@ -175,11 +175,11 @@ function writeHouseFiles(write: (rel: string, body: string) => void, vars: Recor
175
175
  * include lines pull it into the house contract, so it gets the house half
176
176
  * of the day-one shape and nothing that says what the repo IS. Create-only,
177
177
  * so every file the repo already holds wins. Returns the paths it wrote */
178
- export function adoptHouse(root: string, opts: { name: string; today?: string; print?: (line: string) => void; cli?: boolean }): string[] {
178
+ export function adoptHouse(root: string, opts: { name: string; today?: string; print?: (line: string) => void; cli?: boolean; claudePolicy: boolean }): string[] {
179
179
  const p = opts.print ?? console.log
180
180
  const vars = { NAME: opts.name, PORT: String(defaultHubPort(opts.name)), DATE: opts.today ?? dayStamp(), ...cliIndexVars(opts.name, opts.cli === true) }
181
181
  const written: string[] = []
182
- writeHouseFiles((rel, body) => { if (put(root, rel, body)) written.push(rel) }, vars, true, written, p)
182
+ writeHouseFiles((rel, body) => { if (put(root, rel, body)) written.push(rel) }, vars, opts.claudePolicy, written, p)
183
183
  if (written.length > 0) p(`ok: adopted into the house, ${written.length} file(s) seeded: ${written.join(', ')}`)
184
184
  return written
185
185
  }
@@ -207,7 +207,9 @@ class Twin {
207
207
  const cs = t.ownerDocument.defaultView?.getComputedStyle?.(t)
208
208
  if (cs) for (const p of TWIN_COPIES) this.el.style.setProperty(p, cs.getPropertyValue(p))
209
209
  this.el.style.width = `${t.clientWidth}px`
210
- this.edge = t.offsetHeight - t.clientHeight
210
+ // the borders as css says them: under a page zoom (WebKit, sk gui) offsetHeight and clientHeight round apart by a
211
+ // px that depends on the height just set, so the box flipped between two heights each frame
212
+ this.edge = cs ? parseFloat(cs.borderTopWidth) + parseFloat(cs.borderBottomWidth) : t.offsetHeight - t.clientHeight
211
213
  const max = parseFloat(cs?.maxHeight ?? '')
212
214
  this.max = Number.isFinite(max) ? max : Infinity
213
215
  this.rows = rows
@@ -3,6 +3,7 @@
3
3
  // them (every version, view, verdict and reply: a click scrolls there and unfolds it), and his answer box pinned under
4
4
  // them: one word, sent with a verdict or as a reply, and nothing between the cells and the box; the arrows at the column's
5
5
  // top count what waits above. The column opens scrolled to the newest cell
6
+ import { findLast } from '../../../core/es2022.ts'
6
7
  import { observer } from 'mobx-react-lite'
7
8
  import { WordRefsCtx } from '../word-refs.ts'
8
9
  import { tagChoices, tagOf } from '../../../review/thread-query.ts'
@@ -250,7 +251,7 @@ const StageBar = observer(({ rv, thread, menu }: { rv: ReviewSt; thread: ThreadS
250
251
 
251
252
  /** a thread that came from another repo says so at its head, quietly: « moved here from <repo> » */
252
253
  const MovedLine = observer(({ thread }: { thread: ThreadSt }) => {
253
- const t = thread.cells.findLast((c) => 'trace' in c && c.trace?.act === 'move')
254
+ const t = findLast(thread.cells, (c) => 'trace' in c && c.trace?.act === 'move')
254
255
  const from = t && 'trace' in t ? /from (\S+) to /.exec(t.trace?.did ?? '')?.[1] : undefined
255
256
  return from === undefined ? null : <span className="trm" data-check="moved-here" {...tip(t && 'summary' in t ? t.summary : '')}>moved here from {from}</span>
256
257
  })
@@ -814,13 +814,19 @@ export class ThreadSt {
814
814
  return this.takeBack()
815
815
  }
816
816
 
817
- /** the verdict given on `on` (a version's id or a message's cell id), the one on its way first */
817
+ /** the verdict given on `on` (a version's id or a message's cell id), the one on its way first; on a person's own
818
+ * view, their newest ok or fix on that version that waits for the owner */
818
819
  givenOn(on: string): ItemVerdict | undefined {
819
820
  const q = this.questionCell(on)
820
- const s = this.chosenOn(on) ?? (q !== undefined ? this.questionTone(q) : this.askingCell(on)?.judge?.verdict?.status)
821
+ const s = this.chosenOn(on) ?? (q !== undefined ? this.questionTone(q) : (this.askingCell(on)?.judge?.verdict?.status ?? this.adviceOn(on)))
821
822
  return s !== undefined && (ITEM_VERDICTS as readonly string[]).includes(s) ? (s as ItemVerdict) : undefined
822
823
  }
823
824
 
825
+ /** the tone of the reader's newest advice on version `on` that waits for the owner (advisors/sync.ts pendingCells) */
826
+ private adviceOn(on: string): ItemVerdict | undefined {
827
+ return findLast(this.cells, (c): c is ReplyCell => c.kind === 'reply' && c.advice?.on === on)?.advice?.status
828
+ }
829
+
824
830
  /** the message `on` names when it is one that asks the owner's verdict; a version's id names none */
825
831
  private askingCell(on: string): ReplyCell | undefined {
826
832
  return this.cells.find((x): x is ReplyCell => x.kind === 'reply' && x.id === on)
@@ -46,6 +46,8 @@ export const ToneBar = observer(({ thread, on, question, pick, option }: { threa
46
46
  const buttons = useRef(new Map<ItemVerdict, HTMLButtonElement>())
47
47
  const sent = thread.givenOn(on)
48
48
  const version = question === undefined && thread.versionOf(on)?.id === on
49
+ // a person's ok waits for the owner: they add a note to it, never take back what only he holds
50
+ const takesBack = version && thread.can('reopen')
49
51
  const given = sent !== undefined && !(version && thread.marked)
50
52
  const note = thread.note?.on === on && thread.note.option === option ? thread.note : null
51
53
  const failed = thread.failed?.on === on && note === null ? thread.failed.why : null
@@ -67,7 +69,7 @@ export const ToneBar = observer(({ thread, on, question, pick, option }: { threa
67
69
  return (
68
70
  <button key={t.status} type="button" ref={(b) => void (b ? buttons.current.set(t.status, b) : buttons.current.delete(t.status))} data-check="tone" data-status={t.status}
69
71
  className={`rv-tone ${cls(t.status)}${lit ? ' chosen' : ''}${open ? ' open' : ''}${t.words ? ' words' : ''}`} aria-pressed={lit} aria-haspopup={t.words ? 'dialog' : undefined} aria-expanded={t.words ? open : undefined}
70
- {...tip(`${t.word} (${t.key} or ${t.letter}): ${lit ? 'your answer; a note on it' + (version ? ', or take it back' : '') : t.says}${t.words && !lit ? '\nopens a box for your words, Enter sends' : ''}`)}
72
+ {...tip(`${t.word} (${t.key} or ${t.letter}): ${lit ? 'your answer; a note on it' + (takesBack ? ', or take it back' : '') : t.says}${t.words && !lit ? '\nopens a box for your words, Enter sends' : ''}`)}
71
73
  onMouseDown={keepFocus} onClick={() => void thread.tone(on, t.status, option)}>
72
74
  <ToneMark t={t} />
73
75
  <span className="rv-toneword">{t.word}</span>
@@ -78,7 +80,7 @@ export const ToneBar = observer(({ thread, on, question, pick, option }: { threa
78
80
  {note && noteTone ? (
79
81
  <Popover open anchor={buttons.current.get(note.status) ?? null} onClose={() => thread.cancelNote()} outside={note.text.trim() === ''} className={`rv-vnote ${cls(note.status)}${option !== undefined ? ' boxed' : ''}`}
80
82
  label={`your ${noteTone.word}, with your words`} placement={option !== undefined ? 'bottom-start' : 'top-start'} fallbacks={option !== undefined ? ['top-start'] : ['bottom-start', 'top-end']}>
81
- <NoteBox thread={thread} on={on} t={noteTone} question={q} text={note.text} why={note.why ?? null} takesBack={version && sent === note.status} />
83
+ <NoteBox thread={thread} on={on} t={noteTone} question={q} text={note.text} why={note.why ?? null} takesBack={takesBack && sent === note.status} />
82
84
  </Popover>
83
85
  ) : null}
84
86
  {failed !== null ? <span className="rv-vfail" role="alert">✗ not saved: {failed}</span> : null}
@@ -15,6 +15,7 @@ import { consumerOf } from './core/machine-link.ts'
15
15
  import { runner, type Run } from './git-bootstrap.ts'
16
16
  import { installedHouseRoot, plistPath } from './home/home-launchd.ts'
17
17
  import { daemonUp, homeUp, pmUp } from './home/home-paths.ts'
18
+ import { houseLine } from './home/this-house.ts'
18
19
  import { includeTargets } from './house/project-gutter.ts'
19
20
  import { initRepo } from './init-repo.ts'
20
21
  import { loadRepoConfig } from './repo-config.ts'
@@ -94,13 +95,6 @@ async function defaultPortsUp(): Promise<string[]> {
94
95
  return [pm ? 'pm' : null, daemon ? 'daemon' : null, web ? 'web' : null].filter((x): x is string => x != null)
95
96
  }
96
97
 
97
- /** the line 1 a wired repo's CLAUDE.md carries: the house index, `~/` relative when it sits under the home */
98
- export function houseLine(house: string, home: string): string {
99
- const index = join(house, HOUSE_WIKI_INDEX)
100
- // a home behind a symlink (/var → /private/var) would expand `~/` to another spelling of the path
101
- return inside(index, home) && real(home) === home ? `@~/${relative(home, index)}` : `@${index}`
102
- }
103
-
104
98
  /** what is in the way, each a line with its fix; empty when setup may go on. Reads, never writes */
105
99
  export async function refusals(o: { repo: string; house: string; home: string; scratch: boolean; realHome: string; platform: string; portsUp: () => Promise<string[]>; which: (b: string) => string | null; gitIdentity: () => Promise<{ name: string; email: string }> }): Promise<string[]> {
106
100
  const out: string[] = []
package/src/start-repo.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  // `shipkit start` — ensure <root>/<name> exists and that CLAUDE.md carries
2
- // its include lines (in order, at the top): the HOUSE lines below, unless
3
- // --include overrides them or the house index is not on this disk, then
2
+ // its include lines (in order, at the top): the house's own lines, unless
3
+ // --include overrides them or this machine has no house, then
4
4
  // `@./agent/index.md` whenever the repo has that file, because the scaffold
5
5
  // writes it and SK003 fails a repo that has it unrouted. Plain module behind
6
6
  // cmd_Start. Status lines go to STDERR —
@@ -9,9 +9,10 @@
9
9
  // for its parent shell).
10
10
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
11
11
  import { homedir } from 'os'
12
- import { dirname, join } from 'path'
12
+ import { join } from 'path'
13
13
  import { ensureGitRepo, ensureIgnoreBaseline, firstGhLine, isScratch, publishRepo, runner, type Run } from './git-bootstrap.ts'
14
14
  import { initRepo } from './init-repo.ts'
15
+ import { houseLine, isStarterHouse, reposRoot, thisHouse } from './home/this-house.ts'
15
16
  import { AGENT_LINE } from './checks/SK003-claude-md-shape.check.ts'
16
17
  import { writeContextLine } from './context/context-line.ts'
17
18
  import { writeProjectContext } from './context/project-context.ts'
@@ -19,36 +20,31 @@ import { adoptCli, adoptHouse, installedLib, scaffoldProject, TOOLCHAIN } from '
19
20
  import { kitInstalled } from './scaffold/cli-skeleton.ts'
20
21
  import { defaultHubPort } from './http/hub-port.ts'
21
22
 
22
- /** the one template: `shipkit start <name>` is the only thing anyone types,
23
- * and a repo without the house wiki in its context is not a started repo.
24
- * Base context first, the repo's own router last, so repo docs override.
25
- * A public repo swaps line 1 for the gitignored `@./CLAUDE.local.md`,
23
+ /** the lines of a started repo: the house of this machine first (home/this-house.ts), the repo's own router last, so
24
+ * repo docs override. A public repo swaps line 1 for the gitignored `@./CLAUDE.local.md`,
26
25
  * which is why that line satisfies the first include (SK003) */
27
- // sk-disable-next-line RV003, SK035 -- the start template writes the house include line itself
28
- export const HOUSE_INCLUDE = ['@~/dev/corvion/wiki/index.md', '@./agent/index.md']
26
+ export const houseInclude = (house: string, home: string): string[] => [houseLine(house, home), AGENT_LINE]
27
+ /** whether a start writes the .claude/ policy files, a pre-approved shell allowlist among them: for include lines the
28
+ * caller typed, and for a house its owner wrote; a house `sk setup` made chose no policy, so it widens no permission */
29
+ export const writesPolicy = (o: { include?: readonly string[] | undefined; house: string | null }): boolean => (o.include != null ? o.include.length > 0 : o.house != null && !isStarterHouse(o.house))
30
+
29
31
  export const HOUSE_ALSO_OK = ['@./CLAUDE.local.md']
30
32
  /** a repo shipkit never touches: no CLAUDE.md, no git, no scaffold, no push */
31
33
  export const isSkipped = (name: string, skip: readonly string[]): boolean => skip.includes(name)
32
34
 
33
35
  /** the repo names the house config lists under `start.skip` (a day-job checkout belongs there), [] with no house:
34
36
  * the names live on the machine, never in this published lib */
35
- export async function houseSkip(home: string): Promise<string[]> {
36
- const root = dirname(dirname(housePath(home)))
37
- if (!existsSync(join(root, 'repo.config.ts'))) return []
37
+ export async function houseSkip(home: string, root?: string): Promise<string[]> {
38
+ const house = thisHouse({ home, ...(root != null ? { root } : {}) })
39
+ if (house == null) return []
38
40
  const { loadRepoConfig } = await import('./repo-config.ts')
39
- return [...((await loadRepoConfig(root)).start?.skip ?? [])]
40
- }
41
-
42
- /** where the first house line points, `~` resolved against `home` */
43
- export const housePath = (home: string): string => {
44
- const p = HOUSE_INCLUDE[0]!.replace(/^@/, '')
45
- return p.startsWith('~/') ? join(home, p.slice(2)) : p
41
+ return [...((await loadRepoConfig(house)).start?.skip ?? [])]
46
42
  }
47
43
 
48
44
  export type StartOpts = {
49
- /** parent dir for repos — default ~/dev */
45
+ /** parent dir for repos — default the house's own folder, ~/dev with no house */
50
46
  root?: string
51
- /** lines CLAUDE.md must carry, in order; omitted = HOUSE_INCLUDE. An empty list means no house: only the agent route lands */
47
+ /** lines CLAUDE.md must carry, in order; omitted = the house of this machine, then the agent route. An empty list means no house: only the agent route lands */
52
48
  include?: string[]
53
49
  /** alternative lines that satisfy the FIRST include — never double-add; omitted = HOUSE_ALSO_OK */
54
50
  alsoOk?: string[]
@@ -74,20 +70,21 @@ export async function startRepo(name: string, opts: StartOpts = {}): Promise<num
74
70
  return 2
75
71
  }
76
72
  const home = opts.home ?? homedir()
77
- const dir = join(opts.root ?? join(home, 'dev'), name)
73
+ const found = thisHouse({ home, ...(opts.root != null ? { root: opts.root } : {}) })
74
+ const root = opts.root ?? reposRoot(found, home)
75
+ const dir = join(root, name)
78
76
  const justCreated = !existsSync(dir)
79
77
  if (justCreated) {
80
78
  mkdirSync(dir, { recursive: true })
81
79
  console.error(`ok: created ${dir}`)
82
80
  }
83
- // flags win, else the house, and only on a machine that HAS the house:
84
- // this lib is on npm, so elsewhere the template would be an include
81
+ // flags win, else the house, and only on a machine that HAS one:
82
+ // elsewhere the template would be an include
85
83
  // pointing at nothing plus the widened agent permissions riding on it
86
- const houseOnDisk = existsSync(housePath(home))
87
- const house = opts.include ?? (houseOnDisk ? HOUSE_INCLUDE : [])
88
- if (opts.include == null && !houseOnDisk) console.error(`skip: no house wiki at ${housePath(home)} — CLAUDE.md gets the agent route only, and no .claude/ policy files`)
84
+ const house = opts.include ?? (found != null ? houseInclude(found, home) : [])
85
+ if (opts.include == null && found == null) console.error('skip: no house on this machine (`sk setup` makes one): CLAUDE.md gets the agent route only, and no .claude/ policy files')
89
86
  const alt = opts.alsoOk ?? HOUSE_ALSO_OK
90
- const skipped = isSkipped(name, opts.skip ?? (houseOnDisk ? await houseSkip(home) : []))
87
+ const skipped = isSkipped(name, opts.skip ?? (found != null ? await houseSkip(home, root) : []))
91
88
  if (skipped && house.length > 0) console.error(`skip: ${name} is include-exempt — CLAUDE.md untouched`)
92
89
  // start is the from-anywhere verb, and a STARTED repo comes out READY:
93
90
  // any dir with no commit history gets a minimal package.json, a first
@@ -156,7 +153,7 @@ export async function startRepo(name: string, opts: StartOpts = {}): Promise<num
156
153
  // installed lib carries the kit its entry imports
157
154
  const kit = kitInstalled(installedLib(dir))
158
155
  if (kit === false) console.error(`skip: project CLI — the installed rvlib-shipkit ${installedLib(dir)?.version ?? ''} predates the CLI kit: \`sk start ${name} --cli\` once a release carries it`)
159
- try { scaffoldProject(dir, { name, port: defaultHubPort(name), print, claudePolicy: house.length > 0, projectCli: kit !== false }) }
156
+ try { scaffoldProject(dir, { name, port: defaultHubPort(name), print, claudePolicy: writesPolicy({ include: opts.include, house: found }), projectCli: kit !== false }) }
160
157
  catch (e) { console.error(`WARN scaffold incomplete in ${dir}: ${e instanceof Error ? e.message : String(e)} — the dir is still yours`) }
161
158
  await linkBin(dir, bun)
162
159
  }
@@ -173,7 +170,7 @@ export async function startRepo(name: string, opts: StartOpts = {}): Promise<num
173
170
  if (cliWritten) await linkBin(dir, bun)
174
171
  }
175
172
  if (wired && !startable && house.length > 0) {
176
- try { adoptHouse(dir, { name, print, cli: cliWritten }) }
173
+ try { adoptHouse(dir, { name, print, cli: cliWritten, claudePolicy: writesPolicy({ include: opts.include, house: found }) }) }
177
174
  catch (e) { console.error(`WARN could not seed the house files in ${dir}: ${e instanceof Error ? e.message : String(e)} — the dir is still yours`) }
178
175
  }
179
176
  let unscaffolded = false