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: local internal dev CLI (#760)
Sid553662ed460f
diff --git a/.env.example b/.env.exampleindex f498c51dae..19224fe920 100644--- a/.env.example+++ b/.env.example@@ -1,31 +1,22 @@-# Carbon specific-AUTH_PROVIDERS="email,google" # "email" | "google" | "azure"+# Copy to `.env` and fill in your secrets.+#+# For local dev, ports/URLs/Supabase keys/Redis/Inngest are auto-generated into+# `.env.local` by `crbn up` (see packages/dev/src/commands/up.ts). Vite/React Router+# auto-load `.env.local` on top of `.env`, so you only need to set genuine+# secrets in this file (OAuth, Stripe, Resend, etc.). Leave port/URL/Supabase+# variables out — `.env.local` will provide them.++# Carbon+AUTH_PROVIDERS="email,google" # "email" | "google" | "azure"CARBON_EDITION="community" # "community" | "cloud" | "enterprise"-DOMAIN="localhost"-VERCEL_URL="http://localhost:3000"-ERP_URL="http://localhost:3000"-MES_URL="http://localhost:3001"SESSION_SECRET="************************"RATE_LIMIT="5"-# Supabase-SUPABASE_ANON_KEY="******************"-SUPABASE_SERVICE_ROLE_KEY="*****************"-SUPABASE_URL="http://localhost:54321"-SUPABASE_DB_URL="postgresql://postgres:postgres@localhost:54322/postgres"--## Supabase google auth+# Supabase OAuth (client IDs/secrets from your provider; redirect URIs come from .env.local)SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID="************.apps.googleusercontent.com"SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_SECRET="GOCSPX-****************************"-SUPABASE_AUTH_EXTERNAL_GOOGLE_REDIRECT_URI="http://127.0.0.1:54321/auth/v1/callback"--## Supabase azure authSUPABASE_AUTH_EXTERNAL_AZURE_CLIENT_ID="***************************************"SUPABASE_AUTH_EXTERNAL_AZURE_CLIENT_SECRET="***********************************"-SUPABASE_AUTH_EXTERNAL_AZURE_REDIRECT_URI="http://127.0.0.1:54321/auth/v1/callback"--# Redis-REDIS_URL="redis://localhost:6379"# PosthogPOSTHOG_API_HOST="https://us.posthog.com"@@ -36,21 +27,18 @@ STRIPE_SECRET_KEY="sk_test_*************"STRIPE_WEBHOOK_SECRET="whsec_************"# GTM (notifications fan-out)-GTM_URL="http://localhost:4000"GTM_EVENTS_API_SECRET_KEY=""# ResendRESEND_API_KEY="************************"-RESEND_DOMAIN="carbon.ms" # or your domain (no trailing slashes or protocols)-# RESEND_AUDIENCE_ID="*****" # Optional - required for contact management in `packages/jobs`+RESEND_DOMAIN="carbon.ms"+# RESEND_AUDIENCE_ID="*****" # Optional — required for contact management in `packages/jobs`# NovuNOVU_APPLICATION_ID="********************"NOVU_SECRET_KEY="********************"-# Ingest-INNGEST_DEV=1-INNGEST_BASE_URL=http://localhost:8288+# Inngest (production keys; dev mode flags are in .env.local)# INNGEST_SIGNING_KEY="signkey-****-********************"# INNGEST_EVENT_KEY="********************"@@ -66,4 +54,4 @@ ANTHROPIC_API_KEY="sk-ant-***************"OPENAI_API_KEY="sk-proj-*****************"# Google Places-GOOGLE_PLACES_API_KEY="*******************"\ No newline at end of file+GOOGLE_PLACES_API_KEY="*******************"diff --git a/.gitignore b/.gitignoreindex 2e5134264b..b03b26622d 100644--- a/.gitignore+++ b/.gitignore@@ -52,5 +52,7 @@ packages/database/supabase/seed.sql# C++ (cad-engine)**/build/!**/build/.gitkeep-.orcka-.superpowers\ No newline at end of file++# Worktree-isolated dev environment+.carbon-worktree+.superpowersdiff --git a/README.md b/README.mdindex 52d9847a72..688409a1b6 100644--- a/README.md+++ b/README.md@@ -99,12 +99,14 @@ The monorepo follows the Turborepo convention of grouping packages into one of t### `/apps`-| Package Name | Description | Local Command |-| ------------ | --------------- | --------------------- |-| `erp` | ERP Application | `pnpm run dev` |-| `mes` | MES | `pnpm run dev:mes` |-| `academy` | Academy | `pnpm run dev:academy` |-| `starter` | Starter | `pnpm run dev:starter` |+| Package Name | Description | How to run |+| ------------ | --------------- | --------------------------------------------------- |+| `erp` | ERP Application | `pnpm dev` (boots stack + ERP via `crbn up` picker) |+| `mes` | MES | `pnpm dev` (select MES in picker, or both) |+| `academy` | Academy | `pnpm dev:academy` |+| `starter` | Starter | `pnpm dev:starter` |++`pnpm dev` runs the per-worktree dev CLI (`crbn up`). ERP and MES are first-class — the CLI boots the docker stack, applies migrations, regenerates types/swagger, and spawns the selected apps behind portless. Academy and starter are standalone Turborepo entries.### `/packages`@@ -161,14 +163,51 @@ This repo uses **pnpm** as its package manager. Enable Corepack so the correct p$ corepack enable # one-time: activates pnpm shim from packageManager field```-Then install + start the database:+Then install dependencies:```bash$ nvm use # use node v22$ pnpm install # install dependencies-$ pnpm run db:start # pull and run the containers```+The dev stack (Postgres, GoTrue, Kong, Storage, Inngest, Inbucket, Studio, Realtime) is booted later by `crbn up` — see [Local dev CLI](#local-dev-cli-crbn) below. There is no separate "start the database" step.++### Local dev CLI (`crbn`)++`crbn` is a small CLI at `packages/dev/bin/crbn` that wraps two things:++- **Git worktrees** — every feature branch can live in its own checkout dir, so you can switch branches without stashing.+- **Per-worktree docker compose stack** — each worktree gets its own Postgres / Supabase services on dynamic ports, isolated under `carbon-<slug>` compose project. Routing is handled by [portless](https://github.com/portless-dev/portless) (a local HTTPS reverse proxy that serves `*.dev` hostnames on `:443` with locally-trusted certs — installed automatically on first `crbn up`).++Run `setup.sh` once to put `crbn` on your `$PATH` and install the `crbn` shell function (so `crbn checkout` can change cwd):++```bash+$ ./setup.sh # writes a sentinel block to ~/.zshrc or ~/.bashrc+$ source ~/.zshrc # or open a new shell+$ crbn # shows commands+```++Common flows:++```bash+$ crbn checkout sid/cool-thing # cd into worktree (creates if missing,+ # auto-fetches from origin if needed)+$ crbn checkout -b feat/new-thing # new branch off origin/main + worktree+$ crbn checkout sid/cool-thing --up # …and boot the stack inside it+$ crbn checkout 760 # fetch GitHub PR #760 into a `pr-760`+ # branch + worktree (fork PRs work too)+$ crbn copy # re-sync .env from main checkout+$ crbn up | down | reset | status # per-worktree compose stack+$ crbn new | list | remove # interactive worktree management+```++`crbn up` flags:++- `--no-migrate` — skip `supabase migration up` (use when schema is already current and you just want to re-boot containers fast)+- `--no-regen` — skip regenerating `packages/database/src/types.ts` + `swagger-docs-schema.ts` (auto-skipped when `--no-migrate` is set, since no schema change implies no type drift)++Files synced by `crbn copy` are listed under `package.json#crbn.copy` (defaults to `[".env"]`). To uninstall the rc block: `./setup.sh --uninstall`.+Create an `.env` file and copy the contents of `.env.example` file into it```bash@@ -179,25 +218,24 @@ $ cp ./.env.example ./.env- Email requires a Resend API key (you'll set this up later on)- Sign-in with Google requires a Google auth client with these variables. [See the Supabase docs for instructions on how to set this up](https://supabase.com/docs/guides/auth/social-login/auth-google):- - Set `Authorized JavaScript origins` to only `http://127.0.0.1:54321`- - Set `Authorized redirect URIs` to `http://127.0.0.1:54321/auth/v1/callback`+ - Set `Authorized JavaScript origins` to `https://api.carbon.dev`+ - Set `Authorized redirect URIs` to `https://api.carbon.dev/auth/v1/callback`+ - **About the two API URLs you'll see:** each worktree has its own scoped Supabase URL (`https://<worktree>.api.dev`) for app traffic, **and** there is one stable alias `https://api.carbon.dev` registered on whichever worktree is currently `up`. The stable alias exists only so OAuth callbacks have a single registered redirect URI — one Google Console entry covers every worktree. Day-to-day, your app talks to its worktree-scoped URL; only the OAuth callback hits the stable alias.- You should set environment variables like the following.- `SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID="******.apps.googleusercontent.com"`- `SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_SECRET="GOCSPX-****************"`-2. **Supabase**: Start up the backend services using `pnpm run db:start`. Set the Supabase entries from the CLI output:--- `SUPABASE_URL` — **Project URL** (e.g. `http://127.0.0.1:54321`)-- `SUPABASE_ANON_KEY` — the **Publishable** key (`sb_publishable_...`). Older CLI versions labeled this the anon key (`eyJ...`).-- `SUPABASE_SERVICE_ROLE_KEY` — the **Secret** key (`sb_secret_...`). Older CLI versions labeled this the service_role key.+2. **Supabase**: Backend services run inside the per-worktree docker stack — `crbn up` boots them and writes everything you need into `.env.local` automatically:-Alternatively, run `supabase status -o env` in `packages/database` (or your Supabase project directory) for machine-readable lines, including legacy JWT-style anon/service keys if your CLI still prints them.+- `SUPABASE_URL` — portless alias (e.g. `https://local-dev.api.dev`)+- `SUPABASE_ANON_KEY`, `SUPABASE_SERVICE_ROLE_KEY` — keys minted per-worktree from a random `SUPABASE_JWT_SECRET`+- `SUPABASE_DB_URL` — direct Postgres URL on a dynamic port-See [Supabase API keys](https://supabase.com/docs/guides/api/api-keys) for how publishable and secret keys relate to the legacy names.+`.env.local` is generated; do not commit it or hand-edit values that came from `crbn up` (they are re-derived on each boot). Put genuine secrets (OAuth client IDs, Stripe keys, Resend, Novu) in `.env` only.-3. **Redis** (Caching): Set up a Redis instance (local or cloud) and add the connection URL. You can set one up in the cloud easily using [Upstash](https://console.upstash.com/auth/sign-in):+Run `crbn status` at any time to see the live port assignment and the URLs portless is serving.-- `REDIS_URL=[redis://user:password@host:port]`+3. **Redis** (Caching): No setup needed for local dev — `crbn up` boots a shared Redis container and writes `REDIS_URL` into `.env.local` automatically (each worktree gets its own logical Redis DB). For self-hosted production, set `REDIS_URL` to any Redis-compatible endpoint (Upstash, AWS ElastiCache, etc.) in your prod environment.4. **Posthog** (Analytics): In Posthog go to [https://[region].posthog.com/project/[project-id]/settings/project-details](https://[region].posthog.com/project/[project-id]/settings/project-details) to find your Project ID and Project API key:@@ -229,25 +267,27 @@ pnpm run novu:syncThis command syncs your Novu workflows with the Carbon application using the bridge URL.-Finally, start the apps and packages:+Finally, boot the stack and the apps:```bash-$ pnpm run dev-$ pnpm run dev:mes # pnpm run dev in all apps & packages+$ pnpm dev # equivalent to `crbn up` — picker lets you choose ERP/MES```-After installation you should be able run the apps locally.-| Application | URL |-| --------------- | ------------------------------------------------------------------------------------------------------------------ |-| ERP | [http://localhost:3000](http://localhost:3000) |-| MES | [http://localhost:3001](http://localhost:3001) |-| Academy | [http://localhost:4111](http://localhost:4111) |-| Starter | [http://localhost:4000](http://localhost:4000) |-| Background Jobs | [http://localhost:8288](http://localhost:8288) |-| Postgres | [postgresql://postgres:postgres@localhost:54322/postgres](postgresql://postgres:postgres@localhost:54322/postgres) |-| Supabase Studio | [http://localhost:54323/project/default](http://localhost:54323/project/default) |-| Mailpit | [http://localhost:54324](http://localhost:54324) |-| Edge Functions | [http://localhost:54321/functions/v1/<function-name>](http://localhost:54321/functions/v1/<function-name>) |+`crbn up` prints a summary box with the live URLs once the stack is healthy. Defaults look like:++| Surface | URL |+| --------------- | -------------------------------------------------------------- |+| ERP | `https://<worktree>.erp.dev` |+| MES | `https://<worktree>.mes.dev` |+| Supabase API | `https://<worktree>.api.dev` |+| Supabase Studio | `https://<worktree>.studio.dev` |+| Inngest | `https://<worktree>.inngest.dev` |+| Mail (Inbucket) | `https://<worktree>.mail.dev` |+| Postgres | `postgresql://postgres:postgres@localhost:<PORT_DB>/postgres` |++`<worktree>` is derived from the branch name (e.g. `sid-local-dev` → `local-dev`). The main checkout drops the prefix and just uses `erp.dev`, `mes.dev`, etc. Ports for raw TCP services (Postgres, Inbucket, Inngest) are dynamic per-worktree — `crbn status` is the source of truth.++Academy and starter still run on classic localhost ports via `pnpm dev:academy` / `pnpm dev:starter` (they are not part of the per-worktree stack).### Code Formatting@@ -291,39 +331,50 @@ To add an AI tool$ pnpm run tool:new <name>```-To kill the database containers in a non-recoverable way, you can run:+To stop the stack (keeps volumes — data preserved):```bash-$ pnpm run db:kill # stop and delete all database containers+$ crbn down```-To restart and reseed the database, you can run:+To wipe the stack and start clean (destroys Postgres volume + flushes the redis db for this worktree):```bash-$ pnpm run db:build # runs db:kill, db:start, and setup+$ crbn reset```-To run a particular application, use the `-w workspace` flag.--For example, to run test command in the `@carbon/react` package you can run:+To regenerate types or swagger schema manually (normally `crbn up` does this for you after applying migrations):+```bash+$ pnpm db:types # → packages/database/src/types.ts + functions/lib/types.ts+$ pnpm generate:swagger # → packages/database/src/swagger-docs-schema.ts```-$ pnpm --filter @carbon/react test-```--To restore a production database locally:-1. Download the production database as a .backup file-2. Rename the `migrations` folder to `_migrations`-3. Restore the database with the following command:+To run a command against a single workspace, use `pnpm --filter`:```bash-$ pnpm run db:build # this should error out at the seed step-$ PGPASSWORD=postgres psql -h localhost -p 54322 -U supabase_admin -d postgres < ~/Downloads/[email protected]-$ pnpm run dev+$ pnpm --filter @carbon/react test```-4. Rename the `_migraitons` folder back to `migrations`+To restore a production database snapshot locally:++1. Export a backup from your production Supabase project (`pg_dump` or Supabase Dashboard → Database → Backups).+2. Boot the stack **without applying migrations** so they don't fight the dump's schema state:+ ```bash+ $ crbn up --no-migrate+ ```+3. Find the live Postgres port (`crbn status` shows it; or read `PORT_DB` from `.env.local`).+4. Pipe the backup into the local DB as the superuser (`supabase_admin` for plain-text dumps, or use `pg_restore` for `.dump` archives):+ ```bash+ $ source .env.local+ $ PGPASSWORD=postgres psql -h localhost -p "$PORT_DB" -U supabase_admin -d postgres < /path/to/backup.sql+ # …or for .dump archives:+ $ PGPASSWORD=postgres pg_restore -h localhost -p "$PORT_DB" -U supabase_admin -d postgres --no-owner /path/to/backup.dump+ ```+5. Regenerate types so app code reflects the restored schema:+ ```bash+ $ pnpm db:types+ ```## API@@ -417,3 +468,12 @@ Background jobs have been migrated from [Trigger.dev](https://trigger.dev) to [I### Upstash to Local RedisThe caching layer (`@carbon/kv`) no longer depends on Upstash. A standard Redis instance is used instead. The `REDIS_URL` environment variable still applies, but you can point it at any Redis-compatible server (including a local Docker container).++### Supabase CLI to docker compose (`crbn`)++Local dev no longer relies on `supabase start` / `supabase stop`. The full backend stack (Postgres 15, GoTrue, Kong, Storage, Realtime, Studio, Inngest, Inbucket, edge-runtime) runs from `docker-compose.dev.yml` under a per-worktree compose project (`carbon-<slug>`), managed by `crbn up` / `down` / `reset`. Ports are allocated dynamically per worktree so multiple branches can run side-by-side. Key changes:++- `pnpm db:start` / `db:stop` / `db:kill` / `db:build` are removed — use `crbn up` / `down` / `reset`.+- `.env.local` is generated by `crbn up` (worktree-specific URLs, ports, JWT secret, anon/service keys). Genuine secrets stay in `.env`.+- `pnpm db:migrate` now drives `supabase migration up --db-url $SUPABASE_DB_URL`; it falls back to the CLI's linked-project mode when `SUPABASE_DB_URL` is unset.+- `pnpm db:types` generates types directly from `$SUPABASE_DB_URL` (no `supabase gen types --local`).diff --git a/apps/academy/package.json b/apps/academy/package.jsonindex 7f5f4067dd..d0fc173a48 100644--- a/apps/academy/package.json+++ b/apps/academy/package.json@@ -65,7 +65,6 @@"lint": "biome lint --write","start": "react-router-serve ./build/server/index.js","typecheck": "tsgo --noEmit",- "types": "tsgo --noEmit","typegen": "react-router typegen"},"sideEffects": falsediff --git a/apps/erp/package.json b/apps/erp/package.jsonindex 5362ee0106..7b3f0faecd 100644--- a/apps/erp/package.json+++ b/apps/erp/package.json@@ -165,13 +165,13 @@"scripts": {"build": "react-router build","clean": "rimraf .cache .turbo node_modules dist build",- "dev": "react-router dev",+ "dev": "portless --script dev:app run --force",+ "dev:app": "react-router dev --port $PORT --host $HOST","dev:novu": "pnpm dlx novu@latest dev --port 3000","sync:novu": "pnpm dlx novu@latest sync ","lint": "biome lint --write ","start": "NODE_ENV=production react-router-serve ./build/server/index.js","typecheck": "tsgo --noEmit",- "types": "tsgo --noEmit","typegen": "react-router typegen"},"sideEffects": falsediff --git a/apps/erp/vite.config.ts b/apps/erp/vite.config.tsindex 6d3c8c49fb..037bd371b2 100644--- a/apps/erp/vite.config.ts+++ b/apps/erp/vite.config.ts@@ -57,7 +57,7 @@ export default defineConfig(({ isSsrBuild, mode }) => {},server: {port: 3000,- allowedHosts: [".ngrok-free.app", ".ngrok-free.dev"],+ allowedHosts: [".ngrok-free.app", ".ngrok-free.dev", ".dev", ".localhost"],watch: {awaitWriteFinish: { stabilityThreshold: 250 },},diff --git a/apps/mes/package.json b/apps/mes/package.jsonindex 2b19518ea4..b5ba4759ae 100644--- a/apps/mes/package.json+++ b/apps/mes/package.json@@ -100,11 +100,11 @@"scripts": {"build": "react-router build","clean": "rimraf .cache .turbo node_modules dist build",- "dev": "react-router dev",+ "dev": "portless --script dev:app run --force",+ "dev:app": "react-router dev --port $PORT --host $HOST","lint": "biome lint --write ","start": "NODE_ENV=production react-router-serve ./build/server/index.js","typecheck": "tsgo --noEmit",- "types": "tsgo --noEmit","typegen": "react-router typegen"},"sideEffects": falsediff --git a/apps/mes/vite.config.ts b/apps/mes/vite.config.tsindex 524144f2b4..d235d6ea97 100644--- a/apps/mes/vite.config.ts+++ b/apps/mes/vite.config.ts@@ -32,7 +32,7 @@ export default defineConfig(({ mode, isSsrBuild }) => ({},server: {port: 3001,- allowedHosts: [".ngrok-free.app", ".w.modal.host", ".w.modal.dev"],+ allowedHosts: [".ngrok-free.app", ".w.modal.host", ".w.modal.dev", ".dev", ".localhost"],},plugins: [babelMacros(),diff --git a/apps/starter/package.json b/apps/starter/package.jsonindex 227ca986fc..5f3512e834 100644--- a/apps/starter/package.json+++ b/apps/starter/package.json@@ -66,7 +66,6 @@"lint": "biome lint --write ","start": "react-router-serve ./build/server/index.js","typecheck": "tsgo --noEmit",- "types": "tsgo --noEmit","typegen": "react-router typegen"},"sideEffects": falsediff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlnew file mode 100644index 0000000000..12e1afee8e--- /dev/null+++ b/docker-compose.dev.yml@@ -0,0 +1,244 @@+###+# Worktree-isolated dev stack. Boot via `npm run dev:up` (see packages/dev/src/cli.ts).+# COMPOSE_PROJECT_NAME=carbon-<slug> namespaces every container, network, volume.+# Required env (provided by .env via --env-file): PORT_*, SUPABASE_JWT_SECRET,+# SUPABASE_ANON_KEY, SUPABASE_SERVICE_ROLE_KEY, plus user secrets passed through.+###++services:+ postgres:+ image: supabase/postgres:15.14.1.112+ restart: unless-stopped+ networks:+ default:+ aliases:+ - db+ ports:+ - "${PORT_DB}:5432"+ environment:+ POSTGRES_HOST: /var/run/postgresql+ POSTGRES_PORT: 5432+ PGPORT: 5432+ POSTGRES_DB: postgres+ PGDATABASE: postgres+ POSTGRES_PASSWORD: postgres+ PGPASSWORD: postgres+ JWT_SECRET: ${SUPABASE_JWT_SECRET}+ JWT_EXP: 3600+ volumes:+ - pgdata:/var/lib/postgresql/data+ - pgconfig:/etc/postgresql-custom+ - ./packages/dev/docker/init.sql:/docker-entrypoint-initdb.d/zz-carbon-roles.sql:ro+ command:+ - postgres+ - -c+ - config_file=/etc/postgresql/postgresql.conf+ - -c+ - log_min_messages=fatal+ healthcheck:+ test: ["CMD", "pg_isready", "-U", "postgres", "-h", "localhost"]+ interval: 5s+ timeout: 5s+ retries: 20++ gotrue:+ image: supabase/gotrue:v2.189.0+ restart: unless-stopped+ depends_on:+ postgres:+ condition: service_healthy+ environment:+ GOTRUE_API_HOST: 0.0.0.0+ GOTRUE_API_PORT: 9999+ API_EXTERNAL_URL: ${SUPABASE_URL}+ GOTRUE_DB_DRIVER: postgres+ GOTRUE_DB_DATABASE_URL: postgres://supabase_auth_admin:postgres@postgres:5432/postgres+ GOTRUE_SITE_URL: ${ERP_URL}+ GOTRUE_URI_ALLOW_LIST: ${ERP_URL},${MES_URL},${GTM_URL}+ GOTRUE_DISABLE_SIGNUP: "false"+ GOTRUE_JWT_SECRET: ${SUPABASE_JWT_SECRET}+ GOTRUE_JWT_EXP: 3600+ GOTRUE_JWT_DEFAULT_GROUP_NAME: authenticated+ GOTRUE_JWT_ADMIN_ROLES: service_role+ GOTRUE_JWT_AUD: authenticated+ GOTRUE_EXTERNAL_EMAIL_ENABLED: "true"+ GOTRUE_MAILER_AUTOCONFIRM: "true"+ GOTRUE_SMTP_HOST: inbucket+ GOTRUE_SMTP_PORT: 2500+ GOTRUE_SMTP_ADMIN_EMAIL: [email protected]+ GOTRUE_SMTP_SENDER_NAME: Carbon+ GOTRUE_EXTERNAL_GOOGLE_ENABLED: "true"+ GOTRUE_EXTERNAL_GOOGLE_CLIENT_ID: ${SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID:-}+ GOTRUE_EXTERNAL_GOOGLE_SECRET: ${SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_SECRET:-}+ GOTRUE_EXTERNAL_GOOGLE_REDIRECT_URI: ${SUPABASE_AUTH_EXTERNAL_GOOGLE_REDIRECT_URI}+ GOTRUE_EXTERNAL_AZURE_ENABLED: "true"+ GOTRUE_EXTERNAL_AZURE_CLIENT_ID: ${SUPABASE_AUTH_EXTERNAL_AZURE_CLIENT_ID:-}+ GOTRUE_EXTERNAL_AZURE_SECRET: ${SUPABASE_AUTH_EXTERNAL_AZURE_CLIENT_SECRET:-}+ GOTRUE_EXTERNAL_AZURE_REDIRECT_URI: ${SUPABASE_AUTH_EXTERNAL_AZURE_REDIRECT_URI}++ postgrest:+ image: postgrest/postgrest:v13.0.8+ restart: unless-stopped+ depends_on:+ postgres:+ condition: service_healthy+ environment:+ PGRST_DB_URI: postgres://authenticator:postgres@postgres:5432/postgres+ PGRST_DB_SCHEMAS: public,storage,graphql_public+ PGRST_DB_ANON_ROLE: anon+ PGRST_JWT_SECRET: ${SUPABASE_JWT_SECRET}+ PGRST_DB_USE_LEGACY_GUCS: "false"+ PGRST_APP_SETTINGS_JWT_SECRET: ${SUPABASE_JWT_SECRET}+ PGRST_APP_SETTINGS_JWT_EXP: 3600++ realtime:+ image: supabase/realtime:v2.89.0+ restart: unless-stopped+ depends_on:+ postgres:+ condition: service_healthy+ environment:+ PORT: 4000+ DB_HOST: postgres+ DB_PORT: 5432+ DB_USER: supabase_admin+ DB_PASSWORD: postgres+ DB_NAME: postgres+ DB_AFTER_CONNECT_QUERY: 'SET search_path TO _realtime'+ DB_ENC_KEY: supabaserealtime+ API_JWT_SECRET: ${SUPABASE_JWT_SECRET}+ METRICS_JWT_SECRET: ${SUPABASE_JWT_SECRET}+ SECRET_KEY_BASE: UpNVntn3cDxHJpq99YMc1T1AQgQpc8kfYTuRgBiYa15BLrx8etQoXz3gZv1/u2oq+ APP_NAME: realtime+ ERL_AFLAGS: -proto_dist inet_tcp+ DNS_NODES: "''"+ RLIMIT_NOFILE: "10000"+ SEED_SELF_HOST: "true"+ RUN_JANITOR: "true"+ DISABLE_HEALTHCHECK_LOGGING: "true"++ storage:+ image: supabase/storage-api:v1.58.4+ restart: unless-stopped+ depends_on:+ postgres:+ condition: service_healthy+ environment:+ ANON_KEY: ${SUPABASE_ANON_KEY}+ SERVICE_KEY: ${SUPABASE_SERVICE_ROLE_KEY}+ POSTGREST_URL: http://postgrest:3000+ PGRST_JWT_SECRET: ${SUPABASE_JWT_SECRET}+ DATABASE_URL: postgres://supabase_storage_admin:postgres@postgres:5432/postgres+ FILE_SIZE_LIMIT: 52428800+ STORAGE_BACKEND: file+ FILE_STORAGE_BACKEND_PATH: /var/lib/storage+ TENANT_ID: stub+ REGION: stub+ GLOBAL_S3_BUCKET: stub+ ENABLE_IMAGE_TRANSFORMATION: "false"+ volumes:+ - storage:/var/lib/storage:z++ meta:+ image: supabase/postgres-meta:v0.96.5+ restart: unless-stopped+ depends_on:+ postgres:+ condition: service_healthy+ environment:+ PG_META_PORT: 8080+ PG_META_DB_HOST: postgres+ PG_META_DB_PORT: 5432+ PG_META_DB_NAME: postgres+ PG_META_DB_USER: supabase_admin+ PG_META_DB_PASSWORD: postgres++ studio:+ image: supabase/studio:2026.04.28-sha-89d08a2+ restart: unless-stopped+ depends_on:+ meta:+ condition: service_started+ ports:+ - "${PORT_STUDIO}:3000"+ environment:+ STUDIO_PG_META_URL: http://meta:8080+ POSTGRES_PASSWORD: postgres+ DEFAULT_ORGANIZATION_NAME: Carbon+ DEFAULT_PROJECT_NAME: carbon-${CARBON_WORKTREE}+ SUPABASE_URL: http://kong:8000+ SUPABASE_PUBLIC_URL: ${SUPABASE_URL}+ SUPABASE_ANON_KEY: ${SUPABASE_ANON_KEY}+ SUPABASE_SERVICE_KEY: ${SUPABASE_SERVICE_ROLE_KEY}++ inbucket:+ image: inbucket/inbucket:3.1.1+ restart: unless-stopped+ ports:+ - "${PORT_INBUCKET}:9000"++ edge-runtime:+ image: supabase/edge-runtime:v1.74.0+ restart: unless-stopped+ depends_on:+ postgres:+ condition: service_healthy+ environment:+ JWT_SECRET: ${SUPABASE_JWT_SECRET}+ SUPABASE_URL: http://kong:8000+ SUPABASE_ANON_KEY: ${SUPABASE_ANON_KEY}+ SUPABASE_SERVICE_ROLE_KEY: ${SUPABASE_SERVICE_ROLE_KEY}+ SUPABASE_DB_URL: postgresql://postgres:postgres@postgres:5432/postgres+ VERIFY_JWT: "false"+ volumes:+ - ./packages/database/supabase/functions:/home/deno/functions:ro+ - ./packages/database/src:/home/src:ro+ # Dev-only dispatcher; lives outside supabase/functions/ so prod+ # `supabase functions deploy --all` can't pick it up.+ - ./packages/dev/docker/edge-main:/home/deno/main:ro+ command:+ - start+ - --main-service+ - /home/deno/main++ kong:+ image: kong:2.8.1+ restart: unless-stopped+ depends_on:+ - gotrue+ - postgrest+ - realtime+ - storage+ - meta+ - edge-runtime+ ports:+ - "${PORT_API}:8000"+ environment:+ KONG_DATABASE: "off"+ KONG_DECLARATIVE_CONFIG: /home/kong/kong.yml+ KONG_DNS_ORDER: LAST,A,CNAME+ KONG_PLUGINS: request-transformer,cors,key-auth,acl,basic-auth+ volumes:+ - ./packages/dev/docker/kong.yml:/home/kong/kong.yml:ro++ # Redis is shared across worktrees — see root docker-compose.yml.+ # Each worktree gets its own logical DB index (0-15) via REDIS_URL.++ inngest:+ image: inngest/inngest:v1.18.0+ restart: unless-stopped+ ports:+ - "${PORT_INNGEST}:8288"+ command:+ - inngest+ - dev+ extra_hosts:+ - "host.docker.internal:host-gateway"+ volumes:+ - inngest:/data++volumes:+ pgdata:+ pgconfig:+ storage:+ inngest:diff --git a/docker-compose.yml b/docker-compose.ymlindex bac6638649..cb0df15bbc 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -1,5 +1,7 @@version: '3.8'+name: carbon-shared+services:redis:image: redis:7-alpinediff --git a/llm/workflows/edge-function.md b/llm/workflows/edge-function.mdindex d7fb9e0196..a9de9aedf7 100644--- a/llm/workflows/edge-function.md+++ b/llm/workflows/edge-function.md@@ -203,11 +203,12 @@ export async function createJournalEntry(#### Local Testing```bash-# Start Supabase local development-npm run db:start+# Boot the per-worktree dev stack (includes edge-runtime)+pnpm dev # or `crbn up`-# Test your function-curl -X POST 'http://localhost:54321/functions/v1/<function-name>' \+# Find the live API port (PORT_API in .env.local, or shown by `crbn status`)+# Test your function via the dynamic port:+curl -X POST "http://localhost:${PORT_API:?run crbn status}/functions/v1/<function-name>" \-H 'Authorization: Bearer <token>' \-H 'Content-Type: application/json' \-H 'x-company-id: <company-id>' \diff --git a/package.json b/package.jsonindex 4be73bde64..e3b37ea1e2 100755--- a/package.json+++ b/package.json@@ -6,7 +6,9 @@"@react-router/dev": "catalog:","@types/aws-lambda": "8.10.152","@typescript/native-preview": "7.0.0-dev.20260409.1",+ "cli-table3": "^0.6.5","csv-parse": "5.6.0",+ "execa": "^8.0.1","husky": "8.0.3","lint-staged": "16.4.0","npm-run-all": "catalog:",@@ -35,33 +37,17 @@"ci:migrations": "pnpm --filter ci ci:migrations","ci:deploy": "pnpm --filter ci ci:deploy","clean": "turbo run clean && rimraf ./node_modules && rimraf ./pnpm-lock.yaml",- "db:build": "run-s db:kill db:start setup","db:function:new": "pnpm --filter @carbon/database db:function:new",- "db:kill": "pnpm --filter @carbon/database db:kill",- "db:kill:redis": "pnpm --filter @carbon/kv db:kill","db:migrate": "pnpm --filter @carbon/database db:migrate",- "db:migrate:force": "turbo run db:migrate:force --no-cache","db:migrate:new": "pnpm --filter @carbon/database db:migrate:new",- "db:pull": "turbo run db:pull",- "db:push": "turbo run db:push",- "db:restart": "run-s db:stop db:start","db:seed": "turbo run db:seed --no-cache","db:seed:dev": "pnpm --filter @carbon/database db:seed:dev --",- "db:start": "pnpm --filter @carbon/database db:start",- "db:start:redis": "pnpm --filter @carbon/kv db:start",- "db:stop": "pnpm --filter @carbon/database db:stop",- "db:types": "pnpm --filter @carbon/database db:types",+ "db:types": "tsx scripts/generate-db-types.ts","deploy": "turbo run deploy",- "dev": "run-p dev:docker dev:jobs dev:jobs-wait",- "dev:docker": "docker compose up -d redis || docker-compose up -d redis",- "dev:jobs-wait": "pnpm dlx wait-on tcp:8288 && run-p dev:erp dev:stripe",+ "dev": "./packages/dev/bin/crbn up","dev:academy": "turbo run dev --filter=./apps/academy --filter=./packages/",- "dev:erp": "turbo run dev --filter=./apps/erp --filter=./packages/ ",- "dev:jobs": "pnpm --filter @carbon/jobs dev:jobs",- "dev:mes": "turbo run dev --filter=./apps/mes","dev:packages": "turbo run dev --filter=./packages/*","dev:starter": "turbo run dev --filter=./apps/starter --filter=./packages/",- "dev:stripe": "pnpm --filter @carbon/stripe dev:stripe","format": "biome format --write","generate:mcp": "tsx scripts/generate-mcp.ts","generate:swagger": "tsx scripts/generate-swagger-docs.ts && pnpm exec biome format ./packages/database/src/swagger-docs-schema.ts --write --files-max-size=5000000",@@ -71,15 +57,11 @@"lingui:compile": "lingui compile --namespace es","lingui:extract": "lingui extract --clean","novu:sync": "pnpm dlx novu@latest sync --bridge-url https://app.carbon.ms/api/novu --secret-key $NOVU_SECRET_KEY --api-url https://api.novu.co",- "postdb:build": "run-s generate:types generate:swagger",- "predb:build": "tsx scripts/setup-env-files.ts","prepare": "pnpm exec husky install",- "setup": "turbo run setup","test": "turbo run test","tool:new": "tsx scripts/create-tool.ts","translate": "pnpm dlx linguito translate --llm","agent:new": "tsx scripts/create-agent.ts",- "types": "turbo run types","typecheck": "turbo run typecheck --filter='*'","typegen": "turbo run typegen"},@@ -106,6 +88,11 @@"optionalDependencies": {"@rollup/rollup-linux-x64-gnu": "4.60.1"},+ "crbn": {+ "copy": [+ ".env"+ ]+ },"pnpm": {"onlyBuiltDependencies": ["@biomejs/biome",diff --git a/packages/database/package.json b/packages/database/package.jsonindex e01c1028d8..fa281e9206 100644--- a/packages/database/package.json+++ b/packages/database/package.json@@ -28,21 +28,14 @@"private": true,"scripts": {"clean": "rimraf .turbo node_modules dist",- "db:diff": "supabase db diff","db:function:new": "supabase functions new","db:init": "supabase init",- "db:kill": "supabase stop --no-backup",- "db:migrate": "supabase migration up",+ "db:migrate": "tsx src/migrate.ts","db:migrate:new": "supabase migration new","db:seed": "tsx src/seed.ts","db:seed:dev": "tsx src/seed-dev.ts",- "db:setup": "supabase db reset",- "db:start": "supabase start",- "db:stop": "supabase stop",- "db:types": "supabase gen types typescript --local > src/types.ts","deploy": "supabase link --project-ref $SUPABASE_PROJECT_ID && supabase db push","lint": "biome lint --write ",- "setup": "tsx src/seed.ts","typecheck": "tsgo --noEmit"},"sideEffects": false,diff --git a/packages/database/src/migrate.ts b/packages/database/src/migrate.tsnew file mode 100644index 0000000000..b362fd3c7c--- /dev/null+++ b/packages/database/src/migrate.ts@@ -0,0 +1,55 @@+import { spawnSync } from "node:child_process";+import net from "node:net";+import * as dotenv from "dotenv";++dotenv.config({ path: ".env" });+dotenv.config({ path: ".env.local", override: true });++function reachable(host: string, port: number): Promise<boolean> {+ return new Promise((resolve) => {+ const s = net.connect({ host, port });+ const done = (ok: boolean) => {+ s.removeAllListeners();+ s.destroy();+ resolve(ok);+ };+ s.once("connect", () => done(true));+ s.once("error", () => done(false));+ s.setTimeout(1500, () => done(false));+ });+}++async function main() {+ const dbUrl = process.env.SUPABASE_DB_URL;+ const extraArgs = process.argv.slice(2);++ // When SUPABASE_DB_URL points at a local stack, pre-flight a TCP check so we+ // surface "stack isn't running" instead of supabase's misleading "Network+ // Restrictions" cloud-dashboard error.+ if (dbUrl) {+ const m = dbUrl.match(/@([^:/]+):(\d+)\//);+ if (+ m &&+ (m[1] === "localhost" || m[1] === "127.0.0.1") &&+ !(await reachable(m[1], Number(m[2])))+ ) {+ console.error(+ `Local DB at ${m[1]}:${m[2]} is not reachable.\nStart the dev stack first: \`pnpm dev\` (or \`crbn up\`).`+ );+ process.exit(1);+ }+ }++ // When SUPABASE_DB_URL is set (dev stack via crbn up, or explicit override),+ // target it directly. Otherwise fall back to `supabase migration up` against+ // the CLI's linked project — preserves pre-PR behavior for operators who run+ // `supabase link` and then `pnpm db:migrate`.+ const args = dbUrl+ ? ["migration", "up", "--db-url", dbUrl, ...extraArgs]+ : ["migration", "up", ...extraArgs];++ const r = spawnSync("supabase", args, { stdio: "inherit" });+ process.exit(r.status ?? 1);+}++main();diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 53250bd6e7..b27051c270 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -3,7 +3,7 @@ export default {info: {description: "",title: "standard public schema",- version: "14.8"+ version: "13.0.8"},host: "0.0.0.0:3000",basePath: "/",@@ -69047,7 +69047,7 @@ export default {get: {parameters: [{- format: "vector",+ format: "extensions.vector",in: "query",name: "query_embedding",required: true,@@ -69061,7 +69061,7 @@ export default {type: "number"},{- format: "int32",+ format: "integer",in: "query",name: "match_count",required: true,@@ -69096,7 +69096,7 @@ export default {schema: {properties: {match_count: {- format: "int32",+ format: "integer",type: "integer"},match_threshold: {@@ -69108,7 +69108,7 @@ export default {type: "string"},query_embedding: {- format: "vector",+ format: "extensions.vector",type: "string"}},@@ -69795,42 +69795,42 @@ export default {type: "string"},{- format: "int32",+ format: "integer",in: "query",name: "p_reorder_point",required: true,type: "integer"},{- format: "int32",+ format: "integer",in: "query",name: "p_reorder_quantity",required: true,type: "integer"},{- format: "int32",+ format: "integer",in: "query",name: "p_minimum_order_quantity",required: true,type: "integer"},{- format: "int32",+ format: "integer",in: "query",name: "p_maximum_order_quantity",required: true,type: "integer"},{- format: "int32",+ format: "integer",in: "query",name: "p_order_multiple",required: true,type: "integer"},{- format: "int32",+ format: "integer",in: "query",name: "p_lot_size",required: true,@@ -69844,7 +69844,7 @@ export default {type: "number"},{- format: "int32",+ format: "integer",in: "query",name: "p_demand_accumulation_period",required: true,@@ -69886,7 +69886,7 @@ export default {schema: {properties: {p_demand_accumulation_period: {- format: "int32",+ format: "integer",type: "integer"},p_demand_accumulation_safety_stock: {@@ -69894,7 +69894,7 @@ export default {type: "number"},p_lot_size: {- format: "int32",+ format: "integer",type: "integer"},p_maximum_inventory_quantity: {@@ -69902,15 +69902,15 @@ export default {type: "number"},p_maximum_order_quantity: {- format: "int32",+ format: "integer",type: "integer"},p_minimum_order_quantity: {- format: "int32",+ format: "integer",type: "integer"},p_order_multiple: {- format: "int32",+ format: "integer",type: "integer"},p_projections: {@@ -69921,11 +69921,11 @@ export default {type: "array"},p_reorder_point: {- format: "int32",+ format: "integer",type: "integer"},p_reorder_quantity: {- format: "int32",+ format: "integer",type: "integer"},p_reordering_policy: {@@ -70431,7 +70431,7 @@ export default {type: "string"},p_index: {- format: "int32",+ format: "integer",type: "integer"},p_receipt_id: {@@ -71351,7 +71351,7 @@ export default {type: "string"},p_limit: {- format: "int32",+ format: "integer",type: "integer"},p_window: {@@ -71437,15 +71437,15 @@ export default {type: "string"},mask: {- format: "int32",+ format: "integer",type: "integer"},size: {- format: "int32",+ format: "integer",type: "integer"},step: {- format: "int32",+ format: "integer",type: "integer"}},@@ -72067,11 +72067,11 @@ export default {type: "string"},p_limit: {- format: "int32",+ format: "integer",type: "integer"},p_offset: {- format: "int32",+ format: "integer",type: "integer"},p_record_id: {@@ -73195,11 +73195,11 @@ export default {type: "string"},p_limit: {- format: "int32",+ format: "integer",type: "integer"},p_offset: {- format: "int32",+ format: "integer",type: "integer"},p_operation: {@@ -75107,7 +75107,7 @@ export default {type: "string"},size: {- format: "int32",+ format: "integer",type: "integer"}},@@ -75527,7 +75527,7 @@ export default {type: "array"},p_limit: {- format: "int32",+ format: "integer",type: "integer"},p_query: {@@ -77154,7 +77154,7 @@ export default {get: {parameters: [{- format: "vector",+ format: "extensions.vector",in: "query",name: "query_embedding",required: true,@@ -77168,7 +77168,7 @@ export default {type: "number"},{- format: "int32",+ format: "integer",in: "query",name: "match_count",required: true,@@ -77203,7 +77203,7 @@ export default {schema: {properties: {match_count: {- format: "int32",+ format: "integer",type: "integer"},match_threshold: {@@ -77215,7 +77215,7 @@ export default {type: "string"},query_embedding: {- format: "vector",+ format: "extensions.vector",type: "string"}},@@ -77825,7 +77825,7 @@ export default {type: "string"},modelSize: {- format: "int64",+ format: "bigint",type: "integer"},supplierIds: {@@ -77911,7 +77911,7 @@ export default {},quoteRevisionId: {default: 0,- format: "int32",+ format: "integer",type: "integer"},status: {@@ -78027,7 +78027,7 @@ export default {},unitPricePrecision: {default: 2,- format: "int32",+ format: "integer",type: "integer"},externalNotes: {@@ -78195,7 +78195,7 @@ export default {},quantity: {default: 1,- format: "int32",+ format: "integer",type: "integer"},companyId: {@@ -78573,7 +78573,7 @@ export default {format: "json"},sortOrder: {- format: "int32",+ format: "integer",type: "integer"},tags: {@@ -78995,17 +78995,17 @@ export default {},users: {default: 0,- format: "int32",+ format: "integer",type: "integer"},tasks: {default: 0,- format: "int32",+ format: "integer",type: "integer"},aiTokens: {default: 0,- format: "int32",+ format: "integer",type: "integer"},nextResetDatetime: {@@ -79967,7 +79967,7 @@ export default {type: "string"},sampleSize: {- format: "int32",+ format: "integer",type: "integer"},percentage: {@@ -80323,7 +80323,7 @@ export default {},sortOrder: {default: 0,- format: "int32",+ format: "integer",type: "integer"},columnOrder: {@@ -80525,11 +80525,11 @@ export default {type: "string"},rowCount: {- format: "int32",+ format: "integer",type: "integer"},sizeBytes: {- format: "int64",+ format: "bigint",type: "integer"},createdAt: {@@ -80589,7 +80589,7 @@ export default {},sortOrder: {default: 0,- format: "int32",+ format: "integer",type: "integer"},tags: {@@ -80872,7 +80872,7 @@ export default {},supplierQuoteRevisionId: {default: 0,- format: "int32",+ format: "integer",type: "integer"},quantity: {@@ -81483,7 +81483,7 @@ export default {type: "string"},hoursPerWeek: {- format: "int32",+ format: "integer",type: "integer"},abilityId: {@@ -81878,7 +81878,7 @@ export default {type: "string"},calibrationIntervalInMonths: {- format: "int32",+ format: "integer",type: "integer"},lastCalibrationDate: {@@ -82531,7 +82531,7 @@ export default {holidayYears: {properties: {year: {- format: "int32",+ format: "integer",type: "integer"},companyId: {@@ -82783,7 +82783,7 @@ export default {type: "string"},leadTime: {- format: "int32",+ format: "integer",type: "integer"}},@@ -82829,7 +82829,7 @@ export default {},minimumOrderQuantity: {default: 1,- format: "int32",+ format: "integer",type: "integer"},conversionFactor: {@@ -82906,7 +82906,7 @@ export default {},hoursPerWeek: {default: 0,- format: "int32",+ format: "integer",type: "integer"},abilityId: {@@ -83147,7 +83147,7 @@ export default {},index: {default: 0,- format: "int32",+ format: "integer",type: "integer"}},@@ -83571,7 +83571,7 @@ export default {type: "string"},modelSize: {- format: "int64",+ format: "bigint",type: "integer"},salesOrderReadableId: {@@ -83882,7 +83882,7 @@ export default {type: "string"},entryNumber: {- format: "int32",+ format: "integer",type: "integer"},postingDate: {@@ -84113,7 +84113,7 @@ export default {},sortOrder: {default: 0,- format: "int32",+ format: "integer",type: "integer"},tags: {@@ -84344,7 +84344,7 @@ export default {type: "string"},orderCount: {- format: "int64",+ format: "bigint",type: "integer"},phone: {@@ -84888,17 +84888,17 @@ export default {},tasksLimit: {default: 10000,- format: "int32",+ format: "integer",type: "integer"},aiTokensLimit: {default: 1000000,- format: "int32",+ format: "integer",type: "integer"},stripeTrialPeriodDays: {default: 7,- format: "int32",+ format: "integer",type: "integer"},public: {@@ -84960,7 +84960,7 @@ export default {},priority: {default: 0,- format: "int32",+ format: "integer",type: "integer"},minQuantity: {@@ -85156,7 +85156,7 @@ export default {type: "string"},quantity: {- format: "int32",+ format: "integer",type: "integer"},locationId: {@@ -85276,7 +85276,7 @@ export default {},requestCount: {default: 1,- format: "int32",+ format: "integer",type: "integer"}},@@ -85636,7 +85636,7 @@ export default {},revisionId: {default: 0,- format: "int32",+ format: "integer",type: "integer"},status: {@@ -85865,7 +85865,7 @@ export default {properties: {id: {description: "Note:\nThis is a Primary Key.<pk/>",- format: "int32",+ format: "integer",type: "integer"},trainingAssignmentId: {@@ -86244,7 +86244,7 @@ export default {},revisionId: {default: 0,- format: "int32",+ format: "integer",type: "integer"},status: {@@ -86423,7 +86423,7 @@ export default {},quantity: {default: 1,- format: "int32",+ format: "integer",type: "integer"},companyId: {@@ -86832,7 +86832,7 @@ export default {type: "string"},revisionId: {- format: "int32",+ format: "integer",type: "integer"},status: {@@ -87582,7 +87582,7 @@ export default {type: "string"},leadTime: {- format: "int32",+ format: "integer",type: "integer"},locationId: {@@ -87662,11 +87662,11 @@ export default {type: "number"},sampleSize: {- format: "int32",+ format: "integer",type: "integer"},defectsFound: {- format: "int32",+ format: "integer",type: "integer"},outcome: {@@ -87794,17 +87794,17 @@ export default {},next: {default: 1,- format: "int32",+ format: "integer",type: "integer"},size: {default: 5,- format: "int32",+ format: "integer",type: "integer"},step: {default: 1,- format: "int32",+ format: "integer",type: "integer"},companyId: {@@ -89280,7 +89280,7 @@ export default {type: "number"},lineCount: {- format: "int32",+ format: "integer",type: "integer"}},@@ -89875,7 +89875,7 @@ export default {type: "string"},revisionId: {- format: "int32",+ format: "integer",type: "integer"},status: {@@ -89950,7 +89950,7 @@ export default {type: "string"},supplierCount: {- format: "int64",+ format: "bigint",type: "integer"},supplierIds: {@@ -90332,7 +90332,7 @@ export default {type: "string"},duration: {- format: "int32",+ format: "integer",type: "integer"},nonConformanceId: {@@ -90451,7 +90451,7 @@ export default {type: "string"},leadTime: {- format: "int32",+ format: "integer",type: "integer"},locationId: {@@ -91468,7 +91468,7 @@ export default {type: "number"},decimalPlaces: {- format: "int32",+ format: "integer",type: "integer"},active: {@@ -91631,7 +91631,7 @@ export default {type: "string"},size: {- format: "int32",+ format: "integer",type: "integer"},extension: {@@ -91831,7 +91831,7 @@ export default {type: "string"},supplierQuoteRevisionId: {- format: "int32",+ format: "integer",type: "integer"},quantity: {@@ -91996,7 +91996,7 @@ export default {},hoursPerWeek: {default: 0,- format: "int32",+ format: "integer",type: "integer"},active: {@@ -92075,7 +92075,7 @@ export default {type: "string"},quantity: {- format: "int32",+ format: "integer",type: "integer"},unitOfMeasureCode: {@@ -92338,7 +92338,7 @@ export default {},sortOrder: {default: 1,- format: "int32",+ format: "integer",type: "integer"},userAttributeCategoryId: {@@ -92350,7 +92350,7 @@ export default {attributeDataTypeId: {description:"Note:\nThis is a Foreign Key to `attributeDataType.id`.<fk table='attributeDataType' column='id'/>",- format: "int32",+ format: "integer",type: "integer"},listOptions: {@@ -93151,11 +93151,11 @@ export default {type: "string"},orderCount: {- format: "int64",+ format: "bigint",type: "integer"},partCount: {- format: "int64",+ format: "bigint",type: "integer"},phone: {@@ -93863,7 +93863,7 @@ export default {type: "string"},rn: {- format: "int64",+ format: "bigint",type: "integer"}},@@ -94281,7 +94281,7 @@ export default {type: "string"},duration: {- format: "int32",+ format: "integer",type: "integer"},companyId: {@@ -94326,7 +94326,7 @@ export default {type: "string"},revisionId: {- format: "int32",+ format: "integer",type: "integer"},quotedDate: {@@ -94857,7 +94857,7 @@ export default {type: "boolean"},hoursPerWeek: {- format: "int32",+ format: "integer",type: "integer"},companyId: {@@ -94916,7 +94916,7 @@ export default {type: "string"},revisionId: {- format: "int32",+ format: "integer",type: "integer"},dueDate: {@@ -95101,11 +95101,11 @@ export default {type: "string"},lines: {- format: "int64",+ format: "bigint",type: "integer"},completedLines: {- format: "int64",+ format: "bigint",type: "integer"},shippingCost: {@@ -95268,11 +95268,11 @@ export default {type: "string"},severity: {- format: "int32",+ format: "integer",type: "integer"},likelihood: {- format: "int32",+ format: "integer",type: "integer"},itemId: {@@ -95489,7 +95489,7 @@ export default {properties: {id: {description: "Note:\nThis is a Primary Key.<pk/>",- format: "int32",+ format: "integer",type: "integer"},name: {@@ -95693,15 +95693,15 @@ export default {type: "string"},sampleSize: {- format: "int32",+ format: "integer",type: "integer"},acceptanceNumber: {- format: "int32",+ format: "integer",type: "integer"},rejectionNumber: {- format: "int32",+ format: "integer",type: "integer"},aql: {@@ -95792,7 +95792,7 @@ export default {properties: {id: {description: "Note:\nThis is a Primary Key.<pk/>",- format: "int32",+ format: "integer",type: "integer"},groupId: {@@ -96479,7 +96479,7 @@ export default {},revisionId: {default: 0,- format: "int32",+ format: "integer",type: "integer"},quotedDate: {@@ -96970,7 +96970,7 @@ export default {type: "string"},duration: {- format: "int32",+ format: "integer",type: "integer"},nonConformanceId: {@@ -97465,7 +97465,7 @@ export default {},revisionId: {default: 0,- format: "int32",+ format: "integer",type: "integer"},status: {@@ -97892,7 +97892,7 @@ export default {type: "string"},modelSize: {- format: "int64",+ format: "bigint",type: "integer"},unitCost: {@@ -98059,17 +98059,17 @@ export default {},tasksLimit: {default: 10000,- format: "int32",+ format: "integer",type: "integer"},aiTokensLimit: {default: 1000000,- format: "int32",+ format: "integer",type: "integer"},usersLimit: {default: 10,- format: "int32",+ format: "integer",type: "integer"},subscriptionStartDate: {@@ -98311,7 +98311,7 @@ export default {type: "string"},modelSize: {- format: "int64",+ format: "bigint",type: "integer"},thumbnailPath: {@@ -98361,7 +98361,7 @@ export default {},revisionId: {default: 0,- format: "int32",+ format: "integer",type: "integer"},status: {@@ -98570,7 +98570,7 @@ export default {type: "string"},modelSize: {- format: "int64",+ format: "bigint",type: "integer"},supplierIds: {@@ -98657,7 +98657,7 @@ export default {},decimalPlaces: {default: 2,- format: "int32",+ format: "integer",type: "integer"},active: {@@ -98843,7 +98843,7 @@ export default {type: "string"},modelSize: {- format: "int64",+ format: "bigint",type: "integer"},supplierIds: {@@ -98949,7 +98949,7 @@ export default {type: "string"},size: {- format: "int64",+ format: "bigint",type: "integer"},modelPath: {@@ -99018,7 +99018,7 @@ export default {type: "string"},entryNumber: {- format: "int32",+ format: "integer",type: "integer"},postingDate: {@@ -99375,7 +99375,7 @@ export default {},lotSize: {default: 0,- format: "int32",+ format: "integer",type: "integer"},companyId: {@@ -99422,7 +99422,7 @@ export default {},leadTime: {default: 7,- format: "int32",+ format: "integer",type: "integer"}},@@ -99559,7 +99559,7 @@ export default {type: "string"},modelSize: {- format: "int64",+ format: "bigint",type: "integer"},supplierIds: {@@ -99911,7 +99911,7 @@ export default {},quantity: {default: 1,- format: "int32",+ format: "integer",type: "integer"},companyId: {@@ -99998,7 +99998,7 @@ export default {type: "string"},estimatedDuration: {- format: "int32",+ format: "integer",type: "integer"},active: {@@ -100110,7 +100110,7 @@ export default {type: "string"},quoteRevisionId: {- format: "int32",+ format: "integer",type: "integer"},status: {@@ -100221,7 +100221,7 @@ export default {type: "array"},unitPricePrecision: {- format: "int32",+ format: "integer",type: "integer"},externalNotes: {@@ -100255,7 +100255,7 @@ export default {type: "string"},modelSize: {- format: "int64",+ format: "bigint",type: "integer"},unitCost: {@@ -100685,7 +100685,7 @@ export default {properties: {id: {description: "Note:\nThis is a Primary Key.<pk/>",- format: "int32",+ format: "integer",type: "integer"},label: {@@ -101316,7 +101316,7 @@ export default {type: "string"},quantity: {- format: "int32",+ format: "integer",type: "integer"},unitOfMeasureCode: {@@ -103037,7 +103037,7 @@ export default {type: "string"},size: {- format: "int32",+ format: "integer",type: "integer"},extension: {@@ -103321,12 +103321,12 @@ export default {},daysDue: {default: 0,- format: "int32",+ format: "integer",type: "integer"},daysDiscount: {default: 0,- format: "int32",+ format: "integer",type: "integer"},discountPercentage: {@@ -103435,7 +103435,7 @@ export default {},demandAccumulationPeriod: {default: 4,- format: "int32",+ format: "integer",type: "integer"},demandAccumulationIncludesInventory: {@@ -103445,27 +103445,27 @@ export default {},reorderPoint: {default: 0,- format: "int32",+ format: "integer",type: "integer"},reorderQuantity: {default: 0,- format: "int32",+ format: "integer",type: "integer"},minimumOrderQuantity: {default: 0,- format: "int32",+ format: "integer",type: "integer"},maximumOrderQuantity: {default: 0,- format: "int32",+ format: "integer",type: "integer"},orderMultiple: {default: 1,- format: "int32",+ format: "integer",type: "integer"},companyId: {@@ -103636,7 +103636,7 @@ export default {properties: {id: {description: "Note:\nThis is a Primary Key.<pk/>",- format: "int32",+ format: "integer",type: "integer"},userId: {@@ -103818,7 +103818,7 @@ export default {type: "string"},revisionId: {- format: "int32",+ format: "integer",type: "integer"},status: {@@ -104726,7 +104726,7 @@ export default {type: "string"},modelSize: {- format: "int64",+ format: "bigint",type: "integer"},unitCost: {@@ -105179,7 +105179,7 @@ export default {},rateLimit: {default: 60,- format: "int32",+ format: "integer",type: "integer"},rateLimitWindow: {@@ -105650,7 +105650,7 @@ export default {type: "string"},revisionId: {- format: "int32",+ format: "integer",type: "integer"},status: {@@ -105957,7 +105957,7 @@ export default {type: "string"},leadTime: {- format: "int32",+ format: "integer",type: "integer"}},@@ -106544,7 +106544,7 @@ export default {type: "string"},entryNumber: {- format: "int32",+ format: "integer",type: "integer"},postingDate: {@@ -107015,7 +107015,7 @@ export default {type: "string"},estimatedDuration: {- format: "int32",+ format: "integer",type: "integer"},active: {@@ -107216,7 +107216,7 @@ export default {type: "string"},quoteRevisionId: {- format: "int32",+ format: "integer",type: "integer"},status: {@@ -107327,7 +107327,7 @@ export default {type: "array"},unitPricePrecision: {- format: "int32",+ format: "integer",type: "integer"},externalNotes: {@@ -107361,7 +107361,7 @@ export default {type: "string"},modelSize: {- format: "int64",+ format: "bigint",type: "integer"},unitCost: {@@ -107429,7 +107429,7 @@ export default {type: "string"},year: {- format: "int32",+ format: "integer",type: "integer"},companyId: {@@ -107510,7 +107510,7 @@ export default {type: "string"},duration: {- format: "int32",+ format: "integer",type: "integer"},employeeId: {@@ -107737,7 +107737,7 @@ export default {},successCount: {default: 0,- format: "int64",+ format: "bigint",type: "integer"},lastSuccess: {@@ -107746,7 +107746,7 @@ export default {},errorCount: {default: 0,- format: "int64",+ format: "bigint",type: "integer"},lastError: {@@ -108075,7 +108075,7 @@ export default {},calibrationIntervalInMonths: {default: 6,- format: "int32",+ format: "integer",type: "integer"},lastCalibrationDate: {@@ -108176,11 +108176,11 @@ export default {type: "string"},severity: {- format: "int32",+ format: "integer",type: "integer"},likelihood: {- format: "int32",+ format: "integer",type: "integer"},itemId: {@@ -108532,7 +108532,7 @@ export default {type: "string"},quantity: {- format: "int32",+ format: "integer",type: "integer"},unitOfMeasureCode: {@@ -108828,7 +108828,7 @@ export default {},sortOrder: {default: 1,- format: "int32",+ format: "integer",type: "integer"},table: {@@ -108840,7 +108840,7 @@ export default {dataTypeId: {description:"Note:\nThis is a Foreign Key to `attributeDataType.id`.<fk table='attributeDataType' column='id'/>",- format: "int32",+ format: "integer",type: "integer"},listOptions: {@@ -108974,7 +108974,7 @@ export default {},revisionId: {default: 0,- format: "int32",+ format: "integer",type: "integer"},dueDate: {@@ -109555,7 +109555,7 @@ export default {},maintenanceAdvanceDays: {default: 3,- format: "int32",+ format: "integer",type: "integer"},maintenanceDispatchNotificationGroup: {@@ -109638,7 +109638,7 @@ export default {},qualityIssueTarget: {default: 20,- format: "int32",+ format: "integer",type: "integer"},consoleEnabled: {@@ -109792,7 +109792,7 @@ export default {type: "number"},escalationDays: {- format: "int32",+ format: "integer",type: "integer"},companyId: {@@ -109942,7 +109942,7 @@ export default {type: "string"},depth: {- format: "int32",+ format: "integer",type: "integer"},ancestorPath: {@@ -110003,7 +110003,7 @@ export default {type: "string"},quantity: {- format: "int32",+ format: "integer",type: "integer"},locationId: {@@ -146874,6 +146874,6 @@ export default {},externalDocs: {description: "PostgREST Documentation",- url: "https://postgrest.org/en/v14/references/api.html"+ url: "https://postgrest.org/en/v13/references/api.html"}};diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex bd259d3717..d338027d29 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -56008,21 +56008,21 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -56579,14 +56579,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/config.toml b/packages/database/supabase/config.tomlindex f27d139ea2..40fd164bcf 100644--- a/packages/database/supabase/config.toml+++ b/packages/database/supabase/config.toml@@ -1,3 +1,9 @@+# NOTE: For local dev, only `project_id` and `[functions.*]` sections are+# authoritative. Runtime services (db/api/auth/storage/studio/inbucket/realtime)+# are managed by docker-compose.dev.yml (see scripts/dev/cli.ts). The other+# sections here are kept for `supabase functions deploy` and reference parity+# with what `supabase start` used to provide.+# A string used to distinguish different Supabase projects on the same host. Defaults to the# working directory name when running `supabase init`.project_id = "carbon-database"diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex bd259d3717..d338027d29 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -56008,21 +56008,21 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -56579,14 +56579,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/dev/bin/crbn b/packages/dev/bin/crbnnew file mode 100755index 0000000000..6e287ace38--- /dev/null+++ b/packages/dev/bin/crbn@@ -0,0 +1,384 @@+#!/usr/bin/env bash+# Carbon dev CLI router. Bash for `checkout` (needs eval'd cd in parent+# shell); the rest delegates to `tsx packages/dev/src/main.ts` (citty).+#+# Setup once: ./setup.sh+# Then: crbn <command>++set -euo pipefail++# ---------------------------------------------------------------------------+# Output helpers (colors when stderr is a TTY).+# All listings/errors go to stderr so they never get eval'd by the `crbn()`+# shell function from setup.sh, which only consumes stdout.+# ---------------------------------------------------------------------------++if [[ -t 2 ]] && command -v tput >/dev/null 2>&1 && [[ "$(tput colors 2>/dev/null || echo 0)" -ge 8 ]]; then+ C_BOLD=$(tput bold); C_DIM=$(tput dim); C_RESET=$(tput sgr0)+ C_GREEN=$(tput setaf 2); C_YELLOW=$(tput setaf 3)+ C_CYAN=$(tput setaf 6); C_RED=$(tput setaf 1)+else+ C_BOLD=""; C_DIM=""; C_RESET=""+ C_GREEN=""; C_YELLOW=""; C_CYAN=""; C_RED=""+fi++ok() { printf '%s✓%s %s\n' "$C_GREEN" "$C_RESET" "$*" >&2; }+info() { printf '%s•%s %s\n' "$C_CYAN" "$C_RESET" "$*" >&2; }+warn() { printf '%s!%s %s\n' "$C_YELLOW" "$C_RESET" "$*" >&2; }+fail() { printf '%s✗%s %s\n' "$C_RED" "$C_RESET" "$*" >&2; }+hdr() { printf '\n%s%s%s\n' "$C_BOLD" "$*" "$C_RESET" >&2; }++# ---------------------------------------------------------------------------+# Repo discovery+# ---------------------------------------------------------------------------++repo_root() {+ # Each linked worktree has its own --show-toplevel. We want the *main*+ # checkout (where packages/dev lives), which is `--git-common-dir`'s parent.+ local common_dir+ common_dir=$(git rev-parse --git-common-dir 2>/dev/null) || {+ echo "crbn: not inside a git repository" >&2+ return 1+ }+ if [[ "$common_dir" != /* ]]; then+ common_dir="$PWD/$common_dir"+ fi+ dirname "$common_dir"+}++slugify_branch() {+ # Mirrors packages/dev/src/lib/slug.ts:slugify — lowercase, replace+ # non-[a-z0-9-] runs with `-`, trim/collapse `-`.+ printf '%s' "$1" \+ | tr '[:upper:]' '[:lower:]' \+ | sed -E 's/[^a-z0-9-]+/-/g; s/^-+|-+$//g; s/-+/-/g'+}++delegate_ts() {+ # Run citty entry through tsx. Prefer the locally-installed binary in the+ # main checkout (single process under the shell — keeps Ctrl+C / SIGTERM+ # semantics clean for the `crbn up` → graceful-`down` teardown flow).+ # Falls back to `pnpx tsx` for fresh checkouts where node_modules isn't+ # populated yet (e.g. immediately after `crbn checkout`).+ local root+ root="$(repo_root)"+ if [[ -x "$root/node_modules/.bin/tsx" ]]; then+ exec "$root/node_modules/.bin/tsx" "$root/packages/dev/src/main.ts" "$@"+ fi+ exec pnpx tsx "$root/packages/dev/src/main.ts" "$@"+}++# ---------------------------------------------------------------------------+# checkout <name> [-b] [--path PATH] [--base REF] [--up]+#+# Unified verb: jumps into an existing worktree, or creates one when needed.+# Mirrors `git checkout` semantics:+#+# crbn checkout <name> Existing branch → worktree (create if missing,+# cd into it). Falls back to `origin/<name>`+# (auto-fetches) when no local branch exists.+# No match → error.+#+# crbn checkout -b <name> Branch must NOT exist. Creates new branch+# from --base (default HEAD) + worktree.+#+# All progress logs go to stderr; the only stdout is `cd '<path>'` for the+# shell function in setup.sh to eval. Pass --up to chain `crbn up` after+# creation (bypasses the eval-wrapper; user's cwd doesn't change but the+# stack starts in the new worktree).+# ---------------------------------------------------------------------------++checkout_usage() {+ cat >&2 <<'USAGE'+Usage: crbn checkout <name> [--path PATH] [--up]+ crbn checkout -b <name> [--base REF] [--path PATH] [--up]+ crbn checkout <pr-number> [--up]++ Without -b: resolve <name> as an existing branch (local first, then+ origin/<name> with auto-fetch). If a worktree on that branch exists,+ cd into it. Otherwise create one + cd.++ With -b: create a new branch <name> from --base (default HEAD), add a+ worktree, cd in. Fails if the branch already exists.++ PR shortcut: a purely-numeric <name> is treated as a GitHub PR number.+ Fetches `pull/<num>/head` from origin, materializes a local branch+ `pr-<num>` + worktree. Works for fork PRs too. If `gh` is on PATH it's+ used for a nicer banner; not required.++ --path PATH Override the default worktree directory.+ --base REF (with -b) base ref for the new branch. Default: HEAD.+ --up After creation, exec `crbn up` in the new worktree.+USAGE+}++# Find an existing worktree's path by branch. Empty stdout if not found.+worktree_path_for_branch() {+ local query="$1" current_path="" branch="" line=""+ while IFS= read -r line; do+ if [[ "$line" == worktree\ * ]]; then+ current_path="${line#worktree }"+ elif [[ "$line" == branch\ refs/heads/* ]]; then+ branch="${line#branch refs/heads/}"+ if [[ "$branch" == "$query" ]]; then+ printf '%s\n' "$current_path"+ return 0+ fi+ fi+ done < <(git worktree list --porcelain)+}++cmd_checkout() {+ local name="" custom_path="" base_ref="HEAD" do_up=0 create_new=0+ while (( $# )); do+ case "$1" in+ -b) create_new=1; shift ;;+ --path) custom_path="${2:-}"; shift 2 ;;+ --path=*) custom_path="${1#*=}"; shift ;;+ --base) base_ref="${2:-}"; shift 2 ;;+ --base=*) base_ref="${1#*=}"; shift ;;+ --up) do_up=1; shift ;;+ -h|--help) checkout_usage; exit 0 ;;+ --) shift; break ;;+ -*) fail "unknown flag $1"; exit 2 ;;+ *)+ if [[ -z "$name" ]]; then+ name="$1"+ else+ fail "extra arg $1"+ exit 2+ fi+ shift+ ;;+ esac+ done+ if [[ -z "$name" ]]; then+ fail "branch required"+ checkout_usage+ exit 2+ fi++ # PR shortcut: bare numeric arg → fetch GitHub PR head ref + worktree it.+ if [[ "$name" =~ ^[0-9]+$ ]] && (( create_new == 0 )); then+ if [[ -n "$custom_path" || "$base_ref" != "HEAD" ]]; then+ warn "--path/--base ignored for PR checkout"+ fi+ _checkout_pr "$name" "$do_up"+ return $?+ fi++ local root parent base target+ root="$(repo_root)"+ parent="$(dirname "$root")"+ base="$(basename "$root")"+ base="${base%%-[a-z0-9-]*}" # strip prior `-<slug>` suffix+ if [[ -n "$custom_path" ]]; then+ target="$custom_path"+ [[ "$target" = /* ]] || target="$PWD/$target"+ else+ target="$parent/${base}-$(slugify_branch "$name")"+ fi++ local local_exists=0 origin_exists=0 existing_worktree=""+ if git -C "$root" show-ref --verify --quiet "refs/heads/$name"; then+ local_exists=1+ fi+ existing_worktree="$(worktree_path_for_branch "$name")"++ if (( create_new )); then+ # -b path: branch must not exist.+ if (( local_exists )); then+ fail "branch '$name' already exists locally — drop -b to use it"+ exit 1+ fi+ if [[ -e "$target" ]]; then+ fail "target path already exists: $target"+ exit 1+ fi+ info "creating branch '$name' from ${C_BOLD}${base_ref}${C_RESET}"+ git -C "$root" worktree add -b "$name" "$target" "$base_ref" >&2+ ok "worktree at $target"+ do_post_create "$target"+ printf "cd %q\n" "$target"+ maybe_up "$target" "$do_up"+ return 0+ fi++ # No -b: fast-path if the branch already has a worktree.+ if [[ -n "$existing_worktree" ]]; then+ info "worktree exists at ${C_DIM}${existing_worktree}${C_RESET}"+ printf "cd %q\n" "$existing_worktree"+ maybe_up "$existing_worktree" "$do_up"+ return 0+ fi++ # Need to materialize a worktree. Resolve the ref locally or via origin.+ local resolved=""+ if (( local_exists )); then+ resolved="$name"+ else+ info "fetching ${C_BOLD}origin/${name}${C_RESET}"+ if git -C "$root" fetch origin "$name" --quiet 2>/dev/null \+ && git -C "$root" show-ref --verify --quiet "refs/remotes/origin/$name"; then+ git -C "$root" branch --track "$name" "origin/$name" >&2+ resolved="$name"+ origin_exists=1+ else+ fail "branch '$name' not found locally or on origin (use -b to create)"+ exit 1+ fi+ fi+ : "$origin_exists" # tracked for clarity; not used after this++ if [[ -e "$target" ]]; then+ fail "target path already exists: $target"+ exit 1+ fi++ info "git worktree add ${C_DIM}${target}${C_RESET}"+ git -C "$root" worktree add "$target" "$resolved" >&2+ ok "worktree at $target"+ do_post_create "$target"+ printf "cd %q\n" "$target"+ maybe_up "$target" "$do_up"+}++# Fetch a GitHub PR head into a local `pr-<num>` branch and worktree it.+# Same stdout contract as cmd_checkout (only `cd '<path>'` goes to stdout).+_checkout_pr() {+ local num="$1" do_up="$2"+ local root parent base target branch+ root="$(repo_root)"+ parent="$(dirname "$root")"+ base="$(basename "$root")"+ base="${base%%-[a-z0-9-]*}"+ branch="pr-${num}"+ target="$parent/${base}-${branch}"++ # Fast-path: worktree already exists for this PR.+ local existing+ existing="$(worktree_path_for_branch "$branch")"+ if [[ -n "$existing" ]]; then+ info "worktree for PR #${num} exists at ${C_DIM}${existing}${C_RESET}"+ printf "cd %q\n" "$existing"+ maybe_up "$existing" "$do_up"+ return 0+ fi++ # Optional banner via gh (purely cosmetic — pure-git path works without it).+ local metadata="" title="" head_ref=""+ if command -v gh >/dev/null 2>&1; then+ if metadata=$(gh pr view "$num" --json headRefName,title \+ -q '.headRefName + "\t" + .title' 2>/dev/null); then+ head_ref="${metadata%%$'\t'*}"+ title="${metadata#*$'\t'}"+ info "PR #${num} — ${C_BOLD}${title}${C_RESET} (${C_DIM}${head_ref}${C_RESET})"+ fi+ fi+ if [[ -z "$metadata" ]]; then+ info "fetching PR #${num} from ${C_BOLD}origin${C_RESET}"+ fi++ # If the local branch already exists, reuse it instead of re-fetching.+ # Keeps `pr-<num>` stable across re-runs and avoids accidental overwrites+ # of in-progress local edits on top of the PR ref.+ if git -C "$root" show-ref --verify --quiet "refs/heads/${branch}"; then+ info "local branch '${branch}' exists — skipping fetch"+ else+ if ! git -C "$root" fetch origin "pull/${num}/head:${branch}" --quiet; then+ fail "could not fetch PR #${num} from origin (is the number correct? is the PR open on this repo?)"+ exit 1+ fi+ fi++ if [[ -e "$target" ]]; then+ fail "target path already exists: $target"+ exit 1+ fi++ info "git worktree add ${C_DIM}${target}${C_RESET}"+ git -C "$root" worktree add "$target" "$branch" >&2+ ok "worktree at $target"+ do_post_create "$target"+ printf "cd %q\n" "$target"+ maybe_up "$target" "$do_up"+}++# crbn copy inside the new worktree (so it reads package.json#crbn.copy from+# the main checkout via --git-common-dir). All output goes to stderr to keep+# stdout reserved for the eval'd `cd` line.+do_post_create() {+ local target="$1"+ if ! ( cd "$target" && delegate_ts copy >&2 ); then+ warn "copy step failed (worktree was still created)"+ fi+}++# Replace process with `crbn up` cd'd into the new worktree. Caller's shell+# stays at original cwd; on Ctrl+C they're back where they started.+maybe_up() {+ local target="$1" enabled="$2"+ if (( enabled )); then+ info "starting stack in $target"+ cd "$target"+ delegate_ts up+ fi+}++# ---------------------------------------------------------------------------+# Top-level help+# ---------------------------------------------------------------------------++print_help() {+ cat <<'USAGE'+crbn — Carbon dev CLI++ Worktrees:+ crbn checkout <branch> Switch into worktree for <branch>.+ Creates one if missing (auto-fetches+ from origin if not local).+ crbn checkout -b <branch> Create new branch + worktree from+ --base (default HEAD).+ crbn checkout <pr-number> Fetch the PR head from GitHub into a+ new `pr-<num>` branch + worktree.+ crbn new Interactive: pick branch + base ref,+ create worktree, optionally copy .env.+ crbn list Show all worktrees with stack status.+ crbn remove Pick a worktree to delete (with stack+ teardown).+ crbn copy Sync files (package.json#crbn.copy)+ from main checkout into cwd.++ Stack:+ crbn up Boot compose stack + apps.+ crbn down Stop stack (volumes preserved).+ crbn reset Wipe volumes + redis, then `up`.+ crbn status Port assignment + container health.++USAGE+}++# ---------------------------------------------------------------------------+# Dispatch+# ---------------------------------------------------------------------------++cmd="${1:-}"+[[ $# -gt 0 ]] && shift || true++case "$cmd" in+ ""|help|-h|--help)+ print_help+ ;;+ checkout)+ cmd_checkout "$@"+ ;;+ copy|up|down|reset|status|new|list|remove|complete)+ delegate_ts "$cmd" "$@"+ ;;+ *)+ echo "crbn: unknown command '$cmd'" >&2+ echo >&2+ print_help >&2+ exit 2+ ;;+esacdiff --git a/packages/dev/docker/edge-main/index.ts b/packages/dev/docker/edge-main/index.tsnew file mode 100644index 0000000000..6451b4d057--- /dev/null+++ b/packages/dev/docker/edge-main/index.ts@@ -0,0 +1,38 @@+// Edge runtime dispatcher. Routes /functions/v1/<name>/* to <name>/index.ts.+// Required by supabase/edge-runtime when started with --main-service.++import { STATUS_CODE } from "https://deno.land/[email protected]/http/status.ts";++Deno.serve(async (req: Request) => {+ const url = new URL(req.url);+ const segments = url.pathname.split("/").filter(Boolean);+ const fnName = segments[0];+ if (!fnName) {+ return new Response("Not found", { status: STATUS_CODE.NotFound });+ }++ const servicePath = `/home/deno/functions/${fnName}`;++ try {+ // @ts-ignore EdgeRuntime is provided by the supabase/edge-runtime image.+ const worker = await EdgeRuntime.userWorkers.create({+ servicePath,+ memoryLimitMb: 512,+ workerTimeoutMs: 5 * 60 * 1000,+ noModuleCache: false,+ envVars: Object.entries(Deno.env.toObject()),+ });+ return await worker.fetch(req);+ } catch (err) {+ return new Response(+ JSON.stringify({+ error: err instanceof Error ? err.message : String(err),+ function: fnName,+ }),+ {+ status: STATUS_CODE.InternalServerError,+ headers: { "content-type": "application/json" },+ }+ );+ }+});diff --git a/packages/dev/docker/init.sql b/packages/dev/docker/init.sqlnew file mode 100644index 0000000000..c59303c4a8--- /dev/null+++ b/packages/dev/docker/init.sql@@ -0,0 +1,14 @@+-- Set every supabase service role's password to "postgres" so:+-- * cli.ts bootstrap connects as supabase_admin via host TCP+-- * gotrue/storage/postgrest/realtime authenticate without per-role secrets+-- Runs as the image's bundled superuser during first postgres init+-- (mounted to /docker-entrypoint-initdb.d/init-scripts/).++ALTER USER supabase_admin WITH PASSWORD 'postgres';+ALTER USER supabase_auth_admin WITH PASSWORD 'postgres';+ALTER USER supabase_storage_admin WITH PASSWORD 'postgres';+ALTER USER authenticator WITH PASSWORD 'postgres';++GRANT anon, authenticated, service_role TO authenticator;++CREATE SCHEMA IF NOT EXISTS _realtime AUTHORIZATION supabase_admin;diff --git a/packages/dev/docker/kong.yml b/packages/dev/docker/kong.ymlnew file mode 100644index 0000000000..3b77d18398--- /dev/null+++ b/packages/dev/docker/kong.yml@@ -0,0 +1,107 @@+_format_version: "2.1"+_transform: true++###+# Routes the public API gateway (kong) to the right Supabase service.+# Mirrors supabase/docker/volumes/api/kong.yml structure.+###++services:+ - name: auth-v1-open+ url: http://gotrue:9999/verify+ routes:+ - name: auth-v1-open+ strip_path: true+ paths:+ - /auth/v1/verify+ plugins:+ - name: cors++ - name: auth-v1-open-callback+ url: http://gotrue:9999/callback+ routes:+ - name: auth-v1-open-callback+ strip_path: true+ paths:+ - /auth/v1/callback+ plugins:+ - name: cors++ - name: auth-v1-open-authorize+ url: http://gotrue:9999/authorize+ routes:+ - name: auth-v1-open-authorize+ strip_path: true+ paths:+ - /auth/v1/authorize+ plugins:+ - name: cors++ - name: auth-v1+ url: http://gotrue:9999/+ routes:+ - name: auth-v1-all+ strip_path: true+ paths:+ - /auth/v1/+ plugins:+ - name: cors++ - name: rest-v1+ url: http://postgrest:3000/+ routes:+ - name: rest-v1-all+ strip_path: true+ paths:+ - /rest/v1/+ plugins:+ - name: cors++ - name: realtime-v1-ws+ url: http://realtime:4000/socket+ protocol: ws+ routes:+ - name: realtime-v1-ws+ strip_path: true+ paths:+ - /realtime/v1/++ - name: realtime-v1-rest+ url: http://realtime:4000/api+ routes:+ - name: realtime-v1-rest+ strip_path: true+ paths:+ - /realtime/v1/api+ plugins:+ - name: cors++ - name: storage-v1+ url: http://storage:5000/+ routes:+ - name: storage-v1-all+ strip_path: true+ paths:+ - /storage/v1/+ plugins:+ - name: cors++ - name: functions-v1+ url: http://edge-runtime:9000/+ routes:+ - name: functions-v1-all+ strip_path: true+ paths:+ - /functions/v1/+ plugins:+ - name: cors++ - name: meta+ url: http://meta:8080/+ routes:+ - name: meta-all+ strip_path: true+ paths:+ - /pg/+ plugins:+ - name: corsdiff --git a/packages/dev/package.json b/packages/dev/package.jsonnew file mode 100644index 0000000000..85f52fc750--- /dev/null+++ b/packages/dev/package.json@@ -0,0 +1,30 @@+{+ "name": "@carbon/dev",+ "private": true,+ "version": "0.0.0",+ "type": "module",+ "bin": {+ "crbn": "./bin/crbn"+ },+ "scripts": {+ "clean": "rimraf node_modules .turbo",+ "lint": "biome lint --write"+ },+ "dependencies": {+ "@bomb.sh/tab": "^0.0.15",+ "@clack/prompts": "^1.3.0",+ "citty": "^0.1.6",+ "cli-table3": "^0.6.5",+ "dotenv": "16.3.1",+ "execa": "^8.0.1",+ "get-port-please": "^3.2.0",+ "picocolors": "^1.1.1"+ },+ "devDependencies": {+ "@carbon/config": "*",+ "@types/node": "20.19.39",+ "rimraf": "5.0.10",+ "tsx": "4.21.0",+ "typescript": "5.8.3"+ }+}diff --git a/packages/dev/src/commands/copy.ts b/packages/dev/src/commands/copy.tsnew file mode 100644index 0000000000..f80864bc69--- /dev/null+++ b/packages/dev/src/commands/copy.ts@@ -0,0 +1,54 @@+import { copyFileSync, existsSync, readFileSync } from "node:fs";+import { join } from "node:path";+import { intro, log, outro } from "@clack/prompts";+import pc from "picocolors";+import { mainCheckoutRoot } from "../lib/git.js";++const DEFAULT_INCLUDES = [".env"];++// Copy files listed in package.json#crbn.copy from main checkout into cwd.+export async function copy() {+ intro("Carbon · copy");++ const cwd = process.cwd();+ const mainRoot = await mainCheckoutRoot();+ if (mainRoot === cwd) {+ log.warn("already in main checkout — nothing to copy");+ outro("");+ return;+ }++ const includes = readIncludes(mainRoot);+ let copied = 0;+ for (const rel of includes) {+ const src = join(mainRoot, rel);+ const dest = join(cwd, rel);+ if (!existsSync(src)) {+ log.warn(`${pc.dim(rel)} missing in main checkout — skipped`);+ continue;+ }+ copyFileSync(src, dest);+ log.info(`${pc.green("✓")} ${rel}`);+ copied++;+ }++ outro(+ `${copied} file${copied === 1 ? "" : "s"} copied from ${pc.dim(mainRoot)}`+ );+}++function readIncludes(mainRoot: string): string[] {+ const pkgPath = join(mainRoot, "package.json");+ if (!existsSync(pkgPath)) return DEFAULT_INCLUDES;+ try {+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8")) as {+ crbn?: { copy?: unknown };+ };+ const list = pkg.crbn?.copy;+ if (Array.isArray(list) && list.every((s) => typeof s === "string")) {+ return list as string[];+ }+ // biome-ignore lint/suspicious/noEmptyBlockStatements: ignored using `--suppress`+ } catch {}+ return DEFAULT_INCLUDES;+}diff --git a/packages/dev/src/commands/down.ts b/packages/dev/src/commands/down.tsnew file mode 100644index 0000000000..ed2d9686db--- /dev/null+++ b/packages/dev/src/commands/down.ts@@ -0,0 +1,75 @@+import { intro, outro, tasks } from "@clack/prompts";+import pc from "picocolors";+import { currentBranch, isLinkedWorktree } from "../lib/git.js";+import { syncAppPortlessConfigs } from "../lib/render-env.js";+import { getWorktreeRoot, projectName, resolveSlug } from "../lib/slug.js";+import { stopStack } from "../services/compose.js";+import { branchToPrefix, unregisterAliases } from "../services/portless.js";++// silent: post-SIGINT path. clack tasks/spinner would EIO via setRawMode on+// the freshly-interrupted stdin; fall back to plain printf progress.+export async function down(opts: { silent?: boolean } = {}) {+ const root = await getWorktreeRoot();+ const slug = resolveSlug(root);+ const project = projectName(slug);++ if (opts.silent) {+ return runPlain(root, slug, project);+ }++ intro("Carbon · dev down");+ await tasks([+ {+ title: `Stopping ${project} (volumes preserved)`,+ task: async (msg) => {+ msg("docker compose stop");+ await stopStack(root, slug, false);+ return "stack stopped";+ }+ },+ {+ title: "Unregister portless aliases",+ task: async () => {+ const branch = await currentBranch(root);+ const branchPrefix = branchToPrefix(branch);+ await unregisterAliases(root, branchPrefix);+ return "aliases removed";+ }+ },+ {+ title: "Reset app portless.json",+ task: async () => {+ const linked = await isLinkedWorktree();+ syncAppPortlessConfigs({+ worktreeRoot: root,+ branchPrefix: null,+ linked+ });+ return "configs reset";+ }+ }+ ]);+ outro("stopped");+}++async function runPlain(root: string, slug: string, project: string) {+ const step = (msg: string) =>+ process.stderr.write(`${pc.cyan("•")} ${msg}…\n`);+ const done = (msg: string) =>+ process.stderr.write(`${pc.green("✓")} ${msg}\n`);++ step(`stopping ${project} (volumes preserved)`);+ await stopStack(root, slug, false);+ done("stack stopped");++ step("unregistering portless aliases");+ const branch = await currentBranch(root);+ const branchPrefix = branchToPrefix(branch);+ await unregisterAliases(root, branchPrefix);+ done("aliases removed");++ step("resetting app portless.json");+ const linked = await isLinkedWorktree();+ syncAppPortlessConfigs({ worktreeRoot: root, branchPrefix: null, linked });+ done("configs reset");+}diff --git a/packages/dev/src/commands/list.ts b/packages/dev/src/commands/list.tsnew file mode 100644index 0000000000..32f00728ae--- /dev/null+++ b/packages/dev/src/commands/list.ts@@ -0,0 +1,46 @@+import { intro, log, outro } from "@clack/prompts";+import pc from "picocolors";+import { listWorktrees as gitListWorktrees } from "../lib/git.js";+import { listSlugs } from "../lib/ports.js";+import { dockerProjectStates } from "../services/compose.js";+import { worktreesTable } from "../ui/tables.js";++export async function listWorktrees() {+ intro("Carbon · worktrees");++ const [wtsAll, registry, dockerStates] = await Promise.all([+ gitListWorktrees(),+ Promise.resolve(listSlugs()),+ dockerProjectStates()+ ]);+ const wts = wtsAll.filter((w) => !w.bare);++ const rows = wts.map((w) => {+ const slug = slugForPath(w.path, registry);+ const dockerState = slug+ ? (dockerStates.get(`carbon-${slug}`) ?? null)+ : null;+ return {+ path: w.path,+ branch: w.branch,+ current: w.current,+ slug,+ dockerState+ };+ });++ log.message("\n" + worktreesTable(rows), {+ symbol: pc.bold(pc.yellow("worktrees"))+ });+ outro("");+}++function slugForPath(+ path: string,+ registry: ReturnType<typeof listSlugs>+): string | null {+ for (const [slug, entry] of Object.entries(registry)) {+ if (entry.worktreeRoot === path) return slug;+ }+ return null;+}diff --git a/packages/dev/src/commands/new.ts b/packages/dev/src/commands/new.tsnew file mode 100644index 0000000000..e8b5301338--- /dev/null+++ b/packages/dev/src/commands/new.ts@@ -0,0 +1,60 @@+import { copyFileSync, existsSync } from "node:fs";+import { basename, dirname, join, relative, resolve } from "node:path";+import { intro, outro, tasks } from "@clack/prompts";+import pc from "picocolors";+import { addWorktree, currentBranch } from "../lib/git.js";+import { getWorktreeRoot, slugify } from "../lib/slug.js";+import {+ promptBaseRef,+ promptBranch,+ promptCopyEnv,+ promptDirName+} from "../ui/prompts.js";++export async function newWorktree() {+ intro("Carbon · new worktree");++ const here = await getWorktreeRoot();+ const parentDir = dirname(here);+ const repoBaseName = basename(here).replace(/-[a-z0-9-]+$/i, "");++ const branch = await promptBranch();++ const defaultDir = `${repoBaseName}-${slugify(branch)}`;+ const dirName = await promptDirName(parentDir, defaultDir);+ const targetPath = resolve(parentDir, dirName);++ const cur = await currentBranch(here);+ const baseRef = await promptBaseRef(cur || null);++ const copyEnv = await promptCopyEnv();++ await tasks([+ {+ title: `git worktree add ${dirName}`,+ task: async (msg) => {+ msg(`branching from ${baseRef}`);+ const r = await addWorktree({ path: targetPath, branch, baseRef });+ if (!r.ok) throw new Error(r.error);+ return `worktree at ${relative(here, targetPath)}`;+ }+ },+ ...(copyEnv+ ? [+ {+ title: "Copy .env",+ task: async () => {+ const src = join(here, ".env");+ if (!existsSync(src)) return "no .env in source — skipped";+ copyFileSync(src, join(targetPath, ".env"));+ return ".env copied";+ }+ }+ ]+ : [])+ ]);++ outro(+ `worktree ready — ${pc.cyan(`crbn checkout ${branch} --up`)} to boot it`+ );+}diff --git a/packages/dev/src/commands/remove.ts b/packages/dev/src/commands/remove.tsnew file mode 100644index 0000000000..7dd1c1f711--- /dev/null+++ b/packages/dev/src/commands/remove.ts@@ -0,0 +1,123 @@+import {+ cancel,+ intro,+ isCancel,+ log,+ outro,+ select,+ tasks+} from "@clack/prompts";+import pc from "picocolors";+import {+ listWorktrees as gitListWorktrees,+ isDirty,+ removeWorktree+} from "../lib/git.js";+import { getSlot, listSlugs, removeSlot } from "../lib/ports.js";+import { destroyProjectVolumes, flushDb } from "../services/compose.js";+import { confirmRemove } from "../ui/prompts.js";++export async function removeWorktreeCmd() {+ intro("Carbon · remove worktree");++ const wtsAll = await gitListWorktrees();+ const wts = wtsAll.filter((w) => !w.bare && !w.current);+ if (wts.length === 0) {+ log.warn("no other worktrees to remove");+ outro("");+ return;+ }++ const choice = await select({+ message: "Worktree to remove",+ options: wts.map((w) => ({+ value: w.path,+ label: `${w.branch ?? "(detached)"} ${pc.dim(w.path)}`+ }))+ });+ if (isCancel(choice)) {+ cancel("aborted");+ process.exit(0);+ }+ const targetPath = choice as string;+ const target = wts.find((w) => w.path === targetPath)!;++ const dirty = await isDirty(targetPath);+ const registry = listSlugs();+ const slug = slugForPath(targetPath, registry);+ const projectLabel = slug ? `carbon-${slug}` : "(no stack)";++ const warnings: string[] = [];+ if (dirty) warnings.push(`${pc.yellow("⚠")} uncommitted changes in worktree`);+ if (slug)+ warnings.push(+ `${pc.yellow("⚠")} stack ${projectLabel} will be destroyed (volumes wiped)`+ );+ if (warnings.length) log.warn(warnings.join("\n"));++ const ok = await confirmRemove({+ branchOrPath: target.branch ?? targetPath,+ hasStack: !!slug+ });+ if (!ok) {+ cancel("aborted");+ process.exit(0);+ }++ const slotInfo = slug ? getSlot(slug) : null;+ await tasks([+ ...(slug+ ? [+ {+ title: `docker compose down -v · ${projectLabel}`,+ task: async () => {+ await destroyProjectVolumes(targetPath, projectLabel);+ return "stack removed";+ }+ }+ ]+ : []),+ ...(slotInfo && typeof slotInfo.redisDb === "number"+ ? [+ {+ title: `Flush redis db ${slotInfo.redisDb}`,+ task: async () => {+ await flushDb(slotInfo.redisDb);+ return "redis db flushed";+ }+ }+ ]+ : []),+ {+ title: `git worktree remove ${targetPath}`,+ task: async () => {+ const r = await removeWorktree(targetPath, dirty);+ if (!r.ok) throw new Error(r.error);+ return "worktree removed";+ }+ },+ ...(slug+ ? [+ {+ title: "Prune port registry",+ task: async () => {+ removeSlot(slug);+ return `removed ${slug}`;+ }+ }+ ]+ : [])+ ]);++ outro("done");+}++function slugForPath(+ path: string,+ registry: ReturnType<typeof listSlugs>+): string | null {+ for (const [slug, entry] of Object.entries(registry)) {+ if (entry.worktreeRoot === path) return slug;+ }+ return null;+}diff --git a/packages/dev/src/commands/reset.ts b/packages/dev/src/commands/reset.tsnew file mode 100644index 0000000000..59620a49c0--- /dev/null+++ b/packages/dev/src/commands/reset.ts@@ -0,0 +1,25 @@+import { cancel, intro, log } from "@clack/prompts";+import { getSlot } from "../lib/ports.js";+import { getWorktreeRoot, projectName, resolveSlug } from "../lib/slug.js";+import { flushDb, stopStack } from "../services/compose.js";+import { confirmReset } from "../ui/prompts.js";+import { up } from "./up.js";++export async function reset() {+ intro("Carbon · dev reset");+ const root = await getWorktreeRoot();+ const slug = resolveSlug(root);++ if (!(await confirmReset(projectName(slug)))) {+ cancel("reset aborted");+ process.exit(0);+ }++ log.warn(`resetting ${projectName(slug)}`);+ await stopStack(root, slug, true);+ const slot = getSlot(slug);+ if (slot && typeof slot.redisDb === "number") {+ await flushDb(slot.redisDb);+ }+ await up();+}diff --git a/packages/dev/src/commands/status.ts b/packages/dev/src/commands/status.tsnew file mode 100644index 0000000000..f15691f3ea--- /dev/null+++ b/packages/dev/src/commands/status.ts@@ -0,0 +1,37 @@+import { intro, log, outro } from "@clack/prompts";+import pc from "picocolors";+import { getSlot } from "../lib/ports.js";+import { getWorktreeRoot, projectName, resolveSlug } from "../lib/slug.js";+import { listContainers } from "../services/compose.js";+import { portsTable, servicesTable } from "../ui/tables.js";++export async function status() {+ intro("Carbon · dev status");+ const root = await getWorktreeRoot();+ const slug = resolveSlug(root);+ const slot = getSlot(slug);+ log.info(+ `worktree: ${pc.cyan(slug)} project: ${pc.cyan(projectName(slug))}`+ );+ if (!slot) {+ log.warn("no port assignment yet — run `crbn up`");+ outro("");+ return;+ }++ log.message("\n" + portsTable(slot.ports, slot.redisDb), {+ symbol: pc.bold(pc.yellow("Portless"))+ });++ const containers = await listContainers(root, slug);+ if (containers.length === 0) {+ log.warn("no containers running");+ outro("");+ return;+ }++ log.message("\n" + servicesTable(containers), {+ symbol: pc.bold(pc.yellow("Docker"))+ });+ outro("");+}diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.tsnew file mode 100644index 0000000000..f7d658d244--- /dev/null+++ b/packages/dev/src/commands/up.ts@@ -0,0 +1,225 @@+import { join } from "node:path";+import { box, intro, log, outro, tasks } from "@clack/prompts";+import { config as loadDotenv } from "dotenv";+import { execa } from "execa";+import { currentBranch, isLinkedWorktree } from "../lib/git.js";+import { resolveSlot, SHARED_REDIS_PORT } from "../lib/ports.js";+import {+ renderEnv,+ syncAppPortlessConfigs,+ writeEnv+} from "../lib/render-env.js";+import {+ ensureSlugAvailable,+ getWorktreeRoot,+ persistSlug,+ projectName,+ resolveSlug+} from "../lib/slug.js";+import {+ installDeps,+ spawnApps,+ spawnStripeListener,+ syncEnvSymlinks+} from "../services/apps.js";+import { bootSharedRedis, bootStack } from "../services/compose.js";+import {+ applyMigrations,+ waitForStorageTables,+ waitForTcp+} from "../services/migrations.js";+import {+ branchToPrefix,+ claimAppHosts,+ ensurePortlessInstalled,+ ensureProxyPrivileges,+ hostsFileInSync,+ proxyRunsAsRoot,+ pruneStaleRoutes,+ registerAliases,+ startProxyDaemon,+ syncHostsFile,+ waitForProxyReady+} from "../services/portless.js";+import { pickApps } from "../ui/prompts.js";+import { summaryLines } from "../ui/summary.js";+import { down } from "./down.js";++export async function up(opts: { migrate?: boolean; regen?: boolean } = {}) {+ const shouldMigrate = opts.migrate ?? true;+ // Type/swagger regen depends on a freshly-migrated schema. If migrations+ // were skipped, schema is unchanged — skip regen too.+ const shouldRegen = shouldMigrate && (opts.regen ?? true);+ intro("Carbon · dev up");++ await ensurePortlessInstalled();+ await ensureProxyPrivileges();++ const selectedApps = await pickApps();++ const root = await getWorktreeRoot();+ const slug = resolveSlug(root);+ await ensureSlugAvailable(slug, root);+ persistSlug(root, slug);+ log.info(`worktree: ${slug} (project ${projectName(slug)})`);++ // Outside `tasks` so pnpm progress streams directly when install runs.+ const ran = await installDeps(root);+ if (ran) log.step("pnpm install");+ else log.info("pnpm install skipped (lockfile in sync)");++ let ports!: Awaited<ReturnType<typeof resolveSlot>>["ports"];+ let redisDb!: number;+ let jwt!: Awaited<ReturnType<typeof resolveSlot>>["jwt"];+ let branchPrefix: string | null = null;++ await tasks([+ {+ title: "Configure portless",+ task: async () => {+ const slot = await resolveSlot(slug, root);+ ports = slot.ports;+ redisDb = slot.redisDb;+ jwt = slot.jwt;++ // Prefix every non-default branch. Portless auto-prefixes only in+ // linked worktrees; main checkout gets the same shape via per-app+ // portless.json stamped below.+ const branch = await currentBranch(root);+ const linked = await isLinkedWorktree();+ branchPrefix = branchToPrefix(branch);++ writeEnv(root, renderEnv({ slug, ports, redisDb, jwt, branchPrefix }));+ syncAppPortlessConfigs({ worktreeRoot: root, branchPrefix, linked });+ loadDotenv({ path: join(root, ".env.local"), override: false });+ loadDotenv({ path: join(root, ".env"), override: false });+ return `prefix "${branchPrefix ?? "(none)"}", redis db ${redisDb}`;+ }+ },+ {+ title: "Render .env.local & sync symlinks",+ task: async () => {+ await syncEnvSymlinks(root);+ return "env files synced";+ }+ },+ {+ title: "Boot shared redis",+ task: async () => {+ await bootSharedRedis(root);+ return `shared redis on :${SHARED_REDIS_PORT} (index ${redisDb})`;+ }+ },+ {+ title: "Boot docker compose stack",+ task: async (msg) => {+ msg("pulling/starting 12 services");+ await bootStack(root, slug);+ return "containers up";+ }+ },+ {+ title: "Wait for services",+ task: async (msg) => {+ msg("postgres + kong + inngest");+ await waitForTcp([+ `tcp:${ports.PORT_DB}`,+ `tcp:${ports.PORT_API}`,+ `tcp:${ports.PORT_INNGEST}`+ ]);+ msg("storage tables");+ await waitForStorageTables(ports.PORT_DB);+ return "all services responding";+ }+ },+ ...(shouldMigrate+ ? [+ {+ title: "Apply database migrations",+ task: async () => {+ await applyMigrations(root, ports.PORT_DB);+ return "migrations applied";+ }+ }+ ]+ : [+ {+ title: "Skip database migrations (--no-migrate)",+ task: async () => "skipped"+ }+ ]),+ ...(shouldRegen+ ? [+ {+ title: "Regenerate types & swagger",+ task: async () => {+ await execa("pnpm", ["db:types"], { cwd: root });+ await execa("pnpm", ["generate:swagger"], { cwd: root });+ return "types + swagger refreshed";+ }+ }+ ]+ : []),+ {+ title: "Start portless proxy",+ task: async (msg) => {+ pruneStaleRoutes(branchPrefix);+ startProxyDaemon(root);+ msg("waiting for proxy on :443");+ await waitForProxyReady();+ return "proxy listening";+ }+ },+ {+ title: "Register service aliases",+ task: async () => {+ const count = await registerAliases(root, branchPrefix, ports);+ return `${count} aliases registered`;+ }+ },+ {+ title: "Reserve app hostnames",+ task: async () => {+ const killed = await claimAppHosts(branchPrefix, selectedApps);+ return killed > 0+ ? `killed ${killed} orphan portless process${killed === 1 ? "" : "es"}`+ : "no orphans found";+ }+ }+ ]);++ // Skip sudo sync when root daemon already auto-syncs, or hosts unchanged.+ if (proxyRunsAsRoot()) {+ log.info("/etc/hosts auto-synced by root proxy daemon");+ } else if (hostsFileInSync()) {+ log.info("/etc/hosts already in sync — skipping sudo");+ } else {+ log.step("sudo portless hosts sync");+ await syncHostsFile();+ }++ if (process.env.CARBON_EDITION === "cloud") {+ spawnStripeListener(root);+ log.info("stripe listener spawned (CARBON_EDITION=cloud)");+ }++ box(summaryLines(ports, branchPrefix).join("\n"), `Carbon dev — ${slug}`);+ outro("apps starting (Ctrl+C to stop)");++ await spawnApps({ root, apps: selectedApps });++ // Apps exit on Ctrl+C; auto-`down` so compose stack isn't orphaned.+ // Swallow further signals so a second Ctrl+C during teardown doesn't+ // exit 130 mid-`docker compose stop`.+ const swallow = () => {+ process.stderr.write("\nfinishing teardown — please wait\n");+ };+ const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP", "SIGBREAK"] as const;+ for (const s of SIGNALS) process.on(s, swallow);+ try {+ // silent: post-SIGINT stdin raw-mode triggers EIO in clack's spinner.+ await down({ silent: true });+ } finally {+ for (const s of SIGNALS) process.off(s, swallow);+ }+}diff --git a/packages/dev/src/constants.ts b/packages/dev/src/constants.tsnew file mode 100644index 0000000000..b810efb02d--- /dev/null+++ b/packages/dev/src/constants.ts@@ -0,0 +1,19 @@+/** File names + paths used across the CLI. */+export const COMPOSE_DEV_FILE = "docker-compose.dev.yml";+export const COMPOSE_SHARED_FILE = "docker-compose.yml";++/** Apps the CLI knows how to spawn through portless. */+export const APP_CHOICES = [+ { value: "erp", label: "ERP", hint: "main app" },+ { value: "mes", label: "MES", hint: "shop floor" }+] as const;+export type AppId = (typeof APP_CHOICES)[number]["value"];++/** Compose services that get registered as portless aliases (host TCP). */+export const ALIAS_SERVICES = ["api", "studio", "mail", "inngest"] as const;++/** Minimum portless version that supports bare invocation + package.json config. */+export const PORTLESS_MIN_VERSION = "0.11.0";++/** Hostname TLD portless serves under. */+export const TLD = "dev";diff --git a/packages/dev/src/lib/git.ts b/packages/dev/src/lib/git.tsnew file mode 100644index 0000000000..e4febd8b44--- /dev/null+++ b/packages/dev/src/lib/git.ts@@ -0,0 +1,128 @@+import { dirname, resolve } from "node:path";+import { execa } from "execa";++export type Worktree = {+ path: string;+ branch: string | null; // null = detached+ head: string;+ bare: boolean;+ current: boolean;+};++// Main checkout root — `--git-common-dir`'s parent. Works from any worktree.+export async function mainCheckoutRoot(+ cwd: string = process.cwd()+): Promise<string> {+ const r = await execa("git", ["rev-parse", "--git-common-dir"], {+ cwd,+ reject: false+ });+ if (r.exitCode !== 0) {+ throw new Error("not inside a git repository");+ }+ return dirname(resolve(cwd, r.stdout.trim()));+}++export async function isLinkedWorktree(cwd = process.cwd()): Promise<boolean> {+ // Linked when --git-dir differs from --git-common-dir. Resolve both first —+ // --absolute-git-dir would compare absolute vs relative and false-positive.+ const [a, b] = await Promise.all([+ execa("git", ["rev-parse", "--git-dir"], { cwd, reject: false }),+ execa("git", ["rev-parse", "--git-common-dir"], { cwd, reject: false })+ ]);+ if (a.exitCode !== 0 || b.exitCode !== 0) return false;+ return resolve(cwd, a.stdout.trim()) !== resolve(cwd, b.stdout.trim());+}++export async function currentBranch(cwd = process.cwd()): Promise<string> {+ try {+ const r = await execa("git", ["rev-parse", "--abbrev-ref", "HEAD"], {+ cwd+ });+ const out = r.stdout.trim();+ return out === "HEAD" ? "" : out;+ } catch {+ return "";+ }+}++export async function listWorktrees(): Promise<Worktree[]> {+ const r = await execa("git", ["worktree", "list", "--porcelain"]);+ const cwd = process.cwd();+ const blocks = r.stdout.trim().split("\n\n");+ return blocks.map((block) => {+ const lines = block.split("\n");+ const get = (key: string) =>+ lines.find((l) => l.startsWith(`${key} `))?.slice(key.length + 1) ?? "";+ const path = get("worktree");+ const branchLine = lines.find((l) => l.startsWith("branch "));+ const branch = branchLine+ ? branchLine.slice("branch refs/heads/".length)+ : null;+ return {+ path,+ branch,+ head: get("HEAD"),+ bare: lines.includes("bare"),+ current: path === cwd+ };+ });+}++export async function addWorktree(opts: {+ path: string;+ branch: string;+ baseRef: string;+}): Promise<{ ok: true } | { ok: false; error: string }> {+ const r = await execa(+ "git",+ ["worktree", "add", "-b", opts.branch, opts.path, opts.baseRef],+ { reject: false }+ );+ if (r.exitCode !== 0) {+ return { ok: false, error: (r.stderr || r.stdout || "").trim() };+ }+ return { ok: true };+}++export async function removeWorktree(+ path: string,+ force = false+): Promise<{ ok: true } | { ok: false; error: string }> {+ const args = ["worktree", "remove"];+ if (force) args.push("--force");+ args.push(path);+ const r = await execa("git", args, { reject: false });+ if (r.exitCode !== 0) {+ return { ok: false, error: (r.stderr || r.stdout || "").trim() };+ }+ return { ok: true };+}++export async function isDirty(path: string): Promise<boolean> {+ const r = await execa("git", ["status", "--porcelain"], {+ cwd: path,+ reject: false+ });+ return r.exitCode === 0 && (r.stdout || "").trim().length > 0;+}++export async function branchExists(branch: string): Promise<boolean> {+ const r = await execa(+ "git",+ ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`],+ { reject: false }+ );+ return r.exitCode === 0;+}++export async function deleteBranch(+ branch: string+): Promise<{ ok: true } | { ok: false; error: string }> {+ // -D forces even on unmerged; caller confirms.+ const r = await execa("git", ["branch", "-D", branch], { reject: false });+ if (r.exitCode !== 0) {+ return { ok: false, error: (r.stderr || r.stdout || "").trim() };+ }+ return { ok: true };+}diff --git a/packages/dev/src/lib/jwt.ts b/packages/dev/src/lib/jwt.tsnew file mode 100644index 0000000000..74bb471c36--- /dev/null+++ b/packages/dev/src/lib/jwt.ts@@ -0,0 +1,46 @@+import { createHmac, randomBytes } from "node:crypto";++export type JwtCreds = {+ secret: string;+ anonKey: string;+ serviceKey: string;+};++/**+ * Mint a fresh JWT_SECRET + the matching `anon` and `service_role` HS256 JWTs.+ * Mirrors supabase's well-known dev token shape so all downstream services+ * (gotrue, postgrest, kong, storage, studio) accept them without further config.+ */+export function generateJwtCreds(): JwtCreds {+ // 32-byte (256-bit) secret, hex-encoded — matches HS256 key strength.+ const secret = randomBytes(32).toString("hex");+ const iat = Math.floor(Date.now() / 1000);+ const exp = iat + 10 * 365 * 24 * 60 * 60; // 10 years+ const anonKey = signJwt(+ { iss: "supabase-demo", role: "anon", iat, exp },+ secret+ );+ const serviceKey = signJwt(+ { iss: "supabase-demo", role: "service_role", iat, exp },+ secret+ );+ return { secret, anonKey, serviceKey };+}++function signJwt(payload: object, secret: string): string {+ const header = { alg: "HS256", typ: "JWT" };+ const h = b64url(JSON.stringify(header));+ const p = b64url(JSON.stringify(payload));+ const data = `${h}.${p}`;+ const sig = b64url(createHmac("sha256", secret).update(data).digest());+ return `${data}.${sig}`;+}++function b64url(input: Buffer | string): string {+ const buf = typeof input === "string" ? Buffer.from(input) : input;+ return buf+ .toString("base64")+ .replace(/=+$/, "")+ .replace(/\+/g, "-")+ .replace(/\//g, "_");+}diff --git a/packages/dev/src/lib/ports.ts b/packages/dev/src/lib/ports.tsnew file mode 100644index 0000000000..82380586b2--- /dev/null+++ b/packages/dev/src/lib/ports.ts@@ -0,0 +1,148 @@+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import net from "node:net";+import { homedir } from "node:os";+import { dirname, join } from "node:path";+import { generateJwtCreds, type JwtCreds } from "./jwt.js";++export const PORT_NAMES = [+ "PORT_DB",+ "PORT_API",+ "PORT_STUDIO",+ "PORT_INBUCKET",+ "PORT_INNGEST"+] as const;++type PortName = (typeof PORT_NAMES)[number];+export type PortMap = Record<PortName, number>;++const REDIS_DB_MAX = 16;+export const SHARED_REDIS_PORT = 6379;++const REGISTRY_PATH = join(homedir(), ".carbon", "dev-ports.json");++type RegistryEntry = {+ worktreeRoot: string;+ ports: PortMap;+ redisDb: number;+ jwt: JwtCreds;+};+type Registry = Record<string, RegistryEntry>;++function readRegistry(): Registry {+ if (!existsSync(REGISTRY_PATH)) return {};+ try {+ return JSON.parse(readFileSync(REGISTRY_PATH, "utf8"));+ } catch {+ return {};+ }+}++function writeRegistry(registry: Registry) {+ mkdirSync(dirname(REGISTRY_PATH), { recursive: true });+ writeFileSync(REGISTRY_PATH, JSON.stringify(registry, null, 2));+}++export async function resolveSlot(+ slug: string,+ worktreeRoot: string+): Promise<{ ports: PortMap; redisDb: number; jwt: JwtCreds }> {+ const registry = readRegistry();+ const existing = registry[slug];+ if (+ existing &&+ existing.worktreeRoot === worktreeRoot &&+ typeof existing.redisDb === "number" &&+ existing.jwt?.secret+ ) {+ return {+ ports: existing.ports,+ redisDb: existing.redisDb,+ jwt: existing.jwt+ };+ }++ const claimedPorts = new Set<number>();+ const claimedDbs = new Set<number>();+ for (const [s, entry] of Object.entries(registry)) {+ if (s === slug) continue;+ for (const p of Object.values(entry.ports)) claimedPorts.add(p);+ if (typeof entry.redisDb === "number") claimedDbs.add(entry.redisDb);+ }++ const ports =+ existing?.ports && existing.worktreeRoot === worktreeRoot+ ? existing.ports+ : await pickPorts(claimedPorts);++ const redisDb =+ typeof existing?.redisDb === "number"+ ? existing.redisDb+ : pickRedisDb(claimedDbs);++ // JWT creds tied to data signed/stored in postgres — rotating invalidates+ // existing sessions, so reuse when present.+ const jwt = existing?.jwt?.secret ? existing.jwt : generateJwtCreds();++ registry[slug] = { worktreeRoot, ports, redisDb, jwt };+ writeRegistry(registry);+ return { ports, redisDb, jwt };+}++export function getSlot(slug: string): RegistryEntry | null {+ return readRegistry()[slug] ?? null;+}++export function listSlugs(): Registry {+ return readRegistry();+}++export function removeSlot(slug: string) {+ const registry = readRegistry();+ if (!(slug in registry)) return;+ delete registry[slug];+ writeRegistry(registry);+}++function pickRedisDb(taken: Set<number>): number {+ for (let i = 0; i < REDIS_DB_MAX; i++) {+ if (!taken.has(i)) return i;+ }+ throw new Error(+ `Redis DB pool exhausted (max ${REDIS_DB_MAX}). Free a slot via \`crbn remove\`.`+ );+}++async function pickPorts(claimed: Set<number>): Promise<PortMap> {+ const ports = {} as PortMap;+ for (const name of PORT_NAMES) {+ ports[name] = await pickFreePort(claimed);+ }+ return ports;+}++async function pickFreePort(taken: Set<number>): Promise<number> {+ // OS-assigned ephemeral via listen(0); retry on collision with other+ // worktrees' claimed-set.+ for (let attempt = 0; attempt < 100; attempt++) {+ const port = await new Promise<number>((resolve, reject) => {+ const server = net.createServer();+ server.unref();+ server.on("error", reject);+ server.listen(0, "127.0.0.1", () => {+ const addr = server.address();+ if (typeof addr === "object" && addr) {+ const p = addr.port;+ server.close(() => resolve(p));+ } else {+ server.close();+ reject(new Error("could not determine port"));+ }+ });+ });+ if (!taken.has(port)) {+ taken.add(port);+ return port;+ }+ }+ throw new Error("Failed to allocate a free port after 100 attempts");+}diff --git a/packages/dev/src/lib/render-env.ts b/packages/dev/src/lib/render-env.tsnew file mode 100644index 0000000000..1e8e060d3f--- /dev/null+++ b/packages/dev/src/lib/render-env.ts@@ -0,0 +1,90 @@+import { existsSync, unlinkSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { APP_CHOICES } from "../constants.js";+import type { JwtCreds } from "./jwt.js";+import { type PortMap, SHARED_REDIS_PORT } from "./ports.js";++export function renderEnv(opts: {+ slug: string;+ ports: PortMap;+ redisDb: number;+ jwt: JwtCreds;+ // Sanitized branch segment, e.g. `feat/boo` → `boo`. Null on default branch.+ branchPrefix: string | null;+}): string {+ const { slug, ports, redisDb, jwt, branchPrefix } = opts;+ const host = (sub: string) =>+ branchPrefix ? `${branchPrefix}.${sub}.dev` : `${sub}.dev`;++ const lines: string[] = [];+ lines.push("# Generated by crbn. Do not edit by hand.");+ lines.push("# Vite/React Router auto-load this file alongside .env;");+ lines.push("# values here override .env. The user's .env is left untouched.");+ lines.push("");+ lines.push(`CARBON_WORKTREE=${slug}`);+ lines.push("PORTLESS_TLD=dev");+ lines.push("");+ lines.push("# Internal compose ports (apps do not read these directly)");+ for (const [k, v] of Object.entries(ports)) lines.push(`${k}=${v}`);+ lines.push("");+ lines.push("# App-facing URLs (portless hostnames)");+ lines.push(`DOMAIN=${host("erp")}`);+ lines.push(`ERP_URL=https://${host("erp")}`);+ lines.push(`MES_URL=https://${host("mes")}`);+ lines.push(`VERCEL_URL=https://${host("erp")}`);+ lines.push(`GTM_URL=https://${host("starter")}`);+ lines.push("");+ lines.push(+ "# Supabase (per-worktree dev keys, minted from random JWT_SECRET)"+ );+ lines.push(`SUPABASE_URL=https://${host("api")}`);+ lines.push(+ `SUPABASE_DB_URL=postgresql://postgres:postgres@localhost:${ports.PORT_DB}/postgres`+ );+ lines.push("PGSSLMODE=disable");+ lines.push(`SUPABASE_JWT_SECRET=${jwt.secret}`);+ lines.push(`SUPABASE_ANON_KEY=${jwt.anonKey}`);+ lines.push(`SUPABASE_SERVICE_ROLE_KEY=${jwt.serviceKey}`);+ // Branch-independent OAuth callback host (api.carbon.dev). Last `crbn up`+ // wins — registers `api.carbon` alias to its PORT_API.+ lines.push(+ `SUPABASE_AUTH_EXTERNAL_GOOGLE_REDIRECT_URI=https://api.carbon.dev/auth/v1/callback`+ );+ lines.push(+ `SUPABASE_AUTH_EXTERNAL_AZURE_REDIRECT_URI=https://api.carbon.dev/auth/v1/callback`+ );+ lines.push("");+ lines.push("# Aux services");+ lines.push(`REDIS_URL=redis://localhost:${SHARED_REDIS_PORT}/${redisDb}`);+ lines.push("INNGEST_DEV=1");+ lines.push(`INNGEST_BASE_URL=http://localhost:${ports.PORT_INNGEST}`);+ lines.push("");+ return lines.join("\n");+}++export function writeEnv(worktreeRoot: string, content: string) {+ writeFileSync(join(worktreeRoot, ".env.local"), content);+}++// Stamp `apps/<id>/portless.json` so main-checkout gets `<prefix>.<app>.dev`+// too (portless auto-prefixes only in linked worktrees). Linked worktrees+// leave the file absent — stamping would double-prefix.+export function syncAppPortlessConfigs(opts: {+ worktreeRoot: string;+ branchPrefix: string | null;+ linked: boolean;+}) {+ const { worktreeRoot, branchPrefix, linked } = opts;+ for (const { value: appId } of APP_CHOICES) {+ const path = join(worktreeRoot, "apps", appId, "portless.json");+ const shouldStamp = !linked && branchPrefix !== null;+ if (shouldStamp) {+ writeFileSync(+ path,+ `${JSON.stringify({ name: `${branchPrefix}.${appId}` }, null, 2)}\n`+ );+ } else if (existsSync(path)) {+ unlinkSync(path);+ }+ }+}diff --git a/packages/dev/src/lib/slug.ts b/packages/dev/src/lib/slug.tsnew file mode 100644index 0000000000..72bc37b360--- /dev/null+++ b/packages/dev/src/lib/slug.ts@@ -0,0 +1,70 @@+import { existsSync, readFileSync, writeFileSync } from "node:fs";+import { basename, join } from "node:path";+import { execa } from "execa";++const SLUG_FILE = ".carbon-worktree";++export function resolveSlug(worktreeRoot: string): string {+ const fromEnv = process.env.CARBON_WORKTREE?.trim();+ if (fromEnv) return slugify(fromEnv);++ const filePath = join(worktreeRoot, SLUG_FILE);+ if (existsSync(filePath)) {+ const fromFile = readFileSync(filePath, "utf8").trim();+ if (fromFile) return slugify(fromFile);+ }++ return slugify(basename(worktreeRoot));+}++export function persistSlug(worktreeRoot: string, slug: string) {+ writeFileSync(join(worktreeRoot, SLUG_FILE), `${slug}\n`);+}++export async function getWorktreeRoot(): Promise<string> {+ try {+ const r = await execa("git", ["rev-parse", "--show-toplevel"]);+ return r.stdout.trim();+ } catch {+ return process.cwd();+ }+}++export function projectName(slug: string): string {+ return `carbon-${slug}`;+}++export async function ensureSlugAvailable(slug: string, worktreeRoot: string) {+ const project = projectName(slug);+ let runningPath: string | null = null;+ try {+ const r = await execa(+ "docker",+ [+ "ps",+ "--filter",+ `label=com.docker.compose.project=${project}`,+ "--format",+ '{{.Label "com.docker.compose.project.working_dir"}}'+ ],+ { reject: false }+ );+ const out = r.stdout.trim();+ if (out) runningPath = out.split("\n")[0] ?? null;+ } catch {+ return;+ }+ if (runningPath && runningPath !== worktreeRoot) {+ throw new Error(+ `Slug "${slug}" is already in use by another worktree at:\n ${runningPath}\n\nSet CARBON_WORKTREE to a unique slug for this worktree, or stop the other stack.`+ );+ }+}++export function slugify(input: string): string {+ return input+ .toLowerCase()+ .replace(/[^a-z0-9-]+/g, "-")+ .replace(/^-+|-+$/g, "")+ .replace(/-+/g, "-");+}diff --git a/packages/dev/src/main.ts b/packages/dev/src/main.tsnew file mode 100644index 0000000000..0dbe534dac--- /dev/null+++ b/packages/dev/src/main.ts@@ -0,0 +1,86 @@+import tab from "@bomb.sh/tab/citty";+import { defineCommand, runMain } from "citty";+import { copy } from "./commands/copy.js";+import { down } from "./commands/down.js";+import { listWorktrees } from "./commands/list.js";+import { newWorktree } from "./commands/new.js";+import { removeWorktreeCmd } from "./commands/remove.js";+import { reset } from "./commands/reset.js";+import { status } from "./commands/status.js";+import { up } from "./commands/up.js";++const main = defineCommand({+ meta: {+ name: "crbn",+ description: "Carbon dev CLI (heavy commands; bash router handles checkout)"+ },+ subCommands: {+ up: defineCommand({+ meta: { description: "Boot the per-worktree compose stack and apps" },+ args: {+ migrate: {+ type: "boolean",+ default: true,+ description: "Apply database migrations (use --no-migrate to skip)"+ },+ regen: {+ type: "boolean",+ default: true,+ description:+ "Regenerate db types + swagger after migrations (use --no-regen to skip)"+ }+ },+ run: ({ args }) =>+ up({+ migrate: args.migrate !== false,+ regen: args.regen !== false+ })+ }),+ down: defineCommand({+ meta: { description: "Stop the compose stack (volumes preserved)" },+ run: () => down()+ }),+ reset: defineCommand({+ meta: { description: "Wipe volumes + flush redis db, then `up`" },+ run: () => reset()+ }),+ status: defineCommand({+ meta: { description: "Show port assignment + container health" },+ run: () => status()+ }),+ new: defineCommand({+ meta: { description: "Interactive: create a worktree on a fresh branch" },+ run: () => newWorktree()+ }),+ list: defineCommand({+ meta: { description: "List worktrees with stack status" },+ run: () => listWorktrees()+ }),+ remove: defineCommand({+ meta: { description: "Pick a worktree to delete (with stack teardown)" },+ run: () => removeWorktreeCmd()+ }),+ copy: defineCommand({+ meta: {+ description:+ "Copy files listed in package.json#crbn.copy from main checkout into cwd"+ },+ run: () => copy()+ }),+ // Stubs so shell completion lists these — the bash router (`bin/crbn`)+ // intercepts them before tsx is invoked. Direct invocation lands here.+ checkout: defineCommand({+ meta: {+ description:+ "Switch into worktree for <branch> (handled by bash router)"+ },+ run: () => {+ console.error("checkout is handled by the bash router (bin/crbn)");+ process.exit(1);+ }+ })+ }+});++await tab(main);+await runMain(main);diff --git a/packages/dev/src/services/apps.ts b/packages/dev/src/services/apps.tsnew file mode 100644index 0000000000..fbe9e7decd--- /dev/null+++ b/packages/dev/src/services/apps.ts@@ -0,0 +1,160 @@+import { existsSync, statSync } from "node:fs";+import { join } from "node:path";+import { type ExecaChildProcess, execa } from "execa";+import pc from "picocolors";++const APP_COLORS: Record<string, (s: string) => string> = {+ erp: pc.cyan,+ mes: pc.magenta+};++// Drop portless banners (`-- ...`), pnpm script-echo (`> ...`), blanks.+// Vite "Local:", "ready in …", and errors pass through.+const NOISE_PATTERNS: RegExp[] = [/^\s*--\s/, /^\s*>\s/, /^\s*$/];++function isNoiseLine(line: string): boolean {+ // biome-ignore lint/suspicious/noControlCharactersInRegex: ignored using `--suppress`+ const plain = line.replace(/\x1b\[[0-9;]*m/g, "");+ return NOISE_PATTERNS.some((re) => re.test(plain));+}++// Invoke portless directly per app, bypassing the per-app `dev` script.+// Older branches still have `dev: portless` which recurses into itself in+// portless default mode, racing to register `<prefix>.<app>.dev`.+export function spawnApps(opts: {+ root: string;+ apps: string[];+}): Promise<void> {+ const { root, apps } = opts;++ let shuttingDown = false;++ const children: ExecaChildProcess[] = apps.map((id) => {+ const color = APP_COLORS[id] ?? ((s: string) => s);+ // detached: own process group so `process.kill(-pid, sig)` reaches the+ // whole subtree (portless → react-router → vite → esbuild).+ const child = execa("portless", ["--script", "dev:app", "run", "--force"], {+ cwd: join(root, "apps", id),+ preferLocal: true,+ reject: false,+ stdin: "ignore",+ detached: true+ });++ const prefix = color(pc.bold(`${id.padEnd(3)} | `));+ const pipe = (+ stream: NodeJS.ReadableStream | null,+ sink: NodeJS.WriteStream+ ) => {+ if (!stream) return;+ let buf = "";+ stream.on("data", (chunk) => {+ // Mute shutdown noise (EPIPE, ELIFECYCLE 143, esbuild "stopped").+ if (shuttingDown) return;+ buf += chunk.toString();+ const lines = buf.split("\n");+ buf = lines.pop() ?? "";+ for (const line of lines) {+ if (isNoiseLine(line)) continue;+ sink.write(`${prefix}${line}\n`);+ }+ });+ stream.on("end", () => {+ if (!shuttingDown && buf.length > 0 && !isNoiseLine(buf)) {+ sink.write(`${prefix}${buf}\n`);+ }+ });+ };+ pipe(child.stdout, process.stdout);+ pipe(child.stderr, process.stderr);++ return child;+ });++ let killTimer: NodeJS.Timeout | undefined;++ const shutdown = (signal: "SIGTERM" | "SIGKILL") => {+ for (const c of children) {+ if (c.exitCode !== null || !c.pid) continue;+ try {+ process.kill(-c.pid, signal);+ } catch {+ try {+ c.kill(signal);+ // biome-ignore lint/suspicious/noEmptyBlockStatements: ignored using `--suppress`+ } catch {}+ }+ }+ };++ const onSignal = () => {+ if (shuttingDown) {+ if (killTimer) clearTimeout(killTimer);+ shutdown("SIGKILL");+ return;+ }+ shuttingDown = true;+ process.stderr.write("\nstopping apps…\n");+ shutdown("SIGTERM");+ killTimer = setTimeout(() => shutdown("SIGKILL"), 3_000);+ };++ const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP", "SIGBREAK"] as const;+ for (const s of SIGNALS) process.on(s, onSignal);++ return Promise.all(children)+ .then(() => undefined)+ .catch(() => undefined)+ .finally(() => {+ if (killTimer) clearTimeout(killTimer);+ for (const s of SIGNALS) process.off(s, onSignal);+ });+}++export function spawnStripeListener(root: string) {+ execa("npm", ["run", "dev:stripe"], {+ cwd: root,+ detached: true,+ stdio: "ignore"+ }).unref();+}++// Skip when node_modules/.modules.yaml is newer than pnpm-lock.yaml (pnpm's+// post-install marker). Returns true when install actually ran.+export async function installDeps(root: string): Promise<boolean> {+ if (depsInSync(root)) return false;++ const r = await execa("pnpm", ["install", "--prefer-offline"], {+ cwd: root,+ stdio: "inherit",+ reject: false,+ extendEnv: true+ });+ if (r.exitCode !== 0) {+ throw new Error(`pnpm install failed (exit ${r.exitCode})`);+ }+ return true;+}++function depsInSync(root: string): boolean {+ const lockfile = join(root, "pnpm-lock.yaml");+ const marker = join(root, "node_modules", ".modules.yaml");+ if (!existsSync(lockfile) || !existsSync(marker)) return false;+ try {+ return statSync(marker).mtimeMs >= statSync(lockfile).mtimeMs;+ } catch {+ return false;+ }+}++export async function syncEnvSymlinks(root: string) {+ const r = await execa("tsx", [join("scripts", "setup-env-files.ts")], {+ cwd: root,+ reject: false,+ preferLocal: true+ });+ if (r.exitCode !== 0) {+ process.stderr.write(r.stderr?.toString() ?? "");+ throw new Error(`setup-env-files failed (exit ${r.exitCode})`);+ }+}diff --git a/packages/dev/src/services/compose.ts b/packages/dev/src/services/compose.tsnew file mode 100644index 0000000000..8dbd4ff501--- /dev/null+++ b/packages/dev/src/services/compose.ts@@ -0,0 +1,157 @@+import { log } from "@clack/prompts";+import { execa } from "execa";+import { COMPOSE_DEV_FILE, COMPOSE_SHARED_FILE } from "../constants.js";+import { SHARED_REDIS_PORT } from "../lib/ports.js";+import { projectName } from "../lib/slug.js";++export async function bootStack(root: string, slug: string) {+ await execStrict(+ "docker",+ [+ "compose",+ "-f",+ COMPOSE_DEV_FILE,+ "-p",+ projectName(slug),+ "--env-file",+ ".env.local",+ "up",+ "-d"+ ],+ root+ );+}++export async function stopStack(+ root: string,+ slug: string,+ withVolumes: boolean+) {+ const args = [+ "compose",+ "-f",+ COMPOSE_DEV_FILE,+ "-p",+ projectName(slug),+ "down"+ ];+ if (withVolumes) args.push("-v");+ await execa("docker", args, { cwd: root, stdio: "ignore", reject: false });+}++// One redis per host; recover from stale `carbon-redis` leftovers.+export async function bootSharedRedis(root: string) {+ const args = ["compose", "-f", COMPOSE_SHARED_FILE, "up", "-d", "redis"];+ let r = await execa("docker", args, { cwd: root, reject: false });+ if (r.exitCode !== 0 && /already in use/i.test(r.stderr ?? "")) {+ await execa("docker", ["rm", "-f", "carbon-redis"], {+ reject: false,+ stdio: "ignore"+ });+ r = await execa("docker", args, { cwd: root, reject: false });+ }+ if (r.exitCode !== 0) {+ process.stderr.write(r.stderr ?? "");+ throw new Error(`shared redis up failed (exit ${r.exitCode})`);+ }+}++export async function destroyProjectVolumes(cwd: string, project: string) {+ await execa(+ "docker",+ ["compose", "-f", COMPOSE_DEV_FILE, "-p", project, "down", "-v"],+ { cwd, stdio: "ignore", reject: false }+ );+}++export async function listContainers(+ root: string,+ slug: string+): Promise<Container[]> {+ const r = await execa(+ "docker",+ [+ "compose",+ "-f",+ COMPOSE_DEV_FILE,+ "-p",+ projectName(slug),+ "ps",+ "-a",+ "--format",+ "json"+ ],+ { cwd: root, reject: false }+ );+ if (r.exitCode !== 0 || !r.stdout?.trim()) return [];+ return r.stdout+ .split("\n")+ .filter(Boolean)+ .map((l) => JSON.parse(l) as Container);+}++export async function dockerProjectStates(): Promise<Map<string, string>> {+ const out = new Map<string, string>();+ const r = await execa(+ "docker",+ [+ "ps",+ "-a",+ "--format",+ '{{.Label "com.docker.compose.project"}}\t{{.State}}'+ ],+ { reject: false }+ );+ for (const line of (r.stdout ?? "").split("\n")) {+ const [project, state] = line.split("\t");+ if (!project || !state) continue;+ if (state === "running") out.set(project, "running");+ else if (!out.has(project)) out.set(project, state);+ }+ return out;+}++export type Container = {+ Service: string;+ Name: string;+ State: string;+ Status: string;+ Health?: string;+ Publishers?: { PublishedPort: number; TargetPort: number }[] | null;+};++// Wipe one logical DB on shared redis. Host redis-cli, fallback docker exec.+export async function flushDb(db: number) {+ let r = await execa(+ "redis-cli",+ [+ "-h",+ "localhost",+ "-p",+ String(SHARED_REDIS_PORT),+ "-n",+ String(db),+ "FLUSHDB"+ ],+ { reject: false, stdio: "ignore" }+ );+ if (r.exitCode !== 0) {+ r = await execa(+ "docker",+ ["exec", "carbon-redis", "redis-cli", "-n", String(db), "FLUSHDB"],+ { reject: false, stdio: "ignore" }+ );+ }+ if (r.exitCode !== 0) {+ log.warn(`redis flush of db ${db} failed (skipped)`);+ }+}++async function execStrict(cmd: string, args: string[], cwd: string) {+ const r = await execa(cmd, args, { cwd, reject: false, preferLocal: true });+ if (r.exitCode !== 0) {+ process.stderr.write(r.stderr?.toString() ?? "");+ process.stdout.write(r.stdout?.toString() ?? "");+ throw new Error(`${cmd} ${args.join(" ")} failed (exit ${r.exitCode})`);+ }+}diff --git a/packages/dev/src/services/migrations.ts b/packages/dev/src/services/migrations.tsnew file mode 100644index 0000000000..ef87eca0fa--- /dev/null+++ b/packages/dev/src/services/migrations.ts@@ -0,0 +1,84 @@+import net from "node:net";+import { join } from "node:path";+import { setTimeout as sleep } from "node:timers/promises";+import { execa } from "execa";++// Block until each tcp:<port> accepts on 127.0.0.1.+export async function waitForTcp(targets: string[]) {+ const ports = targets.map((t) => {+ const m = t.match(/^tcp:(\d+)$/);+ if (!m)+ throw new Error(`waitForTcp: bad target "${t}" (expected tcp:<port>)`);+ return Number(m[1]);+ });+ await Promise.all(ports.map((p) => waitForPort(p, 60_000)));+}++async function waitForPort(+ port: number,+ timeoutMs: number,+ host = "127.0.0.1"+) {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ const ok = await tryConnect(host, port);+ if (ok) return;+ await sleep(500);+ }+ throw new Error(`timed out waiting for tcp:${port} after ${timeoutMs}ms`);+}++function tryConnect(host: string, port: number): Promise<boolean> {+ return new Promise((resolve) => {+ const socket = net.connect({ host, port });+ const done = (ok: boolean) => {+ socket.removeAllListeners();+ socket.destroy();+ resolve(ok);+ };+ socket.once("connect", () => done(true));+ socket.once("error", () => done(false));+ socket.setTimeout(2000, () => done(false));+ });+}++// Block until supabase storage-api bootstraps `storage.buckets`.+export async function waitForStorageTables(port: number) {+ const url = `postgresql://postgres:postgres@localhost:${port}/postgres`;+ const deadline = Date.now() + 60_000;+ while (Date.now() < deadline) {+ const r = await execa(+ "psql",+ [url, "-tAc", "SELECT to_regclass('storage.buckets')"],+ { env: { ...process.env, PGSSLMODE: "disable" }, reject: false }+ );+ if (r.exitCode === 0 && r.stdout?.trim() === "storage.buckets") return;+ await sleep(1000);+ }+ throw new Error("storage.buckets did not appear within 60s");+}++// --include-all: supabase bootstrap inserts a sentinel into schema_migrations+// that makes earlier-timestamp migrations look "out of order" without it.+export async function applyMigrations(root: string, dbPort: number) {+ await execStrict(+ "supabase",+ [+ "migration",+ "up",+ "--include-all",+ "--db-url",+ `postgresql://postgres:postgres@localhost:${dbPort}/postgres`+ ],+ join(root, "packages/database")+ );+}++async function execStrict(cmd: string, args: string[], cwd: string) {+ const r = await execa(cmd, args, { cwd, reject: false, preferLocal: true });+ if (r.exitCode !== 0) {+ process.stderr.write(r.stderr?.toString() ?? "");+ process.stdout.write(r.stdout?.toString() ?? "");+ throw new Error(`${cmd} ${args.join(" ")} failed (exit ${r.exitCode})`);+ }+}diff --git a/packages/dev/src/services/portless.ts b/packages/dev/src/services/portless.tsnew file mode 100644index 0000000000..75cf3afa20--- /dev/null+++ b/packages/dev/src/services/portless.ts@@ -0,0 +1,499 @@+import { existsSync, readFileSync, writeFileSync } 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 { execa, execaSync } from "execa";+import pc from "picocolors";+import {+ ALIAS_SERVICES,+ type AppId,+ PORTLESS_MIN_VERSION+} from "../constants.js";+import type { PortMap } from "../lib/ports.js";++// Strip npm_* / PNPM_* so portless doesn't refuse with "should not be run via+// npx or pnpm dlx" when invoked from `pnpm exec tsx`. Pair with+// `extendEnv: false` on the execa call.+function portlessEnv(): NodeJS.ProcessEnv {+ const out: NodeJS.ProcessEnv = {};+ for (const [k, v] of Object.entries(process.env)) {+ if (k.startsWith("PNPM_") || k.startsWith("npm_")) continue;+ out[k] = v;+ }+ return out;+}++export async function ensurePortlessInstalled() {+ const installed = await detectPortlessVersion();+ if (installed && cmpSemver(installed, PORTLESS_MIN_VERSION) >= 0) return;++ if (!installed) {+ log.warn(+ `portless is not installed globally. Required for app routing (${PORTLESS_MIN_VERSION}+).`+ );+ } else {+ log.warn(+ `portless v${installed} is too old. Need ${PORTLESS_MIN_VERSION}+ for monorepo + package.json config.`+ );+ }++ // Auto-yes paths: non-TTY stdin (we were invoked from a script/pipe) or+ // explicit env override. Otherwise interactive confirm.+ const autoYes = process.env.CARBON_DEV_YES === "1" || !process.stdin.isTTY;+ if (!autoYes) {+ const ok = await confirm({+ message: "Install portless@latest globally now?",+ initialValue: true+ });+ if (isCancel(ok) || !ok) {+ throw new Error(+ `Aborted. Install manually: ${pc.cyan("npm install -g portless@latest")} (or bun/pnpm equivalent).`+ );+ }+ } else {+ log.info("auto-installing portless (non-interactive / CARBON_DEV_YES=1)");+ }++ const s = spinner();+ s.start("installing portless@latest globally (pnpm add -g)");+ const r = await execa("pnpm", ["add", "-g", "portless@latest"], {+ reject: false+ });+ if (r.exitCode !== 0) {+ s.stop("✗ install failed");+ const stderr = r.stderr ?? "";+ const stdout = r.stdout ?? "";+ const combined = `${stderr}\n${stdout}`;++ // Fresh dev box: pnpm has no global bin dir. Surface pnpm's setup fix.+ if (/ERR_PNPM_NO_GLOBAL_BIN_DIR/.test(combined)) {+ log.error("pnpm has no global bin directory configured.");+ log.message(+ [+ "To fix this, run pnpm's one-time setup (creates ~/.local/share/pnpm",+ "and writes PNPM_HOME to your shell rc), then re-run `crbn up`:",+ "",+ ` ${pc.cyan("pnpm setup")}`,+ ` ${pc.cyan("source ~/.zshrc # or open a new shell")}`,+ ` ${pc.cyan("crbn up")}`,+ "",+ "Alternative — install portless via npm instead:",+ "",+ ` ${pc.cyan("npm install -g portless@latest")}`+ ].join("\n")+ );+ throw new Error("portless install aborted: pnpm global bin dir missing");+ }++ process.stderr.write(stderr);+ throw new Error(+ `pnpm add -g portless failed (exit ${r.exitCode}). Manual fallback: ${pc.cyan("npm install -g portless@latest")}`+ );+ }+ const after = await detectPortlessVersion();+ s.stop(`portless v${after ?? "?"} installed`);+}++export function startProxyDaemon(root: string) {+ execa("portless", ["proxy", "start"], {+ cwd: root,+ detached: true,+ stdio: "ignore",+ preferLocal: true,+ extendEnv: false,+ env: portlessEnv()+ }).unref();+}++// Must match render-env.ts hostnames + the api.carbon.dev OAuth alias.+const PORTLESS_TLD = "dev";++type PrivilegeIssue =+ | { kind: "wrong_port"; port: number }+ | { kind: "not_running" };++function detectPrivilegeIssues(): PrivilegeIssue[] {+ const issues: PrivilegeIssue[] = [];+ const portFile = `${homedir()}/.portless/proxy.port`;+ const pidFile = `${homedir()}/.portless/proxy.pid`;++ if (!existsSync(portFile) || !existsSync(pidFile)) {+ issues.push({ kind: "not_running" });+ return issues;+ }+ const pid = Number(readFileSync(pidFile, "utf8").trim());+ if (!isProcessAlive(pid)) {+ issues.push({ kind: "not_running" });+ return issues;+ }+ const port = Number(readFileSync(portFile, "utf8").trim());+ if (port && port !== 80 && port !== 443) {+ issues.push({ kind: "wrong_port", port });+ }+ return issues;+}++// Treat EPERM as alive — root-owned portless daemon is still serving even+// when we (normal user) can't signal it.+function isProcessAlive(pid: number): boolean {+ try {+ process.kill(pid, 0);+ return true;+ } catch (err) {+ return (err as NodeJS.ErrnoException).code === "EPERM";+ }+}++function describeIssues(issues: PrivilegeIssue[]): string {+ return issues+ .map((i) =>+ i.kind === "not_running"+ ? "portless proxy not running"+ : `proxy on :${i.port} (not :443; URLs would need port suffix)`+ )+ .join("\n • ");+}++// portless needs sudo to bind :443 and write /etc/hosts. `.dev` is a public+// HSTS-preloaded TLD so we rely on /etc/hosts (no /etc/resolver/<tld> for+// public TLDs).+export async function ensureProxyPrivileges() {+ const issues = detectPrivilegeIssues();+ if (issues.length === 0) return;++ log.warn(+ [+ "portless needs a privileged proxy to serve `*.dev` cleanly:",+ "",+ ` • ${describeIssues(issues)}`,+ "",+ "Without :443 + /etc/hosts entries, browsers hit the public `.dev` TLD",+ "(NXDOMAIN) or you'd have to type `:<port>` after every URL."+ ].join("\n")+ );++ const proceed = await confirm({+ message:+ "Set it up now? Will run sudo to bind :443, install the local CA, and write /etc/hosts entries.",+ initialValue: true+ });+ if (isCancel(proceed) || !proceed) {+ throw new Error(+ "Aborted. Run manually: `sudo portless proxy stop && sudo portless proxy start --tld dev && sudo portless trust`. Then re-run `crbn up`."+ );+ }++ log.info("running sudo commands — you'll be prompted for your password");++ // Preserve user HOME — sudo resets to root's HOME otherwise, sending+ // portless state (~/.portless) into /var/root/.portless.+ const sudoEnvArg = `HOME=${homedir()}`;++ await execa("sudo", [sudoEnvArg, "portless", "proxy", "stop"], {+ stdio: "inherit",+ reject: false+ });++ const start = await execa(+ "sudo",+ [sudoEnvArg, "portless", "proxy", "start", "--tld", PORTLESS_TLD],+ { stdio: "inherit", reject: false }+ );+ if (start.exitCode !== 0) {+ throw new Error(+ `sudo portless proxy start failed (exit ${start.exitCode})`+ );+ }++ const trust = await execa("sudo", [sudoEnvArg, "portless", "trust"], {+ stdio: "inherit",+ reject: false+ });+ if (trust.exitCode !== 0) {+ log.warn(+ `sudo portless trust failed (exit ${trust.exitCode}); browsers may show cert warnings until you run it manually.`+ );+ }++ const remaining = detectPrivilegeIssues();+ if (remaining.length > 0) {+ throw new Error(+ `portless setup still incomplete:\n • ${describeIssues(remaining)}`+ );+ }++ log.success("portless proxy on :443");+}++// Push registered routes into /etc/hosts. Needs sudo; idempotent.+export async function syncHostsFile() {+ const r = await execa(+ "sudo",+ [`HOME=${homedir()}`, "portless", "hosts", "sync"],+ { stdio: "inherit", reject: false }+ );+ if (r.exitCode !== 0) {+ throw new Error(+ `sudo portless hosts sync failed (exit ${r.exitCode}). Run it manually to fix DNS.`+ );+ }+}++// Root proxy daemon watches routes.json (fs.watch) and writes /etc/hosts+// itself — skip our manual sudo sync.+export function proxyRunsAsRoot(): boolean {+ const pidFile = `${homedir()}/.portless/proxy.pid`;+ if (!existsSync(pidFile)) return false;+ const pid = Number(readFileSync(pidFile, "utf8").trim());+ if (!pid) return false;+ try {+ const r = execaSync("ps", ["-p", String(pid), "-o", "user="]);+ return r.stdout.trim() === "root";+ } catch {+ return false;+ }+}++// True when every routes.json hostname appears inside /etc/hosts's+// portless-managed block. Lets `crbn up` skip the sudo sync on unchanged runs.+export function hostsFileInSync(): boolean {+ const routesPath = `${homedir()}/.portless/routes.json`;+ if (!existsSync(routesPath)) return true; // nothing to sync++ let hosts: { hostname: string }[];+ try {+ hosts = JSON.parse(readFileSync(routesPath, "utf8"));+ } catch {+ return false;+ }+ const desired = new Set(hosts.map((h) => h.hostname));+ if (desired.size === 0) return true;++ let etcHosts: string;+ try {+ etcHosts = readFileSync("/etc/hosts", "utf8");+ } catch {+ return false;+ }+ // Only check inside portless-managed block; outside is user-controlled.+ const startIdx = etcHosts.indexOf("# portless-start");+ const endIdx = etcHosts.indexOf("# portless-end");+ if (startIdx === -1 || endIdx === -1 || endIdx < startIdx) return false;+ const block = etcHosts.slice(startIdx, endIdx);+ const present = new Set<string>();+ for (const line of block.split("\n")) {+ const m = line.match(/^\s*\d+\.\d+\.\d+\.\d+\s+(\S+)/);+ if (m && m[1]) present.add(m[1]);+ }+ for (const h of desired) {+ if (!present.has(h)) return false;+ }+ return true;+}++export async function waitForProxyReady(timeoutMs = 30_000) {+ const tldFile = `${homedir()}/.portless/proxy.tld`;+ const pidFile = `${homedir()}/.portless/proxy.pid`;+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ if (existsSync(tldFile) && existsSync(pidFile)) {+ const pid = Number(readFileSync(pidFile, "utf8").trim());+ if (isProcessAlive(pid)) {+ await sleep(500);+ return;+ }+ }+ await sleep(500);+ }+}++export async function registerAliases(+ root: string,+ branchPrefix: string | null,+ ports: PortMap+) {+ const aliases = aliasMap(branchPrefix, ports);+ await Promise.all(+ aliases.map((a) =>+ execa("portless", ["alias", a.name, String(a.port), "--force"], {+ cwd: root,+ reject: false,+ stdio: "ignore",+ preferLocal: true,+ extendEnv: false,+ env: portlessEnv()+ })+ )+ );+ return aliases.length;+}++export async function unregisterAliases(+ root: string,+ branchPrefix: string | null+) {+ await Promise.all(+ ALIAS_SERVICES.map((s) => withPrefix(s, branchPrefix)).map((name) =>+ execa("portless", ["alias", "--remove", name], {+ cwd: root,+ reject: false,+ stdio: "ignore",+ preferLocal: true,+ extendEnv: false,+ env: portlessEnv()+ })+ )+ );+}++// Pre-empt `<prefix>.<app>.{dev,localhost}` routes before spawning apps.+// Orphan portless processes from a prior `crbn up` keep entries alive,+// causing `RouteConflictError` on the next run. SIGTERM → 400ms poll →+// SIGKILL stragglers, then drop matching entries.+export async function claimAppHosts(+ branchPrefix: string | null,+ appIds: readonly AppId[]+): Promise<number> {+ const path = `${homedir()}/.portless/routes.json`;+ if (!existsSync(path)) return 0;++ let routes: { hostname: string; port: number; pid: number }[];+ try {+ routes = JSON.parse(readFileSync(path, "utf8"));+ } catch {+ return 0;+ }++ const ourHosts = new Set(+ appIds.flatMap((id) => {+ const name = withPrefix(id, branchPrefix);+ return [`${name}.dev`, `${name}.localhost`];+ })+ );++ const pidsToKill = new Set<number>();+ for (const r of routes) {+ if (ourHosts.has(r.hostname) && r.pid > 0 && isProcessAlive(r.pid)) {+ pidsToKill.add(r.pid);+ }+ }++ for (const pid of pidsToKill) {+ try {+ process.kill(pid, "SIGTERM");+ // biome-ignore lint/suspicious/noEmptyBlockStatements: ignored using `--suppress`+ } catch {}+ }++ const deadline = Date.now() + 400;+ while (Date.now() < deadline) {+ let allGone = true;+ for (const pid of pidsToKill) {+ if (isProcessAlive(pid)) {+ allGone = false;+ break;+ }+ }+ if (allGone) break;+ await sleep(50);+ }+ for (const pid of pidsToKill) {+ if (isProcessAlive(pid)) {+ try {+ process.kill(pid, "SIGKILL");+ // biome-ignore lint/suspicious/noEmptyBlockStatements: ignored using `--suppress`+ } catch {}+ }+ }++ const filtered = routes.filter((r) => !ourHosts.has(r.hostname));+ if (filtered.length !== routes.length) {+ writeFileSync(path, JSON.stringify(filtered, null, 2));+ }++ return pidsToKill.size;+}++// Drop stale alias entries (pid=0, our hostname pattern) from routes.json.+export function pruneStaleRoutes(branchPrefix: string | null) {+ const path = `${homedir()}/.portless/routes.json`;+ if (!existsSync(path)) return 0;+ let routes: { hostname: string; pid: number }[];+ try {+ routes = JSON.parse(readFileSync(path, "utf8"));+ } catch {+ return 0;+ }+ const ourHosts = ALIAS_SERVICES.flatMap((s) => {+ const name = withPrefix(s, branchPrefix);+ return [`${name}.dev`, `${name}.localhost`];+ });+ const before = routes.length;+ const filtered = routes.filter(+ (r) => !(r.pid === 0 && ourHosts.includes(r.hostname))+ );+ if (filtered.length !== before) {+ writeFileSync(path, JSON.stringify(filtered, null, 2));+ return before - filtered.length;+ }+ return 0;+}++// Branch-independent OAuth callback host. Last `crbn up` wins. Keep in sync+// with SUPABASE_AUTH_EXTERNAL_*_REDIRECT_URI in render-env.ts.+const STABLE_OAUTH_ALIAS = "api.carbon";++const DEFAULT_BRANCHES = new Set(["main", "master", "trunk", "develop", "dev"]);++// Mirrors portless's branchToPrefix: last `/`-segment, sanitized.+// Null when branch missing/HEAD/default. e.g. `feat/boo` → `boo`.+export function branchToPrefix(+ branch: string | null | undefined+): string | null {+ if (!branch || branch === "HEAD" || DEFAULT_BRANCHES.has(branch)) return null;+ const last = branch.split("/").pop() ?? "";+ const sanitized = last+ .toLowerCase()+ .replace(/[^a-z0-9-]+/g, "-")+ .replace(/^-+|-+$/g, "")+ .replace(/-+/g, "-");+ return sanitized || null;+}++function withPrefix(name: string, prefix: string | null): string {+ return prefix ? `${prefix}.${name}` : name;+}++// Compose-service host:port aliases mirroring portless's app-host shape.+function aliasMap(+ branchPrefix: string | null,+ ports: PortMap+): { name: string; port: number }[] {+ return [+ { name: withPrefix("api", branchPrefix), port: ports.PORT_API },+ { name: withPrefix("studio", branchPrefix), port: ports.PORT_STUDIO },+ { name: withPrefix("mail", branchPrefix), port: ports.PORT_INBUCKET },+ { name: withPrefix("inngest", branchPrefix), port: ports.PORT_INNGEST },+ { name: STABLE_OAUTH_ALIAS, port: ports.PORT_API }+ ];+}++async function detectPortlessVersion(): Promise<string | null> {+ const r = await execa("portless", ["--version"], {+ reject: false,+ extendEnv: false,+ env: portlessEnv()+ });+ if (r.exitCode !== 0) return null;+ const m = r.stdout.match(/(\d+)\.(\d+)\.(\d+)/);+ return m ? m[0] : null;+}++function cmpSemver(a: string, b: string): number {+ const pa = a.split(".").map(Number);+ const pb = b.split(".").map(Number);+ for (let i = 0; i < 3; i++) {+ if ((pa[i] ?? 0) !== (pb[i] ?? 0)) return (pa[i] ?? 0) - (pb[i] ?? 0);+ }+ return 0;+}diff --git a/packages/dev/src/ui/prompts.ts b/packages/dev/src/ui/prompts.tsnew file mode 100644index 0000000000..864d960c75--- /dev/null+++ b/packages/dev/src/ui/prompts.ts@@ -0,0 +1,169 @@+import { existsSync } from "node:fs";+import { join } from "node:path";+import {+ cancel,+ confirm,+ isCancel,+ log,+ multiselect,+ select,+ text+} from "@clack/prompts";+import pc from "picocolors";+import { APP_CHOICES, type AppId } from "../constants.js";+import { branchExists, deleteBranch, listWorktrees } from "../lib/git.js";++// git-check-ref-format(1) rules.+const INVALID_BRANCH_RE =+ /(^[/-])|([/-]$)|(\.\.)|(@\{)|([\s~^:?*[\\])|(\/{2,})/;++export async function pickApps(): Promise<AppId[]> {+ const fromEnv = process.env.CARBON_DEV_APPS;+ if (fromEnv) {+ return fromEnv+ .split(",")+ .map((s) => s.trim())+ .filter((s): s is AppId => APP_CHOICES.some((c) => c.value === s));+ }+ if (!process.stdin.isTTY) return APP_CHOICES.map((c) => c.value);++ const picked = await multiselect({+ message: "Which apps to run?",+ options: APP_CHOICES.map((c) => ({+ value: c.value,+ label: c.label,+ hint: c.hint+ })),+ initialValues: APP_CHOICES.map((c) => c.value),+ required: true+ });+ if (isCancel(picked)) abort();+ return picked as AppId[];+}++export async function promptBranch(): Promise<string> {+ while (true) {+ const value = await text({+ message: "Branch name",+ placeholder: "feature/foo",+ validate(v) {+ if (!v || !v.trim()) return "Branch is required";+ const t = v.trim();+ if (INVALID_BRANCH_RE.test(t))+ return "Invalid git branch name (no spaces, control chars, ~^:?*[\\, no leading/trailing - or /, no '..' or '@{')";+ if (t.length > 100) return "Branch name too long";+ }+ });+ if (isCancel(value)) abort();+ const trimmed = (value as string).trim();+ if (await branchExists(trimmed)) {+ const worktrees = await listWorktrees();+ const onWorktree = worktrees.find((w) => w.branch === trimmed);+ if (onWorktree) {+ log.error(+ `Branch '${trimmed}' already has a worktree at ${pc.dim(onWorktree.path)}\n` ++ ` Jump in with: ${pc.cyan(`crbn go ${trimmed}`)}`+ );+ continue;+ }+ // Branch without worktree → offer in-flow nuke + recreate.+ log.warn(+ `Branch '${trimmed}' exists locally but has no worktree.\n` ++ ` Materialize the existing branch with: ${pc.cyan(`crbn checkout ${trimmed}`)}`+ );+ const recreate = await confirm({+ message: `Delete '${trimmed}' (force) and create fresh branch?`,+ initialValue: false+ });+ if (isCancel(recreate)) abort();+ if (!recreate) continue;+ const del = await deleteBranch(trimmed);+ if (!del.ok) {+ log.error(`Failed to delete branch: ${del.error}`);+ continue;+ }+ log.success(`Deleted branch '${trimmed}'`);+ }+ return trimmed;+ }+}++export async function promptDirName(+ parentDir: string,+ initial: string+): Promise<string> {+ while (true) {+ const value = await text({+ message: `Worktree directory (relative to ${pc.dim(parentDir)})`,+ initialValue: initial,+ validate(v) {+ if (!v || !v.trim()) return "Directory name required";+ if (/[\s/]/.test(v.trim()))+ return "No spaces or slashes — must be a single dirname";+ }+ });+ if (isCancel(value)) abort();+ const trimmed = (value as string).trim();+ if (existsSync(join(parentDir, trimmed))) {+ log.error(`Path '${trimmed}' already exists in ${parentDir}`);+ continue;+ }+ return trimmed;+ }+}++export async function promptBaseRef(+ currentBranch: string | null+): Promise<string> {+ const opts: { value: string; label: string }[] = [+ { value: "main", label: "main" }+ ];+ if (currentBranch && currentBranch !== "main") {+ opts.push({ value: currentBranch, label: currentBranch });+ }+ opts.push({ value: "origin/main", label: "origin/main" });++ const baseRef = await select({+ message: "Base ref",+ options: opts,+ initialValue: "main"+ });+ if (isCancel(baseRef)) abort();+ return baseRef as string;+}++export async function promptCopyEnv(): Promise<boolean> {+ const ok = await confirm({+ message: "Copy .env from current worktree?",+ initialValue: true+ });+ if (isCancel(ok)) abort();+ return ok as boolean;+}++export async function confirmReset(projectName: string): Promise<boolean> {+ if (process.env.CARBON_DEV_YES === "1") return true;+ const ok = await confirm({+ message: `Destroy all volumes for ${pc.bold(projectName)}? (postgres, storage, inngest data will be wiped, redis db flushed)`,+ initialValue: false+ });+ if (isCancel(ok)) return false;+ return ok as boolean;+}++export async function confirmRemove(opts: {+ branchOrPath: string;+ hasStack: boolean;+}): Promise<boolean> {+ const ok = await confirm({+ message: `Permanently remove ${opts.branchOrPath} and ${opts.hasStack ? "wipe its docker volumes" : "the worktree"}?`,+ initialValue: false+ });+ if (isCancel(ok)) return false;+ return ok as boolean;+}++function abort(): never {+ cancel("aborted");+ process.exit(0);+}diff --git a/packages/dev/src/ui/summary.ts b/packages/dev/src/ui/summary.tsnew file mode 100644index 0000000000..42f1e62827--- /dev/null+++ b/packages/dev/src/ui/summary.ts@@ -0,0 +1,42 @@+import pc from "picocolors";+import { TLD } from "../constants.js";+import type { PortMap } from "../lib/ports.js";++/**+ * OSC 8 hyperlink. Supported by iTerm2, Terminal.app, Warp, kitty, etc.+ * Falls back to plain text in unsupported terminals.+ */+function link(url: string, text?: string): string {+ const label = text ?? url;+ return `\x1b]8;;${url}\x1b\\${label}\x1b]8;;\x1b\\`;+}++type Color = (s: string) => string;++/** Boxed list of URLs + DB DSN for the up-summary. */+export function summaryLines(+ ports: PortMap,+ branchPrefix: string | null+): string[] {+ const host = (sub: string) =>+ branchPrefix+ ? `https://${branchPrefix}.${sub}.${TLD}`+ : `https://${sub}.${TLD}`;+ const dbUrl = `postgresql://postgres:postgres@localhost:${ports.PORT_DB}/postgres`;+ return [+ row(pc.cyan, "ERP", host("erp")),+ row(pc.magenta, "MES", host("mes")),+ row(pc.green, "API", host("api"), ports.PORT_API),+ row(pc.green, "Studio", host("studio"), ports.PORT_STUDIO),+ row(pc.yellow, "Mail", host("mail"), ports.PORT_INBUCKET),+ row(pc.blue, "Inngest", host("inngest"), ports.PORT_INNGEST),+ `${pc.gray(pc.bold("Postgres".padEnd(8)))} ${pc.gray(dbUrl)}`+ ];+}++function row(color: Color, label: string, url: string, port?: number): string {+ const lbl = color(pc.bold(label.padEnd(8)));+ const target = color(link(url));+ const portTag = port ? ` ${pc.dim(`:${port}`)}` : "";+ return `${lbl} ${target}${portTag}`;+}diff --git a/packages/dev/src/ui/tables.ts b/packages/dev/src/ui/tables.tsnew file mode 100644index 0000000000..db7b46fc51--- /dev/null+++ b/packages/dev/src/ui/tables.ts@@ -0,0 +1,113 @@+import Table from "cli-table3";+import pc from "picocolors";+import { PORT_NAMES, type PortMap, SHARED_REDIS_PORT } from "../lib/ports.js";+import type { Container } from "../services/compose.js";++/** Common cli-table3 style: gray border, no inter-row separators. */+const BASE_STYLE = {+ style: { head: [], border: ["gray"] as string[] },+ chars: {+ mid: "",+ "left-mid": "",+ "mid-mid": "",+ "right-mid": ""+ }+};++/** Per-worktree port + redis-db assignment table. */+export function portsTable(+ ports: PortMap,+ redisDb: number | undefined+): string {+ const t = new Table({+ head: [pc.bold("Service"), pc.bold("Port")],+ ...BASE_STYLE+ });+ for (const n of PORT_NAMES) {+ t.push([+ pc.cyan(n.replace("PORT_", "").toLowerCase()),+ pc.bold(String(ports[n]))+ ]);+ }+ t.push([+ pc.cyan("redis (shared)"),+ pc.bold(String(SHARED_REDIS_PORT)) ++ pc.dim(typeof redisDb === "number" ? ` /db ${redisDb}` : " /db ?")+ ]);+ return t.toString();+}++/** Compose-stack health table for `dev status`. */+export function servicesTable(containers: Container[]): string {+ const sorted = [...containers].sort((a, b) =>+ a.Service.localeCompare(b.Service)+ );+ const t = new Table({+ head: [pc.bold("Service"), pc.bold("Status"), pc.bold("Ports")],+ ...BASE_STYLE+ });+ for (const c of sorted) {+ t.push([pc.cyan(c.Service), colorState(c.State, c.Health), formatPorts(c)]);+ }+ return t.toString();+}++/** Worktree list table for `dev list`. */+export function worktreesTable(+ rows: {+ path: string;+ branch: string | null;+ current: boolean;+ slug: string | null;+ dockerState: string | null;+ }[]+): string {+ const t = new Table({+ head: [pc.bold("Worktree"), pc.bold("Branch"), pc.bold("Stack")],+ ...BASE_STYLE+ });+ for (const r of rows) {+ const project = r.slug ? `carbon-${r.slug}` : "—";+ const stack = !r.slug+ ? pc.gray("not initialized")+ : r.dockerState === "running"+ ? pc.green(`● up · ${project}`)+ : r.dockerState+ ? pc.yellow(`${r.dockerState} · ${project}`)+ : pc.dim(`registered · ${project}`);+ t.push([+ r.current ? pc.bold(pc.cyan(r.path)) : r.path,+ r.branch ? pc.cyan(r.branch) : pc.dim("(detached)"),+ stack+ ]);+ }+ return t.toString();+}++function colorState(state: string, health?: string): string {+ const s = state.toLowerCase();+ if (s === "running" && health === "unhealthy")+ return pc.yellow("◑ unhealthy");+ if (s === "running" && health === "starting") return pc.yellow("◐ starting");+ if (s === "running") return pc.green("● running");+ if (s === "restarting") return pc.yellow("◌ restarting");+ if (s === "exited") return pc.red("✗ exited");+ if (s === "created") return pc.gray("○ created");+ return pc.dim(state);+}++function formatPorts(c: Container): string {+ if (!c.Publishers || c.Publishers.length === 0) return pc.dim("—");+ const seen = new Set<string>();+ const out: string[] = [];+ for (const p of c.Publishers) {+ if (!p.PublishedPort) continue;+ const key = `${p.PublishedPort}:${p.TargetPort}`;+ if (seen.has(key)) continue;+ seen.add(key);+ out.push(+ `${pc.cyan(String(p.PublishedPort))}${pc.dim("→" + p.TargetPort)}`+ );+ }+ return out.length ? out.join(" ") : pc.dim("—");+}diff --git a/packages/dev/tsconfig.json b/packages/dev/tsconfig.jsonnew file mode 100644index 0000000000..d52742e935--- /dev/null+++ b/packages/dev/tsconfig.json@@ -0,0 +1,13 @@+{+ "extends": "@carbon/config/tsconfig/base.json",+ "compilerOptions": {+ "module": "nodenext",+ "moduleResolution": "nodenext",+ "target": "es2022",+ "esModuleInterop": true,+ "skipLibCheck": true,+ "strict": true,+ "noEmit": true+ },+ "include": ["src/**/*", "bin.mjs"]+}diff --git a/packages/documents/package.json b/packages/documents/package.jsonindex 7460a2b6b6..98c049a2fb 100644--- a/packages/documents/package.json+++ b/packages/documents/package.json@@ -38,8 +38,7 @@"clean": "rimraf .turbo node_modules dist","lint": "biome lint --write ","test": "vitest run",- "typecheck": "tsgo --noEmit",- "types": "tsc"+ "typecheck": "tsgo --noEmit"},"sideEffects": false,"version": "0.0.0"diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e15cf29973..560c251002 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -347,9 +347,15 @@ importers:'@typescript/native-preview':specifier: 7.0.0-dev.20260409.1version: 7.0.0-dev.20260409.1+ cli-table3:+ specifier: ^0.6.5+ version: 0.6.5csv-parse:specifier: 5.6.0version: 5.6.0+ execa:+ specifier: ^8.0.1+ version: 8.0.1husky:specifier: 8.0.3version: 8.0.3@@ -1862,6 +1868,49 @@ importers:specifier: 9.0.0version: 9.0.0+ packages/dev:+ dependencies:+ '@bomb.sh/tab':+ specifier: ^0.0.15+ version: 0.0.15([email protected])([email protected])+ '@clack/prompts':+ specifier: ^1.3.0+ version: 1.3.0+ citty:+ specifier: ^0.1.6+ version: 0.1.6+ cli-table3:+ specifier: ^0.6.5+ version: 0.6.5+ dotenv:+ specifier: 16.3.1+ version: 16.3.1+ execa:+ specifier: ^8.0.1+ version: 8.0.1+ get-port-please:+ specifier: ^3.2.0+ version: 3.2.0+ picocolors:+ specifier: ^1.1.1+ version: 1.1.1+ devDependencies:+ '@carbon/config':+ specifier: '*'+ version: link:../config+ '@types/node':+ specifier: 20.19.39+ version: 20.19.39+ rimraf:+ specifier: 5.0.10+ version: 5.0.10+ tsx:+ specifier: 4.21.0+ version: 4.21.0+ typescript:+ specifier: 5.8.3+ version: 5.8.3+packages/documents:dependencies:'@bwip-js/node':@@ -3433,6 +3482,21 @@ packages:cpu: [x64]os: [win32]+ '@bomb.sh/[email protected]':+ resolution: {integrity: sha512-Y90ub44TAvbdO9P8mcD/XPyQjFhiR5xmd4Fk7JErmWmEWEUimNnjWiBrVZ16Tj3GA1rLZ+uvCN2V/pzLawv31g==}+ hasBin: true+ peerDependencies:+ cac: ^6.7.14+ citty: ^0.1.6 || ^0.2.0+ commander: ^13.1.0+ peerDependenciesMeta:+ cac:+ optional: true+ citty:+ optional: true+ commander:+ optional: true+'@bufbuild/[email protected]':resolution: {integrity: sha512-sBXGT13cpmPR5BMgHE6UEEfEaShh5Ror6rfN3yEK5si7QVrtZg8LEPQb0VVhiLRUslD2yLnXtnRzG035J/mZXQ==}@@ -3442,6 +3506,18 @@ packages:'@cfcs/[email protected]':resolution: {integrity: sha512-FxfJMwoLB8MEMConeXUCqtMGqxdtePQxRBOiGip9ULcYYam3WfCgoY6xdnMaSkYvRvmosp5iuG+TiPofm65+Pw==}+ '@clack/[email protected]':+ resolution: {integrity: sha512-xJPHpAmEQUBrXSLx0gF+q5K/IyihXpsHZcha+jB+tyahsKRK3Dxo4D0coZDewHo12NhiuzC3dTtMPbm53GEAAA==}+ engines: {node: '>= 20.12.0'}++ '@clack/[email protected]':+ resolution: {integrity: sha512-GgcWwRCs/xPtaqlMy8qRhPnZf9vlWcWZNHAitnVQ3yk7JmSralSiq5q07yaffYE8SogtDm7zFeKccx1QNVARpw==}+ engines: {node: '>= 20.12.0'}++ '@colors/[email protected]':+ resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==}+ engines: {node: '>=0.1.90'}+'@csstools/[email protected]':resolution: {integrity: sha512-uWvSaeRcHyeNenKg8tp17EVDRkpflmdyvbE0DHo6D/GdBb6PDnCYYU6gRpXhtICMGMcahQmj2zGxwFM/WC8hCg==}engines: {node: ^14 || ^16 || >=18}@@ -8194,6 +8270,9 @@ packages:resolution: {integrity: sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==}engines: {node: '>=18'}+ resolution: {integrity: sha512-tskPPKEs8D2KPafUypv2gxwJP8h/OaJmC82QQGGDQcHvXX43xF2VDACcJVmZ0EuSxkpO9Kc4MlrA3q0+FG58AQ==}+resolution: {integrity: sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q==}@@ -8221,6 +8300,10 @@ packages:resolution: {integrity: sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==}engines: {node: '>=6'}+ resolution: {integrity: sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ==}+ engines: {node: 10.* || >= 12.*}+resolution: {integrity: sha512-IqLQi4lO0nIB4tcdTpN4LCB9FI3uqrJZK7RC515EnhZ6qBaglkIgICb1wjeAqpdoOabm1+SuQtkXIPdYC93jhQ==}engines: {node: '>= 0.2.0'}@@ -8963,9 +9046,18 @@ packages:resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==}engines: {node: '>=8.6.0'}+ resolution: {integrity: sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==}++ resolution: {integrity: sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==}+resolution: {integrity: sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==}+ resolution: {integrity: sha512-rLV8JHxTyhVmFYhBJuMujcrHqOT2cnO5Zxj37qROj23CP39GXubJRBUFF0z8KFK77Uc0SukZUf7JZhsVEQ6n8w==}+resolution: {integrity: sha512-jcyKVSEX13iseJqg7n/KWw+xnu/7fdrZ333Fac54KjHDIELVCfDDJXYIm6DTJ0Su4gSzrhqiK0DzY/wZbF40mw==}@@ -9156,6 +9248,9 @@ packages:resolution: {integrity: sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==}engines: {node: '>=6'}+ resolution: {integrity: sha512-I9QVvBw5U/hw3RmWpYKRumUeaDgxTPd401x364rLmWBJcOQ753eov1eTgzDqRG9bqFIfDc7gfzcQEWrUri3o1A==}+resolution: {integrity: sha512-g/Q1aTSDOxFpchXC4i8ZWvxA1lnPqx/JHqcpIw0/LX9T8x/GBbi6YnlN5nhaKIFkT8oFsscUKgDJYxfwfS6QsQ==}engines: {node: '>=8'}@@ -11515,6 +11610,9 @@ packages:resolution: {integrity: sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==}engines: {node: '>=10'}+ resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==}+resolution: {integrity: sha512-iOBWFgUX7caIZiuutICxVgX1SdxwAVFFKwt1EvMYYec/NWO5meOJ6K5uQxhrYBdQJne4KxiqZc+KptFOWFSI9w==}engines: {node: '>=18'}@@ -13130,6 +13228,11 @@ snapshots:'@biomejs/[email protected]':optional: true+ optionalDependencies:+ cac: 6.7.14+ citty: 0.1.6+'@bufbuild/[email protected]': {}'@bwip-js/[email protected]': {}@@ -13138,6 +13241,21 @@ snapshots:dependencies:'@egjs/component': 3.0.5+ '@clack/[email protected]':+ dependencies:+ fast-wrap-ansi: 0.2.0+ sisteransi: 1.0.5++ '@clack/[email protected]':+ dependencies:+ '@clack/core': 1.3.0+ fast-string-width: 3.0.2+ fast-wrap-ansi: 0.2.0+ sisteransi: 1.0.5++ '@colors/[email protected]':+ optional: true+'@csstools/[email protected]([email protected])':dependencies:postcss-selector-parser: 6.1.2@@ -18857,6 +18975,10 @@ snapshots:+ dependencies:+ consola: 3.4.2+@@ -18879,6 +19001,12 @@ snapshots:+ dependencies:+ string-width: 4.2.3+ optionalDependencies:+ '@colors/colors': 1.5.0+dependencies:colors: 1.0.3@@ -19771,8 +19899,18 @@ snapshots:merge2: 1.4.1micromatch: 4.0.8+ [email protected]: {}++ dependencies:+ fast-string-truncated-width: 3.0.3++ dependencies:+ fast-string-width: 3.0.2+dependencies:path-expression-matcher: 1.5.0@@ -19983,6 +20121,8 @@ snapshots:+ [email protected]: {}+@@ -22872,6 +23012,8 @@ snapshots:dependencies:semver: 7.7.4+ [email protected]: {}+dependencies:ansi-styles: 6.2.1diff --git a/scripts/generate-db-types.ts b/scripts/generate-db-types.tsindex eeb9ebd1e0..33b60330e1 100644--- a/scripts/generate-db-types.ts+++ b/scripts/generate-db-types.ts@@ -1,28 +1,62 @@-import { exec } from "child_process";+import { closeSync, copyFileSync, openSync } from "node:fs";+import { spawnSync } from "node:child_process";+import { join } from "node:path";import * as dotenv from "dotenv";-dotenv.config();-const SUPABASE_URL = process.env.SUPABASE_URL;+dotenv.config({ path: ".env" });+dotenv.config({ path: ".env.local", override: true });-if (!SUPABASE_URL) {- throw new Error("Missing SUPABASE_URL");+const dbUrl = process.env.SUPABASE_DB_URL;+if (!dbUrl) {+ console.error(+ "SUPABASE_DB_URL not set (expected in .env or .env.local). Run `pnpm dev:up` first."+ );+ process.exit(1);+}++if (!/(localhost|127\.0\.0\.1)/.test(dbUrl)) {+ console.error(+ `Refusing to generate types against non-local DB: ${dbUrl.replace(/:[^:@/]+@/, ":***@")}`+ );+ process.exit(1);}-if (SUPABASE_URL.includes("localhost")) {- exec(- "pnpm run db:types && cp packages/database/src/types.ts packages/database/supabase/functions/lib/types.ts",- (error, stdout, stderr) => {- if (error) {- console.error(`error: ${error.message}`);- return;- }+const typesPath = join("packages", "database", "src", "types.ts");+const fnTypesPath = join(+ "packages",+ "database",+ "supabase",+ "functions",+ "lib",+ "types.ts"+);- if (stderr) {- console.error(`stderr: ${stderr}`);- return;- }+// Pipe supabase stdout directly to the types file to avoid spawnSync's 1MB+// default buffer cap (generated types are ~MBs).+const out = openSync(typesPath, "w");+const r = spawnSync(+ "supabase",+ [+ "gen",+ "types",+ "typescript",+ "--db-url",+ dbUrl,+ "--schema",+ "public",+ "--schema",+ "storage",+ "--schema",+ "graphql_public"+ ],+ { stdio: ["ignore", out, "inherit"] }+);+closeSync(out);- console.log(`stdout:\n${stdout}`);- }- );+if (r.status !== 0) {+ console.error(`supabase gen types failed (exit ${r.status})`);+ process.exit(r.status ?? 1);}++copyFileSync(typesPath, fnTypesPath);+console.log(`wrote ${typesPath}\nwrote ${fnTypesPath}`);diff --git a/scripts/generate-swagger-docs.ts b/scripts/generate-swagger-docs.tsindex 234bd19d8d..0f6ec70acc 100644--- a/scripts/generate-swagger-docs.ts+++ b/scripts/generate-swagger-docs.ts@@ -1,15 +1,27 @@-import { writeFileSync } from "fs";-(async () => {- const response = await fetch(- "http://localhost:54323/api/platform/projects/default/api/rest"+import { writeFileSync } from "node:fs";+import * as dotenv from "dotenv";++dotenv.config({ path: ".env" });+dotenv.config({ path: ".env.local", override: true });++const studioPort = process.env.PORT_STUDIO;+if (!studioPort) {+ console.error(+ "PORT_STUDIO not set (expected in .env.local). Run `pnpm dev:up` first.");+ process.exit(1);+}++const url = `http://localhost:${studioPort}/api/platform/projects/default/api/rest`;++(async () => {+ const response = await fetch(url);if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}const data = await response.json();- // write the data to a javascript file using node fs modulewriteFileSync("packages/database/src/swagger-docs-schema.ts",`export default ${JSON.stringify(data, null, 2)}`diff --git a/scripts/setup-env-files.ts b/scripts/setup-env-files.tsindex 203f6df93a..116e5150ff 100644--- a/scripts/setup-env-files.ts+++ b/scripts/setup-env-files.ts@@ -2,6 +2,7 @@ import { existsSync, symlinkSync, unlinkSync } from "fs";import { join } from "path";const ROOT_ENV_PATH = join(process.cwd(), ".env");+const ROOT_ENV_LOCAL_PATH = join(process.cwd(), ".env.local");if (!existsSync(ROOT_ENV_PATH)) {throw new Error("No .env file found in root directory");@@ -28,25 +29,26 @@ function createSymlink(targetPath: string, sourcePath: string) {}}+function linkBoth(targetDir: string) {+ createSymlink(join(targetDir, ".env"), ROOT_ENV_PATH);+ if (existsSync(ROOT_ENV_LOCAL_PATH)) {+ createSymlink(join(targetDir, ".env.local"), ROOT_ENV_LOCAL_PATH);+ }+}+// Create symlinks in apps directoryif (existsSync(APPS_DIR)) {const apps = ["erp", "mes", "academy", "starter"];- apps.forEach((app) => {- const appEnvPath = join(APPS_DIR, app, ".env");- createSymlink(appEnvPath, ROOT_ENV_PATH);- });+ apps.forEach((app) => linkBoth(join(APPS_DIR, app)));}// Create symlinks in selected packagesif (existsSync(PACKAGES_DIR)) {- PACKAGE_FOLDERS.forEach((pkg) => {- const pkgEnvPath = join(PACKAGES_DIR, pkg, ".env");- createSymlink(pkgEnvPath, ROOT_ENV_PATH);- });+ PACKAGE_FOLDERS.forEach((pkg) => linkBoth(join(PACKAGES_DIR, pkg)));}// Copy root .env into supabase/functions/.env so edge functions get all env vars// Must be a copy (not symlink) because edge functions run inside Docker-const supabaseFunctionsEnv = join(PACKAGES_DIR, "database", "supabase", "functions", ".env");-createSymlink(supabaseFunctionsEnv, ROOT_ENV_PATH);+const supabaseFunctionsDir = join(PACKAGES_DIR, "database", "supabase", "functions");+linkBoth(supabaseFunctionsDir);console.log("Environment file setup complete!");diff --git a/setup.sh b/setup.shnew file mode 100755index 0000000000..6f987166e8--- /dev/null+++ b/setup.sh@@ -0,0 +1,380 @@+#!/usr/bin/env bash+# Idempotent one-time setup: adds <repo>/packages/dev/bin to PATH and installs+# the `crbn()` shell function (so `crbn go <branch>` can mutate the caller's+# cwd).+#+# Run from the repo root:+# ./setup.sh # install+# source ./setup.sh # install + activate in current shell+# ./setup.sh --uninstall # remove+#+# When sourced we delegate to a child process for the actual install, then+# source the rc back in the caller. This keeps `set -e`/`exit` from leaking+# into the user's interactive shell (which closes the tab on the first+# expected non-zero exit, e.g. when re-running on an already-installed rc).++# ---------------------------------------------------------------------------+# Sourced detection (bash + zsh)+# ---------------------------------------------------------------------------++__crbn_setup_sourced=0+if [[ -n "${BASH_SOURCE[0]:-}" && "${BASH_SOURCE[0]}" != "${0:-}" ]]; then+ __crbn_setup_sourced=1+fi+if [[ -n "${ZSH_EVAL_CONTEXT:-}" && "$ZSH_EVAL_CONTEXT" == *:file* ]]; then+ __crbn_setup_sourced=1+fi++# When sourced: spawn child to install (no option/exit leakage), then source+# the rc into THIS shell so PATH + crbn() take effect immediately.+if (( __crbn_setup_sourced )); then+ # In bash: BASH_SOURCE[0] is the sourced file. In zsh: $0 is the sourced+ # file (when FUNCTION_ARGZERO is set, the default).+ __crbn_setup_script="${BASH_SOURCE[0]:-$0}"++ bash "$__crbn_setup_script" "$@"; __crbn_setup_rc=$?+ if (( __crbn_setup_rc != 0 )); then+ unset __crbn_setup_sourced __crbn_setup_script __crbn_setup_rc+ return "$__crbn_setup_rc" 2>/dev/null+ fi++ # Activate in the current shell only on install paths (not --uninstall/help).+ case "${1:-}" in+ ""|install)+ __crbn_setup_target="${RC_FILE:-}"+ if [[ -z "$__crbn_setup_target" ]]; then+ case "${SHELL:-}" in+ */zsh) __crbn_setup_target="$HOME/.zshrc" ;;+ */bash) __crbn_setup_target="$HOME/.bashrc" ;;+ *)+ if [[ -f "$HOME/.zshrc" ]]; then __crbn_setup_target="$HOME/.zshrc"+ elif [[ -f "$HOME/.bashrc" ]]; then __crbn_setup_target="$HOME/.bashrc"+ else __crbn_setup_target="$HOME/.zshrc"+ fi+ ;;+ esac+ fi+ if [[ -f "$__crbn_setup_target" ]] && grep -qF "# >>> carbon dev cli (managed by setup.sh) >>>" "$__crbn_setup_target"; then+ # shellcheck disable=SC1090+ source "$__crbn_setup_target"+ printf '\n \033[1;36mcrbn\033[0m active in this shell. try: \033[1;36mcrbn\033[0m\n\n'+ fi+ unset __crbn_setup_target+ ;;+ esac++ unset __crbn_setup_sourced __crbn_setup_script __crbn_setup_rc+ return 0 2>/dev/null+fi++# ---------------------------------------------------------------------------+# Direct invocation: real work happens here.+# ---------------------------------------------------------------------------++set -euo pipefail++SENTINEL_OPEN="# >>> carbon dev cli (managed by setup.sh) >>>"+SENTINEL_CLOSE="# <<< carbon dev cli <<<"++# Output helpers — colors when stdout is a TTY.+if [[ -t 1 ]] && command -v tput >/dev/null 2>&1 && [[ "$(tput colors 2>/dev/null || echo 0)" -ge 8 ]]; then+ C_BOLD=$(tput bold); C_DIM=$(tput dim); C_RESET=$(tput sgr0)+ C_GREEN=$(tput setaf 2); C_YELLOW=$(tput setaf 3); C_CYAN=$(tput setaf 6); C_RED=$(tput setaf 1)+else+ C_BOLD=""; C_DIM=""; C_RESET=""; C_GREEN=""; C_YELLOW=""; C_CYAN=""; C_RED=""+fi++ok() { printf '%s✓%s %s\n' "$C_GREEN" "$C_RESET" "$*"; }+info() { printf '%s•%s %s\n' "$C_CYAN" "$C_RESET" "$*"; }+warn() { printf '%s!%s %s\n' "$C_YELLOW" "$C_RESET" "$*"; }+fail() { printf '%s✗%s %s\n' "$C_RED" "$C_RESET" "$*" >&2; }+hdr() { printf '\n%s%s%s\n' "$C_BOLD" "$*" "$C_RESET"; }+kbd() { printf '%s%s%s' "$C_BOLD$C_CYAN" "$*" "$C_RESET"; }+dim() { printf '%s%s%s' "$C_DIM" "$*" "$C_RESET"; }++repo_root() {+ git rev-parse --show-toplevel 2>/dev/null \+ || { fail "not inside a git repo (cd into the carbon checkout first)"; exit 1; }+}++detect_rc() {+ if [[ -n "${RC_FILE:-}" ]]; then printf '%s\n' "$RC_FILE"; return; fi+ case "${SHELL:-}" in+ */zsh) printf '%s\n' "$HOME/.zshrc" ;;+ */bash) printf '%s\n' "$HOME/.bashrc" ;;+ *)+ if [[ -f "$HOME/.zshrc" ]]; then printf '%s\n' "$HOME/.zshrc"+ elif [[ -f "$HOME/.bashrc" ]]; then printf '%s\n' "$HOME/.bashrc"+ else printf '%s\n' "$HOME/.zshrc"+ fi+ ;;+ esac+}++block_for() {+ local repo="$1"+ local shell="$2"+ cat <<EOF+$SENTINEL_OPEN+export PATH="$repo/packages/dev/bin:\$PATH"+crbn() {+ # Wrap \`checkout\` so the trailing \`cd '<path>'\` on stdout becomes an+ # actual cd in the caller's shell. \`--up\` execs into \`crbn up\` and would+ # clobber the captured stdout, so bypass capture there.+ if [[ "\${1:-}" == "checkout" ]]; then+ local arg+ for arg in "\$@"; do+ if [[ "\$arg" == "--up" ]]; then+ command crbn "\$@"+ return \$?+ fi+ done+ local out+ out="\$(command crbn "\$@")" || return \$?+ [[ -n "\$out" ]] && eval "\$out"+ else+ command crbn "\$@"+ fi+}+# Tab completion (generated by \`crbn complete $shell\`).+if command -v crbn >/dev/null 2>&1; then+ source <(crbn complete $shell 2>/dev/null) || true+fi+$SENTINEL_CLOSE+EOF+}++uninstall() {+ local rc; rc="$(detect_rc)"+ hdr "Uninstall"+ if [[ ! -f "$rc" ]]; then info "no rc file at $(dim "$rc") — nothing to do";+ elif ! grep -qF "$SENTINEL_OPEN" "$rc"; then+ info "no crbn block found in $(dim "$rc") — nothing to do"+ else+ local tmp; tmp="$(mktemp)"+ awk -v sopen="$SENTINEL_OPEN" -v sclose="$SENTINEL_CLOSE" '+ $0 == sopen { skip=1; next }+ skip && $0 == sclose { skip=0; next }+ !skip+ ' "$rc" > "$tmp"+ mv "$tmp" "$rc"+ ok "removed crbn block from $(dim "$rc")"+ info "open a new shell to clear PATH and the crbn() function"+ fi++ uninstall_proxy_daemon+}++LAUNCHD_PLIST="/Library/LaunchDaemons/dev.portless.proxy.plist"++# Install portless globally. Prefer pnpm, fall back to npm. Surface pnpm's+# missing-global-bin-dir hint the CLI does in packages/dev/src/services/portless.ts+# so the user gets the same actionable error in both entry points.+install_portless_global() {+ hdr "Installing portless"+ info "Required for *.dev hostname routing on :443."++ if command -v pnpm >/dev/null 2>&1; then+ local out+ if out=$(pnpm add -g portless@latest 2>&1); then+ ok "portless installed via pnpm"+ return 0+ fi+ if grep -q "ERR_PNPM_NO_GLOBAL_BIN_DIR" <<<"$out"; then+ warn "pnpm has no global bin dir configured. Run \`pnpm setup\`, open a new shell, then re-run \`./setup.sh\`."+ printf '%s\n' "$out" >&2+ return 1+ fi+ printf '%s\n' "$out" >&2+ warn "pnpm install failed — falling back to npm"+ fi++ if command -v npm >/dev/null 2>&1; then+ if npm install -g portless@latest; then+ ok "portless installed via npm"+ return 0+ fi+ fail "npm install -g portless@latest failed"+ return 1+ fi++ fail "no pnpm or npm on PATH — install one of them and re-run"+ return 1+}++# Install portless as a LaunchDaemon (macOS) so the :443 proxy starts at boot+# and crash-restarts. Sidesteps the per-`crbn up` sudo prompt cycle for+# `proxy start` (writing /etc/hosts via `portless hosts sync` still needs+# sudo on first run only — our CLI skips it when hosts are already in sync).+install_proxy_daemon() {+ if [[ "$(uname -s)" != "Darwin" ]]; then+ info "non-macOS — skipping LaunchDaemon install"+ return 0+ fi++ if [[ -f "$LAUNCHD_PLIST" ]]; then+ info "LaunchDaemon already installed at $(dim "$LAUNCHD_PLIST")"+ return 0+ fi++ local portless_bin+ portless_bin="$(command -v portless || true)"+ if [[ -z "$portless_bin" ]]; then+ install_portless_global+ portless_bin="$(command -v portless || true)"+ if [[ -z "$portless_bin" ]]; then+ warn "portless still not on PATH after install attempt — skipping boot-start. Install manually, then re-run \`./setup.sh\`."+ return 0+ fi+ fi++ hdr "Boot-start portless proxy"+ info "Installs $(dim "$LAUNCHD_PLIST") so :443 survives reboots."+ info "One sudo prompt now, none on every \`crbn up\` after that."+ printf '\n %s\n' "$(kbd "ctrl-c to skip")"+ read -r -p " press enter to continue " _++ local plist_tmp+ plist_tmp="$(mktemp)"+ cat > "$plist_tmp" <<EOF+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key>+ <string>dev.portless.proxy</string>+ <key>ProgramArguments</key>+ <array>+ <string>$portless_bin</string>+ <string>proxy</string>+ <string>start</string>+ <string>--foreground</string>+ <string>--port</string>+ <string>443</string>+ <string>--https</string>+ <string>--tld</string>+ <string>dev</string>+ <string>--skip-trust</string>+ </array>+ <key>RunAtLoad</key>+ <true/>+ <key>KeepAlive</key>+ <true/>+ <key>StandardOutPath</key>+ <string>/var/log/portless.out.log</string>+ <key>StandardErrorPath</key>+ <string>/var/log/portless.err.log</string>+ <key>EnvironmentVariables</key>+ <dict>+ <key>HOME</key>+ <string>$HOME</string>+ <key>PATH</key>+ <string>$(dirname "$portless_bin"):/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>+ </dict>+</dict>+</plist>+EOF++ # Stop any current foreground/daemon proxy first so the LaunchDaemon can+ # bind :443 cleanly. Ignore errors — proxy may not be running.+ sudo "HOME=$HOME" portless proxy stop >/dev/null 2>&1 || true++ if ! sudo install -m 644 -o root -g wheel "$plist_tmp" "$LAUNCHD_PLIST"; then+ rm -f "$plist_tmp"+ fail "failed to write $LAUNCHD_PLIST"+ return 1+ fi+ rm -f "$plist_tmp"++ if ! sudo launchctl bootstrap system "$LAUNCHD_PLIST"; then+ fail "launchctl bootstrap failed — proxy may still be running; check \`sudo launchctl print system/dev.portless.proxy\`"+ return 1+ fi++ ok "portless LaunchDaemon installed; proxy starts at boot"+}++uninstall_proxy_daemon() {+ if [[ "$(uname -s)" != "Darwin" ]] || [[ ! -f "$LAUNCHD_PLIST" ]]; then+ return 0+ fi+ info "removing LaunchDaemon"+ sudo launchctl bootout "system/dev.portless.proxy" 2>/dev/null || true+ sudo rm -f "$LAUNCHD_PLIST"+ ok "LaunchDaemon removed"+}++install() {+ local repo rc+ repo="$(repo_root)"+ rc="$(detect_rc)"+ mkdir -p "$(dirname "$rc")"+ touch "$rc"++ hdr "Install"+ info "repo: $(dim "$repo")"+ info "rc: $(dim "$rc")"++ local refreshed=0+ if grep -qF "$SENTINEL_OPEN" "$rc"; then+ # Strip the existing managed block so we can rewrite it. Lets users pull+ # newer setup.sh and re-run install to refresh wrapper logic without an+ # explicit --uninstall step.+ local tmp; tmp="$(mktemp)"+ awk -v sopen="$SENTINEL_OPEN" -v sclose="$SENTINEL_CLOSE" '+ $0 == sopen { skip=1; next }+ skip && $0 == sclose { skip=0; next }+ !skip+ ' "$rc" > "$tmp"+ mv "$tmp" "$rc"+ refreshed=1+ fi++ local shell="zsh"+ case "${SHELL:-}" in+ */bash) shell="bash" ;;+ */fish) shell="fish" ;;+ esac++ {+ printf '\n'+ block_for "$repo" "$shell"+ printf '\n'+ } >> "$rc"++ if (( refreshed )); then+ ok "refreshed crbn block in $rc"+ else+ ok "appended crbn block to $rc"+ fi++ install_proxy_daemon || true++ hdr "Activate"+ printf ' Open a new shell, or run:\n\n'+ printf ' %s\n\n' "$(kbd "source $rc")"+ printf ' Or activate without re-running setup:\n\n'+ printf ' %s\n' "$(kbd "source ./setup.sh")"++ hdr "Verify"+ printf ' %s\n' "$(dim "which crbn # -> $repo/packages/dev/bin/crbn")"+ printf ' %s\n\n' "$(dim "crbn # -> help")"+}++case "${1:-}" in+ ""|install) install ;;+ --uninstall|uninstall) uninstall ;;+ -h|--help)+ cat <<'USAGE'+Usage:+ ./setup.sh install crbn into your shell rc+ source ./setup.sh install AND activate in the current shell+ ./setup.sh --uninstall remove the managed block+ RC_FILE=/path/to/rc ./setup.sh override target rc file+USAGE+ ;;+ *)+ fail "unknown arg '$1'"+ exit 2+ ;;+esacdiff --git a/turbo.json b/turbo.jsonindex 6fd02bed44..148ee7a329 100644--- a/turbo.json+++ b/turbo.json@@ -47,12 +47,6 @@"dependsOn": ["^build"],"cache": false},- "db:start": {- "outputs": []- },- "db:kill": {- "outputs": []- },"db:types": {"outputs": [],"cache": true@@ -64,23 +58,10 @@"outputs": [],"cache": false},- "db:push": {- "outputs": []- },- "db:pull": {- "outputs": []- },"db:seed": {"outputs": [],"cache": false},- "db:migrate:force": {- "outputs": []- },- "setup": {- "cache": false,- "outputs": []- },"typegen": {"cache": false,"outputs": []