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.

crbn: stability improvements

Sidwebworksfd3226371a79
diff --git a/packages/dev/src/commands/new.ts b/packages/dev/src/commands/new.ts
index 2973da55f7..f8285c43a0 100644
--- a/packages/dev/src/commands/new.ts
+++ b/packages/dev/src/commands/new.ts
@@ -11,14 +11,14 @@ import {
} from "../prompts.js";
import { getWorktreeRoot, slugify } from "../worktree.js";
-export async function newWorktree() {
+export async function newWorktree(opts?: { branch?: string }) {
intro("Carbon · new worktree");
const here = await getWorktreeRoot();
const parentDir = dirname(here);
const repoBaseName = basename(here).replace(/-[a-z0-9-]+$/i, "");
- const branch = await promptBranch();
+ const branch = await promptBranch(opts?.branch);
const defaultDir = `${repoBaseName}-${slugify(branch)}`;
const dirName = await promptDirName(parentDir, defaultDir);
diff --git a/packages/dev/src/commands/remove.ts b/packages/dev/src/commands/remove.ts
index 6f245913d0..0bd81d57e5 100644
--- a/packages/dev/src/commands/remove.ts
+++ b/packages/dev/src/commands/remove.ts
@@ -3,14 +3,15 @@ import {
intro,
isCancel,
log,
+ multiselect,
outro,
- select,
- tasks
+ spinner
} from "@clack/prompts";
import pc from "picocolors";
import {
listWorktrees as gitListWorktrees,
isDirty,
+ mainCheckoutRoot,
removeWorktree
} from "../git.js";
import { confirmRemove } from "../prompts.js";
@@ -26,108 +27,134 @@ export async function removeWorktreeCmd() {
intro("Carbon · remove worktree");
const wtsAll = await gitListWorktrees();
- const wts = wtsAll.filter((w) => !w.bare && !w.current);
+ const mainRoot = await mainCheckoutRoot();
+ const wts = wtsAll.filter(
+ (w) => !w.bare && !w.current && w.path !== mainRoot
+ );
if (wts.length === 0) {
log.warn("no other worktrees to remove");
outro("");
return;
}
- const choice = await select({
- message: "Worktree to remove",
+ const choices = await multiselect({
+ message: "Worktrees to remove",
options: wts.map((w) => ({
value: w.path,
label: `${w.branch ?? "(detached)"} ${pc.dim(w.path)}`
- }))
+ })),
+ required: true
});
- if (isCancel(choice)) {
+ if (isCancel(choices)) {
cancel("aborted");
process.exit(0);
}
- const targetPath = choice as string;
- const target = wts.find((w) => w.path === targetPath)!;
+ const selectedPaths = choices as string[];
+ const targets = selectedPaths.map((p) => wts.find((w) => w.path === p)!);
- const dirty = await isDirty(targetPath);
const registry = listSlugs();
- const slug = slugForPath(targetPath, registry);
- const projectLabel = slug ? `carbon-${slug}` : "(no stack)";
-
- const warnings: string[] = [];
- if (dirty) warnings.push(`${pc.yellow("⚠")} uncommitted changes in worktree`);
- if (slug)
- warnings.push(
- `${pc.yellow("⚠")} stack ${projectLabel} will be destroyed (volumes wiped)`
- );
- if (warnings.length) log.warn(warnings.join("\n"));
-
- const ok = await confirmRemove({
- branchOrPath: target.branch ?? targetPath,
- hasStack: !!slug
- });
- if (!ok) {
- cancel("aborted");
- process.exit(0);
+
+ // Build context once (isDirty, slug, etc.) — reused for warnings + removal.
+ const jobs = await Promise.all(
+ targets.map(async (target) => {
+ const slug = slugForPath(target.path, registry);
+ return {
+ target,
+ dirty: await isDirty(target.path),
+ slug,
+ projectLabel: slug ? `carbon-${slug}` : null,
+ slotInfo: slug ? getSlot(slug) : null,
+ branchPrefix: slug ? branchToPrefix(target.branch, slug) : null
+ };
+ })
+ );
+
+ // Show warnings and confirm for each target.
+ for (const job of jobs) {
+ const { target, dirty, slug, projectLabel } = job;
+
+ const warnings: string[] = [];
+ if (dirty)
+ warnings.push(`${pc.yellow("⚠")} uncommitted changes in worktree`);
+ if (slug)
+ warnings.push(
+ `${pc.yellow("⚠")} stack ${projectLabel} will be destroyed (volumes wiped)`
+ );
+ if (warnings.length)
+ log.warn(`${target.branch ?? target.path}\n${warnings.join("\n")}`);
+
+ const ok = await confirmRemove({
+ branchOrPath: target.branch ?? target.path,
+ hasStack: !!slug
+ });
+ if (!ok) {
+ cancel("aborted");
+ process.exit(0);
+ }
}
- const slotInfo = slug ? getSlot(slug) : null;
- const branchPrefix = slug ? branchToPrefix(target.branch, slug) : null;
-
- await tasks([
- ...(branchPrefix
- ? [
- {
- title: "Unregister portless aliases",
- task: async () => {
- await unregisterAliases(targetPath, branchPrefix);
- pruneStaleRoutes();
- return "network stopped";
- }
- }
- ]
- : []),
- ...(slug
- ? [
- {
- title: `docker compose down -v · ${projectLabel}`,
- task: async () => {
- await destroyProjectVolumes(targetPath, projectLabel);
- return "stack and volumes removed";
- }
- }
- ]
- : []),
- ...(slotInfo && typeof slotInfo.redisDb === "number"
- ? [
- {
- title: `Flush redis db ${slotInfo.redisDb}`,
- task: async () => {
- await flushDb(slotInfo.redisDb);
- return "redis db flushed";
- }
- }
- ]
- : []),
- {
- title: `git worktree remove ${targetPath}`,
- task: async () => {
- await removeWorktree(targetPath, dirty);
- return "worktree removed";
+ const s = spinner();
+ let done = 0;
+ const total = jobs.length;
+ const needsPrune = jobs.some((j) => j.branchPrefix);
+
+ const progress = (label: string) => {
+ s.message(`(${done}/${total}) ${label}`);
+ };
+
+ s.start(`Removing ${total} worktree${total > 1 ? "s" : ""}`);
+
+ // Run all removals concurrently.
+ const results = await Promise.allSettled(
+ jobs.map(async (job) => {
+ const label = job.target.branch ?? job.target.path;
+ const { target, dirty, slug, projectLabel, slotInfo, branchPrefix } = job;
+
+ if (branchPrefix) {
+ progress(`${label}: unregistering aliases`);
+ await unregisterAliases(target.path, branchPrefix);
}
- },
- ...(slug
- ? [
- {
- title: "Prune port registry",
- task: async () => {
- removeSlot(slug);
- return `removed ${slug}`;
- }
- }
- ]
- : [])
- ]);
-
- outro("done");
+ if (slug && projectLabel) {
+ progress(`${label}: tearing down stack`);
+ await destroyProjectVolumes(target.path, projectLabel);
+ }
+ if (slotInfo && typeof slotInfo.redisDb === "number") {
+ progress(`${label}: flushing redis db ${slotInfo.redisDb}`);
+ await flushDb(slotInfo.redisDb);
+ }
+
+ progress(`${label}: removing worktree`);
+ await removeWorktree(target.path, dirty);
+
+ if (slug) removeSlot(slug);
+
+ done++;
+ progress(pc.green(label));
+ })
+ );
+
+ // One global prune after all aliases removed.
+ if (needsPrune) {
+ s.message("pruning stale routes");
+ await pruneStaleRoutes();
+ }
+
+ s.stop(`Removed ${done}/${total} worktree${total > 1 ? "s" : ""}`);
+
+ // Report failures.
+ const failed = results.filter(
+ (r): r is PromiseRejectedResult => r.status === "rejected"
+ );
+ for (let i = 0; i < results.length; i++) {
+ if (results[i]!.status === "rejected") {
+ const label = jobs[i]!.target.branch ?? jobs[i]!.target.path;
+ log.error(
+ `${label}: ${(results[i] as PromiseRejectedResult).reason?.message ?? "unknown error"}`
+ );
+ }
+ }
+
+ outro(failed.length ? `done with ${failed.length} error(s)` : "done");
}
function slugForPath(
diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.ts
index 5f09dfae42..fb80f3216d 100644
--- a/packages/dev/src/commands/up.ts
+++ b/packages/dev/src/commands/up.ts
@@ -68,6 +68,8 @@ type UpOpts = {
pull?: boolean;
/** When true, show a picker to borrow another worktree's running containers. */
borrow?: boolean;
+ /** When false, skip portless proxy and use localhost URLs. */
+ portless?: boolean;
};
type Ctx = {
@@ -96,9 +98,13 @@ export async function up(opts: UpOpts = {}) {
loadDotenv({ path: join(root, ".env.local"), override: false });
loadDotenv({ path: join(root, ".env"), override: false });
- // Set CARBON_PORTLESS=0 to use http://localhost:PORT URLs and skip the
- // portless proxy setup (useful when the .dev TLD cert is not trusted).
- const portless = process.env.CARBON_PORTLESS !== "0";
+ // --no-portless flag or CARBON_PORTLESS=0 to use http://localhost:PORT URLs
+ // and skip the portless proxy setup (useful when the .dev TLD cert is not
+ // trusted). The flag takes precedence over the env var.
+ const portless =
+ opts.portless !== undefined
+ ? opts.portless
+ : process.env.CARBON_PORTLESS !== "0";
intro("Carbon · dev up");
diff --git a/packages/dev/src/env.ts b/packages/dev/src/env.ts
index 4250b02257..cfcd5d1368 100644
--- a/packages/dev/src/env.ts
+++ b/packages/dev/src/env.ts
@@ -59,13 +59,13 @@ export function renderEnv(opts: {
lines.push(`SUPABASE_JWT_SECRET=${jwt.secret}`);
lines.push(`SUPABASE_ANON_KEY=${jwt.anonKey}`);
lines.push(`SUPABASE_SERVICE_ROLE_KEY=${jwt.serviceKey}`);
- // Branch-independent OAuth callback host (api.carbon.dev). Last `crbn up`
- // wins — registers `api.carbon` alias to its PORT_API.
+ const apiBase = portless ? `https://${host("api")}` : local(ports.PORT_API);
+ // OAuth callback must match the URL scheme apps actually use.
lines.push(
- `SUPABASE_AUTH_EXTERNAL_GOOGLE_REDIRECT_URI=https://api.carbon.dev/auth/v1/callback`
+ `SUPABASE_AUTH_EXTERNAL_GOOGLE_REDIRECT_URI=${portless ? "https://api.carbon.dev" : apiBase}/auth/v1/callback`
);
lines.push(
- `SUPABASE_AUTH_EXTERNAL_AZURE_REDIRECT_URI=https://api.carbon.dev/auth/v1/callback`
+ `SUPABASE_AUTH_EXTERNAL_AZURE_REDIRECT_URI=${portless ? "https://api.carbon.dev" : apiBase}/auth/v1/callback`
);
lines.push("");
lines.push("# Aux services");
@@ -75,7 +75,9 @@ export function renderEnv(opts: {
// SDK advertises this as its serve URL during self-register. Must be
// reachable from inside the inngest container (handled via extra_hosts +
// portless CA mount in docker-compose.dev.yml).
- lines.push(`INNGEST_SERVE_HOST=https://${host("erp")}`);
+ lines.push(
+ `INNGEST_SERVE_HOST=${portless ? `https://${host("erp")}` : local(ports.PORT_ERP)}`
+ );
lines.push("");
return lines.join("\n");
}
diff --git a/packages/dev/src/git.ts b/packages/dev/src/git.ts
index 50e32ede24..1d42d35d98 100644
--- a/packages/dev/src/git.ts
+++ b/packages/dev/src/git.ts
@@ -116,6 +116,33 @@ export async function branchExists(branch: string): Promise<boolean> {
return r.exitCode === 0;
}
+/**
+ * Check if creating `branch` would conflict with an existing ref in the
+ * hierarchy. Git refs are path-like: `test` and `test/sid` can't coexist
+ * because `test` would need to be both a file and a directory under
+ * `.git/refs/heads/`.
+ *
+ * Returns the conflicting ref name, or null if no conflict.
+ */
+export async function refConflict(branch: string): Promise<string | null> {
+ // A parent segment exists as a branch? e.g. "test" blocks "test/sid".
+ const parts = branch.split("/");
+ for (let i = 1; i < parts.length; i++) {
+ const ancestor = parts.slice(0, i).join("/");
+ if (await branchExists(ancestor)) return ancestor;
+ }
+ // A child branch exists under this name? e.g. "test/sid" blocks "test".
+ const r = await execa(
+ "git",
+ ["for-each-ref", "--format=%(refname:short)", `refs/heads/${branch}/`],
+ { reject: false }
+ );
+ if (r.exitCode === 0 && r.stdout.trim()) {
+ return r.stdout.trim().split("\n")[0]!;
+ }
+ return null;
+}
+
export async function deleteBranch(branch: string): Promise<void> {
// -D forces even on unmerged; caller confirms.
const r = await execa("git", ["branch", "-D", branch], { reject: false });
diff --git a/packages/dev/src/main.ts b/packages/dev/src/main.ts
index 15a583e5b2..3fe324a830 100644
--- a/packages/dev/src/main.ts
+++ b/packages/dev/src/main.ts
@@ -46,6 +46,12 @@ const main = defineCommand({
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: ({ args }) =>
@@ -54,7 +60,8 @@ const main = defineCommand({
regen: args.regen !== false,
apps: args.apps !== false,
pull: args.pull === true,
- borrow: args.borrow === true
+ borrow: args.borrow === true,
+ portless: args.portless !== false
})
}),
down: defineCommand({
@@ -86,7 +93,14 @@ const main = defineCommand({
}),
new: defineCommand({
meta: { description: "Interactive: create a worktree on a fresh branch" },
- run: () => newWorktree()
+ args: {
+ branch: {
+ type: "positional",
+ required: false,
+ description: "Branch name (pre-fills the prompt)"
+ }
+ },
+ run: ({ args }) => newWorktree({ branch: args.branch })
}),
list: defineCommand({
meta: { description: "List worktrees with stack status" },
diff --git a/packages/dev/src/prompts.ts b/packages/dev/src/prompts.ts
index bf8f24d98d..b1bf8f8ad4 100644
--- a/packages/dev/src/prompts.ts
+++ b/packages/dev/src/prompts.ts
@@ -12,7 +12,12 @@ import {
import { join } from "pathe";
import pc from "picocolors";
import { APP_CHOICES, type AppId } from "./constants.js";
-import { branchExists, deleteBranch, listWorktrees } from "./git.js";
+import {
+ branchExists,
+ deleteBranch,
+ listWorktrees,
+ refConflict
+} from "./git.js";
import { listSlugs } from "./worktree.js";
// git-check-ref-format(1) rules.
@@ -71,11 +76,12 @@ export async function pickApps(): Promise<AppId[]> {
return picked as AppId[];
}
-export async function promptBranch(): Promise<string> {
+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();
@@ -86,6 +92,16 @@ export async function promptBranch(): Promise<string> {
});
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);