@rehearsal-db/core 0.1.0-beta.1

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 (35) hide show
  1. package/BENCHMARKS.md +61 -0
  2. package/CHANGELOG.md +59 -0
  3. package/COMPATIBILITY.md +22 -0
  4. package/LICENSE +21 -0
  5. package/README.md +375 -0
  6. package/SECURITY.md +19 -0
  7. package/SUPPORT.md +15 -0
  8. package/docs/adapters.md +23 -0
  9. package/docs/baselines.md +33 -0
  10. package/docs/commands.md +35 -0
  11. package/docs/configuration.md +98 -0
  12. package/docs/getting-started.md +247 -0
  13. package/docs/glossary.md +33 -0
  14. package/docs/production-source.md +33 -0
  15. package/docs/releasing.md +79 -0
  16. package/docs/sanitization.md +69 -0
  17. package/docs/security-model.md +40 -0
  18. package/docs/troubleshooting.md +50 -0
  19. package/docs/tutorial.md +96 -0
  20. package/package.json +77 -0
  21. package/scripts/lib/environment/local_supabase.mjs +197 -0
  22. package/scripts/lib/rehearsal/baseline_artifact.mjs +536 -0
  23. package/scripts/lib/rehearsal/baseline_builder.mjs +155 -0
  24. package/scripts/lib/rehearsal/configuration.d.mts +85 -0
  25. package/scripts/lib/rehearsal/configuration.mjs +559 -0
  26. package/scripts/lib/rehearsal/diagnostics.mjs +193 -0
  27. package/scripts/lib/rehearsal/migration_history.mjs +220 -0
  28. package/scripts/lib/rehearsal/plan.mjs +587 -0
  29. package/scripts/lib/rehearsal/process_environment.mjs +64 -0
  30. package/scripts/lib/rehearsal/runtime_restore.mjs +310 -0
  31. package/scripts/lib/rehearsal/sanitization_policy.mjs +169 -0
  32. package/scripts/lib/rehearsal/schema_snapshot.mjs +113 -0
  33. package/scripts/lib/rehearsal/service_environment.mjs +82 -0
  34. package/scripts/operations/database/manage_rehearsal_database.mjs +784 -0
  35. package/scripts/operations/rehearsal/rehearsal_cli.mjs +565 -0
@@ -0,0 +1,784 @@
1
+ /**
2
+ * Purpose: Restore and manage the disposable local Rehearsal Supabase runtime from
3
+ * the active verified sanitized baseline.
4
+ * Run: `npm run db:rehearsal:reset`, `npm run db:rehearsal:start`,
5
+ * `npm run db:rehearsal:status`, or `npm run db:rehearsal:stop`.
6
+ * Reset deletes only the dedicated local Rehearsal runtime and its Docker volumes.
7
+ */
8
+
9
+ import { spawn } from "node:child_process";
10
+ import { cp, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
11
+ import { createReadStream } from "node:fs";
12
+ import { once } from "node:events";
13
+ import { join, resolve } from "node:path";
14
+ import { createInterface } from "node:readline";
15
+ import { pathToFileURL } from "node:url";
16
+ import {
17
+ resolveActiveBaselinePaths,
18
+ verifyActiveBaseline,
19
+ } from "../../lib/rehearsal/baseline_artifact.mjs";
20
+ import {
21
+ createCleanProcessEnvironment,
22
+ assertLoopbackUrl,
23
+ } from "../../lib/rehearsal/process_environment.mjs";
24
+ import {
25
+ localCommandSucceeds,
26
+ readLocalSupabaseEnvironment,
27
+ removeLocalSupabaseProjectResources,
28
+ runLocalCommand,
29
+ startLocalSupabase,
30
+ stopLocalSupabase,
31
+ } from "../../lib/environment/local_supabase.mjs";
32
+ import {
33
+ buildRestoreSqlPrefix,
34
+ buildRestoreSqlSuffix,
35
+ createCandidateMigrationReceipt,
36
+ encodeBaselineRecordForCopy,
37
+ summarizeRestoreError,
38
+ } from "../../lib/rehearsal/runtime_restore.mjs";
39
+ import {
40
+ buildMigrationLedgerInventory,
41
+ compareSourceToReplay,
42
+ createMigrationReplayReceipt,
43
+ readMigrationFileInventory,
44
+ } from "../../lib/rehearsal/migration_history.mjs";
45
+ import { loadRehearsalConfig } from "../../lib/rehearsal/configuration.mjs";
46
+ import { readRehearsalServiceEnvironment } from "../../lib/rehearsal/service_environment.mjs";
47
+ import {
48
+ captureLocalPublicSchema,
49
+ compareProductionSchemaDumps,
50
+ } from "../../lib/rehearsal/schema_snapshot.mjs";
51
+
52
+ const repositoryRoot = process.cwd();
53
+ const loadedConfiguration = await loadRehearsalConfig({
54
+ projectRoot: repositoryRoot,
55
+ });
56
+ const { config, paths: configuredPaths } = loadedConfiguration;
57
+ const artifactRoot = configuredPaths.artifactDirectory;
58
+ const runtimeWorkdir = configuredPaths.runtimeWorkdir;
59
+ const runtimeSupabaseDirectory = join(runtimeWorkdir, "supabase");
60
+ const runtimeMarkerPath = join(runtimeWorkdir, "baseline.json");
61
+ const runtimeCandidateReceiptPath = join(
62
+ runtimeWorkdir,
63
+ "candidate-receipt.json",
64
+ );
65
+ const environmentPath = configuredPaths.applicationEnvironment;
66
+ const configTemplatePath = configuredPaths.rehearsalConfig;
67
+ const manifestPath = configuredPaths.sanitizationPolicy;
68
+ const applicationMigrations = new URL(
69
+ "./",
70
+ pathToFileURL(`${configuredPaths.migrationDirectory}/`),
71
+ );
72
+ const projectId = config.runtime.projectId;
73
+ const runtimeAdapter = configuredPaths.runtimeAdapter
74
+ ? await import(pathToFileURL(configuredPaths.runtimeAdapter).href)
75
+ : null;
76
+ const environmentKeyPattern = /^[A-Z][A-Z0-9_]*$/u;
77
+ const action = process.argv[2] ?? "status";
78
+
79
+ const readServiceEnvironment = () =>
80
+ readRehearsalServiceEnvironment({
81
+ path: configuredPaths.serviceEnvironment,
82
+ keys: config.supabase.serviceEnvironmentVariables,
83
+ blockedKeys: config.safety.blockedEnvironmentVariables,
84
+ });
85
+
86
+ const assertRuntimePath = () => {
87
+ const resolvedRoot = resolve(artifactRoot);
88
+ const resolvedRuntime = resolve(runtimeWorkdir);
89
+ if (resolvedRuntime !== join(resolvedRoot, "runtime")) {
90
+ throw new Error("Refusing an unsafe Rehearsal runtime path.");
91
+ }
92
+ };
93
+
94
+ const pathExists = async (path) =>
95
+ stat(path)
96
+ .then(() => true)
97
+ .catch((error) => {
98
+ if (error?.code === "ENOENT") return false;
99
+ throw error;
100
+ });
101
+
102
+ const hasProjectRuntimeResources = () => {
103
+ const containers = runLocalCommand(
104
+ "docker",
105
+ [
106
+ "ps",
107
+ "--all",
108
+ "--filter",
109
+ `label=com.supabase.cli.project=${projectId}`,
110
+ "--format",
111
+ "{{.ID}}",
112
+ ],
113
+ { capture: true, cwd: repositoryRoot },
114
+ ).trim();
115
+ const volumes = runLocalCommand(
116
+ "docker",
117
+ ["volume", "ls", "--format", "{{.Name}}"],
118
+ { capture: true, cwd: repositoryRoot },
119
+ )
120
+ .split("\n")
121
+ .some((name) => name.trim().endsWith(`_${projectId}`));
122
+ return Boolean(containers) || volumes;
123
+ };
124
+
125
+ const removeRuntime = async () => {
126
+ assertRuntimePath();
127
+ const hasRuntimeConfig = await pathExists(
128
+ join(runtimeSupabaseDirectory, "config.toml"),
129
+ );
130
+ if (hasRuntimeConfig || hasProjectRuntimeResources()) {
131
+ try {
132
+ const serviceEnvironment = await readServiceEnvironment().catch(
133
+ () => ({}),
134
+ );
135
+ runLocalCommand(
136
+ "supabase",
137
+ hasRuntimeConfig
138
+ ? ["stop", "--no-backup", "--workdir", runtimeWorkdir]
139
+ : ["stop", "--no-backup", "--project-id", projectId],
140
+ { cwd: repositoryRoot, environment: serviceEnvironment },
141
+ );
142
+ } catch {
143
+ removeLocalSupabaseProjectResources({
144
+ cwd: repositoryRoot,
145
+ projectId,
146
+ });
147
+ }
148
+ }
149
+ await rm(runtimeWorkdir, { recursive: true, force: true });
150
+ await rm(environmentPath, { force: true });
151
+ };
152
+
153
+ const findDatabaseContainer = () => {
154
+ const output = runLocalCommand(
155
+ "docker",
156
+ [
157
+ "ps",
158
+ "--filter",
159
+ `label=com.supabase.cli.project=${projectId}`,
160
+ "--format",
161
+ "{{.Names}}",
162
+ ],
163
+ { capture: true, cwd: repositoryRoot },
164
+ );
165
+ const names = output
166
+ .split("\n")
167
+ .map((value) => value.trim())
168
+ .filter((value) => value.startsWith("supabase_db_"));
169
+ if (names.length !== 1) {
170
+ throw new Error(
171
+ `Expected one local Rehearsal database container; found ${names.length}.`,
172
+ );
173
+ }
174
+ return names[0];
175
+ };
176
+
177
+ const writeChunk = async (stream, chunk, completion) => {
178
+ if (stream.destroyed || stream.writableEnded) {
179
+ throw new Error("The Rehearsal restore connection closed early.");
180
+ }
181
+ if (!stream.write(chunk)) {
182
+ await Promise.race([once(stream, "drain"), completion]);
183
+ if (stream.destroyed || stream.writableEnded) {
184
+ throw new Error("The Rehearsal restore connection closed early.");
185
+ }
186
+ }
187
+ };
188
+
189
+ const restoreBaselineRows = async ({ baseline, paths, manifest }) => {
190
+ const child = spawn(
191
+ "docker",
192
+ [
193
+ "exec",
194
+ "--interactive",
195
+ findDatabaseContainer(),
196
+ "psql",
197
+ "--quiet",
198
+ "--set",
199
+ "ON_ERROR_STOP=1",
200
+ "--username",
201
+ "postgres",
202
+ "--dbname",
203
+ "postgres",
204
+ ],
205
+ {
206
+ cwd: repositoryRoot,
207
+ env: createCleanProcessEnvironment(),
208
+ stdio: ["pipe", "ignore", "pipe"],
209
+ },
210
+ );
211
+ let stderr = "";
212
+ child.stderr.setEncoding("utf8");
213
+ child.stderr.on("data", (chunk) => {
214
+ stderr = `${stderr}${chunk}`.slice(-16_384);
215
+ });
216
+ const completion = new Promise((complete, reject) => {
217
+ child.once("error", reject);
218
+ child.once("close", complete);
219
+ });
220
+ child.stdin.on("error", () => undefined);
221
+ try {
222
+ await writeChunk(child.stdin, buildRestoreSqlPrefix(), completion);
223
+ const lines = createInterface({
224
+ input: createReadStream(paths.dataPath, { encoding: "utf8" }),
225
+ crlfDelay: Infinity,
226
+ });
227
+ for await (const line of lines) {
228
+ if (line) {
229
+ await writeChunk(
230
+ child.stdin,
231
+ `${encodeBaselineRecordForCopy(line)}\n`,
232
+ completion,
233
+ );
234
+ }
235
+ }
236
+ await writeChunk(
237
+ child.stdin,
238
+ buildRestoreSqlSuffix({
239
+ manifest,
240
+ tableCounts: baseline.tableCounts,
241
+ }),
242
+ completion,
243
+ );
244
+ child.stdin.end();
245
+ const exitCode = await completion;
246
+ if (exitCode !== 0) {
247
+ throw new Error(
248
+ `The local Rehearsal restore failed. ${summarizeRestoreError(stderr)}`,
249
+ );
250
+ }
251
+ } catch (error) {
252
+ if (child.exitCode === null) child.kill("SIGTERM");
253
+ await completion.catch(() => undefined);
254
+ throw new Error(
255
+ `The local Rehearsal restore failed. ${summarizeRestoreError(stderr)}`,
256
+ { cause: error },
257
+ );
258
+ }
259
+ };
260
+
261
+ const restoreBaselineAssets = async ({ baseline, paths, environment }) => {
262
+ const assets = Object.entries(baseline.storageAssets ?? {});
263
+ if (assets.length === 0) return;
264
+ assertLoopbackUrl("Rehearsal Supabase API", environment.apiUrl);
265
+ for (const [relativePath, receipt] of assets) {
266
+ const content = await readFile(
267
+ join(paths.generationDirectory, relativePath),
268
+ );
269
+ const objectUrl = new URL(
270
+ `/storage/v1/object/${encodeURIComponent(receipt.bucket)}/${receipt.objectPath
271
+ .split("/")
272
+ .map(encodeURIComponent)
273
+ .join("/")}`,
274
+ environment.apiUrl,
275
+ );
276
+ const response = await fetch(objectUrl, {
277
+ method: "POST",
278
+ headers: {
279
+ apikey: environment.serviceRoleKey,
280
+ authorization: `Bearer ${environment.serviceRoleKey}`,
281
+ "content-type": receipt.contentType,
282
+ "x-upsert": "true",
283
+ },
284
+ body: content,
285
+ signal: AbortSignal.timeout(30_000),
286
+ });
287
+ if (!response.ok) {
288
+ throw new Error(
289
+ `The local Rehearsal Storage restore failed for ${receipt.bucket} with status ${response.status}.`,
290
+ );
291
+ }
292
+ }
293
+ };
294
+
295
+ const prepareRuntimeWorkdir = async ({ baseline, paths }) => {
296
+ assertRuntimePath();
297
+ await mkdir(join(runtimeSupabaseDirectory, "migrations"), {
298
+ recursive: true,
299
+ mode: 0o700,
300
+ });
301
+ await cp(configTemplatePath, join(runtimeSupabaseDirectory, "config.toml"));
302
+ for (const filename of Object.keys(baseline.migrations).sort()) {
303
+ await cp(
304
+ join(paths.migrationsDirectory, filename),
305
+ join(runtimeSupabaseDirectory, "migrations", filename),
306
+ );
307
+ }
308
+ await writeFile(
309
+ runtimeMarkerPath,
310
+ `${JSON.stringify(
311
+ {
312
+ formatVersion: 1,
313
+ generationId: baseline.generationId,
314
+ dataSha256: baseline.files["sanitized-data.ndjson"].sha256,
315
+ },
316
+ null,
317
+ "\t",
318
+ )}\n`,
319
+ { mode: 0o600 },
320
+ );
321
+ };
322
+
323
+ const writeRuntimeEnvironment = async ({
324
+ environment,
325
+ baseline,
326
+ projectRuntime,
327
+ }) => {
328
+ assertLoopbackUrl("Rehearsal Supabase API", environment.apiUrl);
329
+ const variables = {
330
+ REHEARSAL_RUNTIME_ENVIRONMENT: "rehearsal",
331
+ REHEARSAL_BASELINE_ID: baseline.generationId,
332
+ SUPABASE_URL: environment.apiUrl,
333
+ SUPABASE_PUBLISHABLE_KEY: environment.publishableKey,
334
+ SUPABASE_SERVICE_ROLE_KEY: environment.serviceRoleKey,
335
+ ...projectRuntime.environmentVariables,
336
+ };
337
+ await writeFile(
338
+ environmentPath,
339
+ [
340
+ "# Generated local Rehearsal runtime credentials. Do not commit.",
341
+ ...Object.entries(variables).map(([key, value]) => `${key}=${value}`),
342
+ "",
343
+ ].join("\n"),
344
+ { mode: 0o600 },
345
+ );
346
+ };
347
+
348
+ const runDatabaseSql = (sql) => {
349
+ const databaseArguments = [
350
+ "exec",
351
+ "--interactive",
352
+ findDatabaseContainer(),
353
+ "psql",
354
+ "--quiet",
355
+ "--no-align",
356
+ "--tuples-only",
357
+ "--set",
358
+ "ON_ERROR_STOP=1",
359
+ "--username",
360
+ "postgres",
361
+ "--dbname",
362
+ "postgres",
363
+ ];
364
+ return runLocalCommand("docker", databaseArguments, {
365
+ capture: true,
366
+ cwd: repositoryRoot,
367
+ input: sql,
368
+ });
369
+ };
370
+
371
+ const restoreProductionSchema = async ({ baseline, paths }) => {
372
+ const receipt = baseline.files?.["production-schema.sql"];
373
+ if (baseline.formatVersion === 1 && receipt === undefined) return null;
374
+ if (
375
+ baseline.formatVersion !== 2 ||
376
+ !/^[a-f0-9]{64}$/u.test(receipt?.sha256 ?? "") ||
377
+ !Number.isSafeInteger(receipt?.bytes)
378
+ ) {
379
+ throw new Error(
380
+ "The active baseline predates exact production-schema restoration; refresh it first.",
381
+ );
382
+ }
383
+ const schemaSql = await readFile(paths.schemaPath, "utf8");
384
+ runDatabaseSql("drop schema if exists public cascade;");
385
+ if (runtimeAdapter?.prepareSchema) {
386
+ const preparation = runtimeAdapter.prepareSchema({
387
+ runSql: runDatabaseSql,
388
+ });
389
+ if (!preparation || typeof preparation.message !== "string") {
390
+ throw new Error(
391
+ "The project runtime adapter returned an invalid schema preparation result.",
392
+ );
393
+ }
394
+ }
395
+ runDatabaseSql(schemaSql);
396
+ const restoredSchema = await captureLocalPublicSchema({
397
+ repositoryRoot,
398
+ artifactRoot,
399
+ workdir: runtimeWorkdir,
400
+ });
401
+ return compareProductionSchemaDumps({
402
+ expected: schemaSql,
403
+ actual: restoredSchema,
404
+ });
405
+ };
406
+
407
+ const configureProjectRuntime = ({ environment, baseline }) => {
408
+ assertLoopbackUrl("Rehearsal Supabase API", environment.apiUrl);
409
+ if (!runtimeAdapter?.configureRuntime) {
410
+ return {
411
+ message: "Project-neutral local runtime is configured.",
412
+ environmentVariables: {},
413
+ };
414
+ }
415
+ const projectRuntime = runtimeAdapter.configureRuntime({
416
+ baseline,
417
+ environment,
418
+ runSql: runDatabaseSql,
419
+ });
420
+ if (
421
+ !projectRuntime ||
422
+ typeof projectRuntime.message !== "string" ||
423
+ !projectRuntime.environmentVariables ||
424
+ typeof projectRuntime.environmentVariables !== "object" ||
425
+ Array.isArray(projectRuntime.environmentVariables)
426
+ ) {
427
+ throw new Error("The project runtime adapter returned an invalid result.");
428
+ }
429
+ for (const [key, value] of Object.entries(
430
+ projectRuntime.environmentVariables,
431
+ )) {
432
+ if (
433
+ !environmentKeyPattern.test(key) ||
434
+ typeof value !== "string" ||
435
+ /[\n\r\0]/u.test(value)
436
+ ) {
437
+ throw new Error(
438
+ "The project runtime adapter returned an unsafe environment variable.",
439
+ );
440
+ }
441
+ }
442
+ return projectRuntime;
443
+ };
444
+
445
+ const readActive = async () => {
446
+ const [baseline, paths, manifest] = await Promise.all([
447
+ verifyActiveBaseline({ artifactRoot }),
448
+ resolveActiveBaselinePaths({ artifactRoot }),
449
+ readFile(manifestPath, "utf8").then(JSON.parse),
450
+ ]);
451
+ return { baseline, paths, manifest };
452
+ };
453
+
454
+ const resetRuntime = async () => {
455
+ const active = await readActive();
456
+ const serviceEnvironment = await readServiceEnvironment();
457
+ await removeRuntime();
458
+ try {
459
+ await prepareRuntimeWorkdir(active);
460
+ const environment = startLocalSupabase({
461
+ cwd: repositoryRoot,
462
+ workdir: runtimeWorkdir,
463
+ exclude: ["edge-runtime", "logflare", "vector", "realtime"],
464
+ environment: serviceEnvironment,
465
+ });
466
+ const structuralSchemaSha256 = await restoreProductionSchema(active);
467
+ await restoreBaselineRows(active);
468
+ await restoreBaselineAssets({
469
+ baseline: active.baseline,
470
+ paths: active.paths,
471
+ environment,
472
+ });
473
+ const projectRuntime = configureProjectRuntime({
474
+ environment,
475
+ baseline: active.baseline,
476
+ });
477
+ await writeRuntimeEnvironment({
478
+ environment,
479
+ baseline: active.baseline,
480
+ projectRuntime,
481
+ });
482
+ await writeFile(
483
+ runtimeMarkerPath,
484
+ `${JSON.stringify(
485
+ {
486
+ formatVersion: active.baseline.formatVersion,
487
+ generationId: active.baseline.generationId,
488
+ dataSha256: active.baseline.files["sanitized-data.ndjson"].sha256,
489
+ schemaSha256:
490
+ active.baseline.files?.["production-schema.sql"]?.sha256 ?? null,
491
+ structuralSchemaSha256,
492
+ },
493
+ null,
494
+ "\t",
495
+ )}\n`,
496
+ { mode: 0o600 },
497
+ );
498
+ console.log(
499
+ `Restored Rehearsal baseline ${active.baseline.generationId}: ${active.baseline.rowCount} rows across ${Object.keys(active.baseline.tableCounts).length} tables.`,
500
+ );
501
+ console.log(projectRuntime.message);
502
+ return environment;
503
+ } catch (error) {
504
+ await removeRuntime().catch(() => undefined);
505
+ throw error;
506
+ }
507
+ };
508
+
509
+ const startRuntime = async () => {
510
+ const { baseline } = await readActive();
511
+ if (!(await pathExists(runtimeMarkerPath))) return resetRuntime();
512
+ const serviceEnvironment = await readServiceEnvironment();
513
+ const marker = JSON.parse(await readFile(runtimeMarkerPath, "utf8"));
514
+ if (
515
+ marker.generationId !== baseline.generationId ||
516
+ marker.dataSha256 !== baseline.files["sanitized-data.ndjson"].sha256 ||
517
+ marker.schemaSha256 !==
518
+ (baseline.files?.["production-schema.sql"]?.sha256 ?? null)
519
+ ) {
520
+ throw new Error(
521
+ "The local Rehearsal runtime does not match the active baseline; run db:rehearsal:reset.",
522
+ );
523
+ }
524
+ const environment = startLocalSupabase({
525
+ cwd: repositoryRoot,
526
+ workdir: runtimeWorkdir,
527
+ exclude: ["edge-runtime", "logflare", "vector", "realtime"],
528
+ environment: serviceEnvironment,
529
+ });
530
+ const projectRuntime = configureProjectRuntime({ environment, baseline });
531
+ await writeRuntimeEnvironment({
532
+ environment,
533
+ baseline,
534
+ projectRuntime,
535
+ });
536
+ return environment;
537
+ };
538
+
539
+ const readCandidateReceipt = async (baseline) => {
540
+ const currentFiles = await readMigrationFileInventory(applicationMigrations);
541
+ return {
542
+ currentFiles,
543
+ ...createCandidateMigrationReceipt({
544
+ baselineManifest: baseline,
545
+ currentFiles,
546
+ }),
547
+ };
548
+ };
549
+
550
+ const readRuntimeMigrationLedger = () => {
551
+ const output = runLocalCommand(
552
+ "docker",
553
+ [
554
+ "exec",
555
+ "--interactive",
556
+ findDatabaseContainer(),
557
+ "psql",
558
+ "--quiet",
559
+ "--no-align",
560
+ "--tuples-only",
561
+ "--set",
562
+ "ON_ERROR_STOP=1",
563
+ "--username",
564
+ "postgres",
565
+ "--dbname",
566
+ "postgres",
567
+ ],
568
+ {
569
+ capture: true,
570
+ cwd: repositoryRoot,
571
+ input: `select coalesce(json_agg(json_build_object(
572
+ 'version', version,
573
+ 'name', name,
574
+ 'statements', statements
575
+ ) order by version), '[]'::json)::text
576
+ from supabase_migrations.schema_migrations;`,
577
+ },
578
+ );
579
+ return buildMigrationLedgerInventory(
580
+ JSON.parse(output.trim()),
581
+ "Rehearsal runtime migration ledger",
582
+ );
583
+ };
584
+
585
+ const verifyRuntimeMigrationHistory = async ({ baseline, currentFiles }) => {
586
+ const ledger = readRuntimeMigrationLedger();
587
+ const appliedFiles = currentFiles.slice(0, ledger.length);
588
+ const replayReceipt = createMigrationReplayReceipt({
589
+ files: appliedFiles,
590
+ ledger,
591
+ });
592
+ return compareSourceToReplay({
593
+ sourceLedger: baseline.sourceMigrationHistory,
594
+ replayReceipt,
595
+ snapshotSchemaSha256: baseline.files?.["production-schema.sql"]?.sha256,
596
+ });
597
+ };
598
+
599
+ const verifyRuntime = async () => {
600
+ const { baseline } = await readActive();
601
+ const environment = await startRuntime();
602
+ const candidateReceipt = await readCandidateReceipt(baseline);
603
+ const migrationComparison = await verifyRuntimeMigrationHistory({
604
+ baseline,
605
+ currentFiles: candidateReceipt.currentFiles,
606
+ });
607
+ let projectVerification;
608
+ if (runtimeAdapter?.verifyRuntime) {
609
+ projectVerification = runtimeAdapter.verifyRuntime({
610
+ baseline,
611
+ environment,
612
+ runSql: runDatabaseSql,
613
+ });
614
+ if (
615
+ !projectVerification ||
616
+ typeof projectVerification.message !== "string"
617
+ ) {
618
+ throw new Error(
619
+ "The project runtime adapter returned an invalid verification result.",
620
+ );
621
+ }
622
+ }
623
+ console.log(
624
+ `Verified Rehearsal runtime ${baseline.generationId}: immutable baseline and migration history are valid with ${migrationComparison.candidates.length} applied candidate migrations. Runtime rows may differ from the baseline until the next reset.`,
625
+ );
626
+ if (projectVerification) console.log(projectVerification.message);
627
+ return { baseline, candidateReceipt, migrationComparison };
628
+ };
629
+
630
+ const migrateRuntime = async () => {
631
+ const { baseline } = await readActive();
632
+ await startRuntime();
633
+ const receipt = await readCandidateReceipt(baseline);
634
+ if (receipt.candidates.length === 0) {
635
+ await writeFile(
636
+ runtimeCandidateReceiptPath,
637
+ `${JSON.stringify(
638
+ {
639
+ formatVersion: 1,
640
+ baselineGenerationId: baseline.generationId,
641
+ candidateSha256: receipt.candidateSha256,
642
+ candidates: [],
643
+ },
644
+ null,
645
+ "\t",
646
+ )}\n`,
647
+ { mode: 0o600 },
648
+ );
649
+ console.log(
650
+ `No candidate migrations follow baseline ${baseline.migrationCutoff}.`,
651
+ );
652
+ return receipt;
653
+ }
654
+ console.log(
655
+ `Candidate migrations (${receipt.candidateSha256}): ${receipt.candidates.map((candidate) => candidate.filename).join(", ")}`,
656
+ );
657
+ const confirmation = process.argv
658
+ .find((argument) => argument.startsWith("--confirm-candidates="))
659
+ ?.slice("--confirm-candidates=".length);
660
+ if (confirmation !== receipt.candidateSha256) {
661
+ throw new Error(
662
+ "Candidate migration confirmation is missing or does not match the exact SHA-256.",
663
+ );
664
+ }
665
+ try {
666
+ const serviceEnvironment = await readServiceEnvironment();
667
+ for (const candidate of receipt.candidates) {
668
+ await cp(
669
+ join(configuredPaths.migrationDirectory, candidate.filename),
670
+ join(runtimeSupabaseDirectory, "migrations", candidate.filename),
671
+ );
672
+ }
673
+ runLocalCommand(
674
+ "supabase",
675
+ ["migration", "up", "--local", "--workdir", runtimeWorkdir],
676
+ { cwd: repositoryRoot, environment: serviceEnvironment },
677
+ );
678
+ const comparison = await verifyRuntimeMigrationHistory({
679
+ baseline,
680
+ currentFiles: receipt.currentFiles,
681
+ });
682
+ if (
683
+ comparison.candidates
684
+ .map((candidate) => candidate.filename)
685
+ .join("\0") !==
686
+ receipt.candidates.map((candidate) => candidate.filename).join("\0")
687
+ ) {
688
+ throw new Error(
689
+ "Applied Rehearsal migration history does not match the confirmed candidate suffix.",
690
+ );
691
+ }
692
+ await writeFile(
693
+ runtimeCandidateReceiptPath,
694
+ `${JSON.stringify(
695
+ {
696
+ formatVersion: 1,
697
+ baselineGenerationId: baseline.generationId,
698
+ candidateSha256: receipt.candidateSha256,
699
+ candidates: receipt.candidates.map((candidate) => ({
700
+ filename: candidate.filename,
701
+ sha256: candidate.fileSha256,
702
+ })),
703
+ },
704
+ null,
705
+ "\t",
706
+ )}\n`,
707
+ { mode: 0o600 },
708
+ );
709
+ console.log(
710
+ `Applied ${receipt.candidates.length} confirmed candidate migrations to the disposable Rehearsal runtime.`,
711
+ );
712
+ return receipt;
713
+ } catch (error) {
714
+ await removeRuntime().catch(() => undefined);
715
+ throw error;
716
+ }
717
+ };
718
+
719
+ switch (action) {
720
+ case "reset":
721
+ await resetRuntime();
722
+ break;
723
+ case "start": {
724
+ const environment = await startRuntime();
725
+ console.log(`Local Rehearsal Supabase: ${environment.apiUrl}`);
726
+ break;
727
+ }
728
+ case "status": {
729
+ const baseline = await verifyActiveBaseline({ artifactRoot });
730
+ const receipt = await readCandidateReceipt(baseline);
731
+ const serviceEnvironment = await readServiceEnvironment();
732
+ const runtimeIsRunning = localCommandSucceeds(
733
+ "supabase",
734
+ ["status", "--workdir", runtimeWorkdir],
735
+ { cwd: repositoryRoot, environment: serviceEnvironment },
736
+ );
737
+ if (runtimeIsRunning) {
738
+ const environment = readLocalSupabaseEnvironment({
739
+ cwd: repositoryRoot,
740
+ workdir: runtimeWorkdir,
741
+ environment: serviceEnvironment,
742
+ });
743
+ console.log(`Local Rehearsal Supabase: running at ${environment.apiUrl}`);
744
+ } else {
745
+ console.log("Local Rehearsal Supabase: stopped");
746
+ }
747
+ console.log(`Active sanitized baseline: ${baseline.generationId}`);
748
+ console.log(
749
+ `Candidate migrations (${receipt.candidateSha256}): ${receipt.candidates.map((candidate) => candidate.filename).join(", ") || "none"}`,
750
+ );
751
+ break;
752
+ }
753
+ case "candidates": {
754
+ const baseline = await verifyActiveBaseline({ artifactRoot });
755
+ const receipt = await readCandidateReceipt(baseline);
756
+ console.log(
757
+ `Candidate migrations (${receipt.candidateSha256}): ${receipt.candidates.map((candidate) => candidate.filename).join(", ") || "none"}`,
758
+ );
759
+ break;
760
+ }
761
+ case "migrate":
762
+ await migrateRuntime();
763
+ break;
764
+ case "verify":
765
+ await verifyRuntime();
766
+ break;
767
+ case "run":
768
+ await resetRuntime();
769
+ await migrateRuntime();
770
+ await verifyRuntime();
771
+ break;
772
+ case "stop":
773
+ stopLocalSupabase({
774
+ cwd: repositoryRoot,
775
+ workdir: runtimeWorkdir,
776
+ environment: await readServiceEnvironment(),
777
+ });
778
+ break;
779
+ case "discard":
780
+ await removeRuntime();
781
+ break;
782
+ default:
783
+ throw new Error(`Unknown Rehearsal database action: ${action}`);
784
+ }