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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Address PR #14123 review comments (round 2)
Damian Legawiecc924a2675346
diff --git a/CLAUDE.md b/CLAUDE.mdindex 938710c463..07b9b7cccc 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -74,6 +74,13 @@ Shipped plans:---+## General rules++- ONLY comment complex or non-obvious methods/code, do not comment every method or class, DON'T create comments noise+- Commit message body: be precise, DON'T include implementation detail, focus on the "what" and "why", not the "how"+- If n-commits are needed for a single logical change, use `git commit --fixup` for the follow-ups and `git rebase -i --autosquash` to combine into a single commit before merging+- Documentation also needs to follow the same principles — focus on the "what" and "why", not the "how". Don't include implementation details in docs. Docs should explain the feature, its purpose, and how to use it, but not how it's implemented internally.+## Backend (Ruby)### Architecture Principlesdiff --git a/docs/plans/spree-dev-cli-and-generators.md b/docs/plans/spree-dev-cli-and-generators.mddeleted file mode 100644index 25513d013d..0000000000--- a/docs/plans/spree-dev-cli-and-generators.md+++ /dev/null@@ -1,754 +0,0 @@-# Spree Dev CLI + Generators — DX for TypeScript developers--**Status:** Spec, not approved.-**Audience:** TS developers who want to customize Spree without learning Docker internals or installing Ruby.-**Owners:** TBD.--## Project structure (what a user actually has)--`create-spree-app` scaffolds:--```text-my-spree-app/-├── backend/ # the Rails app (cloned from spree-starter)-│ ├── Dockerfile-│ ├── Gemfile-│ ├── app/, config/, db/ …-│ └── docker-compose{,.dev}.yml (templates — copied up to root during scaffold)-├── apps/storefront/ # Next.js (optional)-├── docker-compose.yml # active compose at project root-├── docker-compose.dev.yml # dev compose at project root-├── .env-└── package.json # has @spree/cli as a dep-```--`create-spree-app/src/scaffold.ts:58–65` copies the compose files from `backend/` up to the project root and rewrites `context: .` → `context: ./backend` so the build context points at the Rails app. Everything in this doc operates against the **project root** compose files and the **`./backend`** Rails app. (The `server/` directory in the `spree/spree` monorepo is the local dev clone of `spree-starter` — irrelevant to user projects.)--## Problem--A TS developer who runs `pnpm dlx create-spree-app` lands in a working prebuilt-image setup. The moment they want to customize the backend — add a `Brand` model, expose an endpoint, write a subscriber — they hit three walls:--1. **`spree eject` means rebuild-on-every-edit.** Today it swaps `docker-compose.yml` for `docker-compose.dev.yml`, which builds from `./backend/Dockerfile`. The Dockerfile `COPY . .`s the source into the image and the compose file mounts only `storage_data:/rails/storage`. There is no source bind-mount, no bundle cache volume, and the env carries `RAILS_ENV=production` + `BUNDLE_DEPLOYMENT=1` + `BUNDLE_WITHOUT=development:test` from the Dockerfile. So every edit needs `docker compose build`; Zeitwerk reloading never engages; dev gems are absent.-2. **The CLI has no escape hatch.** `spree console`, `spree user create`, `spree api-key` each wrap a specific Rails task. There is no `spree exec`, `spree rails`, `spree bundle`, or `spree migrate`. Anything not pre-wrapped requires the developer to know the underlying `docker compose exec web …` incantation — exactly the knowledge the CLI exists to hide.-3. **Generators stop at the model.** `spree:model` (core/lib/generators/spree/model/) emits a model + migration. There is no `spree:api_resource` to scaffold a v3-conformant Store/Admin controller, serializer, route entry, request spec, and OpenAPI fragment. A new resource is hours of conformance work and a likely review back-and-forth on conventions (prefixed IDs, `{ data, meta }` envelope, expand, keyset pagination, Store-vs-Admin exposure split).--The fix is three independent tracks, layered: (1) make the dev container hot-reload, so `eject` stops meaning rebuild-hell; (2) ship a generic CLI passthrough plus a thin set of hot-path wrappers, like Laravel Sail; (3) add `spree:api_resource` so v3-conformance is correct-by-construction. (4) is the MCP/skill layer over the same surface — covered last and deferred to a follow-up.--The deliverables in this doc are concrete diffs against the project-root `docker-compose.dev.yml` (shipped from `spree-starter` and pulled into user projects by `create-spree-app`), `packages/cli/src/`, and the addition of `core/lib/generators/spree/api_resource/`. Devcontainer support is noted as a follow-up; OrbStack/virtiofs is a docs note, not code.-------## Track 1 — Hot-reload dev container--### Goal--After `spree eject`, the developer edits a file under `./backend/` and the next request reflects the change. No `spree build`, no container restart, no Ruby on the host. Adding a gem stays inside the container (`spree bundle add …`) but does not require a full rebuild — gems land in a persisted volume.--### The four things to change--Each one is needed; cutting any one breaks the loop.--| Change | Why it's required |-|---|---|-| **Bind-mount `./backend:/rails`** | Edits on the host reach the container instantly. Generator output lands on the host. |-| **Named volume on `BUNDLE_PATH` (`/usr/local/bundle`)** | The bind-mount would otherwise shadow the gems baked into the image. The named volume sits over the bundle path so gems persist across `spree bundle add` without a rebuild. |-| **`RAILS_ENV=development`, unset `BUNDLE_DEPLOYMENT`, `BUNDLE_WITHOUT=""`** | The Dockerfile bakes production env. Without overrides the container boots in production mode (no reloading, dev gems absent) even with bind-mounts. |-| **Override entrypoint/command** | The Dockerfile's `ENTRYPOINT bin/docker-entrypoint` runs `db:prepare` and assets precompile every boot — wrong for dev. Use a thin dev command instead. |--### Concrete diff: `docker-compose.dev.yml` (project root; shipped from `spree-starter`'s `backend/` template)--Below is the full proposed file. Anchors and the prod-style `bin/docker-entrypoint` go away; bind-mount + bundle volume + dev env + a node_modules-style listener arrangement come in. Volumes that don't change (postgres, redis, meilisearch, storage) are unchanged.--```yaml-# Development: bind-mounts ./backend into the container. Edits are hot.-# Use `spree dev` (which runs `docker compose up -d` against this file).-#-# Adding a gem: `spree bundle add some_gem` — gems persist in the bundle_cache volume.-# Changing the Dockerfile or .ruby-version: `spree build` to rebuild the image.--x-app: &app- build:- context: .- dockerfile: Dockerfile- depends_on:- postgres:- condition: service_healthy- redis:- condition: service_healthy- meilisearch:- condition: service_healthy- env_file: .env- environment: &app-env- DATABASE_URL: postgres://postgres@postgres:5432/spree_development- REDIS_URL: redis://redis:6379/0- SECRET_KEY_BASE: ${SECRET_KEY_BASE}- RAILS_FORCE_SSL: "false"- RAILS_ASSUME_SSL: "false"- MEILISEARCH_URL: http://meilisearch:7700- # --- dev overrides on top of the Dockerfile's production defaults ---- RAILS_ENV: development- BUNDLE_DEPLOYMENT: "0"- BUNDLE_WITHOUT: ""- BUNDLE_PATH: /usr/local/bundle- BOOTSNAP_CACHE_DIR: /rails/tmp/cache/bootsnap- volumes:- # bind-mount the source so host edits are live in the container- - ./backend:/rails- # named volume over BUNDLE_PATH so the bind-mount doesn't shadow installed gems,- # and so `bundle add` persists across container restarts without a rebuild- - bundle_cache:/usr/local/bundle- # named volume for storage (uploads, ActiveStorage local disk)- - storage_data:/rails/storage- # named volume for tmp so bootsnap + cache don't churn the host- - tmp_cache:/rails/tmp--services:- postgres:- image: postgres:18-alpine- environment:- POSTGRES_HOST_AUTH_METHOD: trust- PGDATA: /var/lib/postgresql/18/docker- ports:- # forwarded for native DB clients (TablePlus, DataGrip, psql) — Track 1 add- - "${SPREE_DB_PORT:-5433}:5432"- volumes:- - postgres_data:/var/lib/postgresql- healthcheck:- test: pg_isready -U postgres- interval: 5s- timeout: 5s- retries: 5-- redis:- image: redis:7-alpine- volumes:- - redis_data:/data- healthcheck:- test: redis-cli ping- interval: 5s- timeout: 5s- retries: 5-- meilisearch:- image: getmeili/meilisearch:latest- volumes:- - meilisearch_data:/meili_data- ports:- - "7700:7700"- healthcheck:- test: curl -f http://localhost:7700/health || exit 1- interval: 5s- timeout: 5s- retries: 5-- web:- <<: *app- # bypass bin/docker-entrypoint (which does db:prepare + assets:precompile —- # not what we want in dev). Run setup explicitly via `spree init`.- entrypoint: []- command: ["bin/rails", "server", "-b", "0.0.0.0", "-p", "3000"]- ports:- - "${SPREE_PORT:-3000}:3000"- healthcheck:- test: curl -f http://localhost:3000/up || exit 1- interval: 10s- timeout: 5s- retries: 10- start_period: 30s-- worker:- <<: *app- entrypoint: []- command: ["bundle", "exec", "sidekiq"]- environment:- <<: *app-env- RAILS_MAX_THREADS: ${SIDEKIQ_DB_POOL:-27}--volumes:- postgres_data:- redis_data:- meilisearch_data:- storage_data:- bundle_cache:- tmp_cache:-```--Notes on the diff:--- **`DATABASE_URL` switches `spree_production` → `spree_development`.** This matches `RAILS_ENV=development` (Rails would otherwise look for the wrong DB). `spree init` creates it; `spree migrate` runs against it.-- **The bind-mount + bundle-cache layering is the trick.** Without the named volume on `/usr/local/bundle`, the bind-mount of `./backend → /rails` shadows the gems baked into the image (since the build stage installs to `/usr/local/bundle` and copies them in). The named volume re-overlays gems on top, and persists `bundle add` results across boots.-- **Anchored `volumes:` on `*app`** means `web` and `worker` share the same mount set. Don't define `volumes:` on the service or it'll override the anchor — Compose merges keys, but it replaces lists.-- **`entrypoint: []` is intentional.** `bin/docker-entrypoint` runs `db:prepare` (which would auto-create the DB and silently swallow migration ordering issues) and `bootsnap precompile`. Both are wrong in dev. `spree init` does the explicit equivalent (`db:create`, `db:migrate`, `db:seed`).-- **`SPREE_DB_PORT=5433` default**, not 5432, to avoid colliding with a host-native Postgres if the user has one.--### Adding and updating gems — no image rebuild--The `bundle_cache` named volume is the persistent gem store. The dev image's role is "seed the volume on first creation with a known-good baseline"; after that, the volume is the source of truth.--| Scenario | Command | Image rebuild? |-|---|---|---|-| Add a gem | `spree bundle add foo` | No — installs into `bundle_cache` |-| Update a gem | `spree bundle update <gem>` | No |-| Pull teammate's Gemfile.lock change | `spree bundle install` | No |-| `.ruby-version` bump | `spree build` + see gotcha below | Yes |-| Dockerfile apt package change | `spree build` | Yes |--**Gotcha (documented; not a code change):** Docker initializes a named volume from the image's mount-path contents *only the first time the volume is created*. After `spree build` for a `.ruby-version` bump, the rebuilt image carries gems compiled against the new Ruby, but the existing `bundle_cache` volume still holds gems from the old Ruby — they'll fail to load. Fix: `docker volume rm <project>_bundle_cache` (or, in the CLI: `spree build --reset-bundle` — a small additional flag to wipe the bundle volume in the same operation; trivial to add to the `build` command).--### `eject` semantics post-change--`spree eject` keeps its current job — copy `docker-compose.dev.yml` over `docker-compose.yml` — but the meaning changes: the dev compose is now the live-edit configuration, not a "build from local source" configuration. After `eject`:--- File edits in `./backend/` are live (Zeitwerk).-- `Gemfile` edits use `spree bundle add <gem>` (runs inside the container, persists to `bundle_cache`).-- `Dockerfile` or `.ruby-version` edits require `spree build` (new command, see Track 2).--### Diff: `packages/cli/src/commands/eject.ts`--```diff-- console.log(`\n${pc.bold('Building backend from local source...')}\n`)-- await dockerCompose(['build'], ctx.projectDir, { stdio: 'inherit' })---- console.log(`\n${pc.bold('Restarting services...')}\n`)-+ console.log(`\n${pc.bold('Switching to dev compose (bind-mounts ./backend)...')}\n`)- await dockerCompose(['up', '-d'], ctx.projectDir, { stdio: 'inherit' })-- p.note(- [-- `Backend now builds from ${pc.bold('./backend')}`,-+ `Backend is now bind-mounted from ${pc.bold('./backend')} — edits are live.`,- '',- 'You can now customize:',-- ` ${pc.dim('backend/Gemfile')} — add gems`,-+ ` ${pc.dim('backend/app/')} — models, controllers, services — instant reload`,-+ ` ${pc.dim('backend/Gemfile')} — add gems via ${pc.bold('spree bundle add <gem>')}`,- ` ${pc.dim('backend/app/')} — models, controllers, etc.`,- ` ${pc.dim('backend/config/')} — Rails configuration`,- '',-- `Run ${pc.bold('npx spree dev')} to restart with your changes.`,-+ `Rebuild only on Dockerfile / .ruby-version changes: ${pc.bold('spree build')}`,- ].join('\n'),- 'Ejected!',- )-```--`spree build` is the new "I actually changed the image" escape hatch — see Track 2.-------## Track 2 — CLI: passthrough first, then wrappers--### Goal--A TS developer can run any Rails / bundler / shell command inside the dev container without knowing about Docker. Hot-path commands get a short alias; everything else goes through a generic passthrough.--### Design principle: passthrough is the floor--The hot wrappers (`spree generate`, `spree migrate`, `spree bundle`, `spree build`) save keystrokes for the common cases. The generic passthrough (`spree exec`, `spree rails`, `spree bundle`) guarantees nothing is ever blocked on a command we forgot to wrap. **Build passthrough first, wrappers second** — the wrappers can never invalidate the floor.--### New commands--| Command | Maps to | Notes |-|---|---|---|-| `spree exec <cmd…>` | `docker compose exec web <cmd…>` | Generic escape hatch. Anything works. |-| `spree rails <args…>` | `docker compose exec web bin/rails <args…>` | Short for `spree exec bin/rails …` |-| `spree rake <task> [args…]` | `docker compose exec web bin/rake <task> [args…]` | Direct rake passthrough. `spree rake spree:price_history:seed`, `spree rake spree:channels:create_defaults`. Use this for data backfills, upgrade tasks, and anything not wrapped by a higher-level command. Args after `--` are forwarded as rake task args (`spree rake spree:foo -- BAR=baz`). |-| `spree task <name> [args…]` | alias for `spree rake spree:<name>` | Shorter for Spree-namespaced tasks: `spree task price_history:seed` ≡ `spree rake spree:price_history:seed`. |-| `spree bundle <args…>` | `docker compose exec web bundle <args…>` | `spree bundle add stripe`, `spree bundle install`, `spree bundle outdated`. Gems land in `bundle_cache`. |-| `spree generate <name> [args…]` | `docker compose exec web bin/rails g spree:<name> [args…]` | Translates `spree generate model Brand …` into `bin/rails g spree:model Brand …`. Auto-prefixes `spree:`. |-| `spree migrate` | `docker compose exec web bin/rails db:migrate` | Hot path — first thing after every generator. |-| `spree migrate:rollback [STEP=n]` | `docker compose exec web bin/rails db:rollback` | |-| `spree migrate:status` | `docker compose exec web bin/rails db:migrate:status` | |-| `spree db:reset` | `docker compose exec web bin/rails db:drop db:create db:migrate db:seed` | Common nuke-and-pave. Prompts for confirmation. |-| `spree routes [-g pattern]` | `docker compose exec web bin/rails routes [-g …]` | |-| `spree build` | `docker compose exec` not viable — `docker compose build web` | Used after Dockerfile / `.ruby-version` changes. Not after Gemfile changes (use `spree bundle add` for those). |-| `spree db:console` | `docker compose exec postgres psql -U postgres spree_development` | One-liner for psql without remembering credentials. (Native clients use the forwarded `SPREE_DB_PORT`.) |--The existing commands (`spree dev`, `spree init`, `spree stop`, `spree logs`, `spree console`, `spree user`, `spree api-key`, `spree open`, `spree seed`, `spree sample-data`, `spree update`, `spree eject`) stay.--### Implementation sketch--A single new helper, `dockerComposeExec`, generalizes what `railsConsole` does today (`packages/cli/src/docker.ts:33–37`) and accepts arbitrary argv:--```ts-// packages/cli/src/docker.ts — add alongside existing helpers--export async function dockerComposeExec(- argv: string[],- projectDir: string,- options: { service?: string; tty?: boolean; env?: Record<string, string> } = {},-): Promise<void> {- const { service = 'web', tty = true, env } = options- const args = ['compose', 'exec']- if (!tty) args.push('-T')- if (env) for (const [k, v] of Object.entries(env)) args.push('-e', `${k}=${v}`)- args.push(service, ...argv)-- await execa('docker', args, { cwd: projectDir, stdio: 'inherit' })-}-```--Then `exec`, `rails`, `bundle`, `migrate`, `generate`, `routes` are each one file in `packages/cli/src/commands/` that calls `dockerComposeExec` with a different prefix. Example:--```ts-// packages/cli/src/commands/generate.ts (new)-import type { Command } from 'commander'-import { detectProject } from '../context.js'-import { dockerComposeExec } from '../docker.js'--export function registerGenerateCommand(program: Command): void {- program- .command('generate <name> [args...]')- .alias('g')- .description('Run a Spree generator (e.g. `spree generate model Brand name:string`)')- .allowUnknownOption(true) // pass through `--skip-tests` etc.- .action(async (name: string, args: string[]) => {- const ctx = detectProject()- await dockerComposeExec(- ['bin/rails', 'g', `spree:${name}`, ...args],- ctx.projectDir,- )- })-}-```--```ts-// packages/cli/src/commands/exec.ts (new) — the universal escape hatch-import type { Command } from 'commander'-import { detectProject } from '../context.js'-import { dockerComposeExec } from '../docker.js'--export function registerExecCommand(program: Command): void {- program- .command('exec <command...>')- .description('Run an arbitrary command inside the web container')- .allowUnknownOption(true)- .action(async (command: string[]) => {- const ctx = detectProject()- await dockerComposeExec(command, ctx.projectDir)- })-}-```--`spree rails`, `spree bundle`, `spree migrate`, `spree routes`, `spree db:reset`, `spree db:console` follow the same pattern — ~15 lines each, no shared abstraction needed beyond `dockerComposeExec`.--### `spree console` becomes a thin wrapper--Drop `railsConsole` from `docker.ts` — `registerConsoleCommand` becomes:--```ts-await dockerComposeExec(['bin/rails', 'console'], ctx.projectDir)-```--Same for the other Rails-task-bound commands. `rakeTask` (the non-interactive variant that strips Spree boot noise) stays — `init`, `user create`, `api-key` still use it for parsed output.--### Registration--```diff- // packages/cli/src/index.ts-+import { registerBuildCommand } from './commands/build.js'-+import { registerBundleCommand } from './commands/bundle.js'-+import { registerDbCommand } from './commands/db.js'-+import { registerExecCommand } from './commands/exec.js'-+import { registerGenerateCommand } from './commands/generate.js'-+import { registerMigrateCommand } from './commands/migrate.js'-+import { registerRailsCommand } from './commands/rails.js'-+import { registerRoutesCommand } from './commands/routes.js'- // … existing registrations …-+registerExecCommand(program)-+registerRailsCommand(program)-+registerBundleCommand(program)-+registerGenerateCommand(program)-+registerMigrateCommand(program)-+registerBuildCommand(program)-+registerDbCommand(program)-+registerRoutesCommand(program)-```--### The Laravel Sail parallel--For reviewers benchmarking against Sail:--| Sail | This proposal |-|---|---|-| `sail artisan make:model Brand` | `spree generate model Brand` |-| `sail artisan migrate` | `spree migrate` |-| `sail composer require stripe/stripe-php` | `spree bundle add stripe` |-| `sail tinker` | `spree console` |-| `sail shell` | `spree exec bash` |-| `sail up -d` | `spree dev` |-| `sail build` | `spree build` |--Same shape: thin shell over `docker compose exec`, predictable verb-noun mapping, generic escape hatch covers the long tail.-------## Track 2c — `spree upgrade` (scripted guidance, not magic)--### What it is and what it isn't--**Is:** an interactive walkthrough of the steps required to upgrade from your current Spree version to the target version, with the automatable parts (rake data tasks, `db:migrate`) offered as "run now? [Y/n]". Each step is named, ordered, idempotent, and re-runnable. Output mirrors what's in `docs/upgrades/<version>.mdx` so the command and the docs can never drift.--**Isn't:** a magic `spree upgrade && done` button. Upgrades involve `bundle update spree*`, schema migrations, data backfills, occasional config edits, and version-specific manual review steps (e.g. "audit your custom decorators against the renamed class"). A command that owns half the steps and silently hands the rest to the user is worse than no command — users assume it owned the whole thing and skip the manual parts. The framing is "scripted runbook," not "automation."--This is the same shape as Rails' own upgrade flow (`rails app:update` walks you through config diffs interactively) and Spree's existing per-task `desc` strings ("Run the full 5.4 → 5.5 channel upgrade"). It just makes them addressable from one command and sequences them correctly.--### The mapping problem and how it's solved--Today's data tasks are *implicitly* version-scoped — `spree/core/lib/tasks/channels.rake` is the 5.4→5.5 channel upgrade, `price_history.rake:seed` is the 5.4→5.5 EU Omnibus backfill — but only the rake `desc` strings encode that, and only as prose. The version → tasks mapping lives nowhere machine-readable. Adding `spree upgrade` requires a mapping.--The mapping uses **directory convention + tiny per-version manifest**, with the rake tasks themselves unchanged:--```text-core/lib/spree/upgrades/-├── 5_4_to_5_5/-│ ├── manifest.yml-│ └── README.md (optional long-form; otherwise docs link)-├── 5_5_to_6_0/-│ ├── manifest.yml-│ └── README.md-└── …-```--`manifest.yml` per version is short and lists each step:--```yaml-# core/lib/spree/upgrades/5_4_to_5_5/manifest.yml-from: "5.4"-to: "5.5"-docs: "https://spreecommerce.org/docs/upgrades/5.5"--steps:- - id: bundle- name: "Update Spree gems"- kind: shell- command: "bundle update spree spree_api spree_admin"- automated: true-- - id: migrate- name: "Run database migrations"- kind: rails- command: "db:migrate"- automated: true-- - id: channels- name: "Create default channels and backfill product publications"- kind: rake- task: "spree:channels:full_upgrade"- automated: true- idempotent: true-- - id: price_history- name: "Seed price history from current base prices (EU Omnibus)"- kind: rake- task: "spree:price_history:seed"- automated: true- idempotent: true- skip_if: "non-EU stores can skip"-- - id: review_decorators- name: "Review custom decorators against renamed Promotion → Discount API surface"- kind: manual- docs_anchor: "decorator-review"- automated: false-```--Why a YAML manifest rather than a Ruby DSL or rake task metadata: the manifest is data the CLI reads — it does not need Rails booted to render the plan, and adding a step does not require touching CLI code. A new upgrade directory + manifest = a new upgrade. That's the whole extension model.--### CLI surface--```bash-spree upgrade # detect from → to from Gemfile.lock and run the manifest interactively-spree upgrade --to 5.5 # explicit target (when you want to step rather than jump)-spree upgrade --plan # print the plan, don't execute (good for PR description / runbook)-spree upgrade --step price_history # run one step idempotently-spree upgrade --from 5.4 --to 6.0 # multi-hop: walks 5.4→5.5, then 5.5→6.0 in sequence-```--`--from` defaults to the current installed Spree version (read from `Gemfile.lock` inside the container). `--to` defaults to the latest version with an upgrade manifest. The detected version pair selects which manifests to run, in order. For each step:--- `kind: shell` — print the command, ask, run via `dockerComposeExec`.-- `kind: rails` — same, run via `bin/rails <command>`.-- `kind: rake` — same, run via `bin/rake <task>`.-- `kind: manual` — print the description + docs link, wait for "done? [Y/n]" before continuing.--Default mode is interactive (each step asks). `--yes` runs all automated steps without prompting and stops at the first `kind: manual`. `--plan` doesn't execute anything.--### What this implies for rake task organization--The rake tasks themselves don't move. `spree/core/lib/tasks/channels.rake` stays where it is. What changes:--1. **Add per-version aggregator tasks** where they don't already exist. `channels.rake` already has `full_upgrade`; the pattern should be every version-scoped rake file ends with one idempotent aggregator task that runs the whole version's data migration for that domain. Then the manifest references just the aggregator, never the individual tasks.-2. **Tighten idempotency.** Aggregator tasks must be safe to re-run. Some of the existing ones already are (e.g. `create_defaults` uses `ensure_default_channel`); others (`backfill_*`) should be audited and made idempotent (skip rows where the target column is already populated, etc.) before they appear in any manifest.-3. **Manifest references task names, not file paths.** This makes the manifest survive rake task moves between files.--### What `spree upgrade` does NOT solve--- **Decorator and customization review.** A user with custom decorators on `Spree::Promotion` needs to manually audit them when the API surface renames to `Discount`. This is `kind: manual` in the manifest with a link to the upgrade doc. No tool can do this safely.-- **Database-specific gotchas.** `Spree::Current.store` and similar runtime-context migrations. Same answer: `kind: manual`, link to docs.-- **Cross-extension upgrades.** Each Spree extension owns its own upgrade docs and rake tasks. `spree upgrade` only walks core. Extensions can ship their own manifests under `<gem>/lib/spree/upgrades/`; the CLI globs the gem load paths to discover them. Out of scope for v1; document the convention but don't build it.--### Why not "spree upgrade just runs every rake task in a namespace"--The temptation: pattern-match `spree:upgrades:5_5:*` and run them all. Rejected because (a) ordering matters (you can't seed price history before the migration adds the table), (b) some steps aren't rake tasks (`bundle update`, manual reviews), (c) some are conditionally skippable, and (d) prose context per step matters for the user trusting the command. The manifest is the price of doing this honestly.-------## Track 3 — `spree:api_resource` generator--### Goal--`spree generate api_resource Brand name:string:index slug:string:uniq` produces a complete, idiomatic v3 resource: model, migration, Store controller, Admin controller, two serializers, routes injected, request specs, OpenAPI fragment, and an admin-sdk type entry — all of it conformant with the conventions in `CLAUDE.md` (prefixed IDs, `{ data, meta }` envelope, flat params, Store vs Admin exposure rules).--### Why this lives in Ruby, not in the CLI--The CLI's `spree generate` proxies to `bin/rails g spree:<name>`. The actual scaffolding stays inside `core/lib/generators/spree/api_resource/` for the same reason `spree:model` lives there: generators belong with the framework they generate code for. The CLI's job is environment management; the generator's job is code generation. If we ever ship a non-Docker workflow (mise, native Ruby) the generator works unchanged.--### Generator surface--```text-spree:api_resource NAME [field[:type[:index|:uniq|:null|:default=…]]…] [options]-```--**Standard Rails field syntax**, extended with:--- `:uniq` — adds a unique index, validates uniqueness scoped to `spree_base_uniqueness_scope`-- `:index` — adds a non-unique index-- `:null` — marks `null: false` (the inverse of Rails' default; matches CLAUDE.md "always `null: false` on required columns")-- `belongs_to:<Model>` — adds the association + index, **no FK constraint** (per CLAUDE.md migration rules)--**Options:**--- `--id-prefix=brand` — optional, **auto-filled** from the class name when omitted. Default derivation: snake_case the class name and take the whole thing (`Brand → :brand`, `OrderRoutingRule → :order_routing_rule`). The generated `has_prefix_id :<prefix>` line is surfaced in the generator's summary output so the developer sees the chosen prefix and can edit the model file if they want a shorter or curated form. The existing codebase mixes both — some models go long (`:variant`, `:price`, `:invitation`), others go curated (`:ful` for Shipment, `:py` for Payment for Stripe parity, `:cf` for Metafield rename). Auto-fill picks the safe long form; edit afterwards if you want curated.-- `--store` / `--no-store` (default: yes — generate Store controller + serializer)-- `--admin` / `--no-admin` (default: yes)-- `--store-name=Discount` — emit Store controller/serializer/routes under a different external name (handles the Promotions/Discounts split)-- `--writable` (Store API) — opt into create/update/destroy on the Store controller (default: read-only, per CLAUDE.md "read-only by default")-- `--paranoid` — `acts_as_paranoid`, adds `deleted_at` column + `dependent: :destroy_async` on associations-- `--metafields` — include `Spree::Metafields` + `Spree::Metadata`-- `--skip-routes`, `--skip-openapi`, `--skip-specs` — escape hatches--### What it emits--For `spree generate api_resource Brand name:string:uniq active:boolean:default=true`:--```text-core/app/models/spree/brand.rb (owned-once)-core/db/migrate/<ts>_create_spree_brands.rb (append-only)--api/app/controllers/spree/api/v3/store/brands_controller.rb (managed)-api/app/controllers/spree/api/v3/admin/brands_controller.rb (managed)-api/app/serializers/spree/api/v3/brand_serializer.rb (managed)-api/app/serializers/spree/api/v3/admin/brand_serializer.rb (managed)-api/spec/integration/api/v3/store/brands_spec.rb (managed)-api/spec/integration/api/v3/admin/brands_spec.rb (managed)-api/config/routes.rb (route injected between markers)-core/lib/spree/testing_support/factories/brand_factory.rb (managed)--docs/api-reference/store.yaml (regenerate from specs)-packages/sdk/src/types/generated/store-brand.d.ts (regenerate via Typelizer)-packages/admin-sdk/src/types/generated/admin-brand.d.ts (regenerate via Typelizer)-```--### Idempotency contract--Re-running the generator on an existing resource — the use case is "I added a field, regenerate" — should leave the model file untouched (it's the developer's now), append a new migration for the schema delta, and rewrite the serializers/controllers/specs/routes in place. The model file gets a header comment marking it as owned-once:--```ruby-# This file was scaffolded by `spree generate api_resource Brand`.-# It's yours now — behavior, validations, scopes, callbacks live here.-# Re-running the generator will NOT overwrite this file.-module Spree- class Brand < Spree.base_class- # ...- end-end-```--The contract from the last-turn writeup (owned-once / managed-forever / append-only) is the whole trick. Hand-edit the model freely; hand-editing the serializer is allowed but means the next generator run will overwrite — which is fine because the conventions (prefixed IDs, typelize, what's Store vs Admin) are exactly what the generator already enforces.--**Route injection** uses Rails-style sentinel markers in `api/config/routes.rb`:--```ruby-namespace :store do- # BEGIN spree:api_resource managed routes — do not hand-edit- resources :brands, only: [:index, :show]- # END spree:api_resource managed routes-end-```--`Thor::Actions#insert_into_file` finds the markers and inserts; if a `resources :brands` line already exists in the block, skip.--### Generated examples (abbreviated)--Model (owned-once, minimal — developer adds behavior). Note the `has_prefix_id :brand` line — prefixed IDs are computed on the fly via `Spree::PrefixedId` (no DB column), but the prefix must be declared per-model. The generator emits it from the `--id-prefix` flag:--```ruby-# backend/app/models/spree/brand.rb-# Owned-once: scaffolded by `spree generate api_resource Brand`.-module Spree- class Brand < Spree.base_class- include Spree::Metafields- include Spree::Metadata-- has_prefix_id :brand # from --id-prefix=brand; auto-derived from class name when flag omitted-- validates :name, presence: true- validates :slug, presence: true, uniqueness: { scope: spree_base_uniqueness_scope }-- self.whitelisted_ransackable_attributes = %w[name slug active]- end-end-```--Migration (append-only, conventional Rails):--```ruby-class CreateSpreeBrands < ActiveRecord::Migration[7.2]- def change- create_table :spree_brands do |t|- t.string :name, null: false- t.string :slug, null: false- t.boolean :active, null: false, default: true- t.timestamps- end-- add_index :spree_brands, :slug, unique: true,- name: 'index_spree_brands_on_slug'- end-end-```--Store controller (managed):--```ruby-module Spree::Api::V3::Store- class BrandsController < ResourceController- protected-- def model_class- Spree::Brand- end-- def serializer_class- Spree.api.brand_serializer- end- end-end-```--Store serializer (managed — no timestamps, customer-facing fields only):--```ruby-module Spree::Api::V3- class BrandSerializer < BaseSerializer- typelize active: :boolean- attributes :id, :name, :slug, :active- end-end-```--Admin serializer (managed — extends store, adds timestamps + back-office fields):--```ruby-module Spree::Api::V3::Admin- class BrandSerializer < V3::BrandSerializer- attributes :created_at, :updated_at- end-end-```--Admin controller — empty subclass (full CRUD inherited from `Spree::Api::V3::Admin::ResourceController`).--Request spec (managed — single happy-path + a 422 case for OpenAPI examples; matches CLAUDE.md test guidance):--```ruby-# api/spec/integration/api/v3/store/brands_spec.rb-require 'swagger_helper'--RSpec.describe 'Brands API', type: :request do- path '/api/v3/store/brands' do- get 'List brands' do- tags 'Brands'- produces 'application/json'-- response '200', 'returns brands' do- let!(:brand) { create(:brand) }- run_test!- end- end- end-end-```--(Admin spec covers create/update/destroy; same shape.)--### The `--store-name Discount` flag — the naming-split case--Models, tables, and ability checks stay `Brand` / `spree_brands` internally. The Store API surface re-exposes the same controller under a different external name:--```ruby-# api/config/routes.rb (Store namespace)-resources :discounts, controller: 'brands', only: [:index, :show]-```--…and the Store serializer is aliased (in the registry, not duplicated):--```ruby-Spree.api.brand_serializer = 'Spree::Api::V3::DiscountSerializer'-```--Generated `DiscountSerializer` is a one-line subclass of `BrandSerializer`. This is exactly the Promotions/Discounts pattern from the 6.0 plans — one flag, mechanical output, no per-resource thinking.--### Out of scope--- **TS frontend forms / pages.** Per the conversation: backend-only for now. `@spree/dashboard` route scaffolding is a separate generator, deferred.-- **Diffing across regenerations to produce migration deltas.** Migrations are generated once on resource create; field additions/changes are a separate `spree generate migration AddFieldToBrand` step (proxies to `bin/rails g migration`).-- **Decorator-aware generation** (i.e. detecting that the user has decorated `Spree::Brand` elsewhere). Decorators are last-resort per CLAUDE.md; we don't need to be clever about them.-------## Track 4 — MCP tools + Skill (deferred)--The exact same `dockerComposeExec` + `spree:api_resource` engine surfaces three different ways:--1. **CLI** — what this doc specs.-2. **MCP tools** — `spree_generate_resource(name, fields, options)`, `spree_migrate()`, `spree_run_rails(args)`, etc. Each is a typed wrapper over the same engine. Already partially exists (`mcp__claude_ai_Spree_Commerce_Docs_MCP__*` ships docs search; we'd add an action server).-3. **Skill / `AGENTS.md`** — `docs/agents/spree-customization.md` teaches the agent: "for green-field resources call `spree_generate_resource`; for cross-cutting edits (add a field to an existing serializer, wire a filter into an existing endpoint, write a subscriber) read the file and edit it; the generator output is correct-by-construction so don't second-guess it."--This doc treats those as a follow-up because they all depend on Tracks 1–3 existing first. The shape of (4) doesn't change the design of (1–3) at all — it's pure orchestration over them.-------## Sequencing--Strict order; each phase unblocks the next.--1. **Track 1 (compose rewrite + eject diff).** Single PR. Without this, every other track's wrappers still trigger rebuilds and the developer story is unchanged.-2. **Track 2a — passthrough (`spree exec`, `spree rails`, `spree bundle`).** Single PR. After this, every Rails command is reachable without docs.-3. **Track 2b — hot-path wrappers (`spree generate`, `spree migrate`, `spree build`, `spree db:console`, `spree rake`, `spree task`).** Single PR. Polishing; users have escape hatch from 2a if a wrapper is missing or buggy.-4. **Track 2c — `spree upgrade` + per-version manifests.** Separate PR. Starts with one manifest (5.4→5.5, since the rake tasks largely exist). Adding manifests for future versions becomes part of the release checklist. Can ship independent of Track 3.-5. **Track 3 — `spree:api_resource` generator.** Larger PR, lives in `core/`. The model + migration paths can ship before the serializer/controller/route paths if needed; the value is cumulative.-6. **Track 4 — MCP / skill.** Follow-up doc + PR. Not in this scope.--Devcontainer and mac perf docs (OrbStack, virtiofs) ride along with Track 1 as a separate `docs/developer/dev-environment.md` page.-------## Resolved decisions--These were open and now aren't, written down so future-me doesn't reopen them:--1. **Compose profile vs file swap.** Keep the file swap; revisit only if it bites.-2. **`spree generate` does NOT auto-run `spree migrate`.** Two-step, like Rails. Documented in command help.-3. **Prefixed-ID prefix is per-model and auto-filled.** `Spree::PrefixedId` (`spree/core/app/models/concerns/spree/prefixed_id.rb`) computes IDs on the fly via Sqids from the integer PK — no column, no DB change. The prefix is declared per-class via `has_prefix_id :prod`. The generator auto-derives the prefix from the class name (`Brand → :brand`, `OrderRoutingRule → :order_routing_rule`) and emits the line, surfacing the chosen prefix in the summary output so the developer can edit if they want a shorter or curated form (e.g. matching Stripe like `:py`). See Track 3 options for the override flag.-6. **All upgrade rake tasks MUST be idempotent.** This is a hard contract, not a soft preference: a task that fails on re-run cannot ship to a manifest. The pattern is `where.not(<target_col>: nil)` skip-guards on `backfill_*` and `ensure_*`-style guards on `create_*` (as `channels.rake:create_defaults` does today via `ensure_default_channel`). Audit pass on existing tasks is a prerequisite for Track 2c.-7. **Extension manifests deferred.** v1 ships core-only. Extensions invoke their own upgrade rake tasks manually.--## Open questions--1. **~~`db/schema.rb` write permissions from the dev container.~~ Resolved.** Originally framed as a real problem — turns out it isn't. Every CLI command goes through `docker compose exec web …`, which means file writes happen as the container's default user (UID 1000, `rails`). On macOS, Docker Desktop and OrbStack do UID mapping at the VM boundary, so bind-mount writes always appear as the host user regardless of container UID. On Linux, the host user is typically UID 1000 (Ubuntu/Debian/Fedora default), so the UIDs match. The bundle/tmp/storage volumes are docker-managed (not bind-mounted), so the host never touches them — initial UID-1000 ownership inside the container is exactly what's wanted. The compose stays simple: no `user:` override, no init service, no entrypoint chown. The CLI exporting `HOST_UID`/`HOST_GID` is only needed for the Linux multi-user edge case (host user not UID 1000) and is deferred until someone actually hits it.--2. **`spree-starter` PR.** The new compose ships from `spree-starter`'s `backend/` template. A sibling PR lands the new `docker-compose.dev.yml` there. (The monorepo `server/` directory is dev-only for the gems and doesn't need separate consideration.)--3. **Idempotency helper for backfill tasks.** The existing `backfill_*` family will get `where.not(<col>: nil)` guards as part of the Track 2c prep audit. Whether to extract a shared helper (`Spree::Upgrades::Idempotent.backfill(scope, &block)`) or keep guards per-task is style preference; lean per-task — explicit skip conditions read better than a clever wrapper for something that runs once per upgrade.diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.tsindex a330f240d7..0ccca035e7 100644--- a/packages/cli/src/commands/build.ts+++ b/packages/cli/src/commands/build.ts@@ -7,22 +7,6 @@ import pc from 'picocolors'import { detectProject } from '../context.js'import { dockerCompose } from '../docker.js'-/**- * Register the `spree build` command on the CLI program.- *- * Rebuilds the dev image. Needed after Dockerfile or .ruby-version changes;- * `spree bundle add` does NOT require this — gems land in the bundle_cache- * volume which survives image rebuilds.- *- * `--reset-bundle` wipes the bundle_cache volume so the new image's gem- * baseline gets re-seeded. Use when you bumped .ruby-version (gems compiled- * against the old Ruby won't load against the new one).- *- * Targets docker-compose.dev.yml explicitly when present, so this works- * before `spree eject` too (eject collapses the two files into one).- *- * @param program - The Commander CLI program to register the command on.- */export function registerBuildCommand(program: Command): void {program.command('build')@@ -31,7 +15,17 @@ export function registerBuildCommand(program: Command): void {.option('--yes', 'skip confirmation prompts (for CI)').action(async (flags: { resetBundle?: boolean; yes?: boolean }) => {const ctx = detectProject()- const composeArgs = composeFileArgs(ctx.projectDir)+ // Always build against the active docker-compose.yml — the same file+ // `spree dev` runs. After `spree eject` that contains a `build:` section+ // pointing at ./backend; before eject, it's a prebuilt-image stack and+ // there's nothing to rebuild.+ if (!hasBuildSection(ctx.projectDir)) {+ console.error(+ `\n${pc.red('Error:')} docker-compose.yml has no \`build:\` section. ` ++ `Run ${pc.bold('spree eject')} first to switch to a build-from-source stack.\n`,+ )+ process.exit(1)+ }if (flags.resetBundle) {if (!flags.yes) {@@ -48,25 +42,31 @@ export function registerBuildCommand(program: Command): void {const s = p.spinner()s.start('Wiping bundle_cache volume...')- // Stop containers without -v: `down -v` would also wipe postgres,- // redis, meilisearch, and storage volumes — destroying dev data- // and uploads. We only want to drop bundle_cache.- await dockerCompose([...composeArgs, 'down'], ctx.projectDir, { stdio: 'ignore' })- // Resolve the compose project name so we can target the namespaced- // volume directly. Compose derives the project name from the dir- // (or COMPOSE_PROJECT_NAME); `compose ls --format json` returns- // whatever it actually uses for THIS compose file.- const projectName = await resolveComposeProjectName(composeArgs, ctx.projectDir)- await execa('docker', ['volume', 'rm', `${projectName}_bundle_cache`], {- cwd: ctx.projectDir,- stdio: 'ignore',- reject: false, // Volume may not exist on first build — that's fine- })- s.stop('bundle_cache volume wiped.')+ try {+ // `down` without -v preserves postgres/redis/meilisearch/storage volumes.+ await dockerCompose(['down'], ctx.projectDir, { stdio: 'ignore' })+ const projectName = await resolveComposeProjectName(ctx.projectDir)+ const volumeName = `${projectName}_bundle_cache`+ // Check before removal so we can report missing-volume distinctly+ // from a real failure (wrong permissions, daemon issue).+ const exists = await volumeExists(volumeName, ctx.projectDir)+ if (exists) {+ await execa('docker', ['volume', 'rm', volumeName], {+ cwd: ctx.projectDir,+ stdio: 'ignore',+ })+ s.stop('bundle_cache volume wiped.')+ } else {+ s.stop(`bundle_cache volume not present (looked for ${volumeName}).`)+ }+ } catch (error) {+ s.stop('Failed to wipe bundle_cache volume.')+ throw error+ }}console.log(`\n${pc.bold('Rebuilding dev image...')}\n`)- await dockerCompose([...composeArgs, 'build', 'web', 'worker'], ctx.projectDir, {+ await dockerCompose(['build', 'web', 'worker'], ctx.projectDir, {stdio: 'inherit',})@@ -84,30 +84,19 @@ export function registerBuildCommand(program: Command): void {})}-// Pre-eject projects have `docker-compose.dev.yml` alongside the prod compose;-// we need `-f` to build against it. Post-eject the two files are the same-// (eject overwrites docker-compose.yml with the dev one), so `-f` is harmless.-function composeFileArgs(projectDir: string): string[] {- const devCompose = path.join(projectDir, 'docker-compose.dev.yml')- return fs.existsSync(devCompose) ? ['-f', 'docker-compose.dev.yml'] : []+function hasBuildSection(projectDir: string): boolean {+ const composeFile = path.join(projectDir, 'docker-compose.yml')+ if (!fs.existsSync(composeFile)) return false+ // Cheap YAML probe — looks for `build:` at the start of a line (the only+ // valid YAML position for a service-level build directive).+ return /^\s*build\s*:/m.test(fs.readFileSync(composeFile, 'utf-8'))}-// Returns the compose project name (e.g. `my-spree-app` or whatever-// COMPOSE_PROJECT_NAME / dir basename resolves to). Used to target the-// `<project>_bundle_cache` named volume without guessing.-//-// Falls back to the project directory's basename if the compose ls call-// doesn't find an entry — matches Compose's own default behavior.-async function resolveComposeProjectName(- composeArgs: string[],- projectDir: string,-): Promise<string> {+async function resolveComposeProjectName(projectDir: string): Promise<string> {try {- const { stdout } = await execa(- 'docker',- ['compose', ...composeArgs, 'config', '--format', 'json'],- { cwd: projectDir },- )+ const { stdout } = await execa('docker', ['compose', 'config', '--format', 'json'], {+ cwd: projectDir,+ })const parsed = JSON.parse(stdout) as { name?: string }if (parsed.name) return parsed.name} catch {@@ -118,3 +107,15 @@ async function resolveComposeProjectName(.toLowerCase().replace(/[^a-z0-9_-]/g, '')}++async function volumeExists(name: string, projectDir: string): Promise<boolean> {+ try {+ await execa('docker', ['volume', 'inspect', name], {+ cwd: projectDir,+ stdio: 'ignore',+ })+ return true+ } catch {+ return false+ }+}diff --git a/packages/cli/src/commands/db.ts b/packages/cli/src/commands/db.tsindex f0a345cedd..6ee0971fa1 100644--- a/packages/cli/src/commands/db.ts+++ b/packages/cli/src/commands/db.ts@@ -3,9 +3,6 @@ import type { Command } from 'commander'import { detectProject } from '../context.js'import { dockerComposeExec } from '../docker.js'-// Two related but independent commands: db:reset (destructive) and db:console-// (read-only). Registered as flat commands rather than under a `spree db`-// parent because Rails uses the same flat style (`rails db:reset`).export function registerDbCommand(program: Command): void {program.command('db:reset')@@ -25,9 +22,8 @@ export function registerDbCommand(program: Command): void {}}- // Single Rails invocation chaining all four tasks so any failure short-circuits.await dockerComposeExec(- ['bin/rails', 'db:drop', 'db:create', 'db:migrate', 'db:seed'],+ ['bin/rails', 'db:drop', 'db:create', 'spree:install:migrations', 'db:migrate', 'db:seed'],ctx.projectDir,)})@@ -37,8 +33,6 @@ export function registerDbCommand(program: Command): void {.description('Open a psql session against the dev database').action(async () => {const ctx = detectProject()- // Targets the postgres service, not web. The dev compose sets- // POSTGRES_HOST_AUTH_METHOD=trust so no password is needed.await dockerComposeExec(['psql', '-U', 'postgres', 'spree_development'], ctx.projectDir, {service: 'postgres',})diff --git a/packages/cli/src/commands/dev.ts b/packages/cli/src/commands/dev.tsindex fc801adeca..ec617c1bdb 100644--- a/packages/cli/src/commands/dev.ts+++ b/packages/cli/src/commands/dev.ts@@ -1,3 +1,5 @@+import fs from 'node:fs'+import path from 'node:path'import * as p from '@clack/prompts'import type { Command } from 'commander'import pc from 'picocolors'@@ -12,6 +14,17 @@ export function registerDevCommand(program: Command): void {.action(async () => {const ctx = detectProject()+ if (hasMonorepoSpreePath(ctx.projectDir)) {+ p.cancel(+ [+ 'This project uses SPREE_PATH for monorepo development.',+ `Use ${pc.bold('pnpm server:start')} from the monorepo root instead of ${pc.bold('spree dev')}.`,+ 'It loads the edge compose overlay and sets SPREE_PATH so the Spree gems resolve to the monorepo source.',+ ].join('\n'),+ )+ process.exit(1)+ }+const s = p.spinner()s.start('Starting Docker services...')await dockerCompose(['up', '-d'], ctx.projectDir)@@ -36,3 +49,14 @@ export function registerDevCommand(program: Command): void {await streamLogs('web', ctx.projectDir)})}++function hasMonorepoSpreePath(projectDir: string): boolean {+ const envPath = path.join(projectDir, '.env')+ if (!fs.existsSync(envPath)) return false+ try {+ const contents = fs.readFileSync(envPath, 'utf-8')+ return /^\s*SPREE_PATH\s*=/m.test(contents)+ } catch {+ return false+ }+}diff --git a/packages/cli/src/commands/generate.ts b/packages/cli/src/commands/generate.tsindex f1cf11123d..292b30727f 100644--- a/packages/cli/src/commands/generate.ts+++ b/packages/cli/src/commands/generate.ts@@ -2,24 +2,40 @@ import type { Command } from 'commander'import { detectProject } from '../context.js'import { dockerComposeExec } from '../docker.js'-// Run a Spree generator. Auto-prefixes `spree:` so the common case stays-// short: `spree generate model Brand` → `bin/rails g spree:model Brand`.-//-// If the name already contains a colon (e.g. `spree:model`, `active_storage:install`)-// it's treated as fully-qualified and forwarded as-is. For non-Spree generators-// reach for `spree rails g <name> …` directly.+// Forwarded as-is so `spree generate migration AddX` hits Rails's own+// generator instead of the non-existent `spree:migration`. `model` is+// intentionally absent — Spree provides `spree:model`.+const RAILS_BUILTIN_GENERATORS = new Set([+ 'migration',+ 'scaffold',+ 'scaffold_controller',+ 'mailer',+ 'job',+ 'channel',+ 'helper',+ 'resource',+ 'integration_test',+ 'system_test',+ 'task',+ 'generator',+ 'benchmark',+])+export function registerGenerateCommand(program: Command): void {program.command('generate').alias('g')- .description('Run a Spree generator (auto-prefixes `spree:`)')- .argument('<name>', 'generator name (`model`, `model_decorator`, …)')+ .description(+ 'Run a generator (Spree generators auto-prefixed; Rails built-ins forwarded as-is)',+ )+ .argument('<name>', 'generator name (`model`, `model_decorator`, `migration`, …)').argument('[args...]', 'arguments to pass to the generator').allowUnknownOption(true).passThroughOptions(true).action(async (name: string, args: string[]) => {const ctx = detectProject()- const generator = name.includes(':') ? name : `spree:${name}`+ const generator =+ name.includes(':') || RAILS_BUILTIN_GENERATORS.has(name) ? name : `spree:${name}`await dockerComposeExec(['bin/rails', 'g', generator, ...args], ctx.projectDir)})}diff --git a/packages/cli/src/commands/migrate.ts b/packages/cli/src/commands/migrate.tsindex 6bb84e16c0..708647aff6 100644--- a/packages/cli/src/commands/migrate.ts+++ b/packages/cli/src/commands/migrate.ts@@ -2,18 +2,21 @@ import type { Command } from 'commander'import { detectProject } from '../context.js'import { dockerComposeExec } from '../docker.js'-// Three flat commands matching Rails's own naming: `spree migrate`,-// `spree migrate:rollback [STEP=n]`, `spree migrate:status`.export function registerMigrateCommand(program: Command): void {program.command('migrate')- .description('Run pending database migrations (`bin/rails db:migrate`)')+ .description(+ 'Install pending Spree migrations from gems, then run them (`spree:install:migrations` + `db:migrate`)',+ ).argument('[args...]', 'extra args forwarded to db:migrate').allowUnknownOption(true).passThroughOptions(true).action(async (args: string[]) => {const ctx = detectProject()- await dockerComposeExec(['bin/rails', 'db:migrate', ...args], ctx.projectDir)+ await dockerComposeExec(+ ['bin/rails', 'spree:install:migrations', 'db:migrate', ...args],+ ctx.projectDir,+ )})programdiff --git a/packages/cli/src/commands/restart.ts b/packages/cli/src/commands/restart.tsindex 4d545a8d2d..9e73bc27df 100644--- a/packages/cli/src/commands/restart.ts+++ b/packages/cli/src/commands/restart.ts@@ -3,17 +3,6 @@ import type { Command } from 'commander'import { detectProject } from '../context.js'import { dockerCompose } from '../docker.js'-// `docker compose restart` sends SIGTERM, the container's PID 1 exits, Docker-// re-launches it. Same image, same volumes, fresh Rails process — fast and-// matches the "just restart the app" intent.-//-// Right for: config/initializers/*.rb changes, code that's loaded once at-// boot, any change Zeitwerk doesn't auto-reload.-//-// NOT right for: Gemfile changes (need `spree bundle install` first, then-// `spree stop && spree dev` to recreate the container from the updated-// bundle), Dockerfile / .ruby-version changes (need `spree build`), or-// compose file changes (need recreate). For those, use the heavier path.export function registerRestartCommand(program: Command): void {program.command('restart')@@ -27,8 +16,6 @@ export function registerRestartCommand(program: Command): void {await dockerCompose(['restart', 'web', 'worker'], ctx.projectDir)s.stop('Services restarted.')} catch (error) {- // Without this, the spinner stays "live" when the top-level- // handler prints the error — output lands under a stale prompt.s.stop('Restart failed.')throw error}diff --git a/packages/cli/src/commands/routes.ts b/packages/cli/src/commands/routes.tsindex a383ce0483..f7e6f27929 100644--- a/packages/cli/src/commands/routes.ts+++ b/packages/cli/src/commands/routes.ts@@ -2,17 +2,6 @@ import type { Command } from 'commander'import { detectProject } from '../context.js'import { dockerComposeExec } from '../docker.js'-/**- * Register the `spree routes` command on the CLI program.- *- * Passthrough to `bin/rails routes [-g pattern] [-c controller] [--expanded]`.- *- * spree routes- * spree routes -g products- * spree routes -c Spree::Api::V3::Store::ProductsController- *- * @param program - The Commander CLI program to register the command on.- */export function registerRoutesCommand(program: Command): void {program.command('routes')diff --git a/packages/cli/src/commands/upgrade.ts b/packages/cli/src/commands/upgrade.tsindex 3d75fa5b76..58dec8c417 100644--- a/packages/cli/src/commands/upgrade.ts+++ b/packages/cli/src/commands/upgrade.ts@@ -1,41 +1,13 @@import * as p from '@clack/prompts'import type { Command } from 'commander'+import { execa } from 'execa'import pc from 'picocolors'import { detectProject } from '../context.js'import { dockerComposeExec } from '../docker.js'-/**- * Register the `spree upgrade` command on the CLI program.- *- * Dev-friendly sequencer around the real upgrade flow:- *- * 1. bundle update (universal — bumps spree_core etc.)- * 2. db:migrate (universal — applies the new gem's migrations)- * 3. spree:upgrade (version-specific — runs the rake-only manifest)- *- * On production, step 3 is what your deploy pipeline runs after `bundle- * install` + `db:migrate` happen there. Steps 1 and 2 are handled by your- * platform (Heroku release phase, K8s init container, Render auto-migrate,- * Capistrano deploy hook), not by this CLI.- *- * Local dev: this command runs all three for you. On a clean stack the- * total time is dominated by `bundle update` (network + native ext build).- *- * Flags map to env vars on the inner rake task so the same args work in- * both surfaces:- *- * --plan DRY_RUN=1 (also skips steps 1 + 2)- * --step <id> STEP=<id>- * --to <version> TO=<version>- * --yes no flag — skips the per-step prompt- *- * What this CLI deliberately does NOT do: schedule cron jobs, review- * breaking changes, tune reservation TTLs. Those are in- * docs/developer/upgrades/<v>.mdx and the manifest's `notes` text; we- * print the docs URL at the end so the operator knows where to look.- *- * @param program - The Commander CLI program to register the command on.- */+// Sequences bundle update + db:migrate + spree:upgrade rake. Flags map+// to env vars on the inner rake task: --plan → DRY_RUN, --step → STEP,+// --to → TO. --plan and --step skip the bundle + migrate pre-steps.export function registerUpgradeCommand(program: Command): void {program.command('upgrade')@@ -50,10 +22,6 @@ export function registerUpgradeCommand(program: Command): void {.action(async (flags: { plan?: boolean; step?: string; to?: string; yes?: boolean }) => {const ctx = detectProject()- // --plan and --step both opt out of the universal pre-steps:- // --plan: we're not running anything anyway.- // --step: the operator is retrying one rake step after a fix;- // bundle/migrate already happened in the original run.const skipUniversal = Boolean(flags.plan || flags.step)if (!skipUniversal) {@@ -63,11 +31,6 @@ export function registerUpgradeCommand(program: Command): void {await runRakeUpgrade(ctx.projectDir, flags)- // Closing reminder: the manifest only covers rake-runnable steps.- // Anything human (cron scheduling, breaking-change review) is in- // the upgrade doc — point there so the operator doesn't forget.- // Skipped on --plan because nothing actually ran — the "next steps"- // reminder would be misleading.if (!flags.plan) printPostUpgradeReminder()})}@@ -78,7 +41,6 @@ async function runBundleUpdate(projectDir: string, flags: { yes?: boolean }): Prmessage: 'Run `bundle update` to bump Spree gems?',initialValue: true,})- // Ctrl+C aborts the whole upgrade; "No" just skips this step.if (p.isCancel(confirmed)) {p.cancel('Upgrade aborted.')process.exit(0)@@ -88,8 +50,40 @@ async function runBundleUpdate(projectDir: string, flags: { yes?: boolean }): Prreturn}}- p.log.step(pc.bold('bundle update'))- await dockerComposeExec(['bundle', 'update'], projectDir)++ // Scope to spree* gems to avoid surprise major bumps on unrelated deps.+ const spreeGems = await detectSpreeGems(projectDir)+ if (spreeGems.length === 0) {+ throw new Error(+ 'No Spree gems detected in Gemfile.lock. ' ++ 'Confirm the project has `gem "spree"` (or `spree_core`/`spree_admin`) in its Gemfile.',+ )+ }++ p.log.step(pc.bold(`bundle update ${spreeGems.join(' ')}`))+ await dockerComposeExec(['bundle', 'update', ...spreeGems], projectDir)+}++async function detectSpreeGems(projectDir: string): Promise<string[]> {+ // Let exec failures (stack down, web service missing) bubble up — the+ // upgrade should fail loudly, not silently skip the gem bump.+ const { stdout } = await execa(+ 'docker',+ [+ 'compose',+ 'exec',+ '-T',+ 'web',+ 'sh',+ '-c',+ "bundle list --name-only 2>/dev/null | grep '^spree' || true",+ ],+ { cwd: projectDir },+ )+ return stdout+ .split('\n')+ .map((line) => line.trim())+ .filter((line) => line.length > 0 && line.startsWith('spree'))}async function runMigrate(projectDir: string, flags: { yes?: boolean }): Promise<void> {@@ -98,10 +92,6 @@ async function runMigrate(projectDir: string, flags: { yes?: boolean }): Promisemessage: 'Install + run pending migrations?',initialValue: true,})- // Ctrl+C aborts the whole upgrade; "No" just skips this step.- // Skipping `db:migrate` is risky — the rake `spree:upgrade` step that- // follows often assumes fresh schema. We let the user proceed anyway;- // if rake fails they'll see why.if (p.isCancel(confirmed)) {p.cancel('Upgrade aborted.')process.exit(0)@@ -112,7 +102,6 @@ async function runMigrate(projectDir: string, flags: { yes?: boolean }): Promise}}p.log.step(pc.bold('spree:install:migrations + db:migrate'))- // Compound rails invocation matches the canonical upgrade doc.await dockerComposeExec(['bin/rails', 'spree:install:migrations', 'db:migrate'], projectDir)}@@ -120,9 +109,7 @@ async function runRakeUpgrade(projectDir: string,flags: { plan?: boolean; step?: string; to?: string },): Promise<void> {- // Flags become env vars on the rake side. This is the contract that- // keeps prod (operator typing `STEP=channels rake spree:upgrade`) and- // dev (this CLI) using the same execution path.+ // Flags map to env vars so prod (`STEP=channels rake spree:upgrade`) and dev share the same path.const env: Record<string, string> = {}if (flags.plan) env.DRY_RUN = '1'if (flags.step) env.STEP = flags.stepdiff --git a/scripts/server-setup.sh b/scripts/server-setup.shindex 4c0630cfe5..3628d822c9 100755--- a/scripts/server-setup.sh+++ b/scripts/server-setup.sh@@ -61,8 +61,16 @@ step "Starting the edge stack"pnpm server:startstep "Waiting for web container to come up"+WAIT_TIMEOUT=120+elapsed=0until docker compose -f "$DEV_COMPOSE" ps web --format '{{.State}}' | grep -q running; do+ if [ "$elapsed" -ge "$WAIT_TIMEOUT" ]; then+ echo "✗ web container did not reach 'running' within ${WAIT_TIMEOUT}s." >&2+ echo " Inspect with: docker compose -f $DEV_COMPOSE logs web" >&2+ exit 1+ fisleep 1+ elapsed=$((elapsed + 1))done# Even when running, Rails takes a few seconds to be ready to accept exec.# A quick warmup avoids the first `docker compose exec` racing the boot.diff --git a/spree/core/lib/generators/spree/api_resource/api_resource_generator.rb b/spree/core/lib/generators/spree/api_resource/api_resource_generator.rbindex 74e09401fd..31482a4854 100644--- a/spree/core/lib/generators/spree/api_resource/api_resource_generator.rb+++ b/spree/core/lib/generators/spree/api_resource/api_resource_generator.rb@@ -87,7 +87,7 @@ module Spreedef initialize(*args)super- @model_existed_before_run = File.exist?(model_file_destination)+ @model_existed_before_run = File.exist?(File.join(destination_root, model_file_destination))end# Override parent: skip if the model file already exists. Re-runningdiff --git a/spree/core/lib/generators/spree/api_resource/templates/admin_controller.rb.tt b/spree/core/lib/generators/spree/api_resource/templates/admin_controller.rb.ttindex ab270dc789..269562d529 100644--- a/spree/core/lib/generators/spree/api_resource/templates/admin_controller.rb.tt+++ b/spree/core/lib/generators/spree/api_resource/templates/admin_controller.rb.tt@@ -10,7 +10,7 @@ module Spreeenddef serializer_class- Spree.api.admin_<%= singular_name %>_serializer+ Spree::Api::V3::Admin::<%= bare_class_name %>Serializerenddef permitted_paramsdiff --git a/spree/core/lib/generators/spree/api_resource/templates/store_controller.rb.tt b/spree/core/lib/generators/spree/api_resource/templates/store_controller.rb.ttindex 6493f5f076..0499b6e8f1 100644--- a/spree/core/lib/generators/spree/api_resource/templates/store_controller.rb.tt+++ b/spree/core/lib/generators/spree/api_resource/templates/store_controller.rb.tt@@ -15,7 +15,7 @@ module Spreeend<% else -%>def serializer_class- Spree.api.<%= singular_name %>_serializer+ Spree::Api::V3::<%= bare_class_name %>Serializerend<% end -%><% if writable? -%>diff --git a/spree/core/lib/generators/spree/api_resource/templates/store_serializer.rb.tt b/spree/core/lib/generators/spree/api_resource/templates/store_serializer.rb.ttindex 0e5a60d814..30aebe44c0 100644--- a/spree/core/lib/generators/spree/api_resource/templates/store_serializer.rb.tt+++ b/spree/core/lib/generators/spree/api_resource/templates/store_serializer.rb.tt@@ -7,7 +7,7 @@ module Spreetypelize <%= typelizable.map { |a| "#{a.name}: :#{a.type == :boolean ? 'boolean' : 'number'}" }.join(', ') %><% end -%>- attributes <%= (['id'] + permitted_attribute_names).map { |a| ":#{a}" }.join(', ') %>+ attributes <%= permitted_attribute_names.map { |a| ":#{a}" }.join(', ') %>endendenddiff --git a/spree/core/lib/generators/spree/model/model_generator.rb b/spree/core/lib/generators/spree/model/model_generator.rbindex 6909dd63ef..2021c7a2cb 100644--- a/spree/core/lib/generators/spree/model/model_generator.rb+++ b/spree/core/lib/generators/spree/model/model_generator.rb@@ -1,25 +1,11 @@require "rails/generators/active_record/model/model_generator"module Spree- # spree:model — extend Rails' ActiveRecord model generator with Spree- # conventions: Spree::Base parent, has_prefix_id, no FK constraints in- # migrations, null: false on all columns by default, plus opt-in flags- # for soft-delete (--paranoid) and custom fields (--metafields).- #- # spree:api_resource inherits from this — see api_resource_generator.rb.class ModelGenerator < ActiveRecord::Generators::ModelGeneratordef self.source_paths- # Spree's templates must come FIRST so they override Rails' bundled- # model.rb.tt and create_table_migration.rb.tt. Thor's template lookup- # uses first-match across source_paths.[File.expand_path('templates', __dir__), *superclass.source_paths]end- # Default is the literal expression `Spree.base_class`, not a class- # constant — Spree.base_class is the swappable lookup that lets apps- # override the inheritance root via config. The template emits this- # verbatim. Override with --parent=Spree::SomeOtherClass when you- # genuinely need to inherit from something else.class_option :parent,type: :string,default: 'Spree.base_class',@@ -41,13 +27,10 @@ module Spreedesc 'Creates a new Spree model with prefixed IDs and Spree.base_class parent'- # Override to prevent module file from being createddef create_module_filereturnend- # Exposed to templates (model.rb.tt, create_table_migration.rb.tt) via- # the standard generator-method-as-template-helper mechanism.no_tasks dodef id_prefixoptions[:id_prefix] || file_name@@ -61,20 +44,44 @@ module Spreeoptions[:metafields]end- # Spree models live under app/models/spree/, regardless of whether- # the user invokes `spree:model Brand` or `spree:model Spree::Brand`.- # Rails' generator uses `class_path` (the namespace components) to- # decide where to put the model file; we force `["spree"]`.def class_path['spree']end- # Spree tables are prefixed `spree_` (spree_brands, not brands).- # Rails' `table_name` derives from the class name without namespace- # prefixing in tables, so we add it explicitly.def table_name"spree_#{super.delete_prefix('spree_')}"end++ # Resolution: explicit class hint in attribute spec → Spree.user_class+ # for user-named columns → Spree.admin_user_class for admin-user-named+ # columns → Spree::<CamelCasedName> default. The Rails attribute parser+ # splits on `:` so explicit hints can only be unqualified names; users+ # needing a namespace edit the generated belongs_to.+ def belongs_to_class_name_expr(attribute)+ explicit = attribute.attr_options.keys.find { |k| k.to_s.match?(/\A(::)?[A-Z]/) }+ return "'#{explicit}'" if explicit++ case attribute.name+ when 'user', 'user_id'+ '"::#{Spree.user_class}"'+ when 'admin_user', 'admin_user_id', 'created_by', 'created_by_id',+ 'approver', 'approver_id', 'canceler', 'canceler_id'+ '"::#{Spree.admin_user_class}"'+ else+ "'Spree::#{attribute.name.camelize}'"+ end+ end++ def column_default_for(attribute)+ return nil unless attribute.attr_options.key?(:default)++ value = attribute.attr_options[:default]+ case value+ when true, false, nil then value.inspect+ when Numeric then value.to_s+ else value.to_s.inspect+ end+ endendendenddiff --git a/spree/core/lib/generators/spree/model/templates/create_table_migration.rb.tt b/spree/core/lib/generators/spree/model/templates/create_table_migration.rb.ttindex 4647d085d5..d8ac546aa4 100644--- a/spree/core/lib/generators/spree/model/templates/create_table_migration.rb.tt+++ b/spree/core/lib/generators/spree/model/templates/create_table_migration.rb.tt@@ -7,11 +7,12 @@ class <%= migration_class_name %> < ActiveRecord::Migration[<%= ActiveRecord::Mi<% elsif attribute.token? -%>t.string :<%= attribute.name %>, null: false<% else -%>- t.<%= attribute.type %> :<%= attribute.name %>, null: false+<% default_expr = column_default_for(attribute) -%>+ t.<%= attribute.type %> :<%= attribute.name %>, null: false<%= ", default: #{default_expr}" if default_expr %><% end -%><% end -%><% attributes.select(&:reference?).each do |attribute| -%>- t.references :<%= attribute.name %>, null: false, index: true<%= ', polymorphic: true' if attribute.polymorphic? %>+ t.references :<%= attribute.name %>, null: false, index: true, foreign_key: false<%= ', polymorphic: true' if attribute.polymorphic? %><% end -%><% if paranoid? -%>t.datetime :deleted_atdiff --git a/spree/core/lib/generators/spree/model/templates/model.rb.tt b/spree/core/lib/generators/spree/model/templates/model.rb.ttindex f7af89dded..2a832f0b56 100644--- a/spree/core/lib/generators/spree/model/templates/model.rb.tt+++ b/spree/core/lib/generators/spree/model/templates/model.rb.tt@@ -15,7 +15,7 @@ module Spree<% if attribute.polymorphic? -%>belongs_to :<%= attribute.name %>, polymorphic: true<% else -%>- belongs_to :<%= attribute.name %>, class_name: 'Spree::<%= attribute.name.camelize %>'+ belongs_to :<%= attribute.name %>, class_name: <%= belongs_to_class_name_expr(attribute) %><% end -%><% end -%><% attributes.select(&:rich_text?).each do |attribute| -%>diff --git a/spree/core/lib/tasks/upgrade.rake b/spree/core/lib/tasks/upgrade.rakeindex 174d3a30fb..c23bc4445a 100644--- a/spree/core/lib/tasks/upgrade.rake+++ b/spree/core/lib/tasks/upgrade.rake@@ -72,12 +72,13 @@ module Spree# rendering, invocation) stay separable and the plan can be inspected# without execution.class Runner- attr_reader :target_version, :step_id, :dry_run+ attr_reader :target_version, :step_id, :dry_run, :target_explicitdef initialize(target_version: nil, step_id: nil, dry_run: false)- @target_version = target_version || Spree::Upgrade.installed_minor_version- @step_id = step_id- @dry_run = dry_run+ @target_explicit = !target_version.nil?+ @target_version = target_version || Spree::Upgrade.installed_minor_version+ @step_id = step_id+ @dry_run = dry_runenddef call@@ -97,21 +98,36 @@ module Spreeprivate- # Every manifest whose `to` is ≤ target_version, in walk order.+ # In plan-mode without explicit TO, show manifests ahead of the installed+ # version — the path the operator is about to walk. Otherwise filter to+ # manifests whose `to` is ≤ target.def eligible_manifestsSpree::Upgrade.available_manifests- .select { |m| Spree::Upgrade.compare(m[:to], target_version) <= 0 }+ .select { |manifest| manifest_eligible?(manifest) }.map { |entry| load_manifest_yaml(entry) }end+ def manifest_eligible?(manifest)+ if dry_run && !target_explicit+ Spree::Upgrade.compare(manifest[:from], Spree::Upgrade.installed_minor_version) >= 0+ else+ Spree::Upgrade.compare(manifest[:to], target_version) <= 0+ end+ end+def load_manifest_yaml(entry)YAML.safe_load_file(File.join(entry[:dir], 'manifest.yml'))enddef run_full_walk(manifests)total_steps = manifests.sum { |m| m['steps'].size }+ reported_target = if dry_run && !target_explicit+ manifests.map { |m| m['to'] }.compact.max_by { |v| Spree::Upgrade.version_parts(v) } || target_version+ else+ target_version+ endputs- puts " Walking #{manifests.size} manifest(s), #{total_steps} step(s) total. Target: Spree #{target_version}."+ puts " Walking #{manifests.size} manifest(s), #{total_steps} step(s) total. Target: Spree #{reported_target}."manifests.each do |manifest|print_manifest_header(manifest)diff --git a/spree/core/spec/lib/generators/spree/api_resource/api_resource_generator_spec.rb b/spree/core/spec/lib/generators/spree/api_resource/api_resource_generator_spec.rbnew file mode 100644index 0000000000..b41672642b--- /dev/null+++ b/spree/core/spec/lib/generators/spree/api_resource/api_resource_generator_spec.rb@@ -0,0 +1,138 @@+require 'spec_helper'+require 'fileutils'+require 'rails/generators'+require 'generators/spree/api_resource/api_resource_generator'++RSpec.describe Spree::ApiResourceGenerator, type: :generator do+ let(:destination) { File.expand_path('../../../../../tmp/api_resource_generator_test', __dir__) }++ before do+ FileUtils.rm_rf(destination)+ FileUtils.mkdir_p(destination)+ end++ after do+ FileUtils.rm_rf(destination)+ end++ def run_generator(argv)+ described_class.start(argv + ['--skip-routes', '--skip-specs', '--force', '--migration'], destination_root: destination)++ {+ model: read_first(File.join(destination, 'app/models/spree/*.rb')),+ migration: read_first(File.join(destination, 'db/migrate/*.rb')),+ store_controller: read_at(File.join(destination, 'app/controllers/spree/api/v3/store')),+ admin_controller: read_at(File.join(destination, 'app/controllers/spree/api/v3/admin')),+ store_serializer: read_first(File.join(destination, 'app/serializers/spree/api/v3/*_serializer.rb')),+ admin_serializer: read_first(File.join(destination, 'app/serializers/spree/api/v3/admin/*_serializer.rb')),+ factory: read_first(File.join(destination, 'lib/spree/testing_support/factories/*_factory.rb'))+ }+ end++ def read_first(glob)+ path = Dir[glob].find { |p| File.file?(p) }+ path && File.read(path)+ end++ def read_at(dir)+ path = Dir[File.join(dir, '*.rb')].first+ path && File.read(path)+ end++ describe 'inherits Spree::ModelGenerator behavior' do+ it 'generates the model with has_prefix_id and Spree.base_class' do+ result = run_generator(['Brand', 'name:string'])++ expect(result[:model]).to include('class Brand < Spree.base_class')+ expect(result[:model]).to include('has_prefix_id :brand')+ end++ it 'generates the migration with null: false + foreign_key: false on references' do+ result = run_generator(['Variant', 'product:references', 'name:string'])++ expect(result[:migration]).to include('t.string :name, null: false')+ expect(result[:migration]).to include('t.references :product, null: false, index: true, foreign_key: false')+ end++ it 'respects Spree.user_class for user references' do+ result = run_generator(['UserBrand', 'user:references', 'name:string'])++ expect(result[:model]).to include('belongs_to :user, class_name: "::#{Spree.user_class}"')+ end++ it 'checks model_existed_before_run against destination_root, not process cwd' do+ # Regression: the snapshot used a relative path so the gem's own+ # app/models/spree/<name>.rb was treated as existing in the user's app.+ result = run_generator(['Variant', 'product:references', 'name:string'])++ expect(result[:model]).to include('class Variant < Spree.base_class')+ expect(result[:migration]).to include('create_table :spree_variants')+ end+ end++ describe 'API controllers' do+ it 'generates a Store controller emitting a literal serializer class' do+ result = run_generator(['Brand', 'name:string'])++ expect(result[:store_controller]).to include('Spree::Api::V3::BrandSerializer')+ expect(result[:store_controller]).not_to include('Spree.api.brand_serializer')+ end++ it 'generates an Admin controller emitting a literal admin serializer class' do+ result = run_generator(['Brand', 'name:string'])++ expect(result[:admin_controller]).to include('Spree::Api::V3::Admin::BrandSerializer')+ expect(result[:admin_controller]).not_to include('Spree.api.admin_brand_serializer')+ end++ it 'skips Store generation when --no-store is set' do+ run_generator(['Brand', 'name:string', '--no-store'])++ expect(Dir[File.join(destination, 'app/controllers/spree/api/v3/store/*')]).to be_empty+ end++ it 'skips Admin generation when --no-admin is set' do+ run_generator(['Brand', 'name:string', '--no-admin'])++ expect(Dir[File.join(destination, 'app/controllers/spree/api/v3/admin/*')]).to be_empty+ end++ it 'permits flat params on the Admin controller for full CRUD' do+ result = run_generator(['Brand', 'name:string', 'active:boolean'])++ expect(result[:admin_controller]).to include('params.permit(:name, :active)')+ end++ it 'permits flat params on the Store controller only when --writable is set' do+ read_only = run_generator(['Brand', 'name:string'])+ expect(read_only[:store_controller]).not_to include('params.permit')++ FileUtils.rm_rf(destination)+ FileUtils.mkdir_p(destination)+ writable = run_generator(['Brand', 'name:string', '--writable'])+ expect(writable[:store_controller]).to include('params.permit')+ end+ end++ describe 'factory + serializers' do+ it 'generates a factory file under lib/spree/testing_support/factories/' do+ result = run_generator(['Brand', 'name:string'])++ expect(result[:factory]).to include('factory :brand, class: Spree::Brand')+ end++ it 'generates Store and Admin serializers (Admin inherits Store)' do+ result = run_generator(['Brand', 'name:string'])++ expect(result[:store_serializer]).to include('class BrandSerializer')+ expect(result[:admin_serializer]).to include('< V3::BrandSerializer')+ end++ it 'does not redeclare :id in the Store serializer (BaseSerializer already defines it as the prefixed ID)' do+ result = run_generator(['Brand', 'name:string', 'active:boolean'])++ expect(result[:store_serializer]).to match(/^\s*attributes :name, :active$/)+ expect(result[:store_serializer]).not_to include(':id,')+ end+ end+enddiff --git a/spree/core/spec/lib/generators/spree/model/model_generator_spec.rb b/spree/core/spec/lib/generators/spree/model/model_generator_spec.rbnew file mode 100644index 0000000000..3343367380--- /dev/null+++ b/spree/core/spec/lib/generators/spree/model/model_generator_spec.rb@@ -0,0 +1,174 @@+require 'spec_helper'+require 'fileutils'+require 'rails/generators'+require 'generators/spree/model/model_generator'++RSpec.describe Spree::ModelGenerator, type: :generator do+ let(:destination) { File.expand_path('../../../../../tmp/generator_test', __dir__) }++ before do+ FileUtils.rm_rf(destination)+ FileUtils.mkdir_p(destination)+ end++ after do+ FileUtils.rm_rf(destination)+ end++ # `--force` skips collision check with dummy app constants.+ # `--migration` ensures Rails emits a migration even on re-runs.+ def run_generator(argv)+ described_class.start(argv + ['--force', '--migration'], destination_root: destination)++ model_path = Dir[File.join(destination, 'app/models/spree/*.rb')].first+ migration_path = Dir[File.join(destination, 'db/migrate/*.rb')].first++ {+ model: model_path && File.read(model_path),+ migration: migration_path && File.read(migration_path)+ }+ end++ describe 'model file' do+ it 'inherits from Spree.base_class by default' do+ result = run_generator(['Brand', 'name:string'])++ expect(result[:model]).to include('class Brand < Spree.base_class')+ end++ it 'lives under app/models/spree/ regardless of how the class is named' do+ run_generator(['Spree::Brand', 'name:string'])++ expect(File.exist?(File.join(destination, 'app/models/spree/brand.rb'))).to be true+ end++ it 'declares has_prefix_id derived from the snake_cased class name' do+ result = run_generator(['Brand', 'name:string'])++ expect(result[:model]).to include('has_prefix_id :brand')+ end++ it 'accepts an explicit --id-prefix override' do+ result = run_generator(['Brand', 'name:string', '--id-prefix=br'])++ expect(result[:model]).to include('has_prefix_id :br')+ end++ it 'adds acts_as_paranoid when --paranoid is set' do+ result = run_generator(['Brand', 'name:string', '--paranoid'])++ expect(result[:model]).to include('acts_as_paranoid')+ end++ it 'includes Metafields concerns when --metafields is set' do+ result = run_generator(['Brand', 'name:string', '--metafields'])++ expect(result[:model]).to include('include Spree::Metafields')+ expect(result[:model]).to include('include Spree::Metadata')+ end++ it 'declares the Ransack allowlist tuple (attributes, associations, scopes)' do+ result = run_generator(['Brand', 'name:string', 'active:boolean'])++ expect(result[:model]).to include('self.whitelisted_ransackable_attributes = %w[name active]')+ expect(result[:model]).to include('self.whitelisted_ransackable_associations = %w[]')+ expect(result[:model]).to include('self.whitelisted_ransackable_scopes = %w[]')+ end++ it 'adds presence validations for non-boolean scalar attributes' do+ result = run_generator(['Brand', 'name:string', 'active:boolean'])++ expect(result[:model]).to include('validates :name, presence: true')+ expect(result[:model]).not_to include('validates :active')+ end++ it 'adds uniqueness validation scoped to spree_base_uniqueness_scope for :uniq fields' do+ result = run_generator(['Brand', 'slug:string:uniq'])++ expect(result[:model]).to include('validates :slug, presence: true, uniqueness: { scope: spree_base_uniqueness_scope }')+ end+ end++ describe 'belongs_to class_name resolution' do+ it 'defaults to Spree::<CamelCasedName> when the attribute name has no special handling' do+ result = run_generator(['Variant', 'product:references'])++ expect(result[:model]).to include("belongs_to :product, class_name: 'Spree::Product'")+ end++ it 'resolves to Spree.user_class for user/user_id attributes' do+ result = run_generator(['UserPreference', 'user:references'])++ expect(result[:model]).to include('belongs_to :user, class_name: "::#{Spree.user_class}"')+ end++ it 'resolves to Spree.admin_user_class for admin-user-shaped column names' do+ result = run_generator(['Audit', 'admin_user:references', 'created_by:references', 'approver:references'])++ expect(result[:model]).to include('belongs_to :admin_user, class_name: "::#{Spree.admin_user_class}"')+ expect(result[:model]).to include('belongs_to :created_by, class_name: "::#{Spree.admin_user_class}"')+ expect(result[:model]).to include('belongs_to :approver, class_name: "::#{Spree.admin_user_class}"')+ end++ it 'respects an explicit class hint on the attribute spec' do+ result = run_generator(['Note', 'category:references{TaxonCategory}'])++ expect(result[:model]).to include("belongs_to :category, class_name: 'TaxonCategory'")+ end++ it 'omits class_name and emits polymorphic: true for polymorphic references' do+ result = run_generator(['Metafield', 'resource:references{polymorphic}'])++ expect(result[:model]).to include('belongs_to :resource, polymorphic: true')+ expect(result[:model]).not_to include('class_name:')+ end+ end++ describe 'migration file' do+ it 'targets the spree_<plural> table' do+ result = run_generator(['Brand', 'name:string'])++ expect(result[:migration]).to include('create_table :spree_brands')+ end++ it 'emits null: false on every scalar column' do+ result = run_generator(['Brand', 'name:string', 'active:boolean', 'rating:decimal'])++ expect(result[:migration]).to include('t.string :name, null: false')+ expect(result[:migration]).to include('t.boolean :active, null: false')+ expect(result[:migration]).to include('t.decimal :rating, null: false')+ end++ it 'explicitly sets foreign_key: false on t.references to match Spree conventions' do+ result = run_generator(['Variant', 'product:references'])++ expect(result[:migration]).to include('t.references :product, null: false, index: true, foreign_key: false')+ end++ it 'preserves polymorphic: true on polymorphic references' do+ result = run_generator(['Metafield', 'resource:references{polymorphic}'])++ expect(result[:migration]).to include('polymorphic: true')+ end++ it 'adds a deleted_at column + index when --paranoid is set' do+ result = run_generator(['Brand', 'name:string', '--paranoid'])++ expect(result[:migration]).to include('t.datetime :deleted_at')+ expect(result[:migration]).to include('add_index :spree_brands, :deleted_at')+ end++ it 'adds a unique index for :uniq fields' do+ result = run_generator(['Brand', 'slug:string:uniq'])++ expect(result[:migration]).to include('add_index :spree_brands, :slug, unique: true')+ end++ it 'does not add a foreign key constraint anywhere' do+ result = run_generator(['Variant', 'product:references', 'name:string'])++ expect(result[:migration]).not_to match(/foreign_key:\s*true/)+ expect(result[:migration]).not_to include('add_foreign_key')+ end+ end+end