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
|
@@ -18,9 +18,11 @@ 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
|
+
/** every file a run held, by path: its size, time, sha and key, so a file whose size and time held is never read
|
|
25
|
+
* again (the 6 h run reads every byte again) */
|
|
24
26
|
const SEEN = 'backup-seen'
|
|
25
27
|
|
|
26
28
|
export interface Last {
|
|
@@ -43,11 +45,14 @@ export interface Ready {
|
|
|
43
45
|
file?: string
|
|
44
46
|
/** the object's size: a sqlite's is its gzip */
|
|
45
47
|
size: number
|
|
46
|
-
/** a path the repo names whole:
|
|
48
|
+
/** a path the repo names whole: no size bound, read as a stream */
|
|
47
49
|
whole?: true
|
|
50
|
+
/** read from the disk by this run, not taken from the last run's sha */
|
|
51
|
+
read?: true
|
|
48
52
|
}
|
|
49
53
|
|
|
50
|
-
/** every source read: hashed, snapshotted, or refused
|
|
54
|
+
/** every source read: hashed, snapshotted, or refused. A file whose size and time equal the last run's, its object
|
|
55
|
+
* up, keeps that run's sha unread (`seen`; empty reads every byte) */
|
|
51
56
|
export async function prepare(sources: readonly Source[], scratch: string, seen: Seen = machineGet<Seen>(SEEN) ?? {}): Promise<{ ready: Ready[]; refused: Refused[] }> {
|
|
52
57
|
const ready: Ready[] = []
|
|
53
58
|
const refused: Refused[] = []
|
|
@@ -70,15 +75,15 @@ export async function prepare(sources: readonly Source[], scratch: string, seen:
|
|
|
70
75
|
const gz = new Uint8Array(gzipSync(raw))
|
|
71
76
|
// a snapshot is a new file each run: its live file's time would move the part with no change
|
|
72
77
|
const entry: Entry = { path: s.rel, sha: sha256(raw), size: raw.length, mtime: 0, key: `${BACKUP_LABEL}/${sha256(gz)}.gz`, sqlite: { ...s.sqlite, rows: snap.rows } }
|
|
73
|
-
ready.push({ entry, bytes: gz, size: gz.length })
|
|
78
|
+
ready.push({ entry, bytes: gz, size: gz.length, read: true })
|
|
79
|
+
continue
|
|
80
|
+
}
|
|
81
|
+
const was = seen[s.rel]
|
|
82
|
+
if (was && was.size === s.size && was.mtime === s.mtime && isUp(was.key)) {
|
|
83
|
+
ready.push({ entry: { path: s.rel, sha: was.sha, size: was.size, mtime: s.mtime, key: was.key }, size: was.size, ...(s.whole ? { whole: true as const } : {}) })
|
|
74
84
|
continue
|
|
75
85
|
}
|
|
76
86
|
if (s.whole) {
|
|
77
|
-
const was = seen[s.rel]
|
|
78
|
-
if (was && was.size === s.size && was.mtime === s.mtime && isUp(was.key)) {
|
|
79
|
-
ready.push({ entry: { path: s.rel, sha: was.sha, size: was.size, mtime: s.mtime, key: was.key }, size: was.size, whole: true })
|
|
80
|
-
continue
|
|
81
|
-
}
|
|
82
87
|
const copy = join(scratch, `${ready.length}-whole${extname(s.abs)}`)
|
|
83
88
|
copyFileSync(s.abs, copy, constants.COPYFILE_FICLONE)
|
|
84
89
|
const r = await fileRefusal(copy, basename(s.abs))
|
|
@@ -87,7 +92,7 @@ export async function prepare(sources: readonly Source[], scratch: string, seen:
|
|
|
87
92
|
refused.push({ path: s.rel, why: r.why })
|
|
88
93
|
continue
|
|
89
94
|
}
|
|
90
|
-
ready.push({ entry: { path: s.rel, sha: r.sha, size: r.size, mtime: s.mtime, key: mediaKey(BACKUP_LABEL, { sha: r.sha }, s.abs) }, file: copy, size: r.size, whole: true })
|
|
95
|
+
ready.push({ entry: { path: s.rel, sha: r.sha, size: r.size, mtime: s.mtime, key: mediaKey(BACKUP_LABEL, { sha: r.sha }, s.abs) }, file: copy, size: r.size, whole: true, read: true })
|
|
91
96
|
continue
|
|
92
97
|
}
|
|
93
98
|
const bytes = new Uint8Array(await Bun.file(s.abs).arrayBuffer())
|
|
@@ -97,7 +102,7 @@ export async function prepare(sources: readonly Source[], scratch: string, seen:
|
|
|
97
102
|
continue
|
|
98
103
|
}
|
|
99
104
|
const sha = sha256(bytes)
|
|
100
|
-
ready.push({ entry: { path: s.rel, sha, size: bytes.length, mtime: s.mtime, key: mediaKey(BACKUP_LABEL, { sha }, s.abs) }, bytes, size: bytes.length })
|
|
105
|
+
ready.push({ entry: { path: s.rel, sha, size: bytes.length, mtime: s.mtime, key: mediaKey(BACKUP_LABEL, { sha }, s.abs) }, bytes, size: bytes.length, read: true })
|
|
101
106
|
} catch (e) {
|
|
102
107
|
refused.push({ path: s.rel, why: `not read: ${(e as Error).message}` })
|
|
103
108
|
}
|
|
@@ -116,6 +121,8 @@ export interface RunResult {
|
|
|
116
121
|
there: number
|
|
117
122
|
refused: Refused[]
|
|
118
123
|
failed: { key: string; error: string }[]
|
|
124
|
+
/** files read from the disk; the others kept the last run's sha */
|
|
125
|
+
read: number
|
|
119
126
|
/** the run written, null when nothing changed since `last` or an upload failed */
|
|
120
127
|
manifest: string | null
|
|
121
128
|
/** what the record of the run cost: its parts sent (of all), their bytes, and the run's own bytes */
|
|
@@ -168,7 +175,9 @@ async function sendAll(space: Space, ready: readonly Ready[], scratch: string, j
|
|
|
168
175
|
async function lastOf(space: Space, scratch: string): Promise<Last | null> {
|
|
169
176
|
const held = lastRun()
|
|
170
177
|
if (held) return held
|
|
171
|
-
|
|
178
|
+
// only a run whose key names this Mac: the last run only spares an identical one, so a Mac that never named its
|
|
179
|
+
// runs sends one in full instead of reading every old run for its host
|
|
180
|
+
const run = await runAt(space, undefined, machineName(), { namedOnly: true })
|
|
172
181
|
if (!run) return null
|
|
173
182
|
const m = await readRunHead(space, run.key, join(scratch, 'last.json.gz'))
|
|
174
183
|
return { key: run.key, digest: m.digest, at: m.at }
|
|
@@ -205,20 +214,20 @@ function lock(): () => void {
|
|
|
205
214
|
}
|
|
206
215
|
|
|
207
216
|
/** one run: every source to the Space, then the run's parts the Space lacks, then the run itself, last */
|
|
208
|
-
export async function backupRun(space: Space, o: Collect & { now?: Date; jobs?: number }): Promise<RunResult> {
|
|
217
|
+
export async function backupRun(space: Space, o: Collect & { now?: Date; jobs?: number; sources?: readonly Source[]; rehash?: boolean }): Promise<RunResult> {
|
|
209
218
|
const unlock = lock()
|
|
210
219
|
const scratch = mkdtempSync(join(tmpdir(), 'shipkit-backup-'))
|
|
211
220
|
try {
|
|
212
221
|
const now = o.now ?? new Date()
|
|
213
|
-
const { ready, refused } = await prepare(await collect(o), scratch)
|
|
222
|
+
const { ready, refused } = await prepare(o.sources ?? (await collect(o)), scratch, o.rehash ? {} : undefined)
|
|
214
223
|
const files = ready.map((r) => r.entry)
|
|
215
224
|
const digest = digestOf(files, refused)
|
|
216
225
|
const last = await lastOf(space, scratch)
|
|
217
|
-
const out: RunResult = { files: files.length, bytes: ready.reduce((n, r) => n + r.entry.size, 0), sent: 0, sentBytes: 0, there: 0, refused, failed: [], manifest: null, record: { parts: 0, partsSent: 0, partsBytes: 0, runBytes: 0 }, last, digest }
|
|
226
|
+
const out: RunResult = { files: files.length, bytes: ready.reduce((n, r) => n + r.entry.size, 0), sent: 0, sentBytes: 0, there: 0, refused, failed: [], read: ready.filter((r) => r.read).length, manifest: null, record: { parts: 0, partsSent: 0, partsBytes: 0, runBytes: 0 }, last, digest }
|
|
218
227
|
await sendAll(space, ready, scratch, o.jobs ?? 8, out)
|
|
219
228
|
if (out.failed.length > 0) return out
|
|
220
229
|
const seen: Seen = {}
|
|
221
|
-
for (const r of ready) if (r.
|
|
230
|
+
for (const r of ready) if (!r.entry.sqlite) seen[r.entry.path] = { size: r.entry.size, mtime: r.entry.mtime, sha: r.entry.sha, key: r.entry.key }
|
|
222
231
|
machineSet(SEEN, seen)
|
|
223
232
|
if (last?.digest === digest) return out
|
|
224
233
|
const enc = encodeRun({ at: now.toISOString(), host: hostname(), home: o.home, digest, files, refused }, o.repos.map((r) => relative(o.home, r)))
|
|
@@ -235,7 +244,7 @@ export async function backupRun(space: Space, o: Collect & { now?: Date; jobs?:
|
|
|
235
244
|
}
|
|
236
245
|
}
|
|
237
246
|
if (out.failed.length > 0) return out
|
|
238
|
-
const key = runKey(now, digest)
|
|
247
|
+
const key = runKey(now, digest, machineName())
|
|
239
248
|
await sendOne(space, key, enc.run.length, { bytes: enc.run }, scratch, -1 - enc.parts.length)
|
|
240
249
|
out.record.runBytes = enc.run.length
|
|
241
250
|
machineSet(LAST, { key, digest, at: now.toISOString() } satisfies Last)
|
|
@@ -3,11 +3,12 @@
|
|
|
3
3
|
// and the machine db (consistent sqlite snapshots), the machine's private folder, the agents' memories of each house
|
|
4
4
|
// repo; in each house repo, every untracked file of `.shipkit/` and the hand tuned `.comfy-ts/` files, and its
|
|
5
5
|
// gitignored `*.local.*` files; and what the repo's config adds (`backup`: paths kept whole, sqlite files). Never a cache, a log, a scratch folder, a lock, a dev database it did not name or a media file a kind of
|
|
6
|
-
// the store holds. Walked with
|
|
6
|
+
// the store holds. Walked with sync fs (half the CPU of an async walk): it runs in the job's child or the cli, never on
|
|
7
|
+
// the daemon's loop. A look of the daemon reads again only the paths its watch heard (a Scope)
|
|
7
8
|
import type { Dirent } from 'node:fs'
|
|
8
9
|
import { lstat, readdir } from 'node:fs/promises'
|
|
9
|
-
import { existsSync, statSync } from 'node:fs'
|
|
10
|
-
import { basename, extname, join, relative, sep } from 'node:path'
|
|
10
|
+
import { existsSync, lstatSync, readdirSync, statSync } from 'node:fs'
|
|
11
|
+
import { basename, dirname, extname, join, relative, sep } from 'node:path'
|
|
11
12
|
import { homeDir } from '../../home/home-paths.ts'
|
|
12
13
|
import { machineDbPath } from '../../core/machine-db.ts'
|
|
13
14
|
import { MACHINE_PRIVATE } from '../../core/layout.ts'
|
|
@@ -31,7 +32,7 @@ export interface Source {
|
|
|
31
32
|
}
|
|
32
33
|
|
|
33
34
|
/** `.shipkit/` folders rebuilt, scratch, logs, runtime, or media the store or another owner keeps */
|
|
34
|
-
const SHIPKIT_DENY = new Set(['cache', 'tmp', 'logs', 'wrapper', 'locks', 'shots', 'backups', 'cloud', 'review-watchers', 'worktrees', 'node_modules', '.git'])
|
|
35
|
+
const SHIPKIT_DENY = new Set(['cache', 'tmp', 'logs', 'review-auto', 'wrapper', 'locks', 'shots', 'backups', 'cloud', 'review-watchers', 'worktrees', 'node_modules', '.git'])
|
|
35
36
|
const FILE_DENY = /^(?:STATUS(?:\.full)?\.md|\.DS_Store|\.review-index\.json|review-dispatcher\.json)$|\.(?:log|pid|lock|sqlite(?:-wal|-shm)?|db(?:-wal|-shm)?)$/
|
|
36
37
|
/** the review store's media go up as the `review` kind: only its records come here */
|
|
37
38
|
const RECORD = /\.(?:json|jsonl|md|txt|csv)$/
|
|
@@ -43,10 +44,38 @@ const COMFY_KEEP = ['drafts', 'llm-configs', 'settings.json', 'lora-keywords.jso
|
|
|
43
44
|
const REPO_EXTRA = ['agent/global-contribution.md', 'proposal', '.local']
|
|
44
45
|
const CODE = /\.(?:[cm]?[jt]sx?)$/
|
|
45
46
|
|
|
46
|
-
|
|
47
|
+
/** the paths a look reads again, each one with everything under it: a walk enters only the folders on the way */
|
|
48
|
+
export class Scope {
|
|
49
|
+
private readonly at: Set<string>
|
|
50
|
+
private readonly above = new Set<string>()
|
|
51
|
+
constructor(paths: Iterable<string>) {
|
|
52
|
+
this.at = new Set([...paths].map((p) => (p.length > 1 ? p.replace(/\/+$/, '') : p)))
|
|
53
|
+
for (const p of this.at) for (let d = dirname(p); !this.above.has(d); d = dirname(d)) {
|
|
54
|
+
this.above.add(d)
|
|
55
|
+
if (d === dirname(d)) break
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
get size(): number {
|
|
59
|
+
return this.at.size
|
|
60
|
+
}
|
|
61
|
+
/** at or under a path of the scope */
|
|
62
|
+
covers(abs: string): boolean {
|
|
63
|
+
for (let p = abs; ; p = dirname(p)) {
|
|
64
|
+
if (this.at.has(p)) return true
|
|
65
|
+
if (p === dirname(p)) return false
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** a folder a walk enters: on the way to a path of the scope, or under one */
|
|
69
|
+
reaches(abs: string): boolean {
|
|
70
|
+
return this.above.has(abs) || this.covers(abs)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function walk(dir: string, keep: (rel: string, isDir: boolean) => boolean, out: string[], base = dir, scope?: Scope): Promise<void> {
|
|
75
|
+
if (scope && !scope.reaches(dir)) return
|
|
47
76
|
let names: Dirent[]
|
|
48
77
|
try {
|
|
49
|
-
names =
|
|
78
|
+
names = readdirSync(dir, { withFileTypes: true })
|
|
50
79
|
} catch {
|
|
51
80
|
return
|
|
52
81
|
}
|
|
@@ -54,8 +83,8 @@ async function walk(dir: string, keep: (rel: string, isDir: boolean) => boolean,
|
|
|
54
83
|
const abs = join(dir, d.name)
|
|
55
84
|
const rel = relative(base, abs)
|
|
56
85
|
if (d.isDirectory()) {
|
|
57
|
-
if (keep(rel, true)) await walk(abs, keep, out, base)
|
|
58
|
-
} else if (d.isFile() && keep(rel, false)) out.push(abs)
|
|
86
|
+
if (keep(rel, true)) await walk(abs, keep, out, base, scope)
|
|
87
|
+
} else if (d.isFile() && keep(rel, false) && (!scope || scope.covers(abs))) out.push(abs)
|
|
59
88
|
}
|
|
60
89
|
}
|
|
61
90
|
|
|
@@ -70,6 +99,7 @@ const shipkitKeep = (rel: string, isDir: boolean): boolean => {
|
|
|
70
99
|
}
|
|
71
100
|
|
|
72
101
|
const comfyKeep = (rel: string): boolean => COMFY_KEEP.some((k) => rel === k || rel.startsWith(`${k}${sep}`))
|
|
102
|
+
const comfyWalkKeep = (rel: string, isDir: boolean): boolean => (isDir ? COMFY_KEEP.some((k) => k === rel.split(sep)[0]) : comfyKeep(rel))
|
|
73
103
|
|
|
74
104
|
async function git(repo: string, args: string[]): Promise<string[]> {
|
|
75
105
|
const p = Bun.spawn(['git', '-C', repo, ...args], { stdout: 'pipe', stderr: 'ignore' })
|
|
@@ -84,6 +114,25 @@ export async function localFiles(repo: string): Promise<string[]> {
|
|
|
84
114
|
return names.filter((n) => basename(n) !== 'settings.local.json' && !CODE.test(n) && !n.split('/').some((p) => p === 'node_modules')).map((n) => join(repo, n))
|
|
85
115
|
}
|
|
86
116
|
|
|
117
|
+
/** a repo's kept `*.local.*` list with these heard paths read again: one `git check-ignore` of them, never the
|
|
118
|
+
* repo's walk (seconds in a repo with large ignored folders) */
|
|
119
|
+
export async function patchLocals(repo: string, files: readonly string[], heard: readonly string[]): Promise<string[]> {
|
|
120
|
+
const rels = heard.filter((p) => p.startsWith(`${repo}${sep}`) && isLocalName(p.slice(repo.length + 1))).map((p) => p.slice(repo.length + 1))
|
|
121
|
+
if (rels.length === 0) return [...files]
|
|
122
|
+
const p = Bun.spawn(['git', '-C', repo, 'check-ignore', '-z', '--stdin'], { stdin: 'pipe', stdout: 'pipe', stderr: 'ignore' })
|
|
123
|
+
p.stdin.write(rels.join('\0') + '\0')
|
|
124
|
+
await p.stdin.end()
|
|
125
|
+
const ignored = new Set((await new Response(p.stdout).text()).split('\0').filter((n) => n !== ''))
|
|
126
|
+
await p.exited
|
|
127
|
+
const out = new Set(files)
|
|
128
|
+
for (const rel of rels) {
|
|
129
|
+
const abs = join(repo, rel)
|
|
130
|
+
out.delete(abs)
|
|
131
|
+
if (ignored.has(rel) && lstatSync(abs, { throwIfNoEntry: false })?.isFile()) out.add(abs)
|
|
132
|
+
}
|
|
133
|
+
return [...out].sort()
|
|
134
|
+
}
|
|
135
|
+
|
|
87
136
|
/** the agents' config roots under the home: `.claude`, `.claude-<account>` */
|
|
88
137
|
async function agentRoots(home: string): Promise<string[]> {
|
|
89
138
|
const names = await readdir(home).catch(() => [] as string[])
|
|
@@ -100,6 +149,8 @@ export interface Collect {
|
|
|
100
149
|
locals?: (repo: string) => Promise<string[]>
|
|
101
150
|
/** each repo's `backup` key; by default its repo.config.ts, read again when the file moves */
|
|
102
151
|
backupOf?: (repo: string) => Promise<RepoBackup | null>
|
|
152
|
+
/** only the sources at or under these paths: what a full collect gives there, nothing else is read */
|
|
153
|
+
scope?: Scope
|
|
103
154
|
}
|
|
104
155
|
|
|
105
156
|
const configs = new Map<string, { mtime: number; backup: RepoBackup | null }>()
|
|
@@ -121,22 +172,25 @@ const WHOLE_DENY = /^(?:\.DS_Store)$|\.(?:pid|lock)$|-(?:wal|shm|journal)$/
|
|
|
121
172
|
|
|
122
173
|
/** every source the backup holds now, under the home folder, sorted by path */
|
|
123
174
|
export async function collect(o: Collect): Promise<Source[]> {
|
|
175
|
+
const scope = o.scope
|
|
124
176
|
const files: string[] = []
|
|
125
177
|
const add = (abs: string): void => void files.push(abs)
|
|
126
178
|
// the backup's own objects and records, and the pids, move by themselves: left out, else every run differs
|
|
127
179
|
const sqlite = new Map<string, SqliteCut>([
|
|
128
180
|
[mediaDbPath(), { tables: ['files', 'objects'], except: { objects: "key like 'backup/%'" } }],
|
|
129
|
-
|
|
181
|
+
// the Mac's own names stay out: a run restored on another Mac must not make it take this one's name
|
|
182
|
+
[machineDbPath(), { tables: null, except: { state: "name like 'pid:%' or name like 'backup-%' or name in ('machine-name', 'tailnet-name')" } }],
|
|
130
183
|
])
|
|
131
|
-
await walk(join(homeDir(), 'veille'), () => true, files)
|
|
184
|
+
await walk(join(homeDir(), 'veille'), () => true, files, undefined, scope)
|
|
132
185
|
add(join(o.home, ORDER_FILE))
|
|
133
|
-
await walk(join(o.home, MACHINE_PRIVATE), () => true, files)
|
|
134
|
-
for (const root of await agentRoots(o.home)) for (const repo of o.repos) await walk(join(root, sessionName(repo), 'memory'), () => true, files)
|
|
186
|
+
await walk(join(o.home, MACHINE_PRIVATE), () => true, files, undefined, scope)
|
|
187
|
+
for (const root of await agentRoots(o.home)) for (const repo of o.repos) await walk(join(root, sessionName(repo), 'memory'), () => true, files, undefined, scope)
|
|
188
|
+
const repos = scope ? o.repos.filter((r) => scope.reaches(r)) : o.repos
|
|
135
189
|
// the git walks of ignored trees take seconds each: all at once
|
|
136
|
-
const locals = new Map(await Promise.all(
|
|
190
|
+
const locals = new Map(await Promise.all(repos.map(async (r) => [r, await (o.locals ?? localFiles)(r)] as const)))
|
|
137
191
|
const whole = new Set<string>()
|
|
138
192
|
const extra: Source[] = []
|
|
139
|
-
for (const repo of
|
|
193
|
+
for (const repo of repos) {
|
|
140
194
|
let cfg: RepoBackup | null = null
|
|
141
195
|
try {
|
|
142
196
|
cfg = await (o.backupOf ?? backupOfRepo)(repo)
|
|
@@ -150,7 +204,7 @@ export async function collect(o: Collect): Promise<Source[]> {
|
|
|
150
204
|
const st = await lstat(abs).catch(() => null)
|
|
151
205
|
const got: string[] = []
|
|
152
206
|
if (st?.isFile()) got.push(abs)
|
|
153
|
-
else if (st?.isDirectory()) await walk(abs, (rel, isDir) => (isDir ? !['.git', 'node_modules'].includes(basename(rel)) : !WHOLE_DENY.test(basename(rel))), got)
|
|
207
|
+
else if (st?.isDirectory()) await walk(abs, (rel, isDir) => (isDir ? !['.git', 'node_modules'].includes(basename(rel)) : !WHOLE_DENY.test(basename(rel))), got, abs, scope)
|
|
154
208
|
else extra.push({ abs, rel: relative(o.home, abs), size: 0, mtime: 0, broken: `the repo's backup.paths names it and it is not on the disk` })
|
|
155
209
|
for (const f of got) if (!tracked.has(f)) {
|
|
156
210
|
files.push(f)
|
|
@@ -164,29 +218,121 @@ export async function collect(o: Collect): Promise<Source[]> {
|
|
|
164
218
|
for (const n of hits) sqlite.set(join(repo, n), { tables: null, ...(except ? { except } : {}) })
|
|
165
219
|
}
|
|
166
220
|
const mine: string[] = []
|
|
167
|
-
await walk(join(repo, '.shipkit'), shipkitKeep, mine)
|
|
168
|
-
await walk(join(repo, '.comfy-ts'),
|
|
221
|
+
await walk(join(repo, '.shipkit'), shipkitKeep, mine, undefined, scope)
|
|
222
|
+
await walk(join(repo, '.comfy-ts'), comfyWalkKeep, mine, undefined, scope)
|
|
169
223
|
for (const x of REPO_EXTRA) {
|
|
170
224
|
const abs = join(repo, x)
|
|
171
225
|
const st = await lstat(abs).catch(() => null)
|
|
172
226
|
if (st?.isFile()) mine.push(abs)
|
|
173
|
-
else if (st?.isDirectory()) await walk(abs, (rel, isDir) => isDir || !FILE_DENY.test(basename(rel)), mine)
|
|
227
|
+
else if (st?.isDirectory()) await walk(abs, (rel, isDir) => isDir || !FILE_DENY.test(basename(rel)), mine, abs, scope)
|
|
174
228
|
}
|
|
175
229
|
mine.push(...(locals.get(repo) ?? []))
|
|
176
230
|
for (const f of mine) if (!tracked.has(f)) files.push(f)
|
|
177
231
|
}
|
|
178
232
|
const out = new Map<string, Source>()
|
|
179
233
|
for (const abs of [...files, ...sqlite.keys()]) {
|
|
180
|
-
if (out.has(abs)) continue
|
|
181
|
-
const st =
|
|
234
|
+
if (out.has(abs) || (scope && !scope.covers(abs))) continue
|
|
235
|
+
const st = lstatSync(abs, { throwIfNoEntry: false })
|
|
182
236
|
if (!st?.isFile()) continue
|
|
183
237
|
const rel = relative(o.home, abs)
|
|
184
238
|
if (rel.startsWith('..') || rel === '') continue
|
|
185
239
|
const cut = sqlite.get(abs)
|
|
186
240
|
out.set(abs, { abs, rel, size: st.size, mtime: Math.floor(st.mtimeMs), ...(cut !== undefined ? { sqlite: cut } : whole.has(abs) ? { whole: true as const } : {}) })
|
|
187
241
|
}
|
|
188
|
-
for (const x of extra) out.set(`extra\0${x.rel}`, x)
|
|
189
|
-
return [...out.values()]
|
|
242
|
+
for (const x of extra) if (!scope || scope.covers(x.abs)) out.set(`extra\0${x.rel}`, x)
|
|
243
|
+
return sortSources([...out.values()])
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const sortSources = (list: Source[]): Source[] => list.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : a.broken === b.broken ? 0 : a.broken ? 1 : -1))
|
|
247
|
+
|
|
248
|
+
/** the paths a look reads again for these moved paths: a repo's config moving reads the whole repo again (its
|
|
249
|
+
* `backup` key may name other paths) */
|
|
250
|
+
export function scopeOf(moved: readonly string[], repos: readonly string[]): Scope {
|
|
251
|
+
const all = new Set(moved)
|
|
252
|
+
for (const p of moved) if (basename(p) === 'repo.config.ts' && repos.includes(dirname(p))) all.add(dirname(p))
|
|
253
|
+
return new Scope(all)
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** the last list with the moved paths read again: the list a full collect gives, at the cost of what moved (a
|
|
257
|
+
* repo's own sqlite keeps the size and time of the last full walk: snapshotted live at each run, out of the stamp) */
|
|
258
|
+
export async function refreshSources(prev: readonly Source[], moved: readonly string[], o: Collect): Promise<Source[]> {
|
|
259
|
+
// the home's databases are read at each look: two stats, and one that appears is held from its first run
|
|
260
|
+
const scope = scopeOf([...moved, mediaDbPath(), machineDbPath()], o.repos)
|
|
261
|
+
const fresh = await collect({ ...o, scope })
|
|
262
|
+
return sortSources([...prev.filter((s) => !scope.covers(s.abs)), ...fresh])
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** the sources of `full` that `held` lacks or holds another size or time of: what no event told (a sqlite moves by
|
|
266
|
+
* itself and is snapshotted on the clock) */
|
|
267
|
+
export function missedBy(held: readonly Source[], full: readonly Source[]): string[] {
|
|
268
|
+
const was = new Map(held.map((s) => [s.abs, s]))
|
|
269
|
+
return full.filter((s) => !s.sqlite && !s.broken && (was.get(s.abs)?.size !== s.size || was.get(s.abs)?.mtime !== s.mtime)).map((s) => s.rel)
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const isLocalName = (rel: string): boolean => {
|
|
273
|
+
const name = basename(rel)
|
|
274
|
+
return name.includes('.local.') && name !== 'settings.local.json' && !CODE.test(name) && !rel.split(sep).includes('node_modules')
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** a moved path the repo's `*.local.*` git walk must read again */
|
|
278
|
+
export const movesLocals = (abs: string, repos: readonly string[]): string | null => (isLocalName(abs) ? (repos.find((r) => abs.startsWith(`${r}${sep}`)) ?? null) : null)
|
|
279
|
+
|
|
280
|
+
/** a write in flight: an atomic write's temp file (`x.tmp`, `x.tmp.<pid>.<hex>`, `.STATUS.md.tmp-<n>`) or an editor's
|
|
281
|
+
* partial copy (`.!<pid>!x`). Its rename into place is heard on its own, so the watch never hears the temp: the gate
|
|
282
|
+
* writes one at each run */
|
|
283
|
+
export const isTransient = (name: string): boolean => /\.tmp(?:$|[-.])|^\.!\d+!/.test(name)
|
|
284
|
+
|
|
285
|
+
const isFileName = (name: string): boolean => /\.[^.]+$/.test(name) && !name.startsWith('.')
|
|
286
|
+
|
|
287
|
+
/** how the daemon's watch takes a path it hears: `due`, it could be a source or change which files are (the config's
|
|
288
|
+
* `backup` key, a `*.local.*` file); null, never a source (a denied folder, a status file, a rule's log): a path
|
|
289
|
+
* that moves by itself and makes the backup due would make it due forever */
|
|
290
|
+
export type Heard = 'due' | null
|
|
291
|
+
|
|
292
|
+
const due = (b: boolean): Heard => (b ? 'due' : null)
|
|
293
|
+
|
|
294
|
+
/** a path under a repo, as the watch hears it. A name with no extension is judged as a folder (`.shipkit/tmp` is
|
|
295
|
+
* denied as one), a name with one as a file */
|
|
296
|
+
export function repoPathHeard(rel: string, named: readonly string[] = []): Heard {
|
|
297
|
+
if (rel === '') return null
|
|
298
|
+
if (rel === 'repo.config.ts') return 'due'
|
|
299
|
+
const parts = rel.split(sep)
|
|
300
|
+
// a worktree under `.claude/worktrees/` is a checkout of its own: the repo's git walk never enters it
|
|
301
|
+
if (parts.includes('.git') || parts.includes('node_modules') || (parts[0] === '.claude' && parts[1] === 'worktrees')) return null
|
|
302
|
+
for (const p of named) if (rel === p || rel.startsWith(`${p}${sep}`) || p.startsWith(`${rel}${sep}`)) return due(!WHOLE_DENY.test(basename(rel)))
|
|
303
|
+
if (isLocalName(rel)) return 'due'
|
|
304
|
+
const name = parts[parts.length - 1]!
|
|
305
|
+
const asItem = (keep: (r: string, isDir: boolean) => boolean, under: string[]): boolean => {
|
|
306
|
+
if (under.length === 0) return true
|
|
307
|
+
for (let i = 1; i < under.length; i++) if (!keep(under.slice(0, i).join(sep), true)) return false
|
|
308
|
+
const r = under.join(sep)
|
|
309
|
+
return isFileName(name) ? keep(r, false) : keep(r, true)
|
|
310
|
+
}
|
|
311
|
+
if (parts[0] === '.shipkit') return due(asItem(shipkitKeep, parts.slice(1)))
|
|
312
|
+
if (parts[0] === '.comfy-ts') return due(asItem(comfyWalkKeep, parts.slice(1)))
|
|
313
|
+
for (const x of REPO_EXTRA) if (rel === x || rel.startsWith(`${x}${sep}`) || x.startsWith(`${rel}${sep}`)) return due(!FILE_DENY.test(name))
|
|
314
|
+
return null
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** what the daemon watches: each root, whether it reads its tree, and which paths under it count. A root missing
|
|
318
|
+
* when the watch starts is left to the safety walk */
|
|
319
|
+
export interface WatchRoot {
|
|
320
|
+
dir: string
|
|
321
|
+
recursive: boolean
|
|
322
|
+
heard: (rel: string) => Heard
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** `named` gives a repo's `backup.paths` as the last look read them: asked at each event, so a new name counts at once */
|
|
326
|
+
export async function watchRoots(home: string, repos: readonly string[], named: (repo: string) => readonly string[] = () => []): Promise<WatchRoot[]> {
|
|
327
|
+
const order = join(home, ORDER_FILE)
|
|
328
|
+
const memory = new Set(repos.map(sessionName))
|
|
329
|
+
return [
|
|
330
|
+
{ dir: join(homeDir(), 'veille'), recursive: true, heard: () => 'due' },
|
|
331
|
+
{ dir: join(home, MACHINE_PRIVATE), recursive: true, heard: () => 'due' },
|
|
332
|
+
{ dir: dirname(order), recursive: false, heard: (rel) => due(rel === basename(order)) },
|
|
333
|
+
...(await agentRoots(home)).map((dir): WatchRoot => ({ dir, recursive: true, heard: (rel) => { const [repo, folder] = rel.split(sep); return due(memory.has(repo ?? '') && (folder === undefined || folder === 'memory')) } })),
|
|
334
|
+
...repos.map((r): WatchRoot => ({ dir: r, recursive: true, heard: (rel) => repoPathHeard(rel, named(r)) })),
|
|
335
|
+
]
|
|
190
336
|
}
|
|
191
337
|
|
|
192
338
|
/** a cheap stamp of the sources that are files (a sqlite moves every few seconds; its snapshot runs on the clock) */
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// the daemon's watch of the backup's sources: a path it hears that could be a source (`watchRoots`) is noted, and the
|
|
2
|
+
// next look reads only the noted paths again. The callback only notes: the loop answers every page. A clean stop hands
|
|
3
|
+
// what it heard to the next daemon (a reload in place); a daemon that did not stop cleanly starts with a full walk
|
|
4
|
+
import { watch, type FSWatcher } from 'node:fs'
|
|
5
|
+
import { basename, join } from 'node:path'
|
|
6
|
+
import { machineDelete, machineGet, machineSet } from '../../core/machine-db.ts'
|
|
7
|
+
import { backupDue, BATCH, NAMED, type Batch } from './daemon.ts'
|
|
8
|
+
import { isTransient, watchRoots } from './sources.ts'
|
|
9
|
+
|
|
10
|
+
/** what a stopping daemon heard and no look took yet, for the next one */
|
|
11
|
+
const HELD = 'backup-heard'
|
|
12
|
+
/** a stop this recent is a hand over (a reload in place): the next daemon takes what it heard, else it walks */
|
|
13
|
+
export const HANDOVER_MS = 60_000
|
|
14
|
+
/** past this many paths, the next look walks every source */
|
|
15
|
+
export const MAX_PATHS = 2_000
|
|
16
|
+
|
|
17
|
+
type Held = { at: number; paths: string[]; all: boolean }
|
|
18
|
+
|
|
19
|
+
export interface BackupWatchOptions {
|
|
20
|
+
home: string
|
|
21
|
+
/** the house repos, archived ones included */
|
|
22
|
+
repos: readonly string[]
|
|
23
|
+
now?: () => number
|
|
24
|
+
printErr?: (l: string) => void
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class BackupWatch {
|
|
28
|
+
private readonly heard = new Set<string>()
|
|
29
|
+
/** the next look walks every source */
|
|
30
|
+
private all = false
|
|
31
|
+
/** a watch stopped: every look walks, as with no watch */
|
|
32
|
+
private blind = false
|
|
33
|
+
private named: Record<string, string[]> = {}
|
|
34
|
+
private readonly watchers: FSWatcher[] = []
|
|
35
|
+
private readonly now: () => number
|
|
36
|
+
|
|
37
|
+
constructor(private readonly o: BackupWatchOptions) {
|
|
38
|
+
this.now = o.now ?? Date.now
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** no watch at all: every look walks every source, as before there was one */
|
|
42
|
+
blindly(): this {
|
|
43
|
+
this.blind = true
|
|
44
|
+
return this
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async start(): Promise<this> {
|
|
48
|
+
const held = machineGet<Held>(HELD)
|
|
49
|
+
machineDelete(HELD)
|
|
50
|
+
if (held != null && this.now() - held.at <= HANDOVER_MS) {
|
|
51
|
+
for (const p of held.paths) this.heard.add(p)
|
|
52
|
+
this.all = held.all
|
|
53
|
+
} else this.all = true
|
|
54
|
+
this.named = machineGet<Record<string, string[]>>(NAMED) ?? {}
|
|
55
|
+
for (const root of await watchRoots(this.o.home, this.o.repos, (r) => this.named[r] ?? [])) {
|
|
56
|
+
let w: FSWatcher
|
|
57
|
+
try {
|
|
58
|
+
w = watch(root.dir, { recursive: root.recursive }, (_event, name) => {
|
|
59
|
+
if (this.all) return
|
|
60
|
+
// no name, or the root itself: the system says its tree changed in ways it did not list
|
|
61
|
+
const rel = name == null ? '' : String(name)
|
|
62
|
+
if (rel === '') return void (this.all = true)
|
|
63
|
+
if (isTransient(basename(rel)) || root.heard(rel) == null) return
|
|
64
|
+
if (this.heard.size >= MAX_PATHS) {
|
|
65
|
+
this.all = true
|
|
66
|
+
this.heard.clear()
|
|
67
|
+
} else this.heard.add(join(root.dir, rel))
|
|
68
|
+
})
|
|
69
|
+
} catch {
|
|
70
|
+
// a root not on the disk yet: the safety walk finds what lands there
|
|
71
|
+
continue
|
|
72
|
+
}
|
|
73
|
+
w.on('error', (e) => {
|
|
74
|
+
if (!this.blind) this.o.printErr?.(`WARN backup: the watch of ${root.dir} stopped (${(e as Error).message}): each look walks every source until the daemon reloads`)
|
|
75
|
+
this.blind = true
|
|
76
|
+
})
|
|
77
|
+
this.watchers.push(w)
|
|
78
|
+
}
|
|
79
|
+
return this
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** the paths heard since the last look, for a test or a probe */
|
|
83
|
+
pending(): { paths: string[]; all: boolean } {
|
|
84
|
+
return { paths: [...this.heard].sort(), all: this.all || this.blind }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** the daemon's look: a few reads of the machine db, never a walk. When due, the paths heard go to the look it
|
|
88
|
+
* starts, with those of a look that did not finish */
|
|
89
|
+
due(now: number): boolean {
|
|
90
|
+
this.named = machineGet<Record<string, string[]>>(NAMED) ?? this.named
|
|
91
|
+
if (!backupDue(now, this.all || this.blind || this.heard.size > 0)) return false
|
|
92
|
+
const was = machineGet<Batch>(BATCH)
|
|
93
|
+
const undone = was?.done === false ? was : null
|
|
94
|
+
const paths = [...new Set([...(undone?.paths ?? []), ...this.heard])]
|
|
95
|
+
const all = this.all || this.blind || (undone?.all ?? false) || paths.length > MAX_PATHS
|
|
96
|
+
machineSet(BATCH, { paths: all ? [] : paths.sort(), all, done: false } satisfies Batch)
|
|
97
|
+
this.heard.clear()
|
|
98
|
+
this.all = false
|
|
99
|
+
return true
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
stop(): void {
|
|
103
|
+
for (const w of this.watchers.splice(0)) w.close()
|
|
104
|
+
machineSet(HELD, { at: this.now(), paths: [...this.heard], all: this.all || this.blind } satisfies Held)
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
// the daemon's media job (wiki tools/shipkit/media-store.md, The daemon): one pass, in a child process the daemon
|
|
2
|
-
// starts
|
|
3
|
-
// index once its store moved, what waits sent up, and (when the owner turned it on) the disk purged under
|
|
4
|
-
// Each failure is one line in the daemon's log
|
|
5
|
-
import { existsSync } from 'node:fs'
|
|
2
|
+
// starts when `mediaDue` says so (home/daemon-jobs.ts), never on its loop. Every kind of every house repo scanned into
|
|
3
|
+
// the machine index once its store moved, what waits sent up, and (when the owner turned it on) the disk purged under
|
|
4
|
+
// 40 GB free. Each failure is one line in the daemon's log
|
|
5
|
+
import { existsSync, statSync } from 'node:fs'
|
|
6
|
+
import { resolve } from 'node:path'
|
|
6
7
|
import { machineGet, machineSet } from '../core/machine-db.ts'
|
|
7
8
|
import type { MediaKind } from './kind.ts'
|
|
8
9
|
import { FREE_MIN_BYTES, freeBytes, purge, purgeCandidates, windowDays } from './purge.ts'
|
|
@@ -11,6 +12,8 @@ import { syncKind } from './sync.ts'
|
|
|
11
12
|
import { mb, uploadWaiting } from './upload.ts'
|
|
12
13
|
|
|
13
14
|
export const MEDIA_EVERY_MS = 30_000
|
|
15
|
+
/** a pass that found nothing to do: the next one this much later, unless a store's folder moves first */
|
|
16
|
+
export const MEDIA_QUIET_MS = 5 * 60_000
|
|
14
17
|
const PURGE_EVERY_MS = 10 * 60_000
|
|
15
18
|
const AUTO_KEY = 'media-purge-auto'
|
|
16
19
|
|
|
@@ -22,17 +25,34 @@ export const setAutoPurge = (on: boolean): boolean => machineSet(AUTO_KEY, on)
|
|
|
22
25
|
const SYNCED = 'media-synced'
|
|
23
26
|
const PURGED_AT = 'media-purged-at'
|
|
24
27
|
const NO_SPACE = 'media-no-space'
|
|
28
|
+
/** when the next pass is due, and the folders whose move brings it sooner */
|
|
29
|
+
const NEXT = 'media-next'
|
|
30
|
+
|
|
31
|
+
type Next = { at: number; since: number; dirs: string[] }
|
|
32
|
+
|
|
33
|
+
/** the daemon's look, in its own process: a stat of each store folder, never a walk. Due at the time the last pass
|
|
34
|
+
* named, or as soon as a store's folder moved since that pass began (a new card, a new take) */
|
|
35
|
+
export function mediaDue(now: number): boolean {
|
|
36
|
+
const n = machineGet<Next>(NEXT)
|
|
37
|
+
if (n == null || now >= n.at) return true
|
|
38
|
+
return n.dirs.some((d) => (statSync(d, { throwIfNoEntry: false })?.mtimeMs ?? 0) > n.since)
|
|
39
|
+
}
|
|
25
40
|
|
|
26
41
|
/** one pass of the daemon's media job, in its child process: what `startMediaStore` does each tick, with what it
|
|
27
42
|
* remembers in the machine db */
|
|
28
|
-
export async function mediaTick(o: { roots: string[]; kinds: () => readonly MediaKind[]; print: (l: string) => void; printErr: (l: string) => void }): Promise<void> {
|
|
43
|
+
export async function mediaTick(o: { roots: string[]; kinds: () => readonly MediaKind[]; print: (l: string) => void; printErr: (l: string) => void; now?: () => number }): Promise<void> {
|
|
44
|
+
const now = o.now ?? Date.now
|
|
45
|
+
const since = now()
|
|
29
46
|
const synced = machineGet<Record<string, string>>(SYNCED) ?? {}
|
|
47
|
+
const kinds = o.kinds()
|
|
30
48
|
const stores = o.roots.flatMap((root) =>
|
|
31
|
-
|
|
49
|
+
kinds.flatMap((kind) => {
|
|
32
50
|
const dir = kind.storeOf(root)
|
|
33
51
|
return dir && existsSync(dir) ? [{ kind, root, dir }] : []
|
|
34
52
|
}),
|
|
35
53
|
)
|
|
54
|
+
// work done or left: the next pass at the usual period, else after the quiet one
|
|
55
|
+
let busy = false
|
|
36
56
|
try {
|
|
37
57
|
let moved = false
|
|
38
58
|
for (const { kind, root, dir } of stores) {
|
|
@@ -44,8 +64,10 @@ export async function mediaTick(o: { roots: string[]; kinds: () => readonly Medi
|
|
|
44
64
|
// files left to hash: the next pass goes on with them
|
|
45
65
|
synced[id] = r.left > 0 ? '' : stamp
|
|
46
66
|
moved = true
|
|
67
|
+
if (r.filled > 0 || r.left > 0) busy = true
|
|
47
68
|
if (r.filled > 0) o.print(`ok: media store: ${r.filled} ${kind.kind} files of ${root} hashed${r.left > 0 ? `, ${r.left} to go` : ''}`)
|
|
48
69
|
} catch (e) {
|
|
70
|
+
busy = true
|
|
49
71
|
o.printErr(`WARN media store: the ${kind.kind} files of ${root} did not sync: ${(e as Error).message}`)
|
|
50
72
|
}
|
|
51
73
|
}
|
|
@@ -59,10 +81,11 @@ export async function mediaTick(o: { roots: string[]; kinds: () => readonly Medi
|
|
|
59
81
|
}
|
|
60
82
|
machineSet(NO_SPACE, '')
|
|
61
83
|
const up = await uploadWaiting(space, { limit: 200, jobs: 3 })
|
|
84
|
+
if (up.up + up.there + up.failed.length > 0) busy = true
|
|
62
85
|
if (up.up + up.there > 0) o.print(`ok: media store: ${up.up} up (${mb(up.bytes)})${up.there > 0 ? `, ${up.there} already there` : ''}`)
|
|
63
86
|
if (up.failed.length > 0) o.printErr(`WARN media store: ${up.failed.length} uploads failed, tried again later; first: ${up.failed[0]?.key}: ${up.failed[0]?.error}`)
|
|
64
|
-
if (autoPurgeOn() &&
|
|
65
|
-
machineSet(PURGED_AT,
|
|
87
|
+
if (autoPurgeOn() && now() - (machineGet<number>(PURGED_AT) ?? 0) > PURGE_EVERY_MS) {
|
|
88
|
+
machineSet(PURGED_AT, now())
|
|
66
89
|
for (const { kind, root, dir } of stores) {
|
|
67
90
|
if (freeBytes(dir) >= FREE_MIN_BYTES) continue
|
|
68
91
|
const { candidates } = await purgeCandidates(kind, dir, { olderDays: windowDays(freeBytes(dir)) })
|
|
@@ -72,6 +95,11 @@ export async function mediaTick(o: { roots: string[]; kinds: () => readonly Medi
|
|
|
72
95
|
}
|
|
73
96
|
}
|
|
74
97
|
} catch (e) {
|
|
98
|
+
busy = true
|
|
75
99
|
o.printErr(`WARN media store: the pass broke: ${(e as Error).message}`)
|
|
100
|
+
} finally {
|
|
101
|
+
// a store that is the repo itself (a hand label) moves with every save there: the index is its record
|
|
102
|
+
const dirs = [...new Set(stores.filter((s) => resolve(s.dir) !== resolve(s.root)).map((s) => s.dir))]
|
|
103
|
+
machineSet(NEXT, { at: since + (busy ? MEDIA_EVERY_MS : MEDIA_QUIET_MS), since, dirs } satisfies Next)
|
|
76
104
|
}
|
|
77
105
|
}
|
package/src/media-store/hand.ts
CHANGED
|
@@ -36,9 +36,11 @@ const rowsOf = (label: string, store: string): { item: string; name: string; key
|
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
export function handKind(label: string): MediaKind {
|
|
39
|
+
// read once per kind: a pass asks it for every house repo, and each read scans the whole files table
|
|
40
|
+
let held: string[] | null = null
|
|
39
41
|
return {
|
|
40
42
|
kind: label,
|
|
41
|
-
storeOf: (root) => (storesOf(label).includes(resolve(root)) ? resolve(root) : null),
|
|
43
|
+
storeOf: (root) => ((held ??= storesOf(label)).includes(resolve(root)) ? resolve(root) : null),
|
|
42
44
|
// the index is the record: read it again every 10 min, to see a file the disk let go
|
|
43
45
|
stamp: () => String(Math.floor(Date.now() / 600_000)),
|
|
44
46
|
async scan(store) {
|