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.

14.8 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import { defineCommand, runMain } from "citty";
import { copy, envSync } from "./commands/copy.js";
import { down } from "./commands/down.js";
import { initWorktree } from "./commands/init.js";
import { listWorktrees } from "./commands/list.js";
import { migrate } from "./commands/migrate.js";
import { newWorktree } from "./commands/new.js";
import { prune } from "./commands/prune.js";
import { reload } from "./commands/reload.js";
import { removeWorktreeCmd } from "./commands/remove.js";
import { reset } from "./commands/reset.js";
import { type RestoreMode, restore } from "./commands/restore.js";
import { status } from "./commands/status.js";
import { up } from "./commands/up.js";

const main = defineCommand({
  meta: {
    name: "crbn",
    description: "Carbon dev CLI (heavy commands; bash router handles checkout)"
  },
  subCommands: {
    up: defineCommand({
      meta: { description: "Boot the per-worktree compose stack and apps" },
      args: {
        migrate: {
          type: "boolean",
          default: true,
          description: "Apply database migrations (use --no-migrate to skip)"
        },
        regen: {
          type: "boolean",
          default: true,
          description:
            "Regenerate db types + swagger after migrations (use --no-regen to skip)"
        },
        apps: {
          type: "boolean",
          default: true,
          description:
            "Spawn ERP/MES dev servers (use --no-apps for services-only boot)"
        },
        all: {
          type: "boolean",
          default: false,
          description:
            "Launch all apps without the interactive picker (implies erp+mes)"
        },
        pull: {
          type: "boolean",
          default: false,
          description:
            "Always docker compose pull (default: skip when all images exist locally)"
        },
        borrow: {
          type: "boolean",
          default: false,
          description:
            "Pick another worktree's running containers to use instead of booting a new stack"
        },
        portless: {
          type: "boolean",
          default: true,
          description:
            "Use portless .dev URLs (use --no-portless for localhost mode)"
        },
        run: {
          type: "string",
          description:
            "Boot apps, wait until reachable, run this command, then tear the stack down (scopes the stack's lifetime to the command — for headless/CI use)"
        },
        volumes: {
          type: "boolean",
          default: false,
          description:
            "With --run, also remove Docker volumes on teardown (headless: don't leak data volumes across dispatches)"
        },
        full: {
          type: "boolean",
          default: false,
          description:
            "Also start Studio, Postgres-Meta, the edge runtime and imgproxy (off by default; `crbn reload studio` / `crbn reload imgproxy` starts one on a running stack)"
        },
        minimal: {
          type: "boolean",
          default: false,
          description:
            "Also skip Inbucket, for headless/CI builds that sign in by bypass"
        },
        hibernate: {
          type: "boolean",
          default: true,
          description:
            "Stop the containers after 30 min without ERP/MES traffic, and the dev servers after 2 h; the next request starts them again (--no-hibernate to keep them up; CRBN_IDLE_MINUTES / CRBN_APPS_IDLE_MINUTES change the waits)"
        }
      },
      run: ({ args }) =>
        up({
          migrate: args.migrate !== false,
          regen: args.regen !== false,
          apps: args.apps !== false,
          all: args.all === true,
          pull: args.pull === true,
          borrow: args.borrow === true,
          portless: args.portless !== false,
          run: typeof args.run === "string" ? args.run : undefined,
          volumes: args.volumes === true,
          full: args.full === true,
          minimal: args.minimal === true,
          hibernate: args.hibernate !== false
        })
    }),
    down: defineCommand({
      meta: { description: "Stop the compose stack (volumes preserved)" },
      args: {
        volumes: {
          type: "boolean",
          default: false,
          description: "Also remove Docker volumes (the stack's data is wiped)"
        },
        purge: {
          type: "boolean",
          default: false,
          description:
            "Full teardown for archive/removal: remove volumes, flush redis, and release the port slot"
        }
      },
      run: ({ args }) =>
        down({ volumes: args.volumes === true, purge: args.purge === true })
    }),
    reset: defineCommand({
      meta: { description: "Wipe volumes + flush redis db, then `up`" },
      run: () => reset()
    }),
    status: defineCommand({
      meta: { description: "Show port assignment + container health" },
      args: {
        json: {
          type: "boolean",
          default: false,
          description: "Print the slot and containers as JSON"
        }
      },
      run: ({ args }) => status({ json: args.json === true })
    }),
    reload: defineCommand({
      meta: {
        description:
          "Recreate specific compose services to apply docker-compose/.env.local edits (memory, env, image, ports) WITHOUT restarting the app dev servers — `crbn reload <service...>` (e.g. storage kong)"
      },
      args: {
        service: {
          type: "positional",
          required: true,
          description: "Service name(s) to recreate, e.g. storage kong"
        }
      },
      run: ({ rawArgs }) =>
        reload(rawArgs.filter((a) => a && !a.startsWith("-")))
    }),
    migrate: defineCommand({
      meta: {
        description:
          "Apply database migrations against the worktree's stack (loads .env.local)"
      },
      args: {
        regen: {
          type: "boolean",
          default: true,
          description:
            "Regenerate db types + swagger after migrations (use --no-regen to skip)"
        },
        force: {
          type: "boolean",
          default: false,
          description:
            "Schema unreconcilable? Wipe the stack's volumes and re-provision from scratch (prompts to confirm)"
        }
      },
      run: ({ args }) =>
        args.force ? reset() : migrate({ regen: args.regen !== false })
    }),
    restore: defineCommand({
      meta: {
        description:
          "Restore a production backup into this worktree's database, then apply the migrations it predates (wraps scripts/restore-database.sh)"
      },
      args: {
        file: {
          type: "positional",
          required: true,
          description: "Path to a .backup cluster dump or .dump archive"
        },
        "scrub-emails": {
          type: "boolean",
          default: true,
          description:
            "Rewrite every email address to @example.test so production addresses can never be contacted locally (--no-scrub-emails to keep them)"
        },
        "admin-email": {
          type: "string",
          description:
            "Your email in the backup — upgraded to Admin in the companies it already belongs to, with the password reset locally"
        },
        "admin-password": {
          type: "string",
          description: "Local password for --admin-email (default: localpass)"
        },
        mode: {
          type: "string",
          default: "local",
          description:
            "'local' points config at the local stack and deactivates webhooks/integrations/printer routes; 'prod' restores as-is"
        },
        "keep-storage-objects": {
          type: "boolean",
          default: false,
          description:
            "Keep the backup's storage.objects rows and buckets instead of clearing them. Downloads still 404 (the bytes are not in the DB); use when you need realistic storage metadata, e.g. profiling storage RLS"
        },
        migrate: {
          type: "boolean",
          default: true,
          description:
            "Apply migrations the backup predates (use --no-migrate to leave the schema at the backup's state)"
        },
        regen: {
          type: "boolean",
          default: true,
          description: "Regenerate db types afterwards (use --no-regen to skip)"
        },
        yes: {
          type: "boolean",
          default: false,
          description: "Skip the confirmation prompt"
        }
      },
      run: ({ args }) => {
        // Explicit rather than coercing anything non-"prod" to "local": a typo
        // in a flag that controls whether production services stay wired up
        // must not silently pick a mode.
        const mode = String(args.mode ?? "local");
        if (mode !== "local" && mode !== "prod") {
          console.error(`--mode must be 'local' or 'prod' (got '${mode}')`);
          process.exit(1);
        }
        return restore({
          file: String(args.file),
          scrubEmails: args["scrub-emails"] !== false,
          adminEmail:
            typeof args["admin-email"] === "string"
              ? args["admin-email"]
              : undefined,
          adminPassword:
            typeof args["admin-password"] === "string"
              ? args["admin-password"]
              : undefined,
          mode: mode as RestoreMode,
          keepStorageObjects: args["keep-storage-objects"] === true,
          migrate: args.migrate !== false,
          regen: args.regen !== false,
          yes: args.yes === true
        });
      }
    }),
    new: defineCommand({
      meta: {
        description:
          "Create a worktree on a fresh branch (interactive, or non-interactive with --yes)"
      },
      args: {
        branch: {
          type: "positional",
          required: false,
          description: "Branch name (pre-fills the prompt)"
        },
        base: {
          type: "string",
          description:
            "Base ref to branch from (with --yes; defaults to origin/main)"
        },
        dir: {
          type: "string",
          description: "Worktree directory name (with --yes; default derived)"
        },
        "copy-env": {
          type: "boolean",
          default: true,
          description:
            "Copy .env from the current checkout (--no-copy-env to skip)"
        },
        yes: {
          type: "boolean",
          default: false,
          description:
            "Non-interactive: skip prompts, use flags/defaults (base defaults to origin/main)"
        }
      },
      run: ({ args }) =>
        newWorktree({
          branch: typeof args.branch === "string" ? args.branch : undefined,
          base: typeof args.base === "string" ? args.base : undefined,
          dir: typeof args.dir === "string" ? args.dir : undefined,
          copyEnv: args["copy-env"] !== false,
          yes: args.yes === true
        })
    }),
    init: defineCommand({
      meta: {
        description:
          "Provision the current worktree (slug + env sync + skills) to match a `crbn checkout`"
      },
      args: {
        "copy-env": {
          type: "boolean",
          default: true,
          description:
            "Sync .env from the main checkout (--no-copy-env to skip)"
        }
      },
      run: ({ args }) => initWorktree({ copyEnv: args["copy-env"] !== false })
    }),
    list: defineCommand({
      meta: { description: "List worktrees with stack status" },
      args: {
        json: {
          type: "boolean",
          default: false,
          description: "Print the worktrees as JSON"
        }
      },
      run: ({ args }) => listWorktrees({ json: args.json === true })
    }),
    remove: defineCommand({
      meta: {
        description:
          "Delete worktrees with their stacks — pick interactively, or name them: `crbn remove <branch-or-path...>`"
      },
      args: {
        worktree: {
          type: "positional",
          required: false,
          description: "Branch name(s) or path(s) to remove; skips the picker"
        },
        prune: {
          type: "boolean",
          default: false,
          description: "Also delete the git branch after removing the worktree"
        }
      },
      run: ({ args, rawArgs }) =>
        removeWorktreeCmd({
          prune: args.prune === true,
          targets: rawArgs.filter((a) => a && !a.startsWith("-"))
        })
    }),
    prune: defineCommand({
      meta: {
        description:
          "Destroy stacks no worktree can reach: slots whose directory is gone, and stacks with no slot (volumes wiped; confirms first)"
      },
      args: {
        all: {
          type: "boolean",
          default: false,
          description:
            "Destroy EVERY crbn stack on this machine, running ones included. Worktrees, branches and live slots are kept; the next `crbn up` rebuilds the database"
        },
        tree: {
          type: "boolean",
          default: false,
          description:
            "Also clean up git worktrees: forget ones whose directory is gone; with --all, remove this repo's linked worktrees too (never the main checkout, the current one, or one with uncommitted changes; branches are kept)"
        }
      },
      run: ({ args }) =>
        prune({ all: args.all === true, tree: args.tree === true })
    }),
    copy: defineCommand({
      meta: {
        description: "Copy file(s) from main checkout into current worktree"
      },
      args: {
        files: {
          type: "positional",
          required: true,
          description: "File path(s) to copy from main checkout"
        }
      },
      run: ({ args }) => {
        const files = Array.isArray(args.files)
          ? args.files.filter((f): f is string => typeof f === "string")
          : typeof args.files === "string"
            ? [args.files]
            : [];
        return copy(files);
      }
    }),
    env: defineCommand({
      meta: { description: "Environment file management" },
      subCommands: {
        sync: defineCommand({
          meta: {
            description:
              "Sync files listed in package.json#crbn.copy from main checkout"
          },
          run: () => envSync()
        })
      }
    }),
    // Stubs so shell completion lists these — the bash router (`bin/crbn`)
    // intercepts them before tsx is invoked. Direct invocation lands here.
    checkout: defineCommand({
      meta: {
        description:
          "Switch into worktree for <branch> (handled by bash router)"
      },
      run: () => {
        console.error("checkout is handled by the bash router (bin/crbn)");
        process.exit(1);
      }
    })
  }
});

try {
  const { default: tab } = await import("@bomb.sh/tab/citty");
  await tab(main);
} catch {
  // Optional: shell completions only; continue if the package is missing (run `pnpm install`).
}
await runMain(main);