Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

crbn: refactor cli module

Sidwebworks28260598257f
diff --git a/packages/dev/package.json b/packages/dev/package.json
index db9b3ec699..632bf7e3ae 100644
--- a/packages/dev/package.json
+++ b/packages/dev/package.json
@@ -20,12 +20,13 @@
"cli-table3": "^0.6.5",
"dotenv": "16.3.1",
"execa": "^8.0.1",
- "get-port-please": "^3.2.0",
+ "pg": "8.20.0",
"picocolors": "^1.1.1"
},
"devDependencies": {
"@carbon/config": "*",
"@types/node": "20.19.39",
+ "@types/pg": "^8.11.6",
"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.ts
index bd134a861d..6c4ef73f09 100644
--- a/packages/dev/src/commands/copy.ts
+++ b/packages/dev/src/commands/copy.ts
@@ -1,8 +1,9 @@
-import { copyFileSync, existsSync, readFileSync, statSync } from "node:fs";
+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";
+import { mainCheckoutRoot } from "../git.js";
+import { isAtLeastAsNew } from "../helpers.js";
const DEFAULT_INCLUDES = [".env"];
@@ -21,9 +22,7 @@ export async function syncStaleCopyFiles(cwd: string): Promise<string[]> {
const src = join(mainRoot, rel);
const dest = join(cwd, rel);
if (!existsSync(src)) continue;
- const srcMtime = statSync(src).mtimeMs;
- const destMtime = existsSync(dest) ? statSync(dest).mtimeMs : 0;
- if (destMtime >= srcMtime) continue;
+ if (isAtLeastAsNew(dest, src)) continue;
copyFileSync(src, dest);
copied.push(rel);
}
diff --git a/packages/dev/src/commands/down.ts b/packages/dev/src/commands/down.ts
index cd6fa05dd3..c9c8eb4cb6 100644
--- a/packages/dev/src/commands/down.ts
+++ b/packages/dev/src/commands/down.ts
@@ -1,10 +1,10 @@
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 { syncAppPortlessConfigs } from "../env.js";
+import { currentBranch, isLinkedWorktree } from "../git.js";
import { stopStack } from "../services/compose.js";
import { branchToPrefix, unregisterAliases } from "../services/portless.js";
+import { getWorktreeRoot, projectName, resolveSlug } from "../worktree.js";
// silent: post-SIGINT path. clack tasks/spinner would EIO via setRawMode on
// the freshly-interrupted stdin; fall back to plain printf progress.
diff --git a/packages/dev/src/commands/list.ts b/packages/dev/src/commands/list.ts
index 32f00728ae..5f7cfa006a 100644
--- a/packages/dev/src/commands/list.ts
+++ b/packages/dev/src/commands/list.ts
@@ -1,9 +1,9 @@
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 { listWorktrees as gitListWorktrees } from "../git.js";
import { dockerProjectStates } from "../services/compose.js";
-import { worktreesTable } from "../ui/tables.js";
+import { worktreesTable } from "../ui.js";
+import { listSlugs } from "../worktree.js";
export async function listWorktrees() {
intro("Carbon · worktrees");
diff --git a/packages/dev/src/commands/migrate.ts b/packages/dev/src/commands/migrate.ts
index a4f962de24..7949f46f61 100644
--- a/packages/dev/src/commands/migrate.ts
+++ b/packages/dev/src/commands/migrate.ts
@@ -1,11 +1,11 @@
import { existsSync } from "node:fs";
-import net from "node:net";
import { join } from "node:path";
import { intro, log, outro, tasks } from "@clack/prompts";
import { config as loadDotenv } from "dotenv";
import { execa } from "execa";
-import { getWorktreeRoot } from "../lib/slug.js";
+import { requireNumberEnv, tryConnect } from "../helpers.js";
import { applyMigrations } from "../services/migrations.js";
+import { getWorktreeRoot } from "../worktree.js";
// Run database migrations against the worktree's local stack without booting
// the full compose stack. Reads PORT_DB from `.env.local` (written by
@@ -29,16 +29,18 @@ export async function migrate(opts: { regen?: boolean } = {}) {
loadDotenv({ path: envLocal, override: false });
loadDotenv({ path: join(root, ".env"), override: false });
- const portDb = Number(process.env.PORT_DB);
- if (!portDb) {
+ let portDb: number;
+ try {
+ portDb = requireNumberEnv("PORT_DB");
+ } catch (err) {
log.error(
- "PORT_DB missing from .env.local. Re-run `crbn up` to regenerate it."
+ `${(err as Error).message}. Re-run \`crbn up\` to regenerate .env.local.`
);
outro("");
process.exit(1);
}
- if (!(await reachable("127.0.0.1", portDb))) {
+ if (!(await tryConnect("127.0.0.1", portDb, 1500))) {
log.error(
`Local DB at 127.0.0.1:${portDb} is not reachable. Start the stack first: \`crbn up\`.`
);
@@ -73,17 +75,3 @@ export async function migrate(opts: { regen?: boolean } = {}) {
outro("done");
}
-
-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));
- });
-}
diff --git a/packages/dev/src/commands/new.ts b/packages/dev/src/commands/new.ts
index e8b5301338..43490ff3b4 100644
--- a/packages/dev/src/commands/new.ts
+++ b/packages/dev/src/commands/new.ts
@@ -2,14 +2,14 @@ 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 { addWorktree, currentBranch } from "../git.js";
import {
promptBaseRef,
promptBranch,
promptCopyEnv,
promptDirName
-} from "../ui/prompts.js";
+} from "../prompts.js";
+import { getWorktreeRoot, slugify } from "../worktree.js";
export async function newWorktree() {
intro("Carbon · new worktree");
@@ -34,8 +34,7 @@ export async function newWorktree() {
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);
+ await addWorktree({ path: targetPath, branch, baseRef });
return `worktree at ${relative(here, targetPath)}`;
}
},
diff --git a/packages/dev/src/commands/remove.ts b/packages/dev/src/commands/remove.ts
index 7dd1c1f711..ae675a100b 100644
--- a/packages/dev/src/commands/remove.ts
+++ b/packages/dev/src/commands/remove.ts
@@ -12,10 +12,10 @@ import {
listWorktrees as gitListWorktrees,
isDirty,
removeWorktree
-} from "../lib/git.js";
-import { getSlot, listSlugs, removeSlot } from "../lib/ports.js";
+} from "../git.js";
+import { confirmRemove } from "../prompts.js";
import { destroyProjectVolumes, flushDb } from "../services/compose.js";
-import { confirmRemove } from "../ui/prompts.js";
+import { getSlot, listSlugs, removeSlot } from "../worktree.js";
export async function removeWorktreeCmd() {
intro("Carbon · remove worktree");
@@ -91,8 +91,7 @@ export async function removeWorktreeCmd() {
{
title: `git worktree remove ${targetPath}`,
task: async () => {
- const r = await removeWorktree(targetPath, dirty);
- if (!r.ok) throw new Error(r.error);
+ await removeWorktree(targetPath, dirty);
return "worktree removed";
}
},
diff --git a/packages/dev/src/commands/reset.ts b/packages/dev/src/commands/reset.ts
index 59620a49c0..ae0ed383c6 100644
--- a/packages/dev/src/commands/reset.ts
+++ b/packages/dev/src/commands/reset.ts
@@ -1,8 +1,12 @@
import { cancel, intro, log } from "@clack/prompts";
-import { getSlot } from "../lib/ports.js";
-import { getWorktreeRoot, projectName, resolveSlug } from "../lib/slug.js";
+import { confirmReset } from "../prompts.js";
import { flushDb, stopStack } from "../services/compose.js";
-import { confirmReset } from "../ui/prompts.js";
+import {
+ getSlot,
+ getWorktreeRoot,
+ projectName,
+ resolveSlug
+} from "../worktree.js";
import { up } from "./up.js";
export async function reset() {
diff --git a/packages/dev/src/commands/status.ts b/packages/dev/src/commands/status.ts
index f15691f3ea..e2e11dac6c 100644
--- a/packages/dev/src/commands/status.ts
+++ b/packages/dev/src/commands/status.ts
@@ -1,9 +1,13 @@
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";
+import { portsTable, servicesTable } from "../ui.js";
+import {
+ getSlot,
+ getWorktreeRoot,
+ projectName,
+ resolveSlug
+} from "../worktree.js";
export async function status() {
intro("Carbon · dev status");
diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.ts
index c426447fea..1da8233f1b 100644
--- a/packages/dev/src/commands/up.ts
+++ b/packages/dev/src/commands/up.ts
@@ -1,22 +1,12 @@
import { join } from "node:path";
-import { setTimeout as sleep } from "node:timers/promises";
import { box, intro, log, outro, progress, 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 type { AppId } from "../constants.js";
+import { renderEnv, syncAppPortlessConfigs, writeEnv } from "../env.js";
+import { currentBranch, isLinkedWorktree } from "../git.js";
+import { onShutdown } from "../helpers.js";
+import { pickApps } from "../prompts.js";
import {
installDeps,
spawnApps,
@@ -26,6 +16,7 @@ import {
import {
bootSharedRedis,
bootStack,
+ type Container,
listComposeServices,
listContainers,
pullStack,
@@ -35,9 +26,8 @@ import {
import {
applyBootstrapSql,
applyMigrations,
- storageBucketsExists,
waitForPostgres,
- waitForStorageTables,
+ waitForStorageReady,
waitForTcp
} from "../services/migrations.js";
import {
@@ -53,30 +43,48 @@ import {
syncHostsFile,
waitForProxyReady
} from "../services/portless.js";
-import { pickApps } from "../ui/prompts.js";
-import { summaryLines } from "../ui/summary.js";
+import { summaryLines } from "../ui.js";
+import {
+ ensureSlugAvailable,
+ getWorktreeRoot,
+ type JwtCreds,
+ type PortMap,
+ persistSlug,
+ projectName,
+ resolveSlot,
+ resolveSlug,
+ SHARED_REDIS_PORT
+} from "../worktree.js";
import { syncStaleCopyFiles } from "./copy.js";
import { down } from "./down.js";
-export async function up(
- opts: { migrate?: boolean; regen?: boolean; apps?: boolean } = {}
-) {
+type UpOpts = { migrate?: boolean; regen?: boolean; apps?: boolean };
+
+type Ctx = {
+ root: string;
+ slug: string;
+ ports: PortMap;
+ redisDb: number;
+ jwt: JwtCreds;
+ branchPrefix: string;
+};
+
+export async function up(opts: UpOpts = {}) {
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);
// Services-only mode: boot compose stack + portless aliases (api/studio/
// mail/inngest URLs still useful), skip spawnApps + auto-`down` on Ctrl+C.
- // Triggered by --no-apps OR by deselecting everything in the picker. User
- // runs `crbn down` to tear it back down.
+ // Triggered by --no-apps OR by deselecting everything in the picker.
const appsRequested = opts.apps ?? true;
+
intro("Carbon · dev up");
await ensurePortlessInstalled();
await ensureProxyPrivileges();
const selectedApps = appsRequested ? await pickApps() : [];
- const shouldRunApps = selectedApps.length > 0;
const root = await getWorktreeRoot();
const slug = resolveSlug(root);
@@ -84,50 +92,85 @@ export async function up(
persistSlug(root, slug);
log.info(`worktree: ${slug} (project ${projectName(slug)})`);
- // Auto-heal stale `.env` (and other package.json#crbn.copy entries) from
- // main checkout. `crbn checkout <existing-branch>` skips do_post_create →
- // worktrees drift from main when new env vars land. Mtime-gated, so
- // unchanged files are untouched and local edits made *after* main's last
- // change are preserved.
+ await refreshStaleCopyFiles(root);
+ await ensureDepsInstalled(root);
+
+ const ctx = await provisionSlot(root, slug);
+ await pullImages(ctx);
+ await bootDockerStack(ctx);
+ await waitForServices(ctx);
+ await runDatabaseMigrations(ctx, { shouldMigrate, shouldRegen });
+ await setupPortless(ctx, selectedApps);
+ ensureHostsFile();
+
+ if (process.env.CARBON_EDITION === "cloud") {
+ spawnStripeListener(root);
+ log.info("stripe listener spawned (CARBON_EDITION=cloud)");
+ }
+
+ box(
+ summaryLines(ctx.ports, ctx.branchPrefix, selectedApps).join("\n"),
+ `Carbon dev — ${slug}`
+ );
+
+ if (selectedApps.length === 0) {
+ outro("services up (run `crbn down` to stop)");
+ return;
+ }
+ outro("apps starting (Ctrl+C to stop)");
+ await runAppsThenTeardown(root, selectedApps);
+}
+
+// ---------------------------------------------------------------------------
+// Phases
+// ---------------------------------------------------------------------------
+
+// Auto-heal stale `.env` (and other package.json#crbn.copy entries) from main
+// checkout. `crbn checkout <existing-branch>` skips do_post_create → existing
+// worktrees drift from main when new env vars land. Mtime-gated, so unchanged
+// files are untouched and local edits made *after* main's last change are
+// preserved.
+async function refreshStaleCopyFiles(root: string) {
const refreshed = await syncStaleCopyFiles(root);
if (refreshed.length > 0) {
log.info(
`refreshed ${refreshed.join(", ")} from main checkout (stale vs main)`
);
}
+}
- // Outside `tasks` so pnpm progress streams directly when install runs.
+// Outside `tasks` so pnpm progress streams directly when install runs.
+async function ensureDepsInstalled(root: string) {
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 = "";
- let migrationsApplied = false;
-
+async function provisionSlot(root: string, slug: string): Promise<Ctx> {
+ let ctx!: Ctx;
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, slug);
+ const branchPrefix = branchToPrefix(branch, slug);
- writeEnv(root, renderEnv({ slug, ports, redisDb, jwt, branchPrefix }));
- syncAppPortlessConfigs({ worktreeRoot: root, branchPrefix, linked });
+ ctx = { root, slug, branchPrefix, ...slot };
+
+ writeEnv(root, renderEnv({ slug, branchPrefix, ...slot }));
+ syncAppPortlessConfigs({
+ worktreeRoot: root,
+ branchPrefix,
+ linked
+ });
loadDotenv({ path: join(root, ".env.local"), override: false });
loadDotenv({ path: join(root, ".env"), override: false });
- return `prefix "${branchPrefix}", redis db ${redisDb}`;
+ return `prefix "${branchPrefix}", redis db ${slot.redisDb}`;
}
},
{
@@ -141,149 +184,132 @@ export async function up(
title: "Boot shared redis",
task: async () => {
await bootSharedRedis(root);
- return `shared redis on :${SHARED_REDIS_PORT} (index ${redisDb})`;
+ return `shared redis on :${SHARED_REDIS_PORT} (index ${ctx.redisDb})`;
}
}
]);
+ return ctx;
+}
- // Pull images outside `tasks()` so we can use clack's progress bar (one
- // tick per `<service> Pulled` event). Spinner subtitle inside `tasks()`
- // can't render a bar, only a single line of text.
- {
- const services = await listComposeServices(root, slug);
- const max = Math.max(services.length, 1);
- const bar = progress({ style: "heavy", max });
- bar.start("Pulling docker images");
- try {
- await pullStack(root, slug, (line) => {
- bar.message(line.slice(0, 80));
- if (/ Pulled$/.test(line)) bar.advance(1);
- });
- bar.stop("images up to date");
- } catch (err) {
- bar.stop("pull failed");
- throw err;
- }
+// Pull images outside `tasks()` so we can use clack's progress bar (one
+// tick per `<service> Pulled` event). Spinner subtitle inside `tasks()`
+// can't render a bar, only a single line of text.
+async function pullImages(ctx: Ctx) {
+ const services = await listComposeServices(ctx.root, ctx.slug);
+ const max = Math.max(services.length, 1);
+ const bar = progress({ style: "heavy", max });
+ bar.start("Pulling docker images");
+ try {
+ await pullStack(ctx.root, ctx.slug, (line) => {
+ bar.message(line.slice(0, 80));
+ if (/ Pulled$/.test(line)) bar.advance(1);
+ });
+ bar.stop("images up to date");
+ } catch (err) {
+ bar.stop("pull failed");
+ throw err;
}
+}
+async function bootDockerStack(ctx: Ctx) {
await tasks([
{
title: "Boot docker compose stack",
task: async (msg) => {
msg("starting 12 services");
- await bootStack(root, slug);
+ await bootStack(ctx.root, ctx.slug);
return "containers up";
}
}
]);
+}
- // Wait for services via clack progress bar:
- // 3× TCP ports → +1 supabase roles → +1 storage.buckets = 5 ticks.
- // Heal path: if storage.buckets hasn't appeared within 30s of postgres
- // becoming query-ready, re-apply init.sql + restart storage/gotrue/postgrest.
- // This recovers worktrees whose pgdata volume predates the current init.sql
- // (Docker only runs init scripts on a fresh data dir, so role passwords can
- // drift and storage-api auth-fails forever).
- {
- const bar = progress({ style: "heavy", max: 5 });
- bar.start("Waiting for services");
- try {
- await waitForTcp(
- [
- `tcp:${ports.PORT_DB}`,
- `tcp:${ports.PORT_API}`,
- `tcp:${ports.PORT_INNGEST}`
- ],
- { onProgress: (line) => bar.advance(1, line.slice(0, 80)) }
- );
+// Wait for services via clack progress bar:
+// 3× TCP ports → +1 postgres ready → +1 storage.buckets = 5 ticks.
+// `waitForStorageReady` owns the storage heal path internally.
+async function waitForServices(ctx: Ctx) {
+ const bar = progress({ style: "heavy", max: 5 });
+ bar.start("Waiting for services");
+ try {
+ await waitForTcp(
+ [
+ `tcp:${ctx.ports.PORT_DB}`,
+ `tcp:${ctx.ports.PORT_API}`,
+ `tcp:${ctx.ports.PORT_INNGEST}`
+ ],
+ { onProgress: (line) => bar.advance(1, line.slice(0, 80)) }
+ );
- bar.message("waiting for postgres to accept queries");
- await waitForPostgres(ports.PORT_DB);
+ bar.message("waiting for postgres to accept queries");
+ await waitForPostgres(ctx.ports.PORT_DB);
+ bar.advance(1, "postgres ready");
- const earlyDeadline = Date.now() + 30_000;
- let bucketsReady = false;
- while (Date.now() < earlyDeadline) {
- if (await storageBucketsExists(ports.PORT_DB)) {
- bucketsReady = true;
- break;
- }
- await sleep(1000);
- }
- if (!bucketsReady) {
+ await waitForStorageReady(ctx.ports.PORT_DB, {
+ onProgress: (line) => bar.message(line.slice(0, 80)),
+ onHeal: async () => {
bar.message("storage stuck — re-applying init.sql");
- await applyBootstrapSql(root, ports.PORT_DB);
+ await applyBootstrapSql(ctx.root, ctx.ports.PORT_DB);
bar.message("restarting storage / gotrue / postgrest");
- await restartServices(root, slug, ["storage", "gotrue", "postgrest"]);
- }
- bar.advance(1, "supabase roles ok");
-
- await waitForStorageTables(ports.PORT_DB, {
- onProgress: (line) => bar.message(line.slice(0, 80)),
- onTimeout: async () => {
- const containers = await listContainers(root, slug);
- const out: string[] = ["", "--- container state ---"];
- for (const name of ["postgres", "storage"]) {
- const c = containers.find((x) => x.Service === name);
- out.push(
- c
- ? `${name.padEnd(10)} state=${c.State} health=${c.Health ?? "n/a"} ${c.Status}`
- : `${name.padEnd(10)} (not found)`
- );
- }
- out.push("", "--- storage logs (last 50) ---");
- out.push(await tailServiceLogs(root, slug, "storage", 50));
- out.push("", "--- postgres logs (last 20) ---");
- out.push(await tailServiceLogs(root, slug, "postgres", 20));
- out.push("");
- process.stderr.write(out.join("\n") + "\n");
- }
- });
- bar.advance(1, "storage.buckets ready");
- bar.stop("all services responding");
- } catch (err) {
- bar.stop("services not ready");
- throw err;
- }
+ await restartServices(ctx.root, ctx.slug, [
+ "storage",
+ "gotrue",
+ "postgrest"
+ ]);
+ },
+ onTimeout: () => dumpStorageDiagnostics(ctx)
+ });
+ bar.advance(1, "storage.buckets ready");
+ bar.stop("all services responding");
+ } catch (err) {
+ bar.stop("services not ready");
+ throw err;
}
+}
+async function runDatabaseMigrations(
+ ctx: Ctx,
+ cfg: { shouldMigrate: boolean; shouldRegen: boolean }
+) {
+ let migrationsApplied = false;
await tasks([
- ...(shouldMigrate
- ? [
- {
- title: "Apply database migrations",
- task: async () => {
- const r = await applyMigrations(root, ports.PORT_DB);
- migrationsApplied = r.applied;
- return r.applied
- ? "migrations applied"
- : "schema already up to date";
- }
- }
- ]
- : [
- {
- title: "Skip database migrations (--no-migrate)",
- task: async () => "skipped"
+ cfg.shouldMigrate
+ ? {
+ title: "Apply database migrations",
+ task: async () => {
+ const r = await applyMigrations(ctx.root, ctx.ports.PORT_DB);
+ migrationsApplied = r.applied;
+ return r.applied
+ ? "migrations applied"
+ : "schema already up to date";
}
- ]),
- ...(shouldRegen
+ }
+ : {
+ title: "Skip database migrations (--no-migrate)",
+ task: async () => "skipped"
+ },
+ ...(cfg.shouldRegen
? [
{
title: "Regenerate types & swagger",
task: async () => {
if (!migrationsApplied) return "skipped (no new migrations)";
- await execa("pnpm", ["db:types"], { cwd: root });
- await execa("pnpm", ["generate:swagger"], { cwd: root });
+ await execa("pnpm", ["db:types"], { cwd: ctx.root });
+ await execa("pnpm", ["generate:swagger"], { cwd: ctx.root });
return "types + swagger refreshed";
}
}
]
- : []),
+ : [])
+ ]);
+}
+
+async function setupPortless(ctx: Ctx, selectedApps: AppId[]) {
+ await tasks([
{
title: "Start portless proxy",
task: async (msg) => {
- pruneStaleRoutes(branchPrefix);
- startProxyDaemon(root);
+ pruneStaleRoutes(ctx.branchPrefix);
+ startProxyDaemon(ctx.root);
msg("waiting for proxy on :443");
await waitForProxyReady();
return "proxy listening";
@@ -292,62 +318,77 @@ export async function up(
{
title: "Register service aliases",
task: async () => {
- const count = await registerAliases(root, branchPrefix, ports);
+ const count = await registerAliases(
+ ctx.root,
+ ctx.branchPrefix,
+ ctx.ports
+ );
return `${count} aliases registered`;
}
},
{
title: "Reserve app hostnames",
task: async () => {
- const killed = await claimAppHosts(branchPrefix, selectedApps);
+ const killed = await claimAppHosts(ctx.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.
+// Skip sudo sync when root daemon already auto-syncs, or hosts unchanged.
+function ensureHostsFile() {
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)");
+ return;
}
-
- box(
- summaryLines(ports, branchPrefix, selectedApps).join("\n"),
- `Carbon dev — ${slug}`
- );
-
- if (!shouldRunApps) {
- outro("services up (run `crbn down` to stop)");
+ if (hostsFileInSync()) {
+ log.info("/etc/hosts already in sync — skipping sudo");
return;
}
+ log.step("sudo portless hosts sync");
+ return syncHostsFile();
+}
- outro("apps starting (Ctrl+C to stop)");
-
+async function runAppsThenTeardown(root: string, selectedApps: AppId[]) {
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 = () => {
+ const detach = onShutdown(() => {
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);
+ detach();
}
}
+
+// ---------------------------------------------------------------------------
+// Diagnostics
+// ---------------------------------------------------------------------------
+
+async function dumpStorageDiagnostics(ctx: Ctx) {
+ const containers = await listContainers(ctx.root, ctx.slug);
+ const out: string[] = ["", "--- container state ---"];
+ for (const name of ["postgres", "storage"]) {
+ out.push(formatContainerLine(name, containers));
+ }
+ out.push("", "--- storage logs (last 50) ---");
+ out.push(await tailServiceLogs(ctx.root, ctx.slug, "storage", 50));
+ out.push("", "--- postgres logs (last 20) ---");
+ out.push(await tailServiceLogs(ctx.root, ctx.slug, "postgres", 20));
+ out.push("");
+ process.stderr.write(out.join("\n") + "\n");
+}
+
+function formatContainerLine(name: string, containers: Container[]): string {
+ const c = containers.find((x) => x.Service === name);
+ if (!c) return `${name.padEnd(10)} (not found)`;
+ return `${name.padEnd(10)} state=${c.State} health=${c.Health ?? "n/a"} ${c.Status}`;
+}
diff --git a/packages/dev/src/env.test.ts b/packages/dev/src/env.test.ts
new file mode 100644
index 0000000000..cd30a6ca8c
--- /dev/null
+++ b/packages/dev/src/env.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it } from "vitest";
+import { renderEnv } from "./env.js";
+import type { JwtCreds, PortMap } from "./worktree.js";
+
+const ports: PortMap = {
+ PORT_DB: 54000,
+ PORT_API: 54001,
+ PORT_STUDIO: 54002,
+ PORT_INBUCKET: 54003,
+ PORT_INNGEST: 54004
+};
+
+const jwt: JwtCreds = {
+ secret: "test-secret",
+ anonKey: "test-anon-key",
+ serviceKey: "test-service-key"
+};
+
+describe("renderEnv", () => {
+ it("emits the per-worktree slug and prefix-derived hosts", () => {
+ const out = renderEnv({
+ slug: "feat-x",
+ ports,
+ redisDb: 3,
+ jwt,
+ branchPrefix: "feat-x"
+ });
+ expect(out).toContain("CARBON_WORKTREE=feat-x");
+ expect(out).toContain("ERP_URL=https://feat-x.erp.dev");
+ expect(out).toContain("MES_URL=https://feat-x.mes.dev");
+ expect(out).toContain("SUPABASE_URL=https://feat-x.api.dev");
+ });
+
+ it("wires every port into env vars", () => {
+ const out = renderEnv({
+ slug: "s",
+ ports,
+ redisDb: 0,
+ jwt,
+ branchPrefix: "s"
+ });
+ expect(out).toContain("PORT_DB=54000");
+ expect(out).toContain("PORT_API=54001");
+ expect(out).toContain("PORT_STUDIO=54002");
+ expect(out).toContain("PORT_INBUCKET=54003");
+ expect(out).toContain("PORT_INNGEST=54004");
+ });
+
+ it("places redis db index in REDIS_URL", () => {
+ const out = renderEnv({
+ slug: "s",
+ ports,
+ redisDb: 7,
+ jwt,
+ branchPrefix: "s"
+ });
+ expect(out).toMatch(/REDIS_URL=redis:\/\/localhost:\d+\/7/);
+ });
+
+ it("injects jwt creds verbatim", () => {
+ const out = renderEnv({
+ slug: "s",
+ ports,
+ redisDb: 0,
+ jwt,
+ branchPrefix: "s"
+ });
+ expect(out).toContain("SUPABASE_JWT_SECRET=test-secret");
+ expect(out).toContain("SUPABASE_ANON_KEY=test-anon-key");
+ expect(out).toContain("SUPABASE_SERVICE_ROLE_KEY=test-service-key");
+ });
+
+ it("ends with a trailing newline", () => {
+ const out = renderEnv({
+ slug: "s",
+ ports,
+ redisDb: 0,
+ jwt,
+ branchPrefix: "s"
+ });
+ expect(out.endsWith("\n")).toBe(true);
+ });
+});
diff --git a/packages/dev/src/lib/render-env.ts b/packages/dev/src/env.ts
similarity index 95%
rename from packages/dev/src/lib/render-env.ts
rename to packages/dev/src/env.ts
index 037b56a830..ce03ae5e4b 100644
--- a/packages/dev/src/lib/render-env.ts
+++ b/packages/dev/src/env.ts
@@ -1,8 +1,7 @@
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";
+import { APP_CHOICES } from "./constants.js";
+import { type JwtCreds, type PortMap, SHARED_REDIS_PORT } from "./worktree.js";
export function renderEnv(opts: {
slug: string;
diff --git a/packages/dev/src/lib/git.ts b/packages/dev/src/git.ts
similarity index 86%
rename from packages/dev/src/lib/git.ts
rename to packages/dev/src/git.ts
index e4febd8b44..1d9e528b47 100644
--- a/packages/dev/src/lib/git.ts
+++ b/packages/dev/src/git.ts
@@ -73,30 +73,30 @@ export async function addWorktree(opts: {
path: string;
branch: string;
baseRef: string;
-}): Promise<{ ok: true } | { ok: false; error: string }> {
+}): Promise<void> {
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() };
+ throw new Error((r.stderr || r.stdout || "git worktree add failed").trim());
}
- return { ok: true };
}
export async function removeWorktree(
path: string,
force = false
-): Promise<{ ok: true } | { ok: false; error: string }> {
+): Promise<void> {
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() };
+ throw new Error(
+ (r.stderr || r.stdout || "git worktree remove failed").trim()
+ );
}
- return { ok: true };
}
export async function isDirty(path: string): Promise<boolean> {
@@ -116,13 +116,12 @@ export async function branchExists(branch: string): Promise<boolean> {
return r.exitCode === 0;
}
-export async function deleteBranch(
- branch: string
-): Promise<{ ok: true } | { ok: false; error: string }> {
+export async function deleteBranch(branch: string): Promise<void> {
// -D forces even on unmerged; caller confirms.
const r = await execa("git", ["branch", "-D", branch], { reject: false });
if (r.exitCode !== 0) {
- return { ok: false, error: (r.stderr || r.stdout || "").trim() };
+ throw new Error(
+ (r.stderr || r.stdout || `git branch -D ${branch} failed`).trim()
+ );
}
- return { ok: true };
}
diff --git a/packages/dev/src/helpers.test.ts b/packages/dev/src/helpers.test.ts
new file mode 100644
index 0000000000..e2e3610bae
--- /dev/null
+++ b/packages/dev/src/helpers.test.ts
@@ -0,0 +1,107 @@
+import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
+import { createServer, type Server } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { isAtLeastAsNew, requireNumberEnv, tryConnect } from "./helpers.js";
+
+describe("tryConnect", () => {
+ let server: Server;
+ let port: number;
+
+ beforeEach(async () => {
+ server = createServer();
+ await new Promise<void>((resolve) =>
+ server.listen(0, "127.0.0.1", resolve)
+ );
+ const addr = server.address();
+ if (typeof addr === "object" && addr) port = addr.port;
+ else throw new Error("no port");
+ });
+
+ afterEach(async () => {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+
+ it("returns true when the port accepts", async () => {
+ expect(await tryConnect("127.0.0.1", port)).toBe(true);
+ });
+
+ it("returns false when nothing listens", async () => {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ expect(await tryConnect("127.0.0.1", port, 200)).toBe(false);
+ });
+});
+
+describe("isAtLeastAsNew", () => {
+ let dir: string;
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), "carbon-dev-helpers-"));
+ });
+
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ it("returns true when a is newer than b", () => {
+ const a = join(dir, "a");
+ const b = join(dir, "b");
+ writeFileSync(b, "");
+ writeFileSync(a, "");
+ // bump a forward 1s
+ utimesSync(a, Date.now() / 1000 + 1, Date.now() / 1000 + 1);
+ expect(isAtLeastAsNew(a, b)).toBe(true);
+ });
+
+ it("returns true when a equals b mtime", () => {
+ const a = join(dir, "a");
+ const b = join(dir, "b");
+ writeFileSync(a, "");
+ writeFileSync(b, "");
+ const t = Date.now() / 1000;
+ utimesSync(a, t, t);
+ utimesSync(b, t, t);
+ expect(isAtLeastAsNew(a, b)).toBe(true);
+ });
+
+ it("returns false when a is older than b", () => {
+ const a = join(dir, "a");
+ const b = join(dir, "b");
+ writeFileSync(a, "");
+ writeFileSync(b, "");
+ utimesSync(a, Date.now() / 1000 - 10, Date.now() / 1000 - 10);
+ expect(isAtLeastAsNew(a, b)).toBe(false);
+ });
+
+ it("returns false when either file is missing", () => {
+ expect(isAtLeastAsNew(join(dir, "no-a"), join(dir, "no-b"))).toBe(false);
+ });
+});
+
+describe("requireNumberEnv", () => {
+ const KEY = "CARBON_TEST_REQUIRE_NUMBER_ENV";
+
+ afterEach(() => {
+ delete process.env[KEY];
+ });
+
+ it("returns the parsed number", () => {
+ process.env[KEY] = "54321";
+ expect(requireNumberEnv(KEY)).toBe(54321);
+ });
+
+ it("throws when missing", () => {
+ expect(() => requireNumberEnv(KEY)).toThrow(/missing/);
+ });
+
+ it("throws when empty", () => {
+ process.env[KEY] = "";
+ expect(() => requireNumberEnv(KEY)).toThrow(/missing/);
+ });
+
+ it("throws on non-numeric", () => {
+ process.env[KEY] = "not-a-number";
+ expect(() => requireNumberEnv(KEY)).toThrow(/not a number/);
+ });
+});
diff --git a/packages/dev/src/helpers.ts b/packages/dev/src/helpers.ts
new file mode 100644
index 0000000000..85655b806f
--- /dev/null
+++ b/packages/dev/src/helpers.ts
@@ -0,0 +1,116 @@
+import { existsSync, statSync } from "node:fs";
+import net from "node:net";
+import { createInterface } from "node:readline";
+import { setTimeout as sleep } from "node:timers/promises";
+
+// ---------------------------------------------------------------------------
+// TCP readiness probes
+// ---------------------------------------------------------------------------
+
+/** Resolve true when host:port accepts a connection within `timeoutMs`. */
+export function tryConnect(
+ host: string,
+ port: number,
+ timeoutMs = 2000
+): 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(timeoutMs, () => done(false));
+ });
+}
+
+/** Poll `tryConnect` until it succeeds or `timeoutMs` elapses. */
+export async function waitForPort(
+ port: number,
+ timeoutMs: number,
+ host = "127.0.0.1"
+): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (await tryConnect(host, port)) return;
+ await sleep(500);
+ }
+ throw new Error(`timed out waiting for tcp:${port} after ${timeoutMs}ms`);
+}
+
+// ---------------------------------------------------------------------------
+// Streaming line reader
+// ---------------------------------------------------------------------------
+
+/**
+ * Invoke `onLine` once per line from `stream`. Backed by node's native
+ * `readline.createInterface`, which buffers in C++ and avoids the per-chunk
+ * `buf += chunk.toString(); split('\n')` allocations we used to do by hand.
+ */
+export function readLines(
+ stream: NodeJS.ReadableStream,
+ onLine: (line: string) => void
+): void {
+ const rl = createInterface({ input: stream, crlfDelay: Infinity });
+ rl.on("line", onLine);
+}
+
+// ---------------------------------------------------------------------------
+// File mtime compare
+// ---------------------------------------------------------------------------
+
+/**
+ * True when file `a` is at least as recently modified as `b`. False if either
+ * is missing. Used to gate "is X already in sync with Y" decisions.
+ */
+export function isAtLeastAsNew(a: string, b: string): boolean {
+ if (!existsSync(a) || !existsSync(b)) return false;
+ try {
+ return statSync(a).mtimeMs >= statSync(b).mtimeMs;
+ } catch {
+ return false;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Env var coercion
+// ---------------------------------------------------------------------------
+
+/** Read `process.env[name]` as a number. Throws a clear error if missing or NaN. */
+export function requireNumberEnv(name: string): number {
+ const raw = process.env[name];
+ if (raw === undefined || raw === "") {
+ throw new Error(`env var ${name} is missing`);
+ }
+ const n = Number(raw);
+ if (!Number.isFinite(n)) {
+ throw new Error(`env var ${name} is not a number (got "${raw}")`);
+ }
+ return n;
+}
+
+// ---------------------------------------------------------------------------
+// Shutdown signal helper
+// ---------------------------------------------------------------------------
+
+const SHUTDOWN_SIGNALS = [
+ "SIGINT",
+ "SIGTERM",
+ "SIGHUP",
+ "SIGBREAK"
+] as const satisfies readonly NodeJS.Signals[];
+
+/**
+ * Register a handler for SIGINT/SIGTERM/SIGHUP/SIGBREAK. Returns a cleanup
+ * function that unregisters them all — pair with try/finally.
+ */
+export function onShutdown(
+ handler: (signal: NodeJS.Signals) => void
+): () => void {
+ for (const s of SHUTDOWN_SIGNALS) process.on(s, handler);
+ return () => {
+ for (const s of SHUTDOWN_SIGNALS) process.off(s, handler);
+ };
+}
diff --git a/packages/dev/src/lib/jwt.ts b/packages/dev/src/lib/jwt.ts
deleted file mode 100644
index 74bb471c36..0000000000
--- a/packages/dev/src/lib/jwt.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-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.ts
deleted file mode 100644
index 82380586b2..0000000000
--- a/packages/dev/src/lib/ports.ts
+++ /dev/null
@@ -1,148 +0,0 @@
-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/slug.ts b/packages/dev/src/lib/slug.ts
deleted file mode 100644
index 72bc37b360..0000000000
--- a/packages/dev/src/lib/slug.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-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/ui/prompts.ts b/packages/dev/src/prompts.ts
similarity index 94%
rename from packages/dev/src/ui/prompts.ts
rename to packages/dev/src/prompts.ts
index cf97e7e666..2af78092ed 100644
--- a/packages/dev/src/ui/prompts.ts
+++ b/packages/dev/src/prompts.ts
@@ -11,8 +11,8 @@ import {
text
} from "@clack/prompts";
import pc from "picocolors";
-import { APP_CHOICES, type AppId } from "../constants.js";
-import { branchExists, deleteBranch, listWorktrees } from "../lib/git.js";
+import { APP_CHOICES, type AppId } from "./constants.js";
+import { branchExists, deleteBranch, listWorktrees } from "./git.js";
// git-check-ref-format(1) rules.
const INVALID_BRANCH_RE =
@@ -82,9 +82,10 @@ export async function promptBranch(): Promise<string> {
});
if (isCancel(recreate)) abort();
if (!recreate) continue;
- const del = await deleteBranch(trimmed);
- if (!del.ok) {
- log.error(`Failed to delete branch: ${del.error}`);
+ try {
+ await deleteBranch(trimmed);
+ } catch (err) {
+ log.error(`Failed to delete branch: ${(err as Error).message}`);
continue;
}
log.success(`Deleted branch '${trimmed}'`);
diff --git a/packages/dev/src/services/apps.ts b/packages/dev/src/services/apps.ts
index fbe9e7decd..5afa187659 100644
--- a/packages/dev/src/services/apps.ts
+++ b/packages/dev/src/services/apps.ts
@@ -1,7 +1,7 @@
-import { existsSync, statSync } from "node:fs";
import { join } from "node:path";
import { type ExecaChildProcess, execa } from "execa";
import pc from "picocolors";
+import { isAtLeastAsNew, onShutdown, readLines } from "../helpers.js";
const APP_COLORS: Record<string, (s: string) => string> = {
erp: pc.cyan,
@@ -47,22 +47,10 @@ export function spawnApps(opts: {
sink: NodeJS.WriteStream
) => {
if (!stream) return;
- let buf = "";
- stream.on("data", (chunk) => {
+ readLines(stream, (line) => {
// 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`);
- }
+ if (shuttingDown || isNoiseLine(line)) return;
+ sink.write(`${prefix}${line}\n`);
});
};
pipe(child.stdout, process.stdout);
@@ -99,20 +87,19 @@ export function spawnApps(opts: {
killTimer = setTimeout(() => shutdown("SIGKILL"), 3_000);
};
- const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP", "SIGBREAK"] as const;
- for (const s of SIGNALS) process.on(s, onSignal);
+ const detach = onShutdown(onSignal);
return Promise.all(children)
.then(() => undefined)
.catch(() => undefined)
.finally(() => {
if (killTimer) clearTimeout(killTimer);
- for (const s of SIGNALS) process.off(s, onSignal);
+ detach();
});
}
export function spawnStripeListener(root: string) {
- execa("npm", ["run", "dev:stripe"], {
+ execa("pnpm", ["run", "dev:stripe"], {
cwd: root,
detached: true,
stdio: "ignore"
@@ -139,12 +126,7 @@ export async function installDeps(root: string): Promise<boolean> {
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;
- }
+ return isAtLeastAsNew(marker, lockfile);
}
export async function syncEnvSymlinks(root: string) {
diff --git a/packages/dev/src/services/compose.ts b/packages/dev/src/services/compose.ts
index 38530bd24a..36e5a2a44a 100644
--- a/packages/dev/src/services/compose.ts
+++ b/packages/dev/src/services/compose.ts
@@ -1,23 +1,32 @@
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";
+import { readLines } from "../helpers.js";
+import { projectName } from "../worktree.js";
+
+type Publisher = { PublishedPort: number; TargetPort: number };
+
+// Normalized shape. `parseContainer` ensures Health is always string|null and
+// Publishers is always an array — downstream code (ui.ts) doesn't have to
+// re-check for null/undefined, and the V8 hidden class stays stable across
+// every parsed entry.
+export type Container = {
+ Service: string;
+ Name: string;
+ State: string;
+ Status: string;
+ Health: string | null;
+ Publishers: Publisher[];
+};
+
+// ---------------------------------------------------------------------------
+// Lifecycle
+// ---------------------------------------------------------------------------
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"
- ],
+ devArgs(slug, "--env-file", ".env.local", "up", "-d"),
root
);
}
@@ -31,19 +40,11 @@ export async function restartServices(
services: string[]
) {
if (services.length === 0) return;
- await execa(
- "docker",
- [
- "compose",
- "-f",
- COMPOSE_DEV_FILE,
- "-p",
- projectName(slug),
- "restart",
- ...services
- ],
- { cwd: root, reject: false, stdio: "ignore" }
- );
+ await execa("docker", devArgs(slug, "restart", ...services), {
+ cwd: root,
+ reject: false,
+ stdio: "ignore"
+ });
}
// Pull all images before `up -d` so `bootStack` doesn't block silently behind
@@ -57,31 +58,16 @@ export async function pullStack(
) {
const proc = execa(
"docker",
- [
- "compose",
- "-f",
- COMPOSE_DEV_FILE,
- "-p",
- projectName(slug),
- "--env-file",
- ".env.local",
- "--progress",
- "plain",
- "pull"
- ],
+ devArgs(slug, "--env-file", ".env.local", "--progress", "plain", "pull"),
{ cwd: root, reject: false, all: true }
);
- let buf = "";
- proc.all?.on("data", (b: Buffer) => {
- buf += b.toString();
- const lines = buf.split("\n");
- buf = lines.pop() ?? "";
- for (const l of lines) {
- const trimmed = l.trim();
+ if (proc.all) {
+ readLines(proc.all, (line) => {
+ const trimmed = line.trim();
if (trimmed) onLine(trimmed);
- }
- });
+ });
+ }
const r = await proc;
if (r.exitCode !== 0) {
@@ -95,14 +81,7 @@ export async function stopStack(
slug: string,
withVolumes: boolean
) {
- const args = [
- "compose",
- "-f",
- COMPOSE_DEV_FILE,
- "-p",
- projectName(slug),
- "down"
- ];
+ const args = devArgs(slug, "down");
if (withVolumes) args.push("-v");
await execa("docker", args, { cwd: root, stdio: "ignore", reject: false });
}
@@ -132,30 +111,67 @@ export async function destroyProjectVolumes(cwd: string, project: string) {
);
}
+// ---------------------------------------------------------------------------
+// Inspection
+// ---------------------------------------------------------------------------
+
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"
- ],
+ devArgs(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);
+ const out: Container[] = [];
+ for (const line of r.stdout.split("\n")) {
+ if (!line) continue;
+ let raw: unknown;
+ try {
+ raw = JSON.parse(line);
+ } catch {
+ continue;
+ }
+ const c = parseContainer(raw);
+ if (c) out.push(c);
+ }
+ return out;
+}
+
+function parseContainer(raw: unknown): Container | null {
+ if (!raw || typeof raw !== "object") return null;
+ const r = raw as Record<string, unknown>;
+ if (
+ typeof r.Service !== "string" ||
+ typeof r.Name !== "string" ||
+ typeof r.State !== "string" ||
+ typeof r.Status !== "string"
+ ) {
+ return null;
+ }
+ return {
+ Service: r.Service,
+ Name: r.Name,
+ State: r.State,
+ Status: r.Status,
+ Health: typeof r.Health === "string" ? r.Health : null,
+ Publishers: parsePublishers(r.Publishers)
+ };
+}
+
+function parsePublishers(raw: unknown): Publisher[] {
+ if (!Array.isArray(raw)) return [];
+ const out: Publisher[] = [];
+ for (const p of raw) {
+ if (!p || typeof p !== "object") continue;
+ const pp = (p as Record<string, unknown>).PublishedPort;
+ const tp = (p as Record<string, unknown>).TargetPort;
+ if (typeof pp !== "number" || typeof tp !== "number") continue;
+ out.push({ PublishedPort: pp, TargetPort: tp });
+ }
+ return out;
}
// Names of services declared in the dev compose file, resolved via
@@ -166,17 +182,7 @@ export async function listComposeServices(
): Promise<string[]> {
const r = await execa(
"docker",
- [
- "compose",
- "-f",
- COMPOSE_DEV_FILE,
- "-p",
- projectName(slug),
- "--env-file",
- ".env.local",
- "config",
- "--services"
- ],
+ devArgs(slug, "--env-file", ".env.local", "config", "--services"),
{ cwd: root, reject: false }
);
if (r.exitCode !== 0) return [];
@@ -197,18 +203,7 @@ export async function tailServiceLogs(
): Promise<string> {
const r = await execa(
"docker",
- [
- "compose",
- "-f",
- COMPOSE_DEV_FILE,
- "-p",
- projectName(slug),
- "logs",
- "--tail",
- String(lines),
- "--no-color",
- service
- ],
+ devArgs(slug, "logs", "--tail", String(lines), "--no-color", service),
{ cwd: root, reject: false }
);
return ((r.stdout ?? "") + (r.stderr ?? "")).trim();
@@ -235,42 +230,31 @@ export async function dockerProjectStates(): Promise<Map<string, string>> {
return out;
}
-export type Container = {
- Service: string;
- Name: string;
- State: string;
- Status: string;
- Health?: string;
- Publishers?: { PublishedPort: number; TargetPort: number }[] | null;
-};
+// ---------------------------------------------------------------------------
+// Utility
+// ---------------------------------------------------------------------------
-// Wipe one logical DB on shared redis. Host redis-cli, fallback docker exec.
+// Wipe one logical DB on shared redis via the container's bundled redis-cli —
+// avoids requiring a host `redis-cli` install.
export async function flushDb(db: number) {
- let r = await execa(
- "redis-cli",
- [
- "-h",
- "localhost",
- "-p",
- String(SHARED_REDIS_PORT),
- "-n",
- String(db),
- "FLUSHDB"
- ],
+ const r = await execa(
+ "docker",
+ ["exec", "carbon-redis", "redis-cli", "-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)`);
}
}
+// ---------------------------------------------------------------------------
+// Private helpers
+// ---------------------------------------------------------------------------
+
+function devArgs(slug: string, ...rest: string[]): string[] {
+ return ["compose", "-f", COMPOSE_DEV_FILE, "-p", projectName(slug), ...rest];
+}
+
async function execStrict(cmd: string, args: string[], cwd: string) {
const r = await execa(cmd, args, { cwd, reject: false, preferLocal: true });
if (r.exitCode !== 0) {
diff --git a/packages/dev/src/services/migrations.ts b/packages/dev/src/services/migrations.ts
index 669602e32d..06a9836cac 100644
--- a/packages/dev/src/services/migrations.ts
+++ b/packages/dev/src/services/migrations.ts
@@ -1,8 +1,13 @@
import { readFileSync } from "node:fs";
-import net from "node:net";
import { join } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { execa } from "execa";
+import pg from "pg";
+import { waitForPort } from "../helpers.js";
+
+// ---------------------------------------------------------------------------
+// Readiness gates
+// ---------------------------------------------------------------------------
// Block until each tcp:<port> accepts on 127.0.0.1. `onProgress` fires once
// per port as it opens — caller streams these into a spinner subtitle so a
@@ -29,128 +34,56 @@ export async function waitForTcp(
);
}
-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 postgres accepts queries (TCP-open ≠ ready — init scripts run
-// after the port opens). Standalone so callers can re-apply bootstrap SQL or
-// restart dependents between this gate and `waitForStorageTables`.
+// after the port opens).
export async function waitForPostgres(port: number, timeoutMs = 60_000) {
- const url = `postgresql://postgres:postgres@localhost:${port}/postgres`;
- const env = { ...process.env, PGSSLMODE: "disable" };
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
- const r = await execa("psql", [url, "-tAc", "SELECT 1"], {
- env,
- reject: false
- });
- if (r.exitCode === 0 && r.stdout?.trim() === "1") return;
+ try {
+ await withClient(port, (c) => c.query("SELECT 1"));
+ return;
+ } catch {
+ // postgres still initializing — retry until deadline
+ }
await sleep(1000);
}
throw new Error(`postgres did not accept queries within ${timeoutMs}ms`);
}
-// Single-shot check used by the heal path to decide whether storage-api has
-// already bootstrapped its schema.
-export async function storageBucketsExists(port: number): Promise<boolean> {
- const url = `postgresql://postgres:postgres@localhost:${port}/postgres`;
- const r = await execa(
- "psql",
- [url, "-tAc", "SELECT to_regclass('storage.buckets')"],
- { env: { ...process.env, PGSSLMODE: "disable" }, reject: false }
- );
- return r.exitCode === 0 && r.stdout?.trim() === "storage.buckets";
-}
-
-// Re-apply `packages/dev/docker/init.sql` over psql as the superuser.
-// `docker-entrypoint-initdb.d` only runs on a fresh pgdata volume — a worktree
-// with a pre-existing volume from before init.sql evolved keeps the old role
-// passwords forever, so storage-api / gotrue / postgrest auth-fail on every
-// boot. Re-applying is idempotent (`ALTER USER ... PASSWORD`, `CREATE SCHEMA
-// IF NOT EXISTS`).
-export async function applyBootstrapSql(root: string, port: number) {
- const sql = readFileSync(join(root, "packages/dev/docker/init.sql"), "utf8");
- const url = `postgresql://postgres:postgres@localhost:${port}/postgres`;
- const r = await execa("psql", [url, "-v", "ON_ERROR_STOP=1"], {
- input: sql,
- env: { ...process.env, PGSSLMODE: "disable" },
- reject: false
- });
- if (r.exitCode !== 0) {
- process.stderr.write(r.stderr?.toString() ?? "");
- throw new Error(`init.sql apply failed (exit ${r.exitCode})`);
- }
-}
-
-// Block until postgres accepts queries, then until supabase storage-api
-// bootstraps `storage.buckets`. Postgres opens its TCP port well before init
-// scripts finish — querying `SELECT 1` is the real readiness signal. Storage
-// only starts its bootstrap once postgres is healthy, so both gates share one
-// budget. `onTimeout` runs before the throw so callers can surface container
-// state / logs without leaking compose-project knowledge into this module.
-export async function waitForStorageTables(
+/**
+ * Block until supabase storage-api has bootstrapped `storage.buckets`. Probes
+ * for 30s first; if missing, invokes `onHeal` (re-apply init.sql + restart
+ * dependent services) then polls again with a 150s budget.
+ *
+ * The heal path recovers worktrees whose pgdata volume predates the current
+ * init.sql — Docker only runs init scripts on a fresh data dir, so role
+ * passwords drift and storage-api auth-fails forever otherwise.
+ */
+export async function waitForStorageReady(
port: number,
opts: {
- onTimeout?: () => Promise<void>;
+ onHeal?: () => Promise<void>;
onProgress?: (line: string) => void;
+ onTimeout?: () => Promise<void>;
} = {}
) {
- const url = `postgresql://postgres:postgres@localhost:${port}/postgres`;
- const env = { ...process.env, PGSSLMODE: "disable" };
- const deadline = Date.now() + 180_000;
const start = Date.now();
const elapsed = () => Math.floor((Date.now() - start) / 1000);
- opts.onProgress?.("waiting for postgres to accept queries");
- while (Date.now() < deadline) {
- const r = await execa("psql", [url, "-tAc", "SELECT 1"], {
- env,
- reject: false
- });
- if (r.exitCode === 0 && r.stdout?.trim() === "1") {
- opts.onProgress?.(`postgres ready (${elapsed()}s)`);
- break;
- }
- await sleep(1000);
+ opts.onProgress?.("waiting for storage.buckets");
+ if (await pollBuckets(port, start + 30_000)) {
+ opts.onProgress?.(`storage.buckets ready (${elapsed()}s)`);
+ return;
}
- opts.onProgress?.("waiting for storage-api to create storage.buckets");
- while (Date.now() < deadline) {
- const r = await execa(
- "psql",
- [url, "-tAc", "SELECT to_regclass('storage.buckets')"],
- { env, reject: false }
- );
- if (r.exitCode === 0 && r.stdout?.trim() === "storage.buckets") {
- opts.onProgress?.(`storage.buckets ready (${elapsed()}s)`);
- return;
- }
- await sleep(1000);
+ if (opts.onHeal) {
+ opts.onProgress?.("storage stuck — running heal");
+ await opts.onHeal();
+ }
+
+ if (await pollBuckets(port, start + 180_000)) {
+ opts.onProgress?.(`storage.buckets ready (${elapsed()}s)`);
+ return;
}
if (opts.onTimeout) {
@@ -163,6 +96,21 @@ export async function waitForStorageTables(
throw new Error("storage.buckets did not appear within 180s");
}
+// Re-apply `packages/dev/docker/init.sql` as the superuser. Docker's
+// `docker-entrypoint-initdb.d` only runs on a fresh pgdata volume — a worktree
+// with a pre-existing volume from before init.sql evolved keeps the old role
+// passwords forever, so storage-api / gotrue / postgrest auth-fail on every
+// boot. Re-applying is idempotent (`ALTER USER ... PASSWORD`, `CREATE SCHEMA
+// IF NOT EXISTS`).
+export async function applyBootstrapSql(root: string, port: number) {
+ const sql = readFileSync(join(root, "packages/dev/docker/init.sql"), "utf8");
+ await withClient(port, (c) => c.query(sql));
+}
+
+// ---------------------------------------------------------------------------
+// Schema migrations
+// ---------------------------------------------------------------------------
+
// --include-all: supabase bootstrap inserts a sentinel into schema_migrations
// that makes earlier-timestamp migrations look "out of order" without it.
// Returns `applied: true` when at least one migration ran — callers gate
@@ -194,3 +142,49 @@ export async function applyMigrations(
const applied = /Applying migration/i.test(r.stdout ?? "");
return { applied };
}
+
+// ---------------------------------------------------------------------------
+// Private helpers
+// ---------------------------------------------------------------------------
+
+// Host-side superuser connection. `pg` avoids a host `psql` install —
+// previously a hidden requirement that bit at least one engineer.
+async function withClient<T>(
+ port: number,
+ fn: (c: pg.Client) => Promise<T>
+): Promise<T> {
+ const client = new pg.Client({
+ host: "127.0.0.1",
+ port,
+ user: "postgres",
+ password: "postgres",
+ database: "postgres"
+ });
+ await client.connect();
+ try {
+ return await fn(client);
+ } finally {
+ await client.end();
+ }
+}
+
+async function pollBuckets(port: number, deadline: number): Promise<boolean> {
+ while (Date.now() < deadline) {
+ if (await storageBucketsExists(port)) return true;
+ await sleep(1000);
+ }
+ return false;
+}
+
+async function storageBucketsExists(port: number): Promise<boolean> {
+ try {
+ return await withClient(port, async (c) => {
+ const r = await c.query<{ regclass: string | null }>(
+ "SELECT to_regclass('storage.buckets')::text AS regclass"
+ );
+ return r.rows[0]?.regclass === "storage.buckets";
+ });
+ } catch {
+ return false;
+ }
+}
diff --git a/packages/dev/src/services/portless.ts b/packages/dev/src/services/portless.ts
index 5f5e02a459..42eb0dc3cc 100644
--- a/packages/dev/src/services/portless.ts
+++ b/packages/dev/src/services/portless.ts
@@ -9,7 +9,7 @@ import {
type AppId,
PORTLESS_MIN_VERSION
} from "../constants.js";
-import type { PortMap } from "../lib/ports.js";
+import type { PortMap } from "../worktree.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
diff --git a/packages/dev/src/ui/tables.ts b/packages/dev/src/ui.ts
similarity index 59%
rename from packages/dev/src/ui/tables.ts
rename to packages/dev/src/ui.ts
index db7b46fc51..282397c0a4 100644
--- a/packages/dev/src/ui/tables.ts
+++ b/packages/dev/src/ui.ts
@@ -1,7 +1,12 @@
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";
+import { type AppId, TLD } from "./constants.js";
+import type { Container } from "./services/compose.js";
+import { PORT_NAMES, type PortMap, SHARED_REDIS_PORT } from "./worktree.js";
+
+// ---------------------------------------------------------------------------
+// Tables (status / list)
+// ---------------------------------------------------------------------------
/** Common cli-table3 style: gray border, no inter-row separators. */
const BASE_STYLE = {
@@ -84,7 +89,7 @@ export function worktreesTable(
return t.toString();
}
-function colorState(state: string, health?: string): string {
+function colorState(state: string, health: string | null): string {
const s = state.toLowerCase();
if (s === "running" && health === "unhealthy")
return pc.yellow("◑ unhealthy");
@@ -97,7 +102,7 @@ function colorState(state: string, health?: string): string {
}
function formatPorts(c: Container): string {
- if (!c.Publishers || c.Publishers.length === 0) return pc.dim("—");
+ if (c.Publishers.length === 0) return pc.dim("—");
const seen = new Set<string>();
const out: string[] = [];
for (const p of c.Publishers) {
@@ -111,3 +116,49 @@ function formatPorts(c: Container): string {
}
return out.length ? out.join(" ") : pc.dim("—");
}
+
+// ---------------------------------------------------------------------------
+// Summary (boxed URLs printed after `crbn up`)
+// ---------------------------------------------------------------------------
+
+/** Boxed list of URLs + DB DSN for the up-summary. */
+export function summaryLines(
+ ports: PortMap,
+ branchPrefix: string,
+ apps: readonly AppId[]
+): string[] {
+ const host = (sub: string) => `https://${branchPrefix}.${sub}.${TLD}`;
+ const dbUrl = `postgresql://postgres:postgres@localhost:${ports.PORT_DB}/postgres`;
+ const lines: string[] = [];
+ if (apps.includes("erp")) lines.push(row(pc.cyan, "ERP", host("erp")));
+ if (apps.includes("mes")) lines.push(row(pc.magenta, "MES", host("mes")));
+ lines.push(
+ 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)}`
+ );
+ return lines;
+}
+
+/**
+ * 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\\`;
+}
+
+function row(
+ color: (s: string) => string,
+ 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/summary.ts b/packages/dev/src/ui/summary.ts
deleted file mode 100644
index 621a0c3714..0000000000
--- a/packages/dev/src/ui/summary.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import pc from "picocolors";
-import { type AppId, 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,
- apps: readonly AppId[]
-): string[] {
- const host = (sub: string) => `https://${branchPrefix}.${sub}.${TLD}`;
- const dbUrl = `postgresql://postgres:postgres@localhost:${ports.PORT_DB}/postgres`;
- const lines: string[] = [];
- if (apps.includes("erp")) lines.push(row(pc.cyan, "ERP", host("erp")));
- if (apps.includes("mes")) lines.push(row(pc.magenta, "MES", host("mes")));
- lines.push(
- 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)}`
- );
- return lines;
-}
-
-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/worktree.test.ts b/packages/dev/src/worktree.test.ts
new file mode 100644
index 0000000000..b879b2a978
--- /dev/null
+++ b/packages/dev/src/worktree.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from "vitest";
+import { slugify } from "./worktree.js";
+
+describe("slugify", () => {
+ it("lowercases", () => {
+ expect(slugify("Foo")).toBe("foo");
+ });
+
+ it("collapses non-alphanumeric runs to single dash", () => {
+ expect(slugify("foo/bar baz")).toBe("foo-bar-baz");
+ expect(slugify("foo bar")).toBe("foo-bar");
+ });
+
+ it("strips leading and trailing dashes", () => {
+ expect(slugify("--foo--")).toBe("foo");
+ expect(slugify("/foo/")).toBe("foo");
+ });
+
+ it("preserves embedded dashes", () => {
+ expect(slugify("feat-add-thing")).toBe("feat-add-thing");
+ });
+
+ it("collapses consecutive dashes", () => {
+ expect(slugify("foo--bar")).toBe("foo-bar");
+ });
+
+ it("handles unicode by replacing with dashes", () => {
+ expect(slugify("café/résumé")).toBe("caf-r-sum");
+ });
+
+ it("returns empty string when input is empty or all-symbol", () => {
+ expect(slugify("")).toBe("");
+ expect(slugify("///")).toBe("");
+ });
+});
diff --git a/packages/dev/src/worktree.ts b/packages/dev/src/worktree.ts
new file mode 100644
index 0000000000..3e157d3d84
--- /dev/null
+++ b/packages/dev/src/worktree.ts
@@ -0,0 +1,316 @@
+import { createHmac, randomBytes } from "node:crypto";
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import net from "node:net";
+import { homedir } from "node:os";
+import { basename, dirname, join } from "node:path";
+import { execa } from "execa";
+
+// ---------------------------------------------------------------------------
+// Types & constants
+// ---------------------------------------------------------------------------
+
+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>;
+export type JwtCreds = { secret: string; anonKey: string; serviceKey: string };
+type RegistryEntry = {
+ worktreeRoot: string;
+ ports: PortMap;
+ redisDb: number;
+ jwt: JwtCreds;
+};
+type Registry = Record<string, RegistryEntry>;
+
+export const SHARED_REDIS_PORT = 6379;
+const REDIS_DB_MAX = 16;
+const SLUG_FILE = ".carbon-worktree";
+const REGISTRY_PATH = join(homedir(), ".carbon", "dev-ports.json");
+
+// ---------------------------------------------------------------------------
+// Worktree identity (slug)
+// ---------------------------------------------------------------------------
+
+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, "-");
+}
+
+// ---------------------------------------------------------------------------
+// Per-worktree slot (ports + redis db + jwt creds)
+// ---------------------------------------------------------------------------
+
+export async function resolveSlot(
+ slug: string,
+ worktreeRoot: string
+): Promise<{ ports: PortMap; redisDb: number; jwt: JwtCreds }> {
+ const registry = readRegistry();
+ const existing = registry[slug];
+
+ // Fast path: registry entry is valid and points at this worktree.
+ if (existing && existing.worktreeRoot === worktreeRoot) {
+ return {
+ ports: existing.ports,
+ redisDb: existing.redisDb,
+ jwt: existing.jwt
+ };
+ }
+
+ // Slug collision (different path) or no entry — allocate fresh.
+ // JWT creds tie to data signed/stored in postgres; reuse when present so
+ // existing sessions stay valid.
+ const { claimedPorts, claimedDbs } = collectClaims(registry, slug);
+ const ports = await pickPorts(claimedPorts);
+ const redisDb = pickRedisDb(claimedDbs);
+ const jwt = existing?.jwt ?? generateJwtCreds();
+
+ registry[slug] = { worktreeRoot, ports, redisDb, jwt };
+ writeRegistry(registry);
+ return { ports, redisDb, jwt };
+}
+
+function collectClaims(
+ registry: Registry,
+ excludeSlug: string
+): { claimedPorts: Set<number>; claimedDbs: Set<number> } {
+ const claimedPorts = new Set<number>();
+ const claimedDbs = new Set<number>();
+ for (const [s, entry] of Object.entries(registry)) {
+ if (s === excludeSlug) continue;
+ for (const p of Object.values(entry.ports)) claimedPorts.add(p);
+ claimedDbs.add(entry.redisDb);
+ }
+ return { claimedPorts, claimedDbs };
+}
+
+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);
+}
+
+// ---------------------------------------------------------------------------
+// Private helpers
+// ---------------------------------------------------------------------------
+
+function readRegistry(): Registry {
+ if (!existsSync(REGISTRY_PATH)) return {};
+ let raw: unknown;
+ try {
+ raw = JSON.parse(readFileSync(REGISTRY_PATH, "utf8"));
+ } catch {
+ return {};
+ }
+ return parseRegistry(raw);
+}
+
+// Drop entries that don't match the expected shape rather than letting silently
+// corrupt JSON poison `crbn up`. Returning {} on outer failure would re-allocate
+// fresh slots and break running stacks — drop-bad-entries preserves the good
+// ones and only forces re-allocation for the corrupt slugs.
+function parseRegistry(raw: unknown): Registry {
+ if (!raw || typeof raw !== "object") return {};
+ const out: Registry = {};
+ for (const [slug, value] of Object.entries(raw as Record<string, unknown>)) {
+ const entry = parseRegistryEntry(value);
+ if (entry) out[slug] = entry;
+ }
+ return out;
+}
+
+function parseRegistryEntry(raw: unknown): RegistryEntry | null {
+ if (!raw || typeof raw !== "object") return null;
+ const r = raw as Record<string, unknown>;
+ if (typeof r.worktreeRoot !== "string") return null;
+ if (!isPortMap(r.ports)) return null;
+ if (typeof r.redisDb !== "number" || !Number.isInteger(r.redisDb))
+ return null;
+ if (!isJwtCreds(r.jwt)) return null;
+ return {
+ worktreeRoot: r.worktreeRoot,
+ ports: r.ports,
+ redisDb: r.redisDb,
+ jwt: r.jwt
+ };
+}
+
+function isPortMap(v: unknown): v is PortMap {
+ if (!v || typeof v !== "object") return false;
+ const o = v as Record<string, unknown>;
+ for (const name of PORT_NAMES) {
+ if (typeof o[name] !== "number" || !Number.isInteger(o[name])) return false;
+ }
+ return true;
+}
+
+function isJwtCreds(v: unknown): v is JwtCreds {
+ if (!v || typeof v !== "object") return false;
+ const j = v as Record<string, unknown>;
+ return (
+ typeof j.secret === "string" &&
+ j.secret.length > 0 &&
+ typeof j.anonKey === "string" &&
+ typeof j.serviceKey === "string"
+ );
+}
+
+function writeRegistry(registry: Registry) {
+ mkdirSync(dirname(REGISTRY_PATH), { recursive: true });
+ writeFileSync(REGISTRY_PATH, JSON.stringify(registry, null, 2));
+}
+
+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");
+}
+
+// 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.
+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/pnpm-lock.yaml b/pnpm-lock.yaml
index 96358b0cc1..476f22efc3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1888,9 +1888,9 @@ importers:
execa:
specifier: ^8.0.1
version: 8.0.1
- get-port-please:
- specifier: ^3.2.0
- version: 3.2.0
+ pg:
+ specifier: 8.20.0
+ version: 8.20.0
picocolors:
specifier: ^1.1.1
version: 1.1.1
@@ -1901,6 +1901,9 @@ importers:
'@types/node':
specifier: 20.19.39
version: 20.19.39
+ '@types/pg':
+ specifier: ^8.11.6
+ version: 8.15.6
rimraf:
specifier: 5.0.10
version: 5.0.10
@@ -9273,9 +9276,6 @@ 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'}
@@ -20146,8 +20146,6 @@ snapshots:
-