rvlib-shipkit 2.12.0 → 2.13.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 +48 -13
- package/README.md +1 -1
- package/package.json +4 -2
- package/src/agent-time/store.ts +2 -2
- package/src/check.ts +1 -1
- package/src/checks/SK001-package-json-shape.check.ts +4 -0
- package/src/checks/SK003-claude-md-shape.check.ts +1 -1
- package/src/checks/SK004-gitignore-policy.check.ts +27 -2
- package/src/checks/SK005-rvlib-versions.check.ts +1 -1
- package/src/checks/SK008-reviewer-agent.check.ts +2 -2
- package/src/checks/SK012-config-barrel-import.check.ts +1 -1
- package/src/checks/SK015-nested-repo.check.ts +1 -1
- package/src/checks/SK035-public-clean.check.ts +46 -0
- package/src/checks/SK036-draft-media-size.check.ts +28 -0
- package/src/cli/cmd_Backup.ts +152 -0
- package/src/cli/cmd_Ci.ts +8 -11
- package/src/cli/cmd_Drill.ts +145 -0
- package/src/cli/cmd_Home.ts +50 -3
- package/src/cli/cmd_Media.ts +7 -5
- package/src/cli/cmd_Review.ts +4 -2
- package/src/cli/cmd_Shot.ts +5 -2
- package/src/cli/cmd_Smoke.ts +4 -1
- package/src/cli/cmd_Social.ts +226 -0
- package/src/cli/cmd_Start.ts +1 -1
- package/src/cli/cmd_Time.ts +1 -1
- package/src/cli/cmd_Trailer.ts +5 -2
- package/src/cli/cmd_Veille.ts +173 -0
- package/src/cli/family-pages.ts +3 -0
- package/src/cli/registry.ts +13 -2
- package/src/cli.ts +5 -2
- package/src/collections/actions.ts +1 -49
- package/src/collections/checks.ts +2 -1
- package/src/collections/collection-types.ts +11 -2
- package/src/collections/providers.ts +4 -4
- package/src/collections/review.ts +2 -1
- package/src/collections/tests.ts +19 -8
- package/src/contracts/apply-contracts.ts +1 -3
- package/src/contracts/contract-manifests.ts +2 -3
- package/src/contracts/contract-types.ts +0 -1
- package/src/contracts/contracts-engine.ts +0 -3
- package/src/core/app-icon.ts +9 -3
- package/src/core/bun-builtins.ts +2 -2
- package/src/core/discover-checks.ts +37 -5
- package/src/core/fix-scope.ts +4 -2
- package/src/core/floor-resolve.ts +68 -48
- package/src/core/floor.ts +9 -0
- package/src/core/git-root.ts +24 -0
- package/src/core/last-good.ts +3 -1
- package/src/core/layout.ts +8 -0
- package/src/core/log-stamp.ts +36 -0
- package/src/core/loop-watch.ts +93 -0
- package/src/core/machine-link.ts +134 -0
- package/src/core/memory-watch.ts +41 -0
- package/src/core/one-way-in-policy.ts +27 -19
- package/src/core/run-ci.ts +6 -8
- package/src/core/run-fixers.ts +9 -9
- package/src/core/slots.ts +21 -0
- package/src/core/tree-rev.ts +60 -0
- package/src/core/unit-files.ts +42 -0
- package/src/drill/render.ts +140 -0
- package/src/drill/run.ts +269 -0
- package/src/fleet/scan-fleet.ts +6 -5
- package/src/home/daemon-jobs.ts +201 -0
- package/src/home/global-context.ts +34 -1
- package/src/home/home-routes.ts +22 -15
- package/src/home/hubs.ts +10 -3
- package/src/home/inbox-shape.ts +53 -4
- package/src/home/inbox.ts +16 -1
- package/src/home/lib-watch.ts +10 -3
- package/src/home/machine-stores.ts +15 -29
- package/src/home/run-daemon.ts +15 -18
- package/src/home/run-pm.ts +2 -0
- package/src/home/serve-daemon.ts +4 -3
- package/src/home/serve-web.ts +104 -1
- package/src/hooks/commit-message.ts +28 -19
- package/src/hooks/leak-guard.ts +10 -3
- package/src/hooks/run-hooks.ts +2 -6
- package/src/identities/identities.ts +334 -0
- package/src/identities/machine-route.ts +126 -0
- package/src/identities/machine.ts +62 -0
- package/src/init-repo.ts +1 -1
- package/src/ledger/check-stats.ts +10 -9
- package/src/ledger/gate-checks.ts +32 -1
- package/src/ledger/record-kept.ts +112 -0
- package/src/ledger/repo-view.ts +10 -0
- package/src/ledger/run-log.ts +17 -12
- package/src/ledger/run-timeline.ts +8 -4
- package/src/ledger/store.ts +7 -0
- package/src/ledger/suite-log.ts +17 -13
- package/src/media-kinds.ts +2 -1
- package/src/media-store/backup/daemon.ts +73 -0
- package/src/media-store/backup/keys.ts +25 -0
- package/src/media-store/backup/manifest.ts +193 -0
- package/src/media-store/backup/restore.ts +192 -0
- package/src/media-store/backup/run.ts +278 -0
- package/src/media-store/backup/secret.ts +86 -0
- package/src/media-store/backup/snapshot.ts +64 -0
- package/src/media-store/backup/sources.ts +199 -0
- package/src/media-store/daemon.ts +56 -70
- package/src/media-store/put.ts +4 -2
- package/src/media-store/space.ts +23 -4
- package/src/pages/forward.ts +35 -0
- package/src/pages/frame-client.ts +118 -0
- package/src/pages/routes.ts +29 -0
- package/src/pages/unit.ts +92 -0
- package/src/plan/planner.ts +12 -0
- package/src/plan/repo-source.ts +19 -5
- package/src/reflect/transcript.ts +35 -10
- package/src/release/public-clean.ts +301 -0
- package/src/release/published-here.ts +22 -0
- package/src/release/run-bump.ts +2 -1
- package/src/release/run-release.ts +4 -1
- package/src/repo-config.ts +53 -2
- package/src/review/http.ts +16 -2
- package/src/review/model.ts +15 -4
- package/src/review/notes.ts +77 -0
- package/src/review/project.ts +6 -38
- package/src/review/routes.ts +4 -12
- package/src/review/store.ts +41 -1
- package/src/review/trailer-media.ts +7 -4
- package/src/review/trailer-shots.ts +21 -4
- package/src/review/unit.ts +1 -1
- package/src/scaffold/files/agent-handoff.md +3 -0
- package/src/scaffold/files/agent-index.md +4 -12
- package/src/scaffold/project-scaffold.ts +5 -4
- package/src/serve/embed.ts +1 -1
- package/src/serve/hub-app/col-card.tsx +3 -17
- package/src/serve/hub-app/col-tables-view.tsx +2 -1
- package/src/serve/hub-app/cols-svc.ts +0 -13
- package/src/serve/hub-app/dock-st.ts +4 -2
- package/src/serve/hub-app/dock-view.tsx +2 -0
- package/src/serve/hub-app/frames-st.ts +35 -0
- package/src/serve/hub-app/hash-route.ts +64 -1
- package/src/serve/hub-app/home-st.ts +31 -7
- package/src/serve/hub-app/home-strip.css +9 -1
- package/src/serve/hub-app/home-strip.tsx +7 -6
- package/src/serve/hub-app/home.html +5 -0
- package/src/serve/hub-app/hub-app.tsx +49 -5
- package/src/serve/hub-app/hub.css +29 -11
- package/src/serve/hub-app/icons.tsx +16 -1
- package/src/serve/hub-app/identities-st.ts +210 -0
- package/src/serve/hub-app/identities-view.tsx +352 -0
- package/src/serve/hub-app/identities.css +48 -0
- package/src/serve/hub-app/identity-address.ts +52 -0
- package/src/serve/hub-app/inbox-st.ts +59 -6
- package/src/serve/hub-app/inbox-view.tsx +48 -6
- package/src/serve/hub-app/inbox.css +12 -1
- package/src/serve/hub-app/index.html +3 -0
- package/src/serve/hub-app/keys.ts +10 -2
- package/src/serve/hub-app/list-walk.ts +89 -0
- package/src/serve/hub-app/machine-st.ts +12 -0
- package/src/serve/hub-app/media-view.tsx +2 -1
- package/src/serve/hub-app/pages-frames.tsx +134 -0
- package/src/serve/hub-app/pages-svc.ts +111 -0
- package/src/serve/hub-app/palette-st.ts +18 -3
- package/src/serve/hub-app/palette-view.tsx +9 -2
- package/src/serve/hub-app/planned-view.tsx +2 -1
- package/src/serve/hub-app/project-list.css +18 -14
- package/src/serve/hub-app/project-list.tsx +88 -49
- package/src/serve/hub-app/projects-svc.ts +33 -3
- package/src/serve/hub-app/repo-sections.ts +19 -2
- package/src/serve/hub-app/repo-st.ts +75 -19
- package/src/serve/hub-app/review/review-cells.tsx +3 -3
- package/src/serve/hub-app/review/review-kit.ts +30 -7
- package/src/serve/hub-app/review/review-page.tsx +1 -1
- package/src/serve/hub-app/review/review-st.ts +19 -8
- package/src/serve/hub-app/review/review-thread.tsx +11 -9
- package/src/serve/hub-app/review/review-views.tsx +84 -19
- package/src/serve/hub-app/review/thread-st.ts +1 -10
- package/src/serve/hub-app/review/trailer-page.tsx +2 -1
- package/src/serve/hub-app/review.css +17 -8
- package/src/serve/hub-app/site/site-part.tsx +173 -0
- package/src/serve/hub-app/site/site-st.ts +157 -0
- package/src/serve/hub-app/site.css +35 -0
- package/src/serve/hub-app/social/calendar.tsx +182 -0
- package/src/serve/hub-app/social/comms-page.tsx +306 -0
- package/src/serve/hub-app/social/kit.tsx +244 -0
- package/src/serve/hub-app/social/post-card.tsx +456 -0
- package/src/serve/hub-app/social/problems.tsx +60 -0
- package/src/serve/hub-app/social/social-model.ts +154 -0
- package/src/serve/hub-app/social/social-page.tsx +674 -0
- package/src/serve/hub-app/social/social-st.ts +986 -0
- package/src/serve/hub-app/social.css +289 -0
- package/src/serve/hub-app/stores/stores-page.tsx +311 -0
- package/src/serve/hub-app/stores/stores-st.ts +286 -0
- package/src/serve/hub-app/stores.css +54 -0
- package/src/serve/hub-app/timeline-geometry.ts +1 -1
- package/src/serve/hub-app/timeline-view.tsx +3 -2
- package/src/serve/hub-app/tree-build.ts +6 -0
- package/src/serve/hub-app/tree-row.tsx +27 -4
- package/src/serve/hub-app/tree-svc.ts +18 -49
- package/src/serve/hub-app/veille/veille-page.tsx +514 -0
- package/src/serve/hub-app/veille/veille-st.ts +443 -0
- package/src/serve/hub-app/veille.css +84 -0
- package/src/serve/hub-runtime.ts +14 -9
- package/src/serve/project-gutter-route.ts +44 -12
- package/src/serve/run-lanes.ts +7 -4
- package/src/serve/same-origin.ts +1 -1
- package/src/serve/serve-hub.ts +20 -12
- package/src/serve/tracked-watch.ts +24 -3
- package/src/serve/warm-cell.ts +5 -1
- package/src/shipkit-files.ts +15 -4
- package/src/shipkit.ts +0 -1
- package/src/shot/box.ts +162 -0
- package/src/shot/browser-slot.ts +62 -0
- package/src/shot/client.ts +43 -7
- package/src/shot/clip-encoder.ts +93 -12
- package/src/shot/film-box.ts +188 -0
- package/src/shot/shooter.ts +50 -15
- package/src/shot/shot-ask.ts +10 -2
- package/src/shot/stepped-clip.ts +5 -4
- package/src/site/desk.ts +242 -0
- package/src/site/routes.ts +66 -0
- package/src/site/unit.ts +62 -0
- package/src/social/brands.ts +22 -0
- package/src/social/compose.ts +97 -0
- package/src/social/desk-index.ts +123 -0
- package/src/social/desk-wire.ts +64 -0
- package/src/social/drafts.ts +183 -0
- package/src/social/house.ts +24 -0
- package/src/social/load.ts +319 -0
- package/src/social/md.ts +70 -0
- package/src/social/media-facts.ts +53 -0
- package/src/social/media-kind.ts +189 -0
- package/src/social/media-limit.ts +42 -0
- package/src/social/media-of.ts +30 -0
- package/src/social/migrate.ts +123 -0
- package/src/social/open.ts +17 -0
- package/src/social/post-url.ts +158 -0
- package/src/social/presence.ts +332 -0
- package/src/social/public-read.ts +53 -0
- package/src/social/publish/bluesky.ts +168 -0
- package/src/social/publish/discord.ts +76 -0
- package/src/social/publish/index.ts +24 -0
- package/src/social/publish/secret.ts +13 -0
- package/src/social/push.ts +31 -0
- package/src/social/richtext.ts +37 -0
- package/src/social/routes.ts +180 -0
- package/src/social/stats.ts +134 -0
- package/src/social/text.ts +267 -0
- package/src/social/tracker-route.ts +39 -0
- package/src/social/tracker.ts +255 -0
- package/src/social/unit.ts +53 -0
- package/src/social/writes.ts +130 -0
- package/src/start-repo.ts +14 -9
- package/src/stores/collection.ts +27 -0
- package/src/stores/desk.ts +336 -0
- package/src/stores/model.ts +187 -0
- package/src/stores/routes.ts +126 -0
- package/src/stores/unit.ts +57 -0
- package/src/suite/calibrate.ts +127 -0
- package/src/suite/core-counters.ts +91 -0
- package/src/suite/judge-suites.ts +94 -34
- package/src/suite/suite-cli.ts +44 -10
- package/src/suite/suite-cpu-preload.ts +34 -9
- package/src/trailer/adapter.ts +4 -0
- package/src/trailer/build.ts +42 -11
- package/src/trailer/ffmpeg.ts +11 -0
- package/src/trailer/footage.ts +30 -13
- package/src/trailer/grammar.ts +18 -2
- package/src/trailer/graph.ts +28 -6
- package/src/trailer/passage.ts +17 -5
- package/src/trailer/plan.ts +74 -3
- package/src/trailer/stitch.ts +67 -26
- package/src/trailer/url.ts +1 -1
- package/src/trailer/versions.ts +24 -0
- package/src/ts/gate-typecheck.ts +32 -0
- package/src/ts/typecheck-cli.ts +9 -11
- package/src/tui/tui-app.tsx +0 -1
- package/src/veille/asks.ts +155 -0
- package/src/veille/auto.ts +31 -0
- package/src/veille/batch.ts +27 -0
- package/src/veille/chrome.ts +127 -0
- package/src/veille/collection.ts +28 -0
- package/src/veille/desk.ts +242 -0
- package/src/veille/identity.ts +80 -0
- package/src/veille/import.ts +68 -0
- package/src/veille/log.ts +183 -0
- package/src/veille/platforms.ts +118 -0
- package/src/veille/reads.ts +66 -0
- package/src/veille/replied.ts +110 -0
- package/src/veille/routes.ts +185 -0
- package/src/veille/service.ts +81 -0
- package/src/veille/watch.ts +116 -0
- package/src/veille/worth.ts +46 -0
- package/src/wiki/scan-md.ts +18 -0
- package/src/collections/posts.ts +0 -142
- package/src/contracts/manifests/social.contract.ts +0 -20
- package/src/scaffold/files/agent-coding.md +0 -35
- package/src/ts/typecheck-cache.ts +0 -11
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
// A BACKUP RUN (wiki build/shipkit/media-store.md, Backup): every source read once, refused or hashed (a sqlite
|
|
2
|
+
// snapshotted first), each object the Space lacks sent from the bytes that were hashed (never
|
|
3
|
+
// the live file again: it may have moved), then the run's parts the Space lacks, then the run itself, last, so a run
|
|
4
|
+
// never names an object the Space lacks. A run whose state equals the last one writes nothing. The objects are never
|
|
5
|
+
// deleted: every version stays
|
|
6
|
+
import { constants, copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
7
|
+
import { hostname, tmpdir } from 'node:os'
|
|
8
|
+
import { basename, dirname, join, relative } from 'node:path'
|
|
9
|
+
import { homeDir } from '../../home/home-paths.ts'
|
|
10
|
+
import { gzipSync } from 'node:zlib'
|
|
11
|
+
import { machineGet, machineSet } from '../../core/machine-db.ts'
|
|
12
|
+
import { mediaKey } from '../content.ts'
|
|
13
|
+
import { isUp } from '../remote.ts'
|
|
14
|
+
import type { Space } from '../space.ts'
|
|
15
|
+
import { uploadOne } from '../upload.ts'
|
|
16
|
+
import { BACKUP_LABEL, runKey } from './keys.ts'
|
|
17
|
+
import { digestOf, encodeRun, readManifest, readRunHead, runAt, type Entry, type Refused } from './manifest.ts'
|
|
18
|
+
import { fileRefusal, refusal } from './secret.ts'
|
|
19
|
+
import { snapshotSqlite } from './snapshot.ts'
|
|
20
|
+
import { collect, type Collect, type Source } from './sources.ts'
|
|
21
|
+
|
|
22
|
+
const LAST = 'backup-last'
|
|
23
|
+
/** the files named whole, by path: their size, time, sha and key, so an unchanged archive is never read again */
|
|
24
|
+
const SEEN = 'backup-seen'
|
|
25
|
+
|
|
26
|
+
export interface Last {
|
|
27
|
+
key: string
|
|
28
|
+
digest: string
|
|
29
|
+
at: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
type Seen = Record<string, { size: number; mtime: number; sha: string; key: string }>
|
|
33
|
+
|
|
34
|
+
export const lastRun = (): Last | null => machineGet<Last>(LAST)
|
|
35
|
+
|
|
36
|
+
const sha256 = (b: Uint8Array): string => new Bun.CryptoHasher('sha256').update(b).digest('hex')
|
|
37
|
+
|
|
38
|
+
/** one source made ready: its entry and where the object's bytes are (in memory, a frozen copy, or already up) */
|
|
39
|
+
export interface Ready {
|
|
40
|
+
entry: Entry
|
|
41
|
+
bytes?: Uint8Array
|
|
42
|
+
/** a copy in the scratch folder (an APFS clone): the bytes that were hashed, whatever the live file does next */
|
|
43
|
+
file?: string
|
|
44
|
+
/** the object's size: a sqlite's is its gzip */
|
|
45
|
+
size: number
|
|
46
|
+
/** a path the repo names whole: its sha kept by its size and time */
|
|
47
|
+
whole?: true
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** every source read: hashed, snapshotted, or refused */
|
|
51
|
+
export async function prepare(sources: readonly Source[], scratch: string, seen: Seen = machineGet<Seen>(SEEN) ?? {}): Promise<{ ready: Ready[]; refused: Refused[] }> {
|
|
52
|
+
const ready: Ready[] = []
|
|
53
|
+
const refused: Refused[] = []
|
|
54
|
+
for (const s of sources) {
|
|
55
|
+
try {
|
|
56
|
+
if (s.broken) {
|
|
57
|
+
refused.push({ path: s.rel, why: s.broken })
|
|
58
|
+
continue
|
|
59
|
+
}
|
|
60
|
+
if (s.sqlite) {
|
|
61
|
+
const to = join(scratch, `${ready.length}-${basename(s.abs)}`)
|
|
62
|
+
const snap = snapshotSqlite(s.abs, to, s.sqlite)
|
|
63
|
+
const raw = new Uint8Array(await Bun.file(to).arrayBuffer())
|
|
64
|
+
rmSync(to, { force: true })
|
|
65
|
+
const why = refusal(basename(s.rel), raw)
|
|
66
|
+
if (why) {
|
|
67
|
+
refused.push({ path: s.rel, why })
|
|
68
|
+
continue
|
|
69
|
+
}
|
|
70
|
+
const gz = new Uint8Array(gzipSync(raw))
|
|
71
|
+
// a snapshot is a new file each run: its live file's time would move the part with no change
|
|
72
|
+
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 })
|
|
74
|
+
continue
|
|
75
|
+
}
|
|
76
|
+
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
|
+
const copy = join(scratch, `${ready.length}-whole${extname(s.abs)}`)
|
|
83
|
+
copyFileSync(s.abs, copy, constants.COPYFILE_FICLONE)
|
|
84
|
+
const r = await fileRefusal(copy, basename(s.abs))
|
|
85
|
+
if (r.why) {
|
|
86
|
+
rmSync(copy, { force: true })
|
|
87
|
+
refused.push({ path: s.rel, why: r.why })
|
|
88
|
+
continue
|
|
89
|
+
}
|
|
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 })
|
|
91
|
+
continue
|
|
92
|
+
}
|
|
93
|
+
const bytes = new Uint8Array(await Bun.file(s.abs).arrayBuffer())
|
|
94
|
+
const why = refusal(basename(s.abs), bytes)
|
|
95
|
+
if (why) {
|
|
96
|
+
refused.push({ path: s.rel, why })
|
|
97
|
+
continue
|
|
98
|
+
}
|
|
99
|
+
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 })
|
|
101
|
+
} catch (e) {
|
|
102
|
+
refused.push({ path: s.rel, why: `not read: ${(e as Error).message}` })
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return { ready, refused }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const extname = (p: string): string => /(\.[^./]+)$/.exec(basename(p))?.[1]?.toLowerCase() ?? ''
|
|
109
|
+
|
|
110
|
+
export interface RunResult {
|
|
111
|
+
files: number
|
|
112
|
+
bytes: number
|
|
113
|
+
sent: number
|
|
114
|
+
sentBytes: number
|
|
115
|
+
/** objects the Space already held */
|
|
116
|
+
there: number
|
|
117
|
+
refused: Refused[]
|
|
118
|
+
failed: { key: string; error: string }[]
|
|
119
|
+
/** the run written, null when nothing changed since `last` or an upload failed */
|
|
120
|
+
manifest: string | null
|
|
121
|
+
/** what the record of the run cost: its parts sent (of all), their bytes, and the run's own bytes */
|
|
122
|
+
record: { parts: number; partsSent: number; partsBytes: number; runBytes: number }
|
|
123
|
+
last: Last | null
|
|
124
|
+
digest: string
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** one object up from the bytes that were hashed, checked by a HEAD of its size: true when it was sent */
|
|
128
|
+
async function sendOne(space: Space, key: string, size: number, from: { bytes?: Uint8Array; file?: string }, scratch: string, n: number): Promise<boolean> {
|
|
129
|
+
if (from.file) return uploadOne(space, { key, size, path: from.file })
|
|
130
|
+
const path = join(scratch, `${n}.obj`)
|
|
131
|
+
try {
|
|
132
|
+
writeFileSync(path, from.bytes ?? new Uint8Array(0))
|
|
133
|
+
return await uploadOne(space, { key, size, path })
|
|
134
|
+
} finally {
|
|
135
|
+
rmSync(path, { force: true })
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** the objects of `ready` up, `jobs` at a time */
|
|
140
|
+
async function sendAll(space: Space, ready: readonly Ready[], scratch: string, jobs: number, out: RunResult): Promise<void> {
|
|
141
|
+
const byKey = new Map<string, Ready>()
|
|
142
|
+
for (const r of ready) byKey.set(r.entry.key, r)
|
|
143
|
+
const list = [...byKey.values()].filter((r) => !isUp(r.entry.key))
|
|
144
|
+
out.there += byKey.size - list.length
|
|
145
|
+
let next = 0
|
|
146
|
+
const work = async (): Promise<void> => {
|
|
147
|
+
for (;;) {
|
|
148
|
+
const i = next++
|
|
149
|
+
const r = list[i]
|
|
150
|
+
if (!r) return
|
|
151
|
+
try {
|
|
152
|
+
if (!r.bytes && !r.file) throw new Error(`${r.entry.path}: no bytes held for ${r.entry.key}, and the index does not see it up`)
|
|
153
|
+
if (await sendOne(space, r.entry.key, r.size, r, scratch, i)) {
|
|
154
|
+
out.sent++
|
|
155
|
+
out.sentBytes += r.size
|
|
156
|
+
} else out.there++
|
|
157
|
+
} catch (e) {
|
|
158
|
+
out.failed.push({ key: r.entry.key, error: (e as Error).message })
|
|
159
|
+
} finally {
|
|
160
|
+
if (r.file) rmSync(r.file, { force: true })
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
await Promise.all(Array.from({ length: Math.max(1, jobs) }, work))
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** the last run's digest: the machine db's record, else the Space's last run */
|
|
168
|
+
async function lastOf(space: Space, scratch: string): Promise<Last | null> {
|
|
169
|
+
const held = lastRun()
|
|
170
|
+
if (held) return held
|
|
171
|
+
const run = await runAt(space)
|
|
172
|
+
if (!run) return null
|
|
173
|
+
const m = await readRunHead(space, run.key, join(scratch, 'last.json.gz'))
|
|
174
|
+
return { key: run.key, digest: m.digest, at: m.at }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** a lock this old is taken over even when its pid runs: a restart in place keeps the pid of the process that held it
|
|
178
|
+
* (a daemon that ran a backup in process), and a job child is killed at an hour */
|
|
179
|
+
export const LOCK_STALE_MS = 2 * 3600_000
|
|
180
|
+
|
|
181
|
+
/** one run at a time on the machine (the daemon's job and a hand run): a lock file with its pid, taken over once its
|
|
182
|
+
* process is gone or the lock is older than LOCK_STALE_MS */
|
|
183
|
+
function lock(): () => void {
|
|
184
|
+
const path = join(homeDir(), 'backup.lock')
|
|
185
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
186
|
+
for (let i = 0; i < 2; i++) {
|
|
187
|
+
try {
|
|
188
|
+
writeFileSync(path, String(process.pid), { flag: 'wx' })
|
|
189
|
+
return () => rmSync(path, { force: true })
|
|
190
|
+
} catch {
|
|
191
|
+
const pid = Number(readFileSync(path, 'utf8').trim())
|
|
192
|
+
let alive = false
|
|
193
|
+
try {
|
|
194
|
+
alive = pid > 0 && process.kill(pid, 0)
|
|
195
|
+
} catch {
|
|
196
|
+
alive = false
|
|
197
|
+
}
|
|
198
|
+
const age = Date.now() - (statSync(path, { throwIfNoEntry: false })?.mtimeMs ?? 0)
|
|
199
|
+
if (alive && age < LOCK_STALE_MS) throw new Error(`another backup runs (pid ${pid}): it holds ${path}`)
|
|
200
|
+
if (alive) console.error(`WARN backup: ${path} held by pid ${pid} for ${Math.round(age / 60_000)} min, past ${LOCK_STALE_MS / 3600_000} h: taken over`)
|
|
201
|
+
rmSync(path, { force: true })
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
throw new Error(`${path}: the lock did not take`)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** 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> {
|
|
209
|
+
const unlock = lock()
|
|
210
|
+
const scratch = mkdtempSync(join(tmpdir(), 'shipkit-backup-'))
|
|
211
|
+
try {
|
|
212
|
+
const now = o.now ?? new Date()
|
|
213
|
+
const { ready, refused } = await prepare(await collect(o), scratch)
|
|
214
|
+
const files = ready.map((r) => r.entry)
|
|
215
|
+
const digest = digestOf(files, refused)
|
|
216
|
+
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 }
|
|
218
|
+
await sendAll(space, ready, scratch, o.jobs ?? 8, out)
|
|
219
|
+
if (out.failed.length > 0) return out
|
|
220
|
+
const seen: Seen = {}
|
|
221
|
+
for (const r of ready) if (r.whole) seen[r.entry.path] = { size: r.entry.size, mtime: r.entry.mtime, sha: r.entry.sha, key: r.entry.key }
|
|
222
|
+
machineSet(SEEN, seen)
|
|
223
|
+
if (last?.digest === digest) return out
|
|
224
|
+
const enc = encodeRun({ at: now.toISOString(), host: hostname(), home: o.home, digest, files, refused }, o.repos.map((r) => relative(o.home, r)))
|
|
225
|
+
out.record.parts = enc.parts.length
|
|
226
|
+
for (const [i, p] of enc.parts.entries()) {
|
|
227
|
+
if (isUp(p.ref.key)) continue
|
|
228
|
+
try {
|
|
229
|
+
if (await sendOne(space, p.ref.key, p.bytes.length, p, scratch, -1 - i)) {
|
|
230
|
+
out.record.partsSent++
|
|
231
|
+
out.record.partsBytes += p.bytes.length
|
|
232
|
+
}
|
|
233
|
+
} catch (e) {
|
|
234
|
+
out.failed.push({ key: p.ref.key, error: (e as Error).message })
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
if (out.failed.length > 0) return out
|
|
238
|
+
const key = runKey(now, digest)
|
|
239
|
+
await sendOne(space, key, enc.run.length, { bytes: enc.run }, scratch, -1 - enc.parts.length)
|
|
240
|
+
out.record.runBytes = enc.run.length
|
|
241
|
+
machineSet(LAST, { key, digest, at: now.toISOString() } satisfies Last)
|
|
242
|
+
out.manifest = key
|
|
243
|
+
return out
|
|
244
|
+
} finally {
|
|
245
|
+
rmSync(scratch, { recursive: true, force: true })
|
|
246
|
+
unlock()
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export interface CheckResult {
|
|
251
|
+
files: number
|
|
252
|
+
/** sources whose object the Space lacks */
|
|
253
|
+
waiting: { path: string; size: number }[]
|
|
254
|
+
/** sources the last run holds another content of, or none */
|
|
255
|
+
changed: string[]
|
|
256
|
+
refused: Refused[]
|
|
257
|
+
last: Last | null
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** what is not backed up yet: each source read and hashed, nothing sent */
|
|
261
|
+
export async function backupCheck(space: Space, o: Collect): Promise<CheckResult> {
|
|
262
|
+
const scratch = mkdtempSync(join(tmpdir(), 'shipkit-backup-'))
|
|
263
|
+
try {
|
|
264
|
+
const { ready, refused } = await prepare(await collect(o), scratch)
|
|
265
|
+
const last = await lastOf(space, scratch)
|
|
266
|
+
const held = last ? new Map((await readManifest(space, last.key, join(scratch, 'last'))).files.map((f) => [f.path, f.sha])) : new Map<string, string>()
|
|
267
|
+
const waiting: CheckResult['waiting'] = []
|
|
268
|
+
for (const r of ready) {
|
|
269
|
+
if (isUp(r.entry.key)) continue
|
|
270
|
+
const h = await space.head(r.entry.key)
|
|
271
|
+
if (h?.size !== r.size) waiting.push({ path: r.entry.path, size: r.size })
|
|
272
|
+
}
|
|
273
|
+
const changed = ready.filter((r) => held.get(r.entry.path) !== r.entry.sha && !r.entry.sqlite).map((r) => r.entry.path)
|
|
274
|
+
return { files: ready.length, waiting, changed, refused, last }
|
|
275
|
+
} finally {
|
|
276
|
+
rmSync(scratch, { recursive: true, force: true })
|
|
277
|
+
}
|
|
278
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// what the backup never sends (wiki build/shipkit/media-store.md, Backup): a secret's home is the keychain, never the
|
|
2
|
+
// Space. A file is refused by its name (an env file, a key file, a name that says secret, token, password, api key), by
|
|
3
|
+
// the leak guard's secret shapes in its bytes, by a credential line whose value is no keychain pointer, or by its
|
|
4
|
+
// size (over 50 MB is a question for the owner first, unless his repo names the path whole: `backup.paths`). The
|
|
5
|
+
// reason is printed, the content never
|
|
6
|
+
import { parsePatterns, SECRET_ROWS } from '../../hooks/leak-guard.ts'
|
|
7
|
+
|
|
8
|
+
export const MAX_BYTES = 50e6
|
|
9
|
+
|
|
10
|
+
const SHAPES = parsePatterns(SECRET_ROWS.join('\n')).regexes
|
|
11
|
+
|
|
12
|
+
/** a token word counts only at the end of a name (`github-token`, `token.txt`): `lane-token-budget.md` is prose */
|
|
13
|
+
const SECRET_NAME = /^\.env(?:\..*)?$|\.(?:pem|key|p12|pfx|jks|keystore)$|^id_(?:rsa|dsa|ecdsa|ed25519)$|(?:^|[-_.])(?:secrets?|api-?keys?|passwords?|passwd|credentials?|creds)(?:[-_.]|$)|(?:^|[-_.])tokens?(?:\.[a-z]+)?$/i
|
|
14
|
+
|
|
15
|
+
const KEY = '(?:password|passwd|pwd|mot de passe|api[ _-]?key|secret|token|bearer)'
|
|
16
|
+
/** a line that sets a credential to a value: a bare key at the start of a line, or a quoted key with its closing quote
|
|
17
|
+
* (`"secret:cave"` is a value, « 3. Secret : la grotte » inside a note is prose). A value that points at the keychain
|
|
18
|
+
* (a `secret get` command, the word keychain, an `rv/<name>` secret name) passes */
|
|
19
|
+
const CREDENTIAL_LINE = new RegExp(`(?:^[ \\t>*#-]*${KEY}|"${KEY}"|'${KEY}')[ \\t]*[:=][ \\t]*(?![ \\t]*$)(?!.*(?:\\bsecret get\\b|keychain|\\brv/[\\w/-]+))`, 'im')
|
|
20
|
+
|
|
21
|
+
/** why these bytes never go up, null when they may */
|
|
22
|
+
function textRefusal(bytes: Uint8Array): string | null {
|
|
23
|
+
const text = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('latin1')
|
|
24
|
+
const shape = SHAPES.find((s) => s.re.test(text))
|
|
25
|
+
if (shape) return `it holds a secret shape (${shape.row.slice(3, 24)}…): the keychain keeps those`
|
|
26
|
+
if (CREDENTIAL_LINE.test(text)) return 'a line sets a credential to a value (not a keychain pointer): the keychain keeps those'
|
|
27
|
+
return null
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const nameRefusal = (name: string): string | null => (SECRET_NAME.test(name) ? 'its name says it holds a secret: the keychain keeps those' : null)
|
|
31
|
+
|
|
32
|
+
/** why the file never goes up, null when it may */
|
|
33
|
+
export function refusal(name: string, bytes: Uint8Array): string | null {
|
|
34
|
+
if (bytes.length > MAX_BYTES) return `over 50 MB (${(bytes.length / 1e6).toFixed(0)} MB): asked before it goes`
|
|
35
|
+
return nameRefusal(name) ?? textRefusal(bytes)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** a window of a stream, its end carried into the next so a shape cut by a window's edge is still seen */
|
|
39
|
+
const WINDOW = 8 << 20
|
|
40
|
+
const CARRY = 4096
|
|
41
|
+
|
|
42
|
+
async function streamRefusal(stream: ReadableStream<Uint8Array>, each?: (chunk: Uint8Array) => void): Promise<string | null> {
|
|
43
|
+
let held = new Uint8Array(0)
|
|
44
|
+
let why: string | null = null
|
|
45
|
+
for await (const chunk of stream) {
|
|
46
|
+
each?.(chunk)
|
|
47
|
+
if (why) continue
|
|
48
|
+
const joined = new Uint8Array(held.length + chunk.length)
|
|
49
|
+
joined.set(held)
|
|
50
|
+
joined.set(chunk, held.length)
|
|
51
|
+
held = joined
|
|
52
|
+
if (held.length < WINDOW) continue
|
|
53
|
+
why = textRefusal(held)
|
|
54
|
+
held = held.slice(held.length - CARRY)
|
|
55
|
+
}
|
|
56
|
+
return why ?? (held.length > 0 ? textRefusal(held) : null)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** the names and the bytes inside a zip (`unzip`), never only its compressed bytes: a secret packed in an archive is
|
|
60
|
+
* still a secret */
|
|
61
|
+
async function zipRefusal(path: string): Promise<string | null> {
|
|
62
|
+
const list = Bun.spawn(['unzip', '-Z1', path], { stdout: 'pipe', stderr: 'pipe' })
|
|
63
|
+
const names = (await new Response(list.stdout).text()).split('\n').filter(Boolean)
|
|
64
|
+
if ((await list.exited) !== 0) return `not read: unzip could not list it: ${(await new Response(list.stderr).text()).trim().slice(0, 200)}`
|
|
65
|
+
for (const n of names) {
|
|
66
|
+
const why = nameRefusal(n.split('/').pop() ?? n)
|
|
67
|
+
if (why) return `${n} inside: ${why}`
|
|
68
|
+
}
|
|
69
|
+
const all = Bun.spawn(['unzip', '-p', path], { stdout: 'pipe', stderr: 'ignore' })
|
|
70
|
+
const why = await streamRefusal(all.stdout)
|
|
71
|
+
if ((await all.exited) > 1) return 'not read: unzip could not read every entry'
|
|
72
|
+
return why ? `inside: ${why}` : null
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** a file the owner named whole (an archive, a dump): no size bound, its bytes read as a stream, its sha read on the
|
|
76
|
+
* way. A zip is read inside */
|
|
77
|
+
export async function fileRefusal(path: string, name: string): Promise<{ why: string | null; sha: string; size: number }> {
|
|
78
|
+
const h = new Bun.CryptoHasher('sha256')
|
|
79
|
+
let size = 0
|
|
80
|
+
const scan = await streamRefusal(Bun.file(path).stream(), (c) => {
|
|
81
|
+
h.update(c)
|
|
82
|
+
size += c.length
|
|
83
|
+
})
|
|
84
|
+
const why = nameRefusal(name) ?? scan ?? (/\.zip$/i.test(name) ? await zipRefusal(path) : null)
|
|
85
|
+
return { why, sha: h.digest('hex'), size }
|
|
86
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// a live sqlite copied consistently (wiki build/shipkit/media-store.md, Backup): the live file attached read only into
|
|
2
|
+
// a fresh database, the tables kept copied inside ONE transaction (one read snapshot of the WAL), then vacuumed. Never a
|
|
3
|
+
// copy of the file while a process writes it. The same rows give the same bytes, so an unchanged db is one object.
|
|
4
|
+
// A cut leaves out the rows that move by themselves (a pid, the backup's own records): else every run differs
|
|
5
|
+
import { Database } from 'bun:sqlite'
|
|
6
|
+
|
|
7
|
+
export interface SqliteCut {
|
|
8
|
+
/** the tables kept, null: every table */
|
|
9
|
+
tables: string[] | null
|
|
10
|
+
/** per table, a where clause of the rows left out */
|
|
11
|
+
except?: Record<string, string>
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface Snapshot {
|
|
15
|
+
/** the tables copied and their rows */
|
|
16
|
+
rows: Record<string, number>
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const quote = (name: string): string => `"${name.replace(/"/g, '""')}"`
|
|
20
|
+
const kept = (cut: SqliteCut, table: string): string => (cut.except?.[table] ? ` where not (${cut.except[table]})` : '')
|
|
21
|
+
|
|
22
|
+
/** the live db at `live` copied into the new file `to` */
|
|
23
|
+
export function snapshotSqlite(live: string, to: string, cut: SqliteCut): Snapshot {
|
|
24
|
+
const db = new Database(to, { create: true, readwrite: true })
|
|
25
|
+
try {
|
|
26
|
+
db.exec('pragma journal_mode = delete')
|
|
27
|
+
db.query('attach database ? as live').run(`file:${encodeURI(live)}?mode=ro`)
|
|
28
|
+
db.exec('begin')
|
|
29
|
+
const all = db.query(`select name, sql from live.sqlite_schema where type = 'table' and name not like 'sqlite_%' order by name`).all() as { name: string; sql: string }[]
|
|
30
|
+
const keep = cut.tables === null ? all : all.filter((t) => cut.tables!.includes(t.name))
|
|
31
|
+
const missing = (cut.tables ?? []).filter((t) => !all.some((a) => a.name === t))
|
|
32
|
+
if (missing.length > 0) throw new Error(`${live}: no table ${missing.join(', ')}`)
|
|
33
|
+
const rows: Record<string, number> = {}
|
|
34
|
+
for (const t of keep) {
|
|
35
|
+
db.exec(t.sql)
|
|
36
|
+
db.exec(`insert into main.${quote(t.name)} select * from live.${quote(t.name)}${kept(cut, t.name)}`)
|
|
37
|
+
rows[t.name] = (db.query(`select count(*) as n from main.${quote(t.name)}`).get() as { n: number }).n
|
|
38
|
+
}
|
|
39
|
+
const names = keep.map((t) => t.name)
|
|
40
|
+
const idx = db.query(`select sql from live.sqlite_schema where type = 'index' and sql is not null and tbl_name in (${names.map(() => '?').join(',') || "''"}) order by name`).all(...names) as { sql: string }[]
|
|
41
|
+
for (const i of idx) db.exec(i.sql)
|
|
42
|
+
db.exec('commit')
|
|
43
|
+
db.exec('detach database live')
|
|
44
|
+
db.exec('vacuum')
|
|
45
|
+
return { rows }
|
|
46
|
+
} finally {
|
|
47
|
+
db.close()
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** the rows of each table a cut keeps, read through one read transaction */
|
|
52
|
+
export function rowsOf(file: string, cut: SqliteCut): Record<string, number> {
|
|
53
|
+
const db = new Database(file, { readonly: true })
|
|
54
|
+
try {
|
|
55
|
+
db.exec('begin')
|
|
56
|
+
const names = (db.query(`select name from sqlite_schema where type = 'table' and name not like 'sqlite_%' order by name`).all() as { name: string }[]).map((r) => r.name).filter((n) => cut.tables === null || cut.tables.includes(n))
|
|
57
|
+
const out: Record<string, number> = {}
|
|
58
|
+
for (const n of names) out[n] = (db.query(`select count(*) as n from ${quote(n)}${kept(cut, n)}`).get() as { n: number }).n
|
|
59
|
+
db.exec('commit')
|
|
60
|
+
return out
|
|
61
|
+
} finally {
|
|
62
|
+
db.close()
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
// WHAT THE BACKUP HOLDS (wiki build/shipkit/media-store.md, Backup, The inventory): every file of the machine that no
|
|
2
|
+
// git and no Space keeps, its authored or irreplaceable state. The home's veille logs, the rail order, the media index
|
|
3
|
+
// and the machine db (consistent sqlite snapshots), the machine's private folder, the agents' memories of each house
|
|
4
|
+
// repo; in each house repo, every untracked file of `.shipkit/` and the hand tuned `.comfy-ts/` files, and its
|
|
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 async fs: the daemon runs this between requests
|
|
7
|
+
import type { Dirent } from 'node:fs'
|
|
8
|
+
import { lstat, readdir } from 'node:fs/promises'
|
|
9
|
+
import { existsSync, statSync } from 'node:fs'
|
|
10
|
+
import { basename, extname, join, relative, sep } from 'node:path'
|
|
11
|
+
import { homeDir } from '../../home/home-paths.ts'
|
|
12
|
+
import { machineDbPath } from '../../core/machine-db.ts'
|
|
13
|
+
import { MACHINE_PRIVATE } from '../../core/layout.ts'
|
|
14
|
+
import { ORDER_FILE } from '../../serve/project-gutter-route.ts'
|
|
15
|
+
import { mediaDbPath } from '../db.ts'
|
|
16
|
+
import { loadRepoConfig, type RepoBackup } from '../../repo-config.ts'
|
|
17
|
+
import type { SqliteCut } from './snapshot.ts'
|
|
18
|
+
|
|
19
|
+
export interface Source {
|
|
20
|
+
abs: string
|
|
21
|
+
/** the path under the home folder: the form a manifest and a restore use */
|
|
22
|
+
rel: string
|
|
23
|
+
size: number
|
|
24
|
+
mtime: number
|
|
25
|
+
/** a live sqlite: snapshotted, never copied */
|
|
26
|
+
sqlite?: SqliteCut
|
|
27
|
+
/** a path the repo names whole: no size bound, read as a stream, not read again while its size and time hold */
|
|
28
|
+
whole?: true
|
|
29
|
+
/** why it cannot be read: refused with this reason, loud each run */
|
|
30
|
+
broken?: string
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** `.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 FILE_DENY = /^(?:STATUS(?:\.full)?\.md|\.DS_Store|\.review-index\.json|review-dispatcher\.json)$|\.(?:log|pid|lock|sqlite(?:-wal|-shm)?|db(?:-wal|-shm)?)$/
|
|
36
|
+
/** the review store's media go up as the `review` kind: only its records come here */
|
|
37
|
+
const RECORD = /\.(?:json|jsonl|md|txt|csv)$/
|
|
38
|
+
/** the atelier's rolls are generated media: its kit files and records come here, never its images or sounds */
|
|
39
|
+
const MEDIA = /\.(?:png|jpe?g|webp|gif|avif|mp4|webm|mov|wav|mp3|flac|ogg|opus|m4a|glb|exr|safetensors)$/i
|
|
40
|
+
/** the hand tuned files of `.comfy-ts/`: its caches, outputs and fetched templates stay out */
|
|
41
|
+
const COMFY_KEEP = ['drafts', 'llm-configs', 'settings.json', 'lora-keywords.json', 'image-picker.json', 'serve-tabs.json']
|
|
42
|
+
/** gitignored by some repos and authored there */
|
|
43
|
+
const REPO_EXTRA = ['agent/global-contribution.md', 'proposal', '.local']
|
|
44
|
+
const CODE = /\.(?:[cm]?[jt]sx?)$/
|
|
45
|
+
|
|
46
|
+
async function walk(dir: string, keep: (rel: string, isDir: boolean) => boolean, out: string[], base = dir): Promise<void> {
|
|
47
|
+
let names: Dirent[]
|
|
48
|
+
try {
|
|
49
|
+
names = await readdir(dir, { withFileTypes: true })
|
|
50
|
+
} catch {
|
|
51
|
+
return
|
|
52
|
+
}
|
|
53
|
+
for (const d of names.sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
54
|
+
const abs = join(dir, d.name)
|
|
55
|
+
const rel = relative(base, abs)
|
|
56
|
+
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)
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const shipkitKeep = (rel: string, isDir: boolean): boolean => {
|
|
63
|
+
const parts = rel.split(sep)
|
|
64
|
+
const name = parts[parts.length - 1] ?? ''
|
|
65
|
+
if (isDir) return !(parts.length === 1 && SHIPKIT_DENY.has(name)) && name !== 'node_modules' && name !== '.git' && !(parts[0] === 'social' && name === 'media')
|
|
66
|
+
if (FILE_DENY.test(name)) return false
|
|
67
|
+
if (parts[0] === 'review' && !RECORD.test(name)) return false
|
|
68
|
+
if (parts[0] === 'assets' && MEDIA.test(name)) return false
|
|
69
|
+
return true
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const comfyKeep = (rel: string): boolean => COMFY_KEEP.some((k) => rel === k || rel.startsWith(`${k}${sep}`))
|
|
73
|
+
|
|
74
|
+
async function git(repo: string, args: string[]): Promise<string[]> {
|
|
75
|
+
const p = Bun.spawn(['git', '-C', repo, ...args], { stdout: 'pipe', stderr: 'ignore' })
|
|
76
|
+
const text = await new Response(p.stdout).text()
|
|
77
|
+
if ((await p.exited) !== 0) return []
|
|
78
|
+
return text.split('\0').filter((l) => l !== '')
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** the gitignored `*.local.*` files of a repo, never a settings file or code */
|
|
82
|
+
export async function localFiles(repo: string): Promise<string[]> {
|
|
83
|
+
const names = await git(repo, ['ls-files', '-z', '-o', '-i', '--exclude-standard', '--', ':(glob)**/*.local.*'])
|
|
84
|
+
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
|
+
}
|
|
86
|
+
|
|
87
|
+
/** the agents' config roots under the home: `.claude`, `.claude-<account>` */
|
|
88
|
+
async function agentRoots(home: string): Promise<string[]> {
|
|
89
|
+
const names = await readdir(home).catch(() => [] as string[])
|
|
90
|
+
return names.filter((n) => /^\.claude(?:-[\w-]+)?$/.test(n)).map((n) => join(home, n, 'projects')).filter((p) => existsSync(p))
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** how a session folder names a repo's path */
|
|
94
|
+
const sessionName = (repo: string): string => repo.replace(/[^A-Za-z0-9]/g, '-')
|
|
95
|
+
|
|
96
|
+
export interface Collect {
|
|
97
|
+
home: string
|
|
98
|
+
repos: readonly string[]
|
|
99
|
+
/** each repo's `*.local.*` files; the daemon caches the git walk */
|
|
100
|
+
locals?: (repo: string) => Promise<string[]>
|
|
101
|
+
/** each repo's `backup` key; by default its repo.config.ts, read again when the file moves */
|
|
102
|
+
backupOf?: (repo: string) => Promise<RepoBackup | null>
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const configs = new Map<string, { mtime: number; backup: RepoBackup | null }>()
|
|
106
|
+
|
|
107
|
+
/** a repo's `backup` key from its config, loaded again only when the file moved; a config that does not load throws */
|
|
108
|
+
export async function backupOfRepo(repo: string): Promise<RepoBackup | null> {
|
|
109
|
+
const path = join(repo, 'repo.config.ts')
|
|
110
|
+
const mtime = statSync(path, { throwIfNoEntry: false })?.mtimeMs
|
|
111
|
+
if (mtime === undefined) return null
|
|
112
|
+
const held = configs.get(repo)
|
|
113
|
+
if (held?.mtime === mtime) return held.backup
|
|
114
|
+
const backup = (await loadRepoConfig(repo, { fresh: held !== undefined })).backup ?? null
|
|
115
|
+
configs.set(repo, { mtime, backup })
|
|
116
|
+
return backup
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** a live db's own side files and the locks of a folder named whole: never part of it */
|
|
120
|
+
const WHOLE_DENY = /^(?:\.DS_Store)$|\.(?:pid|lock)$|-(?:wal|shm|journal)$/
|
|
121
|
+
|
|
122
|
+
/** every source the backup holds now, under the home folder, sorted by path */
|
|
123
|
+
export async function collect(o: Collect): Promise<Source[]> {
|
|
124
|
+
const files: string[] = []
|
|
125
|
+
const add = (abs: string): void => void files.push(abs)
|
|
126
|
+
// the backup's own objects and records, and the pids, move by themselves: left out, else every run differs
|
|
127
|
+
const sqlite = new Map<string, SqliteCut>([
|
|
128
|
+
[mediaDbPath(), { tables: ['files', 'objects'], except: { objects: "key like 'backup/%'" } }],
|
|
129
|
+
[machineDbPath(), { tables: null, except: { state: "name like 'pid:%' or name like 'backup-%'" } }],
|
|
130
|
+
])
|
|
131
|
+
await walk(join(homeDir(), 'veille'), () => true, files)
|
|
132
|
+
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)
|
|
135
|
+
// the git walks of ignored trees take seconds each: all at once
|
|
136
|
+
const locals = new Map(await Promise.all(o.repos.map(async (r) => [r, await (o.locals ?? localFiles)(r)] as const)))
|
|
137
|
+
const whole = new Set<string>()
|
|
138
|
+
const extra: Source[] = []
|
|
139
|
+
for (const repo of o.repos) {
|
|
140
|
+
let cfg: RepoBackup | null = null
|
|
141
|
+
try {
|
|
142
|
+
cfg = await (o.backupOf ?? backupOfRepo)(repo)
|
|
143
|
+
} catch (e) {
|
|
144
|
+
extra.push({ abs: join(repo, 'repo.config.ts'), rel: relative(o.home, join(repo, 'repo.config.ts')), size: 0, mtime: 0, broken: `its backup key is unread, the config does not load: ${(e as Error).message.split('\n')[0]}` })
|
|
145
|
+
}
|
|
146
|
+
const named = cfg?.paths ?? []
|
|
147
|
+
const tracked = new Set((await git(repo, ['ls-files', '-z', '--', '.shipkit', '.comfy-ts', ...REPO_EXTRA, ...named])).map((n) => join(repo, n)))
|
|
148
|
+
for (const p of named) {
|
|
149
|
+
const abs = join(repo, p)
|
|
150
|
+
const st = await lstat(abs).catch(() => null)
|
|
151
|
+
const got: string[] = []
|
|
152
|
+
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)
|
|
154
|
+
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
|
+
for (const f of got) if (!tracked.has(f)) {
|
|
156
|
+
files.push(f)
|
|
157
|
+
whole.add(f)
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
for (const s of cfg?.sqlite ?? []) {
|
|
161
|
+
const { path, except } = typeof s === 'string' ? { path: s, except: undefined } : s
|
|
162
|
+
const hits = [...new Bun.Glob(path).scanSync({ cwd: repo, dot: true, onlyFiles: true })].filter((n) => !WHOLE_DENY.test(basename(n))).sort()
|
|
163
|
+
if (hits.length === 0) extra.push({ abs: join(repo, path), rel: relative(o.home, join(repo, path)), size: 0, mtime: 0, broken: `the repo's backup.sqlite names it and no file matches` })
|
|
164
|
+
for (const n of hits) sqlite.set(join(repo, n), { tables: null, ...(except ? { except } : {}) })
|
|
165
|
+
}
|
|
166
|
+
const mine: string[] = []
|
|
167
|
+
await walk(join(repo, '.shipkit'), shipkitKeep, mine)
|
|
168
|
+
await walk(join(repo, '.comfy-ts'), (rel, isDir) => (isDir ? COMFY_KEEP.some((k) => k === rel.split(sep)[0]) : comfyKeep(rel)), mine)
|
|
169
|
+
for (const x of REPO_EXTRA) {
|
|
170
|
+
const abs = join(repo, x)
|
|
171
|
+
const st = await lstat(abs).catch(() => null)
|
|
172
|
+
if (st?.isFile()) mine.push(abs)
|
|
173
|
+
else if (st?.isDirectory()) await walk(abs, (rel, isDir) => isDir || !FILE_DENY.test(basename(rel)), mine)
|
|
174
|
+
}
|
|
175
|
+
mine.push(...(locals.get(repo) ?? []))
|
|
176
|
+
for (const f of mine) if (!tracked.has(f)) files.push(f)
|
|
177
|
+
}
|
|
178
|
+
const out = new Map<string, Source>()
|
|
179
|
+
for (const abs of [...files, ...sqlite.keys()]) {
|
|
180
|
+
if (out.has(abs)) continue
|
|
181
|
+
const st = await lstat(abs).catch(() => null)
|
|
182
|
+
if (!st?.isFile()) continue
|
|
183
|
+
const rel = relative(o.home, abs)
|
|
184
|
+
if (rel.startsWith('..') || rel === '') continue
|
|
185
|
+
const cut = sqlite.get(abs)
|
|
186
|
+
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
|
+
}
|
|
188
|
+
for (const x of extra) out.set(`extra\0${x.rel}`, x)
|
|
189
|
+
return [...out.values()].sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0))
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** a cheap stamp of the sources that are files (a sqlite moves every few seconds; its snapshot runs on the clock) */
|
|
193
|
+
export const stampOfSources = (list: readonly Source[]): string => {
|
|
194
|
+
const h = new Bun.CryptoHasher('sha256')
|
|
195
|
+
for (const s of list) if (!s.sqlite) h.update(`${s.rel}\0${s.size}\0${s.mtime}\0${s.broken ?? ''}\n`)
|
|
196
|
+
return h.digest('hex')
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export const extOf = (rel: string): string => extname(rel).toLowerCase()
|