Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Setup git worktrees as the preferred way of agentic development of th… (#14390)

Damian Legawiec01d21c351394
diff --git a/.config/wt.toml b/.config/wt.toml
new file mode 100644
index 0000000000..a29a0ae45c
--- /dev/null
+++ b/.config/wt.toml
@@ -0,0 +1,14 @@
+# worktrunk project config — see CLAUDE.md "Worktrees" and scripts/worktree/.
+# pre-start blocks worktree creation until the environment (server/, database,
+# deps) exists, so `wt switch -c foo -x claude` lands agents in a working tree.
+# Both hooks are declared as top-level keys: a bare key after a [table] header
+# would belong to that table, turning teardown into a second create hook.
+#
+# The `! test -x` form skips (exit 0) only when the script is absent — which is
+# how worktrees branched from a base predating these scripts stay usable — while
+# a script that runs and fails still fails the hook, so nobody lands in a
+# half-provisioned worktree.
+
+pre-start = "! test -x scripts/worktree/setup.sh && echo 'scripts/worktree/setup.sh not on this branch — provision manually' || scripts/worktree/setup.sh '{{ branch }}'"
+
+post-remove = "! test -x scripts/worktree/teardown.sh && echo 'scripts/worktree/teardown.sh not on this branch — drop databases manually' || scripts/worktree/teardown.sh '{{ branch }}'"
diff --git a/CLAUDE.md b/CLAUDE.md
index d4586c717f..f380a7eadd 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -88,26 +88,39 @@ Shipped plans:
| `packages/sdk-core` | `@spree/sdk-core` — shared HTTP/retry/error layer (private internal) |
| `packages/cli` | `@spree/cli` — Docker-based project management CLI |
| `packages/create-spree-app` | `create-spree-app` — project scaffolding |
-| `server/` | Rails app cloned from `spree/spree-starter` (.gitignored, run `pnpm server:setup`) |
+| `server/` | Rails app cloned from `spree/spree-starter` (.gitignored, provisioned per worktree by `scripts/worktree/setup.sh`) |
-## Development Server (`server/`)
+## Development Server (worktrees)
-One-time bootstrap (Docker required, no host Ruby): `pnpm install && pnpm server:setup`. It clones spree-starter into `server/`, boots the edge stack (monorepo gems bind-mounted via a compose overlay), and prepares + seeds the DB. Idempotent — but re-running it is a **full reset** that wipes the DB and volumes.
+Development happens in **git worktrees** — every worktree is a self-contained native dev environment, no Docker: its own gitignored `server/` clone of spree-starter (monorepo gems loaded as path gems via `SPREE_PATH`), its own database on the shared Homebrew Postgres (:5432, copied in ~2 s from the seeded `spree_worktree_template`), and stable per-branch https URLs via [portless](https://github.com/vercel-labs/portless). Worktrees are managed with [worktrunk](https://worktrunk.dev) (`wt`): creating one runs `scripts/worktree/setup.sh` automatically (see `.config/wt.toml`), removing one drops its databases. The main checkout is for integration (merges, template rebuilds), not for running servers.
-Day-to-day from the repo root: `pnpm server:dev` (foreground — streams web logs; jobs run in-process via Solid Queue; Ctrl+C stops it, postgres stays warm) / `server:stop` (full teardown) / `server:restart` / `server:logs` / `server:console` / `server:seed` / `server:load_sample_data`. CLI commands run from `server/`: `pnpm exec spree <cmd>` (`spree migrate`, `spree console`, `spree generate model …`). `spree dev` and `spree build` refuse to run in `server/` (SPREE_PATH guard) — use the `pnpm server:*` scripts instead.
+```bash
+wt switch -c feature-x # create worktree + provisioned environment (~20 s)
+pnpm wt:dev # Rails → https://feature-x.spree.localhost (/up, /api/v3, /jobs; jobs run inside Puma via Solid Queue)
+pnpm wt:dashboard # admin UI → https://admin.feature-x.spree.localhost
+pnpm wt:e2e [spec...] # Playwright on this worktree's own port block
+pnpm wt:template # rebuild the template DB after schema-changing pulls
+wt merge main # ship + clean up (worktree, branch and databases all removed)
+wt remove # abandon instead of shipping
+```
-| What changed | What to run |
-|---|---|
-| Ruby code in `spree/*` gems | Nothing — bind-mounted, reloads on next request |
-| Hosted React Dashboard at `/dashboard` (single-node test) | `pnpm server:dashboard` — rebuilds `packages/dashboard-starter/dist` with `VITE_BASE_PATH=/dashboard/`; served immediately through the monorepo mount (no restart). For dashboard *development* keep using Vite on :5173 (`cd packages/dashboard && pnpm dev`). |
-| New migration in a gem | Nothing — the next `pnpm server:dev` boot runs `spree:install:migrations db:prepare` (or `cd server && pnpm exec spree migrate` while running) |
-| Gem dependencies (gemspec / Gemfile / starter `Gemfile.lock` drift after a pull) | Nothing — the next `pnpm server:dev` boot self-heals (`bundle check || bundle install` into the `bundle_cache` volume); while running: `cd server && pnpm exec spree bundle install` |
-| Compose files / `server/.env` | `pnpm server:dev` (force-recreates web + worker) |
-| `server/Dockerfile` / `.ruby-version` / starter update that breaks the image build (frozen-lockfile error) | `pnpm server:build`, then `pnpm server:dev` — the build script swaps the edge PATH lock for a RubyGems-resolved one and the next boot swaps it back |
-| Working on the Meilisearch search provider | Off by default (DB provider) — `SPREE_MEILISEARCH=1 pnpm server:dev` chains `scripts/docker-compose.meilisearch.yml` (service + `MEILISEARCH_URL`), then `cd server && pnpm exec spree rake spree:search:reindex` once. Booting without the flag reverts web to DB search and removes the meilisearch container; the index volume stays. Image bump ("database version … is incompatible"): `pnpm server:stop && docker volume rm server_meilisearch_data`, flagged boot, reindex |
-| Broken beyond repair | `pnpm server:setup` (full reset — wipes DB + volumes) |
+Admin login: `[email protected]` / `spree123`. Both dev scripts run in the foreground and stream logs; `server/log/development.log` has the Rails log if the server runs detached. Start servers only in worktrees you're actively looking at — rspec/vitest/tsc need no servers.
-Backend: http://localhost:3000, admin at `/admin`, hosted React Dashboard at `/dashboard` (`[email protected]` / `spree123`). Native no-Docker path: `pnpm server:create`, then `cd server && bin/setup && bin/dev`.
+One-time machine setup: Homebrew `postgresql@18` running on :5432 (with a `postgres` superuser role), Ruby per `server/.ruby-version` (mise or rbenv), Node ≥ 24 with `npm i -g portless` (start the proxy once with `portless proxy start`, accepting sudo for :443), worktrunk, then `pnpm wt:template`.
+
+| What changed | What to run (inside the worktree) |
+|---|---|
+| Ruby code in `spree/*` gems | Nothing — path gems, reloads on next request |
+| New migration in a gem | `cd server && bin/rails spree:install:migrations db:migrate`; then `pnpm wt:template` once so future worktrees inherit it |
+| Gem dependencies | `cd server && bundle install` (the gem home is shared across worktrees, so this is fast) |
+| Need sample data (products + images) | `cd server && bin/rails spree:load_sample_data` — per worktree, on demand; takes minutes and hits the network |
+| Rails console / database | `cd server && bin/rails console`; the DB is `spree_dev_<branch>` on `localhost:5432` |
+| E2E prerequisites | Once per worktree: `cd spree/api && bundle install && bundle exec rake test_app` (then `pnpm wt:e2e`) |
+| Meilisearch search provider | Optional: `brew install meilisearch`, run it, set `MEILISEARCH_URL` in `server/.env`, `bin/rails spree:search:reindex` |
+| Hosted dashboard at `/dashboard` (single-node test) | `pnpm server:dashboard` to build `packages/dashboard-starter/dist`, set `SPREE_DASHBOARD_DIST_PATH=<monorepo>/packages/dashboard-starter/dist` in `server/.env` |
+| Broken beyond repair | `wt remove` and recreate — or `dropdb spree_dev_<branch>`, delete `server/`, re-run `pnpm wt:setup` |
+
+**The legacy Docker compose flow (`pnpm server:setup` / `server:dev` / `server:stop` etc.) is deprecated — never use it.** It exists only for spree-starter parity; it fights the worktree stack for ports and its teardown scripts wipe shared state.
---
@@ -494,20 +507,19 @@ The Spree 6.0 admin dashboard — a Vite-built React SPA that replaces the legac
The split lets plugin authors register UI via `defineDashboardPlugin` from `@spree/dashboard-core/plugin`, build new pages with `@spree/dashboard-ui` primitives, and reuse the same providers/hooks. It also lets app developers compose custom dashboards (e.g. vendor panels) from the same packages.
-**Running the admin UI locally:**
+**Running the admin UI locally** (from a worktree — see "Development Server" above):
```bash
-# 1. Boot a Spree backend (one terminal, from monorepo root)
-pnpm server:setup # one-time bootstrap (see "Development Server" above)
-pnpm server:dev # foreground; streams logs — Rails on http://localhost:3000
+# 1. Boot this worktree's Spree backend (one terminal)
+pnpm wt:dev # foreground; streams logs — https://<branch>.spree.localhost
-# 2. Boot the admin (separate terminal, from monorepo root)
-pnpm turbo dev --filter=@spree/dashboard-starter # http://localhost:5173 (proxies /api/* to :3000)
+# 2. Boot the admin (separate terminal)
+pnpm wt:dashboard # https://admin.<branch>.spree.localhost (proxies /api/* to this worktree's Rails)
```
-The starter is the canonical host — the same app `spree add dashboard` scaffolds — so local dev exercises the real consumer path (shell + plugin pipeline) while still hot-reloading `@spree/dashboard`/`-core`/`-ui` source through the workspace. `turbo dev` (not a bare `pnpm dev` inside the package) matters on a fresh clone: the starter's `vite.config.ts` resolves the compiled Node-side Vite entries (`@spree/dashboard/vite`, `@spree/dashboard-core/vite`) from `dist/`, and turbo's `^build` dependency produces them. After any full `pnpm build`, `cd packages/dashboard-starter && pnpm dev` works too.
+The starter is the canonical host — the same app `spree add dashboard` scaffolds — so local dev exercises the real consumer path (shell + plugin pipeline) while still hot-reloading `@spree/dashboard`/`-core`/`-ui` source through the workspace. Building the workspace deps first matters on a fresh worktree: the starter's `vite.config.ts` resolves the compiled Node-side Vite entries (`@spree/dashboard/vite`, `@spree/dashboard-core/vite`) from `dist/` — `pnpm wt:dashboard` handles this (turbo builds the dependency graph, then starts Vite on the portless-assigned port).
-`VITE_API_PROXY_TARGET` overrides the backend the dev proxy targets (default `http://localhost:3000`); don't use `VITE_SPREE_API_URL` in dev — it flips the SDK to absolute cross-origin URLs, bypassing the proxy. Sign in with the seed admin user (`[email protected]` / `spree123` — override at seed time with `ADMIN_EMAIL` / `ADMIN_PASSWORD`; see `spree/core/app/services/spree/seeds/admin_user.rb`).
+`VITE_API_PROXY_TARGET` sets the backend the dev proxy targets — the worktree setup writes it into `packages/dashboard-starter/.env.local` pointing at that worktree's Rails URL. Don't use `VITE_SPREE_API_URL` in dev — it flips the SDK to absolute cross-origin URLs, bypassing the proxy. Sign in with the seed admin user (`[email protected]` / `spree123` — override at seed time with `ADMIN_EMAIL` / `ADMIN_PASSWORD`; see `spree/core/app/services/spree/seeds/admin_user.rb`).
**When implementing a new admin feature:**
diff --git a/package.json b/package.json
index 8e235b6a61..0d72fd1461 100644
--- a/package.json
+++ b/package.json
@@ -22,6 +22,11 @@
"server:logs": "cd server && spree logs",
"server:seed": "cd server && spree rails db:seed",
"server:load_sample_data": "cd server && spree task load_sample_data",
+ "wt:setup": "scripts/worktree/setup.sh",
+ "wt:template": "scripts/worktree/make-template.sh",
+ "wt:dev": "scripts/worktree/dev.sh",
+ "wt:dashboard": "scripts/worktree/dev-dashboard.sh",
+ "wt:e2e": "scripts/worktree/e2e.sh",
"changeset": "changeset",
"version:preview": "changeset version --ignore @spree/sdk"
},
diff --git a/scripts/worktree/dev-dashboard.sh b/scripts/worktree/dev-dashboard.sh
new file mode 100755
index 0000000000..1097d8cb02
--- /dev/null
+++ b/scripts/worktree/dev-dashboard.sh
@@ -0,0 +1,19 @@
+#!/usr/bin/env bash
+# Start this worktree's React dashboard (Vite) behind portless, proxying API
+# calls to this worktree's Rails URL. URL: https://admin.<branch>.spree.localhost
+#
+# Vite ignores the PORT env var, so we build the dashboard's workspace deps
+# with turbo first, then run vite directly with the portless-assigned port.
+set -euo pipefail
+source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib.sh"
+require_portless
+cd "$(worktree_root)"
+
+export VITE_API_PROXY_TARGET
+VITE_API_PROXY_TARGET="$(rails_url)"
+
+pnpm turbo build --filter='@spree/dashboard-starter^...'
+
+cd packages/dashboard-starter
+echo "▸ $(dashboard_url) (proxying /api → $VITE_API_PROXY_TARGET)"
+exec portless "$(dashboard_name)" sh -c 'exec pnpm vite --port "$PORT" --strictPort'
diff --git a/scripts/worktree/dev.sh b/scripts/worktree/dev.sh
new file mode 100755
index 0000000000..8d9cf69726
--- /dev/null
+++ b/scripts/worktree/dev.sh
@@ -0,0 +1,10 @@
+#!/usr/bin/env bash
+# Start this worktree's Rails server behind portless. One Puma process — jobs
+# run inside it via Solid Queue. URL: https://<branch>.spree.localhost
+set -euo pipefail
+source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib.sh"
+require_portless
+cd "$(worktree_root)/server"
+
+echo "▸ $(rails_url) (/up, /api/v3, /jobs)"
+exec portless "$(rails_name)" bin/dev
diff --git a/scripts/worktree/e2e.sh b/scripts/worktree/e2e.sh
new file mode 100755
index 0000000000..a3b285624f
--- /dev/null
+++ b/scripts/worktree/e2e.sh
@@ -0,0 +1,21 @@
+#!/usr/bin/env bash
+# Run the dashboard Playwright suite on this worktree's deterministic port
+# block, so multiple worktrees can run e2e concurrently. The suite already
+# isolates its database (per-worktree SQLite in spree/api/spec/dummy).
+# Extra args pass through to playwright: scripts/worktree/e2e.sh e2e/auth.spec.ts
+set -euo pipefail
+source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib.sh"
+
+if [ ! -d "$(worktree_root)/spree/api/spec/dummy" ]; then
+ echo "spree/api/spec/dummy missing — the e2e suite needs the API test app." >&2
+ echo "Build it once per worktree: cd spree/api && bundle install && bundle exec rake test_app" >&2
+ exit 1
+fi
+
+E2E_RAILS_PORT=$(e2e_base_port)
+E2E_VITE_PORT=$((E2E_RAILS_PORT + 1))
+export E2E_RAILS_PORT E2E_VITE_PORT
+
+echo "▸ e2e on rails :$E2E_RAILS_PORT / vite :$E2E_VITE_PORT"
+cd "$(worktree_root)/packages/dashboard"
+exec pnpm test:e2e "$@"
diff --git a/scripts/worktree/lib.sh b/scripts/worktree/lib.sh
new file mode 100755
index 0000000000..cce5050a21
--- /dev/null
+++ b/scripts/worktree/lib.sh
@@ -0,0 +1,68 @@
+#!/usr/bin/env bash
+# Shared helpers for the multi-worktree dev workflow (see CLAUDE.md "Worktrees").
+# Everything derives from the current git branch, so the scripts work both from
+# worktrunk hooks and when run by hand. Pass a branch name as WT_BRANCH (or as
+# the first argument to the calling script) to operate on another worktree's
+# resources, e.g. from a post-remove hook running in the primary checkout.
+set -euo pipefail
+
+TEMPLATE_DB="spree_worktree_template"
+PG_ARGS=(-h localhost -p "${DATABASE_PORT:-5432}" -U "${DATABASE_USERNAME:-postgres}")
+
+worktree_root() { git rev-parse --show-toplevel; }
+
+branch_name() { echo "${WT_BRANCH:-$(git rev-parse --abbrev-ref HEAD)}"; }
+
+# Readable prefix plus a hash of the full branch name: normalization alone maps
+# feature/a, feature_a and feature.a onto one slug — and databases are dropped
+# by slug, so a collision means one worktree deleting another's data.
+branch_slug() {
+ local branch prefix hash
+ branch="$(branch_name)"
+ prefix=$(printf '%s' "$branch" | tr '/_.' '-' | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9-' | cut -c1-32)
+ hash=$(printf '%s' "$branch" | shasum | cut -c1-6)
+ echo "${prefix%-}-$hash"
+}
+
+db_name() { echo "spree_dev_$(branch_slug | tr '-' '_')"; }
+test_db_name() { echo "spree_test_$(branch_slug | tr '-' '_')"; }
+
+db_exists() { psql "${PG_ARGS[@]}" -lqt | cut -d'|' -f1 | tr -d ' ' | grep -qx "$1"; }
+
+# portless serves https on 443 when its proxy could bind it, otherwise on the
+# fallback port recorded in ~/.portless/proxy.port — derive URLs dynamically so
+# moving the proxy to 443 later needs no script or env changes.
+portless_port() { cat "$HOME/.portless/proxy.port" 2>/dev/null || echo 443; }
+url_suffix() { [ "$(portless_port)" = "443" ] && echo "" || echo ":$(portless_port)"; }
+
+rails_name() { echo "$(branch_slug).spree"; }
+dashboard_name() { echo "admin.$(branch_slug).spree"; }
+rails_url() { echo "https://$(rails_name).localhost$(url_suffix)"; }
+dashboard_url() { echo "https://$(dashboard_name).localhost$(url_suffix)"; }
+
+port_free() { ! lsof -iTCP:"$1" -sTCP:LISTEN -n -P >/dev/null 2>&1; }
+
+# Even-numbered base in 20000-29999 (rails = base, vite = base+1), derived from
+# the branch so repeat runs reuse it. The hash space is smaller than the set of
+# branch names, so step to the next free pair when another run already holds it.
+e2e_base_port() {
+ local hash base candidate offset
+ hash=$(printf '%s' "$(branch_slug)" | cksum | cut -d' ' -f1)
+ base=$((20000 + (hash % 5000) * 2))
+ for offset in $(seq 0 2 998); do
+ candidate=$(( 20000 + ((base - 20000 + offset) % 10000) ))
+ if port_free "$candidate" && port_free $((candidate + 1)); then
+ echo "$candidate"
+ return 0
+ fi
+ done
+ echo "No free e2e port pair in 20000-29999." >&2
+ return 1
+}
+
+require_portless() {
+ command -v portless >/dev/null || {
+ echo "portless not found — install with: npm install -g portless (Node >= 24)" >&2
+ exit 1
+ }
+}
diff --git a/scripts/worktree/make-template.sh b/scripts/worktree/make-template.sh
new file mode 100755
index 0000000000..7c896d433b
--- /dev/null
+++ b/scripts/worktree/make-template.sh
@@ -0,0 +1,27 @@
+#!/usr/bin/env bash
+# Create (or refresh) the seeded template database that worktree databases are
+# copied from. Run once after machine setup, and again after pulling
+# schema-changing migrations. Takes ~2-3 minutes (migrations + Spree seeds);
+# copying from it afterwards takes ~2 seconds.
+set -euo pipefail
+source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib.sh"
+cd "$(worktree_root)"
+
+[ -d server ] || { echo "server/ missing — run pnpm server:create (or scripts/worktree/setup.sh) first." >&2; exit 1; }
+
+if ! grep -q 'DATABASE_NAME' server/config/database.yml; then
+ sed -i '' \
+ -e 's|database: spree_development|database: <%= ENV.fetch("DATABASE_NAME") { "spree_development" } %>|' \
+ -e 's|database: spree_test|database: <%= ENV.fetch("DATABASE_NAME_TEST") { "spree_test" } %>|' \
+ server/config/database.yml
+fi
+
+echo "▸ Rebuilding $TEMPLATE_DB (migrations + seeds, ~2-3 min)"
+dropdb "${PG_ARGS[@]}" --if-exists "$TEMPLATE_DB"
+createdb "${PG_ARGS[@]}" "$TEMPLATE_DB"
+
+(cd server && bundle install --quiet && \
+ DATABASE_NAME="$TEMPLATE_DB" DATABASE_NAME_TEST="$TEMPLATE_DB" \
+ bin/rails spree:install:migrations db:prepare)
+
+echo "✓ $TEMPLATE_DB ready — new worktrees copy it via createdb -T"
diff --git a/scripts/worktree/setup.sh b/scripts/worktree/setup.sh
new file mode 100755
index 0000000000..8b4928f5ce
--- /dev/null
+++ b/scripts/worktree/setup.sh
@@ -0,0 +1,75 @@
+#!/usr/bin/env bash
+# Provision the current worktree as a self-contained dev environment:
+# its own server/ clone, .env, database (copied from the seeded template),
+# gems, node modules, and dashboard proxy config. Idempotent — safe to re-run.
+# Usage: setup.sh [branch] (branch defaults to the current one; worktrunk
+# passes it explicitly from the pre-start hook)
+set -euo pipefail
+WT_BRANCH="${1:-}"
+source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib.sh"
+cd "$(worktree_root)"
+
+echo "▸ Provisioning worktree '$(branch_slug)' (db: $(db_name))"
+
+if [ ! -d server ]; then
+ echo "▸ Cloning spree-starter into server/"
+ git clone --depth 1 --branch 6-0-dev https://github.com/spree/spree-starter.git server
+ rm -rf server/.git server/.gitignore
+fi
+
+if [ ! -f server/.env ]; then
+ cat > server/.env <<EOF
+SPREE_PATH=$(pwd)
+SECRET_KEY_BASE=$(openssl rand -hex 64)
+DATABASE_NAME=$(db_name)
+DATABASE_NAME_TEST=$(test_db_name)
+EOF
+fi
+
+# The starter hardcodes database names; make them env-driven (defaults keep the
+# stock behavior). server/ is gitignored so the patch is invisible to git.
+# TODO: upstream this to spree-starter 6-0-dev, then drop the sed.
+if ! grep -q 'DATABASE_NAME' server/config/database.yml; then
+ sed -i '' \
+ -e 's|database: spree_development|database: <%= ENV.fetch("DATABASE_NAME") { "spree_development" } %>|' \
+ -e 's|database: spree_test|database: <%= ENV.fetch("DATABASE_NAME_TEST") { "spree_test" } %>|' \
+ server/config/database.yml
+fi
+
+# The Host header arrives from the portless proxy with its port attached
+# (foo.spree.localhost:1355 when the proxy isn't on 443), which Rails' default
+# ".localhost" rule rejects — allow .localhost hosts with or without a port.
+if [ ! -f server/config/initializers/worktree_hosts.rb ]; then
+ cat > server/config/initializers/worktree_hosts.rb <<'RUBY'
+Rails.application.config.hosts << /\A[a-z0-9-]+(\.[a-z0-9-]+)*\.localhost(:\d+)?\z/i
+RUBY
+fi
+
+if ! db_exists "$(db_name)"; then
+ if ! db_exists "$TEMPLATE_DB"; then
+ echo "Template database '$TEMPLATE_DB' missing — run scripts/worktree/make-template.sh first." >&2
+ exit 1
+ fi
+ echo "▸ Creating $(db_name) from $TEMPLATE_DB"
+ createdb "${PG_ARGS[@]}" -T "$TEMPLATE_DB" "$(db_name)"
+fi
+
+# Warm boot caches from the primary checkout's server, if it has any.
+primary_root=$(git worktree list --porcelain | head -1 | sed 's/^worktree //')
+if [ -d "$primary_root/server/tmp/cache/bootsnap" ] && [ ! -d server/tmp/cache/bootsnap ]; then
+ mkdir -p server/tmp/cache
+ cp -R "$primary_root/server/tmp/cache/bootsnap" server/tmp/cache/
+fi
+
+echo "▸ Installing gems + migrations"
+(cd server && bundle install --quiet && bin/rails spree:install:migrations db:migrate)
+
+echo "▸ Installing node modules"
+pnpm install --silent
+
+mkdir -p packages/dashboard-starter
+printf 'VITE_API_PROXY_TARGET=%s\n' "$(rails_url)" > packages/dashboard-starter/.env.local
+
+echo "✓ Worktree ready"
+echo " rails: $(rails_url) (pnpm wt:dev)"
+echo " dashboard: $(dashboard_url) (pnpm wt:dashboard)"
diff --git a/scripts/worktree/teardown.sh b/scripts/worktree/teardown.sh
new file mode 100755
index 0000000000..ecc9e06126
--- /dev/null
+++ b/scripts/worktree/teardown.sh
@@ -0,0 +1,22 @@
+#!/usr/bin/env bash
+# Drop a worktree's databases. Runs from the worktrunk post-remove hook (in the
+# primary checkout, with the removed branch passed as $1) or by hand.
+set -euo pipefail
+WT_BRANCH="${1:-}"
+source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib.sh"
+
+# Refuse to drop databases still claimed by a checked-out worktree — teardown
+# normally runs after the worktree is gone, so a live one means we were pointed
+# at the wrong branch.
+# -F matters: branch names may contain regex metacharacters, and a stray match
+# here would refuse a legitimate cleanup.
+if git worktree list --porcelain | grep -qxF "branch refs/heads/$(branch_name)"; then
+ echo "Branch '$(branch_name)' is still checked out in a worktree — refusing to drop its databases." >&2
+ echo "Remove the worktree first (wt remove), or drop them by hand if that is really what you want." >&2
+ exit 1
+fi
+
+for db in "$(db_name)" "$(test_db_name)"; do
+ echo "▸ Dropping $db"
+ dropdb "${PG_ARGS[@]}" --if-exists "$db"
+done