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.

18.6 KB
Raw Blame
#!/usr/bin/env bash
# Carbon dev CLI router. Bash for `checkout` (needs eval'd cd in parent
# shell); the rest delegates to `tsx packages/dev/src/main.ts` (citty).
#
# Setup once:  ./setup.sh
# Then:        crbn <command>

set -euo pipefail

# crbn is POSIX-only. On Windows, supported environments are WSL (reports
# `Linux` from uname) and Git Bash (reports `MINGW*`/`MSYS*`). Bail early
# with an actionable message anywhere else so users don't hit cryptic
# downstream failures.
case "$(uname -s)" in
  MINGW*|MSYS*|CYGWIN*|Linux*|Darwin*) ;;
  *)
    printf '\033[1;31m✗\033[0m crbn requires WSL or Git Bash on Windows (current: %s)\n' "$(uname -s)" >&2
    exit 1
    ;;
esac

# Node 24.22.1+ required: the October 2026 security release, and the floor in
# the root package.json `engines`. `sort -V -C` succeeds when the minimum sorts
# first, so nightly and RC builds of a newer major still pass.
NODE_MIN="24.22.1"
if command -v node >/dev/null 2>&1; then
  node_ver="$(node -v)"
  node_num="${node_ver#v}"
  # A prerelease of the minimum itself (24.22.1-rc.1) predates it, though sort
  # -V orders it after.
  if ! printf '%s\n' "$NODE_MIN" "$node_num" | sort -V -C ||
     [[ "${node_num%%-*}" == "$NODE_MIN" && "$node_num" == *-* ]]; then
    printf '\033[1;31m✗\033[0m crbn requires Node.js %s+ (found %s)\n' "$NODE_MIN" "$node_ver" >&2
    exit 1
  fi
else
  printf '\033[1;31m✗\033[0m crbn requires Node.js %s+ but node is not in PATH\n' "$NODE_MIN" >&2
  exit 1
fi

# ---------------------------------------------------------------------------
# Output helpers (colors when stderr is a TTY).
# All listings/errors go to stderr so they never get eval'd by the `crbn()`
# shell function from setup.sh, which only consumes stdout.
# ---------------------------------------------------------------------------

if [[ -t 2 ]] && command -v tput >/dev/null 2>&1 && [[ "$(tput colors 2>/dev/null || echo 0)" -ge 8 ]]; then
  C_BOLD=$(tput bold);   C_DIM=$(tput dim);    C_RESET=$(tput sgr0)
  C_GREEN=$(tput setaf 2); C_YELLOW=$(tput setaf 3)
  C_CYAN=$(tput setaf 6);  C_RED=$(tput setaf 1)
else
  C_BOLD=""; C_DIM=""; C_RESET=""
  C_GREEN=""; C_YELLOW=""; C_CYAN=""; C_RED=""
fi

ok()    { printf '%s✓%s %s\n' "$C_GREEN"  "$C_RESET" "$*" >&2; }
info()  { printf '%s•%s %s\n' "$C_CYAN"   "$C_RESET" "$*" >&2; }
warn()  { printf '%s!%s %s\n' "$C_YELLOW" "$C_RESET" "$*" >&2; }
fail()  { printf '%s✗%s %s\n' "$C_RED"    "$C_RESET" "$*" >&2; }
hdr()   { printf '\n%s%s%s\n' "$C_BOLD" "$*" "$C_RESET" >&2; }

# ---------------------------------------------------------------------------
# Repo discovery
# ---------------------------------------------------------------------------

repo_root() {
  # Each linked worktree has its own --show-toplevel. We want the *main*
  # checkout (where packages/dev lives), which is `--git-common-dir`'s parent.
  local common_dir
  common_dir=$(git rev-parse --git-common-dir 2>/dev/null) || {
    echo "crbn: not inside a git repository" >&2
    return 1
  }
  if [[ "$common_dir" != /* ]]; then
    common_dir="$PWD/$common_dir"
  fi
  dirname "$common_dir"
}

slugify_branch() {
  # Mirrors packages/dev/src/worktree.ts:slugify — lowercase, replace
  # non-[a-z0-9-] runs with `-`, trim/collapse `-`.
  printf '%s' "$1" \
    | tr '[:upper:]' '[:lower:]' \
    | sed -E 's/[^a-z0-9-]+/-/g; s/^-+|-+$//g; s/-+/-/g'
}

delegate_ts() {
  # Run citty entry through tsx. Prefer the current worktree's source so CLI
  # changes in a branch are testable immediately; fall back to main checkout.
  # tsx binary: prefer worktree's node_modules, then main's, then pnpx.
  local wt_root main_root src tsx
  wt_root="$(git rev-parse --show-toplevel 2>/dev/null)"
  main_root="$(repo_root)"

  # Pick source: worktree first, but only if deps are installed (otherwise
  # imports like `citty` fail). Falls back to main checkout.
  if [[ -n "$wt_root" && -f "$wt_root/packages/dev/src/main.ts" && -d "$wt_root/node_modules" ]]; then
    src="$wt_root/packages/dev/src/main.ts"
  else
    src="$main_root/packages/dev/src/main.ts"
  fi

  # Pick tsx binary.
  if [[ -n "$wt_root" && -x "$wt_root/node_modules/.bin/tsx" ]]; then
    tsx="$wt_root/node_modules/.bin/tsx"
  elif [[ -x "$main_root/node_modules/.bin/tsx" ]]; then
    tsx="$main_root/node_modules/.bin/tsx"
  else
    exec pnpx tsx "$src" "$@"
  fi

  exec "$tsx" "$src" "$@"
}

# ---------------------------------------------------------------------------
# checkout <name> [-b] [--path PATH] [--base REF] [--up]
#
# Unified verb: jumps into an existing worktree, or creates one when needed.
# Mirrors `git checkout` semantics:
#
#   crbn checkout <name>        Existing branch → worktree (create if missing,
#                               cd into it). Falls back to `origin/<name>`
#                               (auto-fetches) when no local branch exists.
#                               No match → error.
#
#   crbn checkout -b <name>     Branch must NOT exist. Creates new branch
#                               from --base (default HEAD) + worktree.
#
# All progress logs go to stderr; the only stdout is `cd '<path>'` for the
# shell function in setup.sh to eval. Pass --up to chain `crbn up` after
# creation (bypasses the eval-wrapper; user's cwd doesn't change but the
# stack starts in the new worktree).
# ---------------------------------------------------------------------------

checkout_usage() {
  cat >&2 <<'USAGE'
Usage: crbn checkout <name> [--path PATH] [--up]
       crbn checkout -b <name> [--base REF] [--path PATH] [--up]
       crbn checkout <pr-number> [--up]

  Without -b: resolve <name> as an existing branch (local first, then
  origin/<name> with auto-fetch). If a worktree on that branch exists,
  cd into it. Otherwise create one + cd.

  With -b: create a new branch <name> from --base (default HEAD), add a
  worktree, cd in. Fails if the branch already exists.

  PR shortcut: a purely-numeric <name> is treated as a GitHub PR number.
  With `gh` on PATH: checks out the PR's head branch into a worktree with
  push-back tracking, so `git push` updates the PR (same-repo and forks).
  Without `gh`: read-only fetch into a `pr-<num>` worktree (can't push back).

  --path PATH    Override the default worktree directory.
  --base REF     (with -b) base ref for the new branch. Default: HEAD.
  --up           After creation, exec `crbn up` in the new worktree.
USAGE
}

# Find an existing worktree's path by branch. Empty stdout if not found.
worktree_path_for_branch() {
  local query="$1" current_path="" branch="" line=""
  while IFS= read -r line; do
    if [[ "$line" == worktree\ * ]]; then
      current_path="${line#worktree }"
    elif [[ "$line" == branch\ refs/heads/* ]]; then
      branch="${line#branch refs/heads/}"
      if [[ "$branch" == "$query" ]]; then
        printf '%s\n' "$current_path"
        return 0
      fi
    fi
  done < <(git worktree list --porcelain)
}

cmd_checkout() {
  local name="" custom_path="" base_ref="HEAD" do_up=0 create_new=0
  while (( $# )); do
    case "$1" in
      -b)        create_new=1; shift ;;
      --path)    custom_path="${2:-}"; shift 2 ;;
      --path=*)  custom_path="${1#*=}"; shift ;;
      --base)    base_ref="${2:-}"; shift 2 ;;
      --base=*)  base_ref="${1#*=}"; shift ;;
      --up)      do_up=1; shift ;;
      -h|--help) checkout_usage; exit 0 ;;
      --)        shift; break ;;
      -*)        fail "unknown flag $1"; exit 2 ;;
      *)
        if [[ -z "$name" ]]; then
          name="$1"
        else
          fail "extra arg $1"
          exit 2
        fi
        shift
        ;;
    esac
  done
  if [[ -z "$name" ]]; then
    fail "branch required"
    checkout_usage
    exit 2
  fi

  # PR shortcut: bare numeric arg → fetch GitHub PR head ref + worktree it.
  if [[ "$name" =~ ^[0-9]+$ ]] && (( create_new == 0 )); then
    if [[ -n "$custom_path" || "$base_ref" != "HEAD" ]]; then
      warn "--path/--base ignored for PR checkout"
    fi
    _checkout_pr "$name" "$do_up"
    return $?
  fi

  local root parent base target
  root="$(repo_root)"
  parent="$(dirname "$root")"
  base="$(basename "$root")"
  base="${base%%-[a-z0-9-]*}"  # strip prior `-<slug>` suffix
  if [[ -n "$custom_path" ]]; then
    target="$custom_path"
    [[ "$target" = /* ]] || target="$PWD/$target"
  else
    target="$parent/${base}-$(slugify_branch "$name")"
  fi

  local local_exists=0 existing_worktree=""
  if git -C "$root" show-ref --verify --quiet "refs/heads/$name"; then
    local_exists=1
  fi
  existing_worktree="$(worktree_path_for_branch "$name")"

  if (( create_new )); then
    # -b path: branch must not exist.
    if (( local_exists )); then
      fail "branch '$name' already exists locally — drop -b to use it"
      exit 1
    fi
    if [[ -e "$target" ]]; then
      fail "target path already exists: $target"
      exit 1
    fi
    info "creating branch '$name' from ${C_BOLD}${base_ref}${C_RESET}"
    git -C "$root" worktree add -b "$name" "$target" "$base_ref" >&2
    ok "worktree at $target"
    do_post_create "$target"
    printf "cd %q\n" "$target"
    maybe_up "$target" "$do_up"
    return 0
  fi

  # No -b: fast-path if the branch already has a worktree.
  if [[ -n "$existing_worktree" ]]; then
    info "worktree exists at ${C_DIM}${existing_worktree}${C_RESET}"
    printf "cd %q\n" "$existing_worktree"
    maybe_up "$existing_worktree" "$do_up"
    return 0
  fi

  # Never create a separate worktree for the main checkout's branch — just cd
  # into the repo root. `git worktree add main` would detach and confuse.
  local main_branch
  main_branch="$(git -C "$root" symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null || echo "origin/main")"
  main_branch="${main_branch#origin/}"
  if [[ "$name" == "$main_branch" ]]; then
    info "main checkout at ${C_DIM}${root}${C_RESET}"
    printf "cd %q\n" "$root"
    maybe_up "$root" "$do_up"
    return 0
  fi

  # Need to materialize a worktree. Resolve the ref locally or via origin.
  local resolved=""
  if (( local_exists )); then
    resolved="$name"
  else
    info "fetching ${C_BOLD}origin/${name}${C_RESET}"
    if git -C "$root" fetch origin "$name" --quiet 2>/dev/null \
       && git -C "$root" show-ref --verify --quiet "refs/remotes/origin/$name"; then
      git -C "$root" branch --track "$name" "origin/$name" >&2
      resolved="$name"
    else
      fail "branch '$name' not found locally or on origin (use -b to create)"
      exit 1
    fi
  fi

  if [[ -e "$target" ]]; then
    fail "target path already exists: $target"
    exit 1
  fi

  info "git worktree add ${C_DIM}${target}${C_RESET}"
  git -C "$root" worktree add "$target" "$resolved" >&2
  ok "worktree at $target"
  do_post_create "$target"
  printf "cd %q\n" "$target"
  maybe_up "$target" "$do_up"
}

# Fetch a GitHub PR into a worktree whose branch pushes BACK to the PR.
# `gh pr checkout` configures the local branch's push tracking (remote + merge
# ref) for both same-repo and fork PRs — run it *inside* the worktree so commits
# push to the PR, not a new branch. Falls back to a read-only pure-git fetch when
# `gh` is absent. Same stdout contract as cmd_checkout (only `cd '<path>'`).
_checkout_pr() {
  local num="$1" do_up="$2"
  local root parent base
  root="$(repo_root)"
  parent="$(dirname "$root")"
  base="$(basename "$root")"
  base="${base%%-[a-z0-9-]*}"

  if ! command -v gh >/dev/null 2>&1; then
    _checkout_pr_no_gh "$num" "$do_up" "$root" "$parent" "$base"
    return
  fi

  # Resolve the PR's head branch — used verbatim as the local branch name so a
  # plain `git push` (push.default=simple) targets that ref and updates the PR.
  local metadata head_ref title branch target
  if ! metadata=$(gh pr view "$num" --json headRefName,title \
                    -q '.headRefName + "\t" + .title' 2>/dev/null); then
    fail "could not read PR #${num} via gh (correct number? run \`gh auth login\`?)"
    exit 1
  fi
  head_ref="${metadata%%$'\t'*}"
  title="${metadata#*$'\t'}"
  branch="$head_ref"
  target="$parent/${base}-$(slugify_branch "$branch")"
  info "PR #${num} — ${C_BOLD}${title}${C_RESET} (${C_DIM}${head_ref}${C_RESET})"

  # Fast-path: a worktree is already on this branch.
  local existing
  existing="$(worktree_path_for_branch "$branch")"
  if [[ -n "$existing" ]]; then
    info "worktree for PR #${num} exists at ${C_DIM}${existing}${C_RESET}"
    printf "cd %q\n" "$existing"
    maybe_up "$existing" "$do_up"
    return 0
  fi

  if [[ -e "$target" ]]; then
    fail "target path already exists: $target"
    exit 1
  fi

  # Detached worktree first, then `gh pr checkout` creates the PR branch inside
  # it with push-back tracking. On failure, roll back the empty worktree.
  info "git worktree add ${C_DIM}${target}${C_RESET}"
  git -C "$root" worktree add --detach "$target" >&2
  if ! ( cd "$target" && gh pr checkout "$num" --branch "$branch" >&2 ); then
    fail "gh pr checkout failed — removing worktree"
    git -C "$root" worktree remove --force "$target" 2>/dev/null || true
    exit 1
  fi
  ok "worktree at $target — \`git push\` updates PR #${num}"
  do_post_create "$target"
  printf "cd %q\n" "$target"
  maybe_up "$target" "$do_up"
}

# No `gh`: read-only pure-git fetch of the PR head into a local `pr-<num>`
# branch. Commits CANNOT be pushed back (the `pull/<num>/head` ref is read-only
# and no push tracking is set) — install `gh` to push to the PR.
_checkout_pr_no_gh() {
  local num="$1" do_up="$2" root="$3" parent="$4" base="$5"
  local branch="pr-${num}" target="$parent/${base}-pr-${num}"

  local existing
  existing="$(worktree_path_for_branch "$branch")"
  if [[ -n "$existing" ]]; then
    info "worktree for PR #${num} exists at ${C_DIM}${existing}${C_RESET}"
    printf "cd %q\n" "$existing"
    maybe_up "$existing" "$do_up"
    return 0
  fi

  warn "gh not found — fetching PR #${num} read-only (push-back disabled; install gh to push to the PR)"
  # Reuse an existing local branch instead of re-fetching (avoids clobbering
  # in-progress edits stacked on the PR ref).
  if git -C "$root" show-ref --verify --quiet "refs/heads/${branch}"; then
    info "local branch '${branch}' exists — skipping fetch"
  else
    if ! git -C "$root" fetch origin "pull/${num}/head:${branch}" --quiet; then
      fail "could not fetch PR #${num} from origin (correct number? PR open on this repo?)"
      exit 1
    fi
  fi

  if [[ -e "$target" ]]; then
    fail "target path already exists: $target"
    exit 1
  fi

  info "git worktree add ${C_DIM}${target}${C_RESET}"
  git -C "$root" worktree add "$target" "$branch" >&2
  ok "worktree at $target"
  do_post_create "$target"
  printf "cd %q\n" "$target"
  maybe_up "$target" "$do_up"
}

# Provision the freshly-created worktree via `crbn init`: sets the canonical
# slug, syncs `.env`/copy-files from main, and links .ai skills into
# .claude/.codex (all gitignored, so a fresh worktree has none). Run inside the
# worktree so it reads package.json#crbn.copy from main via --git-common-dir.
# All output goes to stderr to keep stdout reserved for the eval'd `cd` line.
do_post_create() {
  local target="$1"
  if ! ( cd "$target" && delegate_ts init >&2 ); then
    warn "init step failed (worktree was still created)"
  fi
}

# Replace process with `crbn up` cd'd into the new worktree. Caller's shell
# stays at original cwd; on Ctrl+C they're back where they started.
maybe_up() {
  local target="$1" enabled="$2"
  if (( enabled )); then
    info "starting stack in $target"
    cd "$target"
    delegate_ts up
  fi
}

# ---------------------------------------------------------------------------
# Top-level help
# ---------------------------------------------------------------------------

print_help() {
  cat <<'USAGE'
crbn — Carbon dev CLI

  Worktrees:
    crbn checkout <branch>          Switch into worktree (creates if missing).
    crbn checkout -b <branch>       New branch + worktree (--base REF).
    crbn checkout <pr-number>       PR → worktree; git push updates the PR (needs gh).
    crbn new [branch]               Interactive worktree creation.
    crbn init                       Provision the current worktree (slug/env/skills).
    crbn list                       Show all worktrees with stack status.
    crbn remove [--prune] [name...] Delete worktrees (picker, or named by branch/path).
                                    --prune also deletes the git branch.
    crbn prune                      Destroy stacks whose worktree is gone.
    crbn prune --all                Destroy every stack on this machine (worktrees kept).
    crbn prune --tree               Also forget missing worktrees; with --all, remove clean ones.

  Stack:
    crbn up                         Boot compose stack + apps.
    crbn up --all                   Launch all apps without the picker.
    crbn up --no-portless           Localhost mode (API:54321 ERP:3000 MES:3001).
    crbn up --borrow                Reuse another worktree's containers.
    crbn up --no-apps               Services only, no dev servers.
    crbn up --full                  Also start Studio, Postgres-Meta, edge runtime, imgproxy.
    crbn up --no-hibernate          Don't stop the containers when ERP/MES go quiet.
    crbn down                       Stop stack (volumes preserved).
    crbn down --purge               Stop stack, wipe volumes, release the slot.
    crbn reset                      Wipe volumes + redis, then up.
    crbn status                     Port assignment + container health.
    crbn status --json              Same, as JSON (also: crbn list --json).
    crbn migrate                    Apply DB migrations (loads .env.local).
    crbn restore <file>             Restore a prod backup, then apply migrations it predates.
    crbn reload <service...>        Recreate compose services (apply compose/env edits, apps untouched).

  Files:
    crbn copy <file...>             Copy file(s) from main checkout.
    crbn env sync                   Sync package.json#crbn.copy from main.

  Misc:
    crbn --version                  Print crbn commit + node version.
    crbn --help                     Show this help.

USAGE
}

# ---------------------------------------------------------------------------
# Dispatch
# ---------------------------------------------------------------------------

cmd="${1:-}"
[[ $# -gt 0 ]] && shift || true

case "$cmd" in
  ""|help|-h|--help)
    print_help
    ;;
  -v|--version)
    sha="$(cd "$(repo_root 2>/dev/null)" 2>/dev/null && git rev-parse --short HEAD 2>/dev/null || true)"
    printf 'crbn (carbon dev cli) — commit %s, node %s\n' "${sha:-unknown}" "$(node -v)"
    ;;
  checkout)
    cmd_checkout "$@"
    ;;
  *)
    # Everything else belongs to the TypeScript CLI, which reports an unknown
    # command itself. No allow-list here: this router runs from the main
    # checkout while the CLI runs from the current worktree, so a list would
    # reject subcommands a branch adds.
    delegate_ts "$cmd" "$@"
    ;;
esac