@omnibase/cli 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/commands/auth.d.ts.map +1 -1
  2. package/dist/commands/auth.js +15 -2
  3. package/dist/commands/auth.js.map +1 -1
  4. package/dist/commands/cloud.d.ts +33 -3
  5. package/dist/commands/cloud.d.ts.map +1 -1
  6. package/dist/commands/cloud.js +838 -56
  7. package/dist/commands/cloud.js.map +1 -1
  8. package/dist/commands/db/index.d.ts.map +1 -1
  9. package/dist/commands/db/index.js +21 -2
  10. package/dist/commands/db/index.js.map +1 -1
  11. package/dist/commands/email.d.ts.map +1 -1
  12. package/dist/commands/email.js +29 -3
  13. package/dist/commands/email.js.map +1 -1
  14. package/dist/commands/environment.d.ts.map +1 -1
  15. package/dist/commands/environment.js +10 -1
  16. package/dist/commands/environment.js.map +1 -1
  17. package/dist/commands/permissions.d.ts.map +1 -1
  18. package/dist/commands/permissions.js +54 -8
  19. package/dist/commands/permissions.js.map +1 -1
  20. package/dist/commands/restart.d.ts.map +1 -1
  21. package/dist/commands/restart.js +15 -2
  22. package/dist/commands/restart.js.map +1 -1
  23. package/dist/commands/stripe.d.ts.map +1 -1
  24. package/dist/commands/stripe.js +99 -17
  25. package/dist/commands/stripe.js.map +1 -1
  26. package/dist/commands/sync.d.ts.map +1 -1
  27. package/dist/commands/sync.js +16 -1
  28. package/dist/commands/sync.js.map +1 -1
  29. package/dist/index.js +39 -5
  30. package/dist/index.js.map +1 -1
  31. package/dist/lib/omnibase.js +1 -1
  32. package/dist/lib/omnibase.js.map +1 -1
  33. package/dist/services/db/generate/policies.d.ts +1 -1
  34. package/dist/services/db/generate/policies.d.ts.map +1 -1
  35. package/dist/services/db/generate/policies.js +3 -3
  36. package/dist/services/db/generate/policies.js.map +1 -1
  37. package/dist/services/db/generate/rls/diff.d.ts.map +1 -1
  38. package/dist/services/db/generate/rls/diff.js +60 -4
  39. package/dist/services/db/generate/rls/diff.js.map +1 -1
  40. package/dist/services/db/generate/rls/emit.d.ts +1 -0
  41. package/dist/services/db/generate/rls/emit.d.ts.map +1 -1
  42. package/dist/services/db/generate/rls/emit.js +29 -4
  43. package/dist/services/db/generate/rls/emit.js.map +1 -1
  44. package/dist/services/db/migrate.d.ts.map +1 -1
  45. package/dist/services/db/migrate.js +8 -4
  46. package/dist/services/db/migrate.js.map +1 -1
  47. package/dist/utils/api-client.d.ts.map +1 -1
  48. package/dist/utils/api-client.js +3 -1
  49. package/dist/utils/api-client.js.map +1 -1
  50. package/dist/utils/config.d.ts +8 -2
  51. package/dist/utils/config.d.ts.map +1 -1
  52. package/dist/utils/config.js +63 -14
  53. package/dist/utils/config.js.map +1 -1
  54. package/dist/utils/docker.d.ts.map +1 -1
  55. package/dist/utils/docker.js +5 -2
  56. package/dist/utils/docker.js.map +1 -1
  57. package/docker/db/000019_rls_helpers_security_definer.down.sql +75 -0
  58. package/docker/db/000019_rls_helpers_security_definer.up.sql +84 -0
  59. package/docker/db/000020_narrow_anon_user_grants.down.sql +10 -0
  60. package/docker/db/000020_narrow_anon_user_grants.up.sql +64 -0
  61. package/docker/db/000021_pg_trgm_schema.down.sql +6 -0
  62. package/docker/db/000021_pg_trgm_schema.up.sql +8 -0
  63. package/docker/docker-compose.base.yml +3 -7
  64. package/package.json +2 -2
  65. package/templates/omnibase.toml +0 -3
@@ -36,6 +36,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.unwrapManagedHostingData = unwrapManagedHostingData;
40
+ exports.packageWorkerBundle = packageWorkerBundle;
41
+ exports.resolveBundleEntry = resolveBundleEntry;
42
+ exports.isGoneBranchStatus = isGoneBranchStatus;
43
+ exports.findLiveBranchByName = findLiveBranchByName;
44
+ exports.pickLiveBranch = pickLiveBranch;
45
+ exports.buildBranchEnv = buildBranchEnv;
46
+ exports.stripUnresolvedOidcProviders = stripUnresolvedOidcProviders;
39
47
  exports.pushEnvConfig = pushEnvConfig;
40
48
  exports.addCloudCommands = addCloudCommands;
41
49
  const child_process_1 = require("child_process");
@@ -47,13 +55,15 @@ const TOML = __importStar(require("smol-toml"));
47
55
  const axios_1 = __importDefault(require("axios"));
48
56
  const prompts_1 = require("@inquirer/prompts");
49
57
  const path = __importStar(require("path"));
50
- const dotenv_1 = require("dotenv");
51
58
  const environment_1 = require("../utils/environment");
52
59
  const credentials_1 = require("../utils/credentials");
53
60
  const logger_1 = require("../utils/logger");
54
61
  const errors_1 = require("../utils/errors");
55
62
  const api_client_1 = require("../utils/api-client");
56
63
  const config_1 = require("../utils/config");
64
+ function unwrapManagedHostingData(body) {
65
+ return (body?.data ?? body);
66
+ }
57
67
  /**
58
68
  * Login to OmniBase Cloud
59
69
  */
@@ -66,7 +76,7 @@ async function login(apiKey, options) {
66
76
  Authorization: `Bearer ${apiKey}`,
67
77
  },
68
78
  });
69
- const data = response.data;
79
+ const data = unwrapManagedHostingData(response.data);
70
80
  if (!data?.tenant_id) {
71
81
  throw new Error("Invalid API key");
72
82
  }
@@ -249,6 +259,8 @@ async function deployWorkers(envFlag, nameFlag, allFlag) {
249
259
  `Ensure your profile is configured: 'omnibase cloud login'`);
250
260
  }
251
261
  const deployments = getDeployments(root);
262
+ const config = (0, config_1.loadConfig)(root);
263
+ const secrets = (0, config_1.loadSecretsMap)(root, env.name);
252
264
  let targets;
253
265
  if (nameFlag) {
254
266
  const match = deployments.find((d) => d.name === nameFlag);
@@ -271,10 +283,12 @@ async function deployWorkers(envFlag, nameFlag, allFlag) {
271
283
  });
272
284
  targets = [selected];
273
285
  }
286
+ const failures = [];
274
287
  for (const dep of targets) {
275
288
  const workersDir = path.join(root, "omnibase", dep.path ?? dep.name);
276
289
  if (!fs.existsSync(workersDir)) {
277
290
  logger_1.logger.fail(`Deployment '${dep.name}' directory not found: ${workersDir}`);
291
+ failures.push(dep.name);
278
292
  continue;
279
293
  }
280
294
  logger_1.logger.start(`Building '${dep.name}' for ${env.name}...`);
@@ -282,24 +296,31 @@ async function deployWorkers(envFlag, nameFlag, allFlag) {
282
296
  (0, child_process_1.execSync)("bunx wrangler deploy --dry-run --outdir .bundle", {
283
297
  cwd: workersDir,
284
298
  stdio: "inherit",
299
+ env: { ...process.env, ...secrets },
285
300
  });
286
301
  }
287
302
  catch (error) {
288
303
  logger_1.logger.fail(`Build failed for '${dep.name}'. Check the output above.`);
304
+ failures.push(dep.name);
289
305
  continue;
290
306
  }
291
- const bundle = await packageWorkerBundle(workersDir);
307
+ const bundle = await packageWorkerBundle(workersDir, secrets);
292
308
  logger_1.logger.succeed(`${dep.name}: packaged (${(bundle.length / 1024).toFixed(1)} KB)`);
293
309
  logger_1.logger.start(`Deploying '${dep.name}'...`);
294
310
  try {
295
311
  const result = await uploadToManagedHosting(env, bundle, dep.name);
312
+ const deployed = unwrapManagedHostingData(result);
296
313
  logger_1.logger.succeed(`${dep.name} deployed`);
297
- logger_1.logger.log(` URL: ${result.url}`);
314
+ logger_1.logger.log(` URL: ${deployed?.url}`);
298
315
  }
299
316
  catch (error) {
300
317
  logger_1.logger.fail(`${dep.name} deploy failed: ${(0, errors_1.formatHttpError)(error)}`);
318
+ failures.push(dep.name);
301
319
  }
302
320
  }
321
+ if (failures.length > 0) {
322
+ throw new Error(`Failed to deploy: ${failures.join(", ")}`);
323
+ }
303
324
  }
304
325
  /**
305
326
  * Turn a `wrangler deploy --dry-run --outdir .bundle` output into a
@@ -307,13 +328,13 @@ async function deployWorkers(envFlag, nameFlag, allFlag) {
307
328
  * `wrangler deploy --dispatch-namespace`. Framework-agnostic: everything is
308
329
  * derived from the project's own wrangler config.
309
330
  */
310
- async function packageWorkerBundle(workersDir) {
311
- const config = await loadWranglerConfig(workersDir);
331
+ async function packageWorkerBundle(workersDir, secrets = {}) {
332
+ const config = (await (0, config_1.interpolateValue)(await loadWranglerConfig(workersDir), secrets));
312
333
  delete config.build;
313
334
  delete config.name;
314
- config.main = "worker.js";
335
+ config.main = await resolveBundleEntry(path.join(workersDir, ".bundle"), config.main);
315
336
  const zip = new jszip_1.default();
316
- await addDirToZip(zip, path.join(workersDir, ".bundle"), (name) => name.endsWith(".map"));
337
+ await addDirToZip(zip, path.join(workersDir, ".bundle"), (name) => name.endsWith(".map") || name === "README.md");
317
338
  const assetsDir = config.assets?.directory;
318
339
  if (assetsDir) {
319
340
  config.assets = { ...config.assets, directory: "assets" };
@@ -325,6 +346,22 @@ async function packageWorkerBundle(workersDir) {
325
346
  compression: "DEFLATE",
326
347
  });
327
348
  }
349
+ async function resolveBundleEntry(bundleDir, configuredMain) {
350
+ const entries = await (0, promises_1.readdir)(bundleDir, { withFileTypes: true });
351
+ const files = entries
352
+ .filter((e) => e.isFile() && !e.name.endsWith(".map"))
353
+ .map((e) => e.name);
354
+ if (configuredMain) {
355
+ const base = path.basename(configuredMain).replace(/\.[^.]+$/, "");
356
+ const match = files.find((f) => path.basename(f).replace(/\.[^.]+$/, "") === base);
357
+ if (match)
358
+ return match;
359
+ }
360
+ const candidates = files.filter((f) => !f.startsWith("chunk-") && /\.(js|mjs)$/.test(f));
361
+ if (candidates.length === 1)
362
+ return candidates[0];
363
+ throw new Error("Could not determine the worker entry module. Check the .bundle output.");
364
+ }
328
365
  async function loadWranglerConfig(workersDir) {
329
366
  const parsers = {
330
367
  "wrangler.jsonc": stripJsonc,
@@ -387,6 +424,146 @@ async function uploadToManagedHosting(env, bundle, deploymentName = "default") {
387
424
  throw new Error((0, errors_1.formatHttpError)(error));
388
425
  }
389
426
  }
427
+ const GONE_BRANCH_STATUSES = new Set(["deleted", "deleting"]);
428
+ const FAILED_BRANCH_STATUSES = new Set([
429
+ "failed",
430
+ "failed_deletion",
431
+ "suspended",
432
+ "deleted",
433
+ ]);
434
+ function isGoneBranchStatus(status) {
435
+ return GONE_BRANCH_STATUSES.has(status);
436
+ }
437
+ function findLiveBranchByName(branches, name) {
438
+ return branches.find((branch) => branch.name === name && !isGoneBranchStatus(branch.status));
439
+ }
440
+ function pickLiveBranch(branches, ref) {
441
+ const matches = branches.filter((branch) => branch.id === ref || branch.name === ref || branch.slug === ref);
442
+ return (matches.find((branch) => !isGoneBranchStatus(branch.status)) ?? matches[0]);
443
+ }
444
+ function resolveProjectId(projectIdFlag) {
445
+ const root = (0, environment_1.findOmnibaseRoot)();
446
+ const config = (0, config_1.loadConfig)(root);
447
+ const projectId = projectIdFlag ?? config.project_id;
448
+ if (!projectId) {
449
+ throw new Error("project_id is required. Provide --project-id or set it in omnibase.toml");
450
+ }
451
+ return projectId;
452
+ }
453
+ async function listProjectBranches(api, projectId) {
454
+ const response = await api.get(`/api/v1/projects/${projectId}/branches`);
455
+ return Array.isArray(response.data) ? response.data : [];
456
+ }
457
+ async function getBranchDetail(api, branchId) {
458
+ const response = await api.get(`/api/v1/project_branches/${branchId}`);
459
+ return response.data;
460
+ }
461
+ function isNotFound(error) {
462
+ return axios_1.default.isAxiosError(error) && error.response?.status === 404;
463
+ }
464
+ function sleep(ms) {
465
+ return new Promise((resolve) => setTimeout(resolve, ms));
466
+ }
467
+ function parseSeconds(value, fallback) {
468
+ if (value === undefined)
469
+ return fallback;
470
+ const seconds = Number(value);
471
+ if (!Number.isFinite(seconds) || seconds <= 0) {
472
+ throw new Error(`Invalid timeout: ${value}`);
473
+ }
474
+ return seconds;
475
+ }
476
+ async function checkBranchHealth(apiUrl) {
477
+ try {
478
+ const response = await axios_1.default.get(`${apiUrl.replace(/\/+$/, "")}/health/ready`, { timeout: 10000, validateStatus: (status) => status === 200 });
479
+ return response.status === 200;
480
+ }
481
+ catch {
482
+ return false;
483
+ }
484
+ }
485
+ async function waitForBranchActive(api, branchId, timeoutMs, quiet) {
486
+ const deadline = Date.now() + timeoutMs;
487
+ let lastStatus = "";
488
+ while (Date.now() < deadline) {
489
+ let detail;
490
+ try {
491
+ detail = await getBranchDetail(api, branchId);
492
+ }
493
+ catch (error) {
494
+ if (!isNotFound(error))
495
+ throw error;
496
+ }
497
+ if (detail) {
498
+ if (detail.status !== lastStatus) {
499
+ lastStatus = detail.status;
500
+ if (!quiet)
501
+ logger_1.logger.info(`Branch status: ${detail.status}`);
502
+ }
503
+ if (detail.status === "active")
504
+ return detail;
505
+ if (FAILED_BRANCH_STATUSES.has(detail.status)) {
506
+ const message = detail.error_message
507
+ ? `${detail.status}: ${detail.error_message}`
508
+ : detail.status;
509
+ throw new Error(`Branch ${detail.name} is ${message}`);
510
+ }
511
+ }
512
+ await sleep(5000);
513
+ }
514
+ throw new Error(`Timed out after ${Math.round(timeoutMs / 1000)}s waiting for branch ${branchId} to become active`);
515
+ }
516
+ async function waitForBranchHealthy(apiUrl, timeoutMs, quiet) {
517
+ const deadline = Date.now() + timeoutMs;
518
+ while (Date.now() < deadline) {
519
+ if (await checkBranchHealth(apiUrl)) {
520
+ if (!quiet)
521
+ logger_1.logger.succeed(`Branch is healthy at ${apiUrl}`);
522
+ return;
523
+ }
524
+ await sleep(5000);
525
+ }
526
+ throw new Error(`Timed out after ${Math.round(timeoutMs / 1000)}s waiting for ${apiUrl}/health/ready`);
527
+ }
528
+ async function getApiServiceKey(api, branchId) {
529
+ try {
530
+ const response = await api.get(`/api/v1/project_branches/${branchId}/api-service-key`);
531
+ const keyData = response.data?.data ?? response.data;
532
+ const serviceKey = keyData?.api_service_key ?? keyData?.service_key;
533
+ if (!serviceKey) {
534
+ throw new Error("API service key missing from response");
535
+ }
536
+ return serviceKey;
537
+ }
538
+ catch (error) {
539
+ throw new Error(`Failed to load branch API service key: ${(0, errors_1.formatHttpError)(error)}`);
540
+ }
541
+ }
542
+ function buildBranchEnv(input) {
543
+ const apiUrl = input.apiUrl.replace(/\/+$/, "");
544
+ const hostname = new URL(apiUrl).hostname;
545
+ const composedSlug = hostname.split(".")[0];
546
+ if (!composedSlug) {
547
+ throw new Error(`Could not derive a branch slug from ${input.apiUrl}`);
548
+ }
549
+ const workerDomain = (input.workerDomain ?? "workers.omnibase.tech").replace(/^\.+/, "");
550
+ const cookieDomain = input.cookieDomain ?? `.${workerDomain}`;
551
+ const dashboardUrl = (input.dashboardUrl ?? `https://${composedSlug}-dashboard.${workerDomain}`).replace(/\/+$/, "");
552
+ const postgrestUrl = (input.postgrestUrl ?? `${apiUrl}/rest/v1`).replace(/\/+$/, "");
553
+ return {
554
+ NEXT_PUBLIC_WEBSITE_URL: dashboardUrl,
555
+ WEBSITE_URL: dashboardUrl,
556
+ ALLOWED_RETURN_URLS: dashboardUrl,
557
+ NEXT_PUBLIC_OMNIBASE_WORKER_URL: dashboardUrl,
558
+ OMNIBASE_API_URL: apiUrl,
559
+ NEXT_PUBLIC_OMNIBASE_API_URL: apiUrl,
560
+ OMNIBASE_POSTGREST_URL: postgrestUrl,
561
+ OMNIBASE_SERVICE_KEY: input.serviceKey,
562
+ MANAGED_HOSTING_API_URL: input.managedHostingUrl,
563
+ NEXT_PUBLIC_MANAGED_HOSTING_API_URL: input.managedHostingUrl,
564
+ OMNIBASE_COOKIE_DOMAIN: cookieDomain,
565
+ };
566
+ }
390
567
  /**
391
568
  * Resolve a branch for the project from managed hosting. A `--env` value
392
569
  * matches by name, slug, or id; otherwise a single branch is auto-selected or
@@ -430,10 +607,31 @@ async function resolveBranch(managedHostingUrl, projectId, branchFlag) {
430
607
  * lives, since managed hosting owns Stripe env via the Connect account it
431
608
  * provisions per branch.
432
609
  *
433
- * {VAR} secrets resolve from process.env, then an optional --from-env file.
434
- * .env.local is NEVER read here — it is strictly for local dev (omnibase start).
610
+ * {VAR} secrets resolve from process.env → omnibase/.env.<branch>.
435
611
  */
436
- async function pushEnvConfig(envFlag, fromEnvPath) {
612
+ function stripUnresolvedOidcProviders(payload) {
613
+ const auth = payload.auth;
614
+ const providers = auth?.oidc;
615
+ if (!Array.isArray(providers))
616
+ return [];
617
+ const dropped = [];
618
+ auth.oidc = providers.filter((provider) => {
619
+ const unresolved = ["client_id", "client_secret"].some((key) => {
620
+ const value = provider[key];
621
+ return typeof value === "string" && /\{[A-Za-z_][A-Za-z0-9_]*\}/.test(value);
622
+ });
623
+ if (unresolved) {
624
+ dropped.push(String(provider.provider ?? "unknown"));
625
+ return false;
626
+ }
627
+ return true;
628
+ });
629
+ if (auth.oidc.length === 0) {
630
+ delete auth.oidc;
631
+ }
632
+ return dropped;
633
+ }
634
+ async function pushEnvConfig(envFlag) {
437
635
  const root = (0, environment_1.findOmnibaseRoot)();
438
636
  const env = await (0, environment_1.selectEnvironment)(envFlag);
439
637
  if (env.name === "local") {
@@ -453,28 +651,16 @@ async function pushEnvConfig(envFlag, fromEnvPath) {
453
651
  if (!config.project_id) {
454
652
  throw new Error("project_id is required in omnibase/omnibase.toml for cloud env push.");
455
653
  }
456
- // Cloud resolution is process.env then --from-env; .env.local is local-only.
457
- const secrets = {};
458
- for (const [k, v] of Object.entries(process.env)) {
459
- if (v !== undefined)
460
- secrets[k] = v;
461
- }
462
- if (fromEnvPath) {
463
- const resolvedPath = path.resolve(fromEnvPath);
464
- const parsed = (0, dotenv_1.config)({ path: resolvedPath }).parsed;
465
- if (!parsed) {
466
- throw new Error(`--from-env file not found or empty: ${resolvedPath}`);
467
- }
468
- for (const [k, v] of Object.entries(parsed)) {
469
- if (!(k in secrets))
470
- secrets[k] = v;
471
- }
472
- }
654
+ const secrets = (0, config_1.loadSecretsMap)(root, env.name);
473
655
  const resolved = (0, config_1.interpolateValue)(config, secrets);
474
656
  if (resolved.versions) {
475
657
  (0, config_1.assertValidVersions)(resolved.versions);
476
658
  }
477
659
  const payload = (0, config_1.cloudConfigOf)(resolved);
660
+ const droppedOidc = stripUnresolvedOidcProviders(payload);
661
+ if (droppedOidc.length > 0) {
662
+ logger_1.logger.warn(`Skipping OIDC provider(s) with unresolved credentials: ${droppedOidc.join(", ")}`);
663
+ }
478
664
  const sections = Object.keys(payload);
479
665
  if (sections.length === 0) {
480
666
  logger_1.logger.info("Nothing to push: omnibase.toml has no cloud config sections.");
@@ -485,7 +671,7 @@ async function pushEnvConfig(envFlag, fromEnvPath) {
485
671
  ];
486
672
  if (unresolved.length > 0) {
487
673
  logger_1.logger.warn(`Unresolved ${unresolved.join(", ")} left literal. ` +
488
- `Set them in process.env or pass --from-env <file>.`);
674
+ `Set them in process.env or omnibase/.env.${env.name}.`);
489
675
  }
490
676
  logger_1.logger.start(`Applying config (${sections.join(", ")}) to branch ${env.name}...`);
491
677
  const api = (0, api_client_1.createManagedHostingClient)(env);
@@ -595,25 +781,142 @@ async function branchList(projectIdFlag) {
595
781
  throw new Error((0, errors_1.formatHttpError)(error));
596
782
  }
597
783
  }
784
+ async function branchEnsure(branchName, options) {
785
+ const api = (0, api_client_1.createProfileClient)();
786
+ const projectId = resolveProjectId(options.projectId);
787
+ const quiet = Boolean(options.json);
788
+ if (!quiet)
789
+ logger_1.logger.start(`Resolving branch '${branchName}'...`);
790
+ const branches = await listProjectBranches(api, projectId);
791
+ let branch = findLiveBranchByName(branches, branchName);
792
+ if (branch) {
793
+ if (!quiet)
794
+ logger_1.logger.succeed(`Reusing branch '${branch.name}' (${branch.id})`);
795
+ }
796
+ else {
797
+ if (!options.region || !options.tier || !options.email) {
798
+ throw new Error("--region, --tier, and --email are required when creating a branch");
799
+ }
800
+ if (!quiet)
801
+ logger_1.logger.start(`Creating branch '${branchName}'...`);
802
+ const response = await api.post("/api/v1/project_branches", {
803
+ project_id: projectId,
804
+ branch_name: branchName,
805
+ region: options.region,
806
+ deployment_tier: options.tier,
807
+ billing_email: options.email,
808
+ });
809
+ branch = {
810
+ id: response.data.branch_id,
811
+ name: branchName,
812
+ slug: "",
813
+ status: response.data.status ?? "provisioning",
814
+ };
815
+ if (!quiet)
816
+ logger_1.logger.succeed(`Branch '${branchName}' provisioning started`);
817
+ }
818
+ let detail = {
819
+ ...branch,
820
+ project_id: projectId,
821
+ };
822
+ if (options.wait !== false) {
823
+ const timeoutMs = parseSeconds(options.timeout, 1800) * 1000;
824
+ const healthTimeoutMs = parseSeconds(options.healthTimeout, 600) * 1000;
825
+ detail = await waitForBranchActive(api, branch.id, timeoutMs, quiet);
826
+ if (!detail.api_url) {
827
+ throw new Error(`Branch ${detail.name} is active but has no API URL`);
828
+ }
829
+ await waitForBranchHealthy(detail.api_url, healthTimeoutMs, quiet);
830
+ }
831
+ if (options.json) {
832
+ logger_1.logger.log(JSON.stringify({
833
+ id: detail.id,
834
+ name: detail.name,
835
+ slug: detail.slug,
836
+ status: detail.status,
837
+ project_id: detail.project_id,
838
+ api_url: detail.api_url ?? null,
839
+ postgrest_url: detail.postgrest_url ?? null,
840
+ }));
841
+ return;
842
+ }
843
+ logger_1.logger.log("");
844
+ logger_1.logger.log(`Branch: ${detail.name} (${detail.id})`);
845
+ logger_1.logger.log(`Status: ${detail.status}`);
846
+ if (detail.api_url)
847
+ logger_1.logger.log(`API URL: ${detail.api_url}`);
848
+ logger_1.logger.log("");
849
+ logger_1.logger.log(`Next steps:`);
850
+ logger_1.logger.log(` omnibase cloud branch env ${detail.name} --output omnibase/.env.${detail.name}`);
851
+ logger_1.logger.log(` omnibase sync all --env ${detail.name}`);
852
+ logger_1.logger.log(` omnibase cloud workers deploy --all --env ${detail.name}`);
853
+ }
854
+ async function branchEnv(branchRef, options) {
855
+ const api = (0, api_client_1.createProfileClient)();
856
+ const projectId = resolveProjectId(options.projectId);
857
+ logger_1.logger.start(`Resolving branch '${branchRef}'...`);
858
+ const branches = await listProjectBranches(api, projectId);
859
+ const branch = pickLiveBranch(branches, branchRef);
860
+ if (!branch || isGoneBranchStatus(branch.status)) {
861
+ throw new Error(`Branch '${branchRef}' not found in project ${projectId}`);
862
+ }
863
+ const detail = await getBranchDetail(api, branch.id);
864
+ if (!detail.api_url) {
865
+ throw new Error(`Branch '${branchRef}' has no API URL yet`);
866
+ }
867
+ const serviceKey = await getApiServiceKey(api, branch.id);
868
+ const profile = (0, credentials_1.getActiveProfile)();
869
+ const managedHostingUrl = profile?.managed_hosting_url ?? process.env.MANAGED_HOSTING_API_URL;
870
+ if (!managedHostingUrl) {
871
+ throw new Error("No managed hosting URL configured. Run 'omnibase cloud login' or set MANAGED_HOSTING_API_URL.");
872
+ }
873
+ const env = buildBranchEnv({
874
+ apiUrl: detail.api_url,
875
+ postgrestUrl: detail.postgrest_url,
876
+ serviceKey,
877
+ managedHostingUrl,
878
+ workerDomain: options.workerDomain ?? process.env.OMNIBASE_WORKER_DOMAIN,
879
+ cookieDomain: options.cookieDomain ?? process.env.OMNIBASE_COOKIE_DOMAIN,
880
+ dashboardUrl: options.dashboardUrl,
881
+ });
882
+ const content = Object.entries(env)
883
+ .map(([key, value]) => `${key}=${value}`)
884
+ .join("\n") + "\n";
885
+ if (options.output) {
886
+ const target = path.resolve(options.output);
887
+ fs.mkdirSync(path.dirname(target), { recursive: true });
888
+ fs.writeFileSync(target, content, { mode: 0o600 });
889
+ logger_1.logger.succeed(`Wrote branch environment to ${target}`);
890
+ return;
891
+ }
892
+ logger_1.logger.succeed(`Resolved to ${detail.name} (${detail.id})`);
893
+ logger_1.logger.log(content.trimEnd());
894
+ }
598
895
  /**
599
896
  * Delete a branch by name or ID
600
897
  */
601
- async function branchDelete(branchRef, projectIdFlag) {
602
- const root = (0, environment_1.findOmnibaseRoot)();
898
+ async function branchDelete(branchRef, projectIdFlag, options = {}) {
603
899
  const api = (0, api_client_1.createProfileClient)();
604
- const config = (0, config_1.loadConfig)(root);
605
- const projectId = projectIdFlag ?? config.project_id;
606
- if (!projectId) {
607
- throw new Error("project_id is required. Provide --project-id or set it in omnibase.toml");
608
- }
900
+ const projectId = resolveProjectId(projectIdFlag);
609
901
  logger_1.logger.start(`Resolving branch '${branchRef}'...`);
610
- const response = await api.get(`/api/v1/projects/${projectId}/branches`);
611
- const branches = response.data;
612
- const match = branches.find((b) => b.id === branchRef || b.name === branchRef || b.slug === branchRef);
902
+ const branches = await listProjectBranches(api, projectId);
903
+ const match = pickLiveBranch(branches, branchRef);
613
904
  if (!match) {
905
+ if (options.ifExists) {
906
+ logger_1.logger.succeed(`Branch '${branchRef}' does not exist`);
907
+ return;
908
+ }
614
909
  logger_1.logger.fail(`Branch '${branchRef}' not found`);
615
910
  throw new Error(`Branch '${branchRef}' not found in project ${projectId}`);
616
911
  }
912
+ if (isGoneBranchStatus(match.status)) {
913
+ if (options.ifExists) {
914
+ logger_1.logger.succeed(`Branch '${branchRef}' is already ${match.status}`);
915
+ return;
916
+ }
917
+ logger_1.logger.fail(`Branch '${branchRef}' is already ${match.status}`);
918
+ throw new Error(`Branch '${branchRef}' is already ${match.status}`);
919
+ }
617
920
  logger_1.logger.succeed(`Resolved to ${match.name} (${match.id})`);
618
921
  logger_1.logger.start(`Deprovisioning branch '${branchRef}'...`);
619
922
  try {
@@ -651,16 +954,172 @@ async function listWorkers(envFlag) {
651
954
  throw new Error((0, errors_1.formatHttpError)(error));
652
955
  }
653
956
  }
957
+ /**
958
+ * Add an account-level custom domain (e.g. example.com or *.example.com)
959
+ */
960
+ async function domainAdd(envFlag, domain) {
961
+ const env = await (0, environment_1.selectEnvironment)(envFlag);
962
+ const api = (0, api_client_1.createManagedHostingClient)(env);
963
+ logger_1.logger.start(`Adding domain ${domain}...`);
964
+ try {
965
+ const response = await api.post(`/api/v1/domains`, { hostname: domain });
966
+ const d = response.data;
967
+ logger_1.logger.succeed(`Domain ${domain} added (status: ${d.status})`);
968
+ if (d.dcv_record_name && d.dcv_record_value) {
969
+ logger_1.logger.log("Add these DNS records at your domain provider:");
970
+ logger_1.logger.log(` ${d.hostname} CNAME → ${d.cname_target}`);
971
+ logger_1.logger.log(` ${d.dcv_record_name} TXT → ${d.dcv_record_value}`);
972
+ logger_1.logger.log("Then run: omnibase cloud domains status <id>");
973
+ }
974
+ else {
975
+ logger_1.logger.log(`Point ${domain} to ${d.cname_target}`);
976
+ }
977
+ }
978
+ catch (error) {
979
+ logger_1.logger.fail("Failed to add domain");
980
+ throw new Error((0, errors_1.formatHttpError)(error));
981
+ }
982
+ }
983
+ /**
984
+ * List account-level domains
985
+ */
986
+ async function domainList(envFlag) {
987
+ const env = await (0, environment_1.selectEnvironment)(envFlag);
988
+ const api = (0, api_client_1.createManagedHostingClient)(env);
989
+ logger_1.logger.start("Fetching domains...");
990
+ try {
991
+ const response = await api.get(`/api/v1/domains`);
992
+ const domains = response.data;
993
+ logger_1.logger.succeed(`Found ${domains?.length || 0} domain(s)`);
994
+ if (!domains || domains.length === 0)
995
+ return;
996
+ for (const d of domains) {
997
+ logger_1.logger.log(` ${d.hostname} — ${d.status}${d.ssl_status ? ` (ssl: ${d.ssl_status})` : ""}`);
998
+ }
999
+ }
1000
+ catch (error) {
1001
+ logger_1.logger.fail("Failed to fetch domains");
1002
+ throw new Error((0, errors_1.formatHttpError)(error));
1003
+ }
1004
+ }
1005
+ /**
1006
+ * Remove an account-level domain
1007
+ */
1008
+ async function domainRemove(envFlag, domainId) {
1009
+ const env = await (0, environment_1.selectEnvironment)(envFlag);
1010
+ const api = (0, api_client_1.createManagedHostingClient)(env);
1011
+ logger_1.logger.start("Removing domain...");
1012
+ try {
1013
+ await api.delete(`/api/v1/domains/${domainId}`);
1014
+ logger_1.logger.succeed("Domain removed");
1015
+ }
1016
+ catch (error) {
1017
+ logger_1.logger.fail("Failed to remove domain");
1018
+ throw new Error((0, errors_1.formatHttpError)(error));
1019
+ }
1020
+ }
1021
+ /**
1022
+ * Poll the status of an account-level domain until it activates or times out
1023
+ */
1024
+ async function domainStatus(envFlag, domainId, pollSeconds) {
1025
+ const env = await (0, environment_1.selectEnvironment)(envFlag);
1026
+ const api = (0, api_client_1.createManagedHostingClient)(env);
1027
+ const deadline = Date.now() + pollSeconds * 1000;
1028
+ try {
1029
+ while (Date.now() < deadline) {
1030
+ const response = await api.get(`/api/v1/domains/${domainId}/status`);
1031
+ const d = response.data;
1032
+ logger_1.logger.log(` ${d.hostname} — ${d.status}${d.ssl_status ? ` (ssl: ${d.ssl_status})` : ""}`);
1033
+ if (d.status === "active") {
1034
+ logger_1.logger.succeed(`Domain ${d.hostname} is live`);
1035
+ return;
1036
+ }
1037
+ if (d.dcv_record_name && d.dcv_record_value && d.status !== "active") {
1038
+ logger_1.logger.log("DNS records needed:");
1039
+ logger_1.logger.log(` ${d.hostname} CNAME → ${d.cname_target}`);
1040
+ logger_1.logger.log(` ${d.dcv_record_name} TXT → ${d.dcv_record_value}`);
1041
+ logger_1.logger.log("Waiting for DNS + certificate issuance...");
1042
+ }
1043
+ await new Promise((resolve) => setTimeout(resolve, 5000));
1044
+ }
1045
+ logger_1.logger.fail("Timed out waiting for domain activation");
1046
+ }
1047
+ catch (error) {
1048
+ logger_1.logger.fail("Failed to check domain status");
1049
+ throw new Error((0, errors_1.formatHttpError)(error));
1050
+ }
1051
+ }
1052
+ /**
1053
+ * Attach a validated account domain to a worker
1054
+ */
1055
+ async function domainAttach(envFlag, domainId, workerName, hostname) {
1056
+ const env = await (0, environment_1.selectEnvironment)(envFlag);
1057
+ const api = (0, api_client_1.createManagedHostingClient)(env);
1058
+ const branchId = env.branchId;
1059
+ if (!branchId) {
1060
+ throw new Error("No branch selected");
1061
+ }
1062
+ logger_1.logger.start(`Attaching domain ${domainId} to worker ${workerName}...`);
1063
+ try {
1064
+ const body = { account_domain_id: domainId };
1065
+ if (hostname)
1066
+ body.hostname = hostname;
1067
+ const response = await api.post(`/api/v1/project_branches/${branchId}/workers/${encodeURIComponent(workerName)}/domains`, body);
1068
+ const d = response.data;
1069
+ logger_1.logger.succeed(`Domain ${d.hostname} attached (status: ${d.status})`);
1070
+ }
1071
+ catch (error) {
1072
+ logger_1.logger.fail("Failed to attach domain");
1073
+ throw new Error((0, errors_1.formatHttpError)(error));
1074
+ }
1075
+ }
1076
+ /**
1077
+ * Detach a domain from a worker
1078
+ */
1079
+ async function domainDetach(envFlag, domainId) {
1080
+ const env = await (0, environment_1.selectEnvironment)(envFlag);
1081
+ const api = (0, api_client_1.createManagedHostingClient)(env);
1082
+ const branchId = env.branchId;
1083
+ if (!branchId) {
1084
+ throw new Error("No branch selected");
1085
+ }
1086
+ logger_1.logger.start("Removing domain from worker...");
1087
+ try {
1088
+ await api.delete(`/api/v1/project_branches/${branchId}/worker-domains/${domainId}`);
1089
+ logger_1.logger.succeed("Domain removed from worker");
1090
+ }
1091
+ catch (error) {
1092
+ logger_1.logger.fail("Failed to remove domain from worker");
1093
+ throw new Error((0, errors_1.formatHttpError)(error));
1094
+ }
1095
+ }
654
1096
  /**
655
1097
  * Add cloud commands to the CLI program
656
1098
  */
657
1099
  function addCloudCommands(program) {
658
1100
  const cloud = program
659
1101
  .command("cloud")
660
- .description("Manage OmniBase Cloud (authentication and deployments)");
1102
+ .summary("Manage OmniBase Cloud")
1103
+ .description("Manage OmniBase Cloud — profile authentication, branch provisioning, " +
1104
+ "Cloudflare Workers deployments, custom domains, and environment config.\n\n" +
1105
+ "Start with `login` to authenticate with an API key and create a profile, " +
1106
+ "then `workers deploy` to ship deployments and `env push` to sync " +
1107
+ "omnibase.toml config to a branch.");
661
1108
  cloud
662
1109
  .command("login")
663
- .description("Login to OmniBase Cloud")
1110
+ .summary("Authenticate with an API key and save a profile")
1111
+ .description("Verify an API key against the managed hosting API and save it as a " +
1112
+ "local profile.\n\n" +
1113
+ "The profile is named after the tenant and key (or `--name`) and is set " +
1114
+ "as active, so subsequent cloud commands use it automatically. " +
1115
+ "Authentication is stored in the CLI credentials file, not in the project.\n\n" +
1116
+ "Before: obtain an API key from the OmniBase dashboard.\n" +
1117
+ "After: a profile is saved and active. Verify with `omnibase cloud profiles`.\n\n" +
1118
+ "```bash\n" +
1119
+ "omnibase cloud login sk_live_abc123\n" +
1120
+ "omnibase cloud login sk_live_abc123 --name staging\n" +
1121
+ "omnibase cloud login sk_live_abc123 --url https://api.omnibase.io\n" +
1122
+ "```")
664
1123
  .argument("<api_key>", "API Key")
665
1124
  .option("--url <url>", "Managed hosting URL")
666
1125
  .option("--name <name>", "Profile name")
@@ -669,7 +1128,18 @@ function addCloudCommands(program) {
669
1128
  });
670
1129
  cloud
671
1130
  .command("logout [profile]")
672
- .description("Logout from OmniBase Cloud (interactive if no profile specified)")
1131
+ .summary("Remove saved authentication profiles")
1132
+ .description("Remove one, several, or all saved profiles.\n\n" +
1133
+ "With a `[profile]` argument only that profile is removed. Without one, " +
1134
+ "an interactive multi-select prompt shows all profiles. `--all` removes " +
1135
+ "every profile and clears the active profile.\n\n" +
1136
+ "If the active profile is removed, the first remaining profile becomes " +
1137
+ "active (or none if the list is empty).\n\n" +
1138
+ "```bash\n" +
1139
+ "omnibase cloud logout\n" +
1140
+ "omnibase cloud logout staging\n" +
1141
+ "omnibase cloud logout --all\n" +
1142
+ "```")
673
1143
  .option("--all", "Remove all profiles")
674
1144
  .action(async (profile, options) => {
675
1145
  try {
@@ -686,7 +1156,17 @@ function addCloudCommands(program) {
686
1156
  });
687
1157
  cloud
688
1158
  .command("switch [profile]")
689
- .description("Switch active profile (interactive if no profile specified)")
1159
+ .summary("Change the active profile")
1160
+ .description("Set which saved profile subsequent cloud commands use.\n\n" +
1161
+ "With a `[profile]` argument the profile is switched directly. Without " +
1162
+ "one, an interactive select shows all saved profiles with the current " +
1163
+ "one marked.\n\n" +
1164
+ "Before: at least one profile must exist (see `omnibase cloud login`).\n" +
1165
+ "After: cloud commands resolve credentials from the active profile.\n\n" +
1166
+ "```bash\n" +
1167
+ "omnibase cloud switch\n" +
1168
+ "omnibase cloud switch acme-prod\n" +
1169
+ "```")
690
1170
  .action(async (profile) => {
691
1171
  try {
692
1172
  await switchProfile(profile);
@@ -702,17 +1182,61 @@ function addCloudCommands(program) {
702
1182
  });
703
1183
  cloud
704
1184
  .command("profiles")
705
- .description("List authentication profiles")
1185
+ .summary("List saved authentication profiles")
1186
+ .description("List every saved profile with its tenant, key name, and key prefix, " +
1187
+ "marking the active profile.\n\n" +
1188
+ "Before: at least one profile must exist (see `omnibase cloud login`).\n\n" +
1189
+ "```bash\n" +
1190
+ "omnibase cloud profiles\n" +
1191
+ "```")
706
1192
  .action(async () => {
707
1193
  await listProfiles();
708
1194
  });
709
1195
  // Workers subcommand
710
1196
  const workers = cloud
711
1197
  .command("workers")
712
- .description("Manage Cloudflare Workers deployments");
1198
+ .summary("Manage Cloudflare Workers deployments")
1199
+ .description("Deploy and inspect the Workers deployments defined in omnibase.toml " +
1200
+ "or `omnibase/workers/`.\n\n" +
1201
+ "Each deployment maps to a directory (default `omnibase/workers/`) " +
1202
+ "containing a `wrangler.toml`, `wrangler.jsonc`, or `wrangler.json`. " +
1203
+ "`deploy` ships a deployment to the managed hosting cloud; `list` shows " +
1204
+ "what is currently deployed for a branch.");
713
1205
  workers
714
1206
  .command("deploy")
715
- .description("Deploy workers to Cloudflare")
1207
+ .summary("Deploy workers to Cloudflare via managed hosting")
1208
+ .description("Build, package, and upload one or more Workers deployments for the " +
1209
+ "selected cloud branch.\n\n" +
1210
+ "End-to-end flow:\n" +
1211
+ "1. Resolve the target environment (`--env` or interactive picker).\n" +
1212
+ "2. Load the resolved secrets for that branch (see env resolution below).\n" +
1213
+ "3. Run `bunx wrangler deploy --dry-run --outdir .bundle` in the " +
1214
+ " deployment directory with the resolved env exported. If the wrangler " +
1215
+ " config declares a `build.command`, wrangler runs it first, so the app " +
1216
+ " is built as part of the deploy; the result is a production bundle.\n" +
1217
+ "4. Package the bundle plus any `[assets]` into a self-contained zip, " +
1218
+ " with the deployment's `wrangler.json` `[vars]` interpolated at " +
1219
+ " package time.\n" +
1220
+ "5. Upload the bundle to managed hosting, which runs " +
1221
+ " `wrangler deploy --dispatch-namespace` and returns the live URL.\n\n" +
1222
+ "By default a single-deployment project deploys it directly; with " +
1223
+ "multiple deployments you are prompted to select one. `--name` picks a " +
1224
+ "specific deployment by name and `--all` deploys every deployment.\n\n" +
1225
+ "Before: the branch must be provisioned (has a branch ID) and a profile " +
1226
+ "must be configured (`omnibase cloud login`). Deployments must exist in " +
1227
+ "omnibase.toml or `omnibase/workers/`. Cloud environments are required — " +
1228
+ "deploying to `local` is not supported.\n\n" +
1229
+ "Environment variables: `{VAR}` references in the wrangler `[vars]` " +
1230
+ "resolve from the branch env file. See the env resolution model on the " +
1231
+ "[`cloud env`](/reference/cli/cloud/env) page.\n\n" +
1232
+ "Caveats: values in `[vars]` are visible in the deployed worker — put " +
1233
+ "secrets in `wrangler secret` or the managed-hosting secrets API, not in " +
1234
+ "`[vars]`. Unresolved `{VAR}` values are left literal and the CLI warns.\n\n" +
1235
+ "```bash\n" +
1236
+ "omnibase cloud workers deploy --env dev\n" +
1237
+ "omnibase cloud workers deploy --env staging --name api\n" +
1238
+ "omnibase cloud workers deploy --env production --all\n" +
1239
+ "```")
716
1240
  .option("--name <name>", "Deploy a specific deployment by name")
717
1241
  .option("--all", "Deploy all deployments")
718
1242
  .action(async (cmdOptions) => {
@@ -726,7 +1250,13 @@ function addCloudCommands(program) {
726
1250
  });
727
1251
  workers
728
1252
  .command("list")
729
- .description("List deployed workers for a branch")
1253
+ .summary("List deployed workers for a branch")
1254
+ .description("List the workers currently deployed for the selected branch, including " +
1255
+ "their public URLs.\n\n" +
1256
+ "Before: a profile must be configured and the branch must be provisioned.\n\n" +
1257
+ "```bash\n" +
1258
+ "omnibase cloud workers list --env dev\n" +
1259
+ "```")
730
1260
  .action(async () => {
731
1261
  try {
732
1262
  const globalOptions = program.opts();
@@ -736,13 +1266,156 @@ function addCloudCommands(program) {
736
1266
  await (0, errors_1.handleCommandError)(error);
737
1267
  }
738
1268
  });
1269
+ const domains = cloud
1270
+ .command("domains")
1271
+ .summary("Manage account-level custom domains")
1272
+ .description("Add, validate, and attach custom domains (e.g. `example.com` or " +
1273
+ "`*.example.com`) to workers.\n\n" +
1274
+ "Domains are account-level: add one, point your DNS records at it, " +
1275
+ "wait for activation with `status`, then attach it to a worker with " +
1276
+ "`attach`.");
1277
+ domains
1278
+ .command("add <domain>")
1279
+ .summary("Add a custom domain")
1280
+ .description("Add an account-level custom domain, for example `example.com` or " +
1281
+ "`*.example.com`.\n\n" +
1282
+ "The response includes the CNAME target and, when required, a TXT " +
1283
+ "DCV record. Add these at your DNS provider, then poll with " +
1284
+ "`omnibase cloud domains status <id>` until the domain is active.\n\n" +
1285
+ "Before: a profile and a provisioned branch must be configured.\n\n" +
1286
+ "```bash\n" +
1287
+ "omnibase cloud domains add example.com --env dev\n" +
1288
+ "omnibase cloud domains add '*.example.com' --env dev\n" +
1289
+ "```")
1290
+ .action(async (domain, cmdOptions) => {
1291
+ try {
1292
+ const globalOptions = program.opts();
1293
+ await domainAdd(globalOptions.env, domain);
1294
+ }
1295
+ catch (error) {
1296
+ await (0, errors_1.handleCommandError)(error);
1297
+ }
1298
+ });
1299
+ domains
1300
+ .command("list")
1301
+ .summary("List account-level custom domains")
1302
+ .description("List every account-level domain with its status and SSL status.\n\n" +
1303
+ "```bash\n" +
1304
+ "omnibase cloud domains list --env dev\n" +
1305
+ "```")
1306
+ .action(async () => {
1307
+ try {
1308
+ const globalOptions = program.opts();
1309
+ await domainList(globalOptions.env);
1310
+ }
1311
+ catch (error) {
1312
+ await (0, errors_1.handleCommandError)(error);
1313
+ }
1314
+ });
1315
+ domains
1316
+ .command("rm <domain-id>")
1317
+ .summary("Remove a custom domain")
1318
+ .description("Remove a custom domain by ID and detach it from all workers.\n\n" +
1319
+ "Use `omnibase cloud domains list` to find the domain ID.\n\n" +
1320
+ "```bash\n" +
1321
+ "omnibase cloud domains list --env dev\n" +
1322
+ "omnibase cloud domains rm dom_123 --env dev\n" +
1323
+ "```")
1324
+ .action(async (domainId, cmdOptions) => {
1325
+ try {
1326
+ const globalOptions = program.opts();
1327
+ await domainRemove(globalOptions.env, domainId);
1328
+ }
1329
+ catch (error) {
1330
+ await (0, errors_1.handleCommandError)(error);
1331
+ }
1332
+ });
1333
+ domains
1334
+ .command("status <domain-id>")
1335
+ .summary("Poll domain status until active")
1336
+ .description("Poll the status of a custom domain until it activates or the timeout " +
1337
+ "elapses (default 120s).\n\n" +
1338
+ "While DNS and certificate issuance are pending it prints the records " +
1339
+ "still needed; it exits successfully as soon as the domain is live.\n\n" +
1340
+ "Before: the domain must exist (see `omnibase cloud domains add`).\n\n" +
1341
+ "```bash\n" +
1342
+ "omnibase cloud domains status dom_123 --env dev\n" +
1343
+ "omnibase cloud domains status dom_123 --timeout 300 --env dev\n" +
1344
+ "```")
1345
+ .option("--timeout <seconds>", "Poll timeout in seconds", "120")
1346
+ .action(async (domainId, cmdOptions) => {
1347
+ try {
1348
+ const globalOptions = program.opts();
1349
+ await domainStatus(globalOptions.env, domainId, parseInt(cmdOptions.timeout, 10));
1350
+ }
1351
+ catch (error) {
1352
+ await (0, errors_1.handleCommandError)(error);
1353
+ }
1354
+ });
1355
+ domains
1356
+ .command("attach <domain-id>")
1357
+ .summary("Attach a validated domain to a worker")
1358
+ .description("Attach an activated account-level domain to a worker on the current " +
1359
+ "branch.\n\n" +
1360
+ "`--worker` is required and names the deployment (matching the name in " +
1361
+ "omnibase.toml or `omnibase/workers/`). For wildcard domains use " +
1362
+ "`--hostname` to choose the concrete hostname to route.\n\n" +
1363
+ "Before: the domain must be active (see `omnibase cloud domains status`).\n\n" +
1364
+ "```bash\n" +
1365
+ "omnibase cloud domains attach dom_123 --worker api --env dev\n" +
1366
+ "omnibase cloud domains attach dom_123 --worker api --hostname www.example.com --env dev\n" +
1367
+ "```")
1368
+ .requiredOption("--worker <name>", "Worker deployment name")
1369
+ .option("--hostname <hostname>", "Concrete hostname to route (required for wildcard domains)")
1370
+ .action(async (domainId, cmdOptions) => {
1371
+ try {
1372
+ const globalOptions = program.opts();
1373
+ await domainAttach(globalOptions.env, domainId, cmdOptions.worker, cmdOptions.hostname);
1374
+ }
1375
+ catch (error) {
1376
+ await (0, errors_1.handleCommandError)(error);
1377
+ }
1378
+ });
1379
+ domains
1380
+ .command("detach <domain-id>")
1381
+ .summary("Detach a domain from a worker")
1382
+ .description("Detach a domain from the current branch's worker. The account-level " +
1383
+ "domain itself is kept.\n\n" +
1384
+ "```bash\n" +
1385
+ "omnibase cloud domains detach dom_123 --env dev\n" +
1386
+ "```")
1387
+ .action(async (domainId, cmdOptions) => {
1388
+ try {
1389
+ const globalOptions = program.opts();
1390
+ await domainDetach(globalOptions.env, domainId);
1391
+ }
1392
+ catch (error) {
1393
+ await (0, errors_1.handleCommandError)(error);
1394
+ }
1395
+ });
739
1396
  // Branch subcommand
740
1397
  const branch = cloud
741
1398
  .command("branch")
742
- .description("Manage project branches");
1399
+ .summary("Manage project branches")
1400
+ .description("Provision, list, and deprovision project branches.\n\n" +
1401
+ "Each branch is an isolated environment with its own database, API, " +
1402
+ "permissions, and workers. Use `new` to provision one, then reference " +
1403
+ "it with `--env <branch>` on other cloud commands.");
743
1404
  branch
744
1405
  .command("new")
745
- .description("Create a new project branch")
1406
+ .summary("Create a new project branch")
1407
+ .description("Provision a new branch (environment) for the project.\n\n" +
1408
+ "The project ID comes from `--project-id` or the `project_id` in " +
1409
+ "omnibase.toml, and is prompted for if neither is set. Region and tier " +
1410
+ "default to a picker fed by the managed hosting options endpoint " +
1411
+ "(falling back to `syd` / `shared` prompts). A billing email is " +
1412
+ "required.\n\n" +
1413
+ "After: provisioning starts asynchronously. Once complete, use the " +
1414
+ "branch with `--env <branch>` on other commands.\n\n" +
1415
+ "```bash\n" +
1416
+ "omnibase cloud branch new --name staging\n" +
1417
+ "omnibase cloud branch new --project-id proj_123 --name dev --region syd --tier shared\n" +
1418
+ "```")
746
1419
  .option("--project-id <id>", "Project ID")
747
1420
  .option("--name <name>", "Branch name")
748
1421
  .option("--region <region>", "Region (e.g. syd)")
@@ -756,9 +1429,70 @@ function addCloudCommands(program) {
756
1429
  await (0, errors_1.handleCommandError)(error);
757
1430
  }
758
1431
  });
1432
+ branch
1433
+ .command("ensure <branch>")
1434
+ .summary("Provision a branch if it does not exist and wait for it")
1435
+ .description("Idempotently provision a branch and wait until it is active and its " +
1436
+ "API reports ready.\n\n" +
1437
+ "An existing live branch with the same name is reused, so this is safe " +
1438
+ "to run on every CI job. When no branch exists, `--region`, `--tier`, " +
1439
+ "and `--email` are required.\n\n" +
1440
+ "With `--json`, prints a single JSON object instead of log output. Use " +
1441
+ "`--no-wait` to return as soon as provisioning starts.\n\n" +
1442
+ "```bash\n" +
1443
+ "omnibase cloud branch ensure pr-123 --region syd --tier shared_starter --email ci@example.com\n" +
1444
+ "omnibase cloud branch ensure pr-123 --region syd --tier shared_starter --email ci@example.com --json\n" +
1445
+ "```")
1446
+ .option("--project-id <id>", "Project ID")
1447
+ .option("--region <region>", "Region (e.g. syd)")
1448
+ .option("--tier <tier>", "Deployment tier (e.g. shared_starter)")
1449
+ .option("--email <email>", "Billing email")
1450
+ .option("--no-wait", "Return immediately after provisioning starts")
1451
+ .option("--timeout <seconds>", "Provisioning timeout in seconds", "1800")
1452
+ .option("--health-timeout <seconds>", "Health check timeout in seconds", "600")
1453
+ .option("--json", "Print the resolved branch as JSON")
1454
+ .action(async (branchName, cmdOptions) => {
1455
+ try {
1456
+ await branchEnsure(branchName, cmdOptions);
1457
+ }
1458
+ catch (error) {
1459
+ await (0, errors_1.handleCommandError)(error);
1460
+ }
1461
+ });
1462
+ branch
1463
+ .command("env <branch>")
1464
+ .summary("Export branch URLs and keys as environment variables")
1465
+ .description("Resolve a branch's API URL, PostgREST URL, service key, and dashboard " +
1466
+ "worker URL, then write them as dotenv content.\n\n" +
1467
+ "Use `--output` to write a gitignored `omnibase/.env.<branch>` file " +
1468
+ "before `omnibase sync` or `omnibase cloud workers deploy`.\n\n" +
1469
+ "```bash\n" +
1470
+ "omnibase cloud branch env pr-123 --output omnibase/.env.pr-123\n" +
1471
+ "omnibase cloud branch env pr-123\n" +
1472
+ "```")
1473
+ .option("--project-id <id>", "Project ID")
1474
+ .option("--worker-domain <domain>", "Workers domain", "workers.omnibase.tech")
1475
+ .option("--cookie-domain <domain>", "Cookie domain")
1476
+ .option("--dashboard-url <url>", "Override the dashboard URL")
1477
+ .option("--output <path>", "Write dotenv output to a file")
1478
+ .action(async (branchRef, cmdOptions) => {
1479
+ try {
1480
+ await branchEnv(branchRef, cmdOptions);
1481
+ }
1482
+ catch (error) {
1483
+ await (0, errors_1.handleCommandError)(error);
1484
+ }
1485
+ });
759
1486
  branch
760
1487
  .command("list")
761
- .description("List branches")
1488
+ .summary("List project branches")
1489
+ .description("List all branches for the project with their status and API URL.\n\n" +
1490
+ "Before: a profile must be configured and `project_id` must be set in " +
1491
+ "omnibase.toml (or passed with `--project-id`).\n\n" +
1492
+ "```bash\n" +
1493
+ "omnibase cloud branch list\n" +
1494
+ "omnibase cloud branch list --project-id proj_123\n" +
1495
+ "```")
762
1496
  .option("--project-id <id>", "Project ID")
763
1497
  .action(async (cmdOptions) => {
764
1498
  try {
@@ -770,11 +1504,24 @@ function addCloudCommands(program) {
770
1504
  });
771
1505
  branch
772
1506
  .command("rm <branch>")
773
- .description("Delete a branch by name, slug, or ID")
1507
+ .summary("Delete a project branch")
1508
+ .description("Delete a branch by name, slug, or ID. The branch is resolved against " +
1509
+ "the project's branch list, then deprovisioning is started.\n\n" +
1510
+ "This is destructive — the branch's database, workers, and services are " +
1511
+ "deprovisioned. `--if-exists` makes a missing or already deleted branch " +
1512
+ "a no-op, which is useful in cleanup jobs.\n\n" +
1513
+ "```bash\n" +
1514
+ "omnibase cloud branch rm staging\n" +
1515
+ "omnibase cloud branch rm pr-123 --if-exists\n" +
1516
+ "omnibase cloud branch rm br_123 --project-id proj_123\n" +
1517
+ "```")
774
1518
  .option("--project-id <id>", "Project ID")
1519
+ .option("--if-exists", "Do not fail if the branch is missing or deleted")
775
1520
  .action(async (branchRef, cmdOptions) => {
776
1521
  try {
777
- await branchDelete(branchRef, cmdOptions.projectId);
1522
+ await branchDelete(branchRef, cmdOptions.projectId, {
1523
+ ifExists: cmdOptions.ifExists,
1524
+ });
778
1525
  }
779
1526
  catch (error) {
780
1527
  await (0, errors_1.handleCommandError)(error);
@@ -783,15 +1530,50 @@ function addCloudCommands(program) {
783
1530
  // Environment subcommand
784
1531
  const envCmd = cloud
785
1532
  .command("env")
786
- .description("Manage environment configuration");
1533
+ .summary("Manage environment configuration")
1534
+ .description("Push configuration to a cloud branch and resolve per-environment " +
1535
+ "variables.\n\n" +
1536
+ "**Environment variable injection**\n\n" +
1537
+ "Several commands resolve `{VAR}` references in your configuration " +
1538
+ "(e.g. `website_url = \"{PUBLIC_WEBSITE_URL}\"`) from a two-layer " +
1539
+ "model:\n\n" +
1540
+ "- **omnibase/omnibase.toml** (committed) — the structure, with `{VAR}` " +
1541
+ "references for per-environment values.\n" +
1542
+ "- **omnibase/.env.<branch>** (gitignored) — flat `KEY=VALUE`, one file " +
1543
+ "per branch/environment (`.env.local` for local dev).\n\n" +
1544
+ "Resolution order, per key, first non-empty wins:\n" +
1545
+ "`process.env` → `omnibase/.env.<branch>` (from `--env` or the " +
1546
+ "interactive picker) → the literal `{VAR}` left in place.\n\n" +
1547
+ "This drives `cloud workers deploy` (wrangler build env + packaged " +
1548
+ "`[vars]`), `cloud env push` (interpolation of the cloud config " +
1549
+ "sections), and `omnibase start` (control-plane env + dev-server spawns).\n\n" +
1550
+ "Caveats: unresolved `{VAR}` values are left literal and the CLI warns; " +
1551
+ "secrets belong in the managed-hosting secrets API or `wrangler secret`, " +
1552
+ "never in `[vars]` (vars are visible in the deployed worker).");
787
1553
  envCmd
788
1554
  .command("push")
789
- .description("Push omnibase.toml config to managed hosting")
790
- .option("--from-env <path>", "Env file to resolve {VAR} secrets from (in addition to process.env). Never reads .env.local.")
1555
+ .summary("Push omnibase.toml config to managed hosting")
1556
+ .description("Push the cloud-relevant sections of omnibase.toml to the selected " +
1557
+ "branch, interpolating `{VAR}` references first.\n\n" +
1558
+ "Everything except `[local]`, `project_id`, and `deployments` is sent; " +
1559
+ "managed hosting applies what it understands and reports the rest. " +
1560
+ "`[local]` stays on this machine — that is where Stripe lives, since " +
1561
+ "managed hosting owns Stripe env via the Connect account it provisions " +
1562
+ "per branch. `[versions]` keys are validated before push.\n\n" +
1563
+ "Before: `project_id` must be set in omnibase.toml, a profile must be " +
1564
+ "configured, and the branch must be provisioned. Pushing to `local` is " +
1565
+ "not supported.\n\n" +
1566
+ "After: the branch reports which sections were applied and which were " +
1567
+ "ignored. Unresolved `{VAR}` values are warned about and left literal.\n\n" +
1568
+ "See the env resolution model on the [`cloud env`](/reference/cli/cloud/env) page.\n\n" +
1569
+ "```bash\n" +
1570
+ "omnibase cloud env push --env dev\n" +
1571
+ "omnibase cloud env push --env staging\n" +
1572
+ "```")
791
1573
  .action(async (cmdOptions) => {
792
1574
  try {
793
1575
  const globalOptions = program.opts();
794
- await pushEnvConfig(globalOptions.env, cmdOptions.fromEnv);
1576
+ await pushEnvConfig(globalOptions.env);
795
1577
  }
796
1578
  catch (error) {
797
1579
  await (0, errors_1.handleCommandError)(error);