Skip to content
Workbench
Esc
↑↓navigate↵open⌘Jpreview
On this page

Local to production

Develop against your personal database, verify a hosted PR preview, then release through main.

Standard workflow

  1. Create a feature branch or worktree and run bun run dev. The frontend and API run locally against your linked personal database branch.
  2. Test the change locally. Generate and commit migrations for schema changes; explicitly provision the personal stage to apply them before testing. Local startup does not deploy resources or apply migrations; hosted PR deployment applies migrations to its isolated branch.
  3. Submit a PR. After CI passes, eligible changes get a PR Preview frontend and API in pr-<number>, with an isolated PlanetScale branch, runtime role, and Hyperdrive connection. Alchemy applies committed migrations before the API becomes available. See preview eligibility for skipped changes.
  4. Open the frontend URL from the GitHub deployment or workflow summary. Hosted checks verify HTML delivery and same-origin /api requests: database readiness, JSON POST bodies, and upstream error/status headers. They also check that the direct API reference and schemas work while frontend documentation requests return 404. Add feature-specific tests alongside the feature.
  5. Fix valid review findings and wait for the required checks before merging. Follow the review and merge requirements. Production reruns CI, then Alchemy applies committed migrations and deploys the application against the production database. Development records are not copied.
  6. Closing or merging the PR runs PR Preview Cleanup, deleting its Workers, Hyperdrive connection, database role, database branch, and shared evidence bucket, including preview records and files. Personal branches, personal evidence buckets, and production remain.

For database changes, follow the Drizzle query guidance.

Example: add an API-backed button

  1. Implement the endpoint and button in one feature branch or worktree. Run bun run dev: your browser calls the local frontend’s /api/... path, which forwards to the local API using your personal database branch. Test the behavior here first.
  2. Commit and submit with bun run pr; use bun run pr --open when ready for review. For PR #123, passing CI creates hosted frontend/API Workers and an isolated database branch in stage pr-123. Open the frontend link in the workflow summary to test the deployed feature. See database isolation for branch naming and rebuild behavior.
  3. Address valid CodeRabbit feedback and rerun the relevant checks. Merge once the merge requirements are satisfied. A PR submission alone does not release the feature to production.
  4. The merge starts two independent workflows: Production checks and deploys the merged code to the production website using the production database; PR Preview Cleanup removes PR #123’s environment and test records. Cleanup does not wait for production deployment.
  5. Confirm both workflows succeeded. On the production website, verify the button, its /api/... request, and database readiness. A successful preview validates the PR environment; production still needs its own post-deployment verification.

Each eligible PR gets its own preview database branch. Features that need sample records beyond the development organization must supply reproducible, non-sensitive fixtures. The database policy does not depend on which files changed.

Database isolation

Local development uses your linked personal branch. Each PR uses a separate PlanetScale branch owned by its pr-<number> Alchemy stage. Alchemy generates the physical branch name with an instance suffix; the stage and frontend/API URLs remain stable. PR previews never use a developer’s personal branch or production runtime credentials. Two PRs from the same person remain isolated.

A new PlanetScale Postgres branch starts empty. When provisioning a PR preview or personal dev-* stage, Alchemy applies the committed migrations and creates Wurthy Demo Advisory with two groups, Bookkeeping Department and Controller Services Department. Each department has a member_of relationship to the firm. Local worktrees use the organization and departments on their linked personal branch. To add them to an existing personal stage, run bun run workbench provision --stage dev-you with your stage name. Production applies migrations to its own database after merge. Preview records stay on their preview branch.

In Wurthy Demo Advisory, members can open a firm-owned Finance space for each of Garrett Co, Estes Media, and Harbor Lane Bakery. Bookkeeping also has its own Finance space for Garrett Co, and Controller Services has its own for Estes Media. Provisioning uses the same Finance preset as the space picker. It reuses existing Finance spaces and upgrades the old seeded Client workspace in place when Finance is missing.

In preview and development, once the development organization is provisioned, signing in with a verified @wurthy.co address grants platform_admin in that environment, provider_admin in Wurthy Demo Advisory, and provider_operator in each active department. Select the organization under Organization access after sign-in. Each eligible sign-in restores missing memberships and roles while preserving other roles. Before provisioning, users can sign in with their existing access.

Normal pushes and new forward migrations reuse the existing branch. Editing or deleting an already-applied migration makes Alchemy replace a non-production branch and apply migrations from scratch, discarding preview records. The replacement receives a new generated name so it can coexist with the old branch during replacement; keep the logical resource ID DatabaseBranch stable and do not force the physical name to the PR stage. Runtime credentials and Hyperdrive follow the replacement through Alchemy’s resource references. Cleanup uses stage state rather than guessing a branch name.

Use the state inspection command to find the recorded physical branch name.

Prefer new forward migrations. Alchemy rejects rewritten migration history on production; preview records are never promoted. See Alchemy’s migration lifecycle and the reference example.

PlanetScale branches incur compute and storage charges while they exist. Closing unused PRs triggers cleanup. For failed cleanup, retry promptly as described below.

One browser origin per app

Workbench and the separate internal admin app each use their own origin and session cookie. Use relative /api/... URLs in browser code for local, preview, and production. Locally, Vite forwards /api to the local API. Hosted, each frontend’s TanStack server route forwards /api through its BACKEND service binding to the matching API Worker. Both proxies preserve /api/auth for authentication and strip /api from other API paths. They preserve the request method, query, headers, and body.

No browser-facing API hostname or CORS origin setting is needed. Custom frontend domains are optional; the same path works on workers.dev. The API remains a separate Effect service with its existing contracts. Preview frontends require Cloudflare Access Google sign-in; direct API documentation is also protected. Use only non-sensitive fixtures. See authentication for protected endpoints.

CI configuration

CI runs Checks, React Doctor, Knip, Tests, and Build once per PR update. All five must succeed before CI calls PR Preview; failed or canceled verification blocks deployment. Both verification and preview check out the event’s exact PR merge commit (github.sha). Preview rejects a closed PR, changed head, or changed merge commit before planning and again before deployment. Merge-queue checks and independent Production verification remain enabled.

Previews refresh when the PR branch changes. An unrelated push to main retains the last-deployed preview; it does not fan out verification or deployments to open PRs. Before merging, update or rebase the PR branch onto current main and wait for fresh required checks and a successful preview. A base change during deployment can invalidate the verified merge commit and fail its freshness check. Rerunning an old workflow preserves its original SHA, so update the branch to verify the new integration revision.

The workflow summary identifies the event’s verified merge SHA and PR head SHA. It reports that merge SHA as deployed only after deployment succeeds. These identify the run’s snapshot, not a continuously rebased preview.

Revisions verify independently so late-starting older jobs cannot cancel newer verification. Preview deployment and cleanup share a per-PR lock without automatic cancellation, so new CI runs do not interrupt Alchemy reconciliation. Preview deployments retain up to 100 pending requests rather than replacing the previous queued request.

Worker measurements

The Build check compiles the API Worker locally, attributes its final JavaScript bytes to packages, and writes the largest dependencies and budget headroom to the job summary. PR builds compare the checked-out base revision with the verified merge revision using the current analysis build settings. Known compiler packages in emitted code fail the build even below the size budget.

Build also captures a startup CPU profile through pinned cf and the project’s pinned workerd binary. This runs without Cloudflare credentials or deployment. Download the worker-analysis artifact for source attribution, the summary and the CPU profile. Local sampled CPU is diagnostic; it is not Cloudflare’s startup_time_ms or a production latency prediction.

Hosted preview smoke checks separately report the first successful observed readiness-request duration and a following request, excluding retry waits. Both include network, Access and database costs. Neither is guaranteed to hit a cold or warm isolate, so these timings do not isolate startup CPU. See Worker analysis commands.

Preview eligibility

The classifier compares the cumulative PR diff from the base/head merge base. Documentation, skills, CLI code, known CI tooling, Oxlint rules under scripts/oxlint/, and Nx project metadata skip hosted deployment when they are the only changes. The exact path allowlist lives in scripts/preview-changes-policy.ts; it includes CI/Linear verification workflows, CI and preview-classification scripts, nx.json, and workspace project.json files. Required CI checks still run; the workflow summary reports the skip reason.

Root package.json changes also skip deployment when only known verification, documentation, or PR scripts change, including ci:*, docs:*, and pr:*. The classifier compares manifest contents at the merge base and PR head. Dependency, workspace, install-hook, build-script, and unrecognized manifest changes remain eligible; adding, deleting, or failing to read a manifest also deploys.

Root vite.config.ts changes skip deployment when only its data-only lint object changes and every other change is known tooling. The classifier parses the source without executing it and compares the remaining syntax against the merge base. This supports the current defineConfig({ ... }) form imported from vite-plus. Existing preset reads, their logical guards, and spreads must stay identical in order and count; new or changed reads can invoke getters and still deploy. Changed imports, helper definitions, build settings, plugins, executable lint expressions, and unsupported config forms also deploy. Added, deleted, invalid, or unreadable config files also deploy.

Runtime code, shared packages, dependencies and lockfiles, migrations, build/deployment configuration, and all unknown paths remain eligible. Missing Git history or an uncertain diff also deploys. A docs-only follow-up commit cannot hide earlier application changes. Renames inspect both source and destination paths.

If app changes are later reverted and the PR becomes ineligible, its existing preview remains until close/merge cleanup. Cleanup runs independently of classification, including for resources provisioned before this policy.

Credentials and execution

The GitHub environment preview holds shared automation credentials, not individual developers’ login sessions:

Setting Source
PROTON_PASS_PERSONAL_ACCESS_TOKEN GitHub environment bootstrap secret; viewer access only to the environment’s dedicated Proton vault
CLOUDFLARE_API_TOKEN Proton; account-scoped Workers, Hyperdrive, and Alchemy state administration
PLANETSCALE_API_TOKEN_ID, PLANETSCALE_API_TOKEN Proton; service token scoped to workbench development-branch and role management
Account/database routing Proton references committed in .env.preview, loaded and validated by the Effect environment command

Production uses a separate reader and .env.production; the two readers cannot read each other’s environment item. See deployment credential ownership.

PlanetScale credentials are required for both deployment and cleanup. Grant read_database, create_branch, read_branch, delete_branch, connect_branch, and delete_branch_password on workbench; production connection/write/delete permissions are not needed. The production database declaration is referenced from prod; the PR owns only its new branch and credentials. Fork PRs are excluded from automatic deployments. Eligible same-repository PRs, including drafts and stacked layers, deploy after checks pass. Deployment and cleanup serialize per PR; stale revisions are rejected before deployment.

Retry or inspect

With an authorized Proton session and these non-secret routing settings:

export PREVIEW_WORKERS_SUBDOMAIN=wurthy-workbench
bun scripts/preview.ts metadata 123
bun scripts/preview.ts plan 123
bun scripts/preview.ts smoke 123

Rerun failed deployment jobs in GitHub after fixing their cause.

Cleanup retries

PR Preview Cleanup runs daily at 07:23 UTC and after a same-repository PR closes. To retry sooner, run it manually from the default branch: provide a closed PR number, or leave the input empty to sweep all remaining previews.

The sweep inventories workbench/pr-<number> stages in Alchemy state, including partially removed previews. It runs at most two teardowns at once, continues after individual failures, and retries remaining state on later sweeps. Each teardown acquires the deployment lock and rechecks GitHub: only CLOSED or MERGED permits removal. Open or reopened PRs, unknown states, and API failures are skipped and reported in workflow summaries.

Cleanup uses trusted default-branch code and native Alchemy destroy. It permanently removes that PR’s Workers, Hyperdrive connection, database role, branch, and records, while preserving production and personal environments. Check failed jobs and their summaries; repair credentials or provider errors before retrying.

This follows Alchemy’s preview-branch guide with the APIs supported by our pinned version.

Automation scripts

Use Effect for orchestration with subprocesses, HTTP calls, timeouts, and retries. Keep path and stage policy as plain functions. Use native effect/cli commands, scoped effect/process children, and BunRuntime.runMain with BunServices.layer; follow scripts/preview.ts and its tests. Match the pinned Effect version: these platform APIs are unstable.

Bound readiness retries; propagate deployment failures without retrying mutations. Keep GitHub triggers, permissions, concurrency, and scheduled jobs in workflow YAML. Effect schedules run only while the script is running.

Was this page helpful?