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): improve resource management
Sidwebworks430aa77d69cc
diff --git a/packages/dev/bin/crbn b/packages/dev/bin/crbnindex c05b403b19..109b992655 100755--- a/packages/dev/bin/crbn+++ b/packages/dev/bin/crbn@@ -438,6 +438,7 @@ crbn — Carbon dev CLIStack: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.diff --git a/packages/dev/docker/docker-compose.dev.yml b/packages/dev/docker/docker-compose.dev.ymlindex 75b9a2ec9f..a4415b1c07 100644--- a/packages/dev/docker/docker-compose.dev.yml+++ b/packages/dev/docker/docker-compose.dev.yml@@ -9,6 +9,11 @@ services:postgres:image: supabase/postgres:15.14.1.112restart: unless-stopped+ deploy:+ resources:+ limits:+ memory: ${MEM_POSTGRES:-384m}+ cpus: ${CPU_POSTGRES:-1.0}networks:default:aliases:@@ -35,6 +40,26 @@ services:- config_file=/etc/postgresql/postgresql.conf- -c- log_min_messages=fatal+ - -c+ - shared_buffers=${PG_SHARED_BUFFERS:-128MB}+ - -c+ - effective_cache_size=${PG_EFFECTIVE_CACHE_SIZE:-256MB}+ - -c+ - work_mem=${PG_WORK_MEM:-4MB}+ - -c+ - maintenance_work_mem=${PG_MAINTENANCE_WORK_MEM:-64MB}+ - -c+ - max_connections=${PG_MAX_CONNECTIONS:-25}+ - -c+ - fsync=off+ - -c+ - synchronous_commit=off+ - -c+ - full_page_writes=off+ - -c+ - max_wal_size=256MB+ - -c+ - jit=offhealthcheck:test: ["CMD", "pg_isready", "-U", "postgres", "-h", "localhost"]interval: 5s@@ -44,6 +69,11 @@ services:gotrue:image: supabase/gotrue:v2.189.0restart: unless-stopped+ deploy:+ resources:+ limits:+ memory: ${MEM_GOTRUE:-48m}+ cpus: ${CPU_GOTRUE:-0.25}environment:GOTRUE_API_HOST: 0.0.0.0GOTRUE_API_PORT: 9999@@ -90,6 +120,11 @@ services:postgrest:image: postgrest/postgrest:v13.0.8restart: unless-stopped+ deploy:+ resources:+ limits:+ memory: ${MEM_POSTGREST:-160m}+ cpus: ${CPU_POSTGREST:-0.25}depends_on:postgres:condition: service_healthy@@ -105,6 +140,11 @@ services:realtime:image: supabase/realtime:v2.89.0restart: unless-stopped+ deploy:+ resources:+ limits:+ memory: ${MEM_REALTIME:-256m}+ cpus: ${CPU_REALTIME:-0.25}depends_on:postgres:condition: service_healthy@@ -135,6 +175,11 @@ services:storage:image: supabase/storage-api:v1.58.4restart: unless-stopped+ deploy:+ resources:+ limits:+ memory: ${MEM_STORAGE:-192m}+ cpus: ${CPU_STORAGE:-0.25}depends_on:postgres:condition: service_healthy@@ -157,6 +202,11 @@ services:meta:image: supabase/postgres-meta:v0.96.5restart: unless-stopped+ deploy:+ resources:+ limits:+ memory: ${MEM_META:-96m}+ cpus: ${CPU_META:-0.25}profiles: ["full"]depends_on:postgres:@@ -172,6 +222,11 @@ services:studio:image: supabase/studio:2026.04.28-sha-89d08a2restart: unless-stopped+ deploy:+ resources:+ limits:+ memory: ${MEM_STUDIO:-256m}+ cpus: ${CPU_STUDIO:-0.25}profiles: ["full"]depends_on:meta:@@ -191,6 +246,11 @@ services:inbucket:image: inbucket/inbucket:3.1.1restart: unless-stopped+ deploy:+ resources:+ limits:+ memory: ${MEM_INBUCKET:-32m}+ cpus: ${CPU_INBUCKET:-0.25}profiles: ["full"]ports:- "${PORT_INBUCKET}:9000"@@ -198,6 +258,11 @@ services:edge-runtime:image: supabase/edge-runtime:v1.74.0restart: unless-stopped+ deploy:+ resources:+ limits:+ memory: ${MEM_EDGE:-512m}+ cpus: ${CPU_EDGE:-0.5}depends_on:postgres:condition: service_healthy@@ -229,13 +294,25 @@ services:kong:image: kong:2.8.1restart: unless-stopped+ deploy:+ resources:+ limits:+ memory: ${MEM_KONG:-192m}+ cpus: ${CPU_KONG:-0.5}depends_on:- - gotrue- - postgrest- - realtime- - storage- - meta- - edge-runtime+ gotrue:+ condition: service_started+ postgrest:+ condition: service_started+ realtime:+ condition: service_started+ storage:+ condition: service_started+ meta:+ condition: service_started+ required: false+ edge-runtime:+ condition: service_startedports:- "${PORT_API}:8000"environment:@@ -243,6 +320,7 @@ services:KONG_DECLARATIVE_CONFIG: /home/kong/kong.ymlKONG_DNS_ORDER: LAST,A,CNAMEKONG_PLUGINS: request-transformer,cors,key-auth,acl,basic-auth+ KONG_NGINX_WORKER_PROCESSES: ${KONG_WORKERS:-1}volumes:- ./packages/dev/docker/kong.yml:/home/kong/kong.yml:ro@@ -253,6 +331,11 @@ services:inngest:image: inngest/inngest:v1.19.4restart: unless-stopped+ deploy:+ resources:+ limits:+ memory: ${MEM_INNGEST:-128m}+ cpus: ${CPU_INNGEST:-0.25}ports:- "${PORT_INNGEST}:8288"command:diff --git a/packages/dev/src/commands/down.ts b/packages/dev/src/commands/down.tsindex 720626d55b..54b8e281b2 100644--- a/packages/dev/src/commands/down.ts+++ b/packages/dev/src/commands/down.ts@@ -2,10 +2,12 @@ import { intro, outro, tasks } from "@clack/prompts";import pc from "picocolors";import { syncAppPortlessConfigs } from "../env.js";import { currentBranch } from "../git.js";+import { killOrphanedApps, killOrphanedStripe } from "../services/apps.js";import { stopStack } from "../services/compose.js";import { branchToPrefix, unregisterAliases } from "../services/portless.js";import {ensureSlugAvailable,+ getSlot,getWorktreeRoot,projectName,resolveSlug@@ -34,11 +36,20 @@ export async function down(opts: { silent?: boolean; volumes?: boolean } = {}) {{title: `Stopping ${project} (${withVolumes ? "removing volumes" : "volumes preserved"})`,task: async (msg) => {- msg(withVolumes ? "docker compose down -v" : "docker compose stop");+ msg(withVolumes ? "docker compose down -v" : "docker compose down");await stopStack(root, slug, withVolumes);return withVolumes ? "stack stopped, volumes removed" : "stack stopped";}},+ {+ title: "Kill orphaned dev servers & stripe listener",+ task: async () => {+ const slot = getSlot(slug);+ if (slot) await killOrphanedApps(slot.ports);+ await killOrphanedStripe(root);+ return "orphaned processes killed";+ }+ },{title: "Unregister portless aliases",task: async () => {@@ -76,6 +87,12 @@ async function runPlain(await stopStack(root, slug, withVolumes);done(withVolumes ? "stack stopped, volumes removed" : "stack stopped");+ step("killing orphaned dev servers & stripe listener");+ const slot = getSlot(slug);+ if (slot) await killOrphanedApps(slot.ports);+ await killOrphanedStripe(root);+ done("orphaned processes killed");+step("unregistering portless aliases");const branch = await currentBranch(root);const branchPrefix = branchToPrefix(branch, slug);diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.tsindex 35b9f36b3e..fd1df2df9d 100644--- a/packages/dev/src/commands/up.ts+++ b/packages/dev/src/commands/up.ts@@ -2,7 +2,7 @@ import { box, intro, log, outro, progress, tasks } from "@clack/prompts";import { config as loadDotenv } from "dotenv";import { type ExecaChildProcess, execa } from "execa";import { join } from "pathe";-import type { AppId } from "../constants.js";+import { APP_CHOICES, type AppId } from "../constants.js";import { renderEnv, syncAppPortlessConfigs, writeEnv } from "../env.js";import { currentBranch } from "../git.js";import { onShutdown } from "../helpers.js";@@ -66,6 +66,8 @@ type UpOpts = {migrate?: boolean;regen?: boolean;apps?: boolean;+ /** When true, launch all apps without the interactive picker. */+ all?: boolean;/** When true, always `docker compose pull` even if images exist locally. */pull?: boolean;/** When true, show a picker to borrow another worktree's running containers. */@@ -149,7 +151,12 @@ export async function up(opts: UpOpts = {}) {log.info("portless disabled (CARBON_PORTLESS=0) — using localhost URLs");}- const selectedApps = appsRequested ? await pickApps() : [];+ const allApps = opts.all === true;+ const selectedApps = appsRequested+ ? allApps+ ? APP_CHOICES.map((c) => c.value)+ : await pickApps()+ : [];const slug = resolveSlug(root);// Resolve borrowed slot before ensureSlugAvailable (borrowing doesn't startdiff --git a/packages/dev/src/main.ts b/packages/dev/src/main.tsindex 6855ca2e62..9187c427a7 100644--- a/packages/dev/src/main.ts+++ b/packages/dev/src/main.ts@@ -35,6 +35,12 @@ const main = defineCommand({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,@@ -76,6 +82,7 @@ const main = defineCommand({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,diff --git a/packages/dev/src/services/apps.ts b/packages/dev/src/services/apps.tsindex 2da236d2e6..914f3d9297 100644--- a/packages/dev/src/services/apps.ts+++ b/packages/dev/src/services/apps.ts@@ -5,7 +5,7 @@ import { type ExecaChildProcess, execa } from "execa";import { join } from "pathe";import pc from "picocolors";import { isAtLeastAsNew, onShutdown, readLines } from "../helpers.js";-import type { PortMap } from "../worktree.js";+import { type PortMap, sameWorktreePath } from "../worktree.js";const APP_COLORS: Record<string, (s: string) => string> = {erp: pc.cyan,@@ -276,3 +276,66 @@ export async function syncEnvSymlinks(root: string) {throw new Error(`setup-env-files failed (exit ${r.exitCode})`);}}++// ---------------------------------------------------------------------------+// Orphan cleanup — used by `crbn down` to kill host processes that survived+// a crashed `crbn up`. Dev servers and the stripe listener are spawned+// `detached: true` so they outlive the parent; without this, orphaned+// processes hold the worktree's ports and block the next `crbn up`.+// ---------------------------------------------------------------------------++// Kill processes listening on PORT_ERP / PORT_MES. Port-based lookup is+// reliable since ports are unique per worktree (allocated in the slot+// registry). Best-effort — silently skips ports with nothing listening.+export async function killOrphanedApps(ports: PortMap): Promise<void> {+ const appPorts = [ports.PORT_ERP, ports.PORT_MES];+ for (const port of appPorts) {+ const r = await execa("lsof", ["-ti", `:${port}`], { reject: false });+ if (r.exitCode !== 0) continue;+ const pids = r.stdout+ .split("\n")+ .map((s) => Number(s.trim()))+ .filter((n) => n > 0);+ for (const pid of pids) {+ try {+ process.kill(pid, "SIGKILL");+ // biome-ignore lint/suspicious/noEmptyBlockStatements: best-effort kill+ } catch {}+ }+ }+}++// Kill the stripe listener (`tsx ./stripe.dev.ts`) whose cwd matches this+// worktree. Cloud-edition only — silently no-ops when nothing matches.+export async function killOrphanedStripe(root: string): Promise<void> {+ const r = await execa("pgrep", ["-f", "stripe.dev.ts"], { reject: false });+ if (r.exitCode !== 0) return;+ const pids = r.stdout+ .split("\n")+ .map((s) => s.trim())+ .filter(Boolean);+ for (const pidStr of pids) {+ const pid = Number(pidStr);+ if (!pid) continue;+ const cwd = await processCwd(pid);+ if (cwd && sameWorktreePath(cwd, root)) {+ try {+ process.kill(pid, "SIGKILL");+ // biome-ignore lint/suspicious/noEmptyBlockStatements: best-effort kill+ } catch {}+ }+ }+}++// Resolve a process's current working directory via lsof (macOS + Linux).+// Returns null if the process is gone or lsof isn't available.+async function processCwd(pid: number): Promise<string | null> {+ const r = await execa("lsof", ["-a", "-p", String(pid), "-d", "cwd", "-Fn"], {+ reject: false+ });+ if (r.exitCode !== 0) return null;+ for (const line of r.stdout.split("\n")) {+ if (line.startsWith("n")) return line.slice(1);+ }+ return null;+}diff --git a/packages/dev/src/services/compose.ts b/packages/dev/src/services/compose.tsindex 5c86f4c04b..8f2cbcee4b 100644--- a/packages/dev/src/services/compose.ts+++ b/packages/dev/src/services/compose.ts@@ -142,14 +142,29 @@ export async function allImagesPresentLocally(return results.every(Boolean);}+// Returns the compose `down` exit code (0 = success). On compose-parse+// failures (missing .env.local, profile issues, renamed compose file), falls+// back to raw `docker rm -f` via destroyProject so the stack is always torn+// down even when compose can't parse the project to find its containers.export async function stopStack(root: string,slug: string,withVolumes: boolean-) {- const args = devArgs(root, slug, "--env-file", ".env.local", "down");- if (withVolumes) args.push("-v", "--remove-orphans");- await execa("docker", args, { cwd: root, stdio: "ignore", reject: false });+): Promise<number> {+ const args = devArgs(+ root,+ slug,+ "--env-file",+ ".env.local",+ "down",+ "--remove-orphans"+ );+ if (withVolumes) args.push("-v");+ const r = await execa("docker", args, { cwd: root, reject: false });+ if (r.exitCode !== 0) {+ await destroyProject(projectName(slug), withVolumes);+ }+ return r.exitCode ?? 0;}// One redis per host, run directly via `docker run` (no compose file).@@ -355,8 +370,9 @@ export async function dockerProjectStates(): Promise<Map<string, string>> {// Destroy a compose project by force-removing its containers, volumes, and// networks using raw docker commands. Works even when the compose file or-// worktree directory no longer exists (orphaned projects).-export async function destroyProject(project: string) {+// worktree directory no longer exists (orphaned projects). When withVolumes is+// false (plain `crbn down`), preserves the project's data volumes.+export async function destroyProject(project: string, withVolumes = true) {// Find containers belonging to the project.const ctr = await execa("docker",@@ -380,39 +396,42 @@ export async function destroyProject(project: string) {});}- // Remove volumes prefixed with the project name.- const vol = await execa(+ // Remove networks prefixed with the project name (always — cheap, and stale+ // networks block the next `up` from reusing the project name cleanly).+ const net = await execa("docker",- ["volume", "ls", "-q", "--filter", `name=${project}_`],+ ["network", "ls", "-q", "--filter", `name=${project}_`],{reject: false});- const vols = (vol.stdout ?? "")+ const nets = (net.stdout ?? "").split("\n").map((s) => s.trim()).filter(Boolean);- if (vols.length > 0) {- await execa("docker", ["volume", "rm", "-f", ...vols], {+ if (nets.length > 0) {+ await execa("docker", ["network", "rm", ...nets], {reject: false,stdio: "ignore"});}- // Remove networks prefixed with the project name.- const net = await execa(+ if (!withVolumes) return;++ // Remove volumes prefixed with the project name.+ const vol = await execa("docker",- ["network", "ls", "-q", "--filter", `name=${project}_`],+ ["volume", "ls", "-q", "--filter", `name=${project}_`],{reject: false});- const nets = (net.stdout ?? "")+ const vols = (vol.stdout ?? "").split("\n").map((s) => s.trim()).filter(Boolean);- if (nets.length > 0) {- await execa("docker", ["network", "rm", ...nets], {+ if (vols.length > 0) {+ await execa("docker", ["volume", "rm", "-f", ...vols], {reject: false,stdio: "ignore"});