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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix: migration command in crbn
Sidwebworksf266c932bbdd
diff --git a/packages/dev/bin/crbn b/packages/dev/bin/crbnindex 109b992655..47c9ce02f8 100755--- a/packages/dev/bin/crbn+++ b/packages/dev/bin/crbn@@ -75,7 +75,7 @@ repo_root() {}slugify_branch() {- # Mirrors packages/dev/src/lib/slug.ts:slugify — lowercase, replace+ # Mirrors packages/dev/src/worktree.ts:slugify — lowercase, replace# non-[a-z0-9-] runs with `-`, trim/collapse `-`.printf '%s' "$1" \| tr '[:upper:]' '[:lower:]' \diff --git a/packages/dev/src/commands/migrate.ts b/packages/dev/src/commands/migrate.tsindex 664042d881..3e5dac9c7d 100644--- a/packages/dev/src/commands/migrate.ts+++ b/packages/dev/src/commands/migrate.ts@@ -3,54 +3,66 @@ import { intro, log, outro, tasks } from "@clack/prompts";import { config as loadDotenv } from "dotenv";import { execa } from "execa";import { join } from "pathe";-import { requireNumberEnv, tryConnect } from "../helpers.js";-import { applyMigrations } from "../services/migrations.js";-import { getWorktreeRoot } from "../worktree.js";--// Run database migrations against the worktree's local stack without booting-// the full compose stack. Reads PORT_DB from `.env.local` (written by-// `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.+import { renderEnv, syncAppPortlessConfigs, writeEnv } from "../env.js";+import { currentBranch } from "../git.js";+import { onShutdown, requireNumberEnv, tryConnect } from "../helpers.js";+import {+ bootStack,+ ensureDockerRunning,+ stopStack+} from "../services/compose.js";+import { applyMigrations, waitForPostgres } from "../services/migrations.js";+import { branchToPrefix } from "../services/portless.js";+import {+ ensureSlugAvailable,+ getWorktreeRoot,+ persistSlug,+ projectName,+ resolveSlot,+ resolveSlug+} from "../worktree.js";++// Run database migrations against the worktree's local stack. If postgres is+// already running (full stack up), migrate against it directly. If not, boot+// just postgres, apply migrations + regenerate types, then tear down — no need+// for the full 11-service compose stack to run migrations.export async function migrate(opts: { regen?: boolean } = {}) {const shouldRegen = opts.regen ?? true;intro("Carbon · dev migrate");const root = await getWorktreeRoot();+ const slug = resolveSlug(root);const envLocal = join(root, ".env.local");- if (!existsSync(envLocal)) {- log.error(- `.env.local not found in ${root}. Run \`crbn up\` once to provision the stack, then re-run \`crbn migrate\`.`- );- outro("");- process.exit(1);- }- // .env.local is the worktree's source of truth for PORT_DB — override any- // stale value already in the shell env, or migrate would target the wrong DB.- // (mirrors `up.ts` provisionSlot, which also loads .env.local with override.)- loadDotenv({ path: envLocal, override: true });+ // Load .env.local if it exists (written by a prior `crbn up`).+ if (existsSync(envLocal)) {+ loadDotenv({ path: envLocal, override: true });+ }loadDotenv({ path: join(root, ".env"), override: false });- let portDb: number;+ let portDb: number | undefined;try {portDb = requireNumberEnv("PORT_DB");- } catch (err) {- log.error(- `${(err as Error).message}. Re-run \`crbn up\` to regenerate .env.local.`- );- outro("");- process.exit(1);+ } catch {+ // .env.local missing or PORT_DB not set — will need to provision.}- if (!(await tryConnect("127.0.0.1", portDb, 1500))) {- log.error(- `Local DB at 127.0.0.1:${portDb} is not reachable. Start the stack first: \`crbn up\`.`- );- outro("");- process.exit(1);+ // If postgres is already reachable, migrate against the running DB.+ if (portDb && (await tryConnect("127.0.0.1", portDb, 500))) {+ return migrateAgainstRunningDb(root, portDb, shouldRegen);}+ // Standalone mode: boot just postgres, migrate, tear down.+ return migrateStandalone(root, slug, shouldRegen);+}++// ─── Running-stack path (existing behavior) ──────────────────────────────++async function migrateAgainstRunningDb(+ root: string,+ portDb: number,+ shouldRegen: boolean+) {let applied = false;await tasks([{@@ -75,6 +87,88 @@ export async function migrate(opts: { regen?: boolean } = {}) {]: [])]);+ outro("done");+}++// ─── Standalone path (postgres-only) ──────────────────────────────────────++async function migrateStandalone(+ root: string,+ slug: string,+ shouldRegen: boolean+) {+ const envLocal = join(root, ".env.local");++ // Provision slot if .env.local doesn't exist yet (first time in this+ // worktree). Reuses the registry so the next `crbn up` gets the same+ // ports/JWT/volumes.+ if (!existsSync(envLocal)) {+ log.info("provisioning worktree slot (first run)");+ await ensureDockerRunning();+ await ensureSlugAvailable(slug, root);+ persistSlug(root, slug);++ const slot = await resolveSlot(slug, root);+ const branch = await currentBranch(root);+ const branchPrefix = branchToPrefix(branch, slug);+ writeEnv(root, renderEnv({ slug, portless: true, branchPrefix, ...slot }));+ syncAppPortlessConfigs(root);+ loadDotenv({ path: envLocal, override: true });+ }++ const portDb = requireNumberEnv("PORT_DB");+ const project = projectName(slug);++ log.info(`booting postgres-only stack (${project})`);+ await ensureDockerRunning();++ // Tear down on Ctrl+C so the standalone postgres doesn't orphan.+ let interrupted = false;+ const detach = onShutdown(() => {+ if (interrupted) return;+ interrupted = true;+ process.stderr.write("\ninterrupted — stopping postgres…\n");+ void stopStack(root, slug, false).finally(() => process.exit(130));+ });++ try {+ await bootStack(root, slug, { services: ["postgres"] });+ await waitForPostgres(portDb);++ let applied = false;+ await tasks([+ {+ title: "Apply database migrations",+ task: async () => {+ const r = await applyMigrations(root, portDb);+ applied = r.applied;+ return r.applied ? "migrations applied" : "schema already up to date";+ }+ },+ ...(shouldRegen+ ? [+ {+ title: "Regenerate types",+ task: async () => {+ if (!applied) return "skipped (no new migrations)";+ await execa("pnpm", ["db:types"], { cwd: root });+ return "types refreshed";+ }+ }+ ]+ : [])+ ]);++ if (shouldRegen) {+ log.warn(+ "swagger skipped — requires Studio (run `crbn up` for full regen)"+ );+ }+ } finally {+ detach();+ log.info("stopping postgres-only stack");+ await stopStack(root, slug, false);+ }outro("done");}diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.tsindex fd1df2df9d..d8460b8630 100644--- a/packages/dev/src/commands/up.ts+++ b/packages/dev/src/commands/up.ts@@ -613,28 +613,30 @@ async function appResponds(port: number): Promise<boolean> {}}-/** Poll each selected app's port until it serves (or the deadline passes). */+/** Poll each selected app's port concurrently until all serve (or deadline). */async function waitForApps(selectedApps: AppId[],ports: PortMap,timeoutMs = 180_000): Promise<void> {const deadline = Date.now() + timeoutMs;- for (const id of selectedApps) {- const key = APP_PORT_KEY[id];- const port = key ? ports[key] : undefined;- if (port === undefined) continue;- let up = false;- while (Date.now() < deadline) {- if (await appResponds(port)) {- up = true;- break;+ await Promise.all(+ selectedApps.map(async (id) => {+ const key = APP_PORT_KEY[id];+ const port = key ? ports[key] : undefined;+ if (port === undefined) return;+ let up = false;+ while (Date.now() < deadline) {+ if (await appResponds(port)) {+ up = true;+ break;+ }+ await new Promise((r) => setTimeout(r, 1500));}- await new Promise((r) => setTimeout(r, 1500));- }- if (up) log.info(`${id} reachable on :${port}`);- else log.warn(`${id} not reachable on :${port} — running command anyway`);- }+ if (up) log.info(`${id} reachable on :${port}`);+ else log.warn(`${id} not reachable on :${port} — running command anyway`);+ })+ );}/**diff --git a/packages/dev/src/env.ts b/packages/dev/src/env.tsindex 2497bd4f96..7533cc378c 100644--- a/packages/dev/src/env.ts+++ b/packages/dev/src/env.ts@@ -44,7 +44,7 @@ export function renderEnv(opts: {lines.push(`VERCEL_URL=${portless ? `https://${host("erp")}` : local(ports.PORT_ERP)}`);- if (portless) lines.push(`GTM_URL=https://${host("starter")}`);+ if (portless) lines.push(`GTM_URL=https://${host("erp")}`);lines.push("");lines.push("# Supabase (per-worktree dev keys, minted from random JWT_SECRET)"diff --git a/packages/dev/src/services/compose.ts b/packages/dev/src/services/compose.tsindex 8f2cbcee4b..e12eff9427 100644--- a/packages/dev/src/services/compose.ts+++ b/packages/dev/src/services/compose.ts@@ -56,11 +56,14 @@ export type Container = {export async function bootStack(root: string,slug: string,- opts?: { minimal?: boolean }+ opts?: { minimal?: boolean; services?: string[] }) {const args = devArgs(root, slug, "--env-file", ".env.local");- if (!opts?.minimal) args.push("--profile", "full");+ // When specific services are requested, don't activate profiles — compose+ // starts only the named services (+ dependencies) regardless of profiles.+ if (!opts?.services && !opts?.minimal) args.push("--profile", "full");args.push("up", "-d");+ if (opts?.services) args.push(...opts.services);await execStrict("docker", args, root);}diff --git a/packages/dev/tsconfig.json b/packages/dev/tsconfig.jsonindex d52742e935..43fc49fd36 100644--- a/packages/dev/tsconfig.json+++ b/packages/dev/tsconfig.json@@ -9,5 +9,5 @@"strict": true,"noEmit": true},- "include": ["src/**/*", "bin.mjs"]+ "include": ["src/**/*"]}