Skip to content

Developer CLI Workflows ​

The beech CLI provides unified workflows for scaffolding projects, running local emulation, managing database migrations, generating types and forms, and deploying to Cloudflare Workers.


Scope Separation: Consumer vs Contributor ​

Commands are categorized by operational scope:

  • Consumer Projects: Scaffolded via npx @beechcms/cms@latest. Workspaces contain worker.ts, wrangler.jsonc, and .dev.vars. Run via npx beech <cmd> or npm run <script>.
  • Monorepo Contributors: Engineers contributing directly to the core BeechCMS engine (apps/api, apps/dashboard, packages/*). Utilizes Docker Compose, Turborepo, Vitest, and interactive terminal TUI.

Comprehensive Command Matrix ​

Commands marked Monorepo drive this repository's own tooling (Docker stack, Turborepo, test tiers). They run through pnpm beech from a clone of the repository and are not part of the published @beechcms/cli.

CommandScopeDescriptionOptions & Aliases
npx @beechcms/cms@latestConsumerInteractive scaffolding wizard for new edge projects.--yes (non-interactive starter)
npx beech initConsumerVerifies project config (worker.ts, wrangler.jsonc, .dev.vars). Does not touch the database.--remote
npx beech keys:migrate (beech keys migrate)ConsumerMoves a 0.10.x project to publishable and secret keys. Removes the 0.10.x key names and the committed secrets from wrangler.jsonc, writes fresh secrets to .dev.vars, never touches PRIVACY_MASTER_KEY, and prints the production commands. Idempotent.None
npx beech db:migrateConsumerApplies local D1 database migrations.Runs the project's npm run db:migrate:local script
npx beech db:resetConsumerClears local Wrangler state and re-bootstraps fresh database.Runs npm run db:reset:local or purges .wrangler/state
pnpm beech resetMonorepoComprehensive environment reset.--db, --docker, --all, --yes
npx beech types generate (beech types:generate)ConsumerGenerates beech.generated.ts (SeedRegistryTypes + SCHEMA_FINGERPRINT) from live D1.--remote, -o/--output <file>, --db <name> (aliases: beech gen types typescript, beech gen-types, beech gen:types, beech generate:types — these print to stdout by default)
npx beech types check (beech types:check)ConsumerDiffs the committed generated types against live D1 in memory. Writes nothing. Exits 1 when the file is missing or stale.--remote, -o/--output <file>, --db <name>
npx beech schema export (beech schema:export)ConsumerWrites beech.schema.ts — a reviewable snapshot of the live D1 schema.--out <file>, --stdout, --remote, --db <name>
npx beech schema diff (beech schema:diff)ConsumerCompares beech.schema.ts against the deployed schema and reports drift. Exits 1 when drift is detected.--manifest <file>, --remote, --db <name>
npx beech schema audit (beech schema:audit)ConsumerRead-only audit of relation storage: compares each relation branch (multiple, targetSeed, onDelete) with the physical FK column, rel_<slug>_<alias> junction (and drafts junction) and FK policy. Reports stranded value counts, never changes data. Exits 1 on any mismatch.--remote, --db <name>
npx beech schema migrate (beech schema:migrate)ConsumerMoves seeds saved before 0.9 to the closed-vocabulary tags contract: text + options becomes single-choice tags (stored strings wrapped into arrays), string options become { value, color }. Dry run by default (exits 1 while work is pending); --apply writes. Idempotent.--apply, --remote, --db <name>
npx beech schema plan (beech schema:plan)ConsumerShows the DDL and the definition-only changes applying beech.schema.ts would make; unchanged seeds print (no change). Writes nothing. Exits 1 when a seed cannot be applied.--manifest <file>, --api-url <url>
npx beech schema apply (beech schema:apply)ConsumerApplies beech.schema.ts through the control plane (mcp-plan / mcp-apply). Additive only. Skips seeds whose definition already matches.--manifest <file>, --api-url <url>, -y/--yes
npx beech run <name|path> (beech run)ConsumerRuns .beech/scripts/<name>.ts through the typed beech SDK as the signed-in user and prints a RunReport. Exits 1 when the script fails; pending intents alone exit 0.--arg <k=v> (repeatable), --dry-run, --json, --out <file>, --api-url <url>
npx beech agent setup (beech agent:setup)ConsumerWrites the beechcms entry in .mcp.json, the agent skill, .beech/scripts/README.md, an example script, and adds @beechcms/cli to devDependencies. Idempotent; never overwrites a differing file without --force.--force, --api-url <url>
npx beech formsConsumerInteractive wizard generating React, Vue, Svelte, or Web Component forms.--seed <slug>, --framework <name>, --mode <create|edit>, --out <path>, --yes, --json (aliases: form, forms:add)
npx beech setup:cloudflareConsumer1-step Cloudflare edge provisioning (D1, R2, S3 secrets).--name <name>, --yes (alias: setup:cf)
npx beech deployConsumerDeploys Worker and embedded admin dashboard to Cloudflare.--skip-check, --skip-seed
npx beech updateConsumerUpgrades core engine packages and applies system migrations.None
pnpm beech doctorMonorepoRuns health checks and React diagnostics on the Dashboard.None
pnpm beech devMonorepoStarts local contributor environment (Docker + API + Dashboard).--plain (headless non-TUI), alias start
pnpm beech dev:stopMonorepoGracefully stops local monorepo Docker containers.None
pnpm beech dev:resetMonorepoStops local Docker containers and purges volumes (docker compose down -v).None
pnpm beech dev:tunnelMonorepoDisplays active Cloudflare quick tunnel public URL from container logs.None
pnpm beech mailpit:clearMonorepoClears local Mailpit development inbox.None
pnpm beech logs <service>MonorepoStreams logs from Docker services.Services: mailpit, sqlite (db), tunnel, minio (storage)
npx beech schema diff (beech schema:diff)ConsumerReports manifest-vs-deployed drift and definition-vs-physical-table drift. Exits 1 on drift.--manifest <file>, --remote, --db <name>
pnpm beech testMonorepoExecutes Turborepo test runner.--coverage, --diff, --tier <unit|flow|integration|e2e>
pnpm beech lintMonorepoExecutes project linter checks via Turborepo.None

Core Developer Workflows ​

1. Scaffolding & Initialization ​

Scaffold an edge project interactively or with non-interactive flags:

bash
# Interactive wizard
npx @beechcms/cms@latest my-app

# Non-interactive quickstart
npx @beechcms/cms@latest my-app --yes
cd my-app
npm install

Verify your project setup:

bash
npx beech init

Moving a 0.10.x project to publishable and secret keys ​

bash
npx beech keys:migrate

Run it from the project root. It removes PUBLIC_READ_API_KEY, PUBLIC_WRITE_API_KEY, JWT_SECRET and PUBLIC_TIME_TRAP_SECRET from the vars of wrangler.jsonc and adds BEECH_PUBLISHABLE_KEY there. JWT_SECRET, BEECH_SECRET_KEY and PUBLIC_TIME_TRAP_SECRET go to .dev.vars; PRIVACY_MASTER_KEY is never touched.

  • The committed secrets get fresh values, because the old ones are in the git history. Sessions signed with the old JWT_SECRET end, so everyone signs in again.
  • It prints the production steps and runs none of them. Run npm run deploy first, then npx wrangler secret put for the three names: Cloudflare refuses a secret whose name is still a plain-text var.
  • It stops without writing when wrangler.jsonc or .dev.vars is missing or vars cannot be edited safely, and it refuses legacy names inside env.<name>.vars. A second run changes nothing.

2. Database Migrations ​

Apply migrations after pulling updates or creating seeds:

bash
# Apply local D1 migrations
npx beech db:migrate

# Reset database to clean state
npx beech db:reset

3. TypeScript Type Generation ​

BeechCMS generates typed TypeScript interfaces directly from your live Seed schemas stored in D1. npx beech types generate writes beech.generated.ts, containing SeedRegistryTypes and a SCHEMA_FINGERPRINT constant. Pass it to @beechcms/client as schemaFingerprint: the client compares it against the API's X-Schema-Revision response header and returns a 409 schema_drift problem on a stale build:

bash
# Generate types + fingerprint for all seeds to beech.generated.ts
npx beech types generate

# Generate types from remote production database, to a custom path
npx beech types generate --remote -o src/types/beech.ts

The historical aliases (gen-types, gen:types, generate:types, gen types typescript) still work and keep printing to stdout by default, so no existing script changes behaviour.

npx beech types check closes the CI gap: it regenerates types from live D1 in memory and diffs them against the committed file, without writing anything on a clean run. It replaces the older types generate + git diff --exit-code two-step, and exits 1 the same way schema diff does so both can gate a pipeline:

bash
# Fail if beech.generated.ts is missing or out of sync with live D1
npx beech types check

npx beech types check --remote -o src/types/beech.ts

Auditing stranded relation data ​

Releases before the additive relation gate (relation-change-not-supported) could save a changed multiple, targetSeed or onDelete without migrating the physical storage. The API then reads the new shape while the values still sit in the old one. schema audit identifies those databases:

bash
npx beech schema audit            # local D1
npx beech schema audit --remote   # production D1

Each finding names the seed, the branch and one of: wrong_storage (data in the other shape: FK column vs rel_<slug>_<alias> junction, including the _drafts junction), missing_storage, fk_target_mismatch, fk_on_delete_mismatch. strandedRows counts values in storage the definition no longer reads. These are invisible to the API but still present: do not drop that column or junction. The command is read-only, never deletes anything, and exits 1 on any finding.

Stale-data window: until a repair is applied, affected relations return empty or partial values for entries written before the edit. A reviewed repair workflow is tracked in issue #664.

Migrating pre-0.9 tag and choice fields ​

Before 0.9 a choice field was text + options, or tags + options: string[]. Since 0.9 options exists only on tags, as { value, color }[], and every stored value is a JSON array. A database still holding the old shapes does not stop the API: the affected seed is disabled (its routes answer 404), every other seed keeps serving, and the Worker log carries one warning per seed:

[BeechCMS] Seed "tickets" is disabled until its definition is fixed: ... Run "beech schema migrate" ...

schema audit lists those seeds, and schema migrate repairs them:

bash
npx beech schema migrate              # dry run: prints the plan, writes nothing, exits 1 while work is pending
npx beech schema migrate --apply      # local D1
npx beech schema migrate --apply --remote   # production D1

What --apply does, in order: wraps stored strings into arrays (live table, and the drafts table when drafts are on), rewrites the seed definitions, then bumps the registry version so running Workers rebuild their cached registry. Colors for options that never had one come from a fixed palette, in declaration order. The statements are idempotent, so re-running after an interruption finishes the job.

What it deliberately does not do:

  • Stored values that are not in the new vocabulary are reported and left in place; add the option or fix the rows.
  • A seed with a branch it cannot convert safely (options on a non-text/tags type, a localized branch, a repeater sub-field) is not rewritten at all and is listed as a manual step: edit the seed, then re-run.

After migrating, regenerate client types (npx beech types generate): X-Schema-Revision is v2:.

4. Interactive Form Generation ​

Generate ready-to-use frontend forms mapped to your content models:

bash
npx beech forms --seed posts --framework react --out src/components/PostForm.tsx

5. Cloudflare Provisioning & Deployment ​

bash
# 1. Provision D1, R2, and master secrets
npx beech setup:cloudflare

# 2. Deploy Worker and embedded dashboard
npx beech deploy

6. Schema Evolution & GitOps Migrations ​

NOTE

The manifest loop is closed. export → review in Git → diff → plan → apply → types generate. The CLI never executes SQL and never opens D1 directly; every write goes through POST /api/seeds/:slug/mcp-*. Authoring reference for the manifest file itself (defineSchema, defineSeed, defineField, defineGroup): Schema Manifest. The first plan or apply opens the browser once to authorize the beech-mcp-cli OAuth client. The grant is cached in ~/.beechcms/mcp-tokens.json and revocable from Settings → Connected apps. apply never deletes a seed absent from the manifest and never performs a drop, rename, or retype — the server refuses destructive intent and names the endpoint that can perform it.

The versioned SQL files in apps/api/migrations/ cover the system schema (seeds, users, sessions, api_keys, media, OAuth clients), not per-Seed content tables. Apply them with Wrangler.

Automated GitOps in GitHub Actions ​

Apply versioned D1 system migrations in CI/CD before deploying the Worker:

yaml
name: Deploy (D1 migrations + Worker)
on:
  push:
    branches: [main]
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v4
      - uses: actions/setup-node@v4
        with: { node-version: 22, cache: pnpm }
      - run: pnpm install --frozen-lockfile
      # Apply versioned migrations BEFORE deploying the Worker
      - name: Apply D1 migrations
        run: pnpm --filter @beechcms/api exec wrangler d1 migrations apply beech-db --remote
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
      - name: Deploy Worker
        run: pnpm --filter @beechcms/api exec wrangler deploy
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}

7. Agent Scripts ​

An agent (or you) writes a TypeScript script against the typed beech SDK; beech run executes it with your own permissions and prints one report. Requires Node ≥ 22.18 (native type stripping).

  1. npx beech agent setup: creates .beech/scripts/, the agent skill and the .mcp.json entry, and adds @beechcms/cli to devDependencies (install afterwards).
  2. Write .beech/scripts/<name>.ts with defineScript from @beechcms/cli/sdk.
  3. npx beech run <name> --dry-run --json: records every write in calls and sends none.
  4. npx beech run <name> --arg key=value --json: runs it for real.

--json prints exactly one document on stdout; console.log inside a script goes to logs.

For the full agent workflow (setup, consent, approvals), see Working with an Agent Locally.

RunReport ​

FieldMeaning
versionReport format version (1).
scriptScript path relative to the working directory.
statusok or error.
dryRunTrue under --dry-run.
apiUrlAPI the script ran against.
durationMsRun time.
resultThe script's JSON return value; null on error.
error{ code, message, status, operationId } or null. Codes: SDK/API codes, script_load_failed, sdk_unresolved, invalid_script, script_error, result_not_serializable.
logsLines from context.log and console.log (first 500).
callsEvery SDK call in order, with outcome executed, pending, dry-run or error.
pendingIntentsActions that did not run and wait for approval: ask the agent to call beech_confirm, or use Dashboard → Settings → Connected apps → Pending agent actions.

Exit codes: 0 for ok, including pending intents; 1 for error or a usage error. A script can never approve an intent: the CLI OAuth client lacks agent:approve and the SDK has no approve method.

Writes that need ifMatch ​

beech.layout.update(body, { ifMatch }) and beech.layout.reset({ ifMatch }) change the Dashboard Composer layout, which the API only writes against the version the caller read. ifMatch is the updatedAt returned by beech.layout.get(), or null for a first save (nothing stored yet, sent as If-None-Match: *). The SDK refuses a call without it before any request is sent (layout.update needs { ifMatch }); a raw HTTP call without a precondition header is answered 428.

ts
import { defineScript } from '@beechcms/cli/sdk'

interface StoredLayout { layout: { version: number; pages: unknown[] } | null; updatedAt: number | null }

// Read the layout, then write it back under the version just read. Put your edit in place of `pages`.
// Run: pnpm beech run layout-roundtrip --dry-run --json
export default defineScript(async (beech) => {
  const { layout, updatedAt } = (await beech.layout.get()) as StoredLayout
  if (layout === null) throw new Error('nothing stored yet: a first save uses { ifMatch: null }')

  const outcome = await beech.layout.update({ ...layout, pages: layout.pages }, { ifMatch: updatedAt })
  return outcome.kind
})

If another writer saved in between, the call fails with BeechSdkError status 409 and code layout-conflict: run get() again and re-apply the edit. A first save, and any change to the tab structure, needs manage_roles at *; see Dashboard Layout API.


Monorepo Contributor Infrastructure ​

For developers working directly on the BeechCMS monorepo, pnpm beech dev orchestrates local Docker services:

Docker Infrastructure Services ​

ServiceContainerPortsPurpose
MinIObeech-minio9000 (S3 API), 9001 (Console)Local Cloudflare R2 emulation with presigned URL support.
Mailpitbeech-mailpit1025 (SMTP), 8025 (Web UI/API)Zero-config local email delivery and verification.
SQLite Webbeech-sqlite-web8080 (Web UI)Visual database browser for local D1 SQLite state.
Webhook Testerbeech-webhook-tester8084 (HTTP API)Local endpoint for testing notification webhooks.
Cloudflare Tunnelbeech-tunnelPublic URL (*.trycloudflare.com)Public HTTPS URL forwarding to local Worker for webhooks.

Interactive TUI Dashboard ​

When executing pnpm beech dev, an interactive Ink terminal interface is launched:

  • Press 1: Status overview of all background services.
  • Press 2: API Logs from the Hono Worker.
  • Press 3: Dashboard Logs from the Vite React app.
  • Press 4: Core Logs from the @beechcms/core watch build.
  • Press 5: System Logs from the Docker infrastructure services.
  • Press 6: Endpoints quick reference list with local URLs.
  • Press 7: Versions of all monorepo packages.
  • Press Tab / Shift+Tab (or ← / →): Cycle between tabs.
  • Press r: Restart the API and Dashboard dev servers.
  • Press d / x: Expand or dismiss the currently selected error in the error bar.
  • Press q (or Ctrl+C): Gracefully terminate all services.
  • Flag --plain: Launches services without TUI formatting for CI/CD environments.