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
Changed CLI commands to backend-neutral names (#14975)
Damian Legawiecf86d75c467ca
diff --git a/.changeset/backend-agnostic-cli.md b/.changeset/backend-agnostic-cli.mdnew file mode 100644index 0000000000..700b80d1a1--- /dev/null+++ b/.changeset/backend-agnostic-cli.md@@ -0,0 +1,6 @@+---+"@spree/cli": minor+"create-spree-app": patch+---++Renamed the CLI commands and flags that were named after Rails tools, so each command describes what it does rather than which Rails tool runs it. `spree test` replaces `spree rspec`, `spree add <extension>` replaces `spree bundle add`, `spree migrate:rollback --steps n` replaces `STEP=n`, `spree build --reset-deps` replaces `--reset-bundle`, and `spree plugin new` takes `--backend-name` / `--no-backend`. `spree rails`, `spree rake`, `spree bundle`, `spree routes`, `spree rspec` and the old flags still work and print a notice naming the replacement; they will be removed in Spree 7.0. `spree test` now creates the test database when it is missing, so the suite runs on a fresh project with no setup step. Also fixed the setup-link hint `spree init` printed, which named a command that does not exist.diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.mdindex b4380764f0..35f3667249 100644--- a/.github/CONTRIBUTING.md+++ b/.github/CONTRIBUTING.md@@ -404,19 +404,11 @@ A **Lefthook pre-commit hook** regenerates both whenever you commit a change toTo regenerate manually (useful when iterating on serializers before committing):```bash-cd server-pnpm exec spree rake typelizer:generate # regenerate TS types-cd ..-pnpm generate:zod # regenerate Zod schemas for every SDK+pnpm generate:types # regenerate TS types from the serializers+pnpm generate:zod # regenerate Zod schemas for every SDK```-If you'd rather avoid the Docker round-trip and have Ruby on your host, the native equivalent works too:--```bash-cd spree/api-bundle install-bundle exec rake typelizer:generate-```+`pnpm generate:types` runs with the Ruby on your machine, like the pre-commit hook, so run `bundle install` in `spree/api` once first.### Releasing packagesdiff --git a/docs/developer/agentic/llm-docs.mdx b/docs/developer/agentic/llm-docs.mdxindex 72308d7149..203c407d14 100644--- a/docs/developer/agentic/llm-docs.mdx+++ b/docs/developer/agentic/llm-docs.mdx@@ -55,4 +55,4 @@ Projects scaffolded with [create-spree-app](/developer/create-spree-app/quicksta## Generated agent instructions-`create-spree-app` scaffolds every project with an `AGENTS.md` that tells coding agents where the local docs live, how to inspect live data with `spree api`, and that every command goes through the [Spree CLI](/developer/cli/quickstart) — `spree migrate`, `spree console`, `spree rspec` — never `bin/rails`, `bundle` or `rake` directly. `server/AGENTS.md` adds the customization patterns to follow. Each directory also has a `CLAUDE.md` that imports its `AGENTS.md`, so Claude Code reads the same instructions as every other agent. The scaffold also installs the [agent skills](/developer/agentic/agent-skills) unless you opt out.+`create-spree-app` scaffolds every project with an `AGENTS.md` that tells coding agents where the local docs live, how to inspect live data with `spree api`, and that every command goes through the [Spree CLI](/developer/cli/quickstart) — `spree migrate`, `spree console`, `spree test` — never `bin/rails`, `bundle` or `rake` directly. `server/AGENTS.md` adds the customization patterns to follow. Each directory also has a `CLAUDE.md` that imports its `AGENTS.md`, so Claude Code reads the same instructions as every other agent. The scaffold also installs the [agent skills](/developer/agentic/agent-skills) unless you opt out.diff --git a/docs/developer/cli/quickstart.mdx b/docs/developer/cli/quickstart.mdxindex 75dccc1a3d..9195c63f9c 100644--- a/docs/developer/cli/quickstart.mdx+++ b/docs/developer/cli/quickstart.mdx@@ -69,27 +69,27 @@ spree stop### `spree restart`-Restart `web` and `worker` in place — same image, same volumes, fresh Rails process. Good for `config/initializers/*.rb` changes or anything Zeitwerk doesn't auto-reload.+Restart `web` and `worker` in place — same image, same volumes, fresh backend process. Good for configuration changes the backend doesn't reload on its own.```bashspree restart```-Not appropriate for Gemfile changes (use `spree bundle install`, then Ctrl+C and re-run `spree dev`), Dockerfile / `.ruby-version` changes (use `spree build`), or compose file changes (Ctrl+C and re-run `spree dev`).+Not appropriate for dependency changes (Ctrl+C and re-run `spree dev`), Dockerfile or runtime version changes (use `spree build`), or compose file changes (Ctrl+C and re-run `spree dev`).### `spree build`-Rebuild the dev image after Dockerfile or `.ruby-version` changes. Only relevant after `spree eject`.+Rebuild the dev image after Dockerfile or runtime version changes. Only relevant after `spree eject`.```bashspree build-spree build --reset-bundle # Also drop the bundle_cache volume so gems re-seed+spree build --reset-deps # Also drop the cached backend dependencies so they re-installspree build --yes # Skip confirmation prompts (for CI)```-`spree bundle add` does NOT require a rebuild — gems land in the `bundle_cache` volume which survives image rebuilds.+`spree add <extension>` does NOT require a rebuild — dependencies land in a cache volume which survives image rebuilds.-`--reset-bundle` only drops `bundle_cache`. Postgres, Redis, Meilisearch, and storage volumes are preserved.+`--reset-deps` only drops that cache. Postgres, Redis, Meilisearch, and storage volumes are preserved.### `spree upgrade`@@ -120,7 +120,7 @@ Production upgrades only need the data backfills — installing gems and migrati### `spree eject`-Switch from the prebuilt Docker image to building from your local `server/` directory. This lets you customize the Rails app — add gems, override models, add migrations, etc.+Switch from the prebuilt Docker image to building from your local `server/` directory. This lets you customize the backend — add extensions, override models, add migrations, etc.```bashspree eject@@ -184,7 +184,7 @@ spree logs worker # Worker service### `spree console`-Open a Rails console.+Open an interactive backend console.```bashspree console@@ -192,7 +192,7 @@ spree console### `spree shell`-Open an interactive bash shell inside the web container — the system-shell sibling of `spree console` (Rails) and `spree db:console` (psql). If the web container is down, it starts a one-off container against the same volumes instead. For one-off non-interactive commands, use `spree exec`.+Open an interactive bash shell inside the web container — the system-shell sibling of `spree console` and `spree db:console` (psql). If the web container is down, it starts a one-off container against the same volumes instead. For one-off non-interactive commands, use `spree exec`.```bashspree shell@@ -280,7 +280,7 @@ spree auth logout --profile prod## Dev workflow commands-These mirror the Rails commands you'd run if you were running the app directly on your host — but each is routed through `docker compose exec` against the running stack.+These commands run inside the project's containers against the running stack. The one exception is `spree filters types --from`, which reads a saved file and needs no running stack.### `spree generate`@@ -302,21 +302,24 @@ Generate TypeScript declarations for your app's list filters, so the SDKs accept```bashspree filters types # every app under apps/spree filters types --api store --out ../my-storefront/src/types/spree-filters.d.ts # one app elsewhere-spree filters types --from filter-tables.json # from `bin/rails spree:api:filter_tables` output+spree filters types --from filter-tables.json # from `spree task api:filter_tables` output```See [using your own filters from TypeScript](/developer/core-concepts/search-filtering#using-your-own-filters-from-typescript).### `spree migrate`-Install pending Spree migrations from gems, then run `db:migrate` — the canonical post-update sequence.+Install pending Spree migrations, then run them — the canonical post-update sequence.```bashspree migrate-spree migrate:status # show the migration log (`db:migrate:status`)-spree migrate:rollback STEP=2 # roll back (`db:rollback`)+spree migrate:status # show which migrations have run+spree migrate:rollback # roll back the last migration+spree migrate:rollback --steps 2 # roll back the last two```+`spree migrate:status` and `spree migrate:rollback` use the backend's own migration tooling, so they may change in a future major release. `spree migrate` itself stays the same.+### `spree db:reset`Drop, recreate, migrate, and seed the database. **Destructive** — wipes everything. Asks for confirmation.@@ -334,84 +337,41 @@ Open a `psql` session against the dev Postgres database (runs inside the `postgrspree db:console```-### `spree routes`--Show Rails routes. All flags pass through to `bin/rails routes`.--```bash-spree routes-spree routes -g products # Filter by pattern-spree routes -c Spree::Api::V3::Store::ProductsController # Filter by controller-spree routes --expanded-```--### `spree rspec`+### `spree test`-Run the RSpec test suite inside the web container with `RAILS_ENV=test`, so tests hit the `spree_test` database — never your development data. Everything after `rspec` passes through, so file paths, line numbers, and flags work as usual.+Run the backend test suite inside the web container against the test database — never your development data. Everything after `test` goes to the backend's test runner (RSpec today), so file paths, line numbers and flags follow that runner's format.```bash-spree rspec # full suite-spree rspec spec/models/spree/brand_spec.rb # one file-spree rspec spec/models/spree/brand_spec.rb:15 # one example-spree rspec --format documentation+spree test # full suite+spree test spec/models/spree/brand_spec.rb # one file+spree test spec/models/spree/brand_spec.rb:15 # one example+spree test --format documentation```-Before the first run, create the test database with `spree rails db:test:prepare`. See the [Testing tutorial](/developer/tutorial/testing) for writing specs.+The test database is created on the first run. See the [Testing tutorial](/developer/tutorial/testing) for writing specs.## Running things inside the container-These are passthrough commands — anything after the subcommand reaches the inner Rails/Bundle/Rake invocation as-is. Useful for ad-hoc commands that don't have a dedicated wrapper.--### `spree exec`--Run an arbitrary command inside the `web` container.--```bash-spree exec ls -la-spree exec env-spree exec ruby -v-```--### `spree rails`--Run a `bin/rails` command.--```bash-spree rails c # Console (alias of `spree console`)-spree rails routes -g products # Alias of `spree routes -g products`-spree rails runner "puts Spree::Product.count"-spree rails new_subcommand arg1 arg2-```--### `spree bundle`--Run a `bundle` command. Gems land in the `bundle_cache` volume (no image rebuild needed).--```bash-spree bundle install-spree bundle add faker-spree bundle update spree_core-spree bundle outdated-```--### `spree rake`+### `spree task`-Run a Rake task.+Run a Spree maintenance task. The task names are stable; anything after the name goes to the task in the task runner's own format.```bash-spree rake -T # List tasks-spree rake spree:upgrade # Run the version-specific data backfills-spree rake spree:upgrade DRY_RUN=1 # Same, plan only+spree task load_sample_data+spree task search:reindex+spree task price_history:seed+spree task price_history:prune```-### `spree task`+### `spree exec`-Shortcut for `bin/rails <task>` (Spree-style rake tasks registered as Rails tasks).+Run an arbitrary command inside the `web` container. Use it for anything without a dedicated command.```bash-spree task load_sample_data-spree task spree:price_history:seed-spree task spree:price_history:prune+spree exec ls -la+spree exec env+spree exec bin/rails runner "puts Spree::Product.count"+spree exec bundle outdated```## Pair with AI agentsdiff --git a/docs/developer/contributing/developing-spree.mdx b/docs/developer/contributing/developing-spree.mdxindex 7ab9ace753..292e9e6465 100644--- a/docs/developer/contributing/developing-spree.mdx+++ b/docs/developer/contributing/developing-spree.mdx@@ -82,7 +82,7 @@ Which command after which change:| Gem dependencies (gemspec / Gemfile / lock drift after `git pull`) | Nothing — the next `pnpm server:dev` boot self-heals via `bundle check || bundle install` (or `cd server && pnpm exec spree bundle install` while the stack runs) || Compose files / `server/.env` | `pnpm server:dev` (force-recreates the containers) || `server/Dockerfile` / `.ruby-version` / starter update that breaks the image build ("lockfile can't be updated because frozen") | `pnpm server:build`, then `pnpm server:dev` — the build script handles the edge-rewritten `Gemfile.lock` automatically |-| Meilisearch image bump ("database version … is incompatible") | Remove the `server_meilisearch_data` volume, boot, then reindex (`pnpm exec spree rake spree:search:reindex`) — the index is derived data |+| Meilisearch image bump ("database version … is incompatible") | Remove the `server_meilisearch_data` volume, boot, then reindex (`pnpm exec spree task search:reindex`) — the index is derived data || Broken beyond repair | `pnpm server:setup` (full reset — wipes the database and volumes) |Re-run `pnpm server:setup` **only** to fully reset — it does `docker compose down -v` + `rm -rf ./server`, wiping all DB data.@@ -310,19 +310,11 @@ A **Lefthook pre-commit hook** regenerates both whenever you commit a change toTo regenerate manually (useful when iterating on serializers before committing):```bash-cd server-pnpm exec spree rake typelizer:generate # regenerate TS types-cd ..-pnpm generate:zod # regenerate Zod schemas for every SDK+pnpm generate:types # regenerate TS types from the serializers+pnpm generate:zod # regenerate Zod schemas for every SDK```-If you'd rather avoid the Docker round-trip and have Ruby on your host, the native equivalent works too:--```bash-cd spree/api-bundle install-bundle exec rake typelizer:generate-```+`pnpm generate:types` runs with the Ruby on your machine, like the pre-commit hook, so run `bundle install` in `spree/api` once first.### Releasing packagesdiff --git a/docs/developer/core-concepts/data-privacy.mdx b/docs/developer/core-concepts/data-privacy.mdxindex f2f2aa2dbe..f55501a877 100644--- a/docs/developer/core-concepts/data-privacy.mdx+++ b/docs/developer/core-concepts/data-privacy.mdx@@ -228,7 +228,7 @@ defaults to 30 days via `price_history_retention_days`; prune with:<CodeGroup>```bash Spree CLI (Docker)-spree rake spree:price_history:prune+spree task price_history:prune``````bash Without Spree CLIdiff --git a/docs/developer/core-concepts/inventory.mdx b/docs/developer/core-concepts/inventory.mdxindex 0f6b498f85..45b15550ad 100644--- a/docs/developer/core-concepts/inventory.mdx+++ b/docs/developer/core-concepts/inventory.mdx@@ -56,7 +56,7 @@ Reserved and incoming are kept as counters rather than worked out on every read,<CodeGroup>```bash Spree CLI (Docker)-spree rake spree:stock:recount_levels+spree task stock:recount_levels``````bash Without Spree CLIdiff --git a/docs/developer/core-concepts/pricing.mdx b/docs/developer/core-concepts/pricing.mdxindex 2c785dd389..6987bdb0f1 100644--- a/docs/developer/core-concepts/pricing.mdx+++ b/docs/developer/core-concepts/pricing.mdx@@ -328,7 +328,7 @@ Retention defaults to 30 days, set per store with the `price_history_retention_d<CodeGroup>```bash Spree CLI (Docker)-spree rake spree:price_history:prune+spree task price_history:prune``````bash Without Spree CLI@@ -344,7 +344,7 @@ After enabling price history on an existing store, seed the current prices as a<CodeGroup>```bash Spree CLI (Docker)-spree rake spree:price_history:seed+spree task price_history:seed``````bash Without Spree CLIdiff --git a/docs/developer/create-spree-app/quickstart.mdx b/docs/developer/create-spree-app/quickstart.mdxindex 5e972515d9..ea38a45916 100644--- a/docs/developer/create-spree-app/quickstart.mdx+++ b/docs/developer/create-spree-app/quickstart.mdx@@ -141,7 +141,7 @@ The project includes [@spree/cli](/developer/cli/quickstart) for managing your SThe dashboard runs as its own dev server: `spree dev` starts it alongside the API at [http://localhost:5173](http://localhost:5173), live-reloading from `apps/dashboard/`. See the [dashboard docs](/developer/dashboard/overview).-No default admin account is created. On the first run, `spree dev` opens a one-time setup link where you create the admin account. If you missed it, print it again with `spree rails spree:setup:token`.+No default admin account is created. On the first run, `spree dev` opens a one-time setup link where you create the admin account. If you missed it, print it again with `spree task setup:token`.### Store APIdiff --git a/docs/developer/dashboard/plugins/scaffolding.mdx b/docs/developer/dashboard/plugins/scaffolding.mdxindex 64e44778c3..411737d7f7 100644--- a/docs/developer/dashboard/plugins/scaffolding.mdx+++ b/docs/developer/dashboard/plugins/scaffolding.mdx@@ -43,7 +43,7 @@ npx @spree/cli plugin new my-pluginThe CLI prompts for:- **Plugin name** — slug (kebab-case), used for package names and i18n keys-- **Ruby gem name** — only matters if you later add a Rails engine+- **Backend package name** — only matters if you later add a backend half- **Module name** — PascalCase, used as the React component prefix (`MyPluginCard`)- **npm scope** — e.g., `@acme`- **Author + email** — for `package.json` and `LICENSE`; prefilled from `git config user.name` / `user.email`@@ -53,7 +53,7 @@ Every prompt has a matching flag:```bashnpx @spree/cli plugin new my-plugin \- --ruby-name spree_my_plugin \+ --backend-name spree_my_plugin \--module-name MyPlugin \--npm-scope @acme \--author "Ada Lovelace" \@@ -68,7 +68,7 @@ For CI and scripted use, `-y` / `--yes` accepts the default for anything the flanpx @spree/cli plugin new my-plugin -y```-`--force` overwrites an existing directory. `--no-dashboard` and `--no-engine` are reserved for when engine scaffolding lands — today the dashboard package is the only half the CLI generates, so `--no-dashboard` leaves nothing to scaffold.+`--force` overwrites an existing directory. `--no-dashboard` and `--no-backend` are reserved for when backend scaffolding lands — today the dashboard package is the only half the CLI generates, so `--no-dashboard` leaves nothing to scaffold.## After scaffoldingdiff --git a/docs/developer/deployment/environment_variables.mdx b/docs/developer/deployment/environment_variables.mdxindex 4d6e7bfaab..308f6cb591 100644--- a/docs/developer/deployment/environment_variables.mdx+++ b/docs/developer/deployment/environment_variables.mdx@@ -178,7 +178,7 @@ Spree.search_provider = 'SpreeMeilisearch::SearchProvider'<CodeGroup>```bash Spree CLI (Docker)-spree rake spree:search:reindex+spree task search:reindex``````bash Without Spree CLIdiff --git a/docs/developer/how-to/build-a-marketplace.mdx b/docs/developer/how-to/build-a-marketplace.mdxindex 6a35b6ef58..51e2c0f699 100644--- a/docs/developer/how-to/build-a-marketplace.mdx+++ b/docs/developer/how-to/build-a-marketplace.mdx@@ -31,7 +31,7 @@ To try the flow quickly, you can seed a sample seller with an owner account, a p<CodeGroup>```bash Spree CLI-spree rake spree:sellers:sample_data+spree task sellers:sample_data``````bash Without CLIdiff --git a/docs/developer/tutorial/testing.mdx b/docs/developer/tutorial/testing.mdxindex e3d82a552b..64a6d3556e 100644--- a/docs/developer/tutorial/testing.mdx+++ b/docs/developer/tutorial/testing.mdx@@ -17,8 +17,8 @@ server/spec/controllers/spree/api/v3/admin/brands_controller_spec.rbYou can now run them, a directory or a single file at a time:```bash-spree rspec spec/controllers/spree/api/v3/-spree rspec spec/models/spree/brand_spec.rb+spree test spec/controllers/spree/api/v3/+spree test spec/models/spree/brand_spec.rb```## The dashboard@@ -104,7 +104,7 @@ Two conventions matter here:Run what you changed, not everything:```bash-spree rspec spec/models/spree/brand_spec.rb # the backend+spree test spec/models/spree/brand_spec.rb # the backendcd apps/dashboard && pnpm test # the dashboard```diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdxindex c921713f53..6eb1431e0c 100644--- a/docs/developer/upgrades/5.6-to-6.0.mdx+++ b/docs/developer/upgrades/5.6-to-6.0.mdx@@ -91,8 +91,8 @@ Reference material — the data backfills `bundle exec rake spree:upgrade` execu<CodeGroup>```bash Spree CLI (Docker)-spree rake spree:upgrade:preferences_json-spree rake spree:upgrade:encrypt_secret_preferences+spree task upgrade:preferences_json+spree task upgrade:encrypt_secret_preferences``````bash Without Spree CLI@@ -306,7 +306,7 @@ Recreate the containers so they pick up the new `.env` (`spree dev` — `spree rNever change or lose the keys once data is encrypted — the encrypted records become unreadable.</Warning>-**3. Encrypt existing rows.** Rows written before the keys were set are plain text. Gateway and integration secrets and the OAuth tokens on user identities stay readable and are encrypted on their next write; run `spree rake spree:upgrade:encrypt_secret_preferences` (`bundle exec rake spree:upgrade:encrypt_secret_preferences` without the Spree CLI) to encrypt every gateway and integration secret at once. Webhook endpoint secrets and gateway customer IDs can't be read in plain text once encryption is on — follow [Enabling encryption on an existing installation](/developer/deployment/environment_variables#enabling-encryption-on-an-existing-installation): turn on `support_unencrypted_data` and `extend_queries`, deploy with the keys, run `find_each(&:encrypt)` over `Spree::WebhookEndpoint`, `Spree::GatewayCustomer` and `Spree::UserIdentity`, then turn the two settings off again.+**3. Encrypt existing rows.** Rows written before the keys were set are plain text. Gateway and integration secrets and the OAuth tokens on user identities stay readable and are encrypted on their next write; run `spree task upgrade:encrypt_secret_preferences` (`bundle exec rake spree:upgrade:encrypt_secret_preferences` without the Spree CLI) to encrypt every gateway and integration secret at once. Webhook endpoint secrets and gateway customer IDs can't be read in plain text once encryption is on — follow [Enabling encryption on an existing installation](/developer/deployment/environment_variables#enabling-encryption-on-an-existing-installation): turn on `support_unencrypted_data` and `extend_queries`, deploy with the keys, run `find_each(&:encrypt)` over `Spree::WebhookEndpoint`, `Spree::GatewayCustomer` and `Spree::UserIdentity`, then turn the two settings off again.## Preferences are stored as JSON@@ -330,7 +330,7 @@ Model preferences moved from YAML to JSON, and secrets moved out of them. Declar- **Per-preference helper methods are gone.** Use `preference_type(:name)`, `preference_default(:name)` and `preference_deprecated(:name)` instead of `preferred_<name>_type`, `preferred_<name>_default` and `preferred_<name>_deprecated`. `clear_preferences`, `restore_preferences_for`, `preferences_of_type`, the class methods `preference_getter_method`, `preference_setter_method` and `prefers_query_method`, `Spree::Preferences::ScopedStore`, `Spree::Preferences::Store` and the `Spree::Preference` model are removed.- **The `spree_preferences` table is dropped.** The installation id it held is not carried over: the default store generates a new one the next time it is saved. Rows an application wrote there itself are dropped with it: copy any you need before upgrading.- **Preferences live only on models.** `Spree::Preferences::Preferable` is included by `Spree::Base` and needs a `preferences` JSON column; including it in a plain Ruby class is no longer supported. A hash stored inside a preference comes back with string keys.-- **A record whose preferences still hold YAML cannot be read.** The migration converts every row, so this only happens to rows written by older code after it ran. Run `spree rake spree:upgrade:preferences_json` (`bundle exec rake spree:upgrade:preferences_json` without the Spree CLI) to convert it.+- **A record whose preferences still hold YAML cannot be read.** The migration converts every row, so this only happens to rows written by older code after it ran. Run `spree task upgrade:preferences_json` (`bundle exec rake spree:upgrade:preferences_json` without the Spree CLI) to convert it.## The Cart/Order split@@ -989,7 +989,7 @@ Other changes that come with it:<CodeGroup>```bash Spree CLI (Docker)-spree rake spree:money:audit_capture_events+spree task money:audit_capture_events``````bash Without Spree CLIdiff --git a/docs/integrations/analytics/google-analytics.mdx b/docs/integrations/analytics/google-analytics.mdxindex fbb8826ae2..e5d4312447 100644--- a/docs/integrations/analytics/google-analytics.mdx+++ b/docs/integrations/analytics/google-analytics.mdx@@ -19,7 +19,7 @@ Before you can enable Google Analytics 4, it must be installed. To do so, you ne<CodeGroup>```bash Spree CLI (Docker)-spree bundle add spree_google_analytics && spree generate spree_google_analytics:install+spree add --gem spree_google_analytics``````bash Without Spree CLIdiff --git a/docs/integrations/analytics/google-tag-manager.mdx b/docs/integrations/analytics/google-tag-manager.mdxindex 04fd23a920..cd6f1d1a49 100644--- a/docs/integrations/analytics/google-tag-manager.mdx+++ b/docs/integrations/analytics/google-tag-manager.mdx@@ -29,7 +29,7 @@ Before you can enable Google Tag Manager, it must be installed. To do so, you ne<CodeGroup>```bash Spree CLI (Docker)-spree bundle add spree_google_analytics && spree generate spree_google_analytics:install+spree add --gem spree_google_analytics``````bash Without Spree CLIdiff --git a/docs/integrations/payments/razorpay.mdx b/docs/integrations/payments/razorpay.mdxindex a7285b41bc..8a456cb174 100644--- a/docs/integrations/payments/razorpay.mdx+++ b/docs/integrations/payments/razorpay.mdx@@ -19,7 +19,7 @@ Before you can enable Razorpay, it must be installed. To do so, you need to run<CodeGroup>```bash Spree CLI (Docker)-spree bundle add spree_razorpay_checkout && spree generate spree_razorpay_checkout:install+spree add --gem spree_razorpay_checkout``````bash Without Spree CLIdiff --git a/docs/integrations/search/meilisearch.mdx b/docs/integrations/search/meilisearch.mdxindex 60cfad9a2b..3894d4f668 100644--- a/docs/integrations/search/meilisearch.mdx+++ b/docs/integrations/search/meilisearch.mdx@@ -90,7 +90,7 @@ Spree.search_provider = 'SpreeMeilisearch::SearchProvider'<CodeGroup>```bash Spree CLI (Docker)-spree rake spree:search:reindex+spree task search:reindex``````bash Without Spree CLI@@ -160,7 +160,7 @@ Each store gets its own Meilisearch index: `{store_code}_products`. For a store<CodeGroup>```bash Spree CLI (Docker)-spree rake spree:search:reindex+spree task search:reindex``````bash Without Spree CLIdiff --git a/docs/plans/6.0-backend-agnostic-cli.md b/docs/plans/6.0-backend-agnostic-cli.mdnew file mode 100644index 0000000000..00b3f2ecf9--- /dev/null+++ b/docs/plans/6.0-backend-agnostic-cli.md@@ -0,0 +1,65 @@+# Backend-Agnostic CLI++**Status:** In Progress — 6.x renames, deprecation notices and the backend adapter are in; removing the deprecated names is left for Spree 7.0+**Target:** Spree 6.0 (renames + deprecations), Spree 7.0 (removals)+**Depends on:** `5.5-admin-api-cli.md`, `6.0-cli-configurator.md`, `6.0-cli-add-extensions.md`+**Author:** Damian Legawiec+**Last updated:** 2026-10-26+**Tracking:** Linear — · GitHub —++## Summary+The `spree` CLI is the main way developers drive a project, and several of its commands, flags and help texts were named after Rails tools (`spree rails`, `spree rake`, `spree bundle`, `spree rspec`, `spree routes`, `--reset-bundle`, `--ruby-name`). This plan makes the CLI's public surface describe *what* a developer wants (run tests, run a task, add an extension) rather than *which Rails tool* does it, so the commands stay the same however the backend runs them. Rails-named commands keep working through 6.x with a deprecation notice and are removed in Spree 7.0.++## Key Decisions (do not deviate without discussion)+- **The neutral command is the contract; the backend is an implementation detail.** Every Rails invocation the CLI makes lives in `packages/cli/src/backend.ts`. Changing how the backend runs an operation means changing that file; command files do not change.+- **Deprecate, never break, in 6.x.** Old names stay registered as hidden commands or hidden flags, keep their exact behaviour, and print one line to stderr naming the replacement. stderr keeps captured output (`$(spree …)`) clean.+- **`spree exec` is the only escape hatch.** Anything only meaningful on Rails (`bin/rails runner`, `bundle outdated`) is reached as `spree exec bin/rails …`. No other Rails-named command is added.+- **Extensions are installed with `spree add <extension>`** (decided 2026-10-01), built by `6.0-cli-add-extensions.md`: catalog names (`spree add stripe`), or `spree add --gem <gem>` outside the catalog. The deprecation notice for `spree bundle add` points at whichever of the two applies.+- **`spree generate` keeps every generator** (decided 2026-10-26). The command name is already neutral; only the generator names are Rails ideas, and the docs still teach decorators, subscribers and migrations as the way to customize Spree 6. No generator prints a notice, and docs never route a generator through `spree exec`. Spree 7.0 drops the generators that do not apply to it.+- **`spree task <name>` is kept and its task names become public.** The documented task names (`search:reindex`, `load_sample_data`, `setup:token`, `price_history:seed`, `channels:full_upgrade`) are part of the CLI's contract.+- **`spree rspec` becomes `spree test`.** The name says what it does, not which runner does it.+- **Command names are the contract; pass-through arguments are not.** Arguments after `spree test` and `spree task <name>` belong to the backend's own test and task runners (RSpec file paths and flags, Rake `KEY=value` values), so they can change when the backend does. Docs say so, and no script should depend on them across a major release.+- **`migrate:status` and `migrate:rollback` are not guaranteed beyond the current backend.** They map onto the backend's migration tooling, which may not offer status or down migrations. `spree migrate` (apply pending migrations) is the guaranteed part.+- **Encryption key names are frozen.** `spree encryption init` writes `ACTIVE_RECORD_ENCRYPTION_*` into `.env`. Data encrypted with them is unreadable without them, so these names are never renamed.++## Design Details++### Command mapping++| Deprecated in 6.0 | Replacement |+| --- | --- |+| `spree rails …` | `spree exec bin/rails …` |+| `spree rake spree:<x> …` | `spree task <x> …` |+| `spree rake <other> …` | `spree exec bin/rake …` |+| `spree bundle add <gem>` | `spree add <extension>` or `spree add --gem <gem>` |+| `spree bundle <other> …` | `spree exec bundle …` |+| `spree rspec …` | `spree test …` |+| `spree routes` | `spree api endpoints`, or `spree exec bin/rails routes …` to filter Rails routes |+| `spree migrate <raw args>` | `spree migrate` |+| `spree migrate:rollback STEP=n` | `spree migrate:rollback --steps n` |+| `spree build --reset-bundle` | `spree build --reset-deps` |+| `spree plugin new --ruby-name` | `--backend-name` |+| `spree plugin new --no-engine` | `--no-backend` |++### Unchanged names, swappable internals+`init`, `dev`, `stop`, `restart`, `logs`, `open`, `eject`, `build`, `seed`, `sample-data`, `user create`, `api-key`, `console`, `shell`, `exec`, `task`, `test`, `migrate`, `migrate:status`, `migrate:rollback`, `db:reset`, `db:console`, `upgrade`, `encryption`, `api`, `auth`, `completion`. Their help text no longer mentions Rails, Rake, Bundler, Puma or Active Record.++### Backend adapter+`src/backend.ts` builds the command each neutral operation runs in the app container: console, test run, Spree task, seed, migrate, rollback, migration status, database reset, generator, extension install. Captured tasks (`spree:cli:*`, used by `init`, `user create` and `api-key`) and the extension installer's gem, generator and migration steps go through the same module.++## Migration Path+1. **6.0** — neutral names, hidden deprecated aliases with notices, backend adapter, docs switched to neutral names.+2. **6.x** — move `user create` and `api-key list/revoke` onto the Admin API (`spree api` transport), which makes them backend-neutral without an adapter. `init` keeps a backend task for the first key.+3. **7.0** — remove the deprecated commands and flags.++## Constraints on Current Work+- Do not add CLI commands, flags or help text named after a Rails tool. New backend operations go into `src/backend.ts` behind a neutral command.+- Docs show neutral commands only. Rails-only steps use `spree exec bin/rails …`.+- New Spree rake tasks that developers run by hand belong in the `spree:` namespace so `spree task` reaches them, and their names are treated as public.+- Do not rename or stop reading the `ACTIVE_RECORD_ENCRYPTION_*` variables.++## References+- `5.5-admin-api-cli.md` — `spree api` transport+- `6.0-cli-configurator.md` — configuration through the Admin API, not Ruby+- `6.0-cli-add-extensions.md` — `spree add <extension>`+- `packages/cli/src/backend.ts`diff --git a/package.json b/package.jsonindex 0273e7268e..88fd9bd769 100644--- a/package.json+++ b/package.json@@ -6,6 +6,7 @@"dev": "turbo dev","build": "turbo build","test": "turbo test",+ "generate:types": "cd spree/api && bundle exec rake typelizer:generate","generate:zod": "pnpm --recursive --filter \"./packages/*\" run generate:zod","generate:filters": "pnpm --recursive --filter \"./packages/*\" run generate:filters","generate:params": "pnpm --recursive --filter \"./packages/*\" run generate:params",@@ -26,7 +27,7 @@"server:teardown": "bash scripts/server-teardown.sh","server:console": "cd server && spree console","server:logs": "cd server && spree logs",- "server:seed": "cd server && spree rails db:seed",+ "server:seed": "cd server && spree seed","server:load_sample_data": "cd server && spree task load_sample_data","dashboard:dev": "turbo build --filter='@spree/dashboard-starter^...' && pnpm --dir packages/dashboard-starter dev --port 5173 --strictPort","seller:dev": "turbo build --filter='@spree/seller-dashboard-starter^...' && pnpm --dir packages/seller-dashboard-starter dev --port 5174 --strictPort",diff --git a/packages/cli/README.md b/packages/cli/README.mdindex abebfdf93e..8f5f5f75a2 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -17,19 +17,22 @@ Run from your Spree project directory:|---------|-------------|| `spree dev` | Run the app in the foreground — streams logs, Ctrl+C stops it. First run completes setup automatically; co-runs the Admin Dashboard dev server when `apps/dashboard` exists and opens the dashboard in the browser once it is ready (`--no-open` skips it) || `spree stop` | Stop backend services |-| `spree upgrade` | Upgrade Spree — the server (image or gems), `@spree/*` packages, migrations and data backfills |+| `spree upgrade` | Upgrade Spree — the server, `@spree/*` packages, migrations and data backfills || `spree eject` | Switch from the prebuilt image to building from `backend/` || `spree add dashboard` | Add the Admin Dashboard to an existing project, to customize it || `spree add seller-dashboard` | Add the marketplace seller panel to an existing project |+| `spree add <extension>` | Install an extension end to end (e.g. `spree add stripe`) || `spree add ai` | Install the Spree agent skills and connect coding agents to the Spree docs MCP server || `spree build --production` | Build the production image — the Spree API plus your dashboard, in one |-| `spree console` / `spree shell` / `spree logs` | Rails console, container shell, log tailing |+| `spree console` / `spree shell` / `spree logs` | Backend console, container shell, log tailing || `spree migrate` / `spree seed` / `spree sample-data` | Database tasks || `spree generate …` | Spree generators (models, API resources, subscribers, migrations) |+| `spree task <name>` | Run a Spree maintenance task (e.g. `search:reindex`) || `spree user create` / `spree api-key …` | Admin users and scoped API keys |-| `spree encryption init` | Add Active Record encryption keys to `.env` (`--print` to only print a set) |+| `spree encryption init` | Add encryption keys to `.env` (`--print` to only print a set) || `spree api get/post/patch/delete <path>` | Call the Admin API directly (`spree api endpoints` lists routes + scopes) |-| `spree rspec` | Run the backend test suite inside the container |+| `spree test` | Run the backend test suite inside the container |+| `spree exec <command>` | Run any other command inside the container |## Documentationdiff --git a/packages/cli/src/backend.ts b/packages/cli/src/backend.tsnew file mode 100644index 0000000000..e3cf9a8198--- /dev/null+++ b/packages/cli/src/backend.ts@@ -0,0 +1,100 @@+// The only place the CLI speaks Rails. Commands say what they want (a console,+// a task, a migration) and this module says how the backend does it, so+// changing the backend means changing this file rather than every command.+// See docs/plans/6.0-backend-agnostic-cli.md.++/** A task by its full backend name, e.g. `db:seed` or `spree:cli:create_admin`. */+export function backendTaskCommand(task: string, args: string[] = []): string[] {+ return railsCommand([task, ...args])+}++/** A Spree maintenance task, named without its `spree:` namespace (`search:reindex`). */+export function spreeTask(name: string): string {+ return `spree:${name}`+}++export function taskCommand(name: string, args: string[] = []): string[] {+ return backendTaskCommand(spreeTask(name), args)+}++export const CONSOLE = railsCommand(['console'])++export const SEED_TASK = 'db:seed'++export const MIGRATE = railsCommand([spreeTask('install:migrations'), 'db:migrate'])++export const MIGRATE_STATUS = backendTaskCommand('db:migrate:status')++export const DATABASE_RESET = railsCommand([+ 'db:drop',+ 'db:create',+ spreeTask('install:migrations'),+ 'db:migrate',+ SEED_TASK,+])++export const UPGRADE = taskCommand('upgrade')++export const PREPARE_DATABASE = backendTaskCommand('db:prepare')++export const TEST_ENV = { RAILS_ENV: 'test' }++// Creates the test database first, so the suite runs on a fresh project; the+// test helper loads the schema into it. Not `db:prepare`, which would seed a+// newly created database. VERBOSE=false silences "already exists" while a real+// failure still prints and stops the run.+export function testCommand(args: string[]): string[] {+ return [+ 'sh',+ '-c',+ 'VERBOSE=false bin/rails db:create && exec bundle exec rspec "$@"',+ 'spree test',+ ...args,+ ]+}++export function rollbackCommand(steps?: number, args: string[] = []): string[] {+ return backendTaskCommand('db:rollback', [...(steps ? [`STEP=${steps}`] : []), ...args])+}++export function addPackageCommand(name: string): string[] {+ return bundleCommand(['add', name])+}++export function updatePackagesCommand(names: string[]): string[] {+ return bundleCommand(['update', ...names])+}++export const LIST_PACKAGES = bundleCommand(['list', '--name-only'])++export const INSTALL_PACKAGES = bundleCommand(['install'])++export const LIST_GENERATORS = railsCommand(['generate', '--help'])++/** The install generator an extension ships, e.g. `spree_stripe:install`. */+export function extensionInstallGenerator(name: string): string {+ return `${name}:install`+}++export function runGeneratorCommand(generator: string, args: string[] = []): string[] {+ return railsCommand(['generate', generator, ...args])+}++// The raw tools, used directly only by the deprecated pass-through commands+// (`spree rails`, `spree rake`, `spree bundle`, `spree routes`).++export function railsCommand(args: string[]): string[] {+ return ['bin/rails', ...args]+}++export function rakeCommand(args: string[]): string[] {+ return ['bin/rake', ...args]+}++export function bundleCommand(args: string[]): string[] {+ return ['bundle', ...args]+}++export function routesCommand(args: string[]): string[] {+ return railsCommand(['routes', ...args])+}diff --git a/packages/cli/src/commands/add-extension.ts b/packages/cli/src/commands/add-extension.tsindex 019e47dd10..ca52344616 100644--- a/packages/cli/src/commands/add-extension.ts+++ b/packages/cli/src/commands/add-extension.ts@@ -3,6 +3,13 @@ import path from 'node:path'import * as p from '@clack/prompts'import { execa } from 'execa'import pc from 'picocolors'+import {+ addPackageCommand,+ extensionInstallGenerator,+ LIST_GENERATORS,+ MIGRATE,+ runGeneratorCommand,+} from '../backend.js'import { findApiDir, isEjectedProject } from '../context.js'import { dockerComposeCapture, dockerComposeExecOrRun, restartAppServices } from '../docker.js'import {@@ -103,10 +110,7 @@ async function installGem(if (!listed) await bundleAdd(ctx.projectDir, apiPath, gem, extension.release)await runInstallGenerator(ctx.projectDir, gem, listed)p.log.step('Running migrations...')- await dockerComposeExecOrRun(- ['bin/rails', 'spree:install:migrations', 'db:migrate'],- ctx.projectDir,- )+ await dockerComposeExecOrRun(MIGRATE, ctx.projectDir)} catch (error) {if (restore) {restore()@@ -134,7 +138,7 @@ async function bundleAdd(gem: string,release: Extension['release'],): Promise<void> {- const args = ['bundle', 'add', gem]+ const args = addPackageCommand(gem)// Unpinned, Bundler picks the newest stable release, which for a gem that// moved into Spree is its old pre-6.0 line.if (release === 'spree') {@@ -156,15 +160,15 @@ async function runInstallGenerator(gem: string,keepExisting: boolean,): Promise<void> {- const generator = `${gem}:install`- const help = await dockerComposeCapture(['bin/rails', 'generate', '--help'], projectDir)+ const generator = extensionInstallGenerator(gem)+ const help = await dockerComposeCapture(LIST_GENERATORS, projectDir)const listed = help.split('\n').some((line) => line.trim() === generator)if (!listed) returnp.log.step(`Running ${pc.bold(generator)}...`)// On a repair, files the first run wrote (and the developer may have// edited) are kept rather than stopping at Thor's overwrite prompt.- const args = ['bin/rails', 'generate', generator, ...(keepExisting ? ['--skip'] : [])]+ const args = runGeneratorCommand(generator, keepExisting ? ['--skip'] : [])await dockerComposeExecOrRun(args, projectDir)}diff --git a/packages/cli/src/commands/api-key.ts b/packages/cli/src/commands/api-key.tsindex 0d92fc6e1b..495a324675 100644--- a/packages/cli/src/commands/api-key.ts+++ b/packages/cli/src/commands/api-key.ts@@ -2,9 +2,10 @@ import * as p from '@clack/prompts'import type { Command } from 'commander'import { printTable } from 'console-table-printer'import pc from 'picocolors'+import { spreeTask } from '../backend.js'import { mintApiKey } from '../config.js'import { detectProject } from '../context.js'-import { rakeTask } from '../docker.js'+import { captureTask } from '../docker.js'export function registerApiKeyCommand(program: Command): void {const apiKey = program.command('api-key').description('Manage API keys')@@ -114,7 +115,7 @@ export function registerApiKeyCommand(program: Command): void {const s = p.spinner()s.start('Fetching API keys...')- const stdout = await rakeTask('spree:cli:list_api_keys', ctx.projectDir)+ const stdout = await captureTask(spreeTask('cli:list_api_keys'), ctx.projectDir)s.stop('')const lines = stdout.trim().split('\n').filter(Boolean)@@ -149,7 +150,7 @@ export function registerApiKeyCommand(program: Command): void {const s = p.spinner()s.start('Revoking API key...')- const stdout = await rakeTask('spree:cli:revoke_api_key', ctx.projectDir, {+ const stdout = await captureTask(spreeTask('cli:revoke_api_key'), ctx.projectDir, {ID: id,})const name = stdout.trim()diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.tsindex 06dd9bd968..d8eb79c81d 100644--- a/packages/cli/src/commands/build.ts+++ b/packages/cli/src/commands/build.ts@@ -1,17 +1,19 @@import fs from 'node:fs'import path from 'node:path'import * as p from '@clack/prompts'-import type { Command } from 'commander'+import { type Command, Option } from 'commander'import { execa } from 'execa'import pc from 'picocolors'import { detectProject, findApiDir, hasMonorepoSpreePath, isEjectedProject } from '../context.js'+import { warnDeprecated } from '../deprecation.js'import { appServices, dockerCompose } from '../docker.js'export function registerBuildCommand(program: Command): void {program.command('build')- .description('Rebuild the dev image (after Dockerfile / .ruby-version changes)')- .option('--reset-bundle', 'also wipe the bundle_cache volume to re-seed gems')+ .description('Rebuild the dev image (after Dockerfile or runtime version changes)')+ .option('--reset-deps', 'also wipe the cached backend dependencies so they re-install')+ .addOption(new Option('--reset-bundle').hideHelp()).option('--yes', 'skip confirmation prompts (for CI)').option('--production',@@ -20,6 +22,7 @@ export function registerBuildCommand(program: Command): void {.option('--tag <tag>', 'image tag for --production (default: <project>-spree:latest)').action(async (flags: {+ resetDeps?: booleanresetBundle?: booleanyes?: booleanproduction?: boolean@@ -29,12 +32,14 @@ export function registerBuildCommand(program: Command): void {await buildProductionImage(detectProject().projectDir, flags.tag)return}- await buildDevImage(flags)+ if (flags.resetBundle)+ warnDeprecated('spree build --reset-bundle', 'spree build --reset-deps')+ await buildDevImage({ ...flags, resetDeps: flags.resetDeps || flags.resetBundle })},)}-async function buildDevImage(flags: { resetBundle?: boolean; yes?: boolean }): Promise<void> {+async function buildDevImage(flags: { resetDeps?: boolean; yes?: boolean }): Promise<void> {const ctx = detectProject()if (hasMonorepoSpreePath(ctx.projectDir)) {@@ -60,11 +65,11 @@ async function buildDevImage(flags: { resetBundle?: boolean; yes?: boolean }): Pprocess.exit(1)}- if (flags.resetBundle) {+ if (flags.resetDeps) {if (!flags.yes) {const confirmed = await p.confirm({message:- 'Wipe the bundle_cache volume? Any gems added via `spree bundle add` since the last image build will be lost.',+ 'Wipe the cached backend dependencies? Any extensions added via `spree add` since the last image build will be lost.',initialValue: false,})if (p.isCancel(confirmed) || !confirmed) {@@ -106,8 +111,8 @@ async function buildDevImage(flags: { resetBundle?: boolean; yes?: boolean }): Pp.note([`Image rebuilt. Start the stack with ${pc.bold('spree dev')}.`,- flags.resetBundle- ? `On next boot, gems will re-seed into a fresh ${pc.dim('bundle_cache')} volume.`+ flags.resetDeps+ ? `On next boot, dependencies will re-seed into a fresh ${pc.dim('bundle_cache')} volume.`: '',].filter(Boolean)diff --git a/packages/cli/src/commands/bundle.ts b/packages/cli/src/commands/bundle.tsindex 6f8c6cc6ed..4ed9a84612 100644--- a/packages/cli/src/commands/bundle.ts+++ b/packages/cli/src/commands/bundle.ts@@ -1,12 +1,12 @@import type { Command } from 'commander'+import { bundleCommand } from '../backend.js'import { detectProject } from '../context.js'+import { warnDeprecated } from '../deprecation.js'import { dockerComposeExecOrRun } from '../docker.js'+import { addCommandFor } from '../lib/extensions.js'-// Run bundler inside the web container. Gems install into the bundle_cache-// volume and persist across container restarts without an image rebuild.-// spree bundle add stripe-// spree bundle update spree spree_api-// spree bundle outdated+// Deprecated: extensions are installed with `spree add`, anything else goes+// through `spree exec bundle …`.//// Gemfile.lock drift crashes the containers before `exec` can reach them —// exactly the state where bundler is needed most — so when web is down we fall@@ -14,14 +14,22 @@ import { dockerComposeExecOrRun } from '../docker.js'// volume so gems land where the next boot expects them.export function registerBundleCommand(program: Command): void {program- .command('bundle')- .description('Run a bundler command (`bundle …`) inside the web container')+ .command('bundle', { hidden: true })+ .description('Deprecated: use `spree add <extension>` or `spree exec bundle …`').argument('<args...>', 'arguments to pass to bundle').allowUnknownOption(true).passThroughOptions(true).action(async (args: string[]) => {+ // A bare `bundle add <gem>` maps onto `spree add`; any extra option+ // (a version, a source) only survives through `spree exec`.+ const gem =+ args[0] === 'add' && args.length === 2 && !args[1].startsWith('-') ? args[1] : undefined+ warnDeprecated(+ 'spree bundle',+ gem ? addCommandFor(gem) : `spree exec bundle ${args.join(' ')}`,+ )const ctx = detectProject()- await dockerComposeExecOrRun(['bundle', ...args], ctx.projectDir, {+ await dockerComposeExecOrRun(bundleCommand(args), ctx.projectDir, {edgeHint: 'the edge stack heals gem drift on boot',})})diff --git a/packages/cli/src/commands/console.ts b/packages/cli/src/commands/console.tsindex a8472dd5d3..f6dc4f33c6 100644--- a/packages/cli/src/commands/console.ts+++ b/packages/cli/src/commands/console.ts@@ -1,17 +1,18 @@import type { Command } from 'commander'+import { CONSOLE } from '../backend.js'import { detectProject } from '../context.js'import { dockerComposeExecOrRun } from '../docker.js'export function registerConsoleCommand(program: Command): void {program.command('console')- .description('Open Rails console')+ .description('Open an interactive backend console').action(async () => {const ctx = detectProject()// When web is down — a crash-looping container is exactly when an// inspection console is most useful — fall back to a one-off `compose run`// console against the same warm DB (its depends_on health-waits postgres).- await dockerComposeExecOrRun(['bin/rails', 'console'], ctx.projectDir, {+ await dockerComposeExecOrRun(CONSOLE, ctx.projectDir, {edgeHint: 'then open the console',})})diff --git a/packages/cli/src/commands/db.ts b/packages/cli/src/commands/db.tsindex 070249bb03..098e015990 100644--- a/packages/cli/src/commands/db.ts+++ b/packages/cli/src/commands/db.ts@@ -1,6 +1,7 @@import * as p from '@clack/prompts'import type { Command } from 'commander'import pc from 'picocolors'+import { DATABASE_RESET } from '../backend.js'import { detectProject, hasMonorepoSpreePath } from '../context.js'import {appServices,@@ -11,15 +12,6 @@ import {isServiceRunning,} from '../docker.js'-export const RESET_TASK = [- 'bin/rails',- 'db:drop',- 'db:create',- 'spree:install:migrations',- 'db:migrate',- 'db:seed',-]-export function registerDbCommand(program: Command): void {program.command('db:reset')@@ -58,8 +50,8 @@ export function registerDbCommand(program: Command): void {}}- // The long-running web (Rails) + worker (Sidekiq) containers hold pooled- // connections to spree_development. Rails' db:drop issues a PLAIN+ // The long-running web + worker containers hold pooled+ // connections to spree_development. The drop issues a PLAIN// `DROP DATABASE` (no WITH FORCE), which PostgreSQL rejects while any other// session is connected — so a reset against a running stack deadlocks. We// stop both regardless of which is up (the worker alone holds up to@@ -92,7 +84,7 @@ export function registerDbCommand(program: Command): void {// for service_healthy) but never restarts web/worker, so nothing reopens// a blocking connection. Works whether the stack was up, down, or partial.// captureStderr so the Postgres "being accessed" error below is matchable.- await dockerComposeRun(RESET_TASK, ctx.projectDir, { captureStderr: true })+ await dockerComposeRun(DATABASE_RESET, ctx.projectDir, { captureStderr: true })} catch (err) {const stderr = String((err as { stderr?: string }).stderr ?? (err as Error).message ?? '')if (/being accessed by other users|55006/.test(stderr)) {diff --git a/packages/cli/src/commands/eject.ts b/packages/cli/src/commands/eject.tsindex 0bd2bb4697..7fb0bb8bca 100644--- a/packages/cli/src/commands/eject.ts+++ b/packages/cli/src/commands/eject.ts@@ -11,12 +11,12 @@ import { dockerCompose, prepareDatabase } from '../docker.js'// edits reload via Zeitwerk on next request, no rebuild needed.//// Image rebuilds (`spree build`) are only required for Dockerfile or-// .ruby-version changes; gem changes go through `spree bundle add` and-// persist in the bundle_cache volume.+// .ruby-version changes; extensions go through `spree add` and persist in+// the bundle_cache volume.export function registerEjectCommand(program: Command) {program.command('eject')- .description('Switch to the dev compose: bind-mount the Rails app with hot reload')+ .description('Switch to the dev compose: bind-mount the backend source with hot reload').action(async () => {await ejectProject(detectProject().projectDir)})@@ -76,17 +76,17 @@ export async function ejectProject(projectDir: string): Promise<void> {p.note([- `The Rails API is now bind-mounted from ${pc.bold(`./${apiDir}`)} — edits are live.`,+ `The backend is now bind-mounted from ${pc.bold(`./${apiDir}`)} — edits are live.`,'',`The dev stack uses its own ${pc.bold('spree_development')} database (just`,`created and seeded). Load demo products with ${pc.bold('spree sample-data')}.`,'','You can now customize:',` ${pc.dim(`${apiDir}/app/`)} — models, controllers, services (instant reload)`,- ` ${pc.dim(`${apiDir}/config/`)} — Rails configuration (instant reload)`,- ` ${pc.dim(`${apiDir}/Gemfile`)} — add gems via ${pc.bold('spree bundle add <gem>')}`,+ ` ${pc.dim(`${apiDir}/config/`)} — backend configuration (instant reload)`,+ ` ${pc.dim(`${apiDir}/Gemfile`)} — add extensions via ${pc.bold('spree add <extension>')}`,'',- `Rebuild only on Dockerfile / .ruby-version changes: ${pc.bold('spree build')}`,+ `Rebuild only on Dockerfile or runtime version changes: ${pc.bold('spree build')}`,].join('\n'),'Ejected!',)diff --git a/packages/cli/src/commands/encryption.ts b/packages/cli/src/commands/encryption.tsindex 23fee879eb..e23e224daf 100644--- a/packages/cli/src/commands/encryption.ts+++ b/packages/cli/src/commands/encryption.ts@@ -21,13 +21,11 @@ const DOCS_URL =export function registerEncryptionCommand(program: Command): void {const encryption = program.command('encryption')- .description('Manage Active Record encryption keys')+ .description('Manage the keys that encrypt sensitive data at rest')encryption.command('init')- .description(- 'Generate Active Record encryption keys and add them to .env (never overwrites existing keys)',- )+ .description('Generate encryption keys and add them to .env (never overwrites existing keys)').option('--print', 'only print a fresh set of keys (e.g. for your hosting provider)').addHelpText('after',@@ -82,7 +80,7 @@ export function initEncryption(projectDir: string): void {}writeEnvAtomically(envPath, withEncryptionKeys(content, generateEncryptionKeys()))- p.log.success('Added Active Record encryption keys to .env.')+ p.log.success('Added encryption keys to .env.')p.note([diff --git a/packages/cli/src/commands/filters.ts b/packages/cli/src/commands/filters.tsindex 1f0e0f119e..91ee9f3ee3 100644--- a/packages/cli/src/commands/filters.ts+++ b/packages/cli/src/commands/filters.ts@@ -3,8 +3,9 @@ import { dirname, join, relative, resolve } from 'node:path'import * as p from '@clack/prompts'import { type FilterSpec, renderAppFilterTypes } from '@spree/sdk-core'import type { Command } from 'commander'+import { spreeTask } from '../backend.js'import { detectProject } from '../context.js'-import { rakeTask } from '../docker.js'+import { captureTask } from '../docker.js'const APIS = ['store', 'admin', 'seller'] as consttype Api = (typeof APIS)[number]@@ -45,7 +46,7 @@ export function registerFiltersCommand(program: Command): void {.option('--out <file>', `where to write that one file (default: ${DEFAULT_OUT})`).option('--from <file>',- 'read the filter tables from a file written by `bin/rails spree:api:filter_tables` instead of the running app',+ 'read the filter tables from a file written by `spree task api:filter_tables` instead of the running app',).action(async (options: TypesOptions) => {if (options.api && !APIS.includes(options.api)) {@@ -78,7 +79,7 @@ export function registerFiltersCommand(program: Command): void {const tables = parseFilterTables(options.from? readFileSync(resolve(options.from), 'utf8')- : await rakeTask('spree:api:filter_tables', projectDir as string),+ : await captureTask(spreeTask('api:filter_tables'), projectDir as string),)for (const { api, out } of targets) {@@ -98,7 +99,7 @@ export function parseFilterTables(output: string): Record<Api, FilterSpec> {const json = output.split('\n').find((line) => line.trimStart().startsWith('{'))if (!json)throw new Error(- 'No filter tables found. Run `bin/rails spree:api:filter_tables` to check its output.',+ 'No filter tables found. Run `spree task api:filter_tables` to check its output.',)return JSON.parse(json) as Record<Api, FilterSpec>diff --git a/packages/cli/src/commands/generate.ts b/packages/cli/src/commands/generate.tsindex ed66c30803..e586a2c26a 100644--- a/packages/cli/src/commands/generate.ts+++ b/packages/cli/src/commands/generate.ts@@ -1,4 +1,5 @@import type { Command } from 'commander'+import { runGeneratorCommand } from '../backend.js'import { detectProject } from '../context.js'import { dockerComposeExecOrRun } from '../docker.js'@@ -29,7 +30,10 @@ export function registerGenerateCommand(program: Command): void {.description('Run a generator (Spree generators auto-prefixed; Rails built-ins forwarded as-is)',)- .argument('<name>', 'generator name (`model`, `model_decorator`, `migration`, …)')+ .argument(+ '<name>',+ 'generator name (`api_resource`, `model`, `model_decorator`, `migration`, …)',+ ).argument('[args...]', 'arguments to pass to the generator').allowUnknownOption(true).passThroughOptions(true)@@ -37,6 +41,7 @@ export function registerGenerateCommand(program: Command): void {const ctx = detectProject()const generator =name.includes(':') || RAILS_BUILTIN_GENERATORS.has(name) ? name : `spree:${name}`- await dockerComposeExecOrRun(['bin/rails', 'g', generator, ...args], ctx.projectDir)++ await dockerComposeExecOrRun(runGeneratorCommand(generator, args), ctx.projectDir)})}diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.tsindex b35c8656de..d38ebf1fe4 100644--- a/packages/cli/src/commands/init.ts+++ b/packages/cli/src/commands/init.ts@@ -6,6 +6,7 @@ import * as p from '@clack/prompts'import type { Command } from 'commander'import { execa } from 'execa'import pc from 'picocolors'+import { SEED_TASK, spreeTask } from '../backend.js'import { mintProjectCredentials, writeAdminEmail, writeProjectSetupMarker } from '../config.js'import { DASHBOARD_PORT, STOREFRONT_PORT } from '../constants.js'import { detectProject, isEjectedProject, readSampleDataFromEnv } from '../context.js'@@ -16,10 +17,10 @@ import {warnDashboardNotRunnable,} from '../dashboard-server.js'import {+ captureTask,dockerCompose,prepareDatabase,primeBundleVolume,- rakeTask,streamLogs,} from '../docker.js'import { detectPackageManager, ensureDashboardDevEnv } from './add.js'@@ -105,9 +106,9 @@ export async function runFirstRunSetup(flags: {s.start('Seeding database...')// Omitted entirely when unresolved — the seed treats blank values as "no// admin" and prints a setup link instead, which we surface on the card- // below (rakeTask captures stdout rather than streaming it).- const seedOutput = await rakeTask(- 'db:seed',+ // below (captureTask captures stdout rather than streaming it).+ const seedOutput = await captureTask(+ SEED_TASK,ctx.projectDir,adminEmail && adminPassword? { ADMIN_EMAIL: adminEmail, ADMIN_PASSWORD: adminPassword }@@ -143,7 +144,7 @@ export async function runFirstRunSetup(flags: {const sampleDataLoaded = sampleData && Boolean(adminEmail && adminPassword)if (sampleDataLoaded) {s.start('Loading sample data...')- await rakeTask('spree:load_sample_data', ctx.projectDir)+ await captureTask(spreeTask('load_sample_data'), ctx.projectDir)s.stop('Sample data loaded.')} else if (sampleData) {p.log.info(@@ -152,7 +153,7 @@ export async function runFirstRunSetup(flags: {}s.start('Indexing products for search...')- await rakeTask('spree:search:reindex', ctx.projectDir)+ await captureTask(spreeTask('search:reindex'), ctx.projectDir)s.stop('Search index ready.')writeProjectSetupMarker(ctx.projectDir)@@ -185,7 +186,7 @@ export async function runFirstRunSetup(flags: {` ${pc.cyan(setupToken? `${setupBase}/setup?token=${setupToken}`- : 'run `spree run bin/rails spree:setup:token` for the setup link',+ : 'run `spree task setup:token` for the setup link',)}`,]@@ -318,11 +319,11 @@ export async function waitForHealthy(port: number, signal?: AbortSignal): Promis}async function fetchApiKey(projectDir: string): Promise<string> {- const stdout = await rakeTask('spree:cli:ensure_api_key', projectDir)+ const stdout = await captureTask(spreeTask('cli:ensure_api_key'), projectDir)const match = stdout.match(/pk_[A-Za-z0-9_-]+/)if (!match) {- throw new Error(`Could not extract API key from Rails output: ${stdout}`)+ throw new Error(`Could not extract API key from the backend output: ${stdout}`)}return match[0]}diff --git a/packages/cli/src/commands/logs.ts b/packages/cli/src/commands/logs.tsindex 5708b3a436..d51e421df8 100644--- a/packages/cli/src/commands/logs.ts+++ b/packages/cli/src/commands/logs.ts@@ -15,8 +15,8 @@ export function registerLogsCommand(program: Command): void {// process, so their logs are web's logs.if (service === 'worker' && !(await appServices(ctx.projectDir)).includes('worker')) {p.log.info(- `This project has no ${pc.bold('worker')} service — jobs run inside the web process ` +- `(Solid Queue in Puma). Streaming ${pc.bold('web')} logs; the job dashboard is at ` ++ `This project has no ${pc.bold('worker')} service — jobs run inside the web process. ` ++ `Streaming ${pc.bold('web')} logs; the job dashboard is at ` +`${pc.cyan(`http://localhost:${ctx.port}/jobs`)}.`,)await streamLogs('web', ctx.projectDir)diff --git a/packages/cli/src/commands/migrate.ts b/packages/cli/src/commands/migrate.tsindex 2afbc1b1eb..af86de263c 100644--- a/packages/cli/src/commands/migrate.ts+++ b/packages/cli/src/commands/migrate.ts@@ -1,40 +1,33 @@import * as p from '@clack/prompts'-import type { Command } from 'commander'+import { type Command, InvalidArgumentError } from 'commander'import pc from 'picocolors'+import { MIGRATE, MIGRATE_STATUS, rollbackCommand } from '../backend.js'import { detectProject } from '../context.js'-import { dockerComposeExec, dockerComposeExecOrRun, isServiceRunning } from '../docker.js'+import { warnDeprecated } from '../deprecation.js'+import { dockerComposeExecOrRun } from '../docker.js'export function registerMigrateCommand(program: Command): void {program.command('migrate')- .description(- 'Install pending Spree migrations from gems, then run them (`spree:install:migrations` + `db:migrate`)',- )- .argument('[args...]', 'extra args forwarded to db:migrate')+ .description('Install pending Spree migrations, then run them')+ .argument('[args...]').allowUnknownOption(true).passThroughOptions(true).action(async (args: string[]) => {- const ctx = detectProject()-- // Both Rails tasks are silent when there's nothing to do, which leaves- // the operator wondering whether anything ran. Print a visible header- // for each step and a footer summarising the outcome.- if (await isServiceRunning('web', ctx.projectDir)) {- console.log(`\n${pc.bold('→ Installing pending Spree migrations from gems...')}`)- await dockerComposeExec(['bin/rails', 'spree:install:migrations'], ctx.projectDir)-- console.log(`\n${pc.bold('→ Running db:migrate...')}`)- await dockerComposeExec(['bin/rails', 'db:migrate', ...args], ctx.projectDir)- } else {- // One combined invocation on the fallback path: a one-off container- // pays a cold Rails boot per invocation, so don't pay it twice.- console.log(`\n${pc.bold('→ Installing + running pending Spree migrations...')}`)- await dockerComposeExecOrRun(- ['bin/rails', 'spree:install:migrations', 'db:migrate', ...args],- ctx.projectDir,- { edgeHint: 'the edge boot installs and runs pending migrations itself' },+ if (args.length > 0) {+ warnDeprecated(+ `spree migrate ${args.join(' ')}`,+ `spree migrate, or spree exec bin/rails db:migrate ${args.join(' ')}`,)}+ const ctx = detectProject()++ // The migration tasks are silent when there's nothing to do, which+ // leaves the operator wondering whether anything ran.+ console.log(`\n${pc.bold('→ Installing + running pending Spree migrations...')}`)+ await dockerComposeExecOrRun([...MIGRATE, ...args], ctx.projectDir, {+ edgeHint: 'the edge boot installs and runs pending migrations itself',+ })p.note(`Run ${pc.bold('spree migrate:status')} to inspect the migration log.`,@@ -44,20 +37,41 @@ export function registerMigrateCommand(program: Command): void {program.command('migrate:rollback')- .description('Roll back the last migration (`STEP=n` to roll back n steps)')- .argument('[args...]', 'extra args forwarded to db:rollback (e.g. STEP=2)')+ .description('Roll back the last migration (`--steps n` to roll back n)')+ .option('--steps <n>', 'number of migrations to roll back', parseSteps)+ .argument('[args...]')+ // No passThroughOptions: --steps must be read wherever it appears, even+ // after a raw `STEP=2` left over from the deprecated form..allowUnknownOption(true)- .passThroughOptions(true)- .action(async (args: string[]) => {+ .action(async (rawArgs: string[], flags: { steps?: number }) => {+ // An explicit --steps wins over a raw STEP=, so the two never both reach the backend.+ const args = flags.steps ? rawArgs.filter((arg) => !arg.startsWith('STEP=')) : rawArgs+ if (args.length > 0) {+ const step = args.length === 1 && args[0].startsWith('STEP=') ? args[0] : undefined+ warnDeprecated(+ `spree migrate:rollback ${args.join(' ')}`,+ step+ ? `spree migrate:rollback --steps ${step.slice('STEP='.length)}`+ : `spree exec bin/rails db:rollback ${args.join(' ')}`,+ )+ }const ctx = detectProject()- await dockerComposeExecOrRun(['bin/rails', 'db:rollback', ...args], ctx.projectDir)+ await dockerComposeExecOrRun(rollbackCommand(flags.steps, args), ctx.projectDir)})program.command('migrate:status')- .description('Show migration status (`bin/rails db:migrate:status`)')+ .description('Show which migrations have run').action(async () => {const ctx = detectProject()- await dockerComposeExecOrRun(['bin/rails', 'db:migrate:status'], ctx.projectDir)+ await dockerComposeExecOrRun(MIGRATE_STATUS, ctx.projectDir)})}++function parseSteps(value: string): number {+ const steps = Number(value)+ if (!Number.isInteger(steps) || steps < 1) {+ throw new InvalidArgumentError(`must be a positive whole number, got "${value}"`)+ }+ return steps+}diff --git a/packages/cli/src/commands/plugin.ts b/packages/cli/src/commands/plugin.tsindex 97c443353a..b8ad1f2583 100644--- a/packages/cli/src/commands/plugin.ts+++ b/packages/cli/src/commands/plugin.ts@@ -2,9 +2,10 @@ import fs from 'node:fs'import path from 'node:path'import { fileURLToPath } from 'node:url'import * as p from '@clack/prompts'-import type { Command } from 'commander'+import { type Command, Option } from 'commander'import { execa } from 'execa'import pc from 'picocolors'+import { warnDeprecated } from '../deprecation.js'import { PLUGIN_PEER_RANGES } from '../lib/plugin-peer-ranges.js'import { render, type TemplateVars } from '../lib/template.js'@@ -12,10 +13,12 @@ const TEMPLATE_RELATIVE_PATH = '../../templates/plugin'interface PluginNewFlags {dashboard: boolean+ backend: booleanengine: booleaninstall: booleanforce: booleanyes: boolean+ backendName?: stringrubyName?: stringmoduleName?: stringnpmScope?: string@@ -29,18 +32,19 @@ const LICENSES = ['MIT', 'Apache-2.0', 'BSD-3-Clause'] as constexport function registerPluginCommand(program: Command): void {const plugin = program.command('plugin')- .description('Scaffold and manage Spree plugins (dashboard + Rails engine)')+ .description('Scaffold and manage Spree plugins (dashboard + backend)')plugin.command('new').description(- 'Scaffold a new Spree plugin monorepo (dashboard plugin half today; Rails engine coming soon)',+ 'Scaffold a new Spree plugin monorepo (dashboard plugin half today; backend half coming soon)',).argument('[name]', 'Plugin name (e.g. brands). If omitted, you will be prompted.')- .option('--ruby-name <name>', 'Ruby gem name (default: spree_<name>)')+ .option('--backend-name <name>', 'Backend package name (default: spree_<name>)')+ .addOption(new Option('--ruby-name <name>').hideHelp()).option('--module-name <name>',- 'Ruby module / TS namespace (default: PascalCase of the gem name)',+ 'Backend module / TS namespace (default: PascalCase of the backend package name)',).option('--npm-scope <scope>', 'npm scope, e.g. @acme (default: unscoped)').option('--author <name>', 'Author name (default: git config user.name)')@@ -53,14 +57,24 @@ export function registerPluginCommand(program: Command): void {).option('--no-dashboard', 'Skip the dashboard plugin half').option(- '--no-engine',- 'Skip the Rails engine half (currently always skipped — engine support coming soon)',+ '--no-backend',+ 'Skip the backend half (currently always skipped — backend support coming soon)',)+ .addOption(new Option('--no-engine').hideHelp()).option('--no-install', 'Skip running pnpm install').option('--force', 'Overwrite a non-empty destination directory').action(async (nameArg: string | undefined, flags: PluginNewFlags) => {p.intro(pc.bgCyan(pc.black(' Spree Plugin Scaffolder ')))+ if (flags.rubyName) {+ warnDeprecated('--ruby-name', '--backend-name')+ flags.backendName ??= flags.rubyName+ }+ if (flags.engine === false) {+ warnDeprecated('--no-engine', '--no-backend')+ flags.backend = false+ }+const answers = await collectAnswers(nameArg, flags)if (p.isCancel(answers)) {p.cancel('Scaffolding cancelled.')@@ -160,8 +174,8 @@ async function collectAnswers(// default for whatever the flags leave unanswered.const rubyDefault = `spree_${(name as string).replace(/-/g, '_')}`const rubyName = await resolveField({- flag: '--ruby-name',- flagValue: flags.rubyName,+ flag: '--backend-name',+ flagValue: flags.backendName,fallback: rubyDefault,yes: flags.yes,validate: (value) =>@@ -170,7 +184,7 @@ async function collectAnswers(: 'Use lowercase letters, digits, and underscores (e.g. "spree_brands")',prompt: () =>p.text({- message: 'Ruby gem name',+ message: 'Backend package name (Ruby gem)',placeholder: rubyDefault,initialValue: rubyDefault,validate: (value) =>@@ -290,13 +304,13 @@ async function collectAnswers(// land in a follow-up PR. For now, we always answer false and note it.// Once the engine templates exist, restore the prompt://- // const includeEngine = flags.engine === false+ // const includeEngine = flags.backend === false// ? false// : await promptConfirm('Include Rails engine (API endpoints)?', true)const includeEngine = false- if (flags.engine !== false) {+ if (flags.backend !== false) {p.log.warn(- 'Rails engine generation is coming in a future release. For now, scaffold the dashboard half here and use `spree-extension create` for the Ruby side.',+ 'Backend generation is coming in a future release. For now, scaffold the dashboard half here and use `spree-extension create` for the backend side.',)}diff --git a/packages/cli/src/commands/rails.ts b/packages/cli/src/commands/rails.tsindex 01d924a94b..7eafb34cce 100644--- a/packages/cli/src/commands/rails.ts+++ b/packages/cli/src/commands/rails.ts@@ -1,20 +1,20 @@import type { Command } from 'commander'+import { railsCommand } from '../backend.js'import { detectProject } from '../context.js'+import { warnDeprecated } from '../deprecation.js'import { dockerComposeExecOrRun } from '../docker.js'-// Run any Rails command. Short for `spree exec bin/rails …`.-// spree rails runner 'puts Rails.env'-// spree rails db:migrate-// spree rails routes -g products+// Deprecated: Rails-only, so it goes through the `spree exec` escape hatch.export function registerRailsCommand(program: Command): void {program- .command('rails')- .description('Run a Rails command (`bin/rails …`) inside the web container')+ .command('rails', { hidden: true })+ .description('Deprecated: use `spree exec bin/rails …`').argument('<args...>', 'arguments to pass to bin/rails').allowUnknownOption(true).passThroughOptions(true).action(async (args: string[]) => {+ warnDeprecated('spree rails', `spree exec bin/rails ${args.join(' ')}`)const ctx = detectProject()- await dockerComposeExecOrRun(['bin/rails', ...args], ctx.projectDir)+ await dockerComposeExecOrRun(railsCommand(args), ctx.projectDir)})}diff --git a/packages/cli/src/commands/rake.ts b/packages/cli/src/commands/rake.tsindex 1bf4c46229..3f5f99dd3e 100644--- a/packages/cli/src/commands/rake.ts+++ b/packages/cli/src/commands/rake.ts@@ -1,21 +1,26 @@import type { Command } from 'commander'+import { rakeCommand } from '../backend.js'import { detectProject } from '../context.js'+import { warnDeprecated } from '../deprecation.js'import { dockerComposeExecOrRun } from '../docker.js'-// Run a rake task inside the web container. Variadic: anything after the-// task name is forwarded verbatim, including `KEY=value` rake args and flags.-// spree rake spree:channels:full_upgrade-// spree rake spree:price_history:seed-// spree rake db:rollback STEP=2+// Deprecated: Spree tasks belong to `spree task`, everything else to `spree exec`.export function registerRakeCommand(program: Command): void {program- .command('rake')- .description('Run a rake task (`bin/rake …`) inside the web container')+ .command('rake', { hidden: true })+ .description('Deprecated: use `spree task …` or `spree exec bin/rake …`').argument('<args...>', 'task name and arguments').allowUnknownOption(true).passThroughOptions(true).action(async (args: string[]) => {+ const [task, ...rest] = args+ warnDeprecated(+ 'spree rake',+ task.startsWith('spree:')+ ? `spree task ${[task.slice('spree:'.length), ...rest].join(' ')}`+ : `spree exec bin/rake ${args.join(' ')}`,+ )const ctx = detectProject()- await dockerComposeExecOrRun(['bin/rake', ...args], ctx.projectDir)+ await dockerComposeExecOrRun(rakeCommand(args), ctx.projectDir)})}diff --git a/packages/cli/src/commands/routes.ts b/packages/cli/src/commands/routes.tsindex 2dee3c0c36..ca1b710707 100644--- a/packages/cli/src/commands/routes.ts+++ b/packages/cli/src/commands/routes.ts@@ -1,16 +1,22 @@import type { Command } from 'commander'+import { routesCommand } from '../backend.js'import { detectProject } from '../context.js'+import { warnDeprecated } from '../deprecation.js'import { dockerComposeExecOrRun } from '../docker.js'export function registerRoutesCommand(program: Command): void {program- .command('routes')- .description('Show Rails routes (`bin/rails routes`)')+ .command('routes', { hidden: true })+ .description('Deprecated: use `spree api endpoints`').argument('[args...]', 'arguments to pass to bin/rails routes').allowUnknownOption(true).passThroughOptions(true).action(async (args: string[]) => {+ warnDeprecated(+ 'spree routes',+ args.length > 0 ? `spree exec bin/rails routes ${args.join(' ')}` : 'spree api endpoints',+ )const ctx = detectProject()- await dockerComposeExecOrRun(['bin/rails', 'routes', ...args], ctx.projectDir)+ await dockerComposeExecOrRun(routesCommand(args), ctx.projectDir)})}diff --git a/packages/cli/src/commands/rspec.ts b/packages/cli/src/commands/rspec.tsdeleted file mode 100644index ad16ee5152..0000000000--- a/packages/cli/src/commands/rspec.ts+++ /dev/null@@ -1,35 +0,0 @@-import type { Command } from 'commander'-import { detectProject } from '../context.js'-import { dockerComposeExecOrRun } from '../docker.js'--// Run the RSpec suite inside the web container. Anything after `rspec` is-// forwarded verbatim — file paths, line numbers, and rspec flags all work.-// spree rspec-// spree rspec spec/models/spree/brand_spec.rb-// spree rspec spec/models/spree/brand_spec.rb:15-// spree rspec --format documentation-//-// RAILS_ENV=test is forced at the exec level: the dev image bakes-// RAILS_ENV=development, and while the starter's rails_helper re-forces test-// itself, setting it here keeps the command correct for apps whose helpers-// don't — and keeps every child process (spring, parallel workers) consistent.-// database.yml resolves the spree_test database from RAILS_ENV, so tests never-// touch the development data.-//-// When web is down we fall back to a one-off `compose run`, whose depends_on-// health-waits postgres — so tests run from a fully cold stack too.-export function registerRspecCommand(program: Command): void {- program- .command('rspec')- .description('Run RSpec tests (`bundle exec rspec …`) inside the web container')- .argument('[args...]', 'files, line numbers, and flags to pass to rspec')- .allowUnknownOption(true)- .passThroughOptions(true)- .action(async (args: string[]) => {- const ctx = detectProject()- await dockerComposeExecOrRun(['bundle', 'exec', 'rspec', ...args], ctx.projectDir, {- env: { RAILS_ENV: 'test' },- edgeHint: 'then re-run spree rspec',- })- })-}diff --git a/packages/cli/src/commands/sample-data.ts b/packages/cli/src/commands/sample-data.tsindex ef7a8c4097..11e5157d30 100644--- a/packages/cli/src/commands/sample-data.ts+++ b/packages/cli/src/commands/sample-data.ts@@ -1,7 +1,8 @@import * as p from '@clack/prompts'import type { Command } from 'commander'+import { spreeTask } from '../backend.js'import { detectProject } from '../context.js'-import { rakeTask } from '../docker.js'+import { captureTask } from '../docker.js'export function registerSampleDataCommand(program: Command): void {program@@ -12,7 +13,7 @@ export function registerSampleDataCommand(program: Command): void {const s = p.spinner()s.start('Loading sample data...')- await rakeTask('spree:load_sample_data', ctx.projectDir)+ await captureTask(spreeTask('load_sample_data'), ctx.projectDir)s.stop('Sample data loaded.')})}diff --git a/packages/cli/src/commands/seed.ts b/packages/cli/src/commands/seed.tsindex 9428f82367..3c92bc4fa6 100644--- a/packages/cli/src/commands/seed.ts+++ b/packages/cli/src/commands/seed.ts@@ -1,7 +1,8 @@import * as p from '@clack/prompts'import type { Command } from 'commander'+import { SEED_TASK } from '../backend.js'import { detectProject } from '../context.js'-import { rakeTask } from '../docker.js'+import { captureTask } from '../docker.js'export function registerSeedCommand(program: Command): void {program@@ -12,7 +13,7 @@ export function registerSeedCommand(program: Command): void {const s = p.spinner()s.start('Seeding database...')- await rakeTask('db:seed', ctx.projectDir)+ await captureTask(SEED_TASK, ctx.projectDir)s.stop('Database seeded.')})}diff --git a/packages/cli/src/commands/task.ts b/packages/cli/src/commands/task.tsindex 6a469eef64..a4d9ac44df 100644--- a/packages/cli/src/commands/task.ts+++ b/packages/cli/src/commands/task.ts@@ -1,22 +1,23 @@import type { Command } from 'commander'+import { taskCommand } from '../backend.js'import { detectProject } from '../context.js'import { dockerComposeExecOrRun } from '../docker.js'-// Shortcut for `spree rake spree:<name>` — most rake tasks a Spree dev runs-// are in the `spree:` namespace, so this saves the prefix.-// spree task search:reindex → bin/rake spree:search:reindex+// Run a Spree maintenance task. Task names are part of the CLI's public+// contract and keep working on every backend.+// spree task search:reindex// spree task channels:full_upgrade// spree task price_history:seedexport function registerTaskCommand(program: Command): void {program.command('task')- .description('Run a Spree rake task (auto-prefixes `spree:`)')- .argument('<name>', 'task name (without `spree:` prefix)')+ .description('Run a Spree maintenance task (e.g. `search:reindex`)')+ .argument('<name>', 'task name, e.g. search:reindex').argument('[args...]', 'arguments to pass to the task').allowUnknownOption(true).passThroughOptions(true).action(async (name: string, args: string[]) => {const ctx = detectProject()- await dockerComposeExecOrRun(['bin/rake', `spree:${name}`, ...args], ctx.projectDir)+ await dockerComposeExecOrRun(taskCommand(name.replace(/^spree:/, ''), args), ctx.projectDir)})}diff --git a/packages/cli/src/commands/test.ts b/packages/cli/src/commands/test.tsnew file mode 100644index 0000000000..2edd3c16c8--- /dev/null+++ b/packages/cli/src/commands/test.ts@@ -0,0 +1,45 @@+import type { Command } from 'commander'+import { TEST_ENV, testCommand } from '../backend.js'+import { detectProject } from '../context.js'+import { warnDeprecated } from '../deprecation.js'+import { dockerComposeExecOrRun } from '../docker.js'++// Run the backend test suite inside the web container. Anything after `test`+// is forwarded verbatim — file paths, line numbers and flags all work.+// spree test+// spree test spec/models/spree/brand_spec.rb:15+//+// The test environment is forced at the exec level: the dev image bakes the+// development environment, and forcing it here keeps every child process+// consistent and keeps tests off the development database.+//+// When web is down we fall back to a one-off `compose run`, whose depends_on+// health-waits postgres — so tests run from a fully cold stack too.+export function registerTestCommand(program: Command): void {+ const run = async (args: string[]) => {+ const ctx = detectProject()+ await dockerComposeExecOrRun(testCommand(args), ctx.projectDir, {+ env: TEST_ENV,+ edgeHint: 'then re-run spree test',+ })+ }++ program+ .command('test')+ .description('Run the backend test suite inside the web container')+ .argument('[args...]', 'files, line numbers and flags to pass to the test runner')+ .allowUnknownOption(true)+ .passThroughOptions(true)+ .action(run)++ program+ .command('rspec', { hidden: true })+ .description('Deprecated: use `spree test`')+ .argument('[args...]')+ .allowUnknownOption(true)+ .passThroughOptions(true)+ .action(async (args: string[]) => {+ warnDeprecated('spree rspec', 'spree test')+ await run(args)+ })+}diff --git a/packages/cli/src/commands/upgrade.ts b/packages/cli/src/commands/upgrade.tsindex d2fecd1e9c..226a6c4e02 100644--- a/packages/cli/src/commands/upgrade.ts+++ b/packages/cli/src/commands/upgrade.ts@@ -4,6 +4,13 @@ import * as p from '@clack/prompts'import type { Command } from 'commander'import { execa } from 'execa'import pc from 'picocolors'+import {+ INSTALL_PACKAGES,+ LIST_PACKAGES,+ MIGRATE,+ UPGRADE,+ updatePackagesCommand,+} from '../backend.js'import { detectProject, hasMonorepoSpreePath, isEjectedProject } from '../context.js'import {dockerCompose,@@ -37,9 +44,7 @@ export function registerUpgradeCommand(program: Command): void {withUpgradeOptions(program.command('upgrade')- .description(- 'Upgrade Spree: the server (image or gems), @spree/* packages, migrations and data backfills',- ),+ .description('Upgrade Spree: the server, @spree/* packages, migrations and data backfills'),).action(upgrade)// `update` predates the merge and only pulled the image. Kept one release@@ -58,12 +63,12 @@ function withUpgradeOptions(command: Command): Command {return command.option('--plan',- 'list the data backfills a run would execute — for the installed Spree version, or the --to version (DRY_RUN=1); runs nothing else',+ 'list the data backfills a run would execute — for the installed Spree version, or the --to version; runs nothing else',)- .option('--step <id>', 'run a single rake step by id (runs nothing else)')+ .option('--step <id>', 'run a single upgrade step by id (runs nothing else)').option('--to <version>',- 'explicit target version (auto-detected from installed gem otherwise)',+ 'explicit target version (auto-detected from the installed Spree otherwise)',).option('--yes', 'skip prompts on automated steps')}@@ -87,7 +92,10 @@ async function upgrade(flags: UpgradeFlags): Promise<void> {await runRakeUpgrade(ctx.projectDir, flags)// Puma loaded the old gems at boot; the rake steps ran in fresh processes.if (gemsUpdated)- await restartAppServices(ctx.projectDir, 'Restarting the app to load the updated gems')+ await restartAppServices(+ ctx.projectDir,+ 'Restarting the app to load the updated Spree packages',+ )} else {const imagePulled = await pullImage(ctx.projectDir, flags)line = await serverReleaseLine(ctx.projectDir, { fromNewImage: imagePulled })@@ -193,8 +201,8 @@ async function assertUpgradeable(projectDir: string): Promise<void> {}async function runBundleUpdate(projectDir: string, flags: UpgradeFlags): Promise<boolean> {- if (!(await confirmStep('Run `bundle update` to bump Spree gems?', flags))) {- p.log.info('Skipping `bundle update`.')+ if (!(await confirmStep('Update the Spree packages?', flags))) {+ p.log.info('Skipping the Spree package update.')return false}@@ -202,13 +210,13 @@ async function runBundleUpdate(projectDir: string, flags: UpgradeFlags): Promiseconst spreeGems = await detectSpreeGems(projectDir)if (spreeGems.length === 0) {throw new Error(- 'No Spree gems detected in Gemfile.lock. ' ++ 'No Spree packages detected in the backend dependencies. ' +'Confirm the project has `gem "spree"` (or `spree_core`) in its Gemfile.',)}- p.log.step(pc.bold(`bundle update ${spreeGems.join(' ')}`))- await dockerComposeExecOrRun(['bundle', 'update', ...spreeGems], projectDir)+ p.log.step(pc.bold(`Updating ${spreeGems.join(' ')}`))+ await dockerComposeExecOrRun(updatePackagesCommand(spreeGems), projectDir)return true}@@ -220,8 +228,11 @@ export async function detectSpreeGems(projectDir: string): Promise<string[]> {try {return await listSpreeGems(projectDir)} catch {- p.log.step(pc.bold('bundle install') + pc.dim(' — the bundle is out of sync with Gemfile.lock'))- await dockerComposeExecOrRun(['bundle', 'install'], projectDir)+ p.log.step(+ pc.bold('Installing backend dependencies') ++ pc.dim(' — they are out of sync with the lockfile'),+ )+ await dockerComposeExecOrRun(INSTALL_PACKAGES, projectDir)}try {@@ -229,7 +240,7 @@ export async function detectSpreeGems(projectDir: string): Promise<string[]> {} catch (err) {const e = err as { stderr?: string }throw new Error(- 'Could not list gems in the web container, even after `bundle install`.' ++ 'Could not list the Spree packages in the web container, even after reinstalling the backend dependencies.' +(e.stderr?.trim() ? `\n\n${e.stderr.trim()}` : ''),)}@@ -239,7 +250,7 @@ export async function detectSpreeGems(projectDir: string): Promise<string[]> {// with zero spree gems, so a nonzero exit unambiguously means bundler itself// errored.async function listSpreeGems(projectDir: string): Promise<string[]> {- const stdout = await dockerComposeCapture(['bundle', 'list', '--name-only'], projectDir)+ const stdout = await dockerComposeCapture(LIST_PACKAGES, projectDir)return stdout.split('\n').map((line) => line.trim())@@ -251,8 +262,8 @@ async function runMigrate(projectDir: string, flags: UpgradeFlags): Promise<voidp.log.info('Skipping migrations.')return}- p.log.step(pc.bold('spree:install:migrations + db:migrate'))- await dockerComposeExecOrRun(['bin/rails', 'spree:install:migrations', 'db:migrate'], projectDir)+ p.log.step(pc.bold('Installing + running pending migrations'))+ await dockerComposeExecOrRun(MIGRATE, projectDir)}async function runRakeUpgrade(projectDir: string, flags: UpgradeFlags): Promise<void> {@@ -263,14 +274,14 @@ async function runRakeUpgrade(projectDir: string, flags: UpgradeFlags): Promise<return}- // Flags map to env vars so prod (`STEP=channels rake spree:upgrade`) and dev share the same path.+ // Flags map to env vars so production and dev runs share the same path.const env: Record<string, string> = {}if (flags.plan) env.DRY_RUN = '1'if (flags.step) env.STEP = flags.stepif (flags.to) env.TO = flags.to- p.log.step(pc.bold('spree:upgrade'))- await dockerComposeExecOrRun(['bin/rake', 'spree:upgrade'], projectDir, { env })+ p.log.step(pc.bold('Running upgrade steps'))+ await dockerComposeExecOrRun(UPGRADE, projectDir, { env })}// A Spree package the project resolves from the registry. Local specs@@ -564,7 +575,7 @@ export function sdkAdvisory(projectDir: string, line: ReleaseLine = RELEASE_LINEfunction printPostUpgradeReminder(projectDir: string, line: ReleaseLine = RELEASE_LINE): void {p.note([- `The manifest only ran ${pc.bold('rake-automatable')} steps.`,+ `The manifest only ran the ${pc.bold('automatable')} steps.`,'',"Don't forget the manual parts from the upgrade doc:",` ${pc.dim('- Compare your scheduled jobs (config/recurring.yml) with the upgrade guide')}`,diff --git a/packages/cli/src/commands/user.ts b/packages/cli/src/commands/user.tsindex ad78cb037c..d812f6b0e6 100644--- a/packages/cli/src/commands/user.ts+++ b/packages/cli/src/commands/user.ts@@ -1,8 +1,9 @@import * as p from '@clack/prompts'import type { Command } from 'commander'import pc from 'picocolors'+import { spreeTask } from '../backend.js'import { detectProject } from '../context.js'-import { rakeTask } from '../docker.js'+import { captureTask } from '../docker.js'export function registerUserCommand(program: Command): void {const user = program.command('user').description('Manage admin users')@@ -53,7 +54,7 @@ export function registerUserCommand(program: Command): void {const s = p.spinner()s.start('Creating admin user...')- await rakeTask('spree:cli:create_admin', ctx.projectDir, {+ await captureTask(spreeTask('cli:create_admin'), ctx.projectDir, {EMAIL: email,PASSWORD: password,})diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.tsindex 492ebf6032..71bc6b8444 100644--- a/packages/cli/src/config.ts+++ b/packages/cli/src/config.ts@@ -2,9 +2,10 @@ import fs from 'node:fs'import os from 'node:os'import path from 'node:path'import pc from 'picocolors'+import { spreeTask } from './backend.js'import { DEFAULT_SPREE_PORT } from './constants.js'import { detectProject } from './context.js'-import { rakeTask } from './docker.js'+import { captureTask } from './docker.js'/** Host a flag/env key defaults to when none is given — the local dev server. */const LOCAL_DEV_URL = `http://localhost:${DEFAULT_SPREE_PORT}`@@ -243,7 +244,7 @@ export interface MintKeyOptions {export async function mintApiKey(projectDir: string, options: MintKeyOptions): Promise<string> {let stdout: stringtry {- stdout = await rakeTask('spree:cli:create_api_key', projectDir, {+ stdout = await captureTask(spreeTask('cli:create_api_key'), projectDir, {NAME: options.name,KEY_TYPE: options.keyType,...(options.scopes?.length ? { SCOPES: options.scopes.join(',') } : {}),diff --git a/packages/cli/src/deprecation.ts b/packages/cli/src/deprecation.tsnew file mode 100644index 0000000000..cb2c7c6a74--- /dev/null+++ b/packages/cli/src/deprecation.ts@@ -0,0 +1,13 @@+import pc from 'picocolors'++/**+ * Print the one-line notice a deprecated command or flag shows before it runs.+ * Written to stderr so scripts capturing stdout are unaffected.+ */+export function warnDeprecated(used: string, replacement: string): void {+ console.error(+ pc.yellow(+ `${pc.bold(used)} is deprecated and will be removed in Spree 7.0. Use ${pc.bold(replacement)} instead.`,+ ),+ )+}diff --git a/packages/cli/src/docker.ts b/packages/cli/src/docker.tsindex d204602d66..93149597f7 100644--- a/packages/cli/src/docker.ts+++ b/packages/cli/src/docker.ts@@ -1,6 +1,7 @@import * as p from '@clack/prompts'import { type Options as ExecaOptions, execa } from 'execa'import pc from 'picocolors'+import { backendTaskCommand, PREPARE_DATABASE } from './backend.js'import { hasMonorepoSpreePath } from './context.js'export async function dockerCompose(args: string[], projectDir: string, options?: ExecaOptions) {@@ -40,14 +41,14 @@ export async function primeBundleVolume(}}-export async function rakeTask(+export async function captureTask(task: string,projectDir: string,env?: Record<string, string>,): Promise<string> {- const stdout = await dockerComposeCapture(['bin/rails', task], projectDir, { env })+ const stdout = await dockerComposeCapture(backendTaskCommand(task), projectDir, { env })- // Rails boot prints noise to stdout (e.g. "[Spree Events] ...") — strip it+ // Backend boot prints noise to stdout (e.g. "[Spree Events] ...") — strip itreturn stdout.split('\n').filter((line) => !line.startsWith('['))@@ -153,7 +154,7 @@ export function dockerStackProblem(error: unknown, command: string): string[] {` ${pc.dim(reason.trim())}`,'',`Run ${pc.bold(command)} from your project root (the directory holding the`,- '.env with SECRET_KEY_BASE), and make sure Docker is running.',+ '.env file), and make sure Docker is running.',]}@@ -168,11 +169,11 @@ export interface DockerComposeExecOptions {}// Run a command inside a service container. The foundation for `spree exec`,-// `spree rails`, `spree bundle`, `spree rake`, and `spree console`.+// `spree task`, `spree test`, and `spree console`.//// Defaults to the `web` service and an interactive TTY. Pass `tty: false`// (which adds `-T`) for non-interactive callers that capture stdout — those-// should use `rakeTask` above, which already does this.+// should use `captureTask` above, which already does this.//// stdio is inherited so the command behaves transparently: a Rails console// stays interactive, a `bundle add` prints progress, an error exits with the@@ -263,7 +264,7 @@ export async function prepareDatabase(): Promise<void> {const stdio = options?.stdio ?? 'pipe'await dockerCompose(['up', '-d', '--wait', 'postgres'], projectDir, { stdio })- await dockerCompose(['run', '--rm', '--build', 'web', 'bin/rails', 'db:prepare'], projectDir, {+ await dockerCompose(['run', '--rm', '--build', 'web', ...PREPARE_DATABASE], projectDir, {stdio,})}@@ -309,7 +310,7 @@ async function resolveComposeMode(// Run a command in the service's container, transparently falling back to a// one-off `compose run` when the long-running container is down. This is the// shared shape behind every app-facing command (`spree migrate`, `spree-// bundle`, `spree console`, `spree rake`, …): exec into the live container if+// test`, `spree console`, `spree task`, …): exec into the live container if// it's up, otherwise boot a fresh one-off against the same warm DB/volumes.export async function dockerComposeExecOrRun(argv: string[],@@ -326,7 +327,7 @@ export async function dockerComposeExecOrRun(}// Captured-output twin of dockerComposeExecOrRun, for callers that parse-// stdout (rakeTask, `bundle list`). Non-interactive (`-T`) so a TTY never+// stdout (captureTask, `bundle list`). Non-interactive (`-T`) so a TTY never// mangles the captured stream; compose's own progress noise goes to stderr,// which stays off stdout and is buffered onto ExecaError for failure paths.export async function dockerComposeCapture(diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex 6bfe8b58d7..6103553791 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -24,12 +24,12 @@ import { registerRailsCommand } from './commands/rails.js'import { registerRakeCommand } from './commands/rake.js'import { registerRestartCommand } from './commands/restart.js'import { registerRoutesCommand } from './commands/routes.js'-import { registerRspecCommand } from './commands/rspec.js'import { registerSampleDataCommand } from './commands/sample-data.js'import { registerSeedCommand } from './commands/seed.js'import { registerShellCommand } from './commands/shell.js'import { registerStopCommand } from './commands/stop.js'import { registerTaskCommand } from './commands/task.js'+import { registerTestCommand } from './commands/test.js'import { registerUpgradeCommand } from './commands/upgrade.js'import { registerUserCommand } from './commands/user.js'import { VERSION } from './version.js'@@ -38,8 +38,8 @@ const program = new Command().name('spree').description('CLI for managing Spree Commerce projects').version(VERSION)- // Required by passThroughOptions on subcommands (exec/rails/bundle/rake/task/rspec)- // so flags like `ls -la` or `bin/rails routes -g foo` reach the inner command+ // Required by passThroughOptions on subcommands (exec/task/test/generate)+ // so flags like `ls -la` or `spree test --fail-fast` reach the inner command// instead of being parsed as options of the spree subcommand..enablePositionalOptions()// "did you mean …" on an unknown command/option (on by default; explicit so@@ -76,19 +76,21 @@ registerBuildCommand(program)registerGenerateCommand(program)registerMigrateCommand(program)registerDbCommand(program)-registerRoutesCommand(program)registerUpgradeCommand(program)// Run things inside the containerregisterExecCommand(program)-registerRailsCommand(program)-registerBundleCommand(program)-registerRakeCommand(program)registerTaskCommand(program)-registerRspecCommand(program)+registerTestCommand(program)registerConsoleCommand(program)registerShellCommand(program)+// Deprecated Rails-named commands (docs/plans/6.0-backend-agnostic-cli.md)+registerRailsCommand(program)+registerRakeCommand(program)+registerBundleCommand(program)+registerRoutesCommand(program)+// Spree-specific helpersregisterUserCommand(program)registerApiKeyCommand(program)diff --git a/packages/cli/src/lib/extensions.ts b/packages/cli/src/lib/extensions.tsindex 91ad32d417..63005627a8 100644--- a/packages/cli/src/lib/extensions.ts+++ b/packages/cli/src/lib/extensions.ts@@ -48,15 +48,29 @@ export function isValidNpmName(name: string): boolean {* `spree_<name>`, so a typo cannot install a stranger's gem.*/export function resolveExtension(name: string): CatalogEntry | undefined {+ return findExtension(name)?.[1]+}++function findExtension(name: string): [string, CatalogEntry] | undefined {const wanted = name.trim().toLowerCase().replaceAll('-', '_')return Object.entries(EXTENSIONS).find(([key, entry]) => key === wanted || entry.gem === wanted || entry.aliases?.includes(wanted),- )?.[1]+ )+}++/** The `spree add` command for a name: its catalog name, or `--gem` for one outside the catalog. */+export function addCommandFor(name: string): string {+ const found = findExtension(name)+ return found ? `spree add ${shortestName(...found)}` : `spree add --gem ${name}`}/** The shortest name of every catalog entry (`paypal`, not `paypal_checkout`), for help and errors. */export function extensionNames(): string[] {- return Object.entries(EXTENSIONS).map(([key, entry]) => entry.aliases?.[0] ?? key)+ return Object.entries(EXTENSIONS).map(([key, entry]) => shortestName(key, entry))+}++function shortestName(key: string, entry: CatalogEntry): string {+ return entry.aliases?.[0] ?? key}/** Whether the Gemfile already declares the gem (commented-out lines don't count). */diff --git a/packages/cli/tests/db.test.ts b/packages/cli/tests/db.test.tsindex e0c1929196..7f12a0f117 100644--- a/packages/cli/tests/db.test.ts+++ b/packages/cli/tests/db.test.ts@@ -1,6 +1,7 @@import { Command } from 'commander'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { RESET_TASK, registerDbCommand } from '../src/commands/db'+import { DATABASE_RESET } from '../src/backend'+import { registerDbCommand } from '../src/commands/db'import { dockerCompose, dockerComposeExec, dockerComposeRun, isServiceRunning } from '../src/docker'let projectDir: string@@ -76,7 +77,7 @@ describe('spree db:reset', () => {await runDbReset('--yes')- expect(dockerComposeRun).toHaveBeenCalledWith(RESET_TASK, '/proj', { captureStderr: true })+ expect(dockerComposeRun).toHaveBeenCalledWith(DATABASE_RESET, '/proj', { captureStderr: true })// Nothing to stop when the stack is already down.expect(dockerCompose).not.toHaveBeenCalled()})@@ -87,7 +88,7 @@ describe('spree db:reset', () => {await runDbReset('--yes')expect(dockerCompose).toHaveBeenCalledWith(['stop', 'web', 'worker'], '/proj')- expect(dockerComposeRun).toHaveBeenCalledWith(RESET_TASK, '/proj', { captureStderr: true })+ expect(dockerComposeRun).toHaveBeenCalledWith(DATABASE_RESET, '/proj', { captureStderr: true })// stop must precede the destructive run.const stopOrder = vi.mocked(dockerCompose).mock.invocationCallOrder[0]const runOrder = vi.mocked(dockerComposeRun).mock.invocationCallOrder[0]@@ -100,7 +101,7 @@ describe('spree db:reset', () => {await runDbReset('--yes')expect(dockerCompose).toHaveBeenCalledWith(['stop', 'web', 'worker'], '/proj')- expect(dockerComposeRun).toHaveBeenCalledWith(RESET_TASK, '/proj', { captureStderr: true })+ expect(dockerComposeRun).toHaveBeenCalledWith(DATABASE_RESET, '/proj', { captureStderr: true })})it('refuses in a monorepo edge project before touching the stack', async () => {diff --git a/packages/cli/tests/deprecated-commands.test.ts b/packages/cli/tests/deprecated-commands.test.tsnew file mode 100644index 0000000000..f80046f14f--- /dev/null+++ b/packages/cli/tests/deprecated-commands.test.ts@@ -0,0 +1,130 @@+import { Command } from 'commander'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { registerBundleCommand } from '../src/commands/bundle'+import { registerGenerateCommand } from '../src/commands/generate'+import { registerRailsCommand } from '../src/commands/rails'+import { registerRakeCommand } from '../src/commands/rake'+import { registerRoutesCommand } from '../src/commands/routes'+import { dockerComposeExecOrRun } from '../src/docker'++vi.mock('../src/context', () => ({+ detectProject: () => ({ mode: 'docker', projectDir: '/proj', port: 3000 }),+}))++vi.mock('../src/docker', () => ({+ dockerComposeExecOrRun: vi.fn().mockResolvedValue(undefined),+}))++async function run(argv: string[]): Promise<void> {+ const program = new Command().enablePositionalOptions()+ for (const register of [+ registerBundleCommand,+ registerGenerateCommand,+ registerRailsCommand,+ registerRakeCommand,+ registerRoutesCommand,+ ]) {+ register(program)+ }+ await program.parseAsync(argv, { from: 'user' })+}++// Rails-named commands keep their 6.x behaviour and name their replacement+// (docs/plans/6.0-backend-agnostic-cli.md).+describe('deprecated Rails-named commands', () => {+ let stderr: ReturnType<typeof vi.spyOn>++ beforeEach(() => {+ vi.clearAllMocks()+ stderr = vi.spyOn(console, 'error').mockImplementation(() => {})+ })++ afterEach(() => {+ vi.restoreAllMocks()+ })++ it.each([+ [+ ['rails', 'runner', 'puts 1'],+ ['bin/rails', 'runner', 'puts 1'],+ 'spree exec bin/rails runner',+ ],+ [+ ['rake', 'spree:search:reindex'],+ ['bin/rake', 'spree:search:reindex'],+ 'spree task search:reindex',+ ],+ [+ ['rake', 'db:rollback', 'STEP=2'],+ ['bin/rake', 'db:rollback', 'STEP=2'],+ 'spree exec bin/rake',+ ],+ [['bundle', 'add', 'spree_stripe'], ['bundle', 'add', 'spree_stripe'], 'spree add stripe'],+ [['bundle', 'add', 'paypal'], ['bundle', 'add', 'paypal'], 'spree add paypal'],+ [['bundle', 'add', 'spree_foo'], ['bundle', 'add', 'spree_foo'], 'spree add --gem spree_foo'],+ [+ ['bundle', 'add', '--version', '~> 6.0', 'spree_stripe'],+ ['bundle', 'add', '--version', '~> 6.0', 'spree_stripe'],+ 'spree exec bundle add --version ~> 6.0 spree_stripe',+ ],+ [['bundle', 'outdated'], ['bundle', 'outdated'], 'spree exec bundle outdated'],+ [['routes'], ['bin/rails', 'routes'], 'spree api endpoints'],+ [+ ['routes', '-g', 'products'],+ ['bin/rails', 'routes', '-g', 'products'],+ 'spree exec bin/rails routes -g products',+ ],+ [+ ['bundle', 'add', 'spree_stripe', '--version', '6.0'],+ ['bundle', 'add', 'spree_stripe', '--version', '6.0'],+ 'spree exec bundle add spree_stripe --version 6.0',+ ],+ ])('spree %j still runs and points at the replacement', async (argv, inner, replacement) => {+ await run(argv)++ expect(dockerComposeExecOrRun).toHaveBeenCalledWith(+ inner,+ '/proj',+ ...(argv[0] === 'bundle' ? [expect.any(Object)] : []),+ )+ expect(stderr).toHaveBeenCalledWith(expect.stringContaining(replacement))+ })+})++describe('spree generate', () => {+ let stderr: ReturnType<typeof vi.spyOn>++ beforeEach(() => {+ vi.clearAllMocks()+ stderr = vi.spyOn(console, 'error').mockImplementation(() => {})+ })++ afterEach(() => {+ vi.restoreAllMocks()+ })++ it.each([+ [+ ['generate', 'api_resource', 'Brand', 'name:string'],+ ['spree:api_resource', 'Brand', 'name:string'],+ ],+ [+ ['g', 'model_decorator', 'Product'],+ ['spree:model_decorator', 'Product'],+ ],+ [+ ['generate', 'migration', 'AddX'],+ ['migration', 'AddX'],+ ],+ [['generate', 'spree:install'], ['spree:install']],+ [['generate', 'spree_stripe:install'], ['spree_stripe:install']],+ ])('spree %j runs without a notice', async (argv, generatorArgs) => {+ await run(argv)++ expect(dockerComposeExecOrRun).toHaveBeenCalledWith(+ ['bin/rails', 'generate', ...generatorArgs],+ '/proj',+ )+ expect(stderr).not.toHaveBeenCalled()+ })+})diff --git a/packages/cli/tests/docker.test.ts b/packages/cli/tests/docker.test.tsindex cf9ced26f5..cdd615cae3 100644--- a/packages/cli/tests/docker.test.ts+++ b/packages/cli/tests/docker.test.ts@@ -16,11 +16,11 @@ vi.mock('@clack/prompts', () => ({import { execa } from 'execa'import {+ captureTask,dockerComposeCapture,dockerComposeExecOrRun,dockerComposeRun,prepareDatabase,- rakeTask,} from '../src/docker'const mockExeca = vi.mocked(execa)@@ -285,7 +285,7 @@ describe('dockerComposeCapture', () => {})})-describe('rakeTask', () => {+describe('captureTask', () => {beforeEach(() => {monorepoEdge = falselogInfoMock.mockClear()@@ -294,10 +294,10 @@ describe('rakeTask', () => {afterEach(() => vi.restoreAllMocks())- it('strips Rails boot noise from the captured output', async () => {+ it('strips backend boot noise from the captured output', async () => {routeExeca(true, '[Spree Events] subscribers loaded\napi_key_abc\n')- await expect(rakeTask('spree:cli:ensure_api_key', '/proj')).resolves.toBe('api_key_abc')+ await expect(captureTask('spree:cli:ensure_api_key', '/proj')).resolves.toBe('api_key_abc')expect(mockExeca).toHaveBeenCalledWith('docker',['compose', 'exec', '-T', 'web', 'bin/rails', 'spree:cli:ensure_api_key'],@@ -308,7 +308,7 @@ describe('rakeTask', () => {it('falls back to a one-off container when web is down', async () => {routeExeca(false, 'seeded')- await expect(rakeTask('db:seed', '/proj')).resolves.toBe('seeded')+ await expect(captureTask('db:seed', '/proj')).resolves.toBe('seeded')expect(mockExeca).toHaveBeenCalledWith('docker',['compose', 'run', '--rm', '-T', 'web', 'bin/rails', 'db:seed'],diff --git a/packages/cli/tests/filters.test.ts b/packages/cli/tests/filters.test.tsindex 98f822faa4..f25b3f389c 100644--- a/packages/cli/tests/filters.test.ts+++ b/packages/cli/tests/filters.test.ts@@ -4,13 +4,13 @@ import { join } from 'node:path'import { Command } from 'commander'import { beforeEach, describe, expect, it, vi } from 'vitest'import { parseFilterTables, registerFiltersCommand } from '../src/commands/filters'-import { rakeTask } from '../src/docker'+import { captureTask } from '../src/docker'let projectDir = '/proj'vi.mock('../src/context', () => ({detectProject: () => ({ mode: 'docker', projectDir, port: 3000 }),}))-vi.mock('../src/docker', () => ({ rakeTask: vi.fn() }))+vi.mock('../src/docker', () => ({ captureTask: vi.fn() }))vi.mock('@clack/prompts', () => ({ log: { success: vi.fn(), error: vi.fn(), info: vi.fn() } }))const predicates = {@@ -77,11 +77,11 @@ describe('spree filters types', () => {projectDir = dirmkdirSync(join(dir, 'apps', 'storefront'), { recursive: true })mkdirSync(join(dir, 'apps', 'dashboard'), { recursive: true })- vi.mocked(rakeTask).mockResolvedValue(taskOutput)+ vi.mocked(captureTask).mockResolvedValue(taskOutput)await run([])- expect(rakeTask).toHaveBeenCalledTimes(1)+ expect(captureTask).toHaveBeenCalledTimes(1)const types = (app: string) => join(dir, 'apps', app, 'src', 'types', 'spree-filters.d.ts')expect(readFileSync(types('storefront'), 'utf8')).toContain("declare module '@spree/sdk'")expect(readFileSync(types('dashboard'), 'utf8')).toContain("declare module '@spree/admin-sdk'")@@ -92,19 +92,19 @@ describe('spree filters types', () => {projectDir = dirawait run([])- expect(rakeTask).not.toHaveBeenCalled()+ expect(captureTask).not.toHaveBeenCalled()expect(process.exitCode).toBe(1)process.exitCode = undefined})it("declares the app's filters and sort fields for the chosen SDK", async () => {- vi.mocked(rakeTask).mockResolvedValue(taskOutput)+ vi.mocked(captureTask).mockResolvedValue(taskOutput)const out = join(dir, 'spree-filters.d.ts')await run(['--api', 'admin', '--out', out])const file = readFileSync(out, 'utf8')- expect(rakeTask).toHaveBeenCalledWith('spree:api:filter_tables', '/proj')+ expect(captureTask).toHaveBeenCalledWith('spree:api:filter_tables', '/proj')expect(file).toContain("declare module '@spree/admin-sdk'")expect(file).toContain("Filter.TextFilters<'erp_id' | 'name'>")expect(file).toContain('interface ProductFilterExtensions extends AppProductFilters {}')@@ -119,7 +119,7 @@ describe('spree filters types', () => {await run(['--from', from, '--out', out])- expect(rakeTask).not.toHaveBeenCalled()+ expect(captureTask).not.toHaveBeenCalled()expect(readFileSync(out, 'utf8')).toContain("declare module '@spree/sdk'")})diff --git a/packages/cli/tests/migrate.test.ts b/packages/cli/tests/migrate.test.tsindex f3a68421be..b6a89cebd3 100644--- a/packages/cli/tests/migrate.test.ts+++ b/packages/cli/tests/migrate.test.ts@@ -1,7 +1,7 @@import { Command } from 'commander'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { registerMigrateCommand } from '../src/commands/migrate'-import { dockerComposeExec, dockerComposeExecOrRun, isServiceRunning } from '../src/docker'+import { dockerComposeExecOrRun } from '../src/docker'let projectDir: string@@ -10,9 +10,7 @@ vi.mock('../src/context', () => ({}))vi.mock('../src/docker', () => ({- dockerComposeExec: vi.fn().mockResolvedValue(undefined),dockerComposeExecOrRun: vi.fn().mockResolvedValue(undefined),- isServiceRunning: vi.fn().mockResolvedValue(true),}))vi.mock('@clack/prompts', () => ({ note: vi.fn() }))@@ -20,42 +18,40 @@ vi.mock('@clack/prompts', () => ({ note: vi.fn() }))async function runMigrate(argv: string[]): Promise<void> {// The real root program enables positional options (src/index.ts), which// commander requires for subcommands using passThroughOptions.- const program = new Command().enablePositionalOptions()+ const program = new Command().enablePositionalOptions().exitOverride()registerMigrateCommand(program)await program.parseAsync(argv, { from: 'user' })}+// Branching (exec vs one-off run vs monorepo-edge refusal) is covered by+// dockerComposeExecOrRun's own tests in docker.test.ts; here we only assert+// the commands delegate with the right argv.describe('spree migrate', () => {+ let stderr: ReturnType<typeof vi.spyOn>+beforeEach(() => {projectDir = '/proj'vi.clearAllMocks()- vi.mocked(isServiceRunning).mockResolvedValue(true)vi.spyOn(console, 'log').mockImplementation(() => {})+ stderr = vi.spyOn(console, 'error').mockImplementation(() => {})})afterEach(() => {vi.restoreAllMocks()})- it('runs install + migrate as separate steps when web is up', async () => {- await runMigrate(['migrate', 'VERSION=20260101000000'])+ it('installs and runs pending migrations in one invocation', async () => {+ await runMigrate(['migrate'])- expect(dockerComposeExec).toHaveBeenNthCalledWith(- 1,- ['bin/rails', 'spree:install:migrations'],- '/proj',- )- expect(dockerComposeExec).toHaveBeenNthCalledWith(- 2,- ['bin/rails', 'db:migrate', 'VERSION=20260101000000'],+ expect(dockerComposeExecOrRun).toHaveBeenCalledWith(+ ['bin/rails', 'spree:install:migrations', 'db:migrate'],'/proj',+ { edgeHint: expect.any(String) },)- expect(dockerComposeExecOrRun).not.toHaveBeenCalled()+ expect(stderr).not.toHaveBeenCalled()})- it('collapses both steps into one one-off invocation when web is down', async () => {- vi.mocked(isServiceRunning).mockResolvedValue(false)-+ it('still forwards raw migrate args, with a deprecation notice', async () => {await runMigrate(['migrate', 'VERSION=20260101000000'])expect(dockerComposeExecOrRun).toHaveBeenCalledWith(@@ -63,19 +59,56 @@ describe('spree migrate', () => {'/proj',{ edgeHint: expect.any(String) },)- expect(dockerComposeExec).not.toHaveBeenCalled()+ expect(stderr).toHaveBeenCalledWith(expect.stringContaining('deprecated'))})- // Branching (exec vs one-off run vs monorepo-edge refusal) for the- // subcommands below is covered by dockerComposeExecOrRun's own tests in- // docker.test.ts; here we only assert they delegate with the right argv.- it('migrate:rollback delegates with forwarded args', async () => {+ it('migrate:rollback --steps rolls back n migrations', async () => {+ await runMigrate(['migrate:rollback', '--steps', '2'])++ expect(dockerComposeExecOrRun).toHaveBeenCalledWith(+ ['bin/rails', 'db:rollback', 'STEP=2'],+ '/proj',+ )+ expect(stderr).not.toHaveBeenCalled()+ })++ it('migrate:rollback STEP=n still works and points at --steps', async () => {await runMigrate(['migrate:rollback', 'STEP=2'])expect(dockerComposeExecOrRun).toHaveBeenCalledWith(['bin/rails', 'db:rollback', 'STEP=2'],'/proj',)+ expect(stderr).toHaveBeenCalledWith(expect.stringContaining('--steps 2'))+ })++ it('migrate:rollback reads --steps after a leftover STEP= and drops the STEP=', async () => {+ await runMigrate(['migrate:rollback', 'STEP=2', '--steps', '3'])++ expect(dockerComposeExecOrRun).toHaveBeenCalledWith(+ ['bin/rails', 'db:rollback', 'STEP=3'],+ '/proj',+ )+ expect(stderr).not.toHaveBeenCalled()+ })++ it('migrate:rollback points other raw args at spree exec', async () => {+ await runMigrate(['migrate:rollback', 'VERSION=20260101000000'])++ expect(dockerComposeExecOrRun).toHaveBeenCalledWith(+ ['bin/rails', 'db:rollback', 'VERSION=20260101000000'],+ '/proj',+ )+ expect(stderr).toHaveBeenCalledWith(+ expect.stringContaining('spree exec bin/rails db:rollback VERSION=20260101000000'),+ )+ })++ it('migrate:rollback rejects a non-positive --steps', async () => {+ await expect(runMigrate(['migrate:rollback', '--steps', '0'])).rejects.toThrow(+ /positive whole number/,+ )+ expect(dockerComposeExecOrRun).not.toHaveBeenCalled()})it('migrate:status delegates', async () => {diff --git a/packages/cli/tests/rspec.test.ts b/packages/cli/tests/rspec.test.tsdeleted file mode 100644index 82c8b621f7..0000000000--- a/packages/cli/tests/rspec.test.ts+++ /dev/null@@ -1,71 +0,0 @@-import { Command } from 'commander'-import { beforeEach, describe, expect, it, vi } from 'vitest'-import { registerRspecCommand } from '../src/commands/rspec'-import { dockerComposeExecOrRun } from '../src/docker'--let projectDir: string--vi.mock('../src/context', () => ({- detectProject: () => ({ mode: 'docker', projectDir, port: 3000 }),-}))--vi.mock('../src/docker', () => ({- dockerComposeExecOrRun: vi.fn().mockResolvedValue(undefined),-}))--async function runRspec(args: string[] = []): Promise<void> {- const program = new Command().enablePositionalOptions()- registerRspecCommand(program)- await program.parseAsync(['rspec', ...args], { from: 'user' })-}--describe('spree rspec', () => {- beforeEach(() => {- projectDir = '/proj'- vi.clearAllMocks()- })-- // Branching (exec vs one-off run vs monorepo-edge refusal) is covered by- // dockerComposeExecOrRun's own tests in docker.test.ts; here we assert the- // delegation shape: `bundle exec rspec` + forwarded args + RAILS_ENV=test.- it('runs the full suite with RAILS_ENV=test when called bare', async () => {- await runRspec()-- expect(dockerComposeExecOrRun).toHaveBeenCalledWith(['bundle', 'exec', 'rspec'], '/proj', {- env: { RAILS_ENV: 'test' },- edgeHint: 'then re-run spree rspec',- })- })-- it('forwards file paths and line numbers', async () => {- await runRspec(['spec/models/spree/brand_spec.rb:15'])-- expect(dockerComposeExecOrRun).toHaveBeenCalledWith(- ['bundle', 'exec', 'rspec', 'spec/models/spree/brand_spec.rb:15'],- '/proj',- expect.objectContaining({ env: { RAILS_ENV: 'test' } }),- )- })-- // Leading flags have no preceding positional, so they rely on- // allowUnknownOption (passThroughOptions alone only covers flags after one).- it('forwards leading rspec flags instead of parsing them', async () => {- await runRspec(['--format', 'documentation'])-- expect(dockerComposeExecOrRun).toHaveBeenCalledWith(- ['bundle', 'exec', 'rspec', '--format', 'documentation'],- '/proj',- expect.objectContaining({ env: { RAILS_ENV: 'test' } }),- )- })-- it('forwards flags following a path untouched', async () => {- await runRspec(['spec/features/', '--fail-fast'])-- expect(dockerComposeExecOrRun).toHaveBeenCalledWith(- ['bundle', 'exec', 'rspec', 'spec/features/', '--fail-fast'],- '/proj',- expect.objectContaining({ env: { RAILS_ENV: 'test' } }),- )- })-})diff --git a/packages/cli/tests/test.test.ts b/packages/cli/tests/test.test.tsnew file mode 100644index 0000000000..369c928146--- /dev/null+++ b/packages/cli/tests/test.test.ts@@ -0,0 +1,101 @@+import { Command } from 'commander'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { testCommand } from '../src/backend'+import { registerTestCommand } from '../src/commands/test'+import { dockerComposeExecOrRun } from '../src/docker'++let projectDir: string++vi.mock('../src/context', () => ({+ detectProject: () => ({ mode: 'docker', projectDir, port: 3000 }),+}))++vi.mock('../src/docker', () => ({+ dockerComposeExecOrRun: vi.fn().mockResolvedValue(undefined),+}))++async function runTests(args: string[] = [], command = 'test'): Promise<void> {+ const program = new Command().enablePositionalOptions()+ registerTestCommand(program)+ await program.parseAsync([command, ...args], { from: 'user' })+}++describe('testCommand', () => {+ // `$0` is the script's name, so forwarded arguments start at `$1` and reach+ // the runner through `"$@"` with their quoting intact.+ it('creates the test database before running the suite', () => {+ expect(testCommand(['spec/models', '--fail-fast'])).toEqual([+ 'sh',+ '-c',+ 'VERBOSE=false bin/rails db:create && exec bundle exec rspec "$@"',+ 'spree test',+ 'spec/models',+ '--fail-fast',+ ])+ })+})++describe('spree test', () => {+ beforeEach(() => {+ projectDir = '/proj'+ vi.clearAllMocks()+ })++ // Branching (exec vs one-off run vs monorepo-edge refusal) is covered by+ // dockerComposeExecOrRun's own tests in docker.test.ts; here we assert the+ // delegation shape: the backend's test command + forwarded args + RAILS_ENV=test.+ it('runs the full suite with RAILS_ENV=test when called bare', async () => {+ await runTests()++ expect(dockerComposeExecOrRun).toHaveBeenCalledWith(testCommand([]), '/proj', {+ env: { RAILS_ENV: 'test' },+ edgeHint: 'then re-run spree test',+ })+ })++ it('forwards file paths and line numbers', async () => {+ await runTests(['spec/models/spree/brand_spec.rb:15'])++ expect(dockerComposeExecOrRun).toHaveBeenCalledWith(+ testCommand(['spec/models/spree/brand_spec.rb:15']),+ '/proj',+ expect.objectContaining({ env: { RAILS_ENV: 'test' } }),+ )+ })++ // Leading flags have no preceding positional, so they rely on+ // allowUnknownOption (passThroughOptions alone only covers flags after one).+ it('forwards leading rspec flags instead of parsing them', async () => {+ await runTests(['--format', 'documentation'])++ expect(dockerComposeExecOrRun).toHaveBeenCalledWith(+ testCommand(['--format', 'documentation']),+ '/proj',+ expect.objectContaining({ env: { RAILS_ENV: 'test' } }),+ )+ })++ it('forwards flags following a path untouched', async () => {+ await runTests(['spec/features/', '--fail-fast'])++ expect(dockerComposeExecOrRun).toHaveBeenCalledWith(+ testCommand(['spec/features/', '--fail-fast']),+ '/proj',+ expect.objectContaining({ env: { RAILS_ENV: 'test' } }),+ )+ })++ it('keeps `spree rspec` working with a deprecation notice', async () => {+ const stderr = vi.spyOn(console, 'error').mockImplementation(() => {})++ await runTests(['spec/models'], 'rspec')++ expect(dockerComposeExecOrRun).toHaveBeenCalledWith(+ testCommand(['spec/models']),+ '/proj',+ expect.objectContaining({ env: { RAILS_ENV: 'test' } }),+ )+ expect(stderr).toHaveBeenCalledWith(expect.stringContaining('spree test'))+ stderr.mockRestore()+ })+})diff --git a/packages/cli/tests/upgrade.test.ts b/packages/cli/tests/upgrade.test.tsindex 88f72ced46..3f096cb1f3 100644--- a/packages/cli/tests/upgrade.test.ts+++ b/packages/cli/tests/upgrade.test.ts@@ -210,7 +210,7 @@ describe('detectSpreeGems', () => {if (args.includes('install')) return { stdout: '' }throw Object.assign(new Error('x'), { exitCode: 1, stderr: 'Could not find gem spree_core' })}) as never)- await expect(detectSpreeGems('/proj')).rejects.toThrow(/even after `bundle install`/)+ await expect(detectSpreeGems('/proj')).rejects.toThrow(/even after reinstalling/)await expect(detectSpreeGems('/proj')).rejects.toThrow(/Could not find gem spree_core/)})})@@ -587,7 +587,7 @@ describe('spree upgrade', () => {'pnpm update @spree/dashboard','pnpm dedupe','docker compose exec web bin/rails spree:install:migrations db:migrate',- 'docker compose exec web bin/rake spree:upgrade',+ 'docker compose exec web bin/rails spree:upgrade','docker compose restart web',])})@@ -605,7 +605,7 @@ describe('spree upgrade', () => {'pnpm dedupe','docker compose up -d --no-deps web','docker compose up -d --wait',- 'docker compose exec web bin/rake spree:upgrade',+ 'docker compose exec web bin/rails spree:upgrade',])})@@ -767,7 +767,7 @@ describe('spree upgrade', () => {await expect(runUpgrade()).rejects.toThrow(/spree:upgrade failed/)expect(commands).toContain('pnpm update @spree/dashboard')- expect(commands.at(-1)).toBe('docker compose exec web bin/rake spree:upgrade')+ expect(commands.at(-1)).toBe('docker compose exec web bin/rails spree:upgrade')})describe('when `compose ps` fails', () => {@@ -859,8 +859,8 @@ describe('spree upgrade', () => {await runUpgrade(['--step', 'channels'])expect(commands).toEqual([- 'docker compose exec -e DRY_RUN=1 web bin/rake spree:upgrade',- 'docker compose exec -e STEP=channels web bin/rake spree:upgrade',+ 'docker compose exec -e DRY_RUN=1 web bin/rails spree:upgrade',+ 'docker compose exec -e STEP=channels web bin/rails spree:upgrade',])})})diff --git a/packages/create-spree-app/src/templates/readme.ts b/packages/create-spree-app/src/templates/readme.tsindex 62a806dfc4..03adcee295 100644--- a/packages/create-spree-app/src/templates/readme.ts+++ b/packages/create-spree-app/src/templates/readme.ts@@ -104,7 +104,7 @@ ${run} spree ejectThis rebuilds the Docker image from \`server/\` and restarts services. You can then:- **Customize the API** by editing the files in \`server/\`-- **Add gems** to \`server/Gemfile\`+- **Add extensions** with \`spree add <extension>\`- **Add new resources** with \`spree generate model <name> <attributes>\`## Spree CLI@@ -122,13 +122,13 @@ This project uses [\`@spree/cli\`](https://spreecommerce.org/docs/developer/cli/| \`spree build --production\` | Build the production image — includes \`apps/dashboard\` when present || \`spree logs\` | View web server logs || \`spree logs worker\` | View background jobs logs |-| \`spree console\` | Open Rails console |+| \`spree console\` | Open an interactive backend console |### Data| Command | Description ||---------|-------------|-| \`spree migrate\` | Install pending Spree migrations from gems, then run them or just run your own migrations |+| \`spree migrate\` | Install pending Spree migrations, then run them along with your own || \`spree seed\` | Seed the database || \`spree sample-data\` | Load sample products, categories, images |diff --git a/scripts/docker-compose.meilisearch.yml b/scripts/docker-compose.meilisearch.ymlindex 2a17e88296..2a3a2d47df 100644--- a/scripts/docker-compose.meilisearch.yml+++ b/scripts/docker-compose.meilisearch.yml@@ -6,7 +6,7 @@# The pnpm server:* scripts chain this file when SPREE_MEILISEARCH is set:## SPREE_MEILISEARCH=1 pnpm server:dev-# cd server && pnpm exec spree rake spree:search:reindex # first boot only+# cd server && pnpm exec spree task search:reindex # first boot only## Dropping the flag on the next `pnpm server:dev` recreates web without# MEILISEARCH_URL (back to DB search) and removes the meilisearch containerdiff --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 d70e42cad8..20aa813e4d 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@@ -108,7 +108,7 @@ module Spree# Override parent: skip if the model existed before this run. Migrations# are append-only — schema changes get a separate migration:- # pnpm exec spree rails g migration AddFooToBar foo:string+ # pnpm exec spree generate migration AddFooToBar foo:stringdef create_migration_fileif @model_existed_before_runsay_status :skip, 'migration (model already exists; add a new migration for schema changes)', :yellow@@ -295,7 +295,7 @@ module Spreeendsay " 4. Add `has_many :#{plural_name}` to Spree::Store" if store_scoped?if options[:store] || options[:admin]- say " #{store_scoped? ? 5 : 4}. Run the specs: pnpm exec spree rspec spec/controllers/spree/api/v3/"+ say " #{store_scoped? ? 5 : 4}. Run the specs: pnpm exec spree test spec/controllers/spree/api/v3/"endsay ''end