rvlib-shipkit 2.23.0 → 2.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/package.json +1 -1
  3. package/src/agent-time/render.ts +28 -14
  4. package/src/agent-time/report.ts +46 -25
  5. package/src/agent-time/store.ts +30 -10
  6. package/src/agent-time/timeline.ts +43 -15
  7. package/src/asks/asks-queue.ts +32 -11
  8. package/src/checks/SK044-behind-upstream.check.ts +38 -0
  9. package/src/cli/cmd_Asks.ts +2 -0
  10. package/src/cli/cmd_Backup.ts +7 -5
  11. package/src/cli/cmd_Bump.ts +1 -0
  12. package/src/cli/cmd_Capacity.ts +26 -0
  13. package/src/cli/cmd_Check.ts +1 -0
  14. package/src/cli/cmd_Checks.ts +1 -0
  15. package/src/cli/cmd_Ci.ts +1 -0
  16. package/src/cli/cmd_Commands.ts +50 -14
  17. package/src/cli/cmd_Home.ts +0 -29
  18. package/src/cli/cmd_Hooks.ts +1 -0
  19. package/src/cli/cmd_Mv.ts +1 -0
  20. package/src/cli/cmd_Reflect.ts +1 -0
  21. package/src/cli/cmd_Releases.ts +1 -0
  22. package/src/cli/cmd_Review.ts +97 -14
  23. package/src/cli/cmd_Secret.ts +41 -2
  24. package/src/cli/cmd_Shot.ts +1 -0
  25. package/src/cli/cmd_Status.ts +1 -0
  26. package/src/cli/cmd_Time.ts +3 -1
  27. package/src/cli/cmd_Tmp.ts +82 -0
  28. package/src/cli/cmd_Wiki.ts +1 -0
  29. package/src/cli/registry.ts +13 -1
  30. package/src/collections/pings.ts +1 -1
  31. package/src/core/capacity.ts +71 -0
  32. package/src/core/check-runner.ts +86 -15
  33. package/src/core/motherhome.ts +67 -9
  34. package/src/core/slots.ts +49 -12
  35. package/src/core/trace-audit.ts +4 -1
  36. package/src/drill/run.ts +5 -2
  37. package/src/home/gui-app/ShipkitGui.swift +1 -0
  38. package/src/home/home-launchd.ts +11 -3
  39. package/src/home/home-routes.ts +11 -4
  40. package/src/home/machine-host.ts +65 -0
  41. package/src/home/machine-stores.ts +19 -17
  42. package/src/home/machine-temp.ts +493 -0
  43. package/src/home/other-macs.ts +74 -0
  44. package/src/home/run-daemon.ts +10 -2
  45. package/src/home/serve-web.ts +2 -2
  46. package/src/home/via-hub.ts +6 -1
  47. package/src/init-repo.ts +7 -3
  48. package/src/ledger/ledger.ts +6 -0
  49. package/src/ledger/store.ts +6 -0
  50. package/src/media-store/backup/keys.ts +21 -6
  51. package/src/media-store/backup/manifest.ts +52 -11
  52. package/src/media-store/backup/restore.ts +17 -10
  53. package/src/media-store/backup/run.ts +5 -2
  54. package/src/media-store/backup/sources.ts +2 -1
  55. package/src/mv/mv-md.ts +121 -42
  56. package/src/reflect/transcript.ts +56 -11
  57. package/src/releases/from-card.ts +45 -3
  58. package/src/releases/model.ts +6 -0
  59. package/src/releases/store.ts +8 -1
  60. package/src/repo-config.ts +5 -3
  61. package/src/review/cells.ts +24 -3
  62. package/src/review/format.ts +33 -9
  63. package/src/review/media-kind.ts +14 -11
  64. package/src/review/media-read.ts +6 -5
  65. package/src/review/model.ts +71 -3
  66. package/src/review/paste.ts +2 -1
  67. package/src/review/previews.ts +123 -36
  68. package/src/review/routes.ts +29 -18
  69. package/src/review/store.ts +74 -12
  70. package/src/review/threads.ts +7 -5
  71. package/src/secrets/copy.ts +110 -0
  72. package/src/secrets/list.ts +17 -7
  73. package/src/serve/hub-app/home-strip.css +5 -0
  74. package/src/serve/hub-app/home-strip.tsx +18 -0
  75. package/src/serve/hub-app/hub-app.tsx +2 -1
  76. package/src/serve/hub-app/hub.css +14 -0
  77. package/src/serve/hub-app/inbox.css +1 -0
  78. package/src/serve/hub-app/pull-refresh.tsx +88 -0
  79. package/src/serve/hub-app/review/review-cells.tsx +52 -13
  80. package/src/serve/hub-app/review/review-list.tsx +6 -1
  81. package/src/serve/hub-app/review/review-st.ts +6 -5
  82. package/src/serve/hub-app/review/review-thread.tsx +3 -1
  83. package/src/serve/hub-app/review/review-views.tsx +18 -11
  84. package/src/serve/hub-app/review/thread-st.ts +82 -14
  85. package/src/serve/hub-app/review.css +15 -2
  86. package/src/serve/hub-runtime.ts +2 -1
  87. package/src/serve/run-serve.ts +4 -2
  88. package/src/serve/serve-hub.ts +9 -2
  89. package/src/suite/child-tools.ts +45 -0
  90. package/src/suite/judge-suites.ts +10 -22
  91. package/src/suite/select.ts +83 -8
  92. package/src/suite/suite-cli.ts +38 -14
  93. package/src/suite/suite-cores.ts +68 -0
  94. package/src/suite/suite-reads-preload.ts +8 -6
  95. package/src/ts/config.ts +44 -0
  96. package/src/ts/rename.ts +11 -1
  97. package/src/home/claude-temp.ts +0 -139
@@ -29,6 +29,8 @@ import { machineCatchUp } from '../plan/catch-up.ts'
29
29
  import { serveDaemon } from './serve-daemon.ts'
30
30
  import { startJobs } from './daemon-jobs.ts'
31
31
  import { Widgets } from './widgets.ts'
32
+ import { machinePublicHost } from './machine-host.ts'
33
+ import { OtherMacs } from './other-macs.ts'
32
34
 
33
35
  const CLI = fileURLToPath(new URL('../cli.ts', import.meta.url))
34
36
 
@@ -72,7 +74,9 @@ export async function runDaemon(root: string, io: HomeIo, o: { port?: number } =
72
74
  const reclaimed = reclaimPreviousImage()
73
75
  if (reclaimed.killed.length > 0) io.print(`ok: the daemon restarted in place: killed ${reclaimed.killed.length} check process(es) its previous image left running`)
74
76
  const c = await loadRepoConfig(root)
75
- const publicHost = c.serve?.publicHost
77
+ // asked again on each use: a Mac whose tailscale was down at boot gains its name once it answers
78
+ const publicHost = (): string | null => machinePublicHost(c)
79
+ const otherMacs = new OtherMacs()
76
80
  const dir = homeDir()
77
81
  // the machine's one plan: every repo and check pair, ticked by the daemon.
78
82
  // Its catch up window lives in the machine db, so a restart in place keeps it
@@ -102,7 +106,10 @@ export async function runDaemon(root: string, io: HomeIo, o: { port?: number } =
102
106
  // every gate is a detached job: a reload of this process never kills one
103
107
  jobs: { cli: CLI },
104
108
  // a ping opens the inbox on its item, or on the list for several
105
- link: (fresh) => (publicHost == null ? undefined : `${publicHome(publicHost)}${fresh.length === 1 ? inboxAddress(repo.name, fresh[0]!.id) : '/inbox'}`),
109
+ link: (fresh) => {
110
+ const host = publicHost()
111
+ return host == null ? undefined : `${publicHome(host)}${fresh.length === 1 ? inboxAddress(repo.name, fresh[0]!.id) : '/inbox'}`
112
+ },
106
113
  })
107
114
  hubIo.print(`${rt.name} hub → http://localhost:${port}${hubBase(repo.name)}/`)
108
115
  return { ...rt, uses: rt.deps.uses ?? [] }
@@ -122,6 +129,7 @@ export async function runDaemon(root: string, io: HomeIo, o: { port?: number } =
122
129
  only: onlyRepos(),
123
130
  widgets: new Widgets(),
124
131
  publicHost,
132
+ otherMacs: () => otherMacs.get(),
125
133
  })
126
134
  io.print(`daemon → http://127.0.0.1:${home.server.port} (the page: http://localhost:${port})`)
127
135
  // the retention sweep (nothing grows unbound, core/retention.ts), the media store and the backup of the
@@ -9,7 +9,7 @@
9
9
  // origin header. The daemon's own guard then refuses any page that calls its
10
10
  // port directly, and lets this door through. The host guard runs here too: Bun's dev server, which bundles the page
11
11
  // and drives its hot reload, answers only to a loopback Host, so it sits on a port of its own behind this one, and a
12
- // request reaches it only once its Host is a loopback name or the tailnet name the house declares (serve.publicHost)
12
+ // request reaches it only once its Host is a loopback name or this Mac's tailnet name (machine-host.ts)
13
13
  import { hostName, loopbackName, REACH_HEADER, reachOfHost, sameOrigin } from '../serve/same-origin.ts'
14
14
  import { hubBase } from './home-paths.ts'
15
15
  import { forwardPage, pagePath } from '../pages/forward.ts'
@@ -75,7 +75,7 @@ export function hostAllowed(host: string | null, names: ReadonlySet<string>): bo
75
75
  }
76
76
 
77
77
  export const hostRefusedText = (host: string | null): string =>
78
- `refused: the home answers to localhost and to the tailnet name the house declares (serve.publicHost), never to ${host == null || host === '' ? 'a request with no Host' : host}`
78
+ `refused: the home answers to localhost and to this Mac's tailnet name, never to ${host == null || host === '' ? 'a request with no Host' : host}`
79
79
 
80
80
  /** the page's colours behind the app on a phone, the --bg tokens of hub.css */
81
81
  const THEME = { dark: '#0d0e10', light: '#f6f7f9' } as const
@@ -66,7 +66,7 @@ export async function runViaHub(root: string, kind: 'ci' | 'check', opts: Record
66
66
  ...(Object.keys(env).length > 0 ? { env } : {}),
67
67
  }
68
68
  // the home waits for a hub still loading before it answers
69
- const post = (): Promise<Response> => fetch(`${daemonUrl()}${hubBase(name)}/api/run`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ kind, opts: sent }) })
69
+ const post = (): Promise<Response> => fetch(`${daemonUrl()}${hubBase(name)}/api/run`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ kind, opts: sent, root: homeRepo(root) }) })
70
70
  return followRun({ name, jobRoot: homeRepo(root), post, up: () => daemonUp(), io })
71
71
  }
72
72
 
@@ -100,6 +100,11 @@ export async function followRun(o: {
100
100
  if (r != null) {
101
101
  // not one of the home's repos: nothing to send it to
102
102
  if (r.status === 404) return null
103
+ // the home's repo of this name is another tree (a clone elsewhere)
104
+ if (r.status === 421) {
105
+ io.printErr(`note: ${await r.text()}, so this gate runs in process`)
106
+ return null
107
+ }
103
108
  if (r.status === 409) {
104
109
  io.printErr(`note: the home could not load ${name}'s hub (${await r.text()}), so this gate runs in process`)
105
110
  return null
package/src/init-repo.ts CHANGED
@@ -17,6 +17,7 @@ import { reportToMotherhome } from './core/motherhome.ts'
17
17
  import { ensureGitRepo, publishRepo, type Run } from './git-bootstrap.ts'
18
18
  import { defineRepo, loadRepoConfig, resolveFloor } from './repo-config.ts'
19
19
  import { gitignorePolicy } from './checks/SK004-gitignore-policy.check.ts'
20
+ import { armHooks } from './hooks/run-hooks.ts'
20
21
 
21
22
  // This lands as SOURCE in the repo being wired, so its comments answer to that
22
23
  // repo's comment style, not to this file's. Dash punctuation is banned there
@@ -177,13 +178,16 @@ export async function initRepo(root: string, opts: InitOpts = {}): Promise<numbe
177
178
 
178
179
  /** ONE WAY IN, both halves, through the SAME fixers `shipkit check --fix` runs
179
180
  * (tools/shipkit/one-way-in.md). Nothing here is a second implementation: rule SK001
180
- * routes the package.json scripts, rule SK013 writes the harness policy, and
181
- * init just calls them so a wired repo is born enforced and a re-run repairs
182
- * one that was not. The deny is a RESTRICTION, which is why it lands
181
+ * routes the package.json scripts, rule SK013 writes the harness policy, the
182
+ * gate's own arming wires the commit hooks, and init just calls them so a
183
+ * wired repo is born enforced (its first commit is gated) and a re-run
184
+ * repairs one that was not. The deny is a RESTRICTION, which is why it lands
183
185
  * unconditionally where the scaffold's allow list stays opt in. */
184
186
  async function repairOneWayIn(root: string, config: Parameters<typeof defineRepo>[0], p: (line: string) => void): Promise<void> {
185
187
  const pkg = await packageJsonShape.repair!(CheckCtx.open({ root, config }))
186
188
  if (pkg.changed) p(`ok: package.json — ${pkg.summary}`)
187
189
  const policy = await oneWayInPolicy.repair!(CheckCtx.open({ root, config }))
188
190
  p(policy.changed ? `ok: ${policy.summary}` : `ok: .claude/settings.json already closes every raw runner`)
191
+ const hooks = armHooks(root, config)
192
+ p(hooks.state === 'armed' || hooks.state === 'current' ? `ok: commit gates ${hooks.state}, ${hooks.detail}` : `WARN commit gates not armed: ${hooks.detail}`)
189
193
  }
@@ -209,6 +209,12 @@ export class Ledger {
209
209
  return { ...e.payload, at: e.at }
210
210
  }
211
211
 
212
+ /** what this check's newest kept runs took, newest first, empty when none is kept. A scheduling hint only: no
213
+ * verdict reads it */
214
+ lastRuns(id: string): number[] {
215
+ return this.answers.lastRuns(NS, id)
216
+ }
217
+
212
218
  /** the stored read set of a READS check, as the last store wrote it */
213
219
  storedReads(id: string): ReadSet | null {
214
220
  const k = this.key(id)
@@ -193,6 +193,12 @@ export class Answers {
193
193
  return this.with(READ_BUSY_MS, (h) => h.query("select name, at, json_extract(payload, '$.measuredMs') as ms, json_extract(payload, '$.status') as status from answers where ns = ? and json_valid(payload)").all(ns) as { name: string; at: number; ms: unknown; status: unknown }[]) ?? []
194
194
  }
195
195
 
196
+ /** what the newest kept answers of one check took to measure, newest first: how a runner tells a short check from a long one */
197
+ lastRuns(ns: string, name: string, limit = 3): number[] {
198
+ const rows = this.with(READ_BUSY_MS, (h) => h.query("select case when json_valid(payload) then json_extract(payload, '$.measuredMs') end as ms from (select payload from answers where ns = ? and name = ? order by at desc limit ?)").all(ns, name, limit) as { ms: unknown }[]) ?? []
199
+ return rows.map((r) => Number(r.ms)).filter((ms) => Number.isFinite(ms) && ms >= 0)
200
+ }
201
+
196
202
  /** a cheap fingerprint of one population, so a reader can cache on it */
197
203
  stamp(ns: string): string {
198
204
  const r = this.with(READ_BUSY_MS, (h) => h.query('select count(*) as n, max(at) as last from answers where ns = ?').get(ns) as { n: number; last: number | null } | null)
@@ -1,20 +1,35 @@
1
1
  // where the backup keeps its objects in the private Space (wiki tools/shipkit/media-store.md, Backup): a file's bytes
2
2
  // under `backup/<sha256>.<ext>`, a sqlite snapshot gzipped under `backup/<sha256 of the gz>.gz`, one manifest a run
3
- // under `backup/runs/<time>-<digest>.json.gz`. Nothing under the prefix is ever deleted
3
+ // under `backup/runs/<time>-<machine>-<digest>.json.gz` (two Macs back up into one Space; a run from before the name is
4
+ // `<time>-<digest>` and names its host only inside). Nothing under the prefix is ever deleted
4
5
  export const BACKUP_LABEL = 'backup'
5
6
  export const RUNS_PREFIX = `${BACKUP_LABEL}/runs/`
6
7
 
7
8
  /** a time as the run keys write it: `20261104T135000Z`, sorted as text */
8
9
  export const stampOf = (d: Date): string => d.toISOString().replace(/\.\d{3}Z$/, 'Z').replace(/[-:]/g, '')
9
10
 
10
- export const runKey = (at: Date, digest: string): string => `${RUNS_PREFIX}${stampOf(at)}-${digest.slice(0, 12)}.json.gz`
11
+ /** a machine name as a key holds it: letters, digits and dashes */
12
+ const cleaned = (machine: string): string => machine.replace(/[^A-Za-z0-9-]+/g, '-').replace(/^-+|-+$/g, '')
13
+ const keyName = (machine: string): string => {
14
+ const name = cleaned(machine)
15
+ if (name === '') throw new Error(`a machine name with no letter or digit cannot key a backup run: ${JSON.stringify(machine)}`)
16
+ return name
17
+ }
11
18
 
12
- /** the time a run key names, null for a key that is no run */
13
- export function timeOfRun(key: string): Date | null {
14
- const m = /^backup\/runs\/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z-[0-9a-f]{12}\.json\.gz$/.exec(key)
15
- return m ? new Date(`${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}Z`) : null
19
+ export const runKey = (at: Date, digest: string, machine: string): string => `${RUNS_PREFIX}${stampOf(at)}-${keyName(machine)}-${digest.slice(0, 12)}.json.gz`
20
+
21
+ /** the time and machine a run key names (machine null for a run from before the name), null for a key that is no run */
22
+ export function ofRunKey(key: string): { at: Date; machine: string | null } | null {
23
+ const m = /^backup\/runs\/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z-(?:([A-Za-z0-9-]+)-)?[0-9a-f]{12}\.json\.gz$/.exec(key)
24
+ return m ? { at: new Date(`${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}Z`), machine: m[7] ?? null } : null
16
25
  }
17
26
 
27
+ /** the time a run key names, null for a key that is no run */
28
+ export const timeOfRun = (key: string): Date | null => ofRunKey(key)?.at ?? null
29
+
30
+ /** do two machine names name one Mac: as a key writes them, case aside */
31
+ export const sameMachine = (a: string, b: string): boolean => cleaned(a) !== '' && cleaned(a).toLowerCase() === cleaned(b).toLowerCase()
32
+
18
33
  /** a time a person types: ISO (`2026-11-04T13:50`, `2026-11-04`) or a run stamp (`20261104T135000Z`) */
19
34
  export function parseAt(text: string): Date {
20
35
  const t = text.trim()
@@ -3,10 +3,13 @@
3
3
  // its files in PARTS, one a group (the home, the memories, a house repo; a big group cut in buckets by folder), each
4
4
  // part content addressed: a run that changes one file writes that file's part and the run's list of parts. A run of
5
5
  // version 1 holds every file in one object, still read. A restore reads only this and the keys
6
- import { rmSync } from 'node:fs'
6
+ import { mkdtempSync, rmSync } from 'node:fs'
7
+ import { tmpdir } from 'node:os'
7
8
  import { gunzipSync, gzipSync } from 'node:zlib'
8
9
  import { dirname, join } from 'node:path'
9
- import { BACKUP_LABEL, RUNS_PREFIX, timeOfRun } from './keys.ts'
10
+ import { BACKUP_LABEL, ofRunKey, RUNS_PREFIX, sameMachine } from './keys.ts'
11
+ import { hostLabel } from '../../home/machine-host.ts'
12
+ import { machineGet, machineSet } from '../../core/machine-db.ts'
10
13
  import type { Space } from '../space.ts'
11
14
  import type { SqliteCut } from './snapshot.ts'
12
15
 
@@ -129,19 +132,57 @@ export function encodeRun(m: Omit<Manifest, 'v'>, repos: readonly string[]): { r
129
132
  export const encodeManifestV1 = (m: Omit<Manifest, 'v'>): Uint8Array => gz(JSON.stringify({ ...m, v: 1 }))
130
133
 
131
134
  /** every run the Space holds, oldest first */
132
- export async function runsOf(space: Space): Promise<{ key: string; at: Date; size: number }[]> {
135
+ export type RunRef = { key: string; at: Date; size: number; machine: string | null }
136
+
137
+ export async function runsOf(space: Space): Promise<RunRef[]> {
133
138
  return (await space.list(RUNS_PREFIX))
134
139
  .flatMap((o) => {
135
- const at = timeOfRun(o.key)
136
- return at ? [{ key: o.key, at, size: o.size }] : []
140
+ const r = ofRunKey(o.key)
141
+ return r ? [{ key: o.key, at: r.at, size: o.size, machine: r.machine }] : []
137
142
  })
138
143
  .sort((a, b) => a.at.getTime() - b.at.getTime() || (a.key < b.key ? -1 : 1))
139
144
  }
140
145
 
141
- /** the last run at or before `at` (the last run when none is given), null when the Space holds none */
142
- export async function runAt(space: Space, at?: Date): Promise<{ key: string; at: Date } | null> {
143
- const runs = (await runsOf(space)).filter((r) => !at || r.at.getTime() <= at.getTime())
144
- return runs[runs.length - 1] ?? null
146
+ /** the last run of `machine` at or before `at` (the last one when no time is given), null when the Space holds none.
147
+ * A run from before the name in the key is read for its host, newest first, only while no named run answered */
148
+ export async function runAt(space: Space, at: Date | undefined, machine: string, o: { namedOnly?: boolean } = {}): Promise<{ key: string; at: Date } | null> {
149
+ const runs = (await runsOf(space)).filter((r) => (!at || r.at.getTime() <= at.getTime()) && (!o.namedOnly || r.machine != null)).reverse()
150
+ const tmp = mkdtempSync(join(tmpdir(), 'shipkit-runs-'))
151
+ try {
152
+ for (const r of runs) {
153
+ const host = r.machine ?? (await hostOfOldRun(space, r.key, tmp))
154
+ if (host != null && sameMachine(host, machine)) return { key: r.key, at: r.at }
155
+ }
156
+ return null
157
+ } finally {
158
+ rmSync(tmp, { recursive: true, force: true })
159
+ }
160
+ }
161
+
162
+ /** the host inside a run whose key names none, kept in the machine db: a run key never changes, so its head is read
163
+ * once (the Space held 938 such runs when the name entered the key) */
164
+ async function hostOfOldRun(space: Space, key: string, tmp: string): Promise<string | null> {
165
+ const held = machineGet<string>(`backup-run-host:${key}`)
166
+ if (held != null) return held === '' ? null : held
167
+ const host = (await readRunHead(space, key, join(tmp, 'head.json.gz'))).host
168
+ const name = host == null ? null : hostLabel(host)
169
+ machineSet(`backup-run-host:${key}`, name ?? '')
170
+ return name
171
+ }
172
+
173
+ /** the machines the runs name, those from before the name read for their host */
174
+ export async function machinesOf(space: Space): Promise<string[]> {
175
+ const tmp = mkdtempSync(join(tmpdir(), 'shipkit-runs-'))
176
+ try {
177
+ const names = new Set<string>()
178
+ for (const r of await runsOf(space)) {
179
+ const host = r.machine ?? (await hostOfOldRun(space, r.key, tmp))
180
+ if (host != null) names.add(host)
181
+ }
182
+ return [...names].sort()
183
+ } finally {
184
+ rmSync(tmp, { recursive: true, force: true })
185
+ }
145
186
  }
146
187
 
147
188
  async function getJson<T>(space: Space, key: string, tmp: string): Promise<{ json: string; value: T }> {
@@ -167,8 +208,8 @@ async function readPart(space: Space, ref: PartRef, tmp: string): Promise<Entry[
167
208
  }
168
209
 
169
210
  /** the top of a run, without its parts: its digest and time */
170
- export async function readRunHead(space: Space, key: string, tmp: string): Promise<{ v: number; digest: string; at: string; parts?: PartRef[] }> {
171
- const { value: m } = await getJson<{ v: number; digest: string; at: string; parts?: PartRef[] }>(space, key, tmp)
211
+ export async function readRunHead(space: Space, key: string, tmp: string): Promise<{ v: number; digest: string; at: string; host?: string; parts?: PartRef[] }> {
212
+ const { value: m } = await getJson<{ v: number; digest: string; at: string; host?: string; parts?: PartRef[] }>(space, key, tmp)
172
213
  if (m.v !== 1 && m.v !== 2) throw new Error(`${key}: no backup run of version 1 or 2`)
173
214
  return m
174
215
  }
@@ -9,8 +9,9 @@ import { dirname, join, resolve } from 'node:path'
9
9
  import { gunzipSync } from 'node:zlib'
10
10
  import { shaOf } from '../content.ts'
11
11
  import type { Space } from '../space.ts'
12
- import { stampOf } from './keys.ts'
13
- import { readManifest, runAt, type Entry, type Manifest } from './manifest.ts'
12
+ import { sameMachine, stampOf } from './keys.ts'
13
+ import { machinesOf, readManifest, runAt, type Entry, type Manifest } from './manifest.ts'
14
+ import { machineName } from '../../home/machine-host.ts'
14
15
  import { rowsOf } from './snapshot.ts'
15
16
 
16
17
  export interface RestoreResult {
@@ -69,22 +70,28 @@ export interface RestoreOptions {
69
70
  to?: string
70
71
  inPlace?: boolean
71
72
  at?: Date
73
+ /** the Mac whose runs are read, this one when absent */
74
+ machine?: string
72
75
  /** only the paths under this prefix */
73
76
  only?: string
74
77
  }
75
78
 
76
- /** the run a restore or a drill reads: the last at or before `at` */
77
- async function runFor(space: Space, at?: Date): Promise<{ key: string; at: Date }> {
78
- const run = await runAt(space, at)
79
- if (!run) throw new Error(at ? `no backup run at or before ${at.toISOString()}` : 'the Space holds no backup run yet: sk backup')
80
- return run
79
+ /** the run a restore or a drill reads: the machine's last at or before `at`. Another Mac's run names files under that
80
+ * Mac's home, so it is read only when `machine` names it */
81
+ async function runFor(space: Space, at: Date | undefined, machine: string): Promise<{ key: string; at: Date }> {
82
+ const run = await runAt(space, at, machine)
83
+ if (run) return run
84
+ const others = (await machinesOf(space)).filter((m) => !sameMachine(m, machine))
85
+ const when = at ? ` at or before ${at.toISOString()}` : ''
86
+ if (others.length > 0) throw new Error(`no backup run of ${machine}${when}; the Space holds runs of ${others.join(', ')}: --host <machine> reads one of them`)
87
+ throw new Error(at ? `no backup run at or before ${at.toISOString()}` : 'the Space holds no backup run yet: sk backup')
81
88
  }
82
89
 
83
90
  export async function restore(space: Space, o: RestoreOptions): Promise<RestoreResult & { manifest: Manifest }> {
84
91
  if ((o.inPlace === true) === (o.to !== undefined)) throw new Error('a restore goes --to <dir> (a folder that is empty or new) or --in-place, one of the two')
85
92
  const to = o.to === undefined ? null : resolve(o.to)
86
93
  if (to && existsSync(to) && readdirSync(to).length > 0) throw new Error(`${to} is not empty: a restore writes into an empty or new folder, never over files`)
87
- const run = await runFor(space, o.at)
94
+ const run = await runFor(space, o.at, o.machine ?? machineName())
88
95
  const scratch = mkdtempSync(join(tmpdir(), 'shipkit-restore-'))
89
96
  const stamp = stampOf(new Date())
90
97
  const aside = join(o.home, '.shipkit', 'backup-replaced', stamp)
@@ -158,10 +165,10 @@ export interface DrillResult {
158
165
 
159
166
  /** a run (the last, or the last at or before `at`) restored into a scratch folder (or `to`), every sha read again and
160
167
  * compared to the live files */
161
- export async function drill(space: Space, o: { home: string; to?: string; keep?: boolean; at?: Date }): Promise<DrillResult & { v: number }> {
168
+ export async function drill(space: Space, o: { home: string; to?: string; keep?: boolean; at?: Date; machine?: string }): Promise<DrillResult & { v: number }> {
162
169
  const dir = o.to ? resolve(o.to) : mkdtempSync(join(tmpdir(), 'shipkit-drill-'))
163
170
  try {
164
- const r = await restore(space, { home: o.home, to: dir, ...(o.at ? { at: o.at } : {}) })
171
+ const r = await restore(space, { home: o.home, to: dir, ...(o.at ? { at: o.at } : {}), ...(o.machine ? { machine: o.machine } : {}) })
165
172
  const out: DrillResult & { v: number } = { v: r.manifest.v, run: r.run, at: r.at, files: r.files, bytes: r.bytes, restored: 0, sameAsLive: 0, liveMoved: [], liveGone: [], sqlite: [], failed: [...r.failed], dir }
166
173
  const bad = new Set(r.failed.map((f) => f.path))
167
174
  for (const e of r.manifest.files) {
@@ -18,6 +18,7 @@ import { digestOf, encodeRun, readManifest, readRunHead, runAt, type Entry, type
18
18
  import { fileRefusal, refusal } from './secret.ts'
19
19
  import { snapshotSqlite } from './snapshot.ts'
20
20
  import { collect, type Collect, type Source } from './sources.ts'
21
+ import { machineName } from '../../home/machine-host.ts'
21
22
 
22
23
  const LAST = 'backup-last'
23
24
  /** the files named whole, by path: their size, time, sha and key, so an unchanged archive is never read again */
@@ -168,7 +169,9 @@ async function sendAll(space: Space, ready: readonly Ready[], scratch: string, j
168
169
  async function lastOf(space: Space, scratch: string): Promise<Last | null> {
169
170
  const held = lastRun()
170
171
  if (held) return held
171
- const run = await runAt(space)
172
+ // only a run whose key names this Mac: the last run only spares an identical one, so a Mac that never named its
173
+ // runs sends one in full instead of reading every old run for its host
174
+ const run = await runAt(space, undefined, machineName(), { namedOnly: true })
172
175
  if (!run) return null
173
176
  const m = await readRunHead(space, run.key, join(scratch, 'last.json.gz'))
174
177
  return { key: run.key, digest: m.digest, at: m.at }
@@ -235,7 +238,7 @@ export async function backupRun(space: Space, o: Collect & { now?: Date; jobs?:
235
238
  }
236
239
  }
237
240
  if (out.failed.length > 0) return out
238
- const key = runKey(now, digest)
241
+ const key = runKey(now, digest, machineName())
239
242
  await sendOne(space, key, enc.run.length, { bytes: enc.run }, scratch, -1 - enc.parts.length)
240
243
  out.record.runBytes = enc.run.length
241
244
  machineSet(LAST, { key, digest, at: now.toISOString() } satisfies Last)
@@ -126,7 +126,8 @@ export async function collect(o: Collect): Promise<Source[]> {
126
126
  // the backup's own objects and records, and the pids, move by themselves: left out, else every run differs
127
127
  const sqlite = new Map<string, SqliteCut>([
128
128
  [mediaDbPath(), { tables: ['files', 'objects'], except: { objects: "key like 'backup/%'" } }],
129
- [machineDbPath(), { tables: null, except: { state: "name like 'pid:%' or name like 'backup-%'" } }],
129
+ // the Mac's own names stay out: a run restored on another Mac must not make it take this one's name
130
+ [machineDbPath(), { tables: null, except: { state: "name like 'pid:%' or name like 'backup-%' or name in ('machine-name', 'tailnet-name')" } }],
130
131
  ])
131
132
  await walk(join(homeDir(), 'veille'), () => true, files)
132
133
  add(join(o.home, ORDER_FILE))
package/src/mv/mv-md.ts CHANGED
@@ -55,7 +55,14 @@ const REF_FORMS: { re: RegExp; group: number }[] = [
55
55
  /** rewrite every relative reference in one file so it still points at the same
56
56
  * thing after the move. `moves` is every path this operation relocates; a ref
57
57
  * that names none of them still moves when the FILE moved under it. */
58
- export function retargetRelativeRefs(root: string, text: string, fromDir: string, toDir: string, moves: Map<string, string>): string {
58
+ export function retargetRelativeRefs(
59
+ root: string,
60
+ text: string,
61
+ fromDir: string,
62
+ toDir: string,
63
+ moves: Map<string, string>,
64
+ isFileAt: (rel: string) => boolean = (rel) => isFile(join(root, rel)),
65
+ ): string {
59
66
  const fix = (target: string): string | null => {
60
67
  // a url, an absolute path and a bare anchor are not ours to resolve
61
68
  if (target === '' || /^[a-z][a-z0-9+.-]*:/i.test(target) || target.startsWith('/') || target.startsWith('#')) return null
@@ -71,7 +78,7 @@ export function retargetRelativeRefs(root: string, text: string, fromDir: string
71
78
  // nothing moved for this reference: neither its target nor its carrier
72
79
  if (to == null && fromDir === toDir) return null
73
80
  // a target that is not a real FILE is prose, not a link
74
- if (to == null && !isFile(join(root, from))) return null
81
+ if (to == null && !isFileAt(from)) return null
75
82
  const next = posix(relative(toDir, to ?? from))
76
83
  if (next === '') return null
77
84
  return `${path.startsWith('./') && !next.startsWith('.') ? `./${next}` : next}${anchor}`
@@ -91,11 +98,79 @@ export function retargetRelativeRefs(root: string, text: string, fromDir: string
91
98
  return out
92
99
  }
93
100
 
94
- export function movePage(root: string, oldRel: string, newRel: string, io: MvIo, o: MvOpts = {}): number {
101
+ /** where a move reads and writes. Applied, it is the disk and git; a dry run is
102
+ * an overlay on them, so the dry run walks the very same steps, and a map's
103
+ * next line sees what the line before it moved */
104
+ class MvTree {
105
+ private readonly text = new Map<string, string>()
106
+ private readonly gone = new Set<string>()
107
+ private list: string[] | null = null
108
+ constructor(readonly root: string, readonly live: boolean) {}
109
+
110
+ private real = (rel: string): string => join(this.root, rel)
111
+ private isGone = (rel: string): boolean => [...this.gone].some((g) => rel === g || rel.startsWith(`${g}/`))
112
+ /** the files the sweep reads: tracked, never a binary, and third party
113
+ * code keeps its own references byte for byte */
114
+ files(): string[] {
115
+ if (this.live || this.list == null) {
116
+ const repo = vendoredAround(this.root)
117
+ const vendored = (repo?.dirs ?? []).map((d) => posix(relative(this.root, join(repo!.root, d))))
118
+ this.list = sh('git ls-files', this.root).split('\n').filter(Boolean)
119
+ .filter((f) => !/\.(png|jpe?g|gif|webp|ico|woff2?|ttf|zip|gz|lockb|lock)$/i.test(f) && !isVendored(f, vendored))
120
+ }
121
+ return this.list
122
+ }
123
+ isFile = (rel: string): boolean => this.text.has(rel) || (!this.isGone(rel) && isFile(this.real(rel)))
124
+ exists = (rel: string): boolean =>
125
+ this.isFile(rel) || (!this.live && this.files().some((f) => f.startsWith(`${rel}/`))) || (!this.isGone(rel) && existsSync(this.real(rel)))
126
+ read = (rel: string): string => this.text.get(rel) ?? readFileSync(this.real(rel), 'utf8')
127
+ write(rel: string, text: string): void {
128
+ if (this.live) writeFileSync(this.real(rel), text)
129
+ else this.text.set(rel, text)
130
+ }
131
+ /** git mv, a file or a folder; the destination's folder is made first */
132
+ mv(from: string, to: string): void {
133
+ if (this.live) {
134
+ mkdirSync(this.real(dirOf(to)), { recursive: true })
135
+ sh(`git mv ${JSON.stringify(from)} ${JSON.stringify(to)}`, this.root)
136
+ return
137
+ }
138
+ const files = this.files()
139
+ files.forEach((f, i) => {
140
+ if (f !== from && !f.startsWith(`${from}/`)) return
141
+ const next = `${to}${f.slice(from.length)}`
142
+ this.text.set(next, this.read(f))
143
+ this.text.delete(f)
144
+ files[i] = next
145
+ })
146
+ this.gone.add(from)
147
+ }
148
+ /** a leftover folder with nothing but Finder's litter */
149
+ dropEmptyDir(rel: string): void {
150
+ if (this.live) rmSync(this.real(rel), { recursive: true })
151
+ else this.gone.add(rel)
152
+ }
153
+ }
154
+
155
+ /** the first line a rewrite changed, as it reads after it, cut around the change */
156
+ const firstChanged = (before: string, after: string): string => {
157
+ const a = before.split('\n')
158
+ const b = after.split('\n')
159
+ const i = b.findIndex((l, k) => l !== a[k])
160
+ const line = b[i] ?? ''
161
+ const old = a[i] ?? ''
162
+ let at = 0
163
+ while (at < line.length && line[at] === old[at]) at++
164
+ const from = Math.max(0, at - 50)
165
+ const cut = line.slice(from, from + 160).trim()
166
+ return `${from > 0 ? '...' : ''}${cut}${from + 160 < line.length ? '...' : ''}`
167
+ }
168
+
169
+ export function movePage(root: string, oldRel: string, newRel: string, io: MvIo, o: MvOpts = {}, tree = new MvTree(root, o.write === true || o.commit === true)): number {
95
170
  const die = (m: string): number => { io.printErr(`FAIL: ${m}`); return 1 }
96
171
  if (!oldRel.endsWith('.md') || !newRel.endsWith('.md')) return die('both paths must be .md (TS moves are not this tool\'s job)')
97
- if (!existsSync(join(root, oldRel))) return die(`${oldRel} does not exist`)
98
- if (existsSync(join(root, newRel))) return die(`${newRel} already exists`)
172
+ if (!tree.exists(oldRel)) return die(`${oldRel} does not exist`)
173
+ if (tree.exists(newRel)) return die(`${newRel} already exists`)
99
174
  // git mv puts a source directory INSIDE an existing destination instead of
100
175
  // refusing, so the probe lands one level too deep and the run still says
101
176
  // ok. Unreachable while every move was a same-dir rename, likely the
@@ -107,21 +182,20 @@ export function movePage(root: string, oldRel: string, newRel: string, io: MvIo,
107
182
  const newBase = indexForm ? dirOf(newRel) : newRel.slice(0, -3)
108
183
  // in place: the page moves into its own asset dir, which already is the topic folder
109
184
  const inPlace = indexForm && newBase === oldBase
110
- if (indexForm && !inPlace && existsSync(join(root, newBase))) return die(`${newBase}/ already exists: a topic folder is created by its move, never merged into`)
111
- if (!indexForm && existsSync(join(root, oldBase)) && existsSync(join(root, newBase)))
185
+ if (indexForm && !inPlace && tree.exists(newBase)) return die(`${newBase}/ already exists: a topic folder is created by its move, never merged into`)
186
+ if (!indexForm && tree.exists(oldBase) && tree.exists(newBase))
112
187
  return die(`${newBase}/ already exists, and ${oldBase}/ would be nested inside it rather than become it: move or merge it by hand first`)
113
188
 
114
- const write = o.write === true || o.commit === true
189
+ const write = tree.live
115
190
  const oldName = basename(oldRel, '.md')
116
191
  const newName = basename(newBase)
117
192
  // docs-root-relative id: refs inside a wiki usually omit the top dir
118
- // (`build/state`, not `wiki/build/state`) — sweep both forms
193
+ // (`build/state`, not `wiki/build/state`), so the sweep takes both forms
119
194
  const tail = (p: string): string | null => { const seg = p.split('/'); return seg.length >= 3 ? seg.slice(1).join('/') : null }
120
195
  const oldId = tail(oldBase)
121
196
  const newId = tail(newBase)
122
197
  const newPageId = tail(newRel.slice(0, -3))
123
198
 
124
- // longest-first so `wiki/x/state.md` beats `x/state` beats bare tokens
125
199
  const pairs: [string, string][] = [
126
200
  [`${oldBase}.md`, newRel],
127
201
  ...(oldId != null ? [[`${oldId}.md`, `${newPageId}.md`] as [string, string]] : []),
@@ -136,14 +210,21 @@ export function movePage(root: string, oldRel: string, newRel: string, io: MvIo,
136
210
  [oldBase, newBase],
137
211
  ...(oldId != null ? [[oldId, newId!] as [string, string]] : []),
138
212
  ]
139
- const bound = (t: string): RegExp =>
140
- new RegExp('(?<![\\w-])' + t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + (/[/.]$/.test(t) || t.endsWith('.ts') ? '' : '(?![\\w-])'), 'g')
213
+ // ONE pass over the text, longest token first at each place: a path one
214
+ // pair writes is never read by the next (`a.md` into `a/a.md` wrote
215
+ // `a/a/a/a.md` when the pairs ran one after the other)
216
+ const to = new Map<string, string>()
217
+ for (const [oldTok, newTok] of pairs) if (!to.has(oldTok)) to.set(oldTok, newTok)
218
+ const sweep = new RegExp(
219
+ '(?<![\\w-])(?:' +
220
+ [...to.keys()].sort((a, b) => b.length - a.length)
221
+ .map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + (/[/.]$/.test(t) || t.endsWith('.ts') ? '' : '(?![\\w-])'))
222
+ .join('|') +
223
+ ')',
224
+ 'g',
225
+ )
141
226
 
142
- // third party code keeps its own references, byte for byte
143
- const repo = vendoredAround(root)
144
- const vendored = (repo?.dirs ?? []).map((d) => posix(relative(root, join(repo!.root, d))))
145
- const tracked = sh('git ls-files', root).split('\n').filter(Boolean)
146
- .filter((f) => !/\.(png|jpe?g|gif|webp|ico|woff2?|ttf|zip|gz|lockb|lock)$/i.test(f) && !isVendored(f, vendored))
227
+ const tracked = tree.files()
147
228
 
148
229
  // every path this move relocates, old → new. The sibling dir carries its
149
230
  // whole subtree, and the probe is renamed after the page, so its own entry
@@ -156,47 +237,45 @@ export function movePage(root: string, oldRel: string, newRel: string, io: MvIo,
156
237
  for (const f of tracked) if (f.startsWith(`${oldBase}/`)) moves.set(f, `${newBase}${f.slice(oldBase.length)}`)
157
238
  for (const sfx of SIBLING_SUFFIXES) {
158
239
  const probe = `${oldBase}/${oldName}${sfx}`
159
- if (existsSync(join(root, probe))) moves.set(probe, `${newBase}/${newName}${sfx}`)
240
+ if (tree.exists(probe)) moves.set(probe, `${newBase}/${newName}${sfx}`)
160
241
  }
161
242
  }
162
243
 
163
244
  let touched = 0
164
- for (const f of tracked) {
165
- const p = join(root, f)
245
+ for (const f of [...tracked]) {
166
246
  // a submodule is one ls-files entry and a directory: nothing to read
167
- if (!isFile(p)) continue
168
- const before = readFileSync(p, 'utf8')
169
- let after = retargetRelativeRefs(root, before, dirOf(f), dirOf(moves.get(f) ?? f), moves)
170
- for (const [oldTok, newTok] of pairs) after = after.replace(bound(oldTok), newTok)
247
+ if (!tree.isFile(f)) continue
248
+ const before = tree.read(f)
249
+ let refs = 0
250
+ const linked = retargetRelativeRefs(root, before, dirOf(f), dirOf(moves.get(f) ?? f), moves, tree.isFile)
251
+ if (linked !== before) { const lines = before.split('\n'); refs += linked.split('\n').filter((l, i) => l !== lines[i]).length }
252
+ const after = linked.replace(sweep, (m) => { const next = to.get(m)!; if (next !== m) refs++; return next })
171
253
  if (after !== before) {
172
- io.print(` ${f}`)
173
- if (write) writeFileSync(p, after)
254
+ io.print(` ${f}: ${refs} ref(s)`)
255
+ io.print(` ${firstChanged(before, after)}`)
256
+ tree.write(f, after)
174
257
  touched++
175
258
  }
176
259
  }
177
- io.print(`${write ? 'renamed' : 'DRY RUN'}: ${oldBase} → ${newBase}, refs in ${touched} file(s)`)
178
- if (!write) { io.print('re-run with --write (or --commit) to apply'); return 0 }
179
260
 
180
261
  // moves AFTER the sweep (the sweep rewrote files at their old paths).
181
- // git mv refuses into a directory that is not there yet, and a move
182
- // between directories is the case where it usually is not
183
262
  // the index form moves the asset dir FIRST, so it becomes the topic
184
263
  // folder; created first, git mv would nest it one level down
185
- if (!hasDir && existsSync(join(root, oldBase)) && readdirSync(join(root, oldBase)).every((e) => e === '.DS_Store')) rmSync(join(root, oldBase), { recursive: true })
186
- mkdirSync(join(root, dirOf(hasDir ? newBase : newRel)), { recursive: true })
187
- if (indexForm && hasDir && !inPlace) sh(`git mv ${JSON.stringify(oldBase)} ${JSON.stringify(newBase)}`, root)
188
- mkdirSync(join(root, dirOf(newRel)), { recursive: true })
189
- sh(`git mv ${JSON.stringify(oldRel)} ${JSON.stringify(newRel)}`, root)
264
+ if (!hasDir && tree.exists(oldBase) && !tree.isFile(oldBase) && readdirSync(join(root, oldBase)).every((e) => e === '.DS_Store')) tree.dropEmptyDir(oldBase)
265
+ if (indexForm && hasDir && !inPlace) tree.mv(oldBase, newBase)
266
+ tree.mv(oldRel, newRel)
190
267
  if (hasDir) {
191
- if (!indexForm) sh(`git mv ${JSON.stringify(oldBase)} ${JSON.stringify(newBase)}`, root)
268
+ if (!indexForm) tree.mv(oldBase, newBase)
192
269
  // the probe is named after its page, so it only moves when the NAME
193
270
  // changed. A move that keeps the name and changes the directory takes
194
271
  // the probe along inside the dir, and `git mv X X` is a fatal
195
272
  for (const sfx of SIBLING_SUFFIXES) {
196
- const oldProbe = join(newBase, `${oldName}${sfx}`)
197
- if (oldName !== newName && existsSync(join(root, oldProbe))) sh(`git mv ${JSON.stringify(oldProbe)} ${JSON.stringify(join(newBase, `${newName}${sfx}`))}`, root)
273
+ const oldProbe = `${newBase}/${oldName}${sfx}`
274
+ if (oldName !== newName && tree.exists(oldProbe)) tree.mv(oldProbe, `${newBase}/${newName}${sfx}`)
198
275
  }
199
276
  }
277
+ io.print(`${write ? 'renamed' : 'DRY RUN'}: ${oldBase} → ${newBase}, refs in ${touched} file(s)`)
278
+ if (!write) { io.print('re-run with --write (or --commit) to apply'); return 0 }
200
279
 
201
280
  if (o.after !== false && !runAfter(root)) return die('mv:after failed, fix before committing')
202
281
  if (o.commit === true) {
@@ -226,13 +305,13 @@ export function parseMoveMap(text: string): [string, string][] {
226
305
  }
227
306
 
228
307
  /** many pages in one run, in map order: each move sweeps the tree the previous
229
- * one left, and `mv:after` runs once at the end. A dry run shows each move
230
- * against the CURRENT tree, so a later pair that depends on an earlier one
231
- * only reports true once applied. Stops at the first failure. */
308
+ * one left, a dry run too (its overlay holds what the lines before moved),
309
+ * and `mv:after` runs once at the end. Stops at the first failure. */
232
310
  export function movePages(root: string, pairs: [string, string][], io: MvIo, o: MvOpts = {}): number {
233
311
  if (o.commit === true) { io.printErr('FAIL: a move map applies with --write, then you commit what you own'); return 1 }
312
+ const tree = new MvTree(root, o.write === true)
234
313
  for (const [from, to] of pairs) {
235
- const code = movePage(root, from, to, io, { ...o, after: false })
314
+ const code = movePage(root, from, to, io, { ...o, after: false }, tree)
236
315
  if (code !== 0) return code
237
316
  }
238
317
  if (o.write === true && !runAfter(root)) { io.printErr('FAIL: mv:after failed, fix before committing'); return 1 }