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
// 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 { existsSync } from "node:fs";
import {
cancel,
confirm,
isCancel,
log,
multiselect,
note,
select,
text
} from "@clack/prompts";
import { join } from "pathe";
import pc from "picocolors";
import { APP_CHOICES, type AppId } from "./constants.js";
import {
branchExists,
deleteBranch,
listWorktrees,
refConflict
} from "./git.js";
import { listSlugs } from "./worktree.js";
// git-check-ref-format(1) rules.
const INVALID_BRANCH_RE =
/(^[/-])|([/-]$)|(\.\.)|(@\{)|([\s~^:?*[\\])|(\/{2,})/;
// A clack prompt with no terminal neither waits nor cancels — the process just
// ends mid-command. Say what was needed, and how to run without a terminal.
export function requireTerminal(what: string, instead: string) {
if (process.stdin.isTTY) return;
// Not a throw: citty prints a thrown error with its stack, twice.
cancel(`${what} needs a terminal. ${instead}`);
process.exit(1);
}
const CONFIRM_BY_ENV = "Set CARBON_DEV_YES=1 to confirm without one.";
export async function pickBorrowSlug(currentSlug: string): Promise<string> {
const registry = listSlugs();
const others = Object.entries(registry).filter(([s]) => s !== currentSlug);
if (others.length === 0) {
throw new Error(
`No other worktree stacks in ~/.carbon/dev-ports.json.\nRun \`crbn up\` in another worktree first.`
);
}
if (others.length === 1) {
log.info(`auto-selecting only available worktree: ${others[0]![0]}`);
return others[0]![0];
}
requireTerminal(
"Choosing a worktree to borrow from",
"Run `crbn up --borrow` in a terminal."
);
const picked = await select({
message: "Borrow containers from which worktree?",
options: others.map(([s, entry]) => ({
value: s,
label: s,
hint: entry.worktreeRoot
}))
});
if (isCancel(picked)) abort();
return picked as string;
}
export async function pickApps(): Promise<AppId[]> {
const fromEnv = process.env.CARBON_DEV_APPS;
if (fromEnv) {
return fromEnv
.split(",")
.map((s) => s.trim())
.filter((s): s is AppId => APP_CHOICES.some((c) => c.value === s));
}
const optInApps: readonly AppId[] = ["assembler", "email", "studio"];
const defaultApps = APP_CHOICES.filter(
(c) => !optInApps.includes(c.value)
).map((c) => c.value);
if (!process.stdin.isTTY) return defaultApps;
note(
"When no apps are selected it will only run (postgres, kong, supabase, inngest, mail) without spawning ERP/MES dev servers.",
"Tip"
);
const picked = await multiselect({
message: "Which apps to run?",
options: APP_CHOICES.map((c) => ({
value: c.value,
label: c.label,
hint: c.hint
})),
initialValues: defaultApps,
required: false
});
if (isCancel(picked)) abort();
return picked as AppId[];
}
export async function promptBranch(initial?: string): Promise<string> {
while (true) {
const value = await text({
message: "Branch name",
placeholder: "feature/foo",
initialValue: initial,
validate(v) {
if (!v || !v.trim()) return "Branch is required";
const t = v.trim();
if (INVALID_BRANCH_RE.test(t))
return "Invalid git branch name (no spaces, control chars, ~^:?*[\\, no leading/trailing - or /, no '..' or '@{')";
if (t.length > 100) return "Branch name too long";
}
});
if (isCancel(value)) abort();
const trimmed = (value as string).trim();
// Detect git ref hierarchy conflicts (e.g. "test" exists → "test/sid" impossible).
const conflict = await refConflict(trimmed);
if (conflict) {
log.error(
`Branch '${trimmed}' conflicts with existing ref '${conflict}'.\n` +
` Git can't have both — pick a different name or delete '${conflict}' first.`
);
initial = undefined;
continue;
}
if (await branchExists(trimmed)) {
const worktrees = await listWorktrees();
const onWorktree = worktrees.find((w) => w.branch === trimmed);
if (onWorktree) {
log.error(
`Branch '${trimmed}' already has a worktree at ${pc.dim(onWorktree.path)}\n` +
` Jump in with: ${pc.cyan(`crbn go ${trimmed}`)}`
);
continue;
}
// Branch without worktree → offer in-flow nuke + recreate.
log.warn(
`Branch '${trimmed}' exists locally but has no worktree.\n` +
` Materialize the existing branch with: ${pc.cyan(`crbn checkout ${trimmed}`)}`
);
const recreate = await confirm({
message: `Delete '${trimmed}' (force — discards any unmerged commits) and create fresh branch?`,
initialValue: false
});
if (isCancel(recreate)) abort();
if (!recreate) continue;
try {
await deleteBranch(trimmed);
} catch (err) {
log.error(`Failed to delete branch: ${(err as Error).message}`);
continue;
}
log.success(`Deleted branch '${trimmed}'`);
}
return trimmed;
}
}
export async function promptDirName(
parentDir: string,
initial: string
): Promise<string> {
while (true) {
const value = await text({
message: `Worktree directory (relative to ${pc.dim(parentDir)})`,
initialValue: initial,
validate(v) {
if (!v || !v.trim()) return "Directory name required";
if (/[\s/]/.test(v.trim()))
return "No spaces or slashes — must be a single dirname";
}
});
if (isCancel(value)) abort();
const trimmed = (value as string).trim();
if (existsSync(join(parentDir, trimmed))) {
log.error(`Path '${trimmed}' already exists in ${parentDir}`);
continue;
}
return trimmed;
}
}
export async function promptBaseRef(
currentBranch: string | null
): Promise<string> {
const opts: { value: string; label: string }[] = [
{ value: "main", label: "main" }
];
if (currentBranch && currentBranch !== "main") {
opts.push({ value: currentBranch, label: currentBranch });
}
opts.push({ value: "origin/main", label: "origin/main" });
const baseRef = await select({
message: "Base ref",
options: opts,
initialValue: "main"
});
if (isCancel(baseRef)) abort();
return baseRef as string;
}
export async function promptCopyEnv(): Promise<boolean> {
const ok = await confirm({
message: "Copy .env from current worktree?",
initialValue: true
});
if (isCancel(ok)) abort();
return ok as boolean;
}
export async function confirmReset(projectName: string): Promise<boolean> {
if (process.env.CARBON_DEV_YES === "1") return true;
requireTerminal("Confirming a reset", CONFIRM_BY_ENV);
const ok = await confirm({
message: `Destroy all volumes for ${pc.bold(projectName)}? (postgres, storage, inngest data will be wiped, redis db flushed)`,
initialValue: false
});
if (isCancel(ok)) return false;
return ok as boolean;
}
export async function confirmPrune(count: number, trees = 0): Promise<boolean> {
if (process.env.CARBON_DEV_YES === "1") return true;
requireTerminal("Confirming a prune", CONFIRM_BY_ENV);
const ok = await confirm({
// Only what will happen: a worktree-only prune wipes no data.
message: `${[
count
? `Destroy ${count} stack(s) and their volumes (postgres, storage, inngest data will be wiped)`
: "",
trees ? `${count ? "remove" : "Remove"} ${trees} worktree(s)` : ""
]
.filter(Boolean)
.join(", and ")}?`,
initialValue: false
});
if (isCancel(ok)) return false;
return ok as boolean;
}
export async function confirmRestore(opts: {
port: number;
file: string;
mode: string;
}): Promise<boolean> {
if (process.env.CARBON_DEV_YES === "1") return true;
requireTerminal("Confirming a restore", CONFIRM_BY_ENV);
const ok = await confirm({
message: `Replace the database on 127.0.0.1:${pc.bold(String(opts.port))} with ${pc.bold(opts.file)}? (mode: ${opts.mode} — the current data, including any seeded test data, is wiped)`,
initialValue: false
});
if (isCancel(ok)) return false;
return ok as boolean;
}
export async function confirmRemove(opts: {
branchOrPath: string;
hasStack: boolean;
}): Promise<boolean> {
if (process.env.CARBON_DEV_YES === "1") return true;
requireTerminal("Confirming a removal", CONFIRM_BY_ENV);
const ok = await confirm({
message: `Permanently remove ${opts.branchOrPath} and ${opts.hasStack ? "wipe its docker volumes" : "the worktree"}?`,
initialValue: false
});
if (isCancel(ok)) return false;
return ok as boolean;
}
function abort(): never {
cancel("aborted");
process.exit(0);
}