rvlib-shipkit 2.23.0 → 2.25.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 +45 -0
- package/package.json +1 -1
- package/src/agent-time/live.ts +153 -0
- package/src/agent-time/render.ts +28 -14
- package/src/agent-time/report.ts +46 -25
- package/src/agent-time/store.ts +30 -10
- package/src/agent-time/timeline.ts +43 -15
- package/src/annex/offload.ts +16 -7
- package/src/asks/asks-queue.ts +32 -11
- package/src/check.ts +3 -1
- package/src/checks/SK004-gitignore-policy.check.ts +32 -11
- package/src/checks/SK027-agent-wiki-links.check.ts +1 -1
- package/src/checks/SK033-global-contribution.check.ts +1 -1
- package/src/checks/SK036-draft-media-size.check.ts +1 -1
- package/src/checks/SK040-release-words.check.ts +1 -1
- package/src/checks/SK042-post-kinds.check.ts +1 -1
- package/src/checks/SK044-behind-upstream.check.ts +38 -0
- package/src/cli/cmd_Annex.ts +12 -7
- package/src/cli/cmd_Asks.ts +2 -0
- package/src/cli/cmd_Assets.ts +5 -5
- package/src/cli/cmd_Backup.ts +16 -8
- package/src/cli/cmd_Bump.ts +1 -0
- package/src/cli/cmd_Capacity.ts +30 -0
- package/src/cli/cmd_Check.ts +1 -0
- package/src/cli/cmd_Checks.ts +13 -1
- package/src/cli/cmd_Ci.ts +3 -2
- package/src/cli/cmd_Commands.ts +61 -16
- package/src/cli/cmd_ConfigKeys.ts +17 -0
- package/src/cli/cmd_Home.ts +1 -30
- package/src/cli/cmd_Hooks.ts +1 -0
- package/src/cli/cmd_Keys.ts +4 -1
- package/src/cli/cmd_Lanes.ts +35 -0
- package/src/cli/cmd_Mv.ts +7 -7
- package/src/cli/cmd_Rec.ts +22 -7
- package/src/cli/cmd_Reflect.ts +1 -0
- package/src/cli/cmd_Releases.ts +1 -0
- package/src/cli/cmd_Review.ts +200 -49
- package/src/cli/cmd_Secret.ts +41 -2
- package/src/cli/cmd_Shot.ts +16 -4
- package/src/cli/cmd_Status.ts +7 -5
- package/src/cli/cmd_Time.ts +13 -5
- package/src/cli/cmd_Tmp.ts +82 -0
- package/src/cli/cmd_Veille.ts +10 -6
- package/src/cli/cmd_Wiki.ts +1 -0
- package/src/cli/family-help.ts +136 -0
- package/src/cli/family-pages.ts +0 -19
- package/src/cli/kit/calls.ts +35 -0
- package/src/cli/kit/project-cli.ts +2 -12
- package/src/cli/registry.ts +52 -7
- package/src/cli.ts +8 -4
- package/src/collections/pings.ts +1 -1
- package/src/core/capacity.ts +127 -0
- package/src/core/check-runner.ts +91 -16
- package/src/core/floor-resolve.ts +6 -2
- package/src/core/floor.ts +6 -2
- package/src/core/history-files.ts +18 -0
- package/src/core/jobs.ts +35 -16
- package/src/core/layout.ts +2 -2
- package/src/core/motherhome.ts +67 -9
- package/src/core/nearest.ts +16 -0
- package/src/core/remove-tree.ts +19 -0
- package/src/core/runs.ts +12 -3
- package/src/core/slots.ts +49 -12
- package/src/core/throwaway-worktree.ts +22 -4
- package/src/core/trace-audit.ts +21 -5
- package/src/drill/run.ts +5 -2
- package/src/home/daemon-jobs.ts +41 -4
- package/src/home/gui-app/ShipkitGui.swift +1 -0
- package/src/home/home-launchd.ts +11 -3
- package/src/home/home-routes.ts +11 -4
- package/src/home/machine-host.ts +65 -0
- package/src/home/machine-stores.ts +19 -17
- package/src/home/machine-temp.ts +485 -0
- package/src/home/other-macs.ts +74 -0
- package/src/home/run-daemon.ts +10 -2
- package/src/home/serve-web.ts +2 -2
- package/src/home/via-hub.ts +6 -1
- package/src/init-repo.ts +7 -3
- package/src/ledger/gate-checks.ts +3 -2
- package/src/ledger/git-key.ts +25 -4
- package/src/ledger/git-scan.ts +10 -0
- package/src/ledger/ledger.ts +6 -0
- package/src/ledger/store.ts +6 -0
- package/src/media-store/backup/daemon.ts +92 -20
- package/src/media-store/backup/keys.ts +21 -6
- package/src/media-store/backup/manifest.ts +52 -11
- package/src/media-store/backup/restore.ts +17 -10
- package/src/media-store/backup/run.ts +26 -17
- package/src/media-store/backup/sources.ts +168 -22
- package/src/media-store/backup/watch.ts +106 -0
- package/src/media-store/daemon.ts +36 -8
- package/src/media-store/hand.ts +3 -1
- package/src/mv/mv-md.ts +167 -56
- package/src/pb/run-pb.ts +2 -10
- package/src/plan/repo-source.ts +25 -14
- package/src/recordings/model.ts +1 -1
- package/src/reflect/transcript.ts +56 -11
- package/src/release/run-bump.ts +3 -2
- package/src/release/run-release.ts +12 -4
- package/src/releases/from-card.ts +45 -3
- package/src/releases/model.ts +6 -0
- package/src/releases/store.ts +8 -1
- package/src/repo-config.ts +5 -3
- package/src/review/cells.ts +26 -4
- package/src/review/format.ts +34 -10
- package/src/review/media-kind.ts +14 -11
- package/src/review/media-read.ts +6 -5
- package/src/review/model.ts +85 -4
- package/src/review/paste.ts +2 -1
- package/src/review/previews.ts +123 -36
- package/src/review/routes.ts +29 -18
- package/src/review/store.ts +89 -19
- package/src/review/threads.ts +7 -5
- package/src/review/trailer-model.ts +2 -2
- package/src/secrets/copy.ts +110 -0
- package/src/secrets/list.ts +17 -7
- package/src/serve/hub-app/home-strip.css +5 -0
- package/src/serve/hub-app/home-strip.tsx +18 -0
- package/src/serve/hub-app/hub-app.tsx +2 -1
- package/src/serve/hub-app/hub.css +14 -0
- package/src/serve/hub-app/inbox.css +1 -0
- package/src/serve/hub-app/pull-refresh.tsx +88 -0
- package/src/serve/hub-app/review/review-cells.tsx +52 -13
- package/src/serve/hub-app/review/review-list.tsx +6 -1
- package/src/serve/hub-app/review/review-st.ts +6 -5
- package/src/serve/hub-app/review/review-thread.tsx +3 -1
- package/src/serve/hub-app/review/review-views.tsx +18 -11
- package/src/serve/hub-app/review/thread-st.ts +82 -14
- package/src/serve/hub-app/review.css +15 -2
- package/src/serve/hub-runtime.ts +2 -1
- package/src/serve/run-serve.ts +4 -2
- package/src/serve/serve-hub.ts +9 -2
- package/src/shot/client.ts +4 -2
- package/src/shot/serve-shot.ts +71 -2
- package/src/shot/shooter.ts +65 -11
- package/src/shot/shot-ask.ts +32 -9
- package/src/suite/child-tools.ts +45 -0
- package/src/suite/judge-suites.ts +10 -22
- package/src/suite/select.ts +95 -9
- package/src/suite/suite-cli.ts +38 -14
- package/src/suite/suite-cores.ts +68 -0
- package/src/suite/suite-reads-preload.ts +8 -6
- package/src/suite/test-units.ts +31 -12
- package/src/trailer/graph.ts +2 -1
- package/src/ts/config.ts +21 -0
- package/src/ts/rename.ts +37 -13
- package/src/ts/workspaces.ts +45 -0
- package/src/wiki/run-wiki.ts +7 -2
- package/src/wiki/scan-md.ts +2 -1
- package/src/home/claude-temp.ts +0 -139
package/src/home/run-daemon.ts
CHANGED
|
@@ -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
|
-
|
|
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) =>
|
|
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
|
package/src/home/serve-web.ts
CHANGED
|
@@ -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
|
|
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
|
|
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
|
package/src/home/via-hub.ts
CHANGED
|
@@ -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,
|
|
181
|
-
*
|
|
182
|
-
*
|
|
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
|
}
|
|
@@ -234,9 +234,9 @@ function derivedRuns(o: { gate: boolean; build: boolean; inputs?: string[]; ttl?
|
|
|
234
234
|
}
|
|
235
235
|
|
|
236
236
|
/** the cache half of a check file, as the key layer reads it */
|
|
237
|
-
function declOfCache(cache: CacheDecl, env: CheckEnv): { inputs?: string[]; ttl?: string; never?: string; key?: string; reads?: boolean } {
|
|
237
|
+
function declOfCache(cache: CacheDecl, env: CheckEnv): { inputs?: string[]; optional?: string[]; ttl?: string; never?: string; key?: string; reads?: boolean } {
|
|
238
238
|
switch (cache.by) {
|
|
239
|
-
case 'files': return { inputs: cache.inputs, key: cache.key?.(env) }
|
|
239
|
+
case 'files': return { inputs: cache.inputs, optional: cache.optional, key: cache.key?.(env) }
|
|
240
240
|
case 'reads': return { reads: true }
|
|
241
241
|
case 'ttl': return { ttl: cache.span, key: cache.key?.(env) }
|
|
242
242
|
case 'fact': return { ttl: FOREVER, key: cache.key(env) }
|
|
@@ -412,6 +412,7 @@ export async function composeChecks(root: string, c: RepoConfig, o: ComposeOpts
|
|
|
412
412
|
decl: {
|
|
413
413
|
id: u.id,
|
|
414
414
|
inputs: cache.inputs,
|
|
415
|
+
optional: cache.optional,
|
|
415
416
|
code: u.rel == null ? undefined : [u.rel],
|
|
416
417
|
// a built-in's code is the toolkit's: keyed on its own closure
|
|
417
418
|
// there, never on the toolkit as a whole
|
package/src/ledger/git-key.ts
CHANGED
|
@@ -51,6 +51,9 @@ import { installIdentity, toolchainIdentity, type LibSource } from './toolchain-
|
|
|
51
51
|
* so an old ledger can never answer a new question. */
|
|
52
52
|
export const KEY_VERSION = 4
|
|
53
53
|
|
|
54
|
+
/** the object id an optional input carries while it is not on disk */
|
|
55
|
+
export const ABSENT = 'absent'
|
|
56
|
+
|
|
54
57
|
/** `dir/**` names a dir a task only LISTS: keyed on the names under it */
|
|
55
58
|
export const isNamesInput = (p: string): boolean => p.endsWith('/**')
|
|
56
59
|
|
|
@@ -74,6 +77,10 @@ export type CheckDecl = {
|
|
|
74
77
|
id: string
|
|
75
78
|
/** CONTENT: repo-relative paths this check reads. Presence declares the population. */
|
|
76
79
|
inputs?: string[]
|
|
80
|
+
/** the inputs a repo may lack, each one of `inputs`. Absent, the key
|
|
81
|
+
* carries `absent` for it, so the key moves when it appears. Any other
|
|
82
|
+
* input missing from disk refuses the key: a typo must never key */
|
|
83
|
+
optional?: string[]
|
|
77
84
|
/** WORLD: clean-pass duration, e.g. '24h'. Presence declares the population. */
|
|
78
85
|
ttl?: string
|
|
79
86
|
/** repo-relative entry files of the check's OWN code — the module-graph
|
|
@@ -302,6 +309,12 @@ export class KeyLayer {
|
|
|
302
309
|
return new KeyLayer(root, decls, registration, scan, scanError, closureByCheck, codeOids, toolchain, [...paths].sort(), o.scope ?? null, performance.now() - started)
|
|
303
310
|
}
|
|
304
311
|
|
|
312
|
+
/** what the scan saw of every declared input of the layer that git does not ignore, as one id; null when the
|
|
313
|
+
* scan failed. The ignored inputs stay out: a run writes some of them, so their id moves with every run */
|
|
314
|
+
treeStamp(): string | null {
|
|
315
|
+
return this.scan == null ? null : this.scan.treeOid
|
|
316
|
+
}
|
|
317
|
+
|
|
305
318
|
/** the key for one check, or the reason there is none. */
|
|
306
319
|
keyFor(id: string): CheckKey {
|
|
307
320
|
const d = this.decls.find((u) => u.id === id)
|
|
@@ -346,16 +359,24 @@ export class KeyLayer {
|
|
|
346
359
|
|
|
347
360
|
let inputs: string[]
|
|
348
361
|
let names: string[]
|
|
362
|
+
let optional: Set<string>
|
|
349
363
|
try {
|
|
350
364
|
inputs = (d.inputs ?? []).filter((p) => !isNamesInput(p)).map(normalizeInput).sort()
|
|
351
365
|
names = (d.inputs ?? []).filter(isNamesInput).map((p) => normalizeInput(p.slice(0, -3))).sort()
|
|
366
|
+
optional = new Set((d.optional ?? []).map(normalizeInput))
|
|
352
367
|
} catch (e) {
|
|
353
368
|
return { ...base, reason: e instanceof Error ? e.message : String(e) }
|
|
354
369
|
}
|
|
355
|
-
|
|
356
|
-
|
|
370
|
+
// absent means not on disk at all: a path git cannot name while it
|
|
371
|
+
// exists (a submodule, an empty folder) keys nothing, optional or not
|
|
372
|
+
const notOnDisk = (p: string): boolean => !existsSync(join(this.root, p))
|
|
373
|
+
const absent = new Set(inputs.filter((p) => optional.has(p) && scan.missing.includes(p) && notOnDisk(p)))
|
|
374
|
+
const stale = inputs.filter((p) => scan.missing.includes(p) && !absent.has(p))
|
|
375
|
+
const gone = stale.filter(notOnDisk)
|
|
376
|
+
if (gone.length > 0) return { ...base, reason: `declared input(s) not on disk: ${gone.join(', ')}` }
|
|
377
|
+
if (stale.length > 0) return { ...base, reason: `declared input(s) on disk that git could not name (a submodule, an empty folder): ${stale.join(', ')}` }
|
|
357
378
|
const hidden = inputs.flatMap((p) => scan.excluded.get(p) ?? [])
|
|
358
|
-
const inputOids: [string, string][] = inputs.map((p) => [p, scan.oidByPath.get(p) ?? ''])
|
|
379
|
+
const inputOids: [string, string][] = inputs.map((p) => [p, absent.has(p) ? ABSENT : scan.oidByPath.get(p) ?? ''])
|
|
359
380
|
if (inputOids.some(([, oid]) => oid === '')) return { ...base, reason: 'git could not name one of the declared inputs' }
|
|
360
381
|
|
|
361
382
|
if (!ownReadable) return { ...base, reason: `git could not hash this check's own source: ${own.filter((p) => this.codeOids.get(p) == null).join(', ')}` }
|
|
@@ -460,7 +481,7 @@ export class KeyLayer {
|
|
|
460
481
|
let h = this.namesMemo.get(rel)
|
|
461
482
|
if (h == null) {
|
|
462
483
|
const abs = join(this.root, rel)
|
|
463
|
-
if (!existsSync(abs)) h =
|
|
484
|
+
if (!existsSync(abs)) h = ABSENT
|
|
464
485
|
else {
|
|
465
486
|
const all: string[] = []
|
|
466
487
|
const walk = (d: string, prefix: string): void => {
|
package/src/ledger/git-scan.ts
CHANGED
|
@@ -200,9 +200,19 @@ function dropAtExit(p: string): void {
|
|
|
200
200
|
/** a scratch index older than this is swept whatever its pid: pids are reused */
|
|
201
201
|
export const SCAN_INDEX_KEEP_MS = 60 * 60 * 1000
|
|
202
202
|
|
|
203
|
+
/** the lock git leaves on the warm ignored index is stale past this: git holds it for one command, seconds at most
|
|
204
|
+
* on the largest tree measured, and a git that was killed leaves it forever. One left in a repo failed every scan
|
|
205
|
+
* there for eleven days: no check had a key, nothing was cached, and each save ran the whole gate again */
|
|
206
|
+
export const SCAN_LOCK_STALE_MS = 2 * 60 * 1000
|
|
207
|
+
const IGNORED_LOCK = 'scan-ignored.idx.lock'
|
|
208
|
+
|
|
203
209
|
/** the scratch indexes of processes that are gone (killed ones leave theirs),
|
|
204
210
|
* and any past the keep window */
|
|
205
211
|
export function sweepScanIndexes(dir: string, now: number): void {
|
|
212
|
+
try {
|
|
213
|
+
const lock = join(dir, IGNORED_LOCK)
|
|
214
|
+
if (statSync(lock).mtimeMs < now - SCAN_LOCK_STALE_MS) rmSync(lock, { force: true })
|
|
215
|
+
} catch { /* no lock, or a live git just released it */ }
|
|
206
216
|
try {
|
|
207
217
|
for (const f of readdirSync(dir)) {
|
|
208
218
|
const m = /^scan-(\d+)\.idx(\.tmp)?$/.exec(f)
|
package/src/ledger/ledger.ts
CHANGED
|
@@ -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)
|
package/src/ledger/store.ts
CHANGED
|
@@ -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,24 +1,42 @@
|
|
|
1
|
-
// the daemon's backup job (wiki tools/shipkit/media-store.md,
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
1
|
+
// the daemon's backup job (wiki tools/shipkit/media-store-backup.md, The daemon). The daemon watches the sources
|
|
2
|
+
// (watch.ts) and starts a look only when one may have moved, a run waits, or a clock says so (`backupDue`, a few
|
|
3
|
+
// reads of the machine db). The look, in its child process, reads again only the paths the watch heard, on the list
|
|
4
|
+
// the last look kept; a full walk every SAFETY_MS catches what no event told. Once the stamp moved and then held
|
|
5
|
+
// still for one look (or waited WAIT_MAX_MS while sources kept moving), a run, at most one each 10 min; a run every
|
|
6
|
+
// 6 h whatever moved, which reads every byte again
|
|
5
7
|
import { machineGet, machineSet } from '../../core/machine-db.ts'
|
|
8
|
+
import type { RepoBackup } from '../../repo-config.ts'
|
|
6
9
|
import type { Space } from '../space.ts'
|
|
7
10
|
import { backupRun, lastRun } from './run.ts'
|
|
8
|
-
import { collect, localFiles, stampOfSources } from './sources.ts'
|
|
11
|
+
import { backupOfRepo, collect, localFiles, missedBy, movesLocals, patchLocals, refreshSources, stampOfSources, type Collect, type Source } from './sources.ts'
|
|
9
12
|
|
|
13
|
+
/** the daemon looks this often: a look starts the child only when `backupDue` says so */
|
|
10
14
|
export const BACKUP_EVERY_MS = 120_000
|
|
11
|
-
const FLOOR_MS = 10 * 60_000
|
|
12
|
-
const EVERY_MS = 6 * 3600_000
|
|
15
|
+
export const FLOOR_MS = 10 * 60_000
|
|
16
|
+
export const EVERY_MS = 6 * 3600_000
|
|
17
|
+
/** a full walk at least this often: a watch that died, a root nobody watches, an event the system dropped */
|
|
18
|
+
export const SAFETY_MS = 30 * 60_000
|
|
19
|
+
/** a change that waits this long goes up even while other sources keep moving: an agent that writes every minute
|
|
20
|
+
* never holds the rest back */
|
|
21
|
+
export const WAIT_MAX_MS = 30 * 60_000
|
|
13
22
|
/** the git walk for `*.local.*` files, kept this long per repo */
|
|
14
23
|
const LOCALS_MS = 30 * 60_000
|
|
15
24
|
|
|
16
|
-
/** the stamp the last look saw
|
|
17
|
-
|
|
25
|
+
/** the stamp the last look saw, the one the last good run sent, and the last full walk; `backup-` rows are left out
|
|
26
|
+
* of the snapshot */
|
|
27
|
+
export const STAMPS = 'backup-stamps'
|
|
18
28
|
const LOCALS = 'backup-locals'
|
|
19
29
|
const NO_SPACE = 'backup-no-space'
|
|
30
|
+
/** the list the last look kept, so the next one reads only what moved */
|
|
31
|
+
const SOURCES = 'backup-sources'
|
|
32
|
+
/** the paths the daemon heard, handed to the look it starts: kept undone until a look took them */
|
|
33
|
+
export const BATCH = 'backup-moved'
|
|
34
|
+
/** each repo's `backup.paths`, for the daemon's watch: a look writes them, the watch reads them */
|
|
35
|
+
export const NAMED = 'backup-named'
|
|
20
36
|
|
|
21
|
-
|
|
37
|
+
/** `waitAt`: since when a stamp the last run did not send waits */
|
|
38
|
+
export type Stamps = { seen: string; ran: string; fullAt?: number; waitAt?: number }
|
|
39
|
+
export type Batch = { paths: string[]; all: boolean; done: boolean }
|
|
22
40
|
type Locals = Record<string, { at: number; files: string[] }>
|
|
23
41
|
|
|
24
42
|
export interface BackupTick {
|
|
@@ -28,10 +46,27 @@ export interface BackupTick {
|
|
|
28
46
|
print: (l: string) => void
|
|
29
47
|
printErr: (l: string) => void
|
|
30
48
|
now?: () => number
|
|
49
|
+
/** each repo's `backup` key; by default its config */
|
|
50
|
+
backupOf?: (repo: string) => Promise<RepoBackup | null>
|
|
31
51
|
}
|
|
32
52
|
|
|
33
|
-
/**
|
|
34
|
-
*
|
|
53
|
+
/** the daemon's read before it starts a look (no walk, no child): something heard, a batch a look did not take, the
|
|
54
|
+
* safety walk due, a run the floor held back, or the 6 h run */
|
|
55
|
+
export function backupDue(now: number, heard: boolean): boolean {
|
|
56
|
+
if (heard) return true
|
|
57
|
+
const s = machineGet<Stamps>(STAMPS)
|
|
58
|
+
if (s == null || now - (s.fullAt ?? 0) >= SAFETY_MS) return true
|
|
59
|
+
if (machineGet<Batch>(BATCH)?.done === false) return true
|
|
60
|
+
const last = lastRun()
|
|
61
|
+
const since = last ? now - Date.parse(last.at) : Infinity
|
|
62
|
+
if (since >= EVERY_MS) return true
|
|
63
|
+
// with no Space a run never lands: only a change or a clock brings the next look
|
|
64
|
+
return s.seen !== s.ran && since >= FLOOR_MS && !machineGet<string>(NO_SPACE)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** one look of the daemon's backup job, in its child process: the moved paths read again (or every source, on the
|
|
68
|
+
* safety clock), then a run when it is due. What a look remembers lives in the machine db, so a daemon restart
|
|
69
|
+
* never makes a run of its own */
|
|
35
70
|
export async function backupTick(o: BackupTick): Promise<void> {
|
|
36
71
|
const now = o.now ?? Date.now
|
|
37
72
|
const locals: Locals = machineGet<Locals>(LOCALS) ?? {}
|
|
@@ -45,13 +80,50 @@ export async function backupTick(o: BackupTick): Promise<void> {
|
|
|
45
80
|
return files
|
|
46
81
|
}
|
|
47
82
|
try {
|
|
48
|
-
const
|
|
49
|
-
if (walked) machineSet(LOCALS, locals)
|
|
83
|
+
const started = now()
|
|
50
84
|
const held: Stamps = machineGet<Stamps>(STAMPS) ?? { seen: '', ran: '' }
|
|
85
|
+
const batch = machineGet<Batch>(BATCH)
|
|
86
|
+
const moved = batch && !batch.done ? batch.paths : []
|
|
87
|
+
const prev = machineGet<Source[]>(SOURCES)
|
|
51
88
|
const last = lastRun()
|
|
52
|
-
const since = last ?
|
|
53
|
-
const
|
|
54
|
-
|
|
89
|
+
const since = last ? started - Date.parse(last.at) : Infinity
|
|
90
|
+
const sixHours = since >= EVERY_MS
|
|
91
|
+
const all = batch?.done === false && batch.all
|
|
92
|
+
const full = prev == null || all || started - (held.fullAt ?? 0) >= SAFETY_MS || sixHours
|
|
93
|
+
// a heard `*.local.*` path is read again in the kept git walk, alone
|
|
94
|
+
for (const r of new Set(moved.map((p) => movesLocals(p, o.repos)).filter((r) => r != null))) {
|
|
95
|
+
const kept = locals[r]
|
|
96
|
+
if (kept == null) continue
|
|
97
|
+
locals[r] = { at: kept.at, files: await patchLocals(r, kept.files, moved) }
|
|
98
|
+
walked = true
|
|
99
|
+
}
|
|
100
|
+
// each config read says its named paths: the daemon's watch hears them
|
|
101
|
+
const named = machineGet<Record<string, string[]>>(NAMED) ?? {}
|
|
102
|
+
const namedWas = JSON.stringify(named)
|
|
103
|
+
const backupOf = async (repo: string): Promise<RepoBackup | null> => {
|
|
104
|
+
const b = await (o.backupOf ?? backupOfRepo)(repo)
|
|
105
|
+
named[repo] = b?.paths ?? []
|
|
106
|
+
return b
|
|
107
|
+
}
|
|
108
|
+
const c: Collect = { home: o.home, repos: o.repos, locals: cachedLocals, backupOf }
|
|
109
|
+
// on a full walk, what the events told is read first: what the walk finds beyond it, no event told
|
|
110
|
+
const told = full && prev != null && !all ? await refreshSources(prev, moved, c) : null
|
|
111
|
+
const list = full ? await collect(c) : await refreshSources(prev, moved, c)
|
|
112
|
+
if (told != null) {
|
|
113
|
+
// said: a watch that went quiet is seen here, not after a lost file
|
|
114
|
+
const missed = missedBy(told, list)
|
|
115
|
+
if (missed.length > 0) o.printErr(`note: backup: the safety walk found ${missed.length} changes no file event told, first ${missed[0]}`)
|
|
116
|
+
}
|
|
117
|
+
if (walked) machineSet(LOCALS, locals)
|
|
118
|
+
if (JSON.stringify(named) !== namedWas) machineSet(NAMED, named)
|
|
119
|
+
machineSet(SOURCES, list)
|
|
120
|
+
if (batch && !batch.done) machineSet(BATCH, { ...batch, done: true } satisfies Batch)
|
|
121
|
+
const stamp = stampOfSources(list)
|
|
122
|
+
const waitAt = stamp === held.ran ? undefined : (held.waitAt ?? started)
|
|
123
|
+
const waited = waitAt != null && started - waitAt >= WAIT_MAX_MS
|
|
124
|
+
const due = sixHours || (stamp !== held.ran && (stamp === held.seen || waited) && since >= FLOOR_MS)
|
|
125
|
+
const fullAt = full ? started : held.fullAt
|
|
126
|
+
machineSet(STAMPS, { seen: stamp, ran: held.ran, ...(fullAt != null ? { fullAt } : {}), ...(waitAt != null ? { waitAt } : {}) } satisfies Stamps)
|
|
55
127
|
if (!due) return
|
|
56
128
|
const { space, why } = await o.space()
|
|
57
129
|
// said once per reason: a look is a child of its own
|
|
@@ -61,10 +133,10 @@ export async function backupTick(o: BackupTick): Promise<void> {
|
|
|
61
133
|
return
|
|
62
134
|
}
|
|
63
135
|
machineSet(NO_SPACE, '')
|
|
64
|
-
const r = await backupRun(space, {
|
|
65
|
-
if (r.failed.length === 0) machineSet(STAMPS, { seen: stamp, ran: stamp } satisfies Stamps)
|
|
136
|
+
const r = await backupRun(space, { ...c, sources: list, rehash: sixHours, now: new Date(now()) })
|
|
137
|
+
if (r.failed.length === 0) machineSet(STAMPS, { seen: stamp, ran: stamp, ...(fullAt != null ? { fullAt } : {}) } satisfies Stamps)
|
|
66
138
|
if (r.failed.length > 0) o.printErr(`WARN backup: ${r.failed.length} objects did not go up, no manifest written; first: ${r.failed[0]?.key}: ${r.failed[0]?.error}`)
|
|
67
|
-
else if (r.manifest) o.print(`ok: backup: ${r.files} files, ${r.sent} objects up (${(r.sentBytes / 1e6).toFixed(1)} MB), ${r.refused.length} refused, manifest ${r.manifest}`)
|
|
139
|
+
else if (r.manifest) o.print(`ok: backup: ${r.files} files, ${r.sent} objects up (${(r.sentBytes / 1e6).toFixed(1)} MB), ${r.read} read again, ${r.refused.length} refused, manifest ${r.manifest}`)
|
|
68
140
|
} catch (e) {
|
|
69
141
|
// a hand run holds the lock: the next look tries again, and says so (a lock that never goes stops every backup)
|
|
70
142
|
const msg = (e as Error).message
|
|
@@ -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
|
|
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
|
-
|
|
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
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
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,
|
|
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
|
|
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
|
|
136
|
-
return
|
|
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
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
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
|
-
|
|
78
|
-
|
|
79
|
-
|
|
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) {
|