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(crbn): cli stability and bug fixes
Sidwebworksd31c1b004722
diff --git a/apps/erp/vite.config.ts b/apps/erp/vite.config.tsindex a11076de9a..ae0095aa28 100644--- a/apps/erp/vite.config.ts+++ b/apps/erp/vite.config.ts@@ -39,9 +39,6 @@ export default defineConfig(({ isSsrBuild, mode }) => {port: 3000,strictPort: true,allowedHosts: [".ngrok-free.app", ".ngrok-free.dev", ".dev", ".localhost"],- watch: {- awaitWriteFinish: { stabilityThreshold: 250 },- },},plugins: [tailwindcss(),diff --git a/packages/dev/bin/crbn b/packages/dev/bin/crbnindex 32081aa256..58d5bc6a95 100755--- a/packages/dev/bin/crbn+++ b/packages/dev/bin/crbn@@ -24,7 +24,9 @@ if command -v node >/dev/null 2>&1; thennode_ver="$(node -v)"node_major="${node_ver#v}"node_major="${node_major%%.*}"- if [[ "$node_major" -lt 22 ]]; then+ # Guard non-numeric majors (nightly/RC builds) so the arithmetic test below+ # doesn't abort with a cryptic "unbound variable" under `set -u`.+ if ! [[ "$node_major" =~ ^[0-9]+$ ]] || (( node_major < 22 )); thenprintf '\033[1;31m✗\033[0m crbn requires Node.js 22+ (found %s)\n' "$node_ver" >&2exit 1fi@@ -406,6 +408,10 @@ crbn — Carbon dev CLIcrbn 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}@@ -420,6 +426,10 @@ 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 "$@";;diff --git a/packages/dev/src/commands/copy.ts b/packages/dev/src/commands/copy.tsindex 313234e7fa..7ae074230d 100644--- a/packages/dev/src/commands/copy.ts+++ b/packages/dev/src/commands/copy.ts@@ -1,6 +1,6 @@import { copyFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";import { intro, log, outro } from "@clack/prompts";-import { dirname, join, relative } from "pathe";+import { dirname, isAbsolute, join, relative, resolve } from "pathe";import pc from "picocolors";import { mainCheckoutRoot } from "../git.js";import { isAtLeastAsNew } from "../helpers.js";@@ -80,8 +80,14 @@ export async function copy(files: string[]) {let copied = 0;for (const file of files) {- // Resolve relative to worktree root so paths are consistent.- const rel = relative(cwd, join(cwd, file));+ // Resolve against the worktree root, then reject anything that escapes it+ // (`../../x`, absolute paths) — copy mirrors the same relative path from+ // main, it must not read/write outside the worktree.+ const rel = relative(cwd, resolve(cwd, file));+ if (rel === "" || rel.startsWith("..") || isAbsolute(rel)) {+ log.warn(`${pc.dim(file)} escapes the worktree — skipped`);+ continue;+ }const src = join(mainRoot, rel);const dest = join(cwd, rel);if (!existsSync(src)) {diff --git a/packages/dev/src/commands/down.ts b/packages/dev/src/commands/down.tsindex 388fe2b1bf..8fb79f2856 100644--- a/packages/dev/src/commands/down.ts+++ b/packages/dev/src/commands/down.ts@@ -4,7 +4,12 @@ import { syncAppPortlessConfigs } from "../env.js";import { currentBranch } from "../git.js";import { stopStack } from "../services/compose.js";import { branchToPrefix, unregisterAliases } from "../services/portless.js";-import { getWorktreeRoot, projectName, resolveSlug } from "../worktree.js";+import {+ ensureSlugAvailable,+ getWorktreeRoot,+ projectName,+ resolveSlug+} from "../worktree.js";// silent: post-SIGINT path. clack tasks/spinner would EIO via setRawMode on// the freshly-interrupted stdin; fall back to plain printf progress.@@ -13,6 +18,10 @@ export async function down(opts: { silent?: boolean } = {}) {const slug = resolveSlug(root);const project = projectName(slug);+ // Refuse to tear down a stack that another worktree owns (same slug, different+ // path). Passes for our own stack and when nothing is running.+ await ensureSlugAvailable(slug, root);+if (opts.silent) {return runPlain(root, slug, project);}diff --git a/packages/dev/src/commands/list.ts b/packages/dev/src/commands/list.tsindex 4112f82814..860ece99b4 100644--- a/packages/dev/src/commands/list.ts+++ b/packages/dev/src/commands/list.ts@@ -3,7 +3,7 @@ import pc from "picocolors";import { listWorktrees as gitListWorktrees } from "../git.js";import { dockerProjectStates } from "../services/compose.js";import { worktreesTable } from "../ui.js";-import { listSlugs, projectName } from "../worktree.js";+import { listSlugs, projectName, slugForWorktreePath } from "../worktree.js";export async function listWorktrees() {intro("Carbon · worktrees");@@ -16,7 +16,7 @@ export async function listWorktrees() {const wts = wtsAll.filter((w) => !w.bare);const rows = wts.map((w) => {- const slug = slugForPath(w.path, registry);+ const slug = slugForWorktreePath(w.path, registry);const dockerState = slug? (dockerStates.get(projectName(slug)) ?? null): null;@@ -34,13 +34,3 @@ export async function listWorktrees() {});outro("");}--function slugForPath(- path: string,- registry: ReturnType<typeof listSlugs>-): string | null {- for (const [slug, entry] of Object.entries(registry)) {- if (entry.worktreeRoot === path) return slug;- }- return null;-}diff --git a/packages/dev/src/commands/migrate.ts b/packages/dev/src/commands/migrate.tsindex d29d15e63e..664042d881 100644--- a/packages/dev/src/commands/migrate.ts+++ b/packages/dev/src/commands/migrate.ts@@ -26,7 +26,10 @@ export async function migrate(opts: { regen?: boolean } = {}) {process.exit(1);}- loadDotenv({ path: envLocal, override: false });+ // .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 });loadDotenv({ path: join(root, ".env"), override: false });let portDb: number;diff --git a/packages/dev/src/commands/remove.ts b/packages/dev/src/commands/remove.tsindex 265dc50f2e..e40e3f69b3 100644--- a/packages/dev/src/commands/remove.ts+++ b/packages/dev/src/commands/remove.ts@@ -22,7 +22,13 @@ import {pruneStaleRoutes,unregisterAliases} from "../services/portless.js";-import { getSlot, listSlugs, projectName, removeSlot } from "../worktree.js";+import {+ getSlot,+ listSlugs,+ projectName,+ removeSlot,+ slugForWorktreePath+} from "../worktree.js";export async function removeWorktreeCmd(opts?: { prune?: boolean }) {const pruneBranches = opts?.prune === true;@@ -59,7 +65,7 @@ export async function removeWorktreeCmd(opts?: { prune?: boolean }) {// 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);+ const slug = slugForWorktreePath(target.path, registry);return {target,dirty: await isDirty(target.path),@@ -77,11 +83,17 @@ export async function removeWorktreeCmd(opts?: { prune?: boolean }) {const warnings: string[] = [];if (dirty)- warnings.push(`${pc.yellow("⚠")} uncommitted changes in worktree`);+ warnings.push(+ `${pc.yellow("⚠")} uncommitted changes will be LOST (force remove)`+ );if (slug)warnings.push(`${pc.yellow("⚠")} stack ${projectLabel} will be destroyed (volumes wiped)`);+ if (pruneBranches && target.branch)+ warnings.push(+ `${pc.yellow("⚠")} branch '${target.branch}' will be force-deleted (git branch -D, even if unmerged)`+ );if (warnings.length)log.warn(`${target.branch ?? target.path}\n${warnings.join("\n")}`);@@ -163,13 +175,3 @@ export async function removeWorktreeCmd(opts?: { prune?: boolean }) {outro(failed.length ? `done with ${failed.length} error(s)` : "done");}--function slugForPath(- path: string,- registry: ReturnType<typeof listSlugs>-): string | null {- for (const [slug, entry] of Object.entries(registry)) {- if (entry.worktreeRoot === path) return slug;- }- return null;-}diff --git a/packages/dev/src/commands/reset.ts b/packages/dev/src/commands/reset.tsindex 4ea39ce0d6..0693faef2a 100644--- a/packages/dev/src/commands/reset.ts+++ b/packages/dev/src/commands/reset.ts@@ -4,9 +4,11 @@ import {destroyProject,flushDb,listCarbonProjects,+ REDIS_CONTAINER,stopStack} from "../services/compose.js";import {+ ensureSlugAvailable,getSlot,getWorktreeRoot,listSlugs,@@ -20,6 +22,10 @@ export async function reset() {const root = await getWorktreeRoot();const slug = resolveSlug(root);+ // reset is the most destructive command (down -v wipes volumes). Refuse if+ // another worktree owns this slug's running stack — don't nuke their data.+ await ensureSlugAvailable(slug, root);+if (!(await confirmReset(projectName(slug)))) {cancel("reset aborted");process.exit(0);@@ -44,7 +50,7 @@ export async function reset() {const allProjects = await listCarbonProjects();const orphans = allProjects.filter(- (p) => !knownProjects.has(p) && p !== "carbon-shared"+ (p) => !knownProjects.has(p) && p !== REDIS_CONTAINER);if (orphans.length > 0) {log.warn(diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.tsindex 5994dbc39f..5628866fd4 100644--- a/packages/dev/src/commands/up.ts+++ b/packages/dev/src/commands/up.ts@@ -1,6 +1,6 @@import { box, intro, log, outro, progress, tasks } from "@clack/prompts";import { config as loadDotenv } from "dotenv";-import { execa } from "execa";+import { type ExecaChildProcess, execa } from "execa";import { join } from "pathe";import type { AppId } from "../constants.js";import { renderEnv, syncAppPortlessConfigs, writeEnv } from "../env.js";@@ -19,6 +19,7 @@ import {bootStack,type Container,devComposeImageRefs,+ ensureDockerRunning,listComposeServices,listContainers,pullStack,@@ -108,6 +109,22 @@ export async function up(opts: UpOpts = {}) {: process.env.CARBON_PORTLESS !== "0";intro("Carbon · dev up");+ // Fail fast with a clear message instead of a cryptic daemon error deep in+ // the boot (after prompts + sudo).+ await ensureDockerRunning();++ // During the long pre-apps phase (image pulls, migrations, sudo prompts) a+ // Ctrl+C would otherwise kill crbn and orphan half-booted containers. Tear+ // them down on interrupt; detached once apps take over teardown (below).+ let stripeChild: ExecaChildProcess | undefined;+ let interrupted = false;+ const detachEarly = onShutdown(() => {+ if (interrupted) return;+ interrupted = true;+ process.stderr.write("\ninterrupted — stopping partial stack…\n");+ killStripe(stripeChild);+ void down({ silent: true }).finally(() => process.exit(130));+ });if (portless) {await ensurePortlessInstalled();@@ -159,7 +176,7 @@ export async function up(opts: UpOpts = {}) {}if (process.env.CARBON_EDITION === "cloud") {- spawnStripeListener(root);+ stripeChild = spawnStripeListener(root);log.info("stripe listener spawned (CARBON_EDITION=cloud)");}@@ -172,12 +189,38 @@ export async function up(opts: UpOpts = {}) {`Carbon dev — ${slug}`);+ // Startup done — hand teardown ownership to the app supervisor (or, for+ // services-only, to a later manual `crbn down`).+ detachEarly();+if (selectedApps.length === 0) {+ // Services-only: the stack stays up after crbn exits, so let the stripe+ // listener outlive us too (apps mode kills it on teardown instead).+ stripeChild?.unref();outro("services up (run `crbn down` to stop)");return;}outro("apps starting (Ctrl+C to stop)");- await runAppsThenTeardown(root, selectedApps, ctx.ports, portless);+ await runAppsThenTeardown(+ root,+ selectedApps,+ ctx.ports,+ portless,+ stripeChild+ );+}++// Kill the detached stripe listener's whole process group (apps-mode teardown).+function killStripe(child?: ExecaChildProcess) {+ if (!child?.pid) return;+ try {+ process.kill(-child.pid, "SIGTERM");+ } catch {+ try {+ child.kill("SIGTERM");+ // biome-ignore lint/suspicious/noEmptyBlockStatements: best-effort kill+ } catch {}+ }}// ---------------------------------------------------------------------------@@ -434,12 +477,14 @@ async function setupPortless(ctx: Ctx, _selectedApps: AppId[]) {{title: "Register service aliases",task: async () => {- const count = await registerAliases(+ const { registered, total } = await registerAliases(ctx.root,ctx.branchPrefix,ctx.ports);- return `${count} aliases registered`;+ return registered === total+ ? `${registered} aliases registered`+ : `${registered}/${total} aliases registered (${total - registered} failed)`;}}]);@@ -472,7 +517,8 @@ async function runAppsThenTeardown(root: string,selectedApps: AppId[],ports: PortMap,- portless: boolean+ portless: boolean,+ stripeChild?: ExecaChildProcess) {await spawnApps({ root, apps: selectedApps, ports, portless });@@ -483,6 +529,8 @@ async function runAppsThenTeardown(process.stderr.write("\nfinishing teardown — please wait\n");});try {+ // Kill the stripe listener too — it's detached and would otherwise survive.+ killStripe(stripeChild);// silent: post-SIGINT stdin raw-mode triggers EIO in clack's spinner.await down({ silent: true });} finally {diff --git a/packages/dev/src/helpers.ts b/packages/dev/src/helpers.tsindex 85655b806f..0de81e18ee 100644--- a/packages/dev/src/helpers.ts+++ b/packages/dev/src/helpers.ts@@ -48,13 +48,21 @@ export async function waitForPort(* Invoke `onLine` once per line from `stream`. Backed by node's native* `readline.createInterface`, which buffers in C++ and avoids the per-chunk* `buf += chunk.toString(); split('\n')` allocations we used to do by hand.+ *+ * Returns a disposer — call it (e.g. on child exit) to close the interface and+ * drop its listeners. Long-lived, restarting children (the app supervisor)+ * would otherwise leak a readline interface per respawn. A stream `error`+ * (child killed mid-read) closes the interface instead of going uncaught.*/export function readLines(stream: NodeJS.ReadableStream,onLine: (line: string) => void-): void {+): () => void {const rl = createInterface({ input: stream, crlfDelay: Infinity });rl.on("line", onLine);+ const close = () => rl.close();+ stream.on("error", close);+ return close;}// ---------------------------------------------------------------------------diff --git a/packages/dev/src/prompts.ts b/packages/dev/src/prompts.tsindex b1bf8f8ad4..3b4144892d 100644--- a/packages/dev/src/prompts.ts+++ b/packages/dev/src/prompts.ts@@ -118,7 +118,7 @@ export async function promptBranch(initial?: string): Promise<string> {` Materialize the existing branch with: ${pc.cyan(`crbn checkout ${trimmed}`)}`);const recreate = await confirm({- message: `Delete '${trimmed}' (force) and create fresh branch?`,+ message: `Delete '${trimmed}' (force — discards any unmerged commits) and create fresh branch?`,initialValue: false});if (isCancel(recreate)) abort();diff --git a/packages/dev/src/services/apps.test.ts b/packages/dev/src/services/apps.test.tsnew file mode 100644index 0000000000..89bb01ddef--- /dev/null+++ b/packages/dev/src/services/apps.test.ts@@ -0,0 +1,177 @@+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "pathe";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { PortMap } from "../worktree.js";+import { spawnApps } from "./apps.js";++// A stand-in "dev server": a real child process we can make crash on demand.+// It appends its app id to a shared log on every launch (so the test can count+// restarts), exits 0 on SIGTERM/SIGINT (clean shutdown), and otherwise:+// mode "crash" -> always exit 1 (perpetual crash loop)+// mode "flaky" -> exit 1 until it has launched > crashTimes, then stay up+// mode "healthy" -> stay up until signaled+const DEV_SERVER = `+const fs = require("node:fs");+const [, , app, log, mode, crashTimes] = process.argv;+fs.appendFileSync(log, app + "\\n");+const launches = fs.readFileSync(log, "utf8").split("\\n").filter((l) => l === app).length;+const quit = () => process.exit(0);+process.on("SIGTERM", quit);+process.on("SIGINT", quit);+if (mode === "crash") process.exit(1);+if (mode === "flaky" && launches <= Number(crashTimes)) process.exit(1);+setInterval(() => {}, 1 << 30);+`;++const ports = { PORT_ERP: 39001, PORT_MES: 39002 } as unknown as PortMap;++let tmpRoot: string;+let scriptPath: string;+let logPath: string;+let active: { controller: AbortController; done: Promise<void> } | undefined;+let stderr: string[];++const countLaunches = (app: string): number =>+ existsSync(logPath)+ ? readFileSync(logPath, "utf8")+ .split("\n")+ .filter((l) => l === app).length+ : 0;++const waitFor = async (+ pred: () => boolean,+ { timeout = 12_000, interval = 25 } = {}+): Promise<void> => {+ const start = Date.now();+ while (!pred()) {+ if (Date.now() - start > timeout) throw new Error("waitFor: timed out");+ await new Promise((r) => setTimeout(r, interval));+ }+};++const startStack = (cfg: {+ apps: string[];+ modes: Record<string, string>;+ crashTimes?: Record<string, number>;+}) => {+ const controller = new AbortController();+ const done = spawnApps({+ root: tmpRoot,+ apps: cfg.apps,+ ports,+ portless: false,+ signal: controller.signal,+ command: ({ id }) => ({+ file: process.execPath,+ args: [+ scriptPath,+ id,+ logPath,+ cfg.modes[id] ?? "healthy",+ String(cfg.crashTimes?.[id] ?? 0)+ ]+ })+ });+ active = { controller, done };+ return { controller, done };+};++describe("spawnApps supervisor (integration)", () => {+ beforeEach(() => {+ tmpRoot = mkdtempSync(join(tmpdir(), "carbon-apps-"));+ mkdirSync(join(tmpRoot, "apps", "erp"), { recursive: true });+ mkdirSync(join(tmpRoot, "apps", "mes"), { recursive: true });+ scriptPath = join(tmpRoot, "dev-server.cjs");+ logPath = join(tmpRoot, "launches.log");+ writeFileSync(scriptPath, DEV_SERVER);+ stderr = [];+ vi.spyOn(process.stderr, "write").mockImplementation((chunk: unknown) => {+ stderr.push(String(chunk));+ return true;+ });+ });++ afterEach(async () => {+ // Make sure no real child process is left running, then clean up.+ active?.controller.abort();+ await active?.done.catch(() => {});+ active = undefined;+ vi.restoreAllMocks();+ rmSync(tmpRoot, { recursive: true, force: true });+ });++ it("auto-recovers a flaky dev server and leaves it running", async () => {+ const { controller, done } = startStack({+ apps: ["erp"],+ modes: { erp: "flaky" },+ crashTimes: { erp: 2 } // crash twice, then stay up on the 3rd launch+ });++ // Restarts through both crashes and reaches a healthy 3rd launch.+ await waitFor(() => countLaunches("erp") === 3);++ // It stays at 3 — the supervisor stops restarting once it's healthy.+ await new Promise((r) => setTimeout(r, 400));+ expect(countLaunches("erp")).toBe(3);+ expect(stderr.join("")).toContain(+ "erp dev server exited (code 1); restarting"+ );+ expect(stderr.join("")).not.toContain("giving up");++ // Clean programmatic shutdown resolves the stack.+ controller.abort();+ await expect(done).resolves.toBeUndefined();+ }, 20_000);++ it("restarts only the crashed app; the sibling is untouched", async () => {+ const { controller, done } = startStack({+ apps: ["erp", "mes"],+ modes: { erp: "flaky", mes: "healthy" },+ crashTimes: { erp: 1 } // erp crashes once then recovers+ });++ await waitFor(() => countLaunches("erp") === 2);+ // mes was started exactly once and never bounced.+ expect(countLaunches("mes")).toBe(1);+ await new Promise((r) => setTimeout(r, 300));+ expect(countLaunches("mes")).toBe(1);++ controller.abort();+ await expect(done).resolves.toBeUndefined();+ }, 20_000);++ it("gives up after a crash loop, with real backoff, and tears down", async () => {+ const start = Date.now();+ const { done } = startStack({+ apps: ["erp"],+ modes: { erp: "crash" } // never recovers+ });++ // No abort needed — give-up triggers teardown internally and resolves.+ await expect(done).resolves.toBeUndefined();+ const elapsed = Date.now() - start;++ // initial launch + 3 restarts, then give up on the 4th crash — no 5th.+ expect(countLaunches("erp")).toBe(4);+ const out = stderr.join("");+ expect(out).toContain("restarting in 500ms");+ expect(out).toContain("restarting in 1000ms");+ expect(out).toContain("restarting in 2000ms");+ expect(out).toContain(+ "erp dev server crashed 4× in 10s (code 1); giving up"+ );+ expect(out).toContain("stopping apps…");++ // Real exponential backoff means it can't have given up faster than+ // 500 + 1000 + 2000 ms.+ expect(elapsed).toBeGreaterThanOrEqual(3_400);+ }, 20_000);+});diff --git a/packages/dev/src/services/apps.ts b/packages/dev/src/services/apps.tsindex 3c1c8e86fd..2da236d2e6 100644--- a/packages/dev/src/services/apps.ts+++ b/packages/dev/src/services/apps.ts@@ -50,13 +50,37 @@ const APP_URL_ENV_KEYS: Partial<Record<string, string>> = {mes: "MES_URL"};+type AppCommand = { file: string; args: string[] };++function reactRouterDevCommand(port: number | undefined): AppCommand {+ return {+ file: "pnpm",+ args: [+ "exec",+ "react-router",+ "dev",+ ...(port !== undefined ? ["--port", String(port)] : []),+ "--host",+ "127.0.0.1"+ ]+ };+}+export function spawnApps(opts: {root: string;apps: string[];ports: PortMap;portless: boolean;+ // What each app runs; defaults to `pnpm exec react-router dev`. Override to+ // run a different process (the integration tests point this at a controllable+ // node script).+ command?: (ctx: { id: string; port: number | undefined }) => AppCommand;+ // Programmatic teardown in addition to OS signals: abort to stop the stack.+ signal?: AbortSignal;}): Promise<void> {const { root, apps, ports, portless } = opts;+ const buildCommand =+ opts.command ?? (({ port }) => reactRouterDevCommand(port));// When portless is active, apps talk to Supabase over HTTPS using// portless's self-signed CA. Tell Node to trust it.@@ -66,7 +90,11 @@ export function spawnApps(opts: {let shuttingDown = false;- const children: ExecaChildProcess[] = apps.map((id) => {+ // The live child per app slot; supervisors swap these on restart and+ // `shutdown()` signals whatever is current.+ const current: (ExecaChildProcess | undefined)[] = new Array(apps.length);++ const spawnOne = (id: string): ExecaChildProcess => {const color = APP_COLORS[id] ?? ((s: string) => s);// Spawn apps directly with assigned ports. Hostnames are registered via// `portless alias` (in registerAliases) so we control the exact format@@ -78,54 +106,52 @@ export function spawnApps(opts: {// OAuth callback) return to the correct app, not always ERP.const urlKey = APP_URL_ENV_KEYS[id];const vercelUrl = urlKey ? appEnv[urlKey] : undefined;- const child = execa(- "pnpm",- [- "exec",- "react-router",- "dev",- ...(port !== undefined ? ["--port", String(port)] : []),- "--host",- "127.0.0.1"- ],- {- cwd: join(root, "apps", id),- env: {- ...appEnv,- ...extraCaEnv,- HOST: "127.0.0.1",- ...(port !== undefined ? { PORT: String(port) } : {}),- ...(vercelUrl ? { VERCEL_URL: vercelUrl } : {})- },- reject: false,- stdin: "ignore",- detached: true- }- );+ const { file, args } = buildCommand({ id, port });+ const child = execa(file, args, {+ cwd: join(root, "apps", id),+ env: {+ ...appEnv,+ ...extraCaEnv,+ HOST: "127.0.0.1",+ ...(port !== undefined ? { PORT: String(port) } : {}),+ ...(vercelUrl ? { VERCEL_URL: vercelUrl } : {})+ },+ reject: false,+ stdin: "ignore",+ detached: true+ });const prefix = color(pc.bold(`${id.padEnd(3)} | `));+ const disposers: Array<() => void> = [];const pipe = (stream: NodeJS.ReadableStream | null,sink: NodeJS.WriteStream) => {if (!stream) return;- readLines(stream, (line) => {- // Mute shutdown noise (EPIPE, ELIFECYCLE 143, esbuild "stopped").- if (shuttingDown || isNoiseLine(line)) return;- sink.write(`${prefix}${line}\n`);- });+ disposers.push(+ readLines(stream, (line) => {+ // Mute shutdown noise (EPIPE, ELIFECYCLE 143, esbuild "stopped").+ if (shuttingDown || isNoiseLine(line)) return;+ sink.write(`${prefix}${line}\n`);+ })+ );};pipe(child.stdout, process.stdout);pipe(child.stderr, process.stderr);+ // Close the readline interfaces when this child exits so a restarting+ // (crash-looping) app doesn't leak one per respawn.+ child.once("exit", () => {+ for (const dispose of disposers) dispose();+ });return child;- });+ };let killTimer: NodeJS.Timeout | undefined;const shutdown = (signal: "SIGTERM" | "SIGKILL") => {- for (const c of children) {- if (c.exitCode !== null || !c.pid) continue;+ for (const c of current) {+ if (!c || c.exitCode !== null || !c.pid) continue;try {process.kill(-c.pid, signal);} catch {@@ -150,22 +176,70 @@ export function spawnApps(opts: {};const detach = onShutdown(onSignal);+ opts.signal?.addEventListener("abort", onSignal, { once: true });++ // Auto-recover a dev server that dies (a bad rebuild after `git pull`, OOM, a+ // boot-time crash). Restart it in place with backoff so the surviving apps+ // keep their state. A genuinely broken tree would crash-loop, so cap it: more+ // than MAX_RESTARTS within RESTART_WINDOW_MS means give up and tear the stack+ // down for a clean `crbn up` rerun, rather than respawning forever.+ const MAX_RESTARTS = 3;+ const RESTART_WINDOW_MS = 10_000;- return Promise.all(children)+ const supervise = (id: string, slot: number): Promise<void> =>+ new Promise<void>((resolve) => {+ const crashes: number[] = [];+ const launch = () => {+ if (shuttingDown) return resolve();+ const child = spawnOne(id);+ current[slot] = child;+ child.on("exit", (code, signal) => {+ if (shuttingDown) return resolve();+ const reason = signal ? signal : `code ${code}`;+ const now = Date.now();+ crashes.push(now);+ let oldest = crashes[0];+ while (oldest !== undefined && now - oldest > RESTART_WINDOW_MS) {+ crashes.shift();+ oldest = crashes[0];+ }+ if (crashes.length > MAX_RESTARTS) {+ process.stderr.write(+ `\n${id} dev server crashed ${crashes.length}× in ${RESTART_WINDOW_MS / 1_000}s (${reason}); giving up. Fix it and rerun \`crbn up\`.\n`+ );+ resolve();+ onSignal();+ return;+ }+ const delay = Math.min(500 * 2 ** (crashes.length - 1), 4_000);+ process.stderr.write(+ `\n${id} dev server exited (${reason}); restarting in ${delay}ms…\n`+ );+ setTimeout(launch, delay);+ });+ };+ launch();+ });++ return Promise.all(apps.map((id, i) => supervise(id, i))).then(() => undefined)- .catch(() => undefined).finally(() => {if (killTimer) clearTimeout(killTimer);detach();});}-export function spawnStripeListener(root: string) {- execa("pnpm", ["run", "dev:stripe"], {+// Detached + reject:false so the caller owns the lifecycle: kill the whole+// process group on teardown (apps mode) or `unref()` it to outlive crbn+// (services-only mode). Previously fire-and-forget `.unref()`, which orphaned+// the listener across `crbn down`.+export function spawnStripeListener(root: string): ExecaChildProcess {+ return execa("pnpm", ["run", "dev:stripe"], {cwd: root,detached: true,- stdio: "ignore"- }).unref();+ stdio: "ignore",+ reject: false+ });}// Skip when node_modules/.modules.yaml is newer than pnpm-lock.yaml (pnpm'sdiff --git a/packages/dev/src/services/compose.ts b/packages/dev/src/services/compose.tsindex d8503568ca..6234aa24f7 100644--- a/packages/dev/src/services/compose.ts+++ b/packages/dev/src/services/compose.ts@@ -20,9 +20,20 @@ function composeFile(root: string): string {// Shared redis runs as a single plain container (not a compose stack) — one per// host, reused across worktrees via per-worktree logical DB indexes.-const REDIS_CONTAINER = "carbon-redis";+export const REDIS_CONTAINER = "carbon-redis";const REDIS_VOLUME = "carbon-redis-data";+// Fail fast with an actionable message when the Docker daemon is unreachable,+// instead of a cryptic `Cannot connect to the Docker daemon` deep in the boot.+export async function ensureDockerRunning() {+ const r = await execa("docker", ["info"], { reject: false, stdio: "ignore" });+ if (r.exitCode !== 0) {+ throw new Error(+ "Docker isn't running. Start Docker Desktop (or your docker daemon) and re-run `crbn up`."+ );+ }+}+type Publisher = { PublishedPort: number; TargetPort: number };// Normalized shape. `parseContainer` ensures Health is always string|null anddiff --git a/packages/dev/src/services/portless.ts b/packages/dev/src/services/portless.tsindex ccb82f4afe..1de6845911 100644--- a/packages/dev/src/services/portless.ts+++ b/packages/dev/src/services/portless.ts@@ -314,6 +314,11 @@ export async function waitForProxyReady(timeoutMs = 30_000) {}await sleep(500);}+ // Don't return silently — the caller would report "proxy listening" for a+ // proxy that never came up, then apps fail with NXDOMAIN.+ throw new Error(+ `portless proxy did not start within ${timeoutMs / 1_000}s. Check \`portless proxy start\` manually, or run \`crbn up --no-portless\` for localhost URLs.`+ );}export async function registerAliases(@@ -322,7 +327,7 @@ export async function registerAliases(ports: PortMap) {const aliases = aliasMap(branchPrefix, ports);- await Promise.all(+ const results = await Promise.all(aliases.map((a) =>execa("portless", ["alias", a.name, String(a.port), "--force"], {cwd: root,@@ -334,12 +339,20 @@ export async function registerAliases(})));- return aliases.length;+ // reject:false means failures don't throw — count actual successes so the+ // caller doesn't report "7 registered" when portless is wedged and 0 took.+ const registered = results.filter((r) => r.exitCode === 0).length;+ return { registered, total: aliases.length };}export async function unregisterAliases(root: string, branchPrefix: string) {// Use a dummy PortMap — only the names matter for removal, not ports.- const names = aliasMap(branchPrefix, {} as PortMap).map((a) => a.name);+ // Keep the shared STABLE_OAUTH_ALIAS ("api.carbon"): it's branch-independent+ // ("last `crbn up` wins") and shared across worktrees, so tearing down one+ // worktree must not remove it and break OAuth for the others still running.+ const names = aliasMap(branchPrefix, {} as PortMap)+ .map((a) => a.name)+ .filter((name) => name !== STABLE_OAUTH_ALIAS);await Promise.all(names.map((name) =>execa("portless", ["alias", "--remove", name], {diff --git a/packages/dev/src/worktree.test.ts b/packages/dev/src/worktree.test.tsindex e87b4bf7a1..3d627470c5 100644--- a/packages/dev/src/worktree.test.ts+++ b/packages/dev/src/worktree.test.ts@@ -1,4 +1,4 @@-import { mkdtempSync, rmSync, symlinkSync } from "node:fs";+import { mkdtempSync, rmSync, symlinkSync, unlinkSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "pathe";import { afterAll, describe, expect, it } from "vitest";@@ -43,7 +43,9 @@ describe("sameWorktreePath", () => {symlinkSync(real, link);afterAll(() => {- rmSync(link, { force: true });+ // `link` is a symlink to a directory; unlink removes the link itself+ // (rmSync without `recursive` throws EISDIR on a dir symlink on macOS).+ unlinkSync(link);rmSync(real, { recursive: true, force: true });});diff --git a/packages/dev/src/worktree.ts b/packages/dev/src/worktree.tsindex 3b1b38322d..369808d632 100644--- a/packages/dev/src/worktree.ts+++ b/packages/dev/src/worktree.ts@@ -186,6 +186,20 @@ export function listSlugs(): Registry {return readRegistry();}+// Find the slug whose registry entry points at `worktreeRoot`. Uses canonical+// path comparison (resolves symlinks / trailing slashes) like `resolveSlot` —+// a raw `===` misses worktrees under symlinked parents (e.g. macOS /var, /tmp),+// so `crbn remove`/`list` wouldn't find the slug and would leak the stack/ports.+export function slugForWorktreePath(+ worktreeRoot: string,+ registry: Registry = readRegistry()+): string | null {+ for (const [slug, entry] of Object.entries(registry)) {+ if (sameWorktreePath(entry.worktreeRoot, worktreeRoot)) return slug;+ }+ return null;+}+export function removeSlot(slug: string) {const registry = readRegistry();if (!(slug in registry)) return;