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
feat(dev): lighter default stack, crbn prune, and CLI robustness fixes (#1844)
Sid5351e9357908
diff --git a/.conductor/settings.toml b/.conductor/settings.tomlindex fd5f3fddcd..518be40e87 100644--- a/.conductor/settings.toml+++ b/.conductor/settings.toml@@ -27,7 +27,13 @@ run_mode = "concurrent"# flush redis, and release the port slot so the pool doesn't leak entries.archive = "./packages/dev/bin/crbn down --purge"+# ERP + MES only. The assembler is a separate script: it needs the one-time+# OCCT build and a cargo compile, which most workspaces never use.[scripts.run.dev]-command = "./packages/dev/bin/crbn up --all"+command = "CARBON_DEV_APPS=erp,mes ./packages/dev/bin/crbn up"default = trueicon = "rocket"++[scripts.run.dev-assembler]+command = "CARBON_DEV_APPS=erp,mes,assembler ./packages/dev/bin/crbn up"+icon = "box"diff --git a/apps/erp/app/modules/documents/documents.service.ts b/apps/erp/app/modules/documents/documents.service.tsindex 82676a1185..04bf92cc30 100644--- a/apps/erp/app/modules/documents/documents.service.ts+++ b/apps/erp/app/modules/documents/documents.service.ts@@ -3,7 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import type { Database } from "@carbon/database";-import { storage } from "@carbon/files";+import { imageTransformErrorMessage, storage } from "@carbon/files";import { isHeic } from "@carbon/files/media";import { trigger } from "@carbon/jobs";import type { SupabaseClient } from "@supabase/supabase-js";@@ -300,7 +300,10 @@ export async function insertUploadedDocument(return {data: null,error: new Error(- "Failed to convert the staged image — is image transformation enabled on this stack? The staged upload was left in place; re-register to retry."+ imageTransformErrorMessage(+ converted.error,+ "Failed to convert the staged image — is image transformation enabled on this stack? The staged upload was left in place; re-register to retry."+ ))};}diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.tsindex 40cfec7f71..7a942e331e 100644--- a/apps/erp/app/modules/shared/shared.service.ts+++ b/apps/erp/app/modules/shared/shared.service.ts@@ -4,7 +4,13 @@import type { Database, Tables } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";-import { getContentType, getFileExtension, storage } from "@carbon/files";+import {+ getContentType,+ getFileExtension,+ imageTransformErrorMessage,+ storage+} from "@carbon/files";+import { getLogger } from "@carbon/logger";import { type ServerFnInput, serverFns } from "@carbon/server-functions";import type {PostgrestResponse,@@ -16,6 +22,8 @@ import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";import type { PriceBreak, SupplierPriceMap } from "./shared.models";import type { ItemModelUpload } from "./types";+const logger = getLogger("erp", "shared");+export async function deleteNote(client: SupabaseClient<Database>,noteId: string@@ -73,10 +81,16 @@ export async function getBase64ImageFromSupabase(return null;}- const { data } = await storage(client)+ const { data, error } = await storage(client).company(companyId).download(path, heic ? { transform: { quality: 90 } } : undefined);if (!data) {+ if (heic) {+ logger.error(+ imageTransformErrorMessage(error, "Failed to transform HEIC file"),+ { path, error }+ );+ }return null;}diff --git a/apps/erp/app/routes/file+/preview+/$bucket.$.tsx b/apps/erp/app/routes/file+/preview+/$bucket.$.tsxindex 2b6866a812..a6fd0c8aef 100644--- a/apps/erp/app/routes/file+/preview+/$bucket.$.tsx+++ b/apps/erp/app/routes/file+/preview+/$bucket.$.tsx@@ -10,6 +10,7 @@ import {fileResponseHeaders,getCompanyPrivateBucket,getContentType,+ imageTransformErrorMessage,isStorageNotFound,isUnsafeStoragePath,LEGACY_PRIVATE_BUCKET,@@ -107,9 +108,15 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {contentType = transformed.data.type || "image/jpeg";return transformed;}- // No imgproxy (stale self-host stack) — fall through to the raw bytes;- // Safari can still render them.- logger.error(transformed.error);+ // No imgproxy (off by default locally, or a stale self-host stack) —+ // fall through to the raw bytes; Safari can still render them.+ logger.error(+ imageTransformErrorMessage(+ transformed.error,+ "Failed to transform HEIC file"+ ),+ { path, error: transformed.error }+ );}// Use the original encoded path for the storage API callreturn source.download(path);diff --git a/apps/mes/app/routes/file+/preview+/$bucket.$.tsx b/apps/mes/app/routes/file+/preview+/$bucket.$.tsxindex bc32cba79b..4d28d8bbf6 100644--- a/apps/mes/app/routes/file+/preview+/$bucket.$.tsx+++ b/apps/mes/app/routes/file+/preview+/$bucket.$.tsx@@ -10,6 +10,7 @@ import {fileResponseHeaders,getCompanyPrivateBucket,getContentType,+ imageTransformErrorMessage,isStorageNotFound,isUnsafeStoragePath,LEGACY_PRIVATE_BUCKET,@@ -115,9 +116,15 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {contentType = transformed.data.type || "image/jpeg";return transformed;}- // No imgproxy (stale self-host stack) — fall through to the raw bytes;- // Safari can still render them.- log.error("Failed to transform HEIC file", { error: transformed.error });+ // No imgproxy (off by default locally, or a stale self-host stack) —+ // fall through to the raw bytes; Safari can still render them.+ log.error(+ imageTransformErrorMessage(+ transformed.error,+ "Failed to transform HEIC file"+ ),+ { path, error: transformed.error }+ );}// Use the original encoded path for the storage API callreturn source.download(path);diff --git a/packages/dev/AGENTS.md b/packages/dev/AGENTS.mdindex a4dc12fe6c..109be0f43d 100644--- a/packages/dev/AGENTS.md+++ b/packages/dev/AGENTS.md@@ -26,18 +26,29 @@ Developer CLI (`crbn` command) — worktree management, Docker Compose stacks, m```bashpnpm --filter @carbon/dev test # vitestpnpm --filter @carbon/dev typecheck # tsgo --noEmit+pnpm --filter @carbon/dev smoke # real containers: slots, fresh migrate, up, status, purge (~40 s, needs Docker; run from a worktree with no stack)```## Key Patterns-- **Commands**: `up`, `down` (`--purge` releases the slot), `new`, `init`, `remove`, `list`, `status`, `reset`, `migrate`, `restore`, `copy` (env sync), `reload` (`crbn reload <service...>` → `docker compose up -d --force-recreate` a subset, applying compose/`.env.local` edits without restarting the app dev servers)-- **Restore** (`commands/restore.ts`): `crbn restore <file>` wraps `scripts/restore-database.sh` (the SQL is deliberately NOT ported) and adds worktree/`PORT_DB` resolution, a confirmation gate, and the trailing `applyMigrations` + `db:types`. The script truncates the local `supabase_migrations` ledger before restoring so the dump's own ledger lands — the ledger must travel WITH the schema, else the dump's older schema pairs with the local newer ledger and the trailing migrate step silently no-ops (leaving weeks of migrations missing while the ledger claims them applied). It deliberately does NOT boot a postgres-only stack the way `crbn migrate` does — a restore rewrites `auth`/`storage`, whose schemas GoTrue and Storage build via their own migrations, so it requires a fully booted stack (`serviceSchemasReady` probes for GoTrue's `auth.users.email_confirmed_at` AND `storage.objects`/`storage.buckets` — the restore script's `to_regclass` guards mean a missing Storage schema would otherwise let the restore finish with no buckets seeded) and refuses otherwise — the backup carries the SOURCE schema, which is usually behind the branch. **`--scrub-emails` defaults ON here, inverting the script's opt-in default**, so a restore cannot drop real customer addresses into a local DB unless asked. By default the script truncates `storage.objects` (kept rows would point at files that live only in the source environment's backend, so downloads 404); pass `--keep-storage-objects` to retain them and the dump's buckets when you need realistic storage metadata, e.g. profiling storage RLS.-- **Stack boot** (`commands/up.ts`): Docker Compose → wait Postgres → migrations → regen types → spawn apps → portless aliases+- **Commands**: `up`, `down` (`--purge` releases the slot), `new`, `init`, `remove`, `prune` (destroys stacks whose worktree directory is gone or that have no slot — the cleanup for worktrees deleted without `crbn remove`; `--all` destroys every stack on the machine and keeps worktrees and live slots), `list`, `status`, `reset`, `migrate`, `restore`, `copy` (env sync), `reload` (`crbn reload <service...>` → `docker compose up -d --force-recreate` a subset, applying compose/`.env.local` edits without restarting the app dev servers)+- **Restore** (`commands/restore.ts`): `crbn restore <file>` wraps `scripts/restore-database.sh` (the SQL is deliberately NOT ported) and adds worktree/`PORT_DB` resolution, a confirmation gate, and the trailing `applyMigrations` + `db:types`. The script truncates the local `supabase_migrations` ledger before restoring so the dump's own ledger lands — the ledger must travel WITH the schema, else the dump's older schema pairs with the local newer ledger and the trailing migrate step silently no-ops (leaving weeks of migrations missing while the ledger claims them applied). It deliberately does NOT boot a partial stack the way `crbn migrate` does — a restore rewrites `auth`/`storage`, whose schemas GoTrue and Storage build via their own migrations, so it requires a fully booted stack (`serviceSchemasReady` probes for GoTrue's `auth.users.email_confirmed_at`, `storage.objects`/`storage.buckets` AND Realtime's `realtime.messages` — the restore script's `to_regclass` guards mean a missing Storage schema would otherwise let the restore finish with no buckets seeded) and refuses otherwise — the backup carries the SOURCE schema, which is usually behind the branch. **`--scrub-emails` defaults ON here, inverting the script's opt-in default**, so a restore cannot drop real customer addresses into a local DB unless asked. By default the script truncates `storage.objects` (kept rows would point at files that live only in the source environment's backend, so downloads 404); pass `--keep-storage-objects` to retain them and the dump's buckets when you need realistic storage metadata, e.g. profiling storage RLS.+- **Stack boot** (`commands/up.ts`): Docker Compose → wait Postgres → wait service schemas → migrations → regen types → spawn apps → portless aliases+- **Migrations need three services, not just Postgres**: they write into `storage.buckets`, GoTrue's `auth` columns and `realtime.messages`, which Storage, GoTrue and Realtime build on first boot. `waitForServiceSchemas` gates every migrate on a fresh volume; standalone `crbn migrate` boots `postgres` + `gotrue` + `storage` + `realtime` for the same reason. A from-zero migrate takes about 5 s once they are up, so there is nothing to gain from caching a migrated volume.+- **Stack size** (`StackSize` / `profileArgs` in `services/compose.ts`): `crbn up` starts the eight services the apps need (Inbucket included, for login emails). `--full` adds Studio, Postgres-Meta, the edge runtime and imgproxy (compose profile `full`). Nothing in the apps calls the first three, and they were ~40% of a stack's memory; imgproxy only converts HEIC and images the wasm pipeline refuses, and a transform attempted without it logs `imageTransformErrorMessage` (`@carbon/files`), which says to run `crbn reload imgproxy`. `--minimal` also drops Inbucket (profile `mail`). `crbn reload studio` starts Studio on a running stack. `generate:swagger` reads PostgREST through Kong with the anon key (byte-identical to what Studio served), so it works at every size.- **Provision** (`commands/init.ts`): `crbn init` provisions an already-created worktree (canonical slug + env sync + skills) to match a `crbn checkout`; shared by `new`, the bash `checkout` post-create hook, and Conductor's `setup` (`.conductor/settings.toml`). It does NOT boot the stack — `crbn up` still mints ports/`.env.local`.- **Worktree** (`worktree.ts`): `resolveSlug()`, `canonicalSlug()` (branch-derived `<repoBase>-<branch>`), `getWorktreeRoot()`, `projectName()`, `ensureSlugAvailable()`- **Services**: `compose.ts` (Docker), `migrations.ts` (Postgres/Supabase), `portless.ts` (`.dev` URLs), `apps.ts` (dev servers)- **Aux spawners** (`services/apps.ts`): `spawnAssembler` (cargo) and `spawnEmailPreview` (`@carbon/documents` `email:previews` on `PORT_EMAIL` — the react-email server over `src/email/previews`, one fixture per email) — opt-in picker apps with their own spawners, not react-router dev servers- **Vite helpers** (`vite.js`, exported as `@carbon/dev/vite`, typed by `vite.d.ts`): `applyDotenvToProcessEnv`, `clientOnlyAlias` (stub a module in the browser build only), `linguiWithoutIdQuery` (works around Lingui 6.9.0 parsing React Router's `?query`-suffixed route ids as plain JS)+- **Spinners come from `ui.ts`, not `@clack/prompts`**: `tasks`, `spinner` and `progress` there print one line per step when stdout is not a terminal (an agent, a pipe, a log file) instead of every animation frame. Importing them from clack directly brings the frame noise back.+- **No command allow-list in `bin/crbn`**: the bash router runs from the main checkout while the TypeScript CLI runs from the current worktree, so the router passes anything it doesn't own (`checkout`, help, version) straight through. Register a subcommand in `src/main.ts` only.+- **Prompts need a terminal — say so**: a clack prompt with no TTY ends the process without a word. Every prompt calls `requireTerminal(what, instead)` (`prompts.ts`) first, which throws a one-line error naming the non-interactive route: `CARBON_DEV_YES=1` for the confirms, `crbn remove <branch-or-path...>`, `crbn new --yes <branch>`.+- **`--json`** on `status` and `list` prints machine-readable output (ports, redis db, containers; never the JWT secret).+- **Read-only compose calls pass `--env-file`** (`envFileArgs`): compose interpolates the whole file before `ps`/`logs`, and it has values with no default, so without `.env.local` those calls fail and report an empty stack.+- **`restart: on-failure`** on every compose service: a crash restarts the container, a Docker daemon start does not. A stack only comes up through `crbn up`.+- **The slot registry is locked** (`lockRegistry` in `worktree.ts`): every change to `~/.carbon/dev-ports.json` is read → decide → write under a `mkdir` lock, written through a temp file + rename. Conductor boots workspaces concurrently; without the lock eight simultaneous `crbn up` left one slot in the file. Any new writer must take the lock.+- **Compose reads throw** (`composeRead` in `services/compose.ts`): `listContainers` and `listComposeServices` raise compose's own error instead of returning an empty list, which used to pass for "no stack".- **Env**: `env.ts` — `renderEnv()`, `writeEnv()`, `syncAppPortlessConfigs()`- **`--run` flag**: scopes stack lifetime to a command (for headless/CI builds); `--volumes` cleans up Docker volumes on teardowndiff --git a/packages/dev/README.md b/packages/dev/README.mdindex 7217b4682c..327c043711 100644--- a/packages/dev/README.md+++ b/packages/dev/README.md@@ -20,8 +20,12 @@ source ./setup.sh # adds crbn to PATH + installs shell wrapper| `crbn checkout main` | cd into the main checkout (never creates a separate worktree). || `crbn new [branch]` | Interactive worktree creation. Optional branch name pre-fills the prompt. || `crbn list` | Show all worktrees with stack status. |+| `crbn list --json` | The same list as JSON, for scripts and agents. || `crbn remove` | Multi-select worktrees to delete (concurrent teardown with progress). |+| `crbn remove <branch-or-path...>` | Remove the named worktrees without the picker (`CARBON_DEV_YES=1` skips the confirmation). || `crbn remove --prune` | Also delete the git branch after removing each worktree. |+| `crbn prune` | Destroy stacks no worktree can reach: slots whose directory is gone, and stacks with no slot. Lists them and confirms first; volumes are wiped. |+| `crbn prune --all` | Destroy every crbn stack on the machine, running ones included. Worktrees, branches and live slots are kept; the next `crbn up` rebuilds the database. |### Stack@@ -32,12 +36,14 @@ source ./setup.sh # adds crbn to PATH + installs shell wrapper| `crbn up --no-portless` | Localhost mode: fixed ports (API `:54321`, ERP `:3000`, MES `:3001`). || `crbn up --borrow` | Reuse another worktree's running containers (DB, API, etc). || `crbn up --no-apps` | Services only (postgres, kong, supabase, inngest, mail). |+| `crbn up --full` | Also start Studio, Postgres-Meta, the edge runtime and imgproxy (HEIC conversion). They are off by default; `crbn reload studio` or `crbn reload imgproxy` starts one on a running stack. || `crbn up --no-migrate` | Skip database migrations. || `crbn up --no-regen` | Skip type/swagger regeneration. || `crbn up --pull` | Force `docker compose pull` even if images exist locally. || `crbn down` | Stop stack (volumes preserved). || `crbn reset` | Wipe volumes + flush redis db, then `up`. || `crbn status` | Port assignment + container health. |+| `crbn status --json` | The slot and containers as JSON, for scripts and agents. || `crbn migrate` | Apply DB migrations against the running stack. |`CARBON_DEV_APPS` skips the picker: `CARBON_DEV_APPS=erp,mes,email crbn up`.diff --git a/packages/dev/bin/crbn b/packages/dev/bin/crbnindex a234f7ade7..25693acf52 100755--- a/packages/dev/bin/crbn+++ b/packages/dev/bin/crbn@@ -436,8 +436,10 @@ crbn — Carbon dev CLIcrbn 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] Multi-select worktrees to delete.+ 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).Stack:crbn up Boot compose stack + apps.@@ -445,10 +447,12 @@ crbn — Carbon dev CLIcrbn 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 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).@@ -482,13 +486,11 @@ case "$cmd" incheckout)cmd_checkout "$@";;- copy|env|up|down|reset|status|migrate|restore|new|init|list|remove|reload|complete)- delegate_ts "$cmd" "$@"- ;;*)- echo "crbn: unknown command '$cmd'" >&2- echo >&2- print_help >&2- exit 2+ # 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" "$@";;esacdiff --git a/packages/dev/docker/docker-compose.dev.yml b/packages/dev/docker/docker-compose.dev.ymlindex 7c6f55ed28..e7bc32fe02 100644--- a/packages/dev/docker/docker-compose.dev.yml+++ b/packages/dev/docker/docker-compose.dev.yml@@ -5,10 +5,14 @@# SUPABASE_ANON_KEY, SUPABASE_SERVICE_ROLE_KEY, plus user secrets passed through.###+# `restart: on-failure` on every service: a crashed container comes back, but+# the stack does NOT restart with the Docker daemon. A stack is only useful+# with its `crbn up` running, and `unless-stopped` brought every stack whose+# terminal had died back to life on each Docker start.services:postgres:image: supabase/postgres:15.14.1.112- restart: unless-stopped+ restart: on-failuredeploy:resources:limits:@@ -73,7 +77,7 @@ services:gotrue:image: supabase/gotrue:v2.189.0- restart: unless-stopped+ restart: on-failuredeploy:resources:limits:@@ -129,7 +133,7 @@ services:postgrest:image: postgrest/postgrest:v13.0.8- restart: unless-stopped+ restart: on-failuredeploy:resources:limits:@@ -155,7 +159,7 @@ services:realtime:image: supabase/realtime:v2.89.0- restart: unless-stopped+ restart: on-failuredeploy:resources:limits:@@ -190,7 +194,7 @@ services:storage:image: supabase/storage-api:v1.58.4- restart: unless-stopped+ restart: on-failuredeploy:resources:limits:@@ -231,7 +235,8 @@ services:# storage volume with no RLS.imgproxy:image: darthsim/imgproxy:v3.8.0- restart: unless-stopped+ restart: on-failure+ profiles: ["full"]deploy:resources:limits:@@ -253,7 +258,7 @@ services:meta:image: supabase/postgres-meta:v0.96.5- restart: unless-stopped+ restart: on-failuredeploy:resources:limits:@@ -273,7 +278,7 @@ services:studio:image: supabase/studio:2026.04.28-sha-89d08a2- restart: unless-stopped+ restart: on-failuredeploy:resources:limits:@@ -302,19 +307,26 @@ services:inbucket:image: inbucket/inbucket:3.1.1- restart: unless-stopped+ restart: on-failuredeploy:resources:limits:memory: ${MEM_INBUCKET:-64m}cpus: ${CPU_INBUCKET:-0.25}- profiles: ["full"]+ profiles: ["mail"]ports:- "${PORT_INBUCKET}:9000"+ # The image declares /config and /storage as volumes; left unmounted, each+ # `down` strands two anonymous volumes. /config is empty in the image.+ tmpfs:+ - /config+ volumes:+ - inbucket:/storageedge-runtime:image: supabase/edge-runtime:v1.74.0- restart: unless-stopped+ restart: on-failure+ profiles: ["full"]deploy:resources:limits:@@ -345,7 +357,7 @@ services:kong:image: kong:2.8.1- restart: unless-stopped+ restart: on-failuredeploy:resources:limits:@@ -365,6 +377,7 @@ services:required: falseedge-runtime:condition: service_started+ required: falseports:- "${PORT_API}:8000"environment:@@ -387,7 +400,7 @@ services:inngest:image: inngest/inngest:v1.19.4- restart: unless-stopped+ restart: on-failuredeploy:resources:limits:@@ -413,3 +426,4 @@ volumes:pgconfig:storage:inngest:+ inbucket:diff --git a/packages/dev/package.json b/packages/dev/package.jsonindex 8f5d99bbc1..9ac3b29cb6 100644--- a/packages/dev/package.json+++ b/packages/dev/package.json@@ -10,6 +10,7 @@"./vite": "./vite.js"},"scripts": {+ "smoke": "bash scripts/smoke.sh","clean": "rimraf node_modules .turbo","lint": "biome lint --write","test": "vitest run",diff --git a/packages/dev/scripts/smoke.sh b/packages/dev/scripts/smoke.shnew file mode 100755index 0000000000..62790cfdea--- /dev/null+++ b/packages/dev/scripts/smoke.sh@@ -0,0 +1,71 @@+#!/usr/bin/env bash+# Checks the unit tests cannot make: they need real containers and real+# processes. Run it from a worktree that has NO stack — it builds one from an+# empty volume and destroys it again. Needs Docker; takes under a minute.+#+# pnpm --filter @carbon/dev smoke+set -euo pipefail++root="$(git rev-parse --show-toplevel)"+cd "$root"+crbn="$root/packages/dev/bin/crbn"+tsx="$root/node_modules/.bin/tsx"+export CARBON_DEV_YES=1++ok() { printf '✓ %s\n' "$*"; }+fail() { printf '✗ %s\n' "$*" >&2; exit 1; }+json() { node -e "const d=JSON.parse(require('fs').readFileSync(0,'utf8')); $1"; }++# --- 1. Slot registry under concurrent boots (no Docker) ---------------------+# A scratch HOME keeps the real registry out of it.+scratch="$(mktemp -d)"+booted=0+cleanup() {+ rm -rf "$scratch"+ if [[ "$booted" == 1 ]]; then "$crbn" down --purge >/dev/null 2>&1 || true; fi+}+trap cleanup EXIT++for i in 1 2 3 4 5 6 7 8; do+ mkdir -p "$scratch/wt-$i"+ HOME="$scratch" "$tsx" -e "import('$root/packages/dev/src/worktree.ts').then((m) => m.resolveSlot('smoke-$i', '$scratch/wt-$i'))" &+done+wait+json "+ const slots = Object.values(d);+ const ports = slots.flatMap((s) => Object.values(s.ports));+ const dbs = slots.map((s) => s.redisDb);+ if (slots.length !== 8) throw new Error('expected 8 slots, got ' + slots.length);+ if (new Set(ports).size !== ports.length) throw new Error('two slots share a port');+ if (new Set(dbs).size !== dbs.length) throw new Error('two slots share a redis db');+" <"$scratch/.carbon/dev-ports.json" || fail "concurrent slot allocation collided"+ok "8 concurrent boots got 8 slots with no shared port or redis db"++# --- 2. A stack from an empty volume ----------------------------------------+project="$("$crbn" status --json | json "console.log(d.project)")"+if docker volume ls -q | grep -qx "${project}_pgdata"; then+ fail "$project already has a database volume — this would wipe it. Run from a worktree with no stack."+fi+booted=1++# Standalone migrate on a volume nothing has ever booted: it must start the+# services whose schemas the migrations write into, not Postgres alone.+"$crbn" migrate --no-regen >/dev/null || fail "crbn migrate failed on a fresh volume"+ok "crbn migrate applied every migration to a fresh volume"++"$crbn" up --no-apps --no-portless --no-regen >/dev/null || fail "crbn up failed"+"$crbn" status --json | json "+ const down = d.containers.filter((c) => c.State !== 'running').map((c) => c.Service);+ const names = d.containers.map((c) => c.Service);+ for (const s of ['postgres', 'kong', 'gotrue', 'storage', 'realtime', 'postgrest', 'inngest'])+ if (!names.includes(s)) throw new Error('status does not list ' + s);+ if (down.length) throw new Error('not running: ' + down.join(', '));+" || fail "crbn status does not show a healthy stack"+ok "crbn up booted the stack and crbn status sees every service running"++"$crbn" down --purge >/dev/null || fail "crbn down --purge failed"+booted=0+left="$(docker ps -aq --filter "label=com.docker.compose.project=$project" | wc -l | tr -d ' ')"+vols="$(docker volume ls -q --filter "label=com.docker.compose.project=$project" | wc -l | tr -d ' ')"+[[ "$left" == 0 && "$vols" == 0 ]] || fail "purge left $left container(s) and $vols volume(s)"+ok "crbn down --purge left no containers or volumes"diff --git a/packages/dev/src/commands/down.ts b/packages/dev/src/commands/down.tsindex acf291fbc9..a2be68ccfa 100644--- a/packages/dev/src/commands/down.ts+++ b/packages/dev/src/commands/down.ts@@ -2,13 +2,14 @@// 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 { intro, log, outro, tasks } from "@clack/prompts";+import { intro, log, outro } 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 { flushDb, stopStack } from "../services/compose.js";import { branchToPrefix, unregisterAliases } from "../services/portless.js";+import { tasks } from "../ui.js";import {getSlot,getWorktreeRoot,diff --git a/packages/dev/src/commands/list.ts b/packages/dev/src/commands/list.tsindex 8df0bb8500..822d359b27 100644--- a/packages/dev/src/commands/list.ts+++ b/packages/dev/src/commands/list.ts@@ -9,8 +9,8 @@ import { dockerProjectStates } from "../services/compose.js";import { worktreesTable } from "../ui.js";import { listSlugs, projectName, slugForWorktreePath } from "../worktree.js";-export async function listWorktrees() {- intro("Carbon · worktrees");+export async function listWorktrees(opts: { json?: boolean } = {}) {+ if (!opts.json) intro("Carbon · worktrees");const [wtsAll, registry, dockerStates] = await Promise.all([gitListWorktrees(),@@ -33,6 +33,11 @@ export async function listWorktrees() {};});+ if (opts.json) {+ process.stdout.write(`${JSON.stringify(rows, null, 2)}\n`);+ return;+ }+log.message("\n" + worktreesTable(rows), {symbol: pc.bold(pc.yellow("worktrees"))});diff --git a/packages/dev/src/commands/migrate.ts b/packages/dev/src/commands/migrate.tsindex 5146f8569b..397e867250 100644--- a/packages/dev/src/commands/migrate.ts+++ b/packages/dev/src/commands/migrate.ts@@ -3,7 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { existsSync } from "node:fs";-import { intro, log, outro, tasks } from "@clack/prompts";+import { intro, log, outro } from "@clack/prompts";import { config as loadDotenv } from "dotenv";import { execa } from "execa";import { join } from "pathe";@@ -19,9 +19,11 @@ import {applyMigrations,ensureConfigRow,syncAuthz,- waitForPostgres+ waitForPostgres,+ waitForServiceSchemas} from "../services/migrations.js";import { branchToPrefix } from "../services/portless.js";+import { tasks } from "../ui.js";import {ensureSlugAvailable,getWorktreeRoot,@@ -31,10 +33,13 @@ import {resolveSlug} from "../worktree.js";+const MIGRATION_SERVICES = ["postgres", "gotrue", "storage", "realtime"];+// Run database migrations against the worktree's local stack. If postgres is// already running (full stack up), migrate against it directly. If not, boot-// just postgres, apply migrations + regenerate types, then tear down — no need-// for the full 11-service compose stack to run migrations.+// postgres plus the three services whose schemas the migrations write into,+// apply migrations + regenerate types, then tear down — no need for the full+// compose stack to run migrations.export async function migrate(opts: { regen?: boolean } = {}) {const shouldRegen = opts.regen ?? true;intro("Carbon · dev migrate");@@ -61,7 +66,7 @@ export async function migrate(opts: { regen?: boolean } = {}) {return migrateAgainstRunningDb(root, portDb, shouldRegen);}- // Standalone mode: boot just postgres, migrate, tear down.+ // Standalone mode: boot the migration services, migrate, tear down.return migrateStandalone(root, slug, shouldRegen);}@@ -123,7 +128,7 @@ async function migrateAgainstRunningDb(outro("done");}-// ─── Standalone path (postgres-only) ──────────────────────────────────────+// ─── Standalone path (migration services only) ────────────────────────────async function migrateStandalone(root: string,@@ -152,7 +157,7 @@ async function migrateStandalone(const portDb = requireNumberEnv("PORT_DB");const project = projectName(slug);- log.info(`booting postgres-only stack (${project})`);+ log.info(`booting migration services (${project})`);await ensureDockerRunning();// Tear down on Ctrl+C so the standalone postgres doesn't orphan.@@ -160,13 +165,14 @@ async function migrateStandalone(const detach = onShutdown(() => {if (interrupted) return;interrupted = true;- process.stderr.write("\ninterrupted — stopping postgres…\n");+ process.stderr.write("\ninterrupted — stopping services…\n");void stopStack(root, slug, false).finally(() => process.exit(130));});try {- await bootStack(root, slug, { services: ["postgres"] });+ await bootStack(root, slug, { services: MIGRATION_SERVICES });await waitForPostgres(portDb);+ await waitForServiceSchemas(portDb);await tasks([{@@ -208,12 +214,12 @@ async function migrateStandalone(if (shouldRegen) {log.warn(- "swagger skipped — requires Studio (run `crbn up` for full regen)"+ "swagger skipped — requires the API (run `crbn up` for full regen)");}} finally {detach();- log.info("stopping postgres-only stack");+ log.info("stopping migration services");await stopStack(root, slug, false);}diff --git a/packages/dev/src/commands/new.ts b/packages/dev/src/commands/new.tsindex 7f37b7eb2c..57b607e61c 100644--- a/packages/dev/src/commands/new.ts+++ b/packages/dev/src/commands/new.ts@@ -3,7 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { writeFileSync } from "node:fs";-import { intro, outro, tasks } from "@clack/prompts";+import { intro, outro } from "@clack/prompts";import { basename, dirname, relative, resolve } from "pathe";import pc from "picocolors";import { addWorktree, currentBranch } from "../git.js";@@ -11,8 +11,10 @@ import {promptBaseRef,promptBranch,promptCopyEnv,- promptDirName+ promptDirName,+ requireTerminal} from "../prompts.js";+import { tasks } from "../ui.js";import { getWorktreeRoot, slugify } from "../worktree.js";import { initWorktree } from "./init.js";@@ -32,6 +34,12 @@ export async function newWorktree(opts?: {// Non-interactive (`--yes`): skip every prompt, use flags/defaults.// Base defaults to origin/main so loops always branch off latest main.const nonInteractive = opts?.yes === true;+ if (!nonInteractive) {+ requireTerminal(+ "crbn new",+ "Pass --yes with a branch name to run without one."+ );+ }const branch = nonInteractive? opts?.branchdiff --git a/packages/dev/src/commands/prune.test.ts b/packages/dev/src/commands/prune.test.tsnew file mode 100644index 0000000000..6d91974766--- /dev/null+++ b/packages/dev/src/commands/prune.test.ts@@ -0,0 +1,45 @@+// 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 { describe, expect, it } from "vitest";+import { planPrune } from "./prune.js";++const slots = {+ live: { worktreeRoot: "/work/live" },+ gone: { worktreeRoot: "/work/gone" }+};+const exists = (path: string) => path === "/work/live";++describe("planPrune", () => {+ it("prunes a slot whose directory is gone, even with no stack left", () => {+ expect(planPrune(slots, [], { exists })).toEqual({+ deadSlugs: ["gone"],+ projects: ["carbon-gone"]+ });+ });++ it("prunes a stack with no slot and keeps a live one", () => {+ const stacks = ["carbon-live", "carbon-gone", "carbon-stray"];+ expect(planPrune(slots, stacks, { exists }).projects).toEqual([+ "carbon-gone",+ "carbon-stray"+ ]);+ });++ it("takes live stacks too with all, but only releases dead slots", () => {+ expect(planPrune(slots, ["carbon-live"], { exists, all: true })).toEqual({+ deadSlugs: ["gone"],+ projects: ["carbon-gone", "carbon-live"]+ });+ });++ it("finds nothing when every stack has a live slot", () => {+ expect(+ planPrune({ live: slots.live }, ["carbon-live"], { exists })+ ).toEqual({+ deadSlugs: [],+ projects: []+ });+ });+});diff --git a/packages/dev/src/commands/prune.ts b/packages/dev/src/commands/prune.tsnew file mode 100644index 0000000000..8e05b96202--- /dev/null+++ b/packages/dev/src/commands/prune.ts@@ -0,0 +1,91 @@+// 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, intro, log, outro } from "@clack/prompts";+import pc from "picocolors";+import { confirmPrune } from "../prompts.js";+import {+ destroyProject,+ ensureDockerRunning,+ flushDb,+ listCarbonStacks+} from "../services/compose.js";+import { pruneStaleRoutes } from "../services/portless.js";+import { listSlugs, projectName, removeSlot } from "../worktree.js";++type Slots = Record<string, { worktreeRoot: string }>;++// A stack is prunable when nothing can reach it any more: its slot points at a+// directory that is gone (worktree deleted without `crbn remove`), or it has no+// slot at all. Slots are compared by directory, not `git worktree list` — the+// registry is machine-wide and holds other clones too. `all` takes every stack+// instead; live worktrees keep their slot and rebuild on the next `crbn up`.+export function planPrune(+ slots: Slots,+ stackProjects: string[],+ opts: { all?: boolean; exists?: (path: string) => boolean } = {}+): { deadSlugs: string[]; projects: string[] } {+ const exists = opts.exists ?? existsSync;+ const deadSlugs = Object.keys(slots).filter(+ (slug) => !exists(slots[slug]!.worktreeRoot)+ );+ const dead = new Set(deadSlugs);+ const live = new Set(+ Object.keys(slots)+ .filter((slug) => !dead.has(slug))+ .map(projectName)+ );+ const projects = new Set([+ ...deadSlugs.map(projectName),+ ...stackProjects.filter((p) => opts.all || !live.has(p))+ ]);+ return { deadSlugs, projects: [...projects].sort() };+}++export async function prune(opts: { all?: boolean } = {}) {+ intro(opts.all ? "Carbon · prune --all" : "Carbon · prune");+ await ensureDockerRunning();++ const slots = listSlugs();+ const { deadSlugs, projects } = planPrune(slots, await listCarbonStacks(), {+ all: opts.all+ });+ if (projects.length === 0) {+ outro("nothing to prune");+ return;+ }++ const dead = new Set(deadSlugs);+ const reasons = new Map(+ Object.keys(slots).map((slug) => [+ projectName(slug),+ dead.has(slug)+ ? `${slots[slug]!.worktreeRoot} is gone`+ : slots[slug]!.worktreeRoot+ ])+ );+ log.warn(+ projects+ .map((p) => `${pc.bold(p)} ${pc.dim(reasons.get(p) ?? "no slot")}`)+ .join("\n")+ );++ if (!(await confirmPrune(projects.length))) {+ cancel("prune aborted");+ process.exit(0);+ }++ await Promise.all(projects.map((p) => destroyProject(p)));+ for (const slug of Object.keys(slots)) {+ if (!dead.has(slug) && !opts.all) continue;+ await flushDb(slots[slug]!.redisDb);+ if (dead.has(slug)) removeSlot(slug);+ }+ await pruneStaleRoutes();++ outro(+ `removed ${projects.length} stack(s), released ${deadSlugs.length} slot(s)`+ );+}diff --git a/packages/dev/src/commands/reload.ts b/packages/dev/src/commands/reload.tsindex 603171eca6..4de99dffb4 100644--- a/packages/dev/src/commands/reload.ts+++ b/packages/dev/src/commands/reload.ts@@ -3,10 +3,11 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { join } from "node:path";-import { intro, log, outro, spinner } from "@clack/prompts";+import { intro, log, outro } from "@clack/prompts";import { config as loadDotenv } from "dotenv";import pc from "picocolors";import { recreateServices } from "../services/compose.js";+import { spinner } from "../ui.js";import { getWorktreeRoot, projectName, resolveSlug } from "../worktree.js";// `crbn reload <service...>` — recreate specific compose services so an edit todiff --git a/packages/dev/src/commands/remove.ts b/packages/dev/src/commands/remove.tsindex 17db3d7353..dbc3cb0094 100644--- a/packages/dev/src/commands/remove.ts+++ b/packages/dev/src/commands/remove.ts@@ -8,9 +8,9 @@ import {isCancel,log,multiselect,- outro,- spinner+ outro} from "@clack/prompts";+import { resolve } from "pathe";import pc from "picocolors";import {deleteBranch,@@ -19,7 +19,7 @@ import {mainCheckoutRoot,removeWorktree} from "../git.js";-import { confirmRemove } from "../prompts.js";+import { confirmRemove, requireTerminal } from "../prompts.js";import { killOrphanedApps, killOrphanedStripe } from "../services/apps.js";import { destroyProjectVolumes, flushDb } from "../services/compose.js";import {@@ -27,15 +27,21 @@ import {pruneStaleRoutes,unregisterAliases} from "../services/portless.js";+import { spinner } from "../ui.js";import {getSlot,listSlugs,projectName,removeSlot,+ sameWorktreePath,slugForWorktreePath} from "../worktree.js";-export async function removeWorktreeCmd(opts?: { prune?: boolean }) {+export async function removeWorktreeCmd(opts?: {+ prune?: boolean;+ /** Branch names or paths; skips the picker. */+ targets?: string[];+}) {const pruneBranches = opts?.prune === true;intro("Carbon · remove worktree");@@ -50,19 +56,38 @@ export async function removeWorktreeCmd(opts?: { prune?: boolean }) {return;}- 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(choices)) {- cancel("aborted");- process.exit(0);+ let selectedPaths: string[];+ if (opts?.targets?.length) {+ selectedPaths = opts.targets.map((name) => {+ const match = wts.find(+ (w) => w.branch === name || sameWorktreePath(w.path, resolve(name))+ );+ if (!match) {+ throw new Error(+ `No removable worktree for '${name}' (pass a branch name or a path; \`crbn list\` shows them)`+ );+ }+ return match.path;+ });+ } else {+ requireTerminal(+ "Picking worktrees to remove",+ "Name them instead: `crbn remove <branch-or-path...>`."+ );+ 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(choices)) {+ cancel("aborted");+ process.exit(0);+ }+ selectedPaths = choices as string[];}- const selectedPaths = choices as string[];const targets = selectedPaths.map((p) => wts.find((w) => w.path === p)!);const registry = listSlugs();diff --git a/packages/dev/src/commands/restore.ts b/packages/dev/src/commands/restore.tsindex 7d30210424..29f9a481ee 100644--- a/packages/dev/src/commands/restore.ts+++ b/packages/dev/src/commands/restore.ts@@ -3,7 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { existsSync } from "node:fs";-import { cancel, intro, log, outro, tasks } from "@clack/prompts";+import { cancel, intro, log, outro } from "@clack/prompts";import { config as loadDotenv } from "dotenv";import { execa } from "execa";import { isAbsolute, join, resolve } from "pathe";@@ -14,6 +14,7 @@ import {serviceSchemasReady,syncAuthz} from "../services/migrations.js";+import { tasks } from "../ui.js";import { getWorktreeRoot } from "../worktree.js";export type RestoreMode = "local" | "prod";diff --git a/packages/dev/src/commands/status.ts b/packages/dev/src/commands/status.tsindex 5e2ffe3b1d..7b1ce250a9 100644--- a/packages/dev/src/commands/status.ts+++ b/packages/dev/src/commands/status.ts@@ -13,11 +13,24 @@ import {resolveSlug} from "../worktree.js";-export async function status() {- intro("Carbon · dev status");+export async function status(opts: { json?: boolean } = {}) {const root = await getWorktreeRoot();const slug = resolveSlug(root);const slot = getSlot(slug);+ if (opts.json) {+ // Ports and containers only — the slot's JWT secret stays out of stdout.+ const out = {+ slug,+ project: projectName(slug),+ ports: slot?.ports ?? null,+ redisDb: slot?.redisDb ?? null,+ containers: slot ? await listContainers(root, slug) : []+ };+ process.stdout.write(`${JSON.stringify(out, null, 2)}\n`);+ return;+ }++ intro("Carbon · dev status");log.info(`worktree: ${pc.cyan(slug)} project: ${pc.cyan(projectName(slug))}`);diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.tsindex 001316e42e..c914ac21fb 100644--- a/packages/dev/src/commands/up.ts+++ b/packages/dev/src/commands/up.ts@@ -2,7 +2,7 @@// 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 { box, intro, log, outro, progress, tasks } from "@clack/prompts";+import { box, intro, log, outro } from "@clack/prompts";import { config as loadDotenv } from "dotenv";import { type ExecaChildProcess, execa } from "execa";import { join } from "pathe";@@ -35,6 +35,7 @@ import {listContainers,pullStack,restartServices,+ type StackSize,tailServiceLogs} from "../services/compose.js";import {@@ -44,6 +45,7 @@ import {ensureSmokeTestUser,syncAuthz,waitForPostgres,+ waitForServiceSchemas,waitForStorageReady,waitForTcp} from "../services/migrations.js";@@ -59,7 +61,7 @@ import {syncHostsFile,waitForProxyReady} from "../services/portless.js";-import { summaryLines } from "../ui.js";+import { progress, summaryLines, tasks } from "../ui.js";import {ensureSlugAvailable,getSlot,@@ -102,6 +104,8 @@ type UpOpts = {* hosts where the Supabase dashboard and email testing UI aren't needed.*/minimal?: boolean;+ /** Also start Studio, Postgres-Meta and the edge runtime. */+ full?: boolean;};type Ctx = {@@ -120,6 +124,7 @@ export async function up(opts: UpOpts = {}) {const shouldRegen = shouldMigrate && (opts.regen ?? true);const shouldBorrow = opts.borrow === true;const minimal = opts.minimal ?? false;+ const size = { minimal, full: !minimal && opts.full === true };// Services-only mode: boot compose stack + portless aliases (api/studio/// mail/inngest URLs still useful), skip spawnApps + auto-`down` on Ctrl+C.// Triggered by --no-apps OR by deselecting everything in the picker.@@ -222,8 +227,8 @@ export async function up(opts: UpOpts = {}) {if (borrowedEntry) {await waitForServices(ctx);} else {- await pullImages(ctx, { force: opts.pull === true, minimal });- await bootDockerStack(ctx, { minimal });+ await pullImages(ctx, { force: opts.pull === true, size });+ await bootDockerStack(ctx, size);await waitForServices(ctx);}await runDatabaseMigrations(ctx, { shouldMigrate, shouldRegen });@@ -251,7 +256,8 @@ export async function up(opts: UpOpts = {}) {const summary = summaryLines(ctx.ports,selectedApps,- portless ? ctx.branchPrefix : undefined+ portless ? ctx.branchPrefix : undefined,+ size.full);// `box()` derives its padding from `process.stdout.columns`; some// non-interactive terminals (e.g. Conductor's run pane) report a width of 0,@@ -436,27 +442,22 @@ async function provisionSlot(// Pull images outside `tasks()` so we can use clack's progress bar (one// tick per `<service> Pulled` event). Spinner subtitle inside `tasks()`// can't render a bar, only a single line of text.-async function pullImages(- ctx: Ctx,- opts: { force: boolean; minimal: boolean }-) {+async function pullImages(ctx: Ctx, opts: { force: boolean; size: StackSize }) {if (!opts.force) {- const refs = await devComposeImageRefs(ctx.root, ctx.slug, {- minimal: opts.minimal- });+ const refs = await devComposeImageRefs(ctx.root, ctx.slug, opts.size);if (refs && (await allImagesPresentLocally(refs))) {log.info("docker images already present — skipping compose pull");return;}}- const services = await listComposeServices(ctx.root, ctx.slug, {- minimal: opts.minimal- });+ const services = await listComposeServices(ctx.root, ctx.slug, opts.size);const max = Math.max(services.length, 1);const bar = progress({ style: "heavy", max });bar.start(- opts.minimal ? "Pulling docker images (minimal)" : "Pulling docker images"+ opts.size.minimal+ ? "Pulling docker images (minimal)"+ : "Pulling docker images");try {await pullStack(@@ -466,7 +467,7 @@ async function pullImages(bar.message(line.slice(0, 80));if (/ Pulled$/.test(line)) bar.advance(1);},- { minimal: opts.minimal }+ opts.size);bar.stop("images up to date");} catch (err) {@@ -475,17 +476,17 @@ async function pullImages(}}-async function bootDockerStack(ctx: Ctx, opts: { minimal: boolean }) {- const serviceCount = opts.minimal ? 8 : 11;- const label = opts.minimal- ? "Boot docker compose stack (minimal — no studio/meta/inbucket)"- : "Boot docker compose stack";+async function bootDockerStack(ctx: Ctx, size: StackSize) {+ const label = size.minimal+ ? "Boot docker compose stack (minimal — no inbucket)"+ : size.full+ ? "Boot docker compose stack (full — with studio/meta/edge-runtime/imgproxy)"+ : "Boot docker compose stack";await tasks([{title: label,- task: async (msg) => {- msg(`starting ${serviceCount} services`);- await bootStack(ctx.root, ctx.slug, { minimal: opts.minimal });+ task: async () => {+ await bootStack(ctx.root, ctx.slug, size);return "containers up";}}@@ -526,7 +527,9 @@ async function waitForServices(ctx: Ctx) {},onTimeout: () => dumpStorageDiagnostics(ctx)});- bar.advance(1, "storage.buckets ready");+ bar.message("waiting for auth / realtime schemas");+ await waitForServiceSchemas(ctx.ports.PORT_DB);+ bar.advance(1, "service schemas ready");bar.stop("all services responding");} catch (err) {bar.stop("services not ready");diff --git a/packages/dev/src/main.ts b/packages/dev/src/main.tsindex 582cd6470c..2bf2f3b73c 100644--- a/packages/dev/src/main.ts+++ b/packages/dev/src/main.ts@@ -9,6 +9,7 @@ import { initWorktree } from "./commands/init.js";import { listWorktrees } from "./commands/list.js";import { migrate } from "./commands/migrate.js";import { newWorktree } from "./commands/new.js";+import { prune } from "./commands/prune.js";import { reload } from "./commands/reload.js";import { removeWorktreeCmd } from "./commands/remove.js";import { reset } from "./commands/reset.js";@@ -77,11 +78,17 @@ const main = defineCommand({description:"With --run, also remove Docker volumes on teardown (headless: don't leak data volumes across dispatches)"},+ full: {+ type: "boolean",+ default: false,+ description:+ "Also start Studio, Postgres-Meta, the edge runtime and imgproxy (off by default; `crbn reload studio` / `crbn reload imgproxy` starts one on a running stack)"+ },minimal: {type: "boolean",default: false,description:- "Skip non-essential services (Studio, Postgres-Meta, Inbucket) to reduce memory footprint (useful for headless/CI builds)"+ "Also skip Inbucket, for headless/CI builds that sign in by bypass"}},run: ({ args }) =>@@ -95,6 +102,7 @@ const main = defineCommand({portless: args.portless !== false,run: typeof args.run === "string" ? args.run : undefined,volumes: args.volumes === true,+ full: args.full === true,minimal: args.minimal === true})}),@@ -122,7 +130,14 @@ const main = defineCommand({}),status: defineCommand({meta: { description: "Show port assignment + container health" },- run: () => status()+ args: {+ json: {+ type: "boolean",+ default: false,+ description: "Print the slot and containers as JSON"+ }+ },+ run: ({ args }) => status({ json: args.json === true })}),reload: defineCommand({meta: {@@ -303,18 +318,52 @@ const main = defineCommand({}),list: defineCommand({meta: { description: "List worktrees with stack status" },- run: () => listWorktrees()+ args: {+ json: {+ type: "boolean",+ default: false,+ description: "Print the worktrees as JSON"+ }+ },+ run: ({ args }) => listWorktrees({ json: args.json === true })}),remove: defineCommand({- meta: { description: "Pick a worktree to delete (with stack teardown)" },+ meta: {+ description:+ "Delete worktrees with their stacks — pick interactively, or name them: `crbn remove <branch-or-path...>`"+ },args: {+ worktree: {+ type: "positional",+ required: false,+ description: "Branch name(s) or path(s) to remove; skips the picker"+ },prune: {type: "boolean",default: false,description: "Also delete the git branch after removing the worktree"}},- run: ({ args }) => removeWorktreeCmd({ prune: args.prune === true })+ run: ({ args, rawArgs }) =>+ removeWorktreeCmd({+ prune: args.prune === true,+ targets: rawArgs.filter((a) => a && !a.startsWith("-"))+ })+ }),+ prune: defineCommand({+ meta: {+ description:+ "Destroy stacks no worktree can reach: slots whose directory is gone, and stacks with no slot (volumes wiped; confirms first)"+ },+ args: {+ all: {+ type: "boolean",+ default: false,+ description:+ "Destroy EVERY crbn stack on this machine, running ones included. Worktrees, branches and live slots are kept; the next `crbn up` rebuilds the database"+ }+ },+ run: ({ args }) => prune({ all: args.all === true })}),copy: defineCommand({meta: {diff --git a/packages/dev/src/prompts.ts b/packages/dev/src/prompts.tsindex 7f5cc4004b..8610f0e9c4 100644--- a/packages/dev/src/prompts.ts+++ b/packages/dev/src/prompts.ts@@ -28,6 +28,15 @@ import { listSlugs } from "./worktree.js";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;+ throw new Error(`${what} needs a terminal. ${instead}`);+}++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);@@ -40,6 +49,10 @@ export async function pickBorrowSlug(currentSlug: string): Promise<string> {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]) => ({@@ -198,6 +211,7 @@ export async function promptCopyEnv(): Promise<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@@ -206,12 +220,24 @@ export async function confirmReset(projectName: string): Promise<boolean> {return ok as boolean;}+export async function confirmPrune(count: number): Promise<boolean> {+ if (process.env.CARBON_DEV_YES === "1") return true;+ requireTerminal("Confirming a prune", CONFIRM_BY_ENV);+ const ok = await confirm({+ message: `Destroy ${count} stack(s) and their volumes? (postgres, storage, inngest data will be wiped)`,+ 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@@ -224,6 +250,8 @@ 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: falsediff --git a/packages/dev/src/services/compose.test.ts b/packages/dev/src/services/compose.test.tsindex bf88ca2d79..efe0201d3a 100644--- a/packages/dev/src/services/compose.test.ts+++ b/packages/dev/src/services/compose.test.ts@@ -25,6 +25,7 @@ describe("buildDownArgs", () => {it("enables every profile that buildUpArgs can enable", () => {const bootable = new Set([...profilesIn(buildUpArgs(ROOT, SLUG)),+ ...profilesIn(buildUpArgs(ROOT, SLUG, { full: true })),...profilesIn(buildUpArgs(ROOT, SLUG, { minimal: true }))]);const tearable = new Set(profilesIn(buildDownArgs(ROOT, SLUG, false)));@@ -79,12 +80,18 @@ describe("teardownExitCode", () => {});describe("buildUpArgs", () => {- // Locks in the pre-existing boot behavior the extraction preserved.- it("enables the full profile by default", () => {- expect(profilesIn(buildUpArgs(ROOT, SLUG))).toEqual(["full"]);+ it("starts mail but nothing from the full profile by default", () => {+ expect(profilesIn(buildUpArgs(ROOT, SLUG))).toEqual(["mail"]);});- it("drops the full profile under --minimal", () => {+ it("adds the full profile under --full", () => {+ expect(profilesIn(buildUpArgs(ROOT, SLUG, { full: true }))).toEqual([+ "full",+ "mail"+ ]);+ });++ it("enables no profile under --minimal", () => {expect(profilesIn(buildUpArgs(ROOT, SLUG, { minimal: true }))).toEqual([]);});diff --git a/packages/dev/src/services/compose.ts b/packages/dev/src/services/compose.tsindex 0ecef1b7b7..5f1ca01ef0 100644--- a/packages/dev/src/services/compose.ts+++ b/packages/dev/src/services/compose.ts@@ -60,18 +60,32 @@ export type Container = {// Every profile `bootStack` can enable. Compose treats profile-gated services// as "not enabled" rather than orphans, so a `down` missing one silently// leaves those containers running. `stopStack`'s sweep backstops drift here.-const COMPOSE_PROFILES = ["full"] as const;+const COMPOSE_PROFILES = ["full", "mail"] as const;++// Which services a boot starts. Default: the stack the apps need plus Inbucket+// (login emails). `full` adds Studio, Postgres-Meta, the edge runtime and+// imgproxy — nothing in the apps calls the first three (~40% of a stack's+// memory) and imgproxy only converts HEIC. `minimal` drops Inbucket too+// (headless runs sign in by bypass).+export type StackSize = { minimal?: boolean; full?: boolean };++function profileArgs(opts?: StackSize): string[] {+ if (opts?.minimal) return [];+ return opts?.full+ ? ["--profile", "full", "--profile", "mail"]+ : ["--profile", "mail"];+}// Exported for tests: the `docker compose … up -d` argv.export function buildUpArgs(root: string,slug: string,- opts?: { minimal?: boolean; services?: string[] }+ opts?: StackSize & { services?: string[] }): string[] {const args = devArgs(root, slug, "--env-file", ".env.local");// When specific services are requested, don't activate profiles — compose// starts only the named services (+ dependencies) regardless of profiles.- if (!opts?.services && !opts?.minimal) args.push("--profile", "full");+ if (!opts?.services) args.push(...profileArgs(opts));args.push("up", "-d");if (opts?.services) args.push(...opts.services);return args;@@ -94,7 +108,7 @@ export function buildDownArgs(export async function bootStack(root: string,slug: string,- opts?: { minimal?: boolean; services?: string[] }+ opts?: StackSize & { services?: string[] }) {await execStrict("docker", buildUpArgs(root, slug, opts), root);}@@ -149,10 +163,10 @@ export async function pullStack(root: string,slug: string,onLine: (line: string) => void,- opts?: { minimal?: boolean }+ opts?: StackSize) {const args = devArgs(root, slug, "--env-file", ".env.local");- if (!opts?.minimal) args.push("--profile", "full");+ args.push(...profileArgs(opts));args.push("--progress", "plain", "pull");const proc = execa("docker", args, { cwd: root, reject: false, all: true });@@ -174,10 +188,10 @@ export async function pullStack(export async function devComposeImageRefs(root: string,slug: string,- opts?: { minimal?: boolean }+ opts?: StackSize): Promise<string[] | null> {const args = devArgs(root, slug, "--env-file", ".env.local");- if (!opts?.minimal) args.push("--profile", "full");+ args.push(...profileArgs(opts));args.push("config", "--images");const r = await execa("docker", args, { cwd: root, reject: false });if (r.exitCode !== 0) return null;@@ -346,14 +360,13 @@ export async function listContainers(root: string,slug: string): Promise<Container[]> {- const r = await execa(- "docker",- devArgs(root, slug, "ps", "-a", "--format", "json"),- { cwd: root, reject: false }+ const stdout = await composeRead(+ root,+ devArgs(root, slug, ...envFileArgs(root), "ps", "-a", "--format", "json"));- if (r.exitCode !== 0 || !r.stdout?.trim()) return [];+ if (!stdout.trim()) return [];const out: Container[] = [];- for (const line of r.stdout.split("\n")) {+ for (const line of stdout.split("\n")) {if (!line) continue;let raw: unknown;try {@@ -406,14 +419,12 @@ function parsePublishers(raw: unknown): Publisher[] {export async function listComposeServices(root: string,slug: string,- opts?: { minimal?: boolean }+ opts?: StackSize): Promise<string[]> {const args = devArgs(root, slug, "--env-file", ".env.local");- if (!opts?.minimal) args.push("--profile", "full");+ args.push(...profileArgs(opts));args.push("config", "--services");- const r = await execa("docker", args, { cwd: root, reject: false });- if (r.exitCode !== 0) return [];- return (r.stdout ?? "")+ return (await composeRead(root, args)).split("\n").map((s) => s.trim()).filter(Boolean);@@ -430,7 +441,16 @@ export async function tailServiceLogs(): Promise<string> {const r = await execa("docker",- devArgs(root, slug, "logs", "--tail", String(lines), "--no-color", service),+ devArgs(+ root,+ slug,+ ...envFileArgs(root),+ "logs",+ "--tail",+ String(lines),+ "--no-color",+ service+ ),{ cwd: root, reject: false });return ((r.stdout ?? "") + (r.stderr ?? "")).trim();@@ -535,6 +555,29 @@ export async function listCarbonProjects(): Promise<string[]> {return [...all];}+// Every crbn stack on the machine, including ones whose containers are gone:+// `down` keeps volumes, so a deleted worktree's data outlives its containers.+// Matching on the `pgdata` volume keeps other "carbon-" compose projects out.+export async function listCarbonStacks(): Promise<string[]> {+ const r = await execa(+ "docker",+ [+ "volume",+ "ls",+ "--filter",+ "label=com.docker.compose.volume=pgdata",+ "--format",+ '{{.Label "com.docker.compose.project"}}'+ ],+ { reject: false }+ );+ const fromVolumes = (r.stdout ?? "")+ .split("\n")+ .map((s) => s.trim())+ .filter((name) => name.startsWith("carbon-"));+ return [...new Set([...fromVolumes, ...(await listCarbonProjects())])];+}+// ---------------------------------------------------------------------------// Utility// ---------------------------------------------------------------------------@@ -556,6 +599,34 @@ export async function flushDb(db: number) {// Private helpers// ---------------------------------------------------------------------------+// A compose command whose answer the caller reports as fact. A failure here is+// thrown with compose's own words: returning "nothing" instead made `crbn+// status` show an empty stack while eight containers ran, hiding the config+// error that caused it.+async function composeRead(root: string, args: string[]): Promise<string> {+ const r = await execa("docker", args, { cwd: root, reject: false });+ if (r.exitCode === 0) return r.stdout ?? "";+ const detail = (r.stderr ?? "")+ .split("\n")+ .filter((line) => line.trim() && !line.includes("level=warning"))+ .slice(-5)+ .join("\n");+ throw new Error(+ `docker ${args.slice(-3).join(" ")} failed (exit ${r.exitCode})\n${detail}`+ );+}++// Compose must interpolate the whole file before it will even list containers,+// and the file has values with no default (extra_hosts names). Read-only+// commands that run outside `crbn up` — where nothing has loaded .env.local+// into the process — need it passed explicitly, or they fail and report an+// empty stack.+function envFileArgs(root: string): string[] {+ return existsSync(join(root, ".env.local"))+ ? ["--env-file", ".env.local"]+ : [];+}+function devArgs(root: string, slug: string, ...rest: string[]): string[] {// --project-directory . pins the project dir to the cwd (repo root) so the// compose file's ./packages/... mounts resolve from root even though the filediff --git a/packages/dev/src/services/migrations.ts b/packages/dev/src/services/migrations.tsindex 07a1528b34..24269bdbe6 100644--- a/packages/dev/src/services/migrations.ts+++ b/packages/dev/src/services/migrations.ts@@ -283,6 +283,9 @@ async function repairStaleMigrations(* stack can't abort the run, which means a missing `storage.objects` would let* the restore finish "successfully" with no buckets seeded. Both services must* have booted.+ *+ * Realtime is the third: `realtime.messages` is built by the Realtime service,+ * and Carbon's migrations put policies on it.*/export async function serviceSchemasReady(dbPort: number): Promise<boolean> {return withClient(dbPort, async (c) => {@@ -290,6 +293,7 @@ export async function serviceSchemasReady(dbPort: number): Promise<boolean> {`SELECT to_regclass('auth.users') IS NOT NULLAND to_regclass('storage.objects') IS NOT NULLAND to_regclass('storage.buckets') IS NOT NULL+ AND to_regclass('realtime.messages') IS NOT NULLAND EXISTS (SELECT 1 FROM information_schema.columnsWHERE table_schema = 'auth' AND table_name = 'users'@@ -300,6 +304,19 @@ export async function serviceSchemasReady(dbPort: number): Promise<boolean> {});}+// Carbon's migrations write into schemas GoTrue, Storage and Realtime build on+// their first boot, so a fresh volume can't be migrated until all three have.+export async function waitForServiceSchemas(port: number, timeoutMs = 90_000) {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ if (await serviceSchemasReady(port).catch(() => false)) return;+ await sleep(1000);+ }+ throw new Error(+ `auth / storage / realtime schemas not ready within ${timeoutMs}ms — check the gotrue, storage and realtime containers`+ );+}+// The singleton "config" row (the API URL and anon key some database// functions read), and the Vault `inngest_event_url` that// util.send_inngest_event posts database events to. Without the URL thediff --git a/packages/dev/src/services/portless.ts b/packages/dev/src/services/portless.tsindex ee9c6bc5ea..3a4a273688 100644--- a/packages/dev/src/services/portless.ts+++ b/packages/dev/src/services/portless.ts@@ -5,10 +5,12 @@import { existsSync, readFileSync } from "node:fs";import { homedir } from "node:os";import { setTimeout as sleep } from "node:timers/promises";-import { confirm, isCancel, log, spinner } from "@clack/prompts";+import { confirm, isCancel, log } from "@clack/prompts";import { execa, execaSync } from "execa";import pc from "picocolors";import { PORTLESS_MIN_VERSION } from "../constants.js";+import { requireTerminal } from "../prompts.js";+import { spinner } from "../ui.js";import type { PortMap } from "../worktree.js";// Strip npm_* / PNPM_* so portless doesn't refuse with "should not be run via@@ -184,6 +186,10 @@ export async function ensureProxyPrivileges() {? "Will bind :443, install the local CA, and write hosts entries (requires Administrator terminal).": "Set it up now? Will run sudo to bind :443, install the local CA, and write /etc/hosts entries.";+ requireTerminal(+ "Setting up the portless proxy (it runs sudo)",+ "Run `crbn up` once in a terminal, or pass --no-portless."+ );const proceed = await confirm({message: elevateHint,initialValue: truediff --git a/packages/dev/src/ui.ts b/packages/dev/src/ui.tsindex a332b15fd4..95e52b1670 100644--- a/packages/dev/src/ui.ts+++ b/packages/dev/src/ui.ts@@ -2,6 +2,11 @@// 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 {+ progress as clackProgress,+ spinner as clackSpinner,+ type Task+} from "@clack/prompts";import Table from "cli-table3";import pc from "picocolors";import { type AppId, TLD } from "./constants.js";@@ -13,6 +18,42 @@ import {SHARED_REDIS_PORT} from "./worktree.js";+// ---------------------------------------------------------------------------+// Spinners+// ---------------------------------------------------------------------------++// clack redraws a spinner every 80 ms, which a pipe (an agent, a log file)+// records as thousands of frames. Its only static mode is keyed on CI=true,+// read when the spinner is created — so set it for that instant only, never+// for the process: the dev servers and pnpm crbn spawns must not inherit it.+function calm<T>(make: () => T): T {+ if (process.stdout.isTTY) return make();+ const prev = process.env.CI;+ process.env.CI = "true";+ try {+ return make();+ } finally {+ if (prev === undefined) delete process.env.CI;+ else process.env.CI = prev;+ }+}++export const spinner: typeof clackSpinner = (opts) =>+ calm(() => clackSpinner(opts));++export const progress: typeof clackProgress = (opts) =>+ calm(() => clackProgress(opts));++export async function tasks(list: Task[]) {+ for (const t of list) {+ if (t.enabled === false) continue;+ const s = spinner();+ s.start(t.title);+ const result = await t.task(s.message);+ s.stop(result || t.title);+ }+}+// ---------------------------------------------------------------------------// Tables (status / list)// ---------------------------------------------------------------------------@@ -135,7 +176,9 @@ export function summaryLines(ports: PortMap,apps: readonly AppId[],/** When provided, show portless hostnames; otherwise show localhost URLs. */- branchPrefix?: string+ branchPrefix?: string,+ /** False when the boot left Studio out; the row then says how to start it. */+ studioRunning = true): string[] {const url = branchPrefix? (sub: string, _port?: number) => `https://${sub}.${branchPrefix}.${TLD}`@@ -153,12 +196,14 @@ export function summaryLines(url("api", ports.PORT_API),branchPrefix ? ports.PORT_API : undefined),- row(- pc.green,- "Studio",- url("studio", ports.PORT_STUDIO),- branchPrefix ? ports.PORT_STUDIO : undefined- ),+ studioRunning+ ? row(+ pc.green,+ "Studio",+ url("studio", ports.PORT_STUDIO),+ branchPrefix ? ports.PORT_STUDIO : undefined+ )+ : `${pc.dim("Studio".padEnd(8))} ${pc.dim("not started — crbn reload studio")}`,row(pc.yellow,"Mail",diff --git a/packages/dev/src/worktree.ts b/packages/dev/src/worktree.tsindex 1de5c96a19..e22658b6ce 100644--- a/packages/dev/src/worktree.ts+++ b/packages/dev/src/worktree.ts@@ -8,6 +8,9 @@ import {mkdirSync,readFileSync,realpathSync,+ renameSync,+ rmdirSync,+ statSync,writeFileSync} from "node:fs";import net from "node:net";@@ -158,6 +161,18 @@ export function slugify(input: string): string {export async function resolveSlot(slug: string,worktreeRoot: string+): Promise<{ ports: PortMap; redisDb: number; jwt: JwtCreds }> {+ const unlock = lockRegistry();+ try {+ return await resolveSlotLocked(slug, worktreeRoot);+ } finally {+ unlock();+ }+}++async function resolveSlotLocked(+ slug: string,+ worktreeRoot: string): Promise<{ ports: PortMap; redisDb: number; jwt: JwtCreds }> {const registry = readRegistry();const existing = registry[slug];@@ -244,10 +259,15 @@ export function slugForWorktreePath(}export function removeSlot(slug: string) {- const registry = readRegistry();- if (!(slug in registry)) return;- delete registry[slug];- writeRegistry(registry);+ const unlock = lockRegistry();+ try {+ const registry = readRegistry();+ if (!(slug in registry)) return;+ delete registry[slug];+ writeRegistry(registry);+ } finally {+ unlock();+ }}// ---------------------------------------------------------------------------@@ -316,9 +336,56 @@ function isJwtCreds(v: unknown): v is JwtCreds {);}+// Temp file + rename, so a reader never sees a half-written registry.function writeRegistry(registry: Registry) {mkdirSync(dirname(REGISTRY_PATH), { recursive: true });- writeFileSync(REGISTRY_PATH, JSON.stringify(registry, null, 2));+ const tmp = `${REGISTRY_PATH}.${process.pid}.tmp`;+ writeFileSync(tmp, JSON.stringify(registry, null, 2));+ renameSync(tmp, REGISTRY_PATH);+}++// Every change to the registry is read → decide → write, and several `crbn up`+// start at once (Conductor boots workspaces concurrently). Without a lock two+// of them read the same file and hand out the same ports and redis db. `mkdir`+// is the lock: it is atomic, and it either creates the directory or fails.+const LOCK_PATH = `${REGISTRY_PATH}.lock`;+const LOCK_STALE_MS = 10_000;+const LOCK_WAIT_MS = 20_000;++function lockRegistry(): () => void {+ mkdirSync(dirname(LOCK_PATH), { recursive: true });+ const deadline = Date.now() + LOCK_WAIT_MS;+ for (;;) {+ try {+ mkdirSync(LOCK_PATH);+ break;+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;+ }+ // A holder that was killed leaves the directory behind. Nothing holds the+ // lock for more than a second, so one this old has no owner.+ try {+ if (Date.now() - statSync(LOCK_PATH).mtimeMs > LOCK_STALE_MS) {+ rmdirSync(LOCK_PATH);+ continue;+ }+ } catch {+ continue; // released between the mkdir and the stat+ }+ if (Date.now() > deadline) {+ throw new Error(+ `Timed out waiting for the slot registry lock (${LOCK_PATH}). If no other crbn is running, delete that directory.`+ );+ }+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);+ }+ return () => {+ try {+ rmdirSync(LOCK_PATH);+ } catch {+ // already gone (taken over as stale) — nothing to release+ }+ };}function pickRedisDb(taken: Set<number>): number {diff --git a/packages/files/AGENTS.md b/packages/files/AGENTS.mdindex d504256d21..35e3711ec6 100644--- a/packages/files/AGENTS.md+++ b/packages/files/AGENTS.md@@ -112,6 +112,10 @@ PDF.js bundle could not be resolved" while dev worked, because dev leavessafety net for legacy/API-stored files, not a licence to skip conversion.- Expose imgproxy outside the Docker network — it reads the storage volume withno RLS.+- Report a failed storage image transform with a message of your own. Pass the+ error through `imageTransformErrorMessage(error, fallback)` (`@carbon/files`):+ the local dev stack leaves imgproxy off unless booted with `crbn up --full`,+ and that helper is what tells the developer to run `crbn reload imgproxy`.## Validationdiff --git a/packages/files/src/media/image.ts b/packages/files/src/media/image.tsindex 06fef8d14f..b4b5c0dadb 100644--- a/packages/files/src/media/image.ts+++ b/packages/files/src/media/image.ts@@ -4,7 +4,7 @@import type { SupabaseClient } from "@supabase/supabase-js";import { nanoid } from "nanoid";-import { isUnsafeStoragePath } from "../storage";+import { imageTransformErrorMessage, isUnsafeStoragePath } from "../storage";import type { ImageShapeOptions, ProcessedImage } from "./image-pipeline";import {ImageTooLargeError,@@ -81,7 +81,12 @@ export async function transformImageViaStorage(.from(bucket).download(tempPath, { transform });if (download.error) {- throw new Error(`Failed to convert image: ${download.error.message}`);+ throw new Error(+ imageTransformErrorMessage(+ download.error,+ `Failed to convert image: ${download.error.message}`+ )+ );}return download.data;} finally {diff --git a/packages/files/src/storage.test.ts b/packages/files/src/storage.test.tsindex fa44017fd3..7ff9d74adf 100644--- a/packages/files/src/storage.test.ts+++ b/packages/files/src/storage.test.ts@@ -7,6 +7,7 @@ import { describe, expect, it, vi } from "vitest";import {getCompanyPrivateBucket,hasCompanyPrivateObjectPathPrefix,+ imageTransformErrorMessage,isStorageNotFound,isUnsafeStoragePath,LEGACY_PRIVATE_BUCKET,@@ -646,6 +647,22 @@ describe("move falls back to a cross-bucket move out of the legacy bucket", () =});});+describe("imageTransformErrorMessage", () => {+ it("names imgproxy when storage could not reach it", () => {+ // The message storage-api returns with the imgproxy container absent.+ const error = { message: "getaddrinfo ENOTFOUND imgproxy", status: 500 };+ expect(imageTransformErrorMessage(error, "fallback")).toContain(+ "crbn reload imgproxy"+ );+ });++ it("keeps the caller's message for any other failure", () => {+ const error = { message: "Object not found", status: 404 };+ expect(imageTransformErrorMessage(error, "fallback")).toBe("fallback");+ expect(imageTransformErrorMessage(null, "fallback")).toBe("fallback");+ });+});+describe("storageErrorStatus", () => {it("reads the status off a download's wrapped response", async () => {const { StorageUnknownError } = await import("@supabase/storage-js");diff --git a/packages/files/src/storage.ts b/packages/files/src/storage.tsindex 5376f094a7..8f8fec8497 100644--- a/packages/files/src/storage.ts+++ b/packages/files/src/storage.ts@@ -165,6 +165,23 @@ export type CarbonStorage = {company(companyId: string): CompanyBucket;};+/**+ * What to say when a storage image transform fails. Storage hands transforms+ * to imgproxy, and when that service is not running the failure names it+ * (`getaddrinfo ENOTFOUND imgproxy`) — a stack problem, not a bad image, and+ * the local dev stack leaves imgproxy off by default. Anything else gets the+ * caller's own message.+ */+export function imageTransformErrorMessage(+ error: unknown,+ fallback: string+): string {+ const message = (error as { message?: unknown } | null)?.message;+ return typeof message === "string" && /imgproxy/i.test(message)+ ? "Image transformation is unavailable: storage cannot reach imgproxy. On the local dev stack, start it with `crbn reload imgproxy` or boot with `crbn up --full`."+ : fallback;+}+/*** The HTTP status behind a storage error. `download()` skips reading the* error body, so a 400/404 arrives as `StorageUnknownError("{}")` with thediff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 737dc2a634..4547e29b3c 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -17068,18 +17068,12 @@ msgstr "Lösungsingenieur"msgid "Some lines extracted from the PDF could not be automatically mapped to your inventory items. Review and map each line below."msgstr "Einige aus dem PDF extrahierte Zeilen konnten nicht automatisch Ihren Bestandsartikeln zugeordnet werden. Überprüfen und ordnen Sie jede Zeile unten zu."-msgid "Some quantities are negative."-msgstr ""-msgid "Some records won't come back. Type <0>{CONFIRM_WORD}</0> to continue."msgstr "Einige Datensätze werden nicht zurückkommen. Geben Sie <0>{CONFIRM_WORD}</0> ein, um fortzufahren."msgid "Some Shifts"msgstr "Einige Schichten"-msgid "Some stock has no storage unit."-msgstr ""-msgid "Something went wrong. Please try again."msgstr "Etwas ist schief gelaufen. Bitte versuchen Sie es erneut."@@ -19616,6 +19610,9 @@ msgstr "Verfolgte Materialien werden nach Kommissionierauftrag vorabausgewähltmsgid "Tracking"msgstr "Verfolgung"+msgid "Tracking ID"+msgstr ""+msgid "Tracking method"msgstr "Verfolgungsmethode"@@ -20003,9 +20000,6 @@ msgstr "Unbenannte Zeile"msgid "Untitled step"msgstr "Unbenannter Schritt"-msgid "Untracked"-msgstr ""-msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Ungenutzte kommissionierte Materialien werden vom Arbeitsplatz zurück ins Lager geleitet."diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 2f0ea5640c..acf5bd8428 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -17068,18 +17068,12 @@ msgstr "Solutions Engineer"msgid "Some lines extracted from the PDF could not be automatically mapped to your inventory items. Review and map each line below."msgstr "Some lines extracted from the PDF could not be automatically mapped to your inventory items. Review and map each line below."-msgid "Some quantities are negative."-msgstr "Some quantities are negative."-msgid "Some records won't come back. Type <0>{CONFIRM_WORD}</0> to continue."msgstr "Some records won't come back. Type <0>{CONFIRM_WORD}</0> to continue."msgid "Some Shifts"msgstr "Some Shifts"-msgid "Some stock has no storage unit."-msgstr "Some stock has no storage unit."-msgid "Something went wrong. Please try again."msgstr "Something went wrong. Please try again."@@ -19616,6 +19610,9 @@ msgstr "Tracked material is pre-selected by pick order (FEFO), even without a pimsgid "Tracking"msgstr "Tracking"+msgid "Tracking ID"+msgstr "Tracking ID"+msgid "Tracking method"msgstr "Tracking method"@@ -20003,9 +20000,6 @@ msgstr "Untitled line"msgid "Untitled step"msgstr "Untitled step"-msgid "Untracked"-msgstr "Untracked"-msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Unused picked material flushed back from the work center to the warehouse."diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 170c88dfe6..cb164b6048 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -17068,18 +17068,12 @@ msgstr "Ingeniero de Soluciones"msgid "Some lines extracted from the PDF could not be automatically mapped to your inventory items. Review and map each line below."msgstr "Algunas líneas extraídas del PDF no se pudieron asignar automáticamente a sus artículos de inventario. Revise y asigne cada línea a continuación."-msgid "Some quantities are negative."-msgstr ""-msgid "Some records won't come back. Type <0>{CONFIRM_WORD}</0> to continue."msgstr "Algunos registros no volverán. Escriba <0>{CONFIRM_WORD}</0> para continuar."msgid "Some Shifts"msgstr "Algunos turnos"-msgid "Some stock has no storage unit."-msgstr ""-msgid "Something went wrong. Please try again."msgstr "Algo salió mal. Por favor, inténtalo de nuevo."@@ -19616,6 +19610,9 @@ msgstr "El material rastreado se preselecciona por orden de picking (FEFO), inclmsgid "Tracking"msgstr "Seguimiento"+msgid "Tracking ID"+msgstr ""+msgid "Tracking method"msgstr "Método de seguimiento"@@ -20003,9 +20000,6 @@ msgstr "Línea sin título"msgid "Untitled step"msgstr "Paso sin título"-msgid "Untracked"-msgstr ""-msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Material recogido no utilizado devuelto desde el centro de trabajo al almacén."diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex c1f532f6d1..d455d0a7f0 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -17068,18 +17068,12 @@ msgstr "Ingénieur Solutions"msgid "Some lines extracted from the PDF could not be automatically mapped to your inventory items. Review and map each line below."msgstr "Certaines lignes extraites du PDF n'ont pas pu être automatiquement associées à vos articles. Passez en revue et associez chaque ligne ci-dessous."-msgid "Some quantities are negative."-msgstr ""-msgid "Some records won't come back. Type <0>{CONFIRM_WORD}</0> to continue."msgstr "Certains enregistrements ne reviendront pas. Tapez <0>{CONFIRM_WORD}</0> pour continuer."msgid "Some Shifts"msgstr "Certaines équipes"-msgid "Some stock has no storage unit."-msgstr ""-msgid "Something went wrong. Please try again."msgstr "Quelque chose s'est mal passé. Veuillez réessayer."@@ -19616,6 +19610,9 @@ msgstr "Le matériel suivi est pré-sélectionné par ordre de prélèvement (FEmsgid "Tracking"msgstr "Suivi"+msgid "Tracking ID"+msgstr ""+msgid "Tracking method"msgstr "Méthode de suivi"@@ -20003,9 +20000,6 @@ msgstr "Ligne sans titre"msgid "Untitled step"msgstr "Étape sans titre"-msgid "Untracked"-msgstr ""-msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Matière prélevée inutilisée renvoyée du poste de travail à l'entrepôt."diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 9c72247248..3bccc58868 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -17068,18 +17068,12 @@ msgstr "समाधान इंजीनियर"msgid "Some lines extracted from the PDF could not be automatically mapped to your inventory items. Review and map each line below."msgstr "PDF से निकाली गई कुछ पंक्तियों को आपकी इन्वेंटरी आइटम्स से स्वचालित रूप से मैप नहीं किया जा सका। नीचे प्रत्येक पंक्ति की समीक्षा करें और मैप करें।"-msgid "Some quantities are negative."-msgstr ""-msgid "Some records won't come back. Type <0>{CONFIRM_WORD}</0> to continue."msgstr "कुछ रिकॉर्ड वापस नहीं आएंगे। जारी रखने के लिए <0>{CONFIRM_WORD}</0> टाइप करें।"msgid "Some Shifts"msgstr "कुछ शिफ्ट"-msgid "Some stock has no storage unit."-msgstr ""-msgid "Something went wrong. Please try again."msgstr "कुछ गलत हो गया। कृपया पुनः प्रयास करें।"@@ -19616,6 +19610,9 @@ msgstr "ट्रैक की गई सामग्री को पिकिmsgid "Tracking"msgstr "ट्रैकिंग"+msgid "Tracking ID"+msgstr ""+msgid "Tracking method"msgstr "ट्रैकिंग विधि"@@ -20003,9 +20000,6 @@ msgstr "बिना शीर्षक की पंक्ति"msgid "Untitled step"msgstr "बिना शीर्षक वाला चरण"-msgid "Untracked"-msgstr ""-msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "अप्रयुक्त सामग्री को वर्क सेंटर से गोदाम में वापस भेजा गया।"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex a0a601cd52..efb737843a 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -17068,18 +17068,12 @@ msgstr "Solutions Engineer"msgid "Some lines extracted from the PDF could not be automatically mapped to your inventory items. Review and map each line below."msgstr "Alcune righe estratte dal PDF non potevano essere mappate automaticamente ai tuoi articoli. Rivedi e mappa ogni riga di seguito."-msgid "Some quantities are negative."-msgstr ""-msgid "Some records won't come back. Type <0>{CONFIRM_WORD}</0> to continue."msgstr "Alcuni record non torneranno. Digita <0>{CONFIRM_WORD}</0> per continuare."msgid "Some Shifts"msgstr "Alcuni turni"-msgid "Some stock has no storage unit."-msgstr ""-msgid "Something went wrong. Please try again."msgstr "Qualcosa è andato storto. Riprova."@@ -19616,6 +19610,9 @@ msgstr "Il materiale tracciato è preselezionato per ordine di prelievo (FEFO),msgid "Tracking"msgstr "Tracciamento"+msgid "Tracking ID"+msgstr ""+msgid "Tracking method"msgstr "Metodo di tracciamento"@@ -20003,9 +20000,6 @@ msgstr "Riga senza titolo"msgid "Untitled step"msgstr "Passo senza titolo"-msgid "Untracked"-msgstr ""-msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Materiale prelevato non utilizzato reso dal centro di lavoro al deposito."diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 71333df158..1ca7d1fab0 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -17068,18 +17068,12 @@ msgstr "ソリューションズエンジニア"msgid "Some lines extracted from the PDF could not be automatically mapped to your inventory items. Review and map each line below."msgstr "PDFから抽出された一部の明細は在庫品目に自動的にマップできませんでした。以下の各明細を確認してマップしてください。"-msgid "Some quantities are negative."-msgstr ""-msgid "Some records won't come back. Type <0>{CONFIRM_WORD}</0> to continue."msgstr "いくつかのレコードは戻りません。続行するには<0>{CONFIRM_WORD}</0>と入力してください。"msgid "Some Shifts"msgstr "一部のシフト"-msgid "Some stock has no storage unit."-msgstr ""-msgid "Something went wrong. Please try again."msgstr "何か問題が発生しました。もう一度お試しください。"@@ -19616,6 +19610,9 @@ msgstr "追跡される材料は、ピッキングリストがない場合でもmsgid "Tracking"msgstr "追跡"+msgid "Tracking ID"+msgstr ""+msgid "Tracking method"msgstr "追跡方法"@@ -20003,9 +20000,6 @@ msgstr "無題の行"msgid "Untitled step"msgstr "無題のステップ"-msgid "Untracked"-msgstr ""-msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "未使用のピッキング済み材料が作業区から倉庫に戻されました。"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex 7a2a53efef..cdc1d94e53 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -17068,18 +17068,12 @@ msgstr "솔루션 엔지니어"msgid "Some lines extracted from the PDF could not be automatically mapped to your inventory items. Review and map each line below."msgstr "PDF에서 추출된 일부 라인을 재고 품목에 자동으로 매핑할 수 없습니다. 아래에서 각 라인을 검토하고 매핑하세요."-msgid "Some quantities are negative."-msgstr ""-msgid "Some records won't come back. Type <0>{CONFIRM_WORD}</0> to continue."msgstr "일부 레코드는 돌아오지 않습니다. 계속하려면 <0>{CONFIRM_WORD}</0>를 입력하세요."msgid "Some Shifts"msgstr "일부 교대조"-msgid "Some stock has no storage unit."-msgstr ""-msgid "Something went wrong. Please try again."msgstr "문제가 발생했습니다. 다시 시도해 주세요."@@ -19616,6 +19610,9 @@ msgstr "추적 자재는 피킹 리스트가 없어도 피킹 순서(FEFO)에msgid "Tracking"msgstr "추적"+msgid "Tracking ID"+msgstr ""+msgid "Tracking method"msgstr "추적 방법"@@ -20003,9 +20000,6 @@ msgstr "제목 없는 라인"msgid "Untitled step"msgstr "제목 없는 단계"-msgid "Untracked"-msgstr ""-msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "작업장에서 창고로 반환된 미사용 선택 재료."diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 497c246d30..3e398793d7 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -17068,18 +17068,12 @@ msgstr "Inżynier Rozwiązań"msgid "Some lines extracted from the PDF could not be automatically mapped to your inventory items. Review and map each line below."msgstr "Niektóre pozycje wyodrębnione z pliku PDF nie mogły być automatycznie zmapowane do artykułów z twoich zapasów. Przejrzyj i zamapuj każdą pozycję poniżej."-msgid "Some quantities are negative."-msgstr ""-msgid "Some records won't come back. Type <0>{CONFIRM_WORD}</0> to continue."msgstr "Niektóre rekordy nie wrócą. Wpisz <0>{CONFIRM_WORD}</0> aby kontynuować."msgid "Some Shifts"msgstr "Niektóre zmiany"-msgid "Some stock has no storage unit."-msgstr ""-msgid "Something went wrong. Please try again."msgstr "Coś poszło nie tak. Spróbuj ponownie."@@ -19616,6 +19610,9 @@ msgstr "Materiał śledzony jest wstępnie wybierany według kolejności poborumsgid "Tracking"msgstr "Śledzenie"+msgid "Tracking ID"+msgstr ""+msgid "Tracking method"msgstr "Metoda śledzenia"@@ -20003,9 +20000,6 @@ msgstr "Linia bez tytułu"msgid "Untitled step"msgstr "Krok bez tytułu"-msgid "Untracked"-msgstr ""-msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Materiał pobrany, ale nieużywany, zwracany ze stanowiska roboczego do magazynu."diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 9802184c3a..50e74ec25b 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -17068,18 +17068,12 @@ msgstr "Engenheiro de Soluções"msgid "Some lines extracted from the PDF could not be automatically mapped to your inventory items. Review and map each line below."msgstr "Algumas linhas extraídas do PDF não puderam ser mapeadas automaticamente para seus itens de inventário. Revise e mapeie cada linha abaixo."-msgid "Some quantities are negative."-msgstr ""-msgid "Some records won't come back. Type <0>{CONFIRM_WORD}</0> to continue."msgstr "Alguns registros não voltarão. Digite <0>{CONFIRM_WORD}</0> para continuar."msgid "Some Shifts"msgstr "Alguns Turnos"-msgid "Some stock has no storage unit."-msgstr ""-msgid "Something went wrong. Please try again."msgstr "Algo deu errado. Tente novamente."@@ -19616,6 +19610,9 @@ msgstr "Material rastreado é pré-selecionado por ordem de separação (FEFO),msgid "Tracking"msgstr "Rastreamento"+msgid "Tracking ID"+msgstr ""+msgid "Tracking method"msgstr "Método de rastreamento"@@ -20003,9 +20000,6 @@ msgstr "Linha sem título"msgid "Untitled step"msgstr "Etapa sem título"-msgid "Untracked"-msgstr ""-msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Material coletado não utilizado devolvido do centro de trabalho para o armazém."diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex c127c2ef24..c2e8b4843e 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -17068,18 +17068,12 @@ msgstr "Инженер решений"msgid "Some lines extracted from the PDF could not be automatically mapped to your inventory items. Review and map each line below."msgstr "Некоторые строки, извлеченные из PDF, не удалось автоматически сопоставить с вашими номенклатурными позициями. Проверьте и сопоставьте каждую строку ниже."-msgid "Some quantities are negative."-msgstr ""-msgid "Some records won't come back. Type <0>{CONFIRM_WORD}</0> to continue."msgstr "Некоторые записи не вернутся. Введите <0>{CONFIRM_WORD}</0> для продолжения."msgid "Some Shifts"msgstr "Некоторые смены"-msgid "Some stock has no storage unit."-msgstr ""-msgid "Something went wrong. Please try again."msgstr "Что-то пошло не так. Пожалуйста, попробуйте еще раз."@@ -19616,6 +19610,9 @@ msgstr "Отслеживаемый материал предварительноmsgid "Tracking"msgstr "Отслеживание"+msgid "Tracking ID"+msgstr ""+msgid "Tracking method"msgstr "Метод отслеживания"@@ -20003,9 +20000,6 @@ msgstr "Безымянная строка"msgid "Untitled step"msgstr "Шаг без названия"-msgid "Untracked"-msgstr ""-msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Неиспользованный отобранный материал поступает обратно из рабочего центра на склад."diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex cbfa9e64ac..94c1902f73 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -17068,18 +17068,12 @@ msgstr "Çözüm Mühendisi"msgid "Some lines extracted from the PDF could not be automatically mapped to your inventory items. Review and map each line below."msgstr "PDF'den çıkarılan bazı satırlar stok kartlarınıza otomatik olarak eşleştirilemedi. Aşağıdaki her satırı gözden geçirin ve eşleştirin."-msgid "Some quantities are negative."-msgstr ""-msgid "Some records won't come back. Type <0>{CONFIRM_WORD}</0> to continue."msgstr "Bazı kayıtlar geri gelmeyecek. Devam etmek için <0>{CONFIRM_WORD}</0> yazın."msgid "Some Shifts"msgstr "Bazı Vardiyalar"-msgid "Some stock has no storage unit."-msgstr ""-msgid "Something went wrong. Please try again."msgstr "Bir şeyler ters gitti. Lütfen tekrar deneyin."@@ -19616,6 +19610,9 @@ msgstr "İzlenen malzeme, toplama listesi olmasa bile toplama sırasına (FEFO)msgid "Tracking"msgstr "Takip"+msgid "Tracking ID"+msgstr ""+msgid "Tracking method"msgstr "İzleme yöntemi"@@ -20003,9 +20000,6 @@ msgstr "Başlıksız satır"msgid "Untitled step"msgstr "Başlıksız Adım"-msgid "Untracked"-msgstr ""-msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "İş merkezinden depoya geri gönderilen kullanılmayan alınan malzeme."diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex ccd8ec8a75..e6222a5715 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -17068,18 +17068,12 @@ msgstr "解决方案工程师"msgid "Some lines extracted from the PDF could not be automatically mapped to your inventory items. Review and map each line below."msgstr "从 PDF 提取的某些行无法自动映射到你的库存物料。查看并映射下面的每一行。"-msgid "Some quantities are negative."-msgstr ""-msgid "Some records won't come back. Type <0>{CONFIRM_WORD}</0> to continue."msgstr "某些记录不会回来。输入 <0>{CONFIRM_WORD}</0> 继续。"msgid "Some Shifts"msgstr "某些班次"-msgid "Some stock has no storage unit."-msgstr ""-msgid "Something went wrong. Please try again."msgstr "出现问题。请重试。"@@ -19616,6 +19610,9 @@ msgstr "追踪原材料按拣货顺序(先到期先出)预选,即使没有msgid "Tracking"msgstr "追踪"+msgid "Tracking ID"+msgstr ""+msgid "Tracking method"msgstr "跟踪方法"@@ -20003,9 +20000,6 @@ msgstr "未命名行"msgid "Untitled step"msgstr "未命名步骤"-msgid "Untracked"-msgstr ""-msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "未使用的已拣货物料从工作中心冲回至仓库。"diff --git a/scripts/generate-swagger-docs.ts b/scripts/generate-swagger-docs.tsindex 3f26774096..0b31f2dcd2 100644--- a/scripts/generate-swagger-docs.ts+++ b/scripts/generate-swagger-docs.ts@@ -8,15 +8,19 @@ import { normalizeSwaggerSchema } from "./lib/swagger-schema";async function main(): Promise<void> {loadDotEnv();- const studioPort = process.env.PORT_STUDIO;- if (!studioPort)+ // PostgREST's own OpenAPI document, through Kong with the anon key. Studio's+ // /api/platform/.../api/rest returns these exact bytes, so reading it here+ // keeps this script working when Studio isn't running.+ const apiPort = process.env.PORT_API;+ const anonKey = process.env.SUPABASE_ANON_KEY;+ if (!apiPort || !anonKey)throw new Error(- "PORT_STUDIO not set (expected in .env.local). Run `pnpm dev:up` first."+ "PORT_API / SUPABASE_ANON_KEY not set (expected in .env.local). Run `crbn up` first.");- const response = await fetch(- `http://127.0.0.1:${studioPort}/api/platform/projects/default/api/rest`,- { signal: AbortSignal.timeout(30_000) }- );+ const response = await fetch(`http://127.0.0.1:${apiPort}/rest/v1/`, {+ headers: { apikey: anonKey },+ signal: AbortSignal.timeout(30_000)+ });if (!response.ok)throw new Error(`Swagger request failed (HTTP ${response.status})`);const data = normalizeSwaggerSchema(await response.json());