@rizom/ops 0.2.0-alpha.80 → 0.2.0-alpha.801

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +84 -3
  2. package/dist/age-key-bootstrap.d.ts +1 -1
  3. package/dist/brains-ops.js +707 -211
  4. package/dist/capability-bundle-migration.d.ts +26 -0
  5. package/dist/cert-bootstrap.d.ts +4 -2
  6. package/dist/content-repo-ref.d.ts +10 -0
  7. package/dist/content-repo.d.ts +1 -1
  8. package/dist/deploy.js +114 -3
  9. package/dist/directory-sync-stress-system.d.ts +75 -0
  10. package/dist/directory-sync-stress.d.ts +117 -0
  11. package/dist/entries/deploy.d.ts +2 -0
  12. package/dist/fetch-with-timeout.d.ts +3 -0
  13. package/dist/fs-paths.d.ts +4 -0
  14. package/dist/health-watchdog-smoke.d.ts +54 -0
  15. package/dist/image-inventory.d.ts +4 -0
  16. package/dist/image-types.d.ts +7 -0
  17. package/dist/images.d.ts +89 -0
  18. package/dist/index.d.ts +7 -0
  19. package/dist/index.js +721 -213
  20. package/dist/legacy-pilot-migration.d.ts +11 -0
  21. package/dist/legacy-projection-job-recovery.d.ts +29 -0
  22. package/dist/load-registry.d.ts +72 -7
  23. package/dist/observed-status.d.ts +1 -1
  24. package/dist/parse-args.d.ts +2 -12
  25. package/dist/preview-domain.d.ts +9 -0
  26. package/dist/provider-key-migration.d.ts +20 -0
  27. package/dist/reconcile-dry-run.d.ts +9 -0
  28. package/dist/run-command.d.ts +22 -5
  29. package/dist/runtime-image-lock.d.ts +12 -0
  30. package/dist/schema.d.ts +132 -172
  31. package/dist/secrets-encrypt.d.ts +9 -11
  32. package/dist/secrets-push.d.ts +1 -1
  33. package/dist/ssh-key-bootstrap.d.ts +1 -26
  34. package/dist/stage-legacy-crossover.d.ts +25 -0
  35. package/dist/stress-command.d.ts +14 -0
  36. package/dist/stress-git-checkout.d.ts +21 -0
  37. package/dist/stress-health-monitor.d.ts +56 -0
  38. package/dist/upgrade.d.ts +10 -0
  39. package/dist/user-add.d.ts +1 -0
  40. package/dist/user-offboard.d.ts +61 -0
  41. package/dist/verify-user.d.ts +5 -2
  42. package/package.json +51 -44
  43. package/templates/rover-pilot/.env.schema +23 -3
  44. package/templates/rover-pilot/.github/actions/varlock-env/action.yml +47 -0
  45. package/templates/rover-pilot/.github/workflows/build.yml +63 -17
  46. package/templates/rover-pilot/.github/workflows/deploy.yml +106 -70
  47. package/templates/rover-pilot/.github/workflows/directory-sync-stress.yml +119 -0
  48. package/templates/rover-pilot/.github/workflows/health-watchdog-smoke.yml +95 -0
  49. package/templates/rover-pilot/.github/workflows/offboard.yml +107 -0
  50. package/templates/rover-pilot/.github/workflows/reconcile.yml +10 -4
  51. package/templates/rover-pilot/.github/workflows/upgrade.yml +104 -0
  52. package/templates/rover-pilot/README.md +14 -6
  53. package/templates/rover-pilot/deploy/scripts/create-predeploy-backup.ts +1265 -0
  54. package/templates/rover-pilot/deploy/scripts/decrypt-user-secrets.ts +84 -23
  55. package/templates/rover-pilot/deploy/scripts/helpers.ts +3 -0
  56. package/templates/rover-pilot/deploy/scripts/install-health-watchdog.ts +144 -0
  57. package/templates/rover-pilot/deploy/scripts/provision-server.ts +51 -21
  58. package/templates/rover-pilot/deploy/scripts/pull-local-models.ts +69 -0
  59. package/templates/rover-pilot/deploy/scripts/reload-homeserver.ts +73 -0
  60. package/templates/rover-pilot/deploy/scripts/resolve-deploy-handles.ts +4 -0
  61. package/templates/rover-pilot/deploy/scripts/resolve-missing-images.ts +13 -0
  62. package/templates/rover-pilot/deploy/scripts/resolve-user-config.ts +74 -9
  63. package/templates/rover-pilot/deploy/scripts/sync-content-repo.ts +51 -47
  64. package/templates/rover-pilot/deploy/scripts/update-dns.ts +58 -12
  65. package/templates/rover-pilot/deploy/scripts/validate-secrets.ts +12 -1
  66. package/templates/rover-pilot/deploy/scripts/verify-runtime-image.ts +18 -0
  67. package/templates/rover-pilot/docs/canonical-crossover-record.md +107 -0
  68. package/templates/rover-pilot/docs/onboarding-checklist.md +23 -24
  69. package/templates/rover-pilot/docs/operator-playbook.md +348 -56
  70. package/templates/rover-pilot/docs/user-onboarding.md +48 -297
  71. package/templates/rover-pilot/package.json +1 -0
  72. package/templates/rover-pilot/pilot.yaml +7 -4
  73. package/dist/origin-ca.d.ts +0 -1
  74. package/dist/push-secrets.d.ts +0 -9
  75. package/dist/push-target.d.ts +0 -2
  76. package/dist/run-subprocess.d.ts +0 -6
@@ -0,0 +1,1265 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { Buffer } from "node:buffer";
3
+ import { appendFileSync } from "node:fs";
4
+
5
+ const getPrototypeOf: (value: object) => object | null = Object.getPrototypeOf;
6
+
7
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
8
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
9
+ return false;
10
+ }
11
+
12
+ const prototype = getPrototypeOf(value);
13
+ return prototype === Object.prototype || prototype === null;
14
+ }
15
+
16
+ /**
17
+ * The slice of `@libsql/client` this script uses.
18
+ *
19
+ * Declared here because the import is dynamic — the package is optional, and
20
+ * only the libsql quick-check driver needs it.
21
+ */
22
+ interface LibsqlModule {
23
+ createClient(options: { url: string }): {
24
+ execute(sql: string): Promise<{
25
+ rows: Array<Record<string | number, unknown>>;
26
+ }>;
27
+ close(): void;
28
+ };
29
+ }
30
+
31
+ export const DEFAULT_PREDEPLOY_BACKUP_RETENTION_COUNT = 5;
32
+ export const PREDEPLOY_BACKUP_TOOL_VERSION = "brains-predeploy-backup-v1";
33
+
34
+ type DatabaseCaptureMethod = "vacuum" | "serialize";
35
+ type QuickCheckDriver = "bun" | "libsql";
36
+
37
+ export interface PredeployDatabaseSource {
38
+ source: string;
39
+ name: string;
40
+ method: DatabaseCaptureMethod;
41
+ quickCheck: QuickCheckDriver;
42
+ logicalVector: boolean;
43
+ /** Verify the image assets the snapshot's entities reference. */
44
+ assets?: boolean | undefined;
45
+ }
46
+
47
+ /** A referenced asset whose stored bytes do not verify. */
48
+ interface AssetFailure {
49
+ digest: string;
50
+ /** The entities referencing it, as `type/id`. */
51
+ entities: string[];
52
+ reason: string;
53
+ }
54
+
55
+ /** The asset inventory a snapshot holds, and what of it verified. */
56
+ interface AssetSnapshotReport {
57
+ /** Entity rows referencing an asset. */
58
+ references: number;
59
+ /** Distinct referenced assets, each re-hashed from its chunks. */
60
+ assets: number;
61
+ totalBytes: number;
62
+ /** Staged uploads no asset publishes; harmless, reported only. */
63
+ orphanUploads: number;
64
+ verified: number;
65
+ failed: number;
66
+ failures: AssetFailure[];
67
+ digests: string[];
68
+ }
69
+
70
+ /** Where the capture program writes what the deploy log shows. */
71
+ export interface PredeployCaptureOutput {
72
+ stdout(line: string): void;
73
+ stderr(line: string): void;
74
+ }
75
+
76
+ const consoleOutput: PredeployCaptureOutput = {
77
+ stdout: (line) => console.log(line),
78
+ stderr: (line) => console.error(line),
79
+ };
80
+
81
+ /** The asset counts a backup reports, read back from its output. */
82
+ export interface PredeployAssetSummary {
83
+ referenced: number;
84
+ verified: number;
85
+ failed: number;
86
+ }
87
+
88
+ export interface PredeployBackupMetadata {
89
+ snapshotId: string;
90
+ targetHandle: string;
91
+ host: string;
92
+ startedAt: string;
93
+ sourceVersion: string;
94
+ targetVersion: string;
95
+ toolVersion: string;
96
+ containerId: string;
97
+ imageId: string;
98
+ imageDigest: string;
99
+ }
100
+
101
+ export interface PredeployCaptureConfig {
102
+ backupDir: string;
103
+ contentRoot: string;
104
+ databases: PredeployDatabaseSource[];
105
+ metadata: PredeployBackupMetadata;
106
+ }
107
+
108
+ export type PredeployBackupResult =
109
+ | { applicable: false }
110
+ | {
111
+ applicable: true;
112
+ snapshotId: string;
113
+ backupPath: string;
114
+ sourceVersion: string;
115
+ targetVersion: string;
116
+ totalBytes: number;
117
+ durationSeconds: number;
118
+ verification: "passed";
119
+ /** Absent when the backup reported no asset counts. */
120
+ assets?: PredeployAssetSummary;
121
+ };
122
+
123
+ interface CommandResult {
124
+ stdout: Uint8Array;
125
+ stderr: Uint8Array;
126
+ }
127
+
128
+ interface DatabaseCaptureRecord extends Omit<
129
+ PredeployDatabaseSource,
130
+ "quickCheck"
131
+ > {
132
+ status: "captured";
133
+ required: true;
134
+ startedAt: string;
135
+ completedAt: string;
136
+ bytes: number;
137
+ sha256: string;
138
+ quickCheckDriver: QuickCheckDriver;
139
+ quickCheck: string;
140
+ assetVerification?: Omit<AssetSnapshotReport, "digests" | "failures">;
141
+ }
142
+
143
+ interface GitCaptureRecord {
144
+ head: string;
145
+ tree: string;
146
+ branch: string;
147
+ upstream: string;
148
+ observedRemoteHead: string;
149
+ aheadBehind: string;
150
+ clean: boolean;
151
+ stagedPatchBytes: number;
152
+ unstagedPatchBytes: number;
153
+ untrackedFiles: number;
154
+ ignoredFiles: number;
155
+ bundleVerified: true;
156
+ }
157
+
158
+ async function runCommand(
159
+ command: string,
160
+ args: string[],
161
+ cwd?: string,
162
+ env?: Record<string, string | undefined>,
163
+ ): Promise<CommandResult> {
164
+ const options = {
165
+ ...(cwd ? { cwd } : {}),
166
+ ...(env ? { env } : {}),
167
+ stdout: "pipe" as const,
168
+ stderr: "pipe" as const,
169
+ };
170
+ const child = Bun.spawn([command, ...args], options);
171
+ const [exitCode, stdout, stderr] = await Promise.all([
172
+ child.exited,
173
+ new Response(child.stdout).bytes(),
174
+ new Response(child.stderr).bytes(),
175
+ ]);
176
+ if (exitCode !== 0) {
177
+ throw new Error(`${command} ${args[0] ?? ""} failed with exit ${exitCode}`);
178
+ }
179
+ return { stdout, stderr };
180
+ }
181
+
182
+ function text(bytes: Uint8Array): string {
183
+ return new TextDecoder().decode(bytes).trim();
184
+ }
185
+
186
+ async function sha256(path: string): Promise<string> {
187
+ const hasher = new Bun.CryptoHasher("sha256");
188
+ for await (const chunk of Bun.file(path).stream()) {
189
+ hasher.update(chunk);
190
+ }
191
+ return hasher.digest("hex");
192
+ }
193
+
194
+ function nullDelimitedCount(bytes: Uint8Array): number {
195
+ let count = 0;
196
+ for (const byte of bytes) {
197
+ if (byte === 0) count += 1;
198
+ }
199
+ return count;
200
+ }
201
+
202
+ function bytesEqual(left: Uint8Array, right: Uint8Array): boolean {
203
+ if (left.length !== right.length) return false;
204
+ for (let index = 0; index < left.length; index += 1) {
205
+ if (left[index] !== right[index]) return false;
206
+ }
207
+ return true;
208
+ }
209
+
210
+ function gitRemoteEnvironment():
211
+ Record<string, string | undefined> | undefined {
212
+ const token = process.env["GIT_SYNC_TOKEN"];
213
+ if (!token) return undefined;
214
+ const currentCount = Number(process.env["GIT_CONFIG_COUNT"] ?? 0);
215
+ const index =
216
+ Number.isSafeInteger(currentCount) && currentCount >= 0 ? currentCount : 0;
217
+ return {
218
+ ...process.env,
219
+ GIT_CONFIG_COUNT: String(index + 1),
220
+ [`GIT_CONFIG_KEY_${index}`]: "http.extraHeader",
221
+ [`GIT_CONFIG_VALUE_${index}`]: `AUTHORIZATION: basic ${Buffer.from(`x-access-token:${token}`).toString("base64")}`,
222
+ };
223
+ }
224
+
225
+ /** How long a snapshot read waits on a runtime that holds the database. */
226
+ const SNAPSHOT_BUSY_TIMEOUT_MS = 10_000;
227
+
228
+ /**
229
+ * Open a database for reading a snapshot. The runtime is live while the
230
+ * backup runs, so a reader can meet a writer's lock or a WAL recovery in
231
+ * progress; it waits for them instead of failing the backup at once.
232
+ */
233
+ function openSnapshotReader(path: string): Database {
234
+ const database = new Database(path, { readonly: true });
235
+ database.run(`PRAGMA busy_timeout = ${SNAPSHOT_BUSY_TIMEOUT_MS}`);
236
+ return database;
237
+ }
238
+
239
+ async function quickCheck(
240
+ path: string,
241
+ driver: QuickCheckDriver,
242
+ ): Promise<string> {
243
+ if (driver === "bun") {
244
+ const database = openSnapshotReader(path);
245
+ try {
246
+ const result: unknown = database.query("PRAGMA quick_check").get();
247
+ const row = isPlainRecord(result) ? result : null;
248
+ return String(row?.["quick_check"] ?? row?.["0"] ?? "");
249
+ } finally {
250
+ database.close(false);
251
+ }
252
+ }
253
+
254
+ const moduleName = "@libsql/client";
255
+ // Annotated rather than asserted: a dynamic import of an optional dependency
256
+ // resolves to `any`, so naming the slice this script uses is a checked
257
+ // assignment instead of a claim about the whole module.
258
+ const libsql: LibsqlModule = await import(moduleName);
259
+ const client = libsql.createClient({ url: `file:${path}` });
260
+ try {
261
+ const result = await client.execute("PRAGMA quick_check");
262
+ return String(result.rows[0]?.["quick_check"] ?? result.rows[0]?.[0] ?? "");
263
+ } finally {
264
+ client.close();
265
+ }
266
+ }
267
+
268
+ function vectorDigestDatabase(database: Database): {
269
+ counts: Record<string, number>;
270
+ sha256: string;
271
+ } {
272
+ const hasher = new Bun.CryptoHasher("sha256");
273
+ // A vector index keeps its entries in libSQL shadow tables. They exist only
274
+ // while an index does: a retired index drops its own shadow table, and a
275
+ // database that never had one has neither. The embeddings rows always count.
276
+ const existing = new Set(
277
+ database
278
+ .query("SELECT name FROM sqlite_master WHERE type = 'table'")
279
+ .all()
280
+ .filter(isPlainRecord)
281
+ .map((row) => String(row["name"])),
282
+ );
283
+ const tables = (
284
+ [
285
+ ["embeddings", "entity_id, entity_type"],
286
+ ["embeddings_embedding_idx_shadow", "index_key"],
287
+ ["libsql_vector_meta_shadow", "name"],
288
+ ] as const
289
+ ).filter(([table]) => table === "embeddings" || existing.has(table));
290
+ const counts: Record<string, number> = {};
291
+ for (const [table, order] of tables) {
292
+ hasher.update(`table:${table}\n`);
293
+ const selected: unknown[] = database
294
+ .query(`SELECT * FROM ${table} ORDER BY ${order}`)
295
+ .all();
296
+ const rows = selected.filter(isPlainRecord);
297
+ counts[table] = rows.length;
298
+ for (const row of rows) {
299
+ for (const [key, value] of Object.entries(row)) {
300
+ hasher.update(`${key}:`);
301
+ if (value instanceof Uint8Array) hasher.update(value);
302
+ else hasher.update(`${typeof value}:${String(value)}`);
303
+ hasher.update("\0");
304
+ }
305
+ hasher.update("\n");
306
+ }
307
+ }
308
+ return { counts, sha256: hasher.digest("hex") };
309
+ }
310
+
311
+ const ASSET_REF_PREFIX = "asset://sha256/";
312
+ /** How the capture names a failed asset on stderr, for the deploy log. */
313
+ const ASSET_FAILURE_PREFIX = "pre-deploy snapshot: asset failed: ";
314
+
315
+ /**
316
+ * Check every asset the snapshot's entities reference: a published header
317
+ * whose chunks run contiguously, add up to its size and hash to its digest.
318
+ * Any failure blocks the backup. A database from before staged asset
319
+ * storage references none.
320
+ */
321
+ /**
322
+ * Re-hash every asset the snapshot's entities reference. Each asset is
323
+ * checked on its own, so one bad asset does not hide the others: the report
324
+ * names every failure and the entities that reference it.
325
+ */
326
+ function verifySnapshotAssets(path: string): AssetSnapshotReport {
327
+ const database = new Database(path, { readonly: true });
328
+ try {
329
+ const tables = new Set(
330
+ database
331
+ .query("SELECT name FROM sqlite_master WHERE type = 'table'")
332
+ .all()
333
+ .filter(isPlainRecord)
334
+ .map((row) => String(row["name"])),
335
+ );
336
+ if (!tables.has("asset_chunks")) {
337
+ return {
338
+ references: 0,
339
+ assets: 0,
340
+ totalBytes: 0,
341
+ orphanUploads: 0,
342
+ verified: 0,
343
+ failed: 0,
344
+ failures: [],
345
+ digests: [],
346
+ };
347
+ }
348
+ const referencing = new Map<string, string[]>();
349
+ database
350
+ .query(
351
+ "SELECT content, entityType, id FROM entities WHERE content LIKE ? ORDER BY content, entityType, id",
352
+ )
353
+ .all(`${ASSET_REF_PREFIX}%`)
354
+ .filter(isPlainRecord)
355
+ .forEach((row) => {
356
+ const digest = String(row["content"]).slice(ASSET_REF_PREFIX.length);
357
+ const entity = `${String(row["entityType"])}/${String(row["id"])}`;
358
+ referencing.set(digest, [...(referencing.get(digest) ?? []), entity]);
359
+ });
360
+ const header = database.query(
361
+ "SELECT upload_id, size_bytes, chunk_count FROM assets WHERE digest = ?",
362
+ );
363
+ const chunks = database.query(
364
+ "SELECT ordinal, bytes FROM asset_chunks WHERE upload_id = ? ORDER BY ordinal",
365
+ );
366
+ /** The asset's size when its chunks verify, else why they do not. */
367
+ const verify = (digest: string): { size: number } | { reason: string } => {
368
+ const row = header.get(digest);
369
+ if (!isPlainRecord(row)) return { reason: "has no published asset" };
370
+ const sizeBytes = Number(row["size_bytes"]);
371
+ const chunkCount = Number(row["chunk_count"]);
372
+ const hasher = new Bun.CryptoHasher("sha256");
373
+ const read = { chunks: 0, bytes: 0 };
374
+ for (const chunk of chunks.iterate(String(row["upload_id"]))) {
375
+ if (!isPlainRecord(chunk) || Number(chunk["ordinal"]) !== read.chunks) {
376
+ return { reason: `is missing chunk ${read.chunks}` };
377
+ }
378
+ const bytes = chunk["bytes"];
379
+ if (!(bytes instanceof Uint8Array)) {
380
+ return { reason: `chunk ${read.chunks} is not binary` };
381
+ }
382
+ hasher.update(bytes);
383
+ read.chunks += 1;
384
+ read.bytes += bytes.byteLength;
385
+ }
386
+ if (read.chunks !== chunkCount || read.bytes !== sizeBytes) {
387
+ return {
388
+ reason: `holds ${read.chunks} chunks and ${read.bytes} bytes; expected ${chunkCount} and ${sizeBytes}`,
389
+ };
390
+ }
391
+ if (hasher.digest("hex") !== digest) {
392
+ return { reason: "chunks hash to a different digest" };
393
+ }
394
+ return { size: sizeBytes };
395
+ };
396
+ const results = [...referencing].map(([digest, entities]) => ({
397
+ digest,
398
+ entities,
399
+ outcome: verify(digest),
400
+ }));
401
+ const failures = results.flatMap(({ digest, entities, outcome }) =>
402
+ "reason" in outcome ? [{ digest, entities, reason: outcome.reason }] : [],
403
+ );
404
+ const orphans = database
405
+ .query(
406
+ "SELECT COUNT(*) AS count FROM asset_uploads WHERE upload_id NOT IN (SELECT upload_id FROM assets)",
407
+ )
408
+ .get();
409
+ return {
410
+ references: results.reduce(
411
+ (sum, { entities }) => sum + entities.length,
412
+ 0,
413
+ ),
414
+ assets: results.length,
415
+ totalBytes: results.reduce(
416
+ (sum, { outcome }) => sum + ("size" in outcome ? outcome.size : 0),
417
+ 0,
418
+ ),
419
+ orphanUploads: isPlainRecord(orphans) ? Number(orphans["count"]) : 0,
420
+ verified: results.length - failures.length,
421
+ failed: failures.length,
422
+ failures,
423
+ digests: results.map(({ digest }) => digest),
424
+ };
425
+ } finally {
426
+ database.close(false);
427
+ }
428
+ }
429
+
430
+ /** The counts and failures the deploy log shows, as the capture prints them. */
431
+ function reportAssetVerification(
432
+ report: AssetSnapshotReport,
433
+ output: PredeployCaptureOutput,
434
+ ): void {
435
+ output.stdout(`ASSETS_REFERENCED=${report.assets}`);
436
+ output.stdout(`ASSETS_VERIFIED=${report.verified}`);
437
+ output.stdout(`ASSETS_FAILED=${report.failed}`);
438
+ report.failures.forEach(({ digest, entities, reason }) =>
439
+ output.stderr(
440
+ `${ASSET_FAILURE_PREFIX}${digest} (${entities.join(", ")}): ${reason}`,
441
+ ),
442
+ );
443
+ }
444
+
445
+ function vectorDigest(path: string): {
446
+ counts: Record<string, number>;
447
+ sha256: string;
448
+ } {
449
+ const database = openSnapshotReader(path);
450
+ try {
451
+ return vectorDigestDatabase(database);
452
+ } finally {
453
+ database.close(false);
454
+ }
455
+ }
456
+
457
+ async function captureDatabases(
458
+ config: PredeployCaptureConfig,
459
+ output: PredeployCaptureOutput,
460
+ ): Promise<DatabaseCaptureRecord[]> {
461
+ const captures: DatabaseCaptureRecord[] = [];
462
+
463
+ for (const source of config.databases) {
464
+ if (!(await Bun.file(source.source).exists())) {
465
+ throw new Error(`Required database missing: ${source.source}`);
466
+ }
467
+ const destination = `${config.backupDir}/${source.name}`;
468
+ if (await Bun.file(destination).exists()) {
469
+ throw new Error(`Snapshot destination already exists: ${source.name}`);
470
+ }
471
+
472
+ const startedAt = new Date().toISOString();
473
+ const database = openSnapshotReader(source.source);
474
+ let originalVectorDigest:
475
+ { counts: Record<string, number>; sha256: string } | undefined;
476
+ if (source.method === "serialize") {
477
+ if (source.logicalVector) {
478
+ database.run("BEGIN");
479
+ originalVectorDigest = vectorDigestDatabase(database);
480
+ }
481
+ const bytes = database.serialize();
482
+ if (source.logicalVector) database.run("COMMIT");
483
+ database.close(false);
484
+ await Bun.write(destination, bytes);
485
+ } else {
486
+ const escapedDestination = destination.replaceAll("'", "''");
487
+ database.run(`VACUUM INTO '${escapedDestination}'`);
488
+ database.close(false);
489
+ }
490
+
491
+ const check = await quickCheck(destination, source.quickCheck);
492
+ if (check !== "ok") {
493
+ throw new Error(`${source.name}: PRAGMA quick_check=${check}`);
494
+ }
495
+ if (source.logicalVector) {
496
+ if (!originalVectorDigest) {
497
+ throw new Error(`${source.name}: source vector digest missing`);
498
+ }
499
+ const snapshot = vectorDigest(destination);
500
+ if (
501
+ originalVectorDigest.sha256 !== snapshot.sha256 ||
502
+ JSON.stringify(originalVectorDigest.counts) !==
503
+ JSON.stringify(snapshot.counts)
504
+ ) {
505
+ throw new Error(`${source.name}: logical vector verification failed`);
506
+ }
507
+ await Bun.write(
508
+ `${config.backupDir}/${source.name}.logical-verify.json`,
509
+ `${JSON.stringify({ original: originalVectorDigest, snapshot, exact: true }, null, 2)}\n`,
510
+ );
511
+ }
512
+
513
+ const assetReport = source.assets
514
+ ? verifySnapshotAssets(destination)
515
+ : undefined;
516
+ if (assetReport) {
517
+ await Bun.write(
518
+ `${config.backupDir}/${source.name}.asset-verify.json`,
519
+ `${JSON.stringify(assetReport, null, 2)}\n`,
520
+ );
521
+ reportAssetVerification(assetReport, output);
522
+ if (assetReport.failed > 0) {
523
+ throw new Error(
524
+ `${source.name}: asset verification failed: ${assetReport.failed} of ${assetReport.assets} referenced assets`,
525
+ );
526
+ }
527
+ }
528
+
529
+ const file = Bun.file(destination);
530
+ const { quickCheck: quickCheckDriver, ...sourceMetadata } = source;
531
+ captures.push({
532
+ ...sourceMetadata,
533
+ status: "captured",
534
+ required: true,
535
+ startedAt,
536
+ completedAt: new Date().toISOString(),
537
+ bytes: file.size,
538
+ sha256: await sha256(destination),
539
+ quickCheckDriver,
540
+ quickCheck: check,
541
+ ...(assetReport && {
542
+ assetVerification: {
543
+ references: assetReport.references,
544
+ assets: assetReport.assets,
545
+ totalBytes: assetReport.totalBytes,
546
+ orphanUploads: assetReport.orphanUploads,
547
+ verified: assetReport.verified,
548
+ failed: assetReport.failed,
549
+ },
550
+ }),
551
+ });
552
+ }
553
+
554
+ await Bun.write(
555
+ `${config.backupDir}/database-captures.json`,
556
+ `${JSON.stringify(captures, null, 2)}\n`,
557
+ );
558
+ return captures;
559
+ }
560
+
561
+ async function captureGitCheckout(
562
+ contentRoot: string,
563
+ backupDir: string,
564
+ ): Promise<GitCaptureRecord> {
565
+ const git = async (args: string[]): Promise<CommandResult> =>
566
+ runCommand("git", args, contentRoot);
567
+ const head = text((await git(["rev-parse", "HEAD"])).stdout);
568
+ const tree = text((await git(["rev-parse", "HEAD^{tree}"])).stdout);
569
+ const branch = text((await git(["branch", "--show-current"])).stdout);
570
+ const upstream = text(
571
+ (await git(["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout,
572
+ );
573
+ const remoteBranch = upstream.replace(/^[^/]+\//, "");
574
+ if (!remoteBranch) throw new Error("Content checkout has no remote branch");
575
+ const observedRemote = text(
576
+ (
577
+ await runCommand(
578
+ "git",
579
+ ["ls-remote", "origin", `refs/heads/${remoteBranch}`],
580
+ contentRoot,
581
+ gitRemoteEnvironment(),
582
+ )
583
+ ).stdout,
584
+ ).split(/\s+/)[0];
585
+ if (!observedRemote) throw new Error("Content remote head is unavailable");
586
+ const aheadBehind = text(
587
+ (await git(["rev-list", "--left-right", "--count", `HEAD...${upstream}`]))
588
+ .stdout,
589
+ );
590
+ const status = await git([
591
+ "status",
592
+ "--porcelain=v1",
593
+ "--branch",
594
+ "--untracked-files=all",
595
+ ]);
596
+ const dirtyStatus = await git([
597
+ "status",
598
+ "--porcelain=v1",
599
+ "--untracked-files=all",
600
+ ]);
601
+ const staged = await git(["diff", "--cached", "--binary", "--full-index"]);
602
+ const unstaged = await git(["diff", "--binary", "--full-index"]);
603
+ const untracked = await git([
604
+ "ls-files",
605
+ "--others",
606
+ "--exclude-standard",
607
+ "-z",
608
+ ]);
609
+ const ignored = await git([
610
+ "ls-files",
611
+ "--others",
612
+ "--ignored",
613
+ "--exclude-standard",
614
+ "-z",
615
+ ]);
616
+ const refs = await git(["show-ref"]);
617
+
618
+ await Promise.all([
619
+ Bun.write(`${backupDir}/content-status.txt`, status.stdout),
620
+ Bun.write(`${backupDir}/content-staged.patch`, staged.stdout),
621
+ Bun.write(`${backupDir}/content-unstaged.patch`, unstaged.stdout),
622
+ Bun.write(`${backupDir}/content-untracked.zlist`, untracked.stdout),
623
+ Bun.write(`${backupDir}/content-ignored.zlist`, ignored.stdout),
624
+ Bun.write(`${backupDir}/content-head.txt`, `${head}\n`),
625
+ Bun.write(`${backupDir}/content-tree.txt`, `${tree}\n`),
626
+ Bun.write(
627
+ `${backupDir}/content-observed-remote.txt`,
628
+ `${observedRemote}\n`,
629
+ ),
630
+ Bun.write(`${backupDir}/content-ahead-behind.txt`, `${aheadBehind}\n`),
631
+ ]);
632
+
633
+ await git(["bundle", "create", `${backupDir}/content.bundle`, "--all"]);
634
+ const bundleVerify = await git([
635
+ "bundle",
636
+ "verify",
637
+ `${backupDir}/content.bundle`,
638
+ ]);
639
+ await Bun.write(
640
+ `${backupDir}/content-bundle-verify.txt`,
641
+ `${new TextDecoder().decode(bundleVerify.stdout)}${new TextDecoder().decode(bundleVerify.stderr)}`,
642
+ );
643
+ await Bun.write(`${backupDir}/content-refs.txt`, refs.stdout);
644
+
645
+ for (const [listName, archiveName] of [
646
+ ["content-untracked.zlist", "content-untracked.tar"],
647
+ ["content-ignored.zlist", "content-ignored.tar"],
648
+ ] as const) {
649
+ const archivePath = `${backupDir}/${archiveName}`;
650
+ await runCommand("tar", [
651
+ "--null",
652
+ "--no-recursion",
653
+ "-C",
654
+ contentRoot,
655
+ "-cf",
656
+ archivePath,
657
+ `--files-from=${backupDir}/${listName}`,
658
+ ]);
659
+ await runCommand("tar", [
660
+ "--compare",
661
+ `--file=${archivePath}`,
662
+ "-C",
663
+ contentRoot,
664
+ ]);
665
+ }
666
+
667
+ const [
668
+ postHead,
669
+ postStatus,
670
+ postStaged,
671
+ postUnstaged,
672
+ postUntracked,
673
+ postIgnored,
674
+ postRefs,
675
+ ] = await Promise.all([
676
+ git(["rev-parse", "HEAD"]),
677
+ git(["status", "--porcelain=v1", "--branch", "--untracked-files=all"]),
678
+ git(["diff", "--cached", "--binary", "--full-index"]),
679
+ git(["diff", "--binary", "--full-index"]),
680
+ git(["ls-files", "--others", "--exclude-standard", "-z"]),
681
+ git(["ls-files", "--others", "--ignored", "--exclude-standard", "-z"]),
682
+ git(["show-ref"]),
683
+ ]);
684
+ const stable =
685
+ text(postHead.stdout) === head &&
686
+ bytesEqual(postStatus.stdout, status.stdout) &&
687
+ bytesEqual(postStaged.stdout, staged.stdout) &&
688
+ bytesEqual(postUnstaged.stdout, unstaged.stdout) &&
689
+ bytesEqual(postUntracked.stdout, untracked.stdout) &&
690
+ bytesEqual(postIgnored.stdout, ignored.stdout) &&
691
+ bytesEqual(postRefs.stdout, refs.stdout);
692
+ if (!stable) {
693
+ throw new Error("Content checkout changed during snapshot capture");
694
+ }
695
+
696
+ return {
697
+ head,
698
+ tree,
699
+ branch,
700
+ upstream,
701
+ observedRemoteHead: observedRemote,
702
+ aheadBehind,
703
+ clean: dirtyStatus.stdout.length === 0,
704
+ stagedPatchBytes: staged.stdout.length,
705
+ unstagedPatchBytes: unstaged.stdout.length,
706
+ untrackedFiles: nullDelimitedCount(untracked.stdout),
707
+ ignoredFiles: nullDelimitedCount(ignored.stdout),
708
+ bundleVerified: true,
709
+ };
710
+ }
711
+
712
+ export async function capturePredeployBackup(
713
+ config: PredeployCaptureConfig,
714
+ output: PredeployCaptureOutput = consoleOutput,
715
+ ): Promise<void> {
716
+ const databases = await captureDatabases(config, output);
717
+ const git = await captureGitCheckout(config.contentRoot, config.backupDir);
718
+ const manifest = {
719
+ schemaVersion: 1,
720
+ outcome: "verified",
721
+ ...config.metadata,
722
+ completedAt: new Date().toISOString(),
723
+ databases,
724
+ git,
725
+ };
726
+ await Bun.write(
727
+ `${config.backupDir}/manifest.json`,
728
+ `${JSON.stringify(manifest, null, 2)}\n`,
729
+ );
730
+ }
731
+
732
+ function captureConfigFromEnvironment(): PredeployCaptureConfig {
733
+ const value = (name: string): string => {
734
+ const result = process.env[name];
735
+ if (!result) throw new Error(`Missing ${name}`);
736
+ return result;
737
+ };
738
+ return {
739
+ backupDir: value("BACKUP_DIR"),
740
+ contentRoot: "/app/brain-data",
741
+ databases: [
742
+ {
743
+ source: "/data/brain.db",
744
+ name: "brain.db",
745
+ method: "vacuum",
746
+ quickCheck: "bun",
747
+ logicalVector: false,
748
+ assets: true,
749
+ },
750
+ {
751
+ source: "/data/brain-jobs.db",
752
+ name: "brain-jobs.db",
753
+ method: "vacuum",
754
+ quickCheck: "bun",
755
+ logicalVector: false,
756
+ },
757
+ {
758
+ source: "/data/conversations.db",
759
+ name: "conversations.db",
760
+ method: "vacuum",
761
+ quickCheck: "bun",
762
+ logicalVector: false,
763
+ },
764
+ {
765
+ source: "/data/embeddings.db",
766
+ name: "embeddings.db",
767
+ method: "serialize",
768
+ quickCheck: "libsql",
769
+ logicalVector: true,
770
+ },
771
+ {
772
+ source: "/data/runtime-state.db",
773
+ name: "runtime-state.db",
774
+ method: "vacuum",
775
+ quickCheck: "bun",
776
+ logicalVector: false,
777
+ },
778
+ {
779
+ source: "/app/data/auth/auth.db",
780
+ name: "auth.db",
781
+ method: "vacuum",
782
+ quickCheck: "bun",
783
+ logicalVector: false,
784
+ },
785
+ ],
786
+ metadata: {
787
+ snapshotId: value("SNAPSHOT_ID"),
788
+ targetHandle: value("TARGET_HANDLE"),
789
+ host: value("HOST_IDENTIFIER"),
790
+ startedAt: value("STARTED_AT"),
791
+ sourceVersion: value("SOURCE_VERSION"),
792
+ targetVersion: value("TARGET_VERSION"),
793
+ toolVersion: value("TOOL_VERSION"),
794
+ containerId: value("CONTAINER_ID"),
795
+ imageId: value("SOURCE_IMAGE_ID"),
796
+ imageDigest: value("SOURCE_IMAGE_DIGEST"),
797
+ },
798
+ };
799
+ }
800
+
801
+ function shellSafe(value: string, name: string): string {
802
+ if (!/^[A-Za-z0-9._-]+$/.test(value)) {
803
+ throw new Error(`${name} contains unsupported characters`);
804
+ }
805
+ return value;
806
+ }
807
+
808
+ /**
809
+ * Run inside the current runtime before capture. The snapshot proves itself
810
+ * (transactional copies, quick_check, checksums), so it needs a serving
811
+ * runtime with no queued work, not a healthy one: a deploy is often the fix
812
+ * for whatever a plugin reports as degraded. Degradation is named, not refused.
813
+ * A job whose lease expired is abandoned, not running: the next worker
814
+ * reclaims and reruns it, so it is named and backed up as it stands.
815
+ */
816
+ export function renderPredeployReadinessProgram(
817
+ healthUrl: string = "http://127.0.0.1:8080/health/ready",
818
+ ): string {
819
+ return `const response = await fetch(${JSON.stringify(healthUrl)});
820
+ const health = await response.json();
821
+ const queue = health.resources?.queue;
822
+ if (response.status !== 200 || health.status !== "ready") {
823
+ console.error("pre-deploy snapshot: current runtime is not ready");
824
+ process.exit(1);
825
+ }
826
+ const abandoned = queue?.staleLeaseCount ?? 0;
827
+ if (queue && (queue.totals?.pending !== 0 || queue.totals?.processing !== abandoned)) {
828
+ console.error("pre-deploy snapshot: job queue is not idle (" + (queue.totals?.pending ?? "?") + " pending, " + (queue.totals?.processing ?? "?") + " processing, " + abandoned + " abandoned); rerun once it drains");
829
+ process.exit(1);
830
+ }
831
+ if (abandoned > 0) {
832
+ console.error("pre-deploy snapshot: " + abandoned + " abandoned job(s) will rerun after the deploy");
833
+ }
834
+ if (health.operationalStatus !== "operational") {
835
+ const degraded = (health.checks ?? []).filter((check) => check.status !== "healthy").map((check) => check.name);
836
+ console.error("pre-deploy snapshot: runtime is degraded (" + degraded.join(", ") + "); backing it up anyway");
837
+ }
838
+ `;
839
+ }
840
+
841
+ /** The runtime's own notices from a successful capture, as workflow warnings;
842
+ * other remote output (ssh host notes) stays out of the log. */
843
+ /** The asset counts the capture printed, when it printed them. */
844
+ function parseAssetSummary(output: string): PredeployAssetSummary | undefined {
845
+ const count = (name: string): number | undefined => {
846
+ const match = new RegExp(`^${name}=(\\d+)$`, "m").exec(output);
847
+ return match?.[1] === undefined ? undefined : Number(match[1]);
848
+ };
849
+ const referenced = count("ASSETS_REFERENCED");
850
+ const verified = count("ASSETS_VERIFIED");
851
+ const failed = count("ASSETS_FAILED");
852
+ return referenced === undefined ||
853
+ verified === undefined ||
854
+ failed === undefined
855
+ ? undefined
856
+ : { referenced, verified, failed };
857
+ }
858
+
859
+ function assetSummaryLine(assets: PredeployAssetSummary): string {
860
+ return `pre-deploy snapshot assets: ${assets.referenced} referenced, ${assets.verified} verified, ${assets.failed} failed`;
861
+ }
862
+
863
+ /** What the deploy log shows for a backup that completed. */
864
+ export function predeployBackupLogLines(
865
+ result: PredeployBackupResult,
866
+ ): string[] {
867
+ if (!result.applicable) {
868
+ return ["pre-deploy snapshot: not applicable (new server)"];
869
+ }
870
+ return [
871
+ `pre-deploy snapshot verified: ${result.snapshotId}`,
872
+ ...(result.assets ? [assetSummaryLine(result.assets)] : []),
873
+ ];
874
+ }
875
+
876
+ /**
877
+ * What the deploy log shows for a backup that failed: the asset counts the
878
+ * capture reached, and each failed asset with the entities referencing it.
879
+ */
880
+ export function predeployBackupFailureLines(
881
+ stdout: string,
882
+ stderr: string,
883
+ ): string[] {
884
+ const assets = parseAssetSummary(stdout);
885
+ return [
886
+ ...(assets ? [assetSummaryLine(assets)] : []),
887
+ ...stderr
888
+ .split("\n")
889
+ .filter((line) => line.startsWith(ASSET_FAILURE_PREFIX))
890
+ .map(
891
+ (line) =>
892
+ `::error title=Pre-deploy backup::${line.slice("pre-deploy snapshot: ".length).trim()}`,
893
+ ),
894
+ ];
895
+ }
896
+
897
+ export function predeployBackupNotices(stderr: string): string[] {
898
+ const prefix = "pre-deploy snapshot: ";
899
+ return stderr
900
+ .split("\n")
901
+ .filter((line) => line.startsWith(prefix))
902
+ .map(
903
+ (line) =>
904
+ `::warning title=Pre-deploy backup::${line.slice(prefix.length).trim()}`,
905
+ );
906
+ }
907
+
908
+ /**
909
+ * Before a deploy, a fresh online backup of the brain's homeserver, when one
910
+ * runs beside it: a SIGUSR2 makes Tuwunel back its database up into
911
+ * `<dir>/backup`, beside the configuration that holds its secrets, and the
912
+ * step waits until the new backup is there. Refuses the deploy when none
913
+ * appears, as the rest of the predeploy backup does.
914
+ */
915
+ export function renderHomeserverBackupStep(
916
+ options: { dir?: string; waitSeconds?: number } = {},
917
+ ): string {
918
+ const dir = options.dir ?? "/opt/brain-matrix";
919
+ const waitSeconds = options.waitSeconds ?? 120;
920
+ return `homeserver="\${SERVICE_NAME}-matrix"
921
+ if docker ps --filter "name=^\${homeserver}$" --format '{{.Names}}' | grep -qx "$homeserver"; then
922
+ # Tuwunel keeps a set number of backups and numbers each one, so a new
923
+ # backup shows as a higher id rather than as one more file.
924
+ latest_homeserver_backup() {
925
+ find "${dir}/backup/meta" -maxdepth 1 -type f -printf '%f\\n' 2>/dev/null | grep -E '^[0-9]+$' | sort -n | tail -n 1 || true
926
+ }
927
+ before="$(latest_homeserver_backup)"
928
+ before="\${before:-0}"
929
+ docker kill --signal USR2 "$homeserver" >/dev/null
930
+ after="$before"
931
+ for attempt in $(seq 1 ${waitSeconds}); do
932
+ after="$(latest_homeserver_backup)"
933
+ after="\${after:-0}"
934
+ [ "$after" -gt "$before" ] && break
935
+ sleep 1
936
+ done
937
+ if [ "$after" -le "$before" ]; then
938
+ echo "pre-deploy snapshot: the homeserver's backup did not appear in ${dir}/backup" >&2
939
+ exit 1
940
+ fi
941
+ echo "pre-deploy snapshot: homeserver backed up in ${dir}/backup"
942
+ fi
943
+ `;
944
+ }
945
+
946
+ export function renderPredeployBackupRemoteScript(options?: {
947
+ captureProgramBase64?: string;
948
+ }): string {
949
+ const captureProgramBase64 =
950
+ options?.captureProgramBase64 ??
951
+ Buffer.from("capture-program").toString("base64");
952
+ return `#!/usr/bin/env bash
953
+ set -euo pipefail
954
+ umask 077
955
+
956
+ TARGET_HANDLE="$1"
957
+ TARGET_VERSION="$2"
958
+ SERVICE_NAME="$3"
959
+ DEFAULT_RETENTION_COUNT="$4"
960
+ TOOL_VERSION="${PREDEPLOY_BACKUP_TOOL_VERSION}"
961
+ CAPTURE_PROGRAM_BASE64="${captureProgramBase64}"
962
+ state_root="/opt/brain-state"
963
+ runtime_root="/opt/brain-runtime"
964
+ content_root="/opt/brain-data"
965
+ backup_root="\${state_root}/backups"
966
+
967
+ mapfile -t containers < <(docker ps --filter "label=service=\${SERVICE_NAME}" --filter label=role=web --format '{{.ID}}')
968
+ if [ "\${#containers[@]}" -gt 1 ]; then
969
+ echo "pre-deploy snapshot: ambiguous runtime" >&2
970
+ exit 1
971
+ fi
972
+ if [ "\${#containers[@]}" -eq 0 ]; then
973
+ has_state=false
974
+ for path in "$state_root" "$runtime_root" "$content_root" /opt/brain.yaml /opt/brain-dist; do
975
+ if [ -f "$path" ] || { [ -d "$path" ] && find "$path" -mindepth 1 -print -quit 2>/dev/null | grep -q .; }; then
976
+ has_state=true
977
+ break
978
+ fi
979
+ done
980
+ if [ "$has_state" = true ]; then
981
+ echo "pre-deploy snapshot: persistent state exists without an identifiable runtime" >&2
982
+ exit 1
983
+ fi
984
+ echo "pre-deploy snapshot: not applicable (new server)"
985
+ exit 0
986
+ fi
987
+ container="\${containers[0]}"
988
+ status="$(docker inspect "$container" --format '{{.State.Status}}')"
989
+ health="$(docker inspect "$container" --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}')"
990
+ if [ "$status" != running ] || [ "$health" != healthy ]; then
991
+ echo "pre-deploy snapshot: current runtime is not healthy" >&2
992
+ exit 1
993
+ fi
994
+
995
+ ${renderHomeserverBackupStep()}
996
+ docker exec "$container" bun -e '
997
+ ${renderPredeployReadinessProgram()}'
998
+
999
+ required_databases=(
1000
+ "$state_root/brain.db"
1001
+ "$state_root/brain-jobs.db"
1002
+ "$state_root/conversations.db"
1003
+ "$state_root/embeddings.db"
1004
+ "$state_root/runtime-state.db"
1005
+ "$runtime_root/auth/auth.db"
1006
+ )
1007
+ for database in "\${required_databases[@]}"; do
1008
+ if [ ! -f "$database" ]; then
1009
+ echo "pre-deploy snapshot: required database missing" >&2
1010
+ exit 1
1011
+ fi
1012
+ done
1013
+ if [ ! -d "$content_root/.git" ]; then
1014
+ echo "pre-deploy snapshot: content checkout missing" >&2
1015
+ exit 1
1016
+ fi
1017
+
1018
+ prune_verified() {
1019
+ local limit="$1"
1020
+ local preserve="\${2:-}"
1021
+ local candidates=()
1022
+ shopt -s nullglob
1023
+ for candidate in "$backup_root"/predeploy-"$TARGET_HANDLE"-*; do
1024
+ case "$candidate" in *.incomplete) continue ;; esac
1025
+ [ -d "$candidate" ] || continue
1026
+ [ -f "$candidate/manifest.json" ] || continue
1027
+ [ -f "$candidate/manifest.sha256" ] || continue
1028
+ grep -q '"outcome": "verified"' "$candidate/manifest.json" || continue
1029
+ candidates+=("$candidate")
1030
+ done
1031
+ shopt -u nullglob
1032
+ if [ "\${#candidates[@]}" -le "$limit" ]; then return; fi
1033
+ mapfile -t candidates < <(printf '%s\n' "\${candidates[@]}" | sort)
1034
+ local remove_count=$((\${#candidates[@]} - limit))
1035
+ for candidate in "\${candidates[@]}"; do
1036
+ [ "$remove_count" -gt 0 ] || break
1037
+ [ "$candidate" != "$preserve" ] || continue
1038
+ rm -rf -- "$candidate"
1039
+ remove_count=$((remove_count - 1))
1040
+ done
1041
+ }
1042
+
1043
+ install -d -m 700 "$backup_root"
1044
+ prune_verified "$DEFAULT_RETENTION_COUNT"
1045
+ state_bytes=0
1046
+ for database in "\${required_databases[@]}"; do
1047
+ state_bytes=$((state_bytes + $(stat -c %s "$database")))
1048
+ done
1049
+ content_bytes="$(du -sb "$content_root" | cut -f1)"
1050
+ base_bytes=$((state_bytes + content_bytes))
1051
+ required_bytes=$((base_bytes + base_bytes / 2 + 1073741824))
1052
+ available_bytes="$(df --output=avail -B1 "$state_root" | tail -1 | tr -d ' ')"
1053
+ if [ "$available_bytes" -lt "$required_bytes" ]; then
1054
+ echo "pre-deploy snapshot: insufficient disk" >&2
1055
+ exit 1
1056
+ fi
1057
+
1058
+ started_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
1059
+ stamp="$(date -u +%Y%m%dT%H%M%SZ)"
1060
+ target_label="\${TARGET_VERSION:0:12}"
1061
+ snapshot_id="predeploy-\${TARGET_HANDLE}-\${target_label}-\${stamp}"
1062
+ incomplete="\${backup_root}/\${snapshot_id}.incomplete"
1063
+ final="\${backup_root}/\${snapshot_id}"
1064
+ container_backup="/data/backups/\${snapshot_id}.incomplete"
1065
+ test ! -e "$incomplete"
1066
+ test ! -e "$final"
1067
+ install -d -m 700 "$incomplete"
1068
+
1069
+ source_version="$(docker exec "$container" bun -e 'const pkg = await Bun.file("/app/node_modules/@rizom/brain/package.json").json(); process.stdout.write(pkg.version)')"
1070
+ source_image_id="$(docker inspect "$container" --format '{{.Image}}')"
1071
+ source_image_digest="$(docker image inspect "$source_image_id" --format '{{join .RepoDigests ","}}')"
1072
+ host_identifier="$(hostname)"
1073
+ docker inspect "$container" --format '{{json .State}}' > "$incomplete/container-state.json"
1074
+ docker inspect "$container" --format '{{json .Mounts}}' > "$incomplete/container-mounts.json"
1075
+ printf '%s\n' "$container" > "$incomplete/container-id.txt"
1076
+ printf '%s\n' "$source_image_id" > "$incomplete/container-image-id.txt"
1077
+ printf '%s\n' "$source_image_digest" > "$incomplete/container-image-digest.txt"
1078
+ cp /opt/brain.yaml "$incomplete/brain.yaml"
1079
+
1080
+ printf '%s' "$CAPTURE_PROGRAM_BASE64" | base64 -d | docker exec -i \
1081
+ -e BACKUP_DIR="$container_backup" \
1082
+ -e SNAPSHOT_ID="$snapshot_id" \
1083
+ -e TARGET_HANDLE="$TARGET_HANDLE" \
1084
+ -e HOST_IDENTIFIER="$host_identifier" \
1085
+ -e STARTED_AT="$started_at" \
1086
+ -e SOURCE_VERSION="$source_version" \
1087
+ -e TARGET_VERSION="$TARGET_VERSION" \
1088
+ -e TOOL_VERSION="$TOOL_VERSION" \
1089
+ -e CONTAINER_ID="$container" \
1090
+ -e SOURCE_IMAGE_ID="$source_image_id" \
1091
+ -e SOURCE_IMAGE_DIGEST="$source_image_digest" \
1092
+ "$container" bun run - --capture
1093
+
1094
+ chmod 600 "$incomplete"/*
1095
+ (
1096
+ cd "$incomplete"
1097
+ sha256sum manifest.json > manifest-checksum.txt
1098
+ chmod 600 manifest-checksum.txt
1099
+ : > manifest.sha256
1100
+ while IFS= read -r file; do
1101
+ sha256sum "$file" >> manifest.sha256
1102
+ done < <(find . -mindepth 1 -maxdepth 1 -type f ! -name manifest.sha256 -printf '%f\n' | sort)
1103
+ chmod 600 manifest.sha256
1104
+ sha256sum --check manifest.sha256 >/dev/null
1105
+ )
1106
+
1107
+ test "$(stat -c %a "$incomplete")" = 700
1108
+ if find "$incomplete" -mindepth 1 -maxdepth 1 -type f ! -perm 600 -print -quit | grep -q .; then
1109
+ echo "pre-deploy snapshot: invalid file permissions" >&2
1110
+ exit 1
1111
+ fi
1112
+ mv "$incomplete" "$final"
1113
+ (cd "$final" && sha256sum --check manifest.sha256 >/dev/null)
1114
+ prune_verified "$DEFAULT_RETENTION_COUNT" "$final"
1115
+
1116
+ duration_seconds=$(( $(date -u +%s) - $(date -u -d "$started_at" +%s) ))
1117
+ total_bytes="$(du -sb "$final" | cut -f1)"
1118
+ echo "SNAPSHOT_ID=$snapshot_id"
1119
+ echo "BACKUP=$final"
1120
+ echo "SOURCE_VERSION=$source_version"
1121
+ echo "TARGET_VERSION=$TARGET_VERSION"
1122
+ echo "TOTAL_BYTES=$total_bytes"
1123
+ echo "DURATION_SECONDS=$duration_seconds"
1124
+ echo "VERIFICATION=passed"
1125
+ `;
1126
+ }
1127
+
1128
+ export function parsePredeployBackupOutput(
1129
+ output: string,
1130
+ ): PredeployBackupResult {
1131
+ if (output.includes("pre-deploy snapshot: not applicable (new server)")) {
1132
+ return { applicable: false };
1133
+ }
1134
+ const values = new Map<string, string>();
1135
+ for (const line of output.split(/\r?\n/)) {
1136
+ const index = line.indexOf("=");
1137
+ if (index > 0) values.set(line.slice(0, index), line.slice(index + 1));
1138
+ }
1139
+ const snapshotId = values.get("SNAPSHOT_ID");
1140
+ const backupPath = values.get("BACKUP");
1141
+ const sourceVersion = values.get("SOURCE_VERSION");
1142
+ const targetVersion = values.get("TARGET_VERSION");
1143
+ const totalBytes = Number(values.get("TOTAL_BYTES"));
1144
+ const durationSeconds = Number(values.get("DURATION_SECONDS"));
1145
+ if (
1146
+ !snapshotId ||
1147
+ !backupPath ||
1148
+ !sourceVersion ||
1149
+ !targetVersion ||
1150
+ !Number.isSafeInteger(totalBytes) ||
1151
+ totalBytes < 0 ||
1152
+ !Number.isSafeInteger(durationSeconds) ||
1153
+ durationSeconds < 0 ||
1154
+ values.get("VERIFICATION") !== "passed"
1155
+ ) {
1156
+ throw new Error("Incomplete predeploy backup result");
1157
+ }
1158
+ const assets = parseAssetSummary(output);
1159
+ return {
1160
+ applicable: true,
1161
+ snapshotId,
1162
+ backupPath,
1163
+ sourceVersion,
1164
+ targetVersion,
1165
+ totalBytes,
1166
+ durationSeconds,
1167
+ verification: "passed",
1168
+ ...(assets && { assets }),
1169
+ };
1170
+ }
1171
+
1172
+ function appendWorkflowResult(result: PredeployBackupResult): void {
1173
+ const outputPath = process.env["GITHUB_OUTPUT"];
1174
+ const summaryPath = process.env["GITHUB_STEP_SUMMARY"];
1175
+ if (outputPath) {
1176
+ appendFileSync(
1177
+ outputPath,
1178
+ result.applicable
1179
+ ? `applicable=true\nsnapshot_id=${result.snapshotId}\nbackup_path=${result.backupPath}\n`
1180
+ : "applicable=false\n",
1181
+ );
1182
+ }
1183
+ if (summaryPath) {
1184
+ appendFileSync(
1185
+ summaryPath,
1186
+ result.applicable
1187
+ ? `### Verified pre-deploy snapshot\n- Snapshot: \`${result.snapshotId}\`\n- Path: \`${result.backupPath}\`\n- Bytes: \`${result.totalBytes}\`\n- Duration: \`${result.durationSeconds}s\`\n- Verification: passed\n${result.assets ? `- Assets: ${result.assets.referenced} referenced, ${result.assets.verified} verified, ${result.assets.failed} failed\n` : ""}`
1188
+ : "### Pre-deploy snapshot\nNot applicable: new server with no persistent state.\n",
1189
+ );
1190
+ }
1191
+ }
1192
+
1193
+ export async function runPredeployBackup(): Promise<PredeployBackupResult> {
1194
+ const serverIp = shellSafe(process.env["SERVER_IP"] ?? "", "SERVER_IP");
1195
+ const targetHandle = shellSafe(
1196
+ process.env["TARGET_HANDLE"] ?? "",
1197
+ "TARGET_HANDLE",
1198
+ );
1199
+ const targetVersion = shellSafe(
1200
+ process.env["TARGET_VERSION"] ?? "",
1201
+ "TARGET_VERSION",
1202
+ );
1203
+ const serviceName = shellSafe(
1204
+ process.env["SERVICE_NAME"] ?? "",
1205
+ "SERVICE_NAME",
1206
+ );
1207
+ const sshUser = shellSafe(process.env["SSH_USER"] ?? "root", "SSH_USER");
1208
+ const retention = Number(
1209
+ process.env["PREDEPLOY_BACKUP_RETENTION_COUNT"] ??
1210
+ DEFAULT_PREDEPLOY_BACKUP_RETENTION_COUNT,
1211
+ );
1212
+ if (!Number.isInteger(retention) || retention < 1 || retention > 100) {
1213
+ throw new Error(
1214
+ "PREDEPLOY_BACKUP_RETENTION_COUNT must be between 1 and 100",
1215
+ );
1216
+ }
1217
+
1218
+ const source = await Bun.file(import.meta.path).arrayBuffer();
1219
+ const remoteScript = renderPredeployBackupRemoteScript({
1220
+ captureProgramBase64: Buffer.from(source).toString("base64"),
1221
+ });
1222
+ const child = Bun.spawn(
1223
+ [
1224
+ "ssh",
1225
+ `${sshUser}@${serverIp}`,
1226
+ "bash",
1227
+ "-s",
1228
+ "--",
1229
+ targetHandle,
1230
+ targetVersion,
1231
+ serviceName,
1232
+ String(retention),
1233
+ ],
1234
+ { stdin: "pipe", stdout: "pipe", stderr: "pipe" },
1235
+ );
1236
+ await child.stdin.write(remoteScript);
1237
+ await child.stdin.end();
1238
+ const [exitCode, stdout, stderr] = await Promise.all([
1239
+ child.exited,
1240
+ new Response(child.stdout).text(),
1241
+ new Response(child.stderr).text(),
1242
+ ]);
1243
+ if (exitCode !== 0) {
1244
+ for (const line of predeployBackupFailureLines(stdout, stderr)) {
1245
+ console.log(line);
1246
+ }
1247
+ const diagnostic = stderr.trim().slice(0, 1000);
1248
+ throw new Error(
1249
+ `Predeploy backup failed${diagnostic ? `: ${diagnostic}` : ""}`,
1250
+ );
1251
+ }
1252
+ for (const notice of predeployBackupNotices(stderr)) console.log(notice);
1253
+ const result = parsePredeployBackupOutput(stdout);
1254
+ appendWorkflowResult(result);
1255
+ for (const line of predeployBackupLogLines(result)) console.log(line);
1256
+ return result;
1257
+ }
1258
+
1259
+ if (import.meta.main) {
1260
+ if (process.argv.includes("--capture")) {
1261
+ await capturePredeployBackup(captureConfigFromEnvironment());
1262
+ } else {
1263
+ await runPredeployBackup();
1264
+ }
1265
+ }