Skip to content

armgit / spree

Public Imported from GitHub
0

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

Changed agent instructions from CLAUDE.md to lean AGENTS.md files (#15002)

Damian Legawiec72a77c4de278
diff --git a/.claude/agents/architect.md b/.claude/agents/architect.md
index 58f4e87a46..c2764e1951 100644
--- a/.claude/agents/architect.md
+++ b/.claude/agents/architect.md
@@ -14,4 +14,3 @@ When reviewing code changes:
- Check if any active plan's constraints are being violated
- Flag when implementation diverges from a finalized plan
-Always update root CLAUDE.md when adding or changing plan status.
diff --git a/.claude/commands/create-plan.md b/.claude/commands/create-plan.md
index b645829fae..8481f591ab 100644
--- a/.claude/commands/create-plan.md
+++ b/.claude/commands/create-plan.md
@@ -9,7 +9,7 @@ Follow this process:
4. **Resolve every open question interactively before finishing** — see below
5. **Open the tracking issues in Linear and GitHub** and record them in the
plan's `Tracking` header line — see below
-6. If the plan affects specific areas of the codebase, add cross-references in relevant directory-level CLAUDE.md files
+6. If the plan affects specific areas of the codebase, add cross-references in relevant directory-level AGENTS.md files
The filename should follow the pattern: `{release}-{feature-slug}.md`
(e.g., `6.0-cart-order-split.md`, `future-mcp-server.md`)
diff --git a/.claude/commands/implement-plan.md b/.claude/commands/implement-plan.md
index 10bb53b4e6..44df6a60f0 100644
--- a/.claude/commands/implement-plan.md
+++ b/.claude/commands/implement-plan.md
@@ -92,7 +92,7 @@ reason.
on the issue's `gitBranchName` (read it with `get_issue`).
- Start with `/goal` so the run has a stated goal to check itself against:
the deliverables from stage 1 plus green changed specs and green CI.
-- Follow the plan's phase order and every convention in `CLAUDE.md` (models,
+- Follow the plan's phase order and every convention in the `AGENTS.md` files (models,
migrations, API controllers, serializers, dashboard, translations in every
locale, type generation pipeline when serializers change, OpenAPI regenerated
from the integration specs — never edited by hand).
diff --git a/.claude/hooks/pre-commit-gate.sh b/.claude/hooks/pre-commit-gate.sh
index ba92c377f5..7f7940fc71 100755
--- a/.claude/hooks/pre-commit-gate.sh
+++ b/.claude/hooks/pre-commit-gate.sh
@@ -18,7 +18,7 @@ set -u
cmd=$(jq -r '.tool_input.command // empty')
# Full test suites are queued machine-wide and are otherwise CI's job (see
-# CLAUDE.md "Testing"). Block the bare forms so a session that has not read the
+# AGENTS.md "Testing"). Block the bare forms so a session that has not read the
# rule is redirected to the wrappers; targeted `rspec <paths>` runs pass.
while IFS= read -r segment; do
seg="${segment#"${segment%%[![:space:]]*}"}"
@@ -33,7 +33,7 @@ while IFS= read -r segment; do
echo " pnpm test:changed specs covering this branch's changed files"
echo " pnpm test:rspec <engine> [paths] one engine; a full suite is queued, capped and low priority"
echo " pnpm wt:e2e [spec] Playwright, queued the same way"
- echo "Then push and watch CI for the full suite. If these commands are missing, run 'git merge main' first. See CLAUDE.md, Testing."
+ echo "Then push and watch CI for the full suite. If these commands are missing, run 'git merge main' first. See AGENTS.md, Testing."
} >&2
exit 2
fi
diff --git a/AGENTS.md b/AGENTS.md
deleted file mode 120000
index 681311eb9c..0000000000
--- a/AGENTS.md
+++ /dev/null
@@ -1 +0,0 @@
-CLAUDE.md
\ No newline at end of file
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000000..7815a7290e
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,92 @@
+# Spree Commerce — Development Rules
+
+Area rules live next to the code and load when you work there: `spree/AGENTS.md` (Ruby gems, APIs, RSpec), `packages/AGENTS.md` (TypeScript packages, dashboards, Playwright) and `docs/AGENTS.md` (documentation site). Anything not covered follows standard Ruby on Rails 8.1 and React / TanStack / Vite practice — these files only record what this codebase does differently or what has bitten us before.
+
+## Plans
+
+Feature plans live in `docs/plans/`, written from `docs/plans/_template.md` — never anywhere else. Before a significant architectural change, check existing plans for conflicts, including their "Constraints on Current Work" sections, which apply even when you aren't implementing that plan. Use `/create-plan`, `/update-plan`, and `/implement-plan <plan>` to deliver one end to end.
+
+## Monorepo structure
+
+| Directory | Contents |
+| --- | --- |
+| `spree/core` | `spree_core` — models, workflows, services, business logic |
+| `spree/api` | `spree_api` — Store, Admin and Seller REST APIs (v3) |
+| `spree/emails` | `spree_emails` (optional) — transactional emails; the default for installations without a storefront that sends its own |
+| `spree/dashboard` | `spree_dashboard` (optional) — serves a built dashboard at `/dashboard` and seller panel at `/sellers` from the Rails node |
+| `spree/mcp` | `spree_mcp` — MCP server for the back office, under the Admin API's tenancy and permission rules |
+| `spree/opentelemetry` | `spree_opentelemetry` — distributed tracing |
+| `spree/providers/*` | Provider gems with flat names: `spree_easypost` (rates, labels), `spree_meilisearch` (product search), `spree_stripe` (payments) |
+| `packages/dashboard` | `@spree/dashboard` — React admin SPA: routes, schemas, resource hooks, locales |
+| `packages/dashboard-core` | `@spree/dashboard-core` — framework and plugin API: registries, providers, shared hooks and components, admin SDK client |
+| `packages/dashboard-ui` | `@spree/dashboard-ui` — design system (shadcn on Base UI); source-only, headless |
+| `packages/seller-dashboard` | `@spree/seller-dashboard` — seller panel for marketplaces |
+| `packages/dashboard-starter`, `packages/seller-dashboard-starter` | Thin host apps; canonical source of the public starter template repos and the in-repo test of the plugin pipeline |
+| `packages/dashboard-plugin-example` | Reference dashboard plugin used by the plugin docs |
+| `packages/sdk`, `admin-sdk`, `seller-sdk` | TypeScript clients for the Store, Admin and Seller APIs |
+| `packages/core` | `@spree/core` — universal TypeScript with no HTTP: code lists, enums, money helpers, filter vocabulary |
+| `packages/sdk-core` | Private shared HTTP, retry and error layer for the SDKs |
+| `packages/cli`, `packages/create-spree-app` | `@spree/cli` and project scaffolding |
+| `packages/docs` | `@spree/docs` — offline docs package for AI agents |
+| `docs/` | Mintlify site deployed to spreecommerce.org/docs |
+| `server/`, `storefront/` | Gitignored per-worktree clones of `spree/spree-starter` and `spree/storefront` |
+
+## Development environment
+
+Work happens in git worktrees managed by [worktrunk](https://worktrunk.dev) (`wt`). Each one gets its own `server/` (monorepo gems loaded as path gems), its own Postgres database copied from a seeded template, and stable https URLs through portless. The main checkout is for integration, not for running servers. Don't use the Docker-based `pnpm server:*` commands in worktrees.
+
+```bash
+wt switch -c feature-x # new worktree + provisioned environment
+pnpm wt:dev # Rails → https://feature-x.spree.localhost
+pnpm wt:dashboard # admin → https://admin.feature-x.spree.localhost
+pnpm wt:seller # seller panel → https://sellers.feature-x.spree.localhost
+pnpm wt:storefront # Next.js storefront → https://store.feature-x.spree.localhost
+pnpm wt:e2e [spec...] # Playwright against this worktree
+pnpm wt:template # rebuild the template DB after schema-changing pulls
+```
+
+- Logins: admin `[email protected]` / `spree123`; seller `[email protected]` / `spree123` after `cd server && bin/rails spree:sellers:sample_data`.
+- A new gem migration needs `cd server && bin/rails spree:install:migrations db:migrate`, then `pnpm wt:template`. Ruby under `app/` reloads per request; changes under a gem's `lib/` need a server restart.
+- Emails land in Mailpit at <http://localhost:8025>.
+- `storefront/` keeps its own `.git` — commit and push from inside it before `wt remove`. Never commit its `pnpm-lock.yaml` (it points at this worktree's SDK). Re-run `pnpm wt:storefront` to pick up SDK or serializer changes.
+- **Never stop dev servers that are already running** unless they are broken.
+- **Cloud sessions** (`CLAUDE_CODE_REMOTE=true`) have no worktrees or portless: start servers with `scripts/cloud/start.sh [rails|dashboard|seller|all]` and check UI changes with `node scripts/cloud/screenshot.mjs <url> <out.png> --login`.
+
+## General rules
+
+- Write to humans in plain, precise English — no jargon or abbreviations, short sentences, lists over walls of text.
+- Comment only non-obvious code. No comments on removed code, framework-native calls, shapes or serializers. Docs explain what and why, never internal how.
+- Reuse before you add: search for an existing helper, component or concern first. Fewer lines is the goal.
+- Assume hostile input: validate, scope every lookup to the tenant, never trust client-supplied types or ids.
+- The admin dashboard is the reference implementation. Seller panel features reuse its code by moving shared pieces into `dashboard-core` / `dashboard-ui`.
+
+## API contract (applies to Ruby, SDKs and dashboards alike)
+
+- **Prefixed IDs** (`prod_86Rf07xd4z`) in every request, response and event payload — never raw integer ids. IDs are strings; never cast them to integers.
+- **No Ruby class names on the wire** — not in requests, responses, filters, webhooks, permission subjects, SDK types or docs. Use the short `api_type` name (`Spree::PriceRules::VolumeRule` → `volume_rule`). Details in `spree/AGENTS.md`.
+- **Read and write names match.** A field a serializer exposes is accepted under the same name on write; legacy column names are bridged on the model, never by the client.
+- **Deprecate, never remove.** Store, Admin and Seller APIs are stable contracts: a renamed field keeps working, marked `deprecated:`, until the next minor release, and the upgrade guide names its replacement. Ruby renames keep the old name working for one release with a deprecation warning.
+- **Money is never a float**, in Ruby or TypeScript (`docs/plans/6.0-money-correctness.md`).
+- **One store per installation.** Store-owned data belongs to a store; cross-store sharing is gone.
+
+## Git
+
+- Never commit to `main`. Branches start with `feat/`, `fix/` or `chore/`; bug-fix commits start with `Fix: `.
+- Titles use plain verbs (Added, Removed, Fixed, Changed). Bodies are three or four sentences on what and why.
+- No co-author or "generated with" trailers.
+- Pull request descriptions are public: no credentials, personal data or local URLs. Keep them short; bullets for larger changes.
+
+## Testing
+
+Many sessions share this machine. Every Ruby test run goes through `scripts/test/` — **never a bare `parallel_rspec`** (a hook blocks it):
+
+```bash
+pnpm test:changed # specs covering this branch's changes — run before pushing
+pnpm test:changed -- --list # what would run, and which changes have no spec
+pnpm test:rspec core spec/models/spree/state_spec.rb:7 # targeted run in one engine
+pnpm test:rspec api # a full engine suite (queued machine-wide)
+```
+
+The full suite is CI's job: push and watch `gh pr checks --watch`. Run a full suite locally only to reproduce a CI failure, or when a change touches everything (a factory, a migration, `Spree::Base`). Engines: `core`, `api`, `emails`, `dashboard`, `opentelemetry`, `easypost`, `meilisearch`, `stripe`.
+
+Every behaviour change a merchant or seller can see — including a backend-only validation or status rule — ships with a Playwright spec (see `packages/AGENTS.md`).
diff --git a/CLAUDE.md b/CLAUDE.md
deleted file mode 100644
index 8b4992ebda..0000000000
--- a/CLAUDE.md
+++ /dev/null
@@ -1,865 +0,0 @@
-# Spree Commerce — Development Rules
-
-## Plans & Architecture Decisions
-
-All feature plans live in `docs/plans/` using the template at `docs/plans/_template.md`. Never create plans elsewhere.
-
-When proposing significant architectural changes:
-
-1. Check existing plans in `docs/plans/` for conflicts
-2. Create or update a plan using the template before implementing
-3. Pay special attention to "Constraints on Current Work" sections — these apply even when you're not implementing that plan directly
-
-Use `/project:create-plan` and `/project:update-plan` for plan management, and `/project:implement-plan <plan>` to deliver a plan end to end (open questions → implementation → reviews → running QA environment → pull request).
-
-## Monorepo Structure
-
-| Directory | Description |
-| --- | --- |
-| `spree/core` | Ruby gem — models, services, business logic (`spree_core`) |
-| `spree/api` | Ruby gem — Store & Admin REST APIs (`spree_api`) |
-| `spree/emails` | Ruby gem — transactional emails (optional). Rebuilt + modernized in 5.6. The default email stack for installations without a storefront app (e.g. mobile apps); headless storefronts may instead own consumer emails via webhooks. |
-| `spree/providers/easypost` | Ruby gem (`spree_easypost`, optional) — reference `DeliveryRateProvider` + `FulfillmentProvider`: live EasyPost rates, label purchase/refund, credentials via `SpreeEasyPost::Integration`. Provider gems live under `spree/providers/` (stripe/adyen/avalara land there too); gem names stay flat. |
-| `spree/providers/meilisearch` | Ruby gem (`spree_meilisearch`, optional) — `SpreeMeilisearch::SearchProvider` + `SpreeMeilisearch::ProductPresenter`: typo-tolerant product search, disjunctive facets and merchant-ordered grouping pages. Extracted from core in 6.0; credentials come from `MEILISEARCH_URL`/`MEILISEARCH_API_KEY` (index is installation-wide infrastructure, not a per-store `Integration`). |
-| `spree/dashboard` | Ruby gem (`spree_dashboard`, optional) — hosts a built React Dashboard at `/dashboard` and Seller Panel at `/seller` from `Spree::Dashboard.dist_path` / `SPREE_DASHBOARD_DIST_PATH` (single-node topology). Successor slot to `spree_admin` at 6.0. |
-| `packages/dashboard` | `@spree/dashboard` — React SPA admin dashboard (Spree 6.0, replaces `spree/admin`). The deployable app shell, routes, schemas, resource hooks, locales. |
-| `packages/dashboard-ui` | `@spree/dashboard-ui` — design system. Shadcn primitives + headless composed components + tokens. Source-only; consumer compiles via Vite/Tailwind. **Components are headless: data comes via props, no provider/hook imports.** |
-| `packages/dashboard-core` | `@spree/dashboard-core` — framework. Registries (table, nav, slot, settings-nav), providers (auth, permission, store, theme), generic infra hooks, admin SDK client singleton, `defineDashboardPlugin` facade. The extension API for plugin authors. |
-| `packages/dashboard-starter` | `@spree/dashboard-starter` — thin host app consuming `<Dashboard />` from `@spree/dashboard`; canonical source of the `spree/dashboard-starter` template repo (synced on release). Doubles as the in-repo consumer test for the plugin pipeline. |
-| `packages/seller-dashboard` | `@spree/seller-dashboard` — React SPA seller panel for marketplace dpeloyments. The deployable app shell, routes, schemas, resource hooks, locales. |
-| `packages/seller-dashboard-starter` | `@spree/seller-dashboard-starter` — thin host app consuming `<SellerDashboard />` from `@spree/seller-dashboard`; canonical source of the `spree/seller-dashboard-starter` template repo (synced on release). Doubles as the in-repo consumer test for the plugin pipeline. |
-| `packages/sdk` | `@spree/sdk` — TypeScript Store API client |
-| `packages/admin-sdk` | `@spree/admin-sdk` — TypeScript Admin API client |
-| `packages/seller-sdk` | `@spree/seller-sdk` — TypeScript Seller API client |
-| `packages/core` | `@spree/core` — universal code with no HTTP: code lists, money helpers, filter vocabulary (published; the base for shared TypeScript code) |
-| `packages/sdk-core` | `@spree/sdk-core` — shared HTTP/retry/error layer (private internal) |
-| `packages/cli` | `@spree/cli` — Docker-based project management CLI |
-| `packages/create-spree-app` | `create-spree-app` — project scaffolding |
-| `server/` | Rails app cloned from `spree/spree-starter` (.gitignored, provisioned per worktree by `scripts/worktree/setup.sh`) |
-| `storefront/` | Next.js storefront cloned from `spree/storefront` `main` (.gitignored, provisioned per worktree; keeps its `.git` — commit and push from inside it) |
-| `docs/` | Mintlify powered documentation website, which is deployed to https://spreecommerce.org/docs |
-## Development Server (worktrees)
-
-Development happens in **git worktrees** — every worktree is a self-contained native dev environment, no Docker: its own gitignored `server/` clone of spree-starter (monorepo gems loaded as path gems via `SPREE_PATH`), its own database on the shared Homebrew Postgres (:5432, copied in ~2 s from the seeded `spree_worktree_template`), and stable per-branch https URLs via [portless](https://github.com/vercel-labs/portless). Worktrees are managed with [worktrunk](https://worktrunk.dev) (`wt`): creating one runs `scripts/worktree/setup.sh` automatically (see `.config/wt.toml`), removing one drops its databases. The main checkout is for integration (merges, template rebuilds), not for running servers.
-
-```bash
-wt switch -c feature-x # create worktree + provisioned environment (~20 s)
-pnpm wt:dev # Rails → https://feature-x.spree.localhost (/up, /api/v3, /jobs; jobs run inside Puma via Solid Queue)
-pnpm wt:dashboard # admin UI → https://admin.feature-x.spree.localhost
-pnpm wt:seller # seller panel → https://sellers.feature-x.spree.localhost
-pnpm wt:storefront # Next.js storefront → https://store.feature-x.spree.localhost
-pnpm wt:e2e [spec...] # Playwright on this worktree's own port block
-pnpm wt:template # rebuild the template DB after schema-changing pulls
-wt merge main # ship + clean up (worktree, branch and databases all removed)
-wt remove # abandon instead of shipping
-```
-
-Admin login: `[email protected]` / `spree123`. The dev scripts run in the foreground and stream logs; `server/log/development.log` has the Rails log if the server runs detached. Start servers only in worktrees you're actively looking at — rspec/vitest/tsc need no servers.
-
-**Storefront (`pnpm wt:storefront`).** The Next.js storefront is a separate repo (`spree/storefront`) cloned per worktree into a gitignored `storefront/`, on its `main` branch. Unlike `server/`, the clone keeps its `.git`: commit and push storefront work from inside it, and push before `wt remove`, which deletes the clone with the worktree.
-
-It is deliberately **not** a member of this pnpm workspace — one lockfile and one set of global overrides cannot serve both Next 16 and the dashboard's Vite tree. It instead points `@spree/sdk` at this worktree's `packages/sdk` through its own `.pnpmfile.cjs`, which rewrites the dependency only when `SPREE_SDK_PATH` is set (the JavaScript twin of `SPREE_PATH`), so a standalone clone still installs the published SDK. The rewrite uses `file:` and not `link:`, because the storefront pins module resolution to its own directory (`turbopack.root`, `output: "standalone"`) and lists the SDK in `transpilePackages` — a symlink pointing outside the project fails to resolve, and every `@spree/sdk` import breaks. Two consequences: the storefront's `pnpm-lock.yaml` will show a local path — never commit it — and because the SDK is **copied**, picking up a change to it means rebuilding and reinstalling, which is exactly what re-running `pnpm wt:storefront` does.
-
-`storefront/.env.local` is regenerated on every boot with this worktree's API URL and the seeded publishable keys (read straight from Postgres — publishable tokens are plaintext), so a reseeded database can't leave a stale key behind. Anything you add below the marker line is preserved.
-
-One-time machine setup: Homebrew `postgresql@18` running on :5432 (with a `postgres` superuser role), `mailpit` (`brew services start mailpit` — one instance serves every worktree), Ruby per `server/.ruby-version` via [mise](https://mise.jdx.dev) (`mise settings add idiomatic_version_file_enable_tools ruby`, so it reads `.ruby-version`), Node ≥ 24 with `npm i -g portless` (start the proxy once with `portless proxy start`, accepting sudo for :443), worktrunk, then `pnpm wt:template`.
-
-| What changed | What to run (inside the worktree) |
-| --- | --- |
-| Ruby code in `spree/*` gems | Nothing — path gems, reloads on next request |
-| New migration in a gem | `cd server && bin/rails spree:install:migrations db:migrate`; then `pnpm wt:template` once so future worktrees inherit it |
-| Deleted and re-cloned `server/` | `pnpm wt:template` — the 6.0 migrations still ship from the gems, so re-cloning renumbers them and the old template no longer matches. `wt:setup` refuses to provision from a mismatched template and rebuilds it automatically when it re-created `server/` itself |
-| Gem dependencies | `cd server && bundle install` (the gem home is shared across worktrees, so this is fast) |
-| Need sample data (products + images) | `cd server && bin/rails spree:load_sample_data` — per worktree, on demand; takes minutes and hits the network |
-| Rails console / database | `cd server && bin/rails console`; the DB is `spree_dev_<branch>` on `localhost:5432` |
-| E2E prerequisites | Once per worktree: `cd spree/api && bundle install && bundle exec rake test_app` (then `pnpm wt:e2e`) |
-| Read an email the app sent | Mailpit catches everything: <http://localhost:8025>. `brew install mailpit && brew services start mailpit` if it is not running — without it the starter falls back to a delivery method that does not exist and every send raises |
-| Store API serializers or SDK code, and the storefront is running | Re-run `pnpm wt:storefront` — it rebuilds the SDK and copies it in. Run the [type generation pipeline](#type-generation-pipeline) first if you changed serializers |
-| Meilisearch search provider | Optional: `brew install meilisearch`, run it, set `MEILISEARCH_URL` in `server/.env`, `bin/rails spree:search:reindex` |
-| Hosted dashboard at `/dashboard` (single-node test) | `pnpm server:dashboard` to build `packages/dashboard-starter/dist`, set `SPREE_DASHBOARD_DIST_PATH=<monorepo>/packages/dashboard-starter/dist` in `server/.env` |
-| Hosted seller panel at `/sellers` (single-node test) | `pnpm server:seller` to build `packages/seller-dashboard-starter/dist`, set `SPREE_SELLER_PANEL_DIST_PATH=<monorepo>/packages/seller-dashboard-starter/dist` in `server/.env` |
-| Broken beyond repair | `wt remove` and recreate — or `dropdb spree_dev_<branch>`, delete `server/`, re-run `pnpm wt:setup` |
-
-When working with worktrees, don't use the `pnpm server:dev` and other docker-based commands.
-
-**Cloud sessions** (`CLAUDE_CODE_REMOTE=true`) have no worktrees, portless or Homebrew. The SessionStart hook (`scripts/cloud/provision.sh`) has already started Postgres and Mailpit, cloned `server/`, and created and seeded `spree_development` — its summary at the top of the session lists the URLs. Start servers with `scripts/cloud/start.sh [rails|dashboard|seller|all]` (plain http: Rails :3000, dashboard :5173, seller :5175, logs in `/tmp/spree-*.log`); `pnpm wt:dev`/`wt:dashboard`/`wt:seller` do not work there. Check UI changes yourself with `node scripts/cloud/screenshot.mjs <url> <out.png> --login` and Read the PNG — the human cannot open these servers. `pnpm test:rspec`, `pnpm test:changed` and `pnpm wt:e2e` work unchanged.
-NEVER kill/shut off dev serves already running unless they are broken (eg. migrations didn't run, missing migrations).
-
----
-
-## General rules
-
-- ONLY comment complex or non-obvious methods/code, do not comment every method or class, DON'T create comments noise
-- DON'T comment code removal, just delete it
-- DON'T comment obvious and native to Rails framework methods, associations, validations
-- DON'T comment on shapes, serializers, types
-- Documentation also needs to follow the same principles — focus on the "what" and "why", not the "how". Don't include implementation details in docs. Docs should explain the feature, its purpose, and how to use it, but not how it's implemented internally.
-- ALWAYS use plain english language when communicating with the human, NEVER use technical jargon, be precise and clear, avoid abbreviations and acronyms, and use proper grammar and punctuation. Avoid using slang or informal language. Use simple and concise sentences to convey your message effectively. Avoid using complex sentence structures or convoluted phrasing that may confuse the reader. Use active voice instead of passive voice whenever possible. Avoid using overly technical terms or industry-specific jargon that may not be familiar to the reader. Use examples or analogies to explain complex concepts in a way that is easy to understand. Avoid using vague or ambiguous language that may lead to misinterpretation. Use headings, bullet points, and numbered lists to organize information and make it easier to read. Avoid using long paragraphs or blocks of text that may overwhelm the reader. Use visuals such as diagrams, charts, or screenshots to supplement written explanations when appropriate. Avoid using visuals that are unclear or difficult to interpret.
-- DRY - Don't Repeat Yourself - before adding a new feature or functionality, check if it already exists in the codebase. If it does, reuse it instead of duplicating code. This helps to keep the codebase clean and maintainable, our goal is to minimize the number of lines of code, not to expand it without control
-- Be Paranoid - always assume that the code you are writing will be used in unexpected ways, and that users may try to break it. Security is another important aspect of development, and we should always be mindful of potential vulnerabilities and attack vectors. Always validate user input, sanitize data, and follow best practices for secure coding. Use tools like static analysis, code reviews, and penetration testing to identify and fix security issues before they become a problem. Always keep security in mind when designing new features or making changes to existing code.
-- Seller Panel and Admin Dashboard - dashboard is the reference, when adding features to Seller panel extract code to re-usable components in dashboard, move it to dashboard-ui/dashboard-core, import it in Seller Panel
-
-
-## Git Policy
-
-- Commit message body: max 3-4 sentences, DON'T include implementation detail, focus on the "what" and "why", not the "how"
-- Commits fixing bugs should start with "Fix: " prefix, branch name should start with "fix/"
-- Use plain phrases like "Added/Removed/Fixed/Changed" in commit messages/titles
-- NEVER commit anything to main branch, always use feat/fix/chore branches for development
-- Pull Request descriptions are public, never disclose any credentials, PII, sensitive data or local dev environment URLs
-- Pull Request descriptions should follow same guidelines as git commits - short, cohesive and short, use bullets to list changes / new features if it's a big PR
-- NEVER add yourself as a co-author of the commit
-
-## Backend (Ruby)
-
-### Architecture Principles
-
-- All code namespaced under `Spree::` module
-- Follow Rails conventions and the Rails Security Guide
-- RESTful routes and action names, AVOID adding custom non CRUD/RESTful actions, promote them to nested controllers instead
-- CanCanCan for authorization: listings use `accessible_by(current_ability, :show)`, other actions use `authorize!`
-- Always use scope fetching for security (e.g. `current_store.orders` not `Spree::Order`). This applies to **every** lookup in a controller, including the incidental ones — resolving a `reason_id` or `stock_location_id` from a create param through the model constant accepts an id belonging to another store. Reading it through `current_store.<association>` turns that into a 404, which is the cheapest defence against IDOR. `accessible_by(current_ability, ...)` is not a substitute: it filters by role, not by tenant.
-- Ransack for filtering/searching, Pagy for pagination
-- Use services only when necessary — prefer standard Rails models and concerns
-- DO NOT call `Spree::User` directly, use `Spree.user_class`; same for `Spree.admin_user_class`
-- DO NOT put logic into controllers or serializers - this should live in models and services
-- ALWAYS use Yard comments for classes and public methods, with `@param` and `@return` types
-- DO NOT generate too much comment noise, be very strict and selective about what gets a comment — only non-obvious public methods, never private methods or internal helpers
-- DO NOT use shorthand variable names, readibility by humans is the core principle
-- Always use `ActiveJob::Continuable`` when a Background Job iterates over records and perform operations on them
-
-### Code Organization
-
-All backend code lives inside `spree/` engine directories following Rails conventions:
-
-- `app/models/spree/`, `app/controllers/spree/`, `app/services/spree/`, `app/serializers/spree/`, `app/subscribers/spree/`, `app/mailers/spree/`, `app/jobs/spree/`, `app/helpers/spree/`, `app/presenters/spree/`
-- File naming matches class: `spree/product.rb` → `Spree::Product`
-- Split large models into concerns, organized by topic
-
-### Spree::Current
-
-Per-request context available in models, controllers, jobs, and services:
-
-- `Spree::Current.store` — current store
-- `Spree::Current.currency` — current currency
-- `Spree::Current.locale` — current locale
-
-### Models
-
-- ALWAYS Inherit from `Spree.base_class`
-- We're on Rails 8.1 so use all the new and available methods from this release
-- New models carrying store-specific data (configuration, catalog, commerce records) ALWAYS `belongs_to :store` via `Spree::SingleStoreResource` — only genuinely global reference data (countries, states, roles) goes unscoped. Cross-store sharing is gone (`spree_multi_store` is legacy and unsupported)
-- ALWAYS pass `class_name` and `dependent` on associations; use `dependent: :destroy_async` for high-fanout associations to offload deletion to a background job
-- Include `Spree::HasCustomFields` for custom fields support
-- Include `Spree::Metadata` for JSON metadata support
-- ALWAYS Use string columns instead of enums
-- NEVER use `Struct` for domain value objects — use a plain Ruby class with `ActiveModel::Model` + `ActiveModel::Attributes` (typed attributes, validations) so it behaves like an ActiveRecord object (e.g. `Spree::PickupPointOption`)
-- No state machines. Spree has none since 6.0 and `state_machines-activerecord` is not a dependency — declare statuses with `has_status` (column always `status`) and move records between them with Workflows (see docs/plans/6.0-normalize-state-to-status.md)
-- NEVER cast IDs to integer — always treat as strings (UUID support)
-- Uniqueness validations: ALWAYS use `scope: spree_base_uniqueness_scope`, should be also enforced by database index
-- If needed use paranoia gem for soft delete support (via `acts_as_paranoid`)
-- For configuration / options always use [Model Preferences](docs/developer/customization/model-preferences.mdx)
-- NEVER hardcode table names, always use `Model.table_name` in models, queries, scopes, etc.
-- ALWAYS use Arel, scopes and ActiveRecord helpers to build queries, only use raw SQL if cannot use Arel
-- ALWAYS use normalizes for normalization of attributes, DON'T use custom before_action callbacks
-- ALWAYS use insert_all/upsert_all when creating records in bulk, this relies on proper database uniqueness indexes. Special treatment for MySQL is needed though
-- ALWAYS put callbacks in private group
-- ALWAYS use existing vocabulary and naming patterns, avoid slang terms
-- DO NOT override Rails core API methods, eg. `update```
-- All new models should have `store_id` and belong to `Store` unless they are sub-children of another Parent (eg. `Variant` under `Product`)
-- All new tier-1 models (eg. Product) should publish events via `publishes_lifecycle_events`
-
-```ruby
-class Spree::Product < Spree.base_class
- include Spree::SingleStoreResource
- include Spree::HasCustomFields
- include Spree::Metadata
-
- acts_as_paranoid
-
- publishes_lifecycle_events
-
- has_many :variants, class_name: 'Spree::Variant', dependent: :destroy
- scope :available, -> { where(available_on: ..Time.current) }
-
- validates :name, presence: true
- validates :slug, presence: true, uniqueness: { scope: spree_base_uniqueness_scope }
-end
-```
-
-### Migrations
-
-- Target version: existing migrations keep their `ActiveRecord::Migration[7.2]` marker; new 6.0 migrations may target `[8.1]` — the 6.0 line requires Rails 8.1 (decisions.md 2026-07-29)
-- No foreign key constraints
-- No default values on string/status columns (statuses are set by the creating workflow); integer, decimal and boolean columns DO carry defaults (`quantity` 1, amounts 0) so raw inserts can't produce nulls
-- Every metadata-carrying table has a single `metadata` JSON column — the `public_metadata`/`private_metadata` split was consolidated in 6.0
-- `preferences` columns are JSON, never `text` — YAML preferences are converted in 6.0 (see `docs/plans/6.0-json-preferences.md`); hash preferences never use number keys; secrets are `:password` preferences, stored encrypted in a `secret_preferences` `text` column
-- Always add `null: false` on required columns
-- One migration per feature when possible
-- Data transformations go in rake tasks, never in migrations
-- Soft delete: use `paranoia` gem, add `deleted_at` column yourself
-- JSON columns must work across PostgreSQL, MySQL, and SQLite. PostgreSQL supports `t.jsonb` (binary, indexable); MySQL and SQLite do not — only `t.json`. Guard with `respond_to?`:
-
-```ruby
-# JSON column — works on PostgreSQL, MySQL, SQLite
-if t.respond_to?(:jsonb)
- t.jsonb :metadata
-else
- t.json :metadata
-end
-```
-
-```ruby
-class CreateSpreeMetafields < ActiveRecord::Migration[8.1]
- def change
- create_table :spree_metafields do |t|
- t.string :key, null: false
- t.text :value, null: false
- t.string :kind, null: false
- t.string :visibility, null: false
- t.references :resource, polymorphic: true, null: false
- t.timestamps
- end
-
- add_index :spree_metafields, [:resource_type, :resource_id, :key, :visibility],
- name: 'index_spree_metafields_on_resource_and_key_and_visibility'
- end
-end
-```
-
-### API Controllers
-
-The Store API (customer-facing) and Admin API (back-office) are two halves of the same v3 API and should follow the same conventions. The differences are in **what data is exposed**, **who can call it**, and **which actions are enabled by default** — not in routing style, parameter shape, or response format.
-
-#### Hierarchy
-
-- **Base:** `Spree::Api::V3::ResourceController` — pagination (Pagy), Ransack, CanCanCan, prefixed ID lookups, HTTP caching
-- **Store API:** `Spree::Api::V3::Store::ResourceController` — publishable API key auth, **read-only by default**; opt into `create`/`update`/`destroy` per resource where it makes sense (carts, customers, addresses)
-- **Admin API:** `Spree::Api::V3::Admin::ResourceController` — secret API key auth (with scopes) **or** JWT auth (with CanCanCan), **full CRUD by default** (`index`, `show`, `create`, `update`, `destroy`); subclasses don't need to redeclare actions unless restricting
-
-#### Key overridable methods
-
-`model_class`, `serializer_class` (use `Spree.api.serializer_name`), `scope` (call `super` and chain), `find_resource`, `permitted_params`, `collection_includes`
-
-**A resource written through a workflow declares it, never re-implements the action.** Override `create_workflow` / `update_workflow` to return the workflow, and the inherited `create`/`update` keep their authorization, their result handling and their rendering — hand-writing those actions is how a controller silently loses the record-level `authorize_resource!` the base class does. Override `create_workflow_arguments` / `update_workflow_arguments` when the workflow's keywords differ from the defaults (`store:`/`attributes:` and `<resource>:`/`attributes:`).
-
-`build_resource` builds through the owner's association — `current_store.products`, or a nested resource's parent — so a new record carries its tenancy from where it was built rather than from an attribute assigned afterwards. A model the store has no association for falls back to the class. When a `create_workflow` is declared the record is left bare, since the workflow assigns the payload and the authorization check reads the record's owner rather than its attributes.
-
-#### Flat request/response structure
-
-API v3 uses flat params — no nested Rails-style wrapping. Declare a controller's writable attributes with **`request_params`** — one typed declaration that the controller permits from, the integration spec documents with `request_body_for`, and the SDK request types are generated from (`pnpm generate:params` → `src/types/params/`), so backend, OpenAPI and TypeScript cannot drift. Never hand-write a request body in an rswag spec or a request type in an SDK. Each attribute is `body.attribute :name, :type, **options` — types `:string :integer :number :decimal :boolean :date :datetime :id :any :country :currency :hash :object :array` (`of:` for an array's items, `shape:` for an object, `choices:` for a value list, `required: true` + `on: :create`, `only:` for one action); money is `:decimal` (canonical string), never `:number`; a country or currency code is `:country` / `:currency`, never `:string` — they publish the closed `CountryCode` / `CurrencyCode` types (from `Spree::IsoData.country_codes` and `Spree::Money::Rounding::CURRENCY_CODES`), which serializers declare with `enum_type_name: 'CountryCode'` / `'CurrencyCode'` so reads and writes share one type. A shape two or more endpoints accept (address, price, stock level, media) is a class in `spree/api/app/request_schemas/` (`class AddressRequestSchema < Spree::Api::V3::RequestSchema`, `publishes 'XyzParams'` to give it its own type; Admin variants subclass the shared one, like serializers) — never copy a field list between controllers; a body used by one endpoint stays inline in its controller; a custom action declares `request_params 'XyzParams', action: :xyz do |body|`. A spec checks that every attribute a model-backed create/update accepts is writable on the model. `resource_permitted_attributes` (a plain list) still works but leaves the body undocumented and untyped. The base `permitted_attributes` appends extension-contributed attributes to it, and `permitted_params` permits and normalizes the result. `Spree::PermittedAttributes` and its model-name inference are **removed in 6.0** — a controller that declares neither `resource_permitted_attributes` nor `permitted_params` raises `NotImplementedError` on its first write.
-
-Extensions add writable attributes to a core resource from an initializer, appending to the model's `additional_permitted_attributes` (a `class_attribute` on `Spree::Base`, default `[]`): `Spree::Product.additional_permitted_attributes += [:brand_id]`. Always `+=`, never `=` — assigning replaces what another extension added. Core STI subclasses set theirs with `self.additional_permitted_attributes = [...]` in the class body. Three rules that matter:
-
-- **Override `resource_permitted_attributes`, never `permitted_attributes`** — the latter is where the extension union happens, so overriding it silently drops extension attributes.
-- **A controller that overrides `permitted_params` outright opts out of the union.** If it needs both, splat `model_additional_permitted_attributes` into its own `params.permit`.
-- **`normalize_params` is not free.** It recurses into nested hashes decoding anything matching the prefixed-ID shape, so a controller carrying opaque provider values (gateway `preferences`, merchant `metadata`) must NOT normalize — a Stripe `we_1MqJ8b...` id would be decoded to an integer. `Admin::PaymentMethodsController` is the worked example. Conversely, a controller that *does* normalize receives already-decoded primary keys, so read raw `params` when you need a prefix-checked `find_by_prefix_id!`.
-
-Prefer Custom Fields for merchant-managed data; the hook is for extensions adding real columns.
-
-```ruby
-# ✅ Flat params, declared once
-request_params :product do |body|
- body.attribute :name, :string, required: true, on: :create
- body.attribute :description, :string
- body.attribute :slug, :string
-end
-
-# ❌ Nested params — not used in API v3
-def permitted_params
- params.require(:product).permit(:name, :description, :slug)
-end
-```
-
-**Read and write attribute names must match.** Whatever a serializer exposes (`label`, `status`, `customer_note`) is what the controller's `permitted_params` must accept on write — no "we expose `label` but accept `presentation`" mismatches. This is non-negotiable for v3: clients should not have to translate field names between read and write. When the underlying column has a legacy name, define a writer alias on the **model** (`def label=(value); self.presentation = value; end` — pair it with the matching reader) and permit the public name in the controller. The model owns the bridge, never the client. Example: `Spree::OptionType#label` / `label=` aliases — the serializer returns `label`, the controller permits `:label`, and the model translates to the underlying `presentation` column.
-
-```ruby
-module Spree::Api::V3::Store
- class ProductsController < ResourceController
- protected
-
- def model_class
- Spree::Product
- end
-
- def serializer_class
- Spree.api.product_serializer
- end
-
- def scope
- super.active(Spree::Current.currency)
- end
- end
-end
-```
-
-```ruby
-# Admin counterpart — gets full CRUD for free from the base class
-module Spree::Api::V3::Admin
- class ProductsController < ResourceController
- protected
-
- def model_class
- Spree::Product
- end
-
- def serializer_class
- Spree.api.admin_product_serializer
- end
-
- # No need to declare index/show/create/update/destroy — inherited.
- # Only override scope/find_resource/permitted_params when behavior differs.
- end
-end
-```
-
-### Prefixed IDs
-
-All API v3 uses Stripe-style prefixed IDs (e.g. `prod_86Rf07xd4z`, `variant_k5nR8xLq`):
-
-- Always return prefixed IDs in responses — never expose raw IDs
-- Always accept prefixed IDs in request params
-- `BaseSerializer` auto-converts the primary `id`; for associations use `object.association&.prefixed_id`
-- Controllers use `find_by_prefix_id!` (automatic in base `ResourceController`)
-- Event payloads also use prefixed IDs
-
-```ruby
-# ✅ Serializer
-attribute :variant_id do |line_item|
- line_item.variant&.prefixed_id
-end
-
-# ❌ Exposes raw ID
-attribute :variant_id
-```
-
-### Typed values (`api_type`, never the Ruby class name)
-
-**No Ruby class name ever crosses the API** — not in a request, response, filter, webhook payload, permission subject, SDK type, doc example or fixture. The database keeps storing class names; the conversion happens at the boundary, so the contract survives a backend that is not Ruby. Every such value is a short name: the demodulized + underscored class (`Spree::PriceRules::VolumeRule` → `volume_rule`, `Spree::CreditCard` → `credit_card`).
-
-**STI families** selected by a `type` (promotion rules/actions, price rules, delivery-method rules, collection rules, commission rules, order-routing rules, payment methods, integrations, seller requirements, calculators, imports/exports):
-
-- Serialize with `Model.api_type_for(record.type)` (or `record.class.api_type`); resolve writes with `subclassed_via` / `find_by_api_type` / `Model.class_name_for_api_type`, which match the registry only, so a class name is rejected as an unknown type
-- Override `def self.api_type` to keep the wire value stable across a class rename — the default is derived, so renaming otherwise changes a public identifier
-- Build pickers from the family's `…/types` endpoint (`{ type, label, schema }`, where `schema` is the JSON Schema of the type's preferences), never a hardcoded list — extension kinds then appear for free
-- Adding a built-in kind means updating the serializer's `comment:` list in the same change (see the value-list tiers below)
-
-**Registry-selected strategy classes** (fulfillment, delivery-rate, pickup-point, payout, tax and digital-asset providers, order routing strategies — plain Ruby, stored as a class-name string on a column or preference):
-
-- The family's base class `extend Spree::ApiTyped`; a gem class named after its family (`SpreeEasyPost::FulfillmentProvider`) answers its gem's name (`easy_post`)
-- The model converts incoming values: `normalizes :rate_provider, with: ->(value) { Spree::ApiTyped.class_name_for(Spree.delivery_rate_providers, value) }` (`parse_on_set:` for a preference), plus an inclusion validation against the registry; a filterable column gets `ransacker :provider, formatter: ->(value) { Spree::ApiTyped.class_name_for(…) }`
-- The serializer declares `api_type_attributes :rate_provider, :fulfillment_provider`
-- Turn a stored value into a class with `Spree::ApiTyped.registered_class(registry, value)` — never `constantize` a stored string; an unregistered value falls back to the default
-- Every new strategy family gets a registry (`Spree.<family>s`) — a column a merchant writes must never name an arbitrary class
-
-**Polymorphic columns** (`owner_type`, `resource_type`, `taggable_type`, `originator_type`, …):
-
-- Serialize with `Spree::Base.polymorphic_api_type(record.owner_type)` — the configured customer and admin user classes always read `customer` / `admin_user`
-- Accept with `Spree::Base.polymorphic_type_for(value, candidates)` against the classes that column may hold
-- **Filters**: the base `ResourceController` translates `type_*` and polymorphic `*_type_*` predicates (`q[receivable_type_eq]=purchase_order`) to class names; a plain column holding class names (`CustomFieldDefinition#resource_type`) overrides the model's `api_type_resolver`, which the published filter tables read too
-
-**Permission subjects** follow the same rule: `/me` serializes class subjects through `polymorphic_api_type` (`product`, `category`), and the dashboard checks them with the `Subject` constants.
-
-Never special-case old class names (`Spree::Taxon`) in this conversion — upgrade tasks migrate stored data. A changed Store API value or webhook field goes in the upgrade guide.
-
-```ruby
-# ✅ Wire shorthand
-{ type: 'volume_rule', preferences: { min_quantity: 10 } }
-{ fulfillment_provider: 'manual', resource_type: 'product' }
-
-# ❌ Never on the wire
-{ type: 'Spree::PriceRules::VolumeRule', preferences: { min_quantity: 10 } }
-{ fulfillment_provider: 'Spree::FulfillmentProvider::Manual', resource_type: 'Spree::Product' }
-```
-
-### Serializers (Alba)
-
-Located in `api/app/serializers/spree/api/v3/`. Store and Admin APIs have separate serializers; **Admin always extends Store** so changes to public fields propagate automatically.
-
-#### What goes where
-
-The Store API is a customer-facing surface. The Admin API is a back-office surface. Two rules govern which serializer an attribute belongs to:
-
-**Store serializer (customer-visible):**
-
-- Public product/category/cart/order data the customer sees in the storefront
-- Computed display values (`display_total`, `purchasable`, `in_stock`)
-- Customer-facing pricing (`price`, `compare_at_price`, `prior_price` for EU Omnibus)
-- **No timestamps** (`created_at`, `updated_at`, `deleted_at`) — these leak operational info and aren't useful to customers
-- **No internal state** — never expose `cost_price`, internal status flags, soft-delete columns, audit logs, internal notes, `metadata`, or admin-only relations (sellers, fulfillment providers)
-
-**Admin serializer (back-office):**
-
-- Always include `created_at`, `updated_at`, and `deleted_at` (when paranoid)
-- Cost price, margins, internal notes, `metadata`
-- Internal status, audit fields (`approved_by_id`, `cancelled_by_id`)
-- Operational relations (stock movements, fulfillment providers, internal customer tags)
-- Anything an admin needs to see but a customer must not
-
-```ruby
-# Store serializer — customer-facing, no timestamps, no back-office data
-module Spree::Api::V3
- class ProductSerializer < BaseSerializer
- typelize purchasable: :boolean, in_stock: :boolean, price: 'number | null'
- attributes :id, :name, :description, :slug, :price
- end
-end
-
-# Admin serializer — extends store, adds back-office attributes + timestamps
-module Spree::Api::V3::Admin
- class ProductSerializer < V3::ProductSerializer
- typelize cost_price: 'number | null', metadata: 'Record<string, unknown> | null'
- attributes :status, :cost_price, :metadata, :created_at, :updated_at, :deleted_at
- end
-end
-```
-
-- `typelize attr: :type` for computed/delegated attribute types
-- Value lists come in three tiers — picking the wrong one is a contract bug:
- - **Closed** (nothing can extend it — units, match policies): `enum: Model::KINDS, enum_type_name: 'ModelKind'` and add the name to `Typelizer::OpenEnums::CLOSED_LIST_NAMES` → closed TS union defined once in `@spree/core` (`MODEL_KINDS` + `ModelKind`), plain OpenAPI `enum`. Never leave a list unnamed: an inline union is copied into every SDK and cannot be imported by the dashboards
- - **Open** (extensions may add, built-ins known at class-load — `has_status`, `Spree::Fee::KINDS`): add `enum_type_name: 'ModelStatus'` → open TS union (`'a' | 'b' | (string & {})`) + OpenAPI `anyOf`, so clients autocomplete the built-ins and still accept extension values. The list is generated once into `@spree/core` (`MODEL_STATUSES` + `ModelStatus`) and each SDK's `Enums.ts` re-exports the type; two serializers giving one name different values stop generation. Dashboards never copy a list: iterate the generated constant, and pick a subset with `subsetOf(MODEL_STATUSES, [...])` so a typo fails to compile
- - **Registry-driven `type`** (the typed families above): plain `:string` + `comment:` listing the built-in shorthands. It *cannot* use `enum:` — registries fill in `to_prepare`/initializers, after serializer classes load, so generated types would depend on boot order and installed extensions. Cost: no autocomplete, no machine-readable list, and the comment is hand-maintained
-- Never use `typelize_from` — it connects to the database
-- **A deprecated field is marked, never only described.** Response attributes: `typelize state_abbr: [:string, nullable: true, deprecated: 'Use `state_code`. Removed in 6.1.']`. Request fields: `string :country_iso, deprecated: 'Use `country_code`. Removed in 6.1.'`. Both reach the API reference (`deprecated: true`) and the SDK types (`@deprecated`, struck through in editors). The message names the replacement and the release that removes it; a "Deprecated:" sentence in a `comment:` or `description:` alone is invisible to clients
-- **Deprecate, never remove.** Since 6.0 the Store, Admin and Seller APIs are all stable contracts: a renamed or retired field keeps working, marked `deprecated:`, until the next minor release, and the upgrade guide names its replacement. Move the dashboards to the replacement in the same change
-- Customize via inheritance + `Spree.api.product_serializer = 'MyApp::ProductSerializer'`
-- NEVER create custom hash/arrays to represent associations or records inside the serializer - each record or a variant of a record (eg. lightweight variant of an existing serializer) should be it's own serializer
-- NEVER put too much logic in serializers, they should be lean and call models for custom methods
-
-### Events System
-
-```ruby
-order.publish_event('order.completed')
-```
-
-Subscribers go in `app/subscribers/spree/`:
-
-```ruby
-module Spree
- class OrderCompletedSubscriber < Spree::Subscriber
- subscribes_to 'order.completed'
-
- def handle(event)
- order = Spree::Order.find_by_prefix_id(event.payload['id'])
- return unless order
- ExternalService.notify_order_placed(order)
- end
- end
-end
-```
-
-For new models, add `publishes_lifecycle_events` concern and create an event serializer.
-
-Webhook payloads use Store serializers only — never a hand-built hash, never an Admin serializer; extra facts go in `metadata`. Every event is being moved to a declared catalog (see `docs/plans/6.0-typed-webhook-events.md`).
-
-### Emails (Liquid + MJML)
-
-Every email renders from a Liquid template written in MJML, never ERB. See `docs/plans/6.0-liquid-mjml-emails.md` and `docs/developer/customization/emails.mdx`.
-
-- **Template** lives at the mailer action's view path: `app/views/spree/<mailer>/<action>.liquid`. That path is its public key, so renaming a mailer or action is a breaking change. The subject goes in YAML front matter; the plain-text part is generated from the HTML (add `<action>.text.liquid` only to hand-write it). Layout is `layouts/spree/base_mailer.liquid`; shared blocks are `spree/shared/_*.liquid`, pulled in with `{% render 'spree/shared/line_item', item: item %}`.
-- **Mailer** inherits `Spree::BaseMailer`, sets `@current_store`, wraps the send in `with_store_locale(store, locale)`, and calls `mail_template({ order: email_data(@order, Spree::Emails::OrderSerializer), resend: resend }, to: ...)`. Keep the mailer's guards (recipients, status checks) as they are.
-- **Data comes from serializers, never models.** `email_data` turns a record into the JSON a template reads. Customer emails extend the Store API serializers (`spree/emails/app/serializers/spree/emails/`); staff emails use core ones (`spree/core/app/serializers/spree/emails/`) so they work without `spree_api`. Add email-only fields there, not to the public Store serializers. **Never serialize a token**: build reset, invitation, download and payment URLs in the mailer and pass them as their own variable.
-- **In templates**: output is HTML-escaped automatically (`| raw` only for HTML sanitized on write). Filters: `money`, `money_with_currency`, `date` (store time zone), `t` (Spree translation keys, so one template serves every language). An unknown variable raises in development and test.
-- **When you add or change an email**: if customers receive it, update `docs/developer/customization/email-variables.mdx` by hand with its variables, add it to `spree/emails/spec/mailers/spree/rendered_emails_spec.rb`, and give it a mailer preview (shown at `/rails/mailers` in development) in `spree/emails/lib/spree/emails/previews/` or, for staff emails, `spree/core/lib/spree/core/previews/`.
-- **Don't** add ERB email views, mailer view helpers, or model calls from templates. Apps' own mailers that call `mail` with ERB views still work: `layouts/spree/base_mailer.html.erb` wraps them in the Liquid layout.
-- **Merchants edit customer emails in the dashboard** (`docs/plans/6.0-email-template-editor.md`). A store's published version is found before the file, per language. A new **customer** email must be registered in `Spree.editable_email_templates` (in `spree/emails/lib/spree/emails/engine.rb`) with a sample builder in `spree/emails/app/services/spree/emails/samples/`, and added to the dashboard's variables manifest; never register staff, store-owner or seller emails. Changing a default template shows merchants who customized it an "updated by Spree" notice, so change defaults deliberately.
-- **Every record a customer email serializes has an email serializer of its own** in `spree/emails/app/serializers/spree/emails/` (a thin subclass of the Store API one is fine), and email serializers point their associations at those. The generated `Email*` types then describe exactly what templates receive, and the editor suggests variables from their Zod schemas; an association pointing at a Store API serializer leaks its types into the email ones.
-- **Colors and fonts come from `store.branding`**, never hard-coded in a customer template. Generate types with `cd spree/api && bundle exec rake typelizer:generate`, which runs inside `spree_emails` so the API and email serializers both load.
-
-### API Authentication
-
-Four credential types, each with its own header and authorization model:
-
-- **Publishable keys** (`pk_xxx`) — Store API, `X-Spree-API-Key` header. Identifies the store; permits public/guest endpoints. Safe to expose in client-side code.
-- **Secret keys** (`sk_xxx`) — Admin API, `X-Spree-API-Key` header. **Server-to-server only.** Each key carries a list of [granular scopes](docs/plans/5.5-admin-api-key-scopes.md) (`read_products`, `write_orders`, etc.) that gate which endpoints it can hit. Authorization is scope-based, not CanCanCan-based.
-- **JWT tokens** — user auth, `Authorization: Bearer <token>` header. Used by both Store API (logged-in customer) and Admin API (logged-in admin user). Admin JWT auth uses **CanCanCan abilities** for authorization, not scopes — this is what the admin SPA uses.
-- **Guest cart tokens** — `X-Spree-Token` header. Authorizes operations on a specific guest cart.
-
-Admin API authorization summary:
-
-- Secret API key + scopes → for apps and integrations (audit-friendly, fine-grained)
-- JWT + CanCanCan → for human admin users (role-based)
-
-Both code paths converge at the same controllers; the controller checks permissions appropriately based on which credential authenticated the request.
-
-### Dependencies System
-
-Register swappable services in `Spree::Dependencies`:
-
-```ruby
-Spree::Dependencies.cart_add_item_service = 'Spree::Cart::AddItem'
-```
-
-### Security
-
-- CanCanCan permission checks on all actions
-- Use Rails [`params.permit`](https://api.rubyonrails.org/classes/ActionController/Parameters.html) to whitelist parameters in controllers
-- Use `Spree.user_class` / `Spree.admin_user_class` — never reference user models directly
-- Declare Ransack allowlists on **models** via `whitelisted_ransackable_attributes`, `whitelisted_ransackable_associations`, and `whitelisted_ransackable_scopes` to control which attributes, associations, and scopes are queryable from API requests
-
-### Performance
-
-- Use `includes`/`preload` to avoid N+1 queries (`ar_lazy_preload` gem also active)
-- **Every API request in the test suite is scanned for N+1 queries** (Prosopite in raise mode, configured in the dummy app's `test.rb`). A `Prosopite::NPlusOneQueriesError` prints the repeated statement and the serializer or model line that issued it. Fix it at that line: add the association to `collection_includes`, read a loaded association instead of running a scoped query, or replace the per-record lookup with one grouped query. Never answer it with `count` or `exists?` per record — that is the same N+1 in another shape; `size` on an already-loaded association is free, a `count` is not. No endpoint is exempt — never fix it by disabling the guard, skipping a spec, or wrapping the read in `Prosopite.pause`. An allow-list entry (`Prosopite.allow_stack_paths` in that `test.rb`) is only for a lookup that legitimately runs once per record being written (a uniqueness probe, a workflow run per requested row) and carries its reason next to it.
-- A list endpoint spec must render at least two records, since a repeated query cannot show with one — every `GET #index` block includes `it_behaves_like 'a list without N+1 queries'` with a `let!` creating them.
-- Use `Rails.cache` for expensive operations; use `cache_key_with_version` for custom keys
-- Proper database indexing
-
-### I18n
-
-- Use `I18n.t('spree.<key>')` with the full key for translations — `Spree.t` is deprecated (see `docs/plans/6.0-translations-in-core.md`)
-- Before removing a translation key `i18n-tasks unused` reports, check it is not passed around as a string or built from a value (`"spree.#{name}"`) — the checker cannot see either
-- Keep translations in `config/locales/en.yml` — no duplication across files
-
-### Money
-
-Money is never a float — not in Ruby, not in TypeScript (see `docs/plans/6.0-money-correctness.md`).
-
-- No `.to_f`, `Float()` or float literal (`100.0`) on an amount, price, total, cost, fee, discount, tax or payout. Compute in `BigDecimal`; in the dashboard never `parseFloat`/`Number()` a money string.
-- Round with `Spree::Money::Rounding.to_currency(amount, currency)` (the currency's ISO 4217 exponent from `spree/core/config/currency_exponents.json`), never `.round(2)`; split in minor units with `to_minor_units` / `from_minor_units`, never `* 100` / `/ 100`. Round only when persisting, calling a gateway, or serializing — not in intermediate math.
-- Read an amount from an API request with `Spree::Money::Rounding.parse_canonical(value, currency)`: canonical decimal strings only (`"1234.56"`), no locale parsing on the server. `Spree::LocalizedNumber` is deprecated; never add a model setter that re-parses numbers.
-- Write amounts out with `Spree::Money::Rounding.format(amount, currency)`.
-- In the dashboards, show and read money in the admin's own number format: `useMoneyLocale()` with `currencyParts` / `normalizeMoneyInput`, never a market's locale.
-- A third party that needs a JSON number gets `.to_f` once, on the line that hands it over, with a comment saying why.
-
-### Time zones
-
-- Parsing or formatting a date **for a store** uses that store's zone, never
- the server's: `Time.find_zone(store.preferred_timezone)` (which answers `nil`
- for a zone it does not know, so fall back with `|| Time.zone`), or
- `.in_time_zone(store.preferred_timezone)` on an existing time. A merchant who
- types `2026-01-01` means midnight where they trade — read in the server's
- zone that deadline moves by hours for every store that is not on it.
- Precedents: `Spree::CollectionRules::AvailableOn`, `Spree::Report`,
- `Spree::PriceList`.
-- Stamping *now* (`Time.current`) needs no zone — it is an instant, stored as
- UTC, and reading it back in a store's zone is the display layer's job.
-- Never `Time.zone.parse` operator input where a fixed instant is meant:
- `parse` fills in whatever the value omits, so `"09:00"` becomes today at nine
- and the stored threshold moves every midnight. Use `iso8601`, which refuses
- anything that is not a complete date.
-
-### 3rd party APIs
-
-When working on integrating 3rd party APIs, SDKs, or webhooks, follow these guidelines:
-- always use official ruby gems or SDKs if available, otherwise use Faraday or Ruby HTTP::Net for HTTP requests
-- tests should use VCR and record real API responses for replay in CI, remember to filter sensitive data from the recordings via VCR config filter
-- when handling errors expose them in a structured way to the API consumer, don't fully swallow errors or return generic 500s - Errors must name what to fix, in the service's own words, eg. EasyPost's summary said "Missing required parameter" while the useful end_shipper.address.phone sat in the structured errors array
-- A catch-all rescue must not swallow a deliberate refusal, eg. so the "unexpected failure means no label" rescue was silently eating every carefully worded message
-- Always use timeout, retries with exponential backoff, and circuit breaker patterns when calling 3rd party APIs. Never block the main thread for long-running API calls; use background jobs for async processing
-
-### Documentation
-
-- Re-generate OpenAPI spec after API changes: `bundle exec rake rswag:specs:swaggerize`
-- OpenAPI spec: `docs/api-reference/store.yaml` (generated from `spree/api/spec/integration`)
-- Update developer docs in `docs/developer/` when relevant
-- DO NOT edit the OpenAPI specs manually, it is generated from the integration tests. If you need to change the spec, change the integration tests instead and run swaggerize to regenerate the spec.
-- Regeneration is **deterministic**: the clock is frozen and every random name, email and token is seeded, so re-running swaggerize without changing the API produces a byte-identical file and an empty diff. A diff in `docs/api-reference/*.yaml` therefore means the API response actually changed — review it. The pinning lives in `spree/api/spec/support/deterministic_openapi.rb` and applies only under `OPENAPI=true` (set by the rake task), so normal spec runs keep their random data and real clock.
-- Because the clock is frozen, a factory whose record must already be in effect cannot rely on `Time.current` as its start: `starts_at < Time.current` is false when the two are the same instant. Give such factories a start slightly in the past (see the `:promotion` factory).
-
----
-
-## Frontend (TypeScript)
-
-### Workspace Setup
-
-Managed with **pnpm** workspace + **Turbo** for task orchestration. All packages use **Tsup** for building and **Vitest** for testing.
-
-```bash
-pnpm install # install all workspace deps
-pnpm build # build all packages (Turbo-cached)
-pnpm test # run all package tests
-pnpm typecheck # TypeScript validation across all packages
-pnpm lint # Biome lint across all packages
-pnpm lint:fix # Biome lint + auto-fix
-pnpm format # Biome format-write
-```
-
-**Linting:** All TypeScript packages use [Biome](https://biomejs.dev/) (replaces ESLint + Prettier). Root config at `biome.json`; per-package configs extend it via `"extends": ["../../biome.json"]` and set `"root": false`. CI runs `pnpm turbo lint` on every PR touching `packages/**`.
-
-### @spree/sdk — Store API Client
-
-TypeScript SDK for the customer-facing Store API v3.
-
-**Structure:**
-
-- `src/client.ts` — `createClient()` factory, `ClientConfig` interface
-- `src/store-client.ts` — all REST endpoints as resource classes (`client.products.list()`, `client.carts.create()`, etc.)
-- `src/types/generated/` — auto-generated TypeScript types from Alba serializers
-- `src/zod/generated/` — auto-generated Zod schemas for runtime validation
-
-**Patterns:**
-
-- Flat resource pattern: `client.products.list()`, `client.carts.items.create()`
-- Auth modes: publishable key (guest), JWT (customer)
-- Automatic retry with exponential backoff
-- `SpreeError` class with code, status, details
-- Ransack query params transformed via `transformListParams()` in sdk-core
-
-**Testing:** Vitest + MSW (Mock Service Worker) for HTTP mocking. Tests in `tests/`.
-
-```bash
-cd packages/sdk
-pnpm build # tsup build (CJS + ESM)
-pnpm test # vitest
-pnpm generate:zod # regenerate Zod schemas from TS types
-pnpm typecheck
-```
-
-### @spree/admin-sdk — Admin API Client
-
-Same patterns as `@spree/sdk` but for the Admin API. Supports both secret key (server-to-server) and JWT (admin SPA) authentication.
-
-### @spree/dashboard — Admin UI (React SPA)
-
-The Spree 6.0 admin dashboard — a Vite-built React SPA that replaces the legacy Rails `spree/admin` engine entirely. Tech stack: Vite, TanStack Router (file-based, type-safe), TanStack Query, React Hook Form + Zod, shadcn/ui + Base UI + Tailwind, Biome, Vitest. All API calls go through `@spree/admin-sdk`. See [`packages/dashboard/README.md`](packages/dashboard/README.md) and `docs/plans/6.0-admin-spa.md` for the full architecture (auth, permissions, multi-store, extension points, the three-package split).
-
-**Package boundary rules** (see `docs/plans/6.0-admin-spa.md` → "Package Split"):
-
-- `@spree/dashboard-ui` — primitives + headless compounds. Components accept data via props, never import providers or hooks.
-- `@spree/dashboard-core` — registries, providers, generic infra hooks, admin SDK client singleton, `defineDashboardPlugin`.
-- `@spree/dashboard` — routes, resource hooks (`use-orders`, `use-products`, …), Zod schemas, locales, app shell.
-
-The split lets plugin authors register UI via `defineDashboardPlugin` from `@spree/dashboard-core/plugin`, build new pages with `@spree/dashboard-ui` primitives, and reuse the same providers/hooks. It also lets app developers compose custom dashboards (e.g. seller panels) from the same packages.
-
-We use [Shadcn](https://ui.shadcn.com/docs/components) components using Base UI (NOT radix). Before adding a component ALWAYS check if Shadcn doesnt include it already. Use Shadcn CLI to install them in `dashboard-ui`.
-
-**Running the admin UI locally** (from a worktree — see "Development Server" above):
-
-```bash
-# 1. Boot this worktree's Spree backend (one terminal)
-pnpm wt:dev # foreground; streams logs — https://<branch>.spree.localhost
-
-# 2. Boot the admin (separate terminal)
-pnpm wt:dashboard # https://admin.<branch>.spree.localhost (proxies /api/* to this worktree's Rails)
-
-# 3. Boot the marketplace seller panel (third terminal, optional)
-pnpm wt:seller # https://sellers.<branch>.spree.localhost
-# Seed a seller to sign in as:
-# cd server && bin/rails spree:sellers:sample_data → [email protected] / spree123
-```
-
-The starter is the canonical host — the same app `spree add dashboard` scaffolds — so local dev exercises the real consumer path (shell + plugin pipeline) while still hot-reloading `@spree/dashboard`/`-core`/`-ui` source through the workspace. Building the workspace deps first matters on a fresh worktree: the starter's `vite.config.ts` resolves the compiled Node-side Vite entries (`@spree/dashboard/vite`, `@spree/dashboard-core/vite`) from `dist/` — `pnpm wt:dashboard` handles this (turbo builds the dependency graph, then starts Vite on the portless-assigned port).
-
-`VITE_API_PROXY_TARGET` sets the backend the dev proxy targets — the worktree setup writes it into `packages/dashboard-starter/.env.local` pointing at that worktree's Rails URL. Don't use `VITE_SPREE_API_URL` in dev — it flips the SDK to absolute cross-origin URLs, bypassing the proxy. Sign in with the seed admin user (`[email protected]` / `spree123` — override at seed time with `ADMIN_EMAIL` / `ADMIN_PASSWORD`; see `spree/core/app/services/spree/seeds/admin_user.rb`).
-
-**When implementing a new admin feature:**
-
-1. **The Admin API is the only data source.** Never reach into Rails models or import server-rendered HTML. If a needed endpoint or attribute is missing, add it to `spree/api` first (see backend conventions above), regenerate types via the [Type Generation Pipeline](#type-generation-pipeline), then consume it from the SPA.
-2. **Follow `docs/plans/6.0-admin-spa.md`** for the three extension points (table registry, navigation registry, component injection) and the shadcn copy-paste ownership model.
-3. **Wrap SDK calls in custom hooks** under `src/hooks/` (e.g. `useOrders`, `useProduct`) — never call `adminClient` directly from components.
-
-**Every detail page exposes slots.** A new or reworked resource detail page (admin dashboard and seller panel alike) renders `<Slot name="<resource>.form_sidebar">` at the end of its sidebar column — plus `<resource>.form_main` when the main column is where plugin cards belong — with the record in the context (`{ <resource> }`), and gets an entry in `docs/developer/dashboard/slots-catalog.mdx` in the same change. Seller panel slots are named `seller.<page>.<area>`. **A slot inside a page's form must be a host form:** wrap the form in `<FormProvider>`, seed `extensionFormValues('<resource>', record)` into its defaults and hydration reset, and merge `extensionSubmitValues('<resource>', form)` into the save payload (and the post-save reset), so fields a plugin binds with `useHostForm()` save with the page's Save button. The matching API controller must accept extension attributes — use `resource_permitted_attributes`, or splat `*model_additional_permitted_attributes` into a hand-written `permitted_params`. Seller API controllers splat `*model_class.additional_seller_permitted_attributes` instead, so an attribute opened to operators never becomes seller-writable by accident. Reference: `routes/_authenticated/$storeId/products/collections/$collectionId.tsx`.
-
-**Translations.** Every user-visible string in `@spree/dashboard` goes through i18next — page titles, headings, table column labels, button labels, empty states, toast messages, confirm dialog copy, select option labels, badges, status text, tooltips, helper text. Never hardcode English (or any language) into JSX, into table column definitions, or into dropdown option arrays. Keys live in `packages/dashboard/src/locales/en.json` (app-specific copy) or `packages/dashboard-core/src/locales/en.json` (cross-cutting: `admin.common.*`, `admin.fields.<attribute>.<facet>`). Reach for `i18n.t(...)` at module load (table definitions) and `useTranslation().t(...)` inside components. **Schemas in `src/schemas/` hold canonical values only — never label strings.** Build `{ value, label }` pairs at render time inside the component by mapping the canonical value list against translation keys. When adding a new translation key, ALWAYS add it to the all languages files in `packages/dashboard/src/locales/` and `packages/dashboard-core/src/locales/`.
-
-**Destructive actions need a confirm — unless a sheet already gates them.** Any action that destroys or detaches data and fires **straight from a click** must go through `useConfirm()` with `variant: 'destructive'` first: row-level delete/remove buttons, and every bulk action that runs immediately. Bulk actions that open a picker sheet or dialog (`BulkAction.form`, `ResourcePickerSheet`) already require an explicit submit — that IS the confirmation, so don't stack a second dialog on top. `BulkAction` takes a `confirm` option (`{n}` interpolates the count) for the immediate case.
-
-State the count for bulk (`{{count}}`, pluralized in every locale) and the record name for a single row. **When the write is immediate but the surrounding page is a dirty-tracked form, say so** — e.g. the products panel on a category/collection persists each add/remove/reorder on click while the rest of the page waits for Save, so its confirm copy reads "This takes effect immediately." Without that, merchants reasonably assume Save-or-Discard applies.
-
-**A listing page renders `<ResourceTable>`, never a hand-built table.** Any page whose job is to list records — a settings resource, a top-level index — goes through `ResourceTable` with a `defineTable` definition in `packages/dashboard/src/tables/`. It carries column visibility, sorting, search, pagination, row selection, bulk actions, empty and loading states, and the drag-reorder contract; a `<Table>` assembled by hand gets none of them and drifts from every other page the moment one of those is added. The endpoint it reads must return `{ data, meta }` — add Pagy to the controller rather than returning a bare array, or the table cannot page. Reference: `routes/_authenticated/$storeId/settings/policies.tsx`. A hand-built `<Table>` is for the panels *inside* a record (a product's variants, an order's line items), which are not listing pages.
-
-**Nested collection panels must paginate, never cap.** A panel listing records that belong to the parent (a category's or collection's products, and anything comparable) has to page through the nested endpoint and render `<Pagination meta={meta} onPageChange={...}>`. A bare `limit: 100` silently hides the remainder on a parent with thousands of children, and "select all" then quietly means "all 100 I happened to load". Two consequences to get right: show the parent's real total from `meta.count` rather than the loaded page length, and offset drag-reorder positions by `meta.from - 1`, since the reposition endpoints want an index across the whole set rather than within the page.
-
-**Forms.** Raw React Hook Form with `<Field>` / `<Input>` / `<FieldError>` blocks. Drive each input explicitly with `form.register(...)` or a `<Controller>` for custom widgets so the form reads top-to-bottom. Wrap RHF's `handleSubmit` with a try/catch that calls `mapSpreeErrorsToForm` (`@/lib/form-errors`) to route 422 responses onto `form.formState.errors`: flat attribute keys become field errors with `aria-invalid` + `<FieldError>`; `:base` and nested keys land on `errors.root.message` so render a destructive banner at the top of the form.
-
-```tsx
-async function handleSubmit(values: FormValues) {
- try {
- await onSubmit(values)
- } catch (err) {
- if (!mapSpreeErrorsToForm(err, form.setError)) throw err
- }
-}
-```
-
-- **Labels/placeholders/help** come from `packages/dashboard/src/locales/en.json` under `admin.fields.<resource>.<attribute>.{label,placeholder,help}` with cross-resource fallback `admin.fields.<attribute>.<facet>`. Dev mode logs missing keys to the console.
-- **Client validation** lives in the Zod schema (`zodResolver`).
-- **Mutation hooks built on `useResourceMutation` suppress their own toast for 422 responses** — the form already shows the inline message. Non-validation errors (network, 5xx, gateway) still toast. For a plain `useMutation` you want a fallback toast on, layer the catch: try `mapSpreeErrorsToForm` first, re-throw `SpreeError`, otherwise `toast.error(...)`.
-
-**Form schemas** live in `packages/dashboard/src/schemas/<resource>.ts` when shared across 2+ files or non-trivial (~30+ lines, nested sub-schemas, companion constants); inline is fine for short single-file forms. The schema file owns the Zod schema, its inferred `FormValues` type, defaults, dropdown option arrays, and regex constants. **Don't add form↔API mappers to paper over field renames** — if you find yourself translating `ot.label → form.presentation`, fix the API instead (read/write symmetry, see "API Controllers" above). Mappers are only for pure frontend state (upload progress, transient UI bookkeeping). **Never embed SDK entity types (`Customer`, `Order`, `Channel`, …) inside a form-values type** — react-hook-form's `Path<T>` enumerates every nested key, and the SDK types embed the whole object graph, which overflows TypeScript's relation cache (`RangeError: Map maximum size exceeded` killing `tsc -b`). Display-only embeds use an opaque record instead (pattern: `RuleEmbedRecord` in `schemas/price-list.ts` — full SDK records still assign into it at runtime; the form type just stays shallow). To locate this class of failure, run `@typescript/native-preview` (tsgo) — it reports the offending comparison with a line number instead of crashing; tsc stays the build compiler.
-
-**Base UI `<Select>` does not auto-render labels.** Unlike Radix, Base UI's `<Select.Value />` renders the raw selected `value` (the slug, the ISO code, the prefixed ID) instead of the matching `<SelectItem>`'s children. Two fixes:
-
-1. **Static option labels** — pass an `items` array; Base UI resolves the trigger label automatically:
-
- ```tsx
- <Select items={KIND_OPTIONS} value={...} onValueChange={...}>
- <SelectTrigger><SelectValue /></SelectTrigger>
- <SelectContent>
- {KIND_OPTIONS.map((o) => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}
- </SelectContent>
- </Select>
- ```
-
-2. **Dynamic option labels** — use the children render-prop:
-
- ```tsx
- <SelectValue>{(value) => roles.find((r) => r.id === value)?.name ?? (value as string)}</SelectValue>
- ```
-
-For free-text **searchable** pickers, use `<Combobox>` instead — see `components/spree/country-state-fields.tsx`.
-
-**`acts_as_list` ⇒ drag-and-drop reorder, never a numeric position input.** When a model uses `acts_as_list`, both top-level list tables and nested collection editors must reorder via dnd-kit:
-
-1. **Top-level resource tables**: pass `reorder={{ onReorder: (id, position) => adminClient.X.update(id, { position }) }}` to `<ResourceTable>` — it owns the `DndContext` + `SortableContext` internally, optimistic with rollback. Reference: `routes/_authenticated/$storeId/settings/payment-methods.tsx`.
-2. **Nested collection editors** (e.g. `option_values[]` on an option-type sheet): wrap `useFieldArray` rows in `DndContext` + `SortableContext`, give each row a `<GripVerticalIcon>` grip with `{...attributes} {...listeners}` from `useSortable`, and on drag end call `valuesArray.move(from, to)` and rewrite each row's `position` to its new index. The position field is **not rendered**; it's a computed output. Reference: `routes/_authenticated/$storeId/products/options.tsx` (vertical), `routes/_authenticated/$storeId/products/$productId.tsx` (product media grid).
-
-Use `verticalListSortingStrategy` for rows/lists, `rectSortingStrategy` for grids. Always pair `PointerSensor` (with `activationConstraint: { distance: 5 }` so row clicks don't hijack as drags) with `KeyboardSensor` + `sortableKeyboardCoordinates` for accessibility.
-
-**`<StoreDatePicker>` is the only correct way to render a date/datetime field.** Never use `<Input type="date">` (native styling breaks the design system) or the bare `<DatePicker>` in `components/ui/` (skips the store timezone). `@/components/spree/store-date-picker` reads the store's IANA timezone from `<StoreProvider>` so every datetime in the SPA means the same thing for every admin. Modes:
-
-- **Date-only** (default): emits `yyyy-MM-dd` strings (timezone-agnostic). Persist as-is — backend `date` columns accept these directly via Ransack.
-- **Datetime** (`includeTime`): the user picks a wall-clock time in the store's timezone; the picker emits the corresponding UTC ISO string and reinterprets it on read.
-
-Wire through `<Controller>` in forms; pass `value`/`onChange` directly in filter panels. **Inside a `<Sheet>`, pass `inline`** — the default Popover path hits the portal bug below.
-
-When displaying amount or percentage fields please always use `<InputGroup>` with a suffix/prefix, showing `%` or currency signs. Also numeric fields should use `number` input type.
-
-**Base UI `<Popover>` is unreliable inside a `<Sheet>`'s portal tree.** Symptom: the trigger gets `aria-expanded="true"` and `data-popup-open=""` on click, but no `[data-slot="popover-content"]` ever appears in the DOM. Happens in deeply-nested portal trees (Sheet → SortableContext → TableRow → Popover). Fix: render the panel inline with `absolute top-full left-0 z-50` + a `document.pointerdown` click-outside listener + Escape-to-close. A portal is only needed to escape an `overflow: hidden` ancestor; for table cells and form fields, inline is fine. Reference: `components/spree/color-picker.tsx`, plus `<StoreDatePicker inline>` above.
-
-`Currency` should be always rendered as a dropdown using `currency-select.tsx` component, this also applies to Preferences fields representing currency
-`Country` and `Countries` fields should always use `copuntry-combobox.tsx` component, this also applies to preferences fields representing a single country or multiple choices
-
-### @spree/core — Universal code
-
-Published package for code that is not tied to HTTP or a framework: the code lists (`pnpm generate:code-lists`) and code-shape checks, the open status/kind lists (`enums.generated.ts`, written by `rake typelizer:generate`), unit systems, display names, money helpers (arithmetic, percentages, reading typed amounts) and the filter vocabulary. The dashboard packages and the seller panel import it directly — never through `@spree/admin-sdk` / `@spree/seller-sdk`, which re-export the same code; `@spree/dashboard-core` still re-exports its money helpers for plugin authors. Code any client could use — a conversion, a format, a validation rule shared with the server — goes here, never into an SDK or a dashboard package. No runtime dependencies. `@spree/sdk-core` re-exports it and the SDKs bundle it, offering its code lists and money helpers under the same names as before. The code generators read it from source (the `@spree/source` export condition), so they run before anything is built.
-
-### @spree/sdk-core — Shared HTTP Layer
-
-Private package providing `createRequestFn()`, `SpreeError`, retry logic, and Ransack param transformation. Used internally by both SDKs.
-
-### Type Generation Pipeline
-
-When changing Alba serializers, run the full pipeline:
-
-```bash
-cd spree/api && bundle exec rake typelizer:generate # 1. TS types from serializers
-cd ../.. && pnpm generate:zod # 2. Zod schemas from TS types (Store, Admin, Seller SDKs)
-cd spree/api && bundle exec rspec spec/integration/ # 3. Integration tests
-bundle exec rake rswag:specs:swaggerize # 4. OpenAPI spec
-cd packages/sdk && pnpm test # 5. SDK tests
-```
-
-- TypeScript types → `packages/sdk/src/types/generated/` (Store) and `packages/admin-sdk/src/types/generated/` (Admin)
-- Zod schemas → `src/zod/generated/` in each SDK, exported as `@spree/sdk/zod`, `@spree/admin-sdk/zod` and `@spree/seller-sdk/zod`. Each SDK's `zod-schemas.test.ts` validates them against the responses recorded in `docs/api-reference/*.yaml`
-- Store types: `StoreProduct`, `StoreOrder`, etc. Admin types: `AdminProduct`, `AdminOrder`, etc.
-- Request body types → `src/types/params/` in each SDK, from the request schemas swaggerize writes (`pnpm generate:params`; the Lefthook hook and CI keep them in sync with `docs/api-reference/*.yaml`)
-
-A **Lefthook pre-commit hook** (`lefthook.yml`) regenerates types and Zod schemas automatically whenever `spree/api/app/serializers/**/*.rb` files are committed, then re-stages the generated output. You don't need to run steps 1 and 2 manually if you're committing serializer changes — the hook handles it. It also regenerates the Zod schemas when generated types or the generator change, and CI fails when committed schemas don't match the types. Steps 3–5 (integration tests, OpenAPI regen, SDK tests) still need to run locally before pushing — run step 3 as `pnpm test:rspec api spec/integration/` so it queues with the other sessions.
-
-### Changesets & Versioning
-
-Published packages use **Changesets** for versioning — one workspace-wide instance. Place changeset files in the root `.changeset/` directory (`pnpm changeset`), never in per-package directories. The packages that talk to the API (`@spree/sdk`, `@spree/admin-sdk`, `@spree/seller-sdk`, `@spree/core`, the dashboard trio and `@spree/seller-dashboard`) are one `fixed` group carrying the Spree gem version in npm spelling (`6.0.0.rc7` → `6.0.0-rc.7`); `@spree/cli` and `create-spree-app` version independently. Release with `pnpm version:packages` after bumping `Spree::VERSION` — never plain `changeset version`, whose computed version for the group is overwritten — then push the tags: `v<Spree version>` publishes the gems and the group, `@spree/cli@<version>` / `create-spree-app@<version>` publish a tool (`.github/workflows/release.yml`; `packages.yml` only runs checks). `pnpm version:tools` versions the tools alone between Spree releases. A changeset's bump type only sorts its changelog entry for those packages. `--ignore` defers changesets, it never discards them.
-
----
-
-## Testing
-
-Run the specs for what you changed before committing, then push and let CI run the full suite. This machine runs many sessions at once, so **never start a bare `parallel_rspec`** — every test run goes through `scripts/test/`:
-
-```bash
-pnpm test:changed # specs covering this branch's changed files (vs main + uncommitted), engine by engine
-pnpm test:changed -- --list # only show what would run, and which changed files have no spec
-pnpm test:rspec core spec/models/spree/state_spec.rb:7 # a targeted run in one engine (low priority, no queue)
-pnpm test:rspec api # a full engine suite: queued behind other suites, one worker per performance core, low priority
-pnpm test:slots # who holds the machine-wide test slot right now
-```
-
-`scripts/test/rspec <engine>` rebuilds the dummy app when it is missing or older than a migration, refreshes the worker databases, and splits a targeted run of several files across up to four workers, so `test_app` / `parallel_setup` rarely need running by hand. Engines: `core`, `api`, `emails`, `dashboard`, `opentelemetry`, `easypost`, `meilisearch`, `stripe`.
-
-**The full suite is CI's job, not the laptop's.** The repository is public, GitHub-hosted runners are free, and `tests.yml` already shards core twelve ways. Push and watch the checks (`gh pr checks --watch`, or `/autofix-pr`). Run a full suite locally only when CI reports a failure you need to reproduce, or when `test:changed` lists a change with no matching spec that touches everything (a factory, a migration, `Spree::Base`). One suite runs at a time machine-wide (`SPREE_TEST_SLOTS` to allow more); queued runs print who they are waiting for. Runs use the `utility` scheduling class, which yields to interactive work but may use every core; `SPREE_TEST_QOS=background` confines a run to the efficiency cores when the machine must stay cool, and `SPREE_TEST_WORKERS` changes the worker count. **A queue of sessions waiting on the slot means they are running full suites they should have pushed to CI.**
-
-### Backend (Ruby — RSpec)
-
-Each engine has its own test suite. Under the wrappers above, the raw commands are:
-
-```bash
-cd spree && bundle install # shared deps
-cd core && bundle install # engine deps
-bundle exec rake test_app # create dummy Rails app (skip if already exists)
-bundle exec rspec spec/models/spree/state_spec.rb # single file
-bundle exec rspec spec/models/spree/state_spec.rb:7 # single test
-```
-
-Default DB is SQLite3. For PostgreSQL:
-
-```bash
-DB=postgres DB_USERNAME=postgres DB_PASSWORD=password DB_HOST=localhost bundle exec rake test_app
-```
-
-Re-run `parallel_setup` after schema changes (`scripts/test/rspec <engine>` does this before every full suite).
-
-**Test guidelines:**
-
-- RSpec + Factory Bot
-- Prefer `build` over `create` for speed, use `create_list` for creating multiple records
-- Factories live in `lib/spree/testing_support/factories/`
-- ALWAYS use factories in tests, never call `Model#create` directly
-- A full suite runs through `scripts/test/rspec <engine>` (queued, capped, parallel); if there are any failures repeat the failed examples separately and confirm they really fail before investigating
-- Pragmatic — no tests for standard Rails validations, only custom ones
-- Controller specs: always add `render_views`, use `stub_authorization!` for auth
-- Use controller specs for testing edge cases, API integration tests are only for happy path/simple 422 failures to generate OpenAPI examples; otherwise they get too brittle and high-maintenance
-- Time-based tests: use `Timecop`
-- NEVER update or save the shared default store (`@default_store`) in specs — it outlives the example, so the change leaks into other specs. Stub what the code reads (`allow(Spree::Store).to receive(:default).and_return(build(:store, ...))`) or create a separate store
-- Don't over-engineer or repeat tests
-- Fold specs into the existing describe blocks, use context blocks for different scenarios, NEVER create new test files for a single new scenario unless it is a completely new feature
-
-### Frontend (TypeScript — Vitest)
-
-```bash
-cd packages/sdk && pnpm test # SDK tests (uses MSW for HTTP mocking)
-```
-
-### Admin SPA E2E (Playwright)
-
-End-to-end tests for `packages/dashboard` live in `packages/dashboard/e2e/`. The global setup boots a real Rails test server (port 3010) + Vite (port 5174) once and seeds the DB; specs then exercise the SPA through a browser against that stack. Locally Vite runs in dev mode; CI builds first and serves the bundle (`E2E_PREVIEW=1` → `vite preview`) because every test's fresh browser context re-downloads all dev-mode modules. CI also splits the suite across shard jobs (`--shard=n/m`), each with its own isolated Rails + SQLite + Vite stack — specs must stay self-contained (seed via global-setup fixtures or create your own records) and must not depend on records another spec file leaves behind.
-
-```bash
-cd packages/dashboard && pnpm test:e2e # full suite
-cd packages/dashboard && pnpm test:e2e:ui # Playwright UI mode (debug)
-```
-
-**Every behaviour change or new feature ships with an E2E test.** If a merchant or seller can see the change in the Admin Dashboard or the Seller Panel, the same change adds or updates a Playwright spec that exercises it there: admin specs as `e2e/<resource>.spec.ts`, seller panel specs as `e2e/seller-<area>.spec.ts`. This applies to backend-only changes too, such as a validation, a status rule or a newly required field. Backend specs and unit tests prove the server refuses bad input; only the E2E test proves the dashboards still let users complete the flow.
-
-The `login(page)` helper authenticates through the API (one POST plants the refresh cookie; the SPA's boot-time silent refresh does the rest) — only `auth.spec.ts` drives the login form itself.
-
-**Write UI-only assertions, like Capybara.** Drive the test through user-visible actions (fill labels, click buttons, find by role) and assert on visible UI. **Do not** reach for `page.waitForResponse(/api/...)` to wait for backend completion — it leaks API shape into tests and makes refactors painful. Playwright's `await expect(...).toBeVisible()` auto-polls until the condition is met (same as Capybara's `default_max_wait_time`), which covers virtually all cases.
-
-```ts
-// ✅ Capybara-style: drive the UI, assert on the UI.
-await page.getByLabel(/^label$/i).fill('Color')
-await page.getByRole('button', { name: /create option type/i }).click()
-await expect(page.getByRole('button', { name: 'color' })).toBeVisible({ timeout: 15_000 })
-
-// ❌ Avoid: couples the test to API shape, brittle on refactor.
-await Promise.all([
- page.waitForResponse((res) => /\/api\/v3\/admin\/option_types/.test(res.url()) && res.status() === 201),
- page.getByRole('button', { name: /create option type/i }).click(),
-])
-```
-
-The narrow exceptions where API-level waits are justified:
-
-- **No UI feedback** — a mutation kicks off background work (e.g., a webhook fire-and-forget) and there's nothing visible to assert against.
-- **Optimistic UI** — success state appears in the DOM before the API confirms; a UI-only assertion can't distinguish "rendered and persisted" from "rendered but later failed."
-
-Both are rare in the admin SPA, which renders success states only after mutations resolve.
-
-**Conventions:**
-
-- Use `Date.now()` suffixes on names so leftover rows from earlier specs don't collide (the suite runs serially — `fullyParallel: false, workers: 1`).
-- Disambiguate duplicate button names (e.g., a "Delete" in the sheet footer + another in a confirm dialog) by scoping: `page.getByRole('dialog').getByRole('button', { name: /^delete$/i })`.
-- Reference: `e2e/option-types.spec.ts`, `e2e/invitation-acceptance.spec.ts`.
-
-
-## Mintlify Documentation
-
-* every architectural changes, new models and entities need to be documented in `docs/developer` documentation
-* before adding new pages to documentation try to fit this into existing pages
-* if adding new pages ALWAYS link to existing associated/connected pages, cross-linking for easier navigation is very important
-* all API calls should be documented via mintlify Tabs component with examples via SDK and/or CURL
-* don't over-expose Ruby code, always try to interface via SDK/API first
-* ruby code snippets should have documented full path of the file, the root is always `server` as it's the default location for new apps created with `create-spree-app` CLI tool (the only official way to setup a Spree project)
-* for rake tasks/rails commands always show this via `spree` CLI tool, not directly rails, as all new projects are bootstrapped in Rails API dockerized by default, we use Tabs component to show `Spree CLI / Without CLI` examples
-* DON'T touch docs in the `v5` directory, it's Spree 5 documentation which is now frozen and shouldn't be updated
diff --git a/docs/AGENTS.md b/docs/AGENTS.md
new file mode 100644
index 0000000000..78ae6d1596
--- /dev/null
+++ b/docs/AGENTS.md
@@ -0,0 +1,11 @@
+# Documentation site (Mintlify)
+
+These rules apply to the pages under `docs/`, not to `docs/plans/`.
+
+- Don't touch `docs/v5/` — Spree 5 docs are frozen.
+- Architectural changes and new models are documented in `docs/developer/`. Fit new material into existing pages before adding one; a new page links to its related pages.
+- Show API usage through the SDK and cURL in a `<Tabs>` component; prefer the API to exposing Ruby internals.
+- Ruby snippets name their file path relative to `server/` (the default app created by `create-spree-app`).
+- Rails commands and rake tasks are shown through the `spree` CLI, with a "Spree CLI / Without CLI" `<Tabs>` pair.
+- `docs/api-reference/*.yaml` are generated from the API's integration specs — never edit them by hand.
+- Explain what a feature does, why it exists and how to use it, not how it works internally.
diff --git a/packages/AGENTS.md b/packages/AGENTS.md
new file mode 100644
index 0000000000..a873feb962
--- /dev/null
+++ b/packages/AGENTS.md
@@ -0,0 +1,38 @@
+# TypeScript packages — rules
+
+pnpm workspace + Turbo, Biome for lint and format (`pnpm lint`, `pnpm lint:fix`, `pnpm typecheck`), Vitest for tests. Libraries build with Tsup; the starters and the dashboard bundle with Vite. Follow standard React, TanStack Router/Query, React Hook Form and Zod practice; below is only what this codebase does differently.
+
+## Packages and boundaries
+
+- `@spree/dashboard-ui` — shadcn primitives on **Base UI (not Radix)**, plus headless composed components. Data comes through props; never import providers or hooks. Add components with the shadcn CLI after checking shadcn doesn't already have one.
+- `@spree/dashboard-core` — registries (table, nav, slot, settings nav), providers (auth, permission, store, theme), shared hooks and components (`StoreDatePicker`, `CurrencySelect`, `CountryCombobox`, `CountryStateFields`, `mapSpreeErrorsToForm`, `useResourceMutation`), the admin SDK client and `defineDashboardPlugin`. This is the plugin authors' API.
+- `@spree/dashboard` — routes, resource hooks, Zod schemas, locales, app shell. See `docs/plans/6.0-admin-spa.md`.
+- `@spree/core` — code any client could use (code lists, enums, money helpers, filter vocabulary). No runtime dependencies. Dashboards import it directly, never through an SDK re-export.
+- SDKs: resource-style clients (`client.products.list()`, `client.carts.items.create()`). Response types and Zod schemas under `src/types/generated/` and `src/zod/generated/`, and request types under `src/types/params/`, are **generated from the Ruby API** — never edit them by hand. List params other than `page`, `limit`, `expand`, `sort` and `fields` become Ransack `q[...]` filters.
+
+## Dashboard rules
+
+- **The Admin API is the only data source.** Missing data means adding it to `spree/api` first, then regenerating types. SDK calls are wrapped in hooks under `src/hooks/`, never called from components. Every `queryKey` includes the store id.
+- The dashboard typechecks against the SDK's built `dist/`; rebuild the SDK after changing it, and check with `pnpm exec tsc -b`.
+- **Translations:** every visible string goes through i18next. Keys live in `packages/dashboard/src/locales/` (app copy) or `packages/dashboard-core/src/locales/` (shared `admin.common.*`, `admin.fields.<attribute>.*`) and are added to **every** language file there. Schemas hold canonical values only; labels are mapped at render time.
+- **Listing pages use `<ResourceTable>`** with a `defineTable` definition in `src/tables/`, backed by a paginated `{ data, meta }` endpoint. Reference: `routes/_authenticated/$storeId/settings/policies.tsx`. Panels inside a record use a plain table, but nested collections paginate (`<Pagination meta={meta}>`, totals from `meta.count`) — never a fixed `limit`.
+- **Detail pages expose slots:** `<Slot name="<resource>.form_sidebar">` (and `.form_main` where plugin cards belong) with the record in context, documented in `docs/developer/dashboard/slots-catalog.mdx`. Seller panel slots are `seller.<page>.<area>`. A slot inside a form makes it a host form: `<FormProvider>`, `extensionFormValues(...)` in defaults and resets, `extensionSubmitValues(...)` merged into the save payload. Reference: `routes/_authenticated/$storeId/products/collections/$collectionId.tsx`.
+- **Forms:** React Hook Form with explicit `register` / `<Controller>`, Zod via `zodResolver`, and `mapSpreeErrorsToForm` in the submit handler's `catch` to route 422s onto fields (`:base` goes to a banner). Labels come from `admin.fields.<resource>.<attribute>.{label,placeholder,help}`. Don't write form↔API mappers to paper over renames — fix the API. Never embed SDK entity types in form-value types (it overflows TypeScript); use an opaque record like `RuleEmbedRecord`. Schemas shared by two or more files go in `src/schemas/`.
+- **Destructive actions** that fire straight from a click confirm through `useConfirm({ variant: 'destructive' })`, naming the record or the count. Actions behind a picker sheet or dialog are already confirmed. If the write is immediate inside a dirty-tracked form, the copy says so.
+- **Ordering:** a model with `acts_as_list` is reordered by drag and drop (dnd-kit), never a position input. Tables pass `reorder` to `<ResourceTable>` (reference: `settings/payment-methods.tsx`); nested editors follow `products/options.tsx`.
+- **Inputs:** dates use `<StoreDatePicker>` (store time zone; pass `inline` inside a Sheet), never `<input type="date">`. Currencies use `CurrencySelect`, countries `CountryCombobox`. Amounts and percentages are `type="number"` inside an `<InputGroup>` showing the currency or `%`. Show and read money in the admin's own format with `useMoneyLocale()`; never `parseFloat` or `Number()` a money string.
+- **Base UI quirks:** `<SelectValue>` renders the raw value, so pass `items` to `<Select>` or a render function to `<SelectValue>`. `<Popover>` can fail to open inside a `<Sheet>`; render the panel inline instead (see `dashboard-ui/src/spree/color-picker.tsx`).
+- Shell components shared with the seller panel must not require providers the seller panel doesn't mount (it has no `StoreProvider`).
+
+## Releases
+
+Changesets live in the root `.changeset/` (`pnpm changeset`). The API-facing packages version together with the Spree gem version; release with `pnpm version:packages`, never plain `changeset version`.
+
+## End-to-end tests (Playwright)
+
+Specs live in `packages/dashboard/e2e/` — `<resource>.spec.ts` for the admin, `seller-<area>.spec.ts` for the seller panel — and run with `pnpm wt:e2e`. The setup boots its own Rails and Vite and seeds the database. CI shards the suite, so every spec creates its own records and depends on no other file.
+
+- Write them like Capybara: drive the UI by label and role, assert on what is visible. Don't wait on API responses unless there is no visible result to wait for.
+- Suffix record names with `Date.now()`. Scope duplicate button names to their dialog.
+- Use the `login(page)` helper; only `auth.spec.ts` drives the login form.
+- Renaming visible copy or changing layout breaks specs — search `e2e/` before committing either.
diff --git a/scripts/worktree/lib.sh b/scripts/worktree/lib.sh
index a070b12c7a..d9ba79b826 100755
--- a/scripts/worktree/lib.sh
+++ b/scripts/worktree/lib.sh
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
-# Shared helpers for the multi-worktree dev workflow (see CLAUDE.md "Worktrees").
+# Shared helpers for the multi-worktree dev workflow (see AGENTS.md "Development environment").
# Everything derives from the current git branch, so the scripts work both from
# worktrunk hooks and when run by hand. Pass a branch name as WT_BRANCH (or as
# the first argument to the calling script) to operate on another worktree's
diff --git a/spree/AGENTS.md b/spree/AGENTS.md
new file mode 100644
index 0000000000..e4ece47e2b
--- /dev/null
+++ b/spree/AGENTS.md
@@ -0,0 +1,112 @@
+# Spree gems — Ruby rules
+
+Rails 8.1 engines, everything namespaced under `Spree::`. Follow Rails conventions and the Rails Security Guide; below is only what Spree does differently.
+
+## Architecture
+
+- Logic lives in models, concerns and workflows — not controllers or serializers. Add a service only when a model or concern won't do.
+- Per-request context: `Spree::Current.store`, `.currency`, `.locale`.
+- Customers and staff: `Spree.customer_class` and `Spree.admin_user_class`, never a user model constant (`Spree.user_class` is deprecated).
+- Swappable classes are registered in `Spree::Dependencies` (`Spree::Dependencies.cart_add_item_workflow = 'MyApp::AddItem'`). The old `*_service` keys are deprecated, and some are no longer consulted at all.
+- YARD comments (`@param`, `@return`) on classes and non-obvious public methods only; never on private helpers.
+- Descriptive variable names, no abbreviations.
+- Jobs that iterate over records use `ActiveJob::Continuable`.
+
+## Models
+
+```ruby
+class Spree::Product < Spree.base_class
+ include Spree::SingleStoreResource # belongs_to :store
+ include Spree::HasCustomFields
+ include Spree::Metadata
+
+ acts_as_paranoid
+ publishes_lifecycle_events
+
+ has_many :variants, class_name: 'Spree::Variant', dependent: :destroy
+ validates :slug, presence: true, uniqueness: { scope: spree_base_uniqueness_scope }
+end
+```
+
+- Inherit from `Spree.base_class`. Store-owned data includes `Spree::SingleStoreResource`; only global reference data (countries, roles) and children of a parent (variants under products) go unscoped.
+- Tier-1 models publish events via `publishes_lifecycle_events`.
+- Always pass `class_name` and `dependent` on associations; `dependent: :destroy_async` for high-fanout ones.
+- String columns, never Rails enums. **No state machines**: declare statuses with `has_status` (column `status`) and move records between them with workflows (`docs/plans/6.0-normalize-state-to-status.md`).
+- Value objects use `ActiveModel::Model` + `ActiveModel::Attributes`, never `Struct` (e.g. `Spree::PickupPointOption`).
+- Uniqueness validations use `scope: spree_base_uniqueness_scope`, backed by a unique index.
+- Use `Model.table_name`, never a hardcoded table name. Bulk writes use `insert_all` / `upsert_all` (MySQL needs special handling).
+- Options and configuration are [model preferences](../docs/developer/customization/model-preferences.mdx).
+- Workflows and services write behaviour inline as named steps; they don't delegate to model business methods.
+
+## Migrations
+
+- New migrations target `ActiveRecord::Migration[8.1]`; existing ones keep `[7.2]`. **Never edit a migration that has shipped.**
+- No foreign key constraints. `null: false` on required columns.
+- No defaults on string or status columns (the creating workflow sets them); integer, decimal and boolean columns do carry defaults.
+- Must run on PostgreSQL, MySQL and SQLite: guard JSON with `t.respond_to?(:jsonb) ? t.jsonb(...) : t.json(...)`. One `metadata` JSON column per table; `preferences` columns are JSON, secrets are `:password` preferences in an encrypted `secret_preferences` text column (`docs/plans/6.0-json-preferences.md`).
+- Data transformations go in rake tasks, never migrations. Soft delete is `paranoia` plus a `deleted_at` column.
+
+## API controllers (`spree/api`)
+
+`Spree::Api::V3::ResourceController` provides Pagy, Ransack, CanCanCan, prefixed-ID lookup and HTTP caching. The `Store::`, `Admin::` and `Seller::` subclasses differ in credentials and defaults: Store is read-only unless a resource opts into writes; Admin is full CRUD by default.
+
+- Credentials: publishable key `pk_` (Store, `X-Spree-API-Key`); secret key `sk_` (Admin, server-to-server, authorized by [scopes](../docs/plans/5.5-admin-api-key-scopes.md)); JWT bearer (customers and admin users — admin JWT is authorized by CanCanCan); guest cart token `X-Spree-Token`.
+- **Scope every lookup to the store** — including incidental ones like a `reason_id` or `stock_location_id` from params. `current_store.<association>` turns a foreign id into a 404. `accessible_by` filters by role, not tenant, so it is no substitute.
+- Override `model_class`, `serializer_class` (`Spree.api.<name>_serializer`), `scope` (call `super`), `collection_includes`. A resource written through a workflow overrides `create_workflow` / `update_workflow` (and `*_workflow_arguments`) instead of re-implementing the action, so it keeps the base class's record-level authorization.
+- RESTful actions only; promote anything else to a nested controller.
+- **Request bodies are flat and declared with `request_params`**, which drives permitting, OpenAPI and the SDK request types (`pnpm generate:params`). Never hand-write a request body in an rswag spec or a request type in an SDK. Money is `:decimal`, countries and currencies are `:country` / `:currency`. A shape used by two or more endpoints is a class in `app/request_schemas/`.
+- Extensions add writable attributes with `Spree::Product.additional_permitted_attributes += [...]` (always `+=`). Override `resource_permitted_attributes`, never `permitted_attributes`, or extension attributes are dropped. Seller controllers splat `additional_seller_permitted_attributes` instead.
+- `normalize_params` decodes anything shaped like a prefixed ID inside nested hashes — don't enable it on controllers that carry opaque provider values (see `Admin::PaymentMethodsController`).
+- Ransack allowlists are declared on models (`whitelisted_ransackable_attributes` / `_associations` / `_scopes`). Every entry is a filter any caller can run, so an association from a global model to store-owned rows is a cross-store leak.
+
+## Typed values — never a Ruby class name on the wire
+
+The database stores class names; the API boundary converts them to short names (`Spree::CreditCard` → `credit_card`).
+
+- **STI families selected by `type`** (promotion and price rules, payment methods, integrations, calculators, imports…): serialize with `Model.api_type_for(record.type)`; resolve writes with `subclassed_via` / `find_by_api_type`, which reject a class name. Override `self.api_type` to keep the value stable across a rename. Pickers read the family's `…/types` endpoint, never a hardcoded list.
+- **Registry-selected strategy classes** (fulfillment, delivery-rate, tax, payout providers…): base class `extend Spree::ApiTyped`; normalize with `Spree::ApiTyped.class_name_for(registry, value)` plus an inclusion validation; serialize with `api_type_attributes`; load with `Spree::ApiTyped.registered_class` — never `constantize` a stored string. Every new family gets a registry.
+- **Polymorphic columns**: serialize with `Spree::Base.polymorphic_api_type`, accept with `polymorphic_type_for(value, candidates)`. The base controller translates `type_*` filters.
+- Never special-case old class names; upgrade tasks migrate stored data.
+
+## Serializers (Alba)
+
+Admin serializers extend Store serializers; every serializer an Admin one references has its own Admin counterpart.
+
+- **Store** (customer-facing): public data and display values only — no timestamps, `metadata`, cost prices, internal statuses or back-office relations.
+- **Admin**: adds `created_at`, `updated_at`, `deleted_at` (when paranoid), `metadata` and back-office fields.
+- Associations are their own serializers, never hand-built hashes. Keep serializers lean; logic goes on the model. Never use `typelize_from`.
+- Value lists: **closed** lists use `enum:` + `enum_type_name:` and are added to `Typelizer::OpenEnums::CLOSED_LIST_NAMES`; **open** lists (`has_status`, kinds extensions can add) use `enum_type_name:` alone; registry-driven `type` attributes stay `:string` with a `comment:` listing the built-ins. Both named kinds are generated into `@spree/core`.
+- Deprecated fields are marked (`deprecated: 'Use X. Removed in 6.1.'`), not just described.
+- After a serializer change run the type pipeline: `cd spree/api && bundle exec rake typelizer:generate`, then `pnpm generate:zod` from the root (the Lefthook pre-commit hook does both), then integration specs and `bundle exec rake rswag:specs:swaggerize`. Restart Rails — Alba caches definitions at boot.
+
+## Events and webhooks
+
+`record.publish_event('order.completed')`; subscribers in `app/subscribers/spree/` subclass `Spree::Subscriber`. Payloads use Store serializers only — never a hand-built hash or an Admin serializer; extras go in `metadata` (`docs/plans/6.0-typed-webhook-events.md`).
+
+## Emails (Liquid + MJML)
+
+See `docs/plans/6.0-liquid-mjml-emails.md` and `docs/developer/customization/emails.mdx`.
+
+- Templates are `app/views/spree/<mailer>/<action>.liquid` (that path is a public key), MJML with front-matter subject; never ERB.
+- Mailers inherit `Spree::BaseMailer`, wrap sends in `with_store_locale`, and pass data through `email_data(record, Spree::Emails::XyzSerializer)` — templates never touch models. Every record a customer email serializes has its own serializer under `spree/emails/app/serializers/spree/emails/`.
+- Never serialize a token: build reset, invitation and download URLs in the mailer.
+- Colors and fonts come from `store.branding`.
+- A new or changed customer email updates `docs/developer/customization/email-variables.mdx`, `spree/emails/spec/mailers/spree/rendered_emails_spec.rb` and gets a mailer preview. A new customer email is registered in `Spree.editable_email_templates` with a sample builder; staff and seller emails never are.
+
+## Money, time and translations
+
+- Money: `BigDecimal` only — no `.to_f`, `Float()` or float literals on amounts. Use `Spree::Money::Rounding`: `to_currency` to round (only when persisting, serializing or calling a gateway), `to_minor_units` / `from_minor_units`, `parse_canonical` for request input (canonical decimal strings, no locale parsing), `format` for output. A third party that needs a JSON number gets `.to_f` once, with a comment.
+- Store dates use the store's zone: `Time.find_zone(store.preferred_timezone) || Time.zone`. Never `Time.zone.parse` operator input meant as a fixed instant — use `iso8601`.
+- `I18n.t('spree.<key>')` with the full key (`Spree.t` is deprecated). Keys live in `config/locales/en.yml`. Before removing a key `i18n-tasks unused` reports, check it isn't built dynamically.
+
+## Third-party APIs
+
+Use the official gem when one exists, record tests with VCR (filter secrets), and call through timeouts and retries — slow calls go to jobs. Errors reaching the API consumer must name what to fix in the provider's own words (surface the structured error, not the summary), and a catch-all `rescue` must never swallow a deliberate, well-worded refusal.
+
+## Tests
+
+- RSpec + FactoryBot (factories in `lib/spree/testing_support/factories/`). No tests for standard Rails validations; fold new cases into existing `describe` blocks.
+- Controller specs (`render_views`) cover edge cases; rswag integration specs cover only the happy path and simple 422s that feed the OpenAPI examples.
+- Every API request in specs is checked for N+1 queries by Prosopite. Fix the query at the reported line (`collection_includes`, a loaded association, one grouped query) — never a per-record `count`, never disabling the guard. Every index spec includes `it_behaves_like 'a list without N+1 queries'` with at least two records.
+- Never update or save the shared `@default_store`; stub what the code reads or build another store. Registries and hooks a spec changes must be restored afterwards.
+- OpenAPI files in `docs/api-reference/` are generated (`bundle exec rake rswag:specs:swaggerize`) and deterministic: the clock is frozen, so a factory whose record must already be active needs a start in the past. Never edit them by hand; a diff means the API changed.