Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: add `crbn migrate` --force flag

Sidwebworks6b0011533f35
diff --git a/packages/dev/src/commands/migrate.ts b/packages/dev/src/commands/migrate.ts
index d29d15e63e..83156f2c99 100644
--- a/packages/dev/src/commands/migrate.ts
+++ b/packages/dev/src/commands/migrate.ts
@@ -12,7 +12,7 @@ import { getWorktreeRoot } from "../worktree.js";
// `crbn up`). Bare `pnpm db:migrate` resolves dotenv relative to cwd and falls
// through to the supabase CLI's linked-project path — `crbn migrate` removes
// that footgun by always targeting the current worktree's DB.
-export async function migrate(opts: { regen?: boolean } = {}) {
+export async function migrate(opts: { regen?: boolean; force?: boolean } = {}) {
const shouldRegen = opts.regen ?? true;
intro("Carbon · dev migrate");
@@ -53,7 +53,9 @@ export async function migrate(opts: { regen?: boolean } = {}) {
{
title: "Apply database migrations",
task: async () => {
- const r = await applyMigrations(root, portDb);
+ const r = await applyMigrations(root, portDb, {
+ force: opts.force ?? false
+ });
applied = r.applied;
return r.applied ? "migrations applied" : "schema already up to date";
}
diff --git a/packages/dev/src/main.ts b/packages/dev/src/main.ts
index 3f864d3b15..dec917a433 100644
--- a/packages/dev/src/main.ts
+++ b/packages/dev/src/main.ts
@@ -87,9 +87,16 @@ const main = defineCommand({
default: true,
description:
"Regenerate db types + swagger after migrations (use --no-regen to skip)"
+ },
+ force: {
+ type: "boolean",
+ default: false,
+ description:
+ "Escalate stale-migration repair via `supabase migration repair --status reverted`"
}
},
- run: ({ args }) => migrate({ regen: args.regen !== false })
+ run: ({ args }) =>
+ migrate({ regen: args.regen !== false, force: !!args.force })
}),
new: defineCommand({
meta: { description: "Interactive: create a worktree on a fresh branch" },
diff --git a/packages/dev/src/services/migrations.ts b/packages/dev/src/services/migrations.ts
index 425ceee7f1..a0f3156c7f 100644
--- a/packages/dev/src/services/migrations.ts
+++ b/packages/dev/src/services/migrations.ts
@@ -130,7 +130,8 @@ export async function applyBootstrapSql(root: string, port: number) {
// `supabase_migrations.schema_migrations` as `postgres`.
export async function applyMigrations(
root: string,
- dbPort: number
+ dbPort: number,
+ opts: { force?: boolean } = {}
): Promise<{ applied: boolean }> {
const dbUrl = `postgresql://supabase_admin:postgres@localhost:${dbPort}/postgres`;
const args = ["migration", "up", "--include-all", "--db-url", dbUrl];
@@ -144,8 +145,18 @@ export async function applyMigrations(
const output = `${r.stderr ?? ""}\n${r.stdout ?? ""}`;
// Auto-repair: DB has migration versions not present locally (stale from
// another branch or incomplete volume wipe). Remove them and retry.
+ //
+ // Default path diffs local files vs schema_migrations and DELETEs the
+ // orphans. --force instead parses the version(s) supabase itself names in
+ // its error and runs `migration repair --status reverted` on them — this
+ // catches rows the readdir diff misses (e.g. a migration whose timestamp
+ // isn't supabase's required 14 digits, which the CLI ignores as a local
+ // file while our diff still counts it as present).
if (/remote migration versions not found in local/i.test(output)) {
- const repaired = await repairStaleMigrations(root, dbPort);
+ const repaired =
+ (opts.force ?? false)
+ ? await forceRepairMigrations(root, dbPort, output)
+ : await repairStaleMigrations(root, dbPort);
if (repaired > 0) {
log.warn(`repaired ${repaired} stale migration(s) — retrying`);
const retry = await execa("supabase", args, {
@@ -217,6 +228,49 @@ async function repairStaleMigrations(
return stale.length;
}
+// --force escalation. supabase's "remote migration versions not found in local"
+// error prints the exact recovery command it wants — e.g.
+// `supabase migration repair --status reverted 20260515`. Parse those
+// version(s) out and run that command verbatim (with --db-url), then let the
+// caller retry `migration up`. Unlike repairStaleMigrations this trusts
+// supabase's own view, so it repairs orphans the readdir diff can't see.
+async function forceRepairMigrations(
+ root: string,
+ dbPort: number,
+ supabaseOutput: string
+): Promise<number> {
+ const m = supabaseOutput.match(
+ /migration repair --status reverted ([0-9 ]+)/
+ );
+ const versions = m?.[1]?.trim().split(/\s+/).filter(Boolean) ?? [];
+ if (versions.length === 0) return 0;
+
+ const dbUrl = `postgresql://supabase_admin:postgres@localhost:${dbPort}/postgres`;
+ const cwd = join(root, "packages/database");
+ log.warn(
+ `--force: supabase migration repair --status reverted ${versions.join(" ")}`
+ );
+ const r = await execa(
+ "supabase",
+ [
+ "migration",
+ "repair",
+ "--status",
+ "reverted",
+ ...versions,
+ "--db-url",
+ dbUrl
+ ],
+ { cwd, reject: false, preferLocal: true }
+ );
+ if (r.exitCode !== 0) {
+ process.stderr.write(r.stderr?.toString() ?? "");
+ process.stdout.write(r.stdout?.toString() ?? "");
+ throw new Error(`supabase migration repair failed (exit ${r.exitCode})`);
+ }
+ return versions.length;
+}
+
// ---------------------------------------------------------------------------
// Private helpers
// ---------------------------------------------------------------------------