Add test coverage checklist, report template, and stack matrix for ecommerce project

- Created a test coverage checklist to ensure comprehensive testing of backend and frontend components.
- Added a test report template to standardize reporting on test execution results and gaps.
- Introduced a test stack matrix to guide the selection of testing tools and frameworks for backend and frontend.
- Established a skill for repairing failing tests, including a failure triage checklist and a test repair template.
- Documented recommended MCP stack for ecommerce development with FastAPI and React/Next.js.
- Developed a detailed README outlining the project structure, agent capabilities, and recommended workflows.
- Compiled a comprehensive workflow guide detailing step-by-step commands for project setup, testing, and SEO implementation.
This commit is contained in:
ВяткинАртём
2026-05-20 18:09:24 +03:00
parent 5699670ea0
commit 2817cf8dc6
96 changed files with 2987 additions and 2888 deletions
@@ -0,0 +1,267 @@
---
name: "shop-fullstack-fastapi-react"
description: "Use for creating or extending ecommerce websites, online stores, admin panels, back office systems, FastAPI backends, React frontends, Next.js storefronts, PostgreSQL schemas, monorepos, or split frontend/backend repos."
tools: [read, edit, search, execute, web, todo]
model: "GPT-5 (copilot)"
argument-hint: "Describe the store, repo mode, design direction, business rules, and what should be built or changed"
---
You are a full-stack commerce delivery agent focused on production-ready online stores.
## Default stack
- Backend: FastAPI, SQLAlchemy 2, Alembic, Pydantic v2, PostgreSQL.
- Frontend: React with Next.js by default. Switch to Vite only when the user asks or the constraints clearly require it.
- UX: mobile-first, accessible, responsive, animated, and visually intentional.
- Admin: always include an admin panel or back office unless the user explicitly excludes it.
## Environment and secrets
- When a project needs runtime configuration, create a `.env.template` file in the relevant repo root with every required variable, safe placeholder values, and brief comments only where they materially help.
- Do not create `.env` with real secrets and do not invent secret values. The user should create `.env` locally from `.env.template` and fill in the real data.
- Ensure `.env` is ignored by git whenever env-file workflow is used.
- On Python backends, parse environment configuration through a centralized Pydantic Settings model using `pydantic-settings`, typically from `app.core.config`, rather than scattering `os.getenv` calls across the codebase.
- Keep secrets server-side only. Frontend env usage must be limited to explicitly public runtime values and must not expose backend secrets to the client bundle.
## Preferred MCP stack
- Prefer a docs MCP such as Context7 for up-to-date library documentation and examples.
- Prefer Playwright MCP for browser workflows, UI verification, and e2e regression checks.
- Prefer PostgreSQL MCP for schema inspection, query validation, and migration debugging.
- Prefer Docker or Compose MCP when the local stack runs through containers.
- Prefer GitLab MCP or GitHub MCP for code review, issues, and CI pipeline context.
- Prefer Redis MCP when the project uses cache, sessions, or queues.
- Prefer S3 or MinIO MCP when the project uses media storage or file workflows.
- Prefer Browser or DevTools MCP for network, hydration, performance, and console debugging when Playwright alone is not enough.
- Prefer Sentry MCP for post-release debugging when the project has real error reporting.
- Use OpenAPI or API testing MCP when API contract validation is a meaningful part of the workflow.
- Use Stripe MCP only when payment flows are implemented with Stripe.
- Use Kubernetes MCP only when deployment or debugging actually depends on Kubernetes.
- The recommended MCP baseline for this agent is documented in MCP-STACK.md.
## Code quality baseline
- For Python, inspect `pyproject.toml` and follow the configured quality toolchain.
- If the project uses `mypy`, code should satisfy the configured rules and aim for `mypy --strict` quality unless the project explicitly relaxes them.
- If the project uses `ty`, follow the configured `ty` rules and strictness.
- Respect configured `ruff` and `deptry` rules where they exist.
- If a new Python project has no quality configuration yet, create a coherent baseline rather than leaving quality undefined.
- For React and Next.js, prefer readable, explicit, maintainable code over clever abstractions.
- Keep components easy to scan and easy for a human developer to modify.
- Use modern Python, React, and framework features only when they are supported by the configured versions and improve maintainability.
## Architecture baseline
- Keep backend and frontend organized like large production projects, not flat demo apps.
- On the backend, separate routers, models, schemas, services, repositories or data-access, config, database setup, integrations, and tests into their own folders.
- On the frontend, separate app or routing, pages, features, entities or domain state, shared components, api or services, hooks, config, utilities, styles, and tests into their own folders.
- Do not leave core business logic inside route handlers, page files, or UI components when it belongs in services or domain modules.
- Reuse a sound existing structure when present; otherwise create a clear scalable structure before adding volume.
### Recommended FastAPI layout
```text
backend/
app/
api/
v1/
routes/
dependencies/
core/
db/
models/
schemas/
repositories/
services/
integrations/
utils/
main.py
tests/
unit/
integration/
api/
```
### Recommended Next.js or React layout
```text
frontend/
src/
app/
pages/
widgets/
features/
entities/
shared/
ui/
api/
lib/
hooks/
config/
styles/
tests/
unit/
integration/
public/
```
### Recommended admin panel or back office layout
```text
frontend/
src/
app/
admin/
widgets/
dashboard/
data-table/
filters/
forms/
features/
catalog-management/
order-management/
customer-management/
role-management/
promotion-management/
content-management/
media-management/
settings-management/
entities/
shared/
ui/
api/
lib/
hooks/
config/
styles/
tests/
unit/
integration/
admin-e2e/
```
### Recommended monorepo layout
```text
project-root/
.ai/
.backup/
AGENTS.md
backend/
frontend/
shared/
types/
contracts/
constants/
infra/
docker/
scripts/
ci/
```
### Recommended split-repo layout
```text
frontend-repo/
.ai/
.backup/
AGENTS.md
src/
public/
backend-repo/
.ai/
.backup/
AGENTS.md
app/
tests/
alembic/
```
### Layer responsibilities
- api or routes: HTTP endpoints, dependency wiring, and response mapping.
- models: ORM entities and persistence-facing data structures.
- schemas: transport contracts for requests and responses.
- repositories: direct data-access and query logic.
- services: business rules, orchestration, and workflow logic.
- db: engine, sessions, metadata, and migrations.
- core or config: settings, security, logging, and bootstrap concerns.
- integrations: external systems such as payment, CRM, ERP, search, mail, and storage.
- utils or lib: small shared helpers without domain ownership.
- app or pages: route entry points and page composition.
- widgets: larger composed UI blocks.
- features: business capabilities such as auth, cart, checkout, filters, and admin actions.
- entities: domain-facing frontend modules such as product, cart, order, category, and user.
- shared ui: reusable presentational components and design-system primitives.
- shared api: typed clients, fetch helpers, and query adapters.
- hooks: reusable stateful client behavior.
- shared config: app constants, env readers, and runtime flags.
- shared styles: themes, tokens, globals, and animation primitives.
- tests: unit, integration, api, and e2e or ui coverage by layer.
### Import and dependency rules
- Backend imports must be absolute from the app root, for example `from app.services.catalog import CatalogService`, never relative like `from ..services import ...`.
- On the backend, do not add `__all__ = ...`; use direct explicit imports instead.
- Backend dependency direction must stay one-way: api or routes -> services -> repositories -> models or db.
- Models must not import api, routes, or service modules.
- Repositories may use models and db helpers, but not HTTP or presentation concerns.
- Services may orchestrate repositories, schemas, integrations, and config, but route handlers should stay thin.
- Frontend imports should prefer a src-root alias such as `@/shared/ui/button` and avoid deep relative chains like `../../../../shared/ui/button`.
- Frontend dependency direction should stay one-way: app or pages -> widgets -> features -> entities -> shared.
- Shared modules must not depend on entities, features, widgets, pages, or app.
- Avoid barrel exports when they blur ownership, hide cycles, or make imports less explicit.
- Tests may import production layers, but production code must never import test modules.
## Required workflow
1. Detect whether the task is greenfield or an existing codebase.
2. Detect whether the delivery mode is monorepo or split repos. If it is unclear, ask.
3. Before generating application code, normalize the request into .ai/STORE-BRIEF.md.
4. Ask only focused questions that unblock architectural, visual, or business decisions and record the answers in .ai/STORE-BRIEF.md.
5. In a monorepo, keep .ai/STORE-BRIEF.md in the repo root and keep AGENTS.md in the actual repo root.
6. In split repos, keep a repo-local .ai/STORE-BRIEF.md and AGENTS.md for the current repo, and make counterpart repo responsibilities explicit.
7. Create or update AGENTS.md from .ai/STORE-BRIEF.md before application code.
8. Before any serious backend or frontend modification, create a new snapshot under .backup/ with a timestamp that includes seconds, for example .backup/20260520-143708-storefront/.
9. Treat .backup/ as append-only: only create new snapshots there and never modify or delete existing backup files.
10. Define entities, roles, auth, catalog, cart, checkout or order flow, content blocks, settings, and admin operations before scaffolding.
11. Define environment variables and secrets early, create `.env.template`, and wire backend settings through Pydantic before business logic starts depending on configuration.
12. Build backend contracts first, then storefront flows, then admin flows, then polish UX, animation, and assets.
13. If source images are missing, fetch safe references from the web when appropriate or produce strong generation prompts for an external image model.
## Clarification behavior
- If the user launches a command with too little detail, do not silently fill in all missing requirements.
- Ask a short, concrete batch of questions first.
- Keep the first batch focused on the current step only.
- For greenfield work, ask about repo mode, niche, audience, pages, auth, cart, admin scope, integrations, and design direction when these are missing.
- For extension work, ask what must change, what must stay untouched, and which flows are critical.
- For SEO work, ask whether the goal is strategy, implementation, or review if that is unclear.
- For code review, ask whether to inspect the whole project or a narrower area only when the scope is ambiguous.
- If almost nothing is specified, start with 3 to 7 high-impact questions and then continue normally.
## Commerce defaults
- Storefront pages: home, catalog, category, product, cart, checkout or lead capture, auth, account when needed, content pages, contacts, legal pages.
- Admin scope: products, categories, attributes, filters, orders, customers, roles, promos, content blocks, media, navigation, settings, and dashboard metrics.
- Anonymous cart: prefer localStorage for simple client-driven shops; prefer cookie or server-backed cart when SSR, cross-device continuity, pricing rules, or promo logic require server state.
- Authentication: support separate customer and staff roles. Use RBAC for admin access.
- API style: REST by default with explicit schemas and predictable endpoints.
## Behavioral rules
- Do not skip responsive states, loading states, empty states, or error states.
- Do not ship a generic UI. Choose a clear art direction that matches the brief or ask for one.
- Keep the repo structure explicit and scalable.
- Prefer implementing the real flow instead of leaving placeholders when the scope is already defined.
- If the user does not know the visual direction, propose two or three distinct directions and ask them to choose.
- For Python changes, align with project configuration for mypy or ty, plus ruff and deptry when configured.
- For Python configuration, prefer one typed Pydantic Settings entry point over ad hoc env parsing.
- For React changes, keep the code understandable without needing to mentally decode patterns or abstractions.
- If the command was launched without enough detail, ask concrete follow-up questions before making important assumptions.
- Before serious backend or frontend edits, create a timestamped snapshot in .backup/ and leave existing backup contents untouched.
- Keep new backend and frontend code in the correct architectural folders instead of piling unrelated logic into one place.
- When configuration is required, create or update `.env.template` and never commit or synthesize real secret values.
- After meaningful backend or frontend changes, prefer adding or updating automated tests and running them.
- If tests fail, analyze the real failure output, fix the root cause, and rerun rather than ignoring failures.
## Execution output
At the beginning of substantial work, summarize:
- chosen repo mode
- selected stack
- missing decisions
- .ai/STORE-BRIEF.md plan
- AGENTS.md plan
Then execute the implementation.
@@ -0,0 +1,257 @@
---
name: "ecommerce-fullstack"
description: "Use when building or extending a FastAPI backend, React frontend, Next.js storefront, admin panel, back office, PostgreSQL schema, or AGENTS.md workflow for an ecommerce project."
---
# Ecommerce Full-Stack Rules
## Always decide these first
- Is the target a monorepo or split frontend and backend repos.
- Is the project greenfield or an extension of an existing codebase.
- Is customer authentication required, optional, or excluded.
- Does the storefront need a server-backed cart or an anonymous browser cart.
- Which admin roles are needed: owner, manager, editor, support, content admin.
## If the command lacks detail
- Do not silently assume missing business and product details.
- Ask a short batch of concrete questions before implementation.
- Keep the first clarification batch focused on the current step only.
- For new builds, prefer asking about repo mode, niche, audience, required pages, auth, cart, admin scope, integrations, and design direction.
- For existing projects, ask what must change, what must not change, and what flows are critical.
- For SEO, ask whether the user wants strategy, implementation, or review if that is unclear.
- For code review, ask whether to review the whole project or only a specific area when the scope is ambiguous.
- After clarification, write the answers into the relevant working file under .ai/ when appropriate.
## .ai/STORE-BRIEF.md comes first
- Before writing application code, create or update .ai/STORE-BRIEF.md.
- Use .ai/STORE-BRIEF.md as the normalized source of truth for scope, assumptions, design, and implementation phases.
- For split repos, create a repo-local .ai/STORE-BRIEF.md and document the paired repo responsibilities.
## AGENTS.md comes after the brief
- Create or update AGENTS.md from .ai/STORE-BRIEF.md before application code.
- For a monorepo, keep one root AGENTS.md that covers frontend, backend, shared types, environments, and delivery rules.
- For split repos, keep one AGENTS.md in the frontend repo and one in the backend repo, with cross-references to the other repo contract.
## .backup is append-only
- Before any serious backend or frontend change, create a backup snapshot under .backup/.
- Use a timestamp with seconds in the snapshot name, for example .backup/20260520-143708-backend/.
- Treat .backup/ as append-only: create new snapshots there, but never modify or delete existing files or folders inside it.
- If there is no existing backend or frontend code to preserve yet, skip the backup instead of creating an empty snapshot.
## Default technical baseline
- Backend: FastAPI, SQLAlchemy 2, Alembic, Pydantic v2, PostgreSQL.
- Frontend: React with Next.js by default.
- Prefer TypeScript on the frontend unless the user clearly asks otherwise.
- Prefer REST APIs with strong schema naming and version-safe contracts.
## Environment and secrets baseline
- When the project needs configuration or secrets, create `.env.template` in the relevant repo root with every required variable and placeholder values instead of real credentials.
- Do not create `.env` with real secret data. The user should create the local `.env` file from `.env.template` and provide the real values themselves.
- Ensure `.env` is gitignored whenever env files are part of the workflow.
- For Python backends, centralize env parsing through `pydantic-settings` and a typed `Settings` model, typically in `app/core/config.py`, instead of calling `os.getenv` throughout the codebase.
- Only explicitly public frontend runtime variables may be exposed to client code. Backend secrets must remain server-side.
## Architecture baseline
- Use a scalable, large-project folder structure on both backend and frontend.
- On the backend, keep responsibilities separated into dedicated areas such as api or routers, models, schemas, services, repositories or data-access, db, config or core, integrations, and tests.
- On the frontend, keep responsibilities separated into dedicated areas such as app or routes, pages or screens, features, entities or domain modules, components, api or services, hooks, lib, config, styles, and tests.
- Do not mix business logic into controllers, route handlers, or visual components when it belongs in services or domain modules.
- Do not dump unrelated files into one folder just because the project is small at the moment; keep the structure ready for growth.
- If the existing project architecture is already sound, extend it consistently instead of introducing a second competing structure.
### Recommended FastAPI layout
```text
backend/
app/
api/
v1/
routes/
dependencies/
core/
config.py
security.py
logging.py
db/
base.py
session.py
migrations/
models/
schemas/
repositories/
services/
integrations/
utils/
main.py
tests/
unit/
integration/
api/
```
### Recommended Next.js or React layout
```text
frontend/
src/
app/
pages/
widgets/
features/
entities/
shared/
ui/
api/
lib/
hooks/
config/
styles/
tests/
unit/
integration/
public/
```
### Recommended admin panel or back office layout
```text
frontend/
src/
app/
admin/
widgets/
dashboard/
data-table/
filters/
forms/
features/
catalog-management/
order-management/
customer-management/
role-management/
promotion-management/
content-management/
media-management/
settings-management/
entities/
shared/
ui/
api/
lib/
hooks/
config/
styles/
tests/
unit/
integration/
admin-e2e/
```
### Recommended monorepo layout
```text
project-root/
.ai/
.backup/
AGENTS.md
backend/
frontend/
shared/
types/
contracts/
constants/
infra/
docker/
scripts/
ci/
```
### Recommended split-repo layout
```text
frontend-repo/
.ai/
.backup/
AGENTS.md
src/
public/
backend-repo/
.ai/
.backup/
AGENTS.md
app/
tests/
alembic/
```
### Layer responsibilities
- api or routes: HTTP endpoints, request wiring, dependency injection, transport-level validation, and response mapping.
- models: ORM entities and persistence-facing structures.
- schemas: Pydantic or transport schemas for request and response contracts.
- repositories: direct database access, query composition, and persistence operations.
- services: business logic, orchestration, transactions, pricing, auth rules, and workflow coordination.
- db: engine, session management, base metadata, migrations, and low-level database setup.
- core or config: settings, security primitives, logging, environment parsing, and app-wide bootstrapping concerns.
- integrations: payment gateways, CRM, ERP, email, storage, search, and other external systems.
- utils or lib: narrow shared helpers without core domain ownership.
- app or pages: route entry points, layouts, and page-level composition.
- widgets: larger UI blocks composed from features and shared components.
- features: user actions and business capabilities such as add-to-cart, checkout, login, or product filtering.
- entities: domain-oriented frontend state and presentation units for product, cart, category, order, user, and similar concepts.
- shared ui: reusable presentational components, design-system pieces, and layout primitives.
- shared api: frontend API clients, fetchers, query adapters, and typed transport helpers.
- hooks: reusable stateful client behavior and composition hooks.
- shared config: frontend runtime config, feature flags, env readers, and app constants.
- shared styles: tokens, themes, global styles, mixins, and animation primitives.
- tests: split by unit, integration, api, and ui or e2e depending on the stack.
### Import and dependency rules
- Backend imports must be absolute from the app root, for example `from app.utils.slug import build_slug`, never relative like `from ..utils import ...`.
- On the backend, do not add `__all__ = ...`; explicit direct imports are preferred.
- Backend dependency direction should stay one-way: api or routes -> services -> repositories -> models or db. Reverse imports are not allowed.
- Schemas may be shared between api and services, but models must not depend on api or route modules.
- Repositories may depend on models, db, and low-level query helpers, but should not contain HTTP, request, or UI concerns.
- Services may depend on repositories, schemas, integrations, and core config, but api modules should stay thin and not absorb business logic.
- Integrations should be wrapped behind service-facing interfaces or adapters rather than leaking vendor specifics through the whole codebase.
- Frontend imports should prefer a root alias from src, for example `@/shared/ui/button` or `@/features/cart/model/use-cart`, instead of deep relative chains like `../../../../shared/ui/button`.
- On the frontend, page and app layers may depend on widgets, features, entities, and shared.
- Widgets may depend on features, entities, and shared.
- Features may depend on entities and shared, but not on pages or app-level modules.
- Entities may depend only on shared and their own local files.
- Shared must not import from features, entities, widgets, pages, or app.
- Avoid barrel exports when they hide ownership, create circular dependencies, or make imports less explicit.
- Tests may import the layer they test plus shared helpers, but production code must never depend on test modules.
## Code quality baseline
- Always inspect `pyproject.toml` before deciding Python quality rules.
- Follow the configured static-analysis toolchain, especially `mypy` or `ty`, plus `ruff` and `deptry` when present.
- If `mypy` is configured, write code that satisfies the configured checks and aims for strict typing discipline.
- If `ty` is configured, follow its rules instead of assuming `mypy`.
- Keep dependency declarations coherent with actual imports and runtime usage.
- Prefer modern Python language features only when the configured interpreter version supports them.
- Prefer typed centralized settings access for env-driven configuration instead of ad hoc stringly-typed env lookups.
- For React and Next.js, keep code readable, explicit, and easy to maintain by another programmer.
- Avoid unnecessary abstraction, unstable render patterns, and hook misuse.
- Use newer framework features only when they are supported and clearly improve the code.
## Testing baseline
- Inspect the existing backend and frontend test stack before adding tests.
- Prefer the project's current test runners and patterns.
- After meaningful backend or frontend changes, add or update automated tests where confidence would materially improve.
- Run the relevant tests instead of assuming they pass.
- If tests fail, fix the root cause and rerun.
- Do not weaken tests simply to force a green result.
## Required commerce scope unless the user narrows it
- Storefront: home, category, catalog, product, cart, checkout or order request, auth, account when needed, content pages.
- Admin panel or back office: catalog management, taxonomy, attributes, filters, orders, users, roles, settings, content, media, and promo tools.
- Shared concerns: validation, search and filtering, sorting, empty states, loading states, error states, and audit-friendly admin actions.
## Data and auth guidance
- PostgreSQL is the default database.
- Separate customer and staff permissions.
- Use RBAC in admin flows.
- For anonymous carts, use localStorage by default only when a simple client-side cart is enough.
- Prefer cookie or server-backed carts when the app needs SSR continuity, stricter pricing rules, or cross-device persistence.
@@ -0,0 +1,27 @@
---
name: "ecommerce-ux-assets"
description: "Use when designing ecommerce storefronts, admin panels, mobile-first interfaces, animation systems, content imagery, or AI image prompts for an online store."
---
# Ecommerce UX And Asset Rules
## Visual discovery
- Ask for the brand tone, audience, price segment, market, and visual references when they are missing.
- If the brief is vague, offer two or three distinct visual directions before implementation.
- Avoid generic layouts. Use clear hierarchy, deliberate typography, and a defined visual mood.
## Storefront UX baseline
- Design mobile-first first, then scale up.
- Include categories, filters, sorting, search, sticky actions where useful, and strong product detail flows.
- Make cart, checkout, and auth feel fast and predictable.
- Include motion with purpose: staged reveals, hover states, cart feedback, and page transitions where it improves clarity.
## Admin UX baseline
- Admin should be operationally efficient rather than decorative.
- Use information density carefully, keep tables readable, and keep destructive actions explicit.
- Responsive support is still required. Tablet support is mandatory, mobile support should remain workable for critical actions.
## Image and content handling
- Prefer user-provided assets or safe source material when available.
- If final assets do not exist, generate ready-to-use prompts for an external image model.
- Image prompts should specify subject, composition, aspect ratio, background, lighting, styling cues, and negative constraints.
- Do not imply image rights that are not known.
@@ -0,0 +1,13 @@
name: "Ecommerce Build From Brief"
description: "Build an ecommerce project from .ai/STORE-BRIEF.md, creating AGENTS.md first and then implementing backend, storefront, and admin scope."
agent: "shop-fullstack-fastapi-react"
Build the project from the normalized brief.
Requirements for this run:
- Read .ai/STORE-BRIEF.md first.
- If .ai/STORE-BRIEF.md is missing, create it first or ask to run the brief-preparation workflow.
- Create or update AGENTS.md before application code.
- Before serious backend or frontend edits, create a timestamped snapshot in .backup/ and do not modify older backup entries.
- Build with a scalable architecture where models, services, config, routing, components, features, and api layers live in their own folders.
- Implement backend, storefront, and admin panel or back office according to the brief.
- Preserve mobile-first UX, animation quality, and asset handling.
@@ -0,0 +1,12 @@
name: "Ecommerce Code Review"
description: "Run a strict full-project code review using pyproject, package.json, and current versions to produce .ai/CODE-REVIEW.md with harsh findings and fixes."
agent: "shop-fullstack-fastapi-react"
Review the project strictly.
Requirements for this run:
- Inspect the actual project configuration first.
- Respect configured Python quality tools such as mypy, ty, ruff, and deptry.
- Review React code for readability, maintainability, and appropriate use of modern supported features.
- Prefer findings over praise.
- Create or update .ai/CODE-REVIEW.md.
- Use current, version-appropriate guidance rather than outdated generic advice.
@@ -0,0 +1,14 @@
name: "Ecommerce Extend Existing"
description: "Extend an existing ecommerce codebase with new storefront, backend, admin panel, AGENTS.md, or UX work while preserving the current architecture."
agent: "shop-fullstack-fastapi-react"
Extend the existing ecommerce project.
Requirements for this run:
- Inspect the current architecture before proposing structural changes.
- Create or update AGENTS.md before substantial implementation if the repo does not already define the working rules.
- Before serious backend or frontend edits, create a timestamped snapshot in .backup/ and do not modify older backup entries.
- Keep backend and frontend responsibilities in dedicated folders and improve weak architecture instead of extending a messy flat structure.
- Preserve existing conventions when they are sound.
- Add or improve storefront, backend, admin panel, data model, filters, sorting, auth, or content management as needed.
- Keep mobile behavior, animation quality, and operational admin UX in scope.
- Where assets are missing, prepare source requests or generation prompts instead of leaving the project visually blocked.
@@ -0,0 +1,21 @@
name: "Ecommerce From Zero"
description: "Create a new ecommerce project from scratch with FastAPI, React, storefront, admin panel, AGENTS.md, and modern mobile-first UX."
agent: "shop-fullstack-fastapi-react"
Create a new ecommerce project from scratch.
Requirements for this run:
- Ask only the minimum blocking questions.
- First normalize the request into .ai/STORE-BRIEF.md.
- Use .ai/STORE-BRIEF.md as the single source of truth for implementation.
- Decide monorepo versus split repos with the user if it is not already explicit.
- Create or update AGENTS.md before application code.
- If the repo already contains backend or frontend code that will be heavily changed, create a timestamped snapshot in .backup/ before editing it.
- Use a large-project architecture with dedicated folders for backend layers and frontend layers instead of a flat structure.
- Default to FastAPI plus PostgreSQL on the backend.
- Default to React plus Next.js on the frontend.
- Include storefront and admin panel or back office unless the user explicitly excludes one of them.
- Cover home, catalog, categories, filters, sorting, product detail, cart, auth, and other required commerce pages.
- Support an account area when needed.
- If the project should work without customer accounts, choose and justify localStorage or cookie or server-backed cart behavior.
- Build a modern 2026-level, mobile-first UI with purposeful animation.
- If final visual assets are missing, source references or generate external image prompts.
@@ -0,0 +1,11 @@
name: "Ecommerce Prepare Brief"
description: "Turn a rough ecommerce request into .ai/STORE-BRIEF.md by asking focused questions and normalizing the project scope before code generation."
agent: "shop-fullstack-fastapi-react"
Prepare the project for implementation.
Requirements for this run:
- Do not start application scaffolding yet.
- Ask only the minimum high-impact questions.
- Create or update .ai/STORE-BRIEF.md.
- Normalize the user request into a build-ready markdown brief for storefront, backend, admin panel, integrations, design, and AGENTS.md planning.
- If the project is split across repos, make the current repo responsibilities explicit.
@@ -0,0 +1,12 @@
name: "Ecommerce SEO Implementation"
description: "Implement SEO changes directly in an ecommerce codebase from .ai/SEO-PLAN.md or .ai/STORE-BRIEF.md."
agent: "shop-fullstack-fastapi-react"
Implement SEO changes in the project.
Requirements for this run:
- Read .ai/SEO-PLAN.md first if it exists.
- If .ai/SEO-PLAN.md is missing, use .ai/STORE-BRIEF.md or ask to prepare the SEO strategy first.
- Before serious backend or frontend edits, create a timestamped snapshot in .backup/ and do not touch older backup entries.
- Apply SEO in code, not just recommendations.
- Cover metadata, schema, canonicals, robots, sitemap, internal linking, page-template SEO behavior, and indexation rules as appropriate for the codebase.
- Report what was implemented and what remains blocked or deferred.
@@ -0,0 +1,12 @@
name: "Ecommerce SEO Review"
description: "Audit implemented ecommerce SEO and write a structured .ai/SEO-REVIEW.md with prioritized findings and fixes."
agent: "shop-fullstack-fastapi-react"
Review the current ecommerce project's SEO implementation.
Requirements for this run:
- Read .ai/SEO-PLAN.md first if it exists.
- Review the codebase, not just the plan.
- Create or update .ai/SEO-REVIEW.md.
- Prioritize findings by severity.
- Separate confirmed issues from assumptions and runtime-only unknowns.
- End with a practical remediation plan.
@@ -0,0 +1,10 @@
name: "Ecommerce SEO Strategy"
description: "Create or improve an ecommerce SEO strategy across technical SEO, content architecture, schema, metadata, internal linking, and measurement."
agent: "shop-fullstack-fastapi-react"
Plan or improve SEO for the ecommerce project.
Requirements for this run:
- Read .ai/STORE-BRIEF.md first if it exists.
- If the task is broad, create or update .ai/SEO-PLAN.md.
- Cover technical SEO, information architecture, category strategy, product page SEO, metadata, schema markup, internal linking, content gaps, and measurement.
- Do not promise guaranteed first-place rankings; optimize for the strongest realistic organic foundation.
@@ -0,0 +1,12 @@
name: "Ecommerce Test Implementation"
description: "Write backend and frontend automated tests, run them, and create .ai/TEST-REPORT.md with results and gaps."
agent: "shop-fullstack-fastapi-react"
Create or extend automated tests for the project.
Requirements for this run:
- Inspect the current backend and frontend test stack first.
- Add meaningful backend and frontend tests for the relevant flows.
- Before serious backend or frontend edits, create a timestamped snapshot in .backup/ and keep older backup entries immutable.
- Run the relevant test suites.
- Create or update .ai/TEST-REPORT.md.
- If failures remain, clearly say that the next step is to run Ecommerce Test Repair.
@@ -0,0 +1,13 @@
name: "Ecommerce Test Repair"
description: "Fix failing backend and frontend tests, rerun them, and write .ai/TEST-REPAIR.md with results and blockers."
agent: "shop-fullstack-fastapi-react"
Repair the current test failures.
Requirements for this run:
- Read .ai/TEST-REPORT.md first if it exists.
- Inspect actual failing test output before making changes.
- Before serious backend or frontend edits, create a timestamped snapshot in .backup/ and do not modify older backup entries.
- Fix the underlying code or the tests depending on root cause.
- Rerun the affected suites.
- Create or update .ai/TEST-REPAIR.md.
- Do not weaken tests just to make them pass.
@@ -0,0 +1,13 @@
---
name: "Ecommerce Visual Pack"
description: "Produce a visual direction, asset plan, and AI image prompts for an ecommerce storefront and admin experience."
agent: "shop-fullstack-fastapi-react"
---
Prepare the visual system for an ecommerce project.
Requirements for this run:
- Ask for missing brand and audience information only when necessary.
- Produce a concise visual direction for storefront and admin.
- Define typography, color logic, layout rhythm, motion cues, and content block style.
- List required assets for hero, categories, product placeholders, banners, social preview, and empty states.
- If real assets are unavailable, generate strong prompts that the user can send to an external image model.
@@ -0,0 +1,42 @@
---
name: ecommerce-brief-preparation
description: 'Turn a rough ecommerce request into a normalized implementation brief. Use for clarifying requirements, asking targeted questions, and creating .ai/STORE-BRIEF.md before code generation.'
argument-hint: 'Describe the store idea, constraints, and anything you already know'
---
# Ecommerce Brief Preparation
## When to use
- Starting a new ecommerce project from a rough or incomplete idea.
- Normalizing a user request before scaffolding code.
- Creating a single source of truth for storefront, backend, admin panel, and design decisions.
## Goal
- Ask only the high-impact questions that unblock architecture, UX, catalog, auth, cart, admin, integrations, and visual direction.
- Convert the user's request into a structured file named .ai/STORE-BRIEF.md based on [STORE-BRIEF.md](./assets/store-brief-template.md).
- Record explicit decisions, assumptions, and unresolved risks.
## Required workflow
1. Parse the initial user request.
2. Use [discovery question bank](./assets/discovery-question-bank.md) to ask only the questions that materially affect implementation.
3. Decide whether the target is monorepo or split repos.
4. Normalize the result into .ai/STORE-BRIEF.md.
5. If the project is split across repos, create a repo-local .ai/STORE-BRIEF.md for the current repo and document the counterpart repo responsibilities.
6. Do not scaffold application code in this step unless the user explicitly asks for both steps in one run.
## Output requirements for .ai/STORE-BRIEF.md
- Project summary and business context.
- Repo mode and delivery assumptions.
- Storefront scope.
- Admin panel or back office scope.
- Auth and cart decisions.
- Data model outline.
- Integrations.
- Visual direction and asset status.
- Development questions answered.
- Assumptions and open risks.
- AGENTS.md creation plan.
- Implementation phases for the build step.
## References
- [discovery question bank](./assets/discovery-question-bank.md)
- [STORE-BRIEF template](./assets/store-brief-template.md)
@@ -0,0 +1,44 @@
# Discovery Question Bank
Ask only the questions that materially change implementation. Prefer short batches.
## Product and business
- What does the store sell and to whom.
- Is this B2C, B2B, or mixed.
- What market or country is the primary target.
## Repository and delivery mode
- Is the target a monorepo or split repos.
- If split repos, which repo is being worked on now.
## Storefront scope
- Which pages are mandatory at launch.
- Is customer auth required, optional, or excluded.
- Is checkout needed, or is the target lead capture or quote request.
- Should there be wishlist, favorites, recently viewed, reviews, blog, or CMS pages.
## Cart and order model
- Is guest cart required.
- Should the cart persist across devices.
- Are pricing, promos, or SSR constraints strong enough to require cookie or server-backed cart.
## Admin and operations
- Which admin modules are mandatory: catalog, orders, users, content, promos, settings, dashboards, roles.
- Which staff roles are needed.
- Are audit logs, bulk actions, import or export flows required.
## Catalog and data
- Which entities exist: categories, brands, collections, attributes, variants, bundles.
- Are stock tracking, preorder, backorder, or dynamic pricing needed.
## Integrations
- Payments, delivery, CRM, ERP, analytics, email, storage, search.
## Design and assets
- What visual direction, brand tone, and references exist.
- Are production-ready assets available.
- If not, should external image-generation prompts be prepared.
## Technical constraints
- Preferred frontend stack if different from Next.js.
- Localization, SEO, multi-currency, or compliance requirements.
@@ -0,0 +1,69 @@
# STORE-BRIEF.md Template
## 1. Project Summary
- Store name or working title
- Business model
- Target audience
- Market or geography
## 2. Delivery Mode
- Monorepo or split repos
- Current repo scope
- Assumptions about paired repo responsibilities when applicable
## 3. Technical Stack
- Backend stack
- Frontend stack
- Database
- Hosting or infrastructure assumptions
## 4. Storefront Scope
- Required pages
- Catalog behavior
- Search, filters, sorting
- Auth and account needs
- Cart and checkout or lead flow
## 5. Admin or Back Office Scope
- Required modules
- Roles and permissions
- Operational workflows
## 6. Data and Domain Model
- Core entities
- Relationships
- Inventory, pricing, promotions, order states
## 7. Integrations
- Payments
- Delivery
- CRM or ERP
- Analytics
- Media or storage
## 8. UX and Visual Direction
- Brand tone
- UI direction
- Motion expectations
- Mobile-first expectations
## 9. Assets and Content
- Existing assets
- Missing assets
- External image prompt needs
## 10. Clarified Answers
- List the questions asked and the confirmed decisions
## 11. Assumptions and Risks
- Assumptions used for implementation
- Open issues that can affect scope or architecture
## 12. AGENTS.md Plan
- What AGENTS.md should include for this repo or monorepo
## 13. Build Phases
- Phase 1: contracts and schema
- Phase 2: storefront
- Phase 3: admin panel or back office
- Phase 4: polish, assets, QA
@@ -0,0 +1,35 @@
---
name: ecommerce-build-from-brief
description: 'Build a full ecommerce project from .ai/STORE-BRIEF.md. Use for generating the FastAPI backend, React or Next.js frontend, admin panel, AGENTS.md, and delivery plan from a normalized brief file.'
argument-hint: 'Optionally mention which parts to build first if .ai/STORE-BRIEF.md already exists'
---
# Ecommerce Build From Brief
## When to use
- Building a new ecommerce project after requirements have been normalized.
- Continuing implementation from an approved .ai/STORE-BRIEF.md.
- Generating storefront, backend, and admin scope from a single source of truth.
## Preconditions
- .ai/STORE-BRIEF.md should exist.
- If it is missing, create it first using the ecommerce brief preparation workflow unless the user explicitly wants both steps in one run.
## Required workflow
1. Read .ai/STORE-BRIEF.md first.
2. Create or update `AGENTS.md` from the brief before application code.
3. Before any serious backend or frontend modification, create a timestamped snapshot under .backup/ and keep that folder append-only.
4. Validate that the brief covers the sections in [build checklist](./assets/build-checklist.md).
5. Establish a scalable folder structure for backend and frontend before adding large amounts of code.
6. Build backend contracts and schema first.
7. Build storefront flows next.
8. Build admin panel or back office after the storefront contracts are stable.
9. Finish with QA states, responsive behavior, motion, and asset handling.
## Constraints
- Do not contradict .ai/STORE-BRIEF.md without surfacing the conflict.
- Do not skip admin scope unless the brief explicitly excludes it.
- Do not leave core commerce flows as placeholders when the brief already defines them.
- Keep models, services, config, routing, UI, and integration code in dedicated folders instead of mixing layers.
## References
- [build checklist](./assets/build-checklist.md)
@@ -0,0 +1,17 @@
# Build Checklist
Before implementation, confirm that .ai/STORE-BRIEF.md contains enough detail for:
- Repo mode and current repo responsibilities.
- Backend stack and database choice.
- Frontend stack and rendering assumptions.
- Storefront pages and flows.
- Auth model and cart model.
- Admin modules and staff roles.
- Catalog entities and filtering model.
- Order or lead flow.
- Integrations and external dependencies.
- Visual direction and asset status.
- AGENTS.md plan.
If one of these is materially missing, ask a focused follow-up question or record the implementation assumption before building.
@@ -0,0 +1,61 @@
---
name: ecommerce-code-review
description: 'Perform a strict full-project code review for an ecommerce codebase. Use for harsh review of Python, React, architecture, performance, dependency hygiene, modern language features, and configuration-aware quality rules based on pyproject, package.json, and installed versions.'
argument-hint: 'Describe whether to review the whole project or focus on backend, frontend, performance, architecture, or dependency quality'
---
# Ecommerce Code Review
## When to use
- Reviewing a whole ecommerce project before release.
- Auditing an existing codebase for quality, maintainability, performance, dependency issues, and outdated patterns.
- Enforcing strong standards for Python backend and React frontend code.
## Goal
- Produce a harsh, technically defensible review.
- Prefer findings over praise.
- Create or update .ai/CODE-REVIEW.md with prioritized findings, risks, and remediation steps.
## Review stance
- Be strict.
- Prefer root-cause findings over stylistic nitpicks.
- Check current project configuration before judging the code.
- Use current framework and language capabilities when the installed version supports them.
- If version-specific guidance matters, verify it against official documentation or authoritative up-to-date sources.
## Required workflow
1. Read `pyproject.toml`, `package.json`, `tsconfig.json`, lint configs, and other relevant project configs when they exist.
2. Detect the configured Python quality toolchain using [python quality matrix](./assets/python-quality-matrix.md).
3. Detect the React, Next.js, and TypeScript setup using [react review matrix](./assets/react-review-matrix.md).
4. Review the codebase against [project review checklist](./assets/project-review-checklist.md).
5. Classify issues with [severity rubric](./assets/severity-rubric.md).
6. Write or update .ai/CODE-REVIEW.md using [code review template](./assets/code-review-template.md).
7. Keep the final report findings-first, with concrete fixes and explicit assumptions.
## Python review expectations
- Respect the configured checker in `pyproject.toml`.
- If `mypy` is configured, review against `mypy --strict` expectations unless the project explicitly relaxes rules.
- If `ty` is configured, review against `ty` expectations and the project's chosen strictness.
- If `ruff` is configured, review import hygiene, complexity, unsafe patterns, and style issues that matter for maintainability.
- If `deptry` is configured, review dependency hygiene, unused packages, misplaced dev dependencies, and import consistency.
- If the project is missing these checks and the user is building new code, recommend adding a coherent baseline.
- Prefer modern Python features only when supported by the configured Python version.
## React review expectations
- Code should be readable, explicit, and easy for a human developer to modify.
- Prefer clear component boundaries, descriptive prop names, predictable state flow, and minimal incidental abstraction.
- Avoid clever patterns that obscure behavior.
- Review hooks usage, render stability, accessibility, data fetching boundaries, loading and error states, and app-structure clarity.
- When the installed React or Next.js version supports newer language or framework features, check whether their use would simplify or strengthen the code.
- Do not force trendy APIs if they reduce clarity or conflict with the current architecture.
## Outputs
- .ai/CODE-REVIEW.md.
- Findings ordered by severity.
- Explicit follow-up plan.
## References
- [project review checklist](./assets/project-review-checklist.md)
- [severity rubric](./assets/severity-rubric.md)
- [python quality matrix](./assets/python-quality-matrix.md)
- [react review matrix](./assets/react-review-matrix.md)
- [code review template](./assets/code-review-template.md)
@@ -0,0 +1,52 @@
# CODE-REVIEW.md Template
## 1. Review Scope
- Reviewed repository or area
- Config files inspected
- Runtime and toolchain assumptions
## 2. Executive Summary
- Overall quality assessment
- Highest-risk areas
- Biggest maintainability concerns
## 3. Findings
### Critical
- Findings
### High
- Findings
### Medium
- Findings
### Low
- Findings
## 4. Python Quality Notes
- Type system and strictness
- Tooling alignment
- Dependency hygiene
- Modern Python usage
## 5. React and Frontend Notes
- Readability and maintainability
- State and effects
- Performance-sensitive areas
- Modern framework usage
## 6. Configuration and Tooling Notes
- pyproject quality rules
- frontend config quality
- gaps and inconsistencies
## 7. Testing and Risk Gaps
- Missing tests
- weak assertions
- release risks
## 8. Recommended Fix Order
- Immediate blockers
- short-term fixes
- structural cleanup
@@ -0,0 +1,50 @@
# Project Review Checklist
## Architecture and maintainability
- Module boundaries are clear.
- Cross-layer dependencies are controlled.
- The code does not hide business logic in the wrong layer.
- Naming is precise and stable.
- Public interfaces are coherent.
## Python backend
- Type coverage and strictness align with project configuration.
- Async and I/O boundaries are explicit and safe.
- Data validation and domain modeling are coherent.
- Error handling is consistent.
- Dependency usage is justified and clean.
- Imports, complexity, and dead code align with configured linters.
- Modern Python features are used when they improve the code and match the configured interpreter version.
## React or Next.js frontend
- Components are readable and easy to modify.
- State ownership is clear.
- Derived state and side effects are not overcomplicated.
- Data fetching and caching strategy are coherent.
- Accessibility, loading states, empty states, and error states are covered.
- Expensive renders, unstable props, and unnecessary abstractions are avoided.
- Newer framework features are used where they meaningfully improve code quality and are supported by the installed version.
## Performance and optimization
- Hot paths are identified.
- No obvious over-fetching or over-rendering.
- Expensive work is not repeated without reason.
- Assets and bundles are handled sensibly.
## Dependency and configuration hygiene
- Dependencies match actual imports and usage.
- Dev and runtime dependencies are separated properly.
- Tooling configuration is coherent.
- The code follows the quality rules implied by the configuration files.
## Security and reliability
- Sensitive flows are validated.
- Auth and permission checks are consistent.
- Dangerous defaults are avoided.
- Error handling does not leak implementation details.
## Testing and verification
- Tests cover high-risk business flows.
- Assertions are meaningful.
- Cleanup and fixture behavior are reliable.
- Gaps in test coverage are identified honestly.
@@ -0,0 +1,26 @@
# Python Quality Matrix
## Configuration detection
- Read `pyproject.toml` first.
- Detect the configured Python version.
- Detect `mypy`, `ty`, `ruff`, `deptry`, `pytest`, and formatter configuration.
## Review rules
- If `mypy` is configured, check the actual options before judging missing annotations or strictness violations.
- If `ty` is configured, use its configured expectations and error model.
- If both exist, respect whichever toolchain the project clearly treats as authoritative, and flag inconsistent duplication.
- If `ruff` is configured, review for meaningful rule violations, not cosmetic churn.
- If `deptry` is configured, verify dependency placement, unused dependencies, and hidden transitive reliance.
## Modern Python usage
- Use modern typing syntax only when the configured Python version supports it.
- Prefer `typing.Self`, `typing.TypeAliasType`, `typing.override`, `collections.abc` imports, `match`, `enum.StrEnum`, dataclass slots, and other newer features only when they improve clarity and compatibility.
- Do not suggest a newer language feature that the configured interpreter cannot run.
## Common harsh checks
- Weak or missing type boundaries.
- Hidden `Any` spread.
- Async misuse.
- Leaky ORM or transport models.
- Overly dynamic code that defeats static analysis.
- Wrong dependency classification.
@@ -0,0 +1,28 @@
# React Review Matrix
## Configuration detection
- Read `package.json`, `tsconfig.json`, ESLint config, framework config, and build setup.
- Detect React version, Next.js version, TypeScript version, and testing setup.
## Readability rules
- Components should be easy to scan.
- Props should be explicit and well named.
- Business logic should not be buried in JSX noise.
- Avoid deeply nested conditional rendering when a clearer structure would help.
- Prefer predictable state flow over clever abstractions.
## Modern React usage
- Use modern React and framework features only when the installed version supports them and they improve maintainability.
- Check whether newer APIs such as `useEffectEvent`, transitions, server components, or framework-native data loading would simplify the code.
- Do not insist on `useMemo` or `useCallback` unless they are justified.
- Avoid stale patterns if the installed version provides a clearer and safer replacement.
## Harsh review checks
- Unclear ownership of state.
- Effect misuse.
- Derived state bugs.
- Excessive prop drilling when a better structure exists.
- Over-componentization that hurts readability.
- Poor separation between UI, data, and business rules.
- Missing loading, empty, and error states.
- Avoidable render churn and unstable object creation in hot paths.
@@ -0,0 +1,24 @@
# Severity Rubric
## Critical
- Likely to cause broken behavior, data loss, security issues, or severe production instability.
- Major architecture flaw affecting core flows.
## High
- Strong risk of bugs, regressions, maintainability collapse, or significant performance issues.
- Serious mismatch with configured quality rules.
## Medium
- Clear quality issue or missed optimization that should be fixed, but not an immediate release blocker.
## Low
- Smaller maintainability issues, cleanup, or polish items.
## Finding format
- Severity
- Area
- Location
- Problem
- Why it matters
- Recommended fix
- Confidence or assumptions when relevant
@@ -0,0 +1,57 @@
---
name: ecommerce-seo-implementation
description: 'Implement SEO directly in an ecommerce codebase. Use for applying .ai/SEO-PLAN.md in code: metadata, schema markup, canonicals, sitemap, robots, internal linking, page templates, and crawl or index rules.'
argument-hint: 'Describe whether to apply the full SEO plan or only specific SEO areas such as metadata, schema, category SEO, or technical SEO'
---
# Ecommerce SEO Implementation
## When to use
- Applying an existing .ai/SEO-PLAN.md to a real ecommerce codebase.
- Implementing SEO directly in frontend, backend, routing, templates, schema, metadata, and technical platform behavior.
- Converting SEO recommendations into production-ready code and content structure.
## Goal
- Execute SEO changes in code, not just describe them.
- Use .ai/SEO-PLAN.md as the source of truth when it exists.
- If .ai/SEO-PLAN.md is missing, derive the minimum required context from .ai/STORE-BRIEF.md or ask to prepare the SEO strategy first.
## Preconditions
- Prefer having .ai/SEO-PLAN.md.
- If .ai/SEO-PLAN.md is absent but the user explicitly wants implementation now, create a compact implementation assumption set from .ai/STORE-BRIEF.md and state the risk.
## Required workflow
1. Read .ai/SEO-PLAN.md first when it exists.
2. Read .ai/STORE-BRIEF.md and AGENTS.md if they exist to align implementation with the product scope and repo rules.
3. Before serious backend or frontend edits, create a timestamped snapshot under .backup/ and keep that folder append-only.
4. Audit the current codebase against [implementation checklist](./assets/implementation-checklist.md).
5. Map required changes by page type using [page type SEO matrix](./assets/page-type-seo-matrix.md).
6. Implement technical SEO behavior using [technical execution map](./assets/technical-execution-map.md).
7. Apply metadata, canonicals, robots policy, sitemap generation, schema markup, internal linking, and template-level SEO content where appropriate.
8. Validate that SEO changes do not create index bloat, duplicate pages, or structured data inconsistencies.
9. Report what was implemented, what remains manual, and what should be measured after deployment.
## What this skill should implement
- Metadata systems for homepage, category, collection, brand, product, article, and utility pages.
- Canonical and noindex rules for filters, sort states, pagination, search results, cart, account, and utility routes.
- XML sitemap generation and robots policy.
- Structured data for organization, website, breadcrumbs, item lists, products, articles, FAQs, and local business when applicable.
- Breadcrumbs and internal linking modules.
- Category and product template support for SEO copy, FAQs, and content blocks when the architecture allows it.
- Image SEO basics: alt text support, responsive image behavior, and index-safe media handling.
- Performance-sensitive SEO work where it is practical within the current codebase.
## Constraints
- Do not generate spammy or keyword-stuffed copy.
- Do not index low-value filter combinations by default.
- Do not implement fake ratings, fake reviews, or misleading schema.
- Do not add SEO code that conflicts with the project routing or rendering model.
## Outputs
- Implemented code changes in the project.
- Optional update to .ai/SEO-PLAN.md when implementation assumptions change.
- Clear summary of completed SEO work, remaining gaps, and validation steps.
## References
- [implementation checklist](./assets/implementation-checklist.md)
- [page type SEO matrix](./assets/page-type-seo-matrix.md)
- [technical execution map](./assets/technical-execution-map.md)
@@ -0,0 +1,20 @@
# SEO Implementation Checklist
Before changing code, confirm the current project has or needs:
- Metadata generation by page type.
- Canonical tags and noindex controls.
- XML sitemap generation.
- robots.txt policy.
- Open Graph and social metadata.
- Structured data by page type.
- Breadcrumb markup and UI breadcrumbs.
- Internal linking modules.
- Category intro content or SEO content blocks.
- Product content sections such as FAQs, specs, care, compatibility, or shipping info.
- Search result and filter route indexation rules.
- Pagination or infinite-scroll SEO handling.
- Image component support for alt text, size hints, and optimized delivery.
- Performance-sensitive rendering for money pages.
If any item is missing, decide whether to implement it now, defer it, or document it as blocked by architecture.
@@ -0,0 +1,31 @@
# Page Type SEO Matrix
## Homepage
- Brand-level title and description.
- Organization and WebSite schema.
- Clear links to priority categories and collections.
## Category and collection pages
- Unique title, meta description, H1, and intro copy strategy.
- Breadcrumbs.
- ItemList schema when appropriate.
- Canonical rules for filters and sort states.
- Internal links to related categories and featured products.
## Brand pages
- Brand-specific copy and linked collections.
- Canonical protection against overlap with categories or collections.
## Product pages
- Product schema with real offer data.
- Rich metadata with variant-aware handling.
- FAQ or support content blocks when relevant.
- Internal links to related products and parent categories.
## Editorial or guide pages
- Article schema when relevant.
- Strong internal links into commercial pages.
- Intent-aligned headings and content sections.
## Utility pages
- Cart, account, checkout, login, internal search, and thin utilities should usually be noindex.
@@ -0,0 +1,29 @@
# Technical Execution Map
## Metadata layer
- Define where titles, descriptions, canonicals, Open Graph, and robots directives are generated.
- Prefer centralized page-type SEO configuration over scattered hardcoded tags.
## Routing and index control
- Ensure low-value routes can emit noindex or canonical rules.
- Align filtered routes, sorted routes, search routes, and pagination with the SEO policy.
## Structured data layer
- Use JSON-LD generated from real page data.
- Keep schema close to the page data source to reduce drift.
## Sitemap and robots
- Generate sitemaps only for valuable indexable URLs.
- Exclude duplicates, noindex pages, and thin utility pages.
## Internal linking systems
- Breadcrumbs, related content blocks, category cross-links, product recommendations, and editorial links should be intentional and reusable.
## Performance-sensitive work
- Protect LCP, INP, and CLS while adding SEO features.
- Avoid heavy client-only SEO logic for key landing pages.
## Validation
- Check for duplicate titles or duplicate canonicals.
- Check that schema matches visible content.
- Check that robots and sitemap policy are coherent.
@@ -0,0 +1,56 @@
---
name: ecommerce-seo-review
description: 'Review implemented ecommerce SEO and produce a structured findings report. Use for auditing metadata, schema, canonicals, sitemaps, robots rules, internal linking, indexation, Core Web Vitals risks, and content-template SEO after changes are shipped.'
argument-hint: 'Describe whether to review the whole site or specific page types such as categories, products, metadata, or technical SEO'
---
# Ecommerce SEO Review
## When to use
- After applying SEO changes in code.
- After launching a new ecommerce site or a major SEO release.
- When you need a structured list of SEO gaps, risks, regressions, and missed opportunities.
## Goal
- Audit the current project state against .ai/SEO-PLAN.md, .ai/STORE-BRIEF.md, and the live codebase.
- Produce .ai/SEO-REVIEW.md with prioritized findings, risks, and next actions.
- Focus on practical issues that affect crawling, indexation, relevance, page quality, internal linking, and performance.
## Preconditions
- Prefer having .ai/SEO-PLAN.md when the project has already gone through the SEO strategy step.
- If .ai/SEO-PLAN.md is missing, review the current site from code and documented assumptions instead of blocking.
## Required workflow
1. Read .ai/SEO-PLAN.md first when it exists.
2. Read .ai/STORE-BRIEF.md and AGENTS.md if they exist.
3. Audit the codebase against [SEO review checklist](./assets/seo-review-checklist.md).
4. Score issues using [severity rubric](./assets/severity-rubric.md).
5. Write or update .ai/SEO-REVIEW.md using [SEO review template](./assets/seo-review-template.md).
6. Group findings into critical, high, medium, and low priority.
7. Separate confirmed issues from assumptions or areas that require runtime validation.
8. End with a remediation plan ordered by business impact and engineering cost.
## Review coverage
- Metadata systems and missing or duplicate titles and descriptions.
- Canonical logic, noindex logic, and index-bloat risks.
- Sitemap and robots policy.
- Schema markup accuracy and visible-content alignment.
- Category, product, brand, collection, and editorial template SEO.
- Internal linking and breadcrumbs.
- Search, filter, sort, pagination, cart, account, and utility route handling.
- Performance and Core Web Vitals risks visible from the codebase.
- Content depth and thin-page risks where they are inferable from templates and data flow.
## Constraints
- Do not claim runtime behavior that cannot be confirmed from code.
- Clearly mark assumptions, unknowns, and items that need browser or production validation.
- Prefer actionable findings over generic SEO advice.
## Outputs
- .ai/SEO-REVIEW.md.
- A prioritized findings list.
- A short remediation plan with quick wins and structural fixes.
## References
- [SEO review checklist](./assets/seo-review-checklist.md)
- [severity rubric](./assets/severity-rubric.md)
- [SEO review template](./assets/seo-review-template.md)
@@ -0,0 +1,40 @@
# SEO Review Checklist
## Metadata
- Titles are unique on strategic page types.
- Meta descriptions are present where useful and not duplicated at scale.
- Open Graph and social metadata are present for key public pages.
## Crawl and indexation
- Canonicals exist where duplication risk is real.
- Noindex is applied to low-value routes such as cart, account, internal search, and thin utility pages when appropriate.
- Filter, sort, and pagination behavior aligns with the SEO plan.
- Sitemap generation excludes noindex and low-value URLs.
- robots.txt does not accidentally block important content.
## Structured data
- JSON-LD exists where intended.
- Schema matches visible content.
- Product, offer, breadcrumb, article, FAQ, and organization schema are used correctly.
- There are no fake reviews, misleading offers, or invalid structured data assumptions.
## Page templates
- Category and collection templates support unique SEO fields and meaningful content.
- Product templates support strong metadata, support content, and structured data.
- Brand and editorial pages have distinct intent and do not cannibalize key landing pages.
## Internal linking
- Breadcrumbs exist where expected.
- Important categories are linked from strong pages.
- Product and editorial pages support relevant internal links.
- Strategic landing pages are not orphaned.
## Performance-sensitive SEO
- Key pages are not overloaded with client-only SEO logic.
- There are obvious protections against large layout shifts and heavy above-the-fold payloads.
- Media and fonts do not create avoidable search-quality regressions.
## Unknowns to flag
- Runtime rendering behavior.
- Search Console or analytics data not visible in code.
- Production-only redirects, robots headers, CDN behavior, and sitemap deployment details.
@@ -0,0 +1,53 @@
# SEO-REVIEW.md Template
## 1. Review Scope
- Reviewed area
- Inputs used: .ai/SEO-PLAN.md, .ai/STORE-BRIEF.md, AGENTS.md, codebase files
- Limits of the review
## 2. Executive Summary
- Overall SEO implementation quality
- Biggest risks
- Biggest missed opportunities
## 3. Findings
### Critical
- List critical findings
### High
- List high-priority findings
### Medium
- List medium-priority findings
### Low
- List low-priority findings
## 4. Page-Type Notes
- Homepage
- Categories and collections
- Product pages
- Brand pages
- Editorial or support pages
- Utility pages
## 5. Technical SEO Notes
- Metadata system
- Canonicals and noindex
- Sitemap and robots
- Structured data
- Internal linking
- Performance-sensitive SEO
## 6. Unknowns and Runtime Validation
- Items that require browser validation
- Items that require production or Search Console data
## 7. Remediation Plan
- Quick wins
- Medium lifts
- Structural fixes
## 8. Suggested Next Validation Steps
- What to test after fixes are applied
@@ -0,0 +1,26 @@
# Severity Rubric
## Critical
- Likely to block crawling or indexation of important commercial pages.
- Likely to create large-scale duplicate or canonical errors.
- Likely to break structured data trust on strategic templates.
## High
- Likely to materially reduce rankings, CTR, or discoverability on important page groups.
- Affects high-value categories, product templates, or core internal-link systems.
## Medium
- Noticeable quality gap or missed opportunity, but not a severe blocker.
- Often template-level improvements, partial metadata gaps, or incomplete linking coverage.
## Low
- Nice-to-have improvements, polish items, or issues with limited SEO impact.
## Finding format
- Severity
- Area
- Affected page type or module
- What is wrong
- Why it matters
- Recommended fix
- Validation note if runtime confirmation is still needed
@@ -0,0 +1,53 @@
---
name: ecommerce-seo-strategy
description: 'Plan and improve ecommerce SEO across technical SEO, information architecture, category strategy, product pages, schema markup, metadata, internal linking, Core Web Vitals, and measurement. Use for SEO audits, SEO planning, and organic growth work on online stores.'
argument-hint: 'Describe the store, market, target pages, and whether this is a new build or an existing site'
---
# Ecommerce SEO Strategy
## When to use
- Planning SEO for a new ecommerce site before build.
- Auditing an existing storefront that needs stronger organic visibility.
- Defining technical SEO, content architecture, schema, metadata, and internal linking.
- Improving category, product, brand, collection, blog, and help content for search intent.
## Goal
- Maximize sustainable organic visibility for the site.
- Produce implementation-ready SEO decisions instead of vague advice.
- Create or update .ai/SEO-PLAN.md when the task is substantial.
## Important constraint
- Do not promise a number one ranking. Search performance depends on competition, domain authority, backlinks, history, and market conditions.
- Optimize for the strongest possible technical and content foundation, measurable growth, and durable search coverage.
## Required workflow
1. Read .ai/STORE-BRIEF.md if it exists. If not, gather enough business and market context from the user or repository.
2. Determine the market, audience, geography, revenue model, and search intent mix.
3. Build a keyword and intent map using [keyword intent framework](./assets/keyword-intent-framework.md).
4. Define search landing pages and information architecture for home, categories, subcategories, collections, brands, products, guides, FAQs, and support content.
5. Review or propose technical SEO using [technical SEO checklist](./assets/technical-seo-checklist.md).
6. Review or propose structured data using [schema markup map](./assets/schema-markup-map.md).
7. Review or propose internal linking using [internal linking playbook](./assets/internal-linking-playbook.md).
8. Define measurement using [SEO measurement framework](./assets/seo-measurement-framework.md).
9. Create or update .ai/SEO-PLAN.md using [SEO plan template](./assets/seo-plan-template.md) when the work is broad enough.
10. Prioritize recommendations into quick wins, medium lifts, and structural work.
## Coverage expectations
- Technical SEO: crawlability, indexability, canonicals, noindex strategy, redirects, sitemaps, robots, rendering, structured data, image SEO, faceted navigation, pagination behavior, hreflang when needed, page speed and Core Web Vitals.
- Commercial SEO: category taxonomy, filter landing page policy, product detail optimization, collection and brand pages, price and availability signals, review strategy, seasonal and campaign landing pages.
- Content SEO: metadata, headings, copy structure, FAQs, guides, comparison pages, supporting content clusters, entity coverage, and user intent alignment.
- UX signals that affect SEO: mobile-first layouts, performance, layout stability, media optimization, readable content hierarchy, and clean navigation.
- Measurement: rankings are not enough; include index coverage, impressions, CTR, non-brand traffic, landing page performance, conversions, and page group health.
## Outputs
- .ai/SEO-PLAN.md for broad SEO work.
- Specific code or content implementation tasks when the user wants execution.
- Clear prioritization by business impact and engineering cost.
## References
- [SEO plan template](./assets/seo-plan-template.md)
- [keyword intent framework](./assets/keyword-intent-framework.md)
- [technical SEO checklist](./assets/technical-seo-checklist.md)
- [schema markup map](./assets/schema-markup-map.md)
- [internal linking playbook](./assets/internal-linking-playbook.md)
- [SEO measurement framework](./assets/seo-measurement-framework.md)
@@ -0,0 +1,18 @@
# Internal Linking Playbook
## Core principles
- Link from high-authority pages to priority commercial pages.
- Use consistent anchor language tied to real user phrasing.
- Keep internal links helpful for users, not mechanically stuffed.
## Required link systems
- Global navigation to top categories and collections.
- Breadcrumbs on category, collection, brand, and product pages.
- Related products and related categories modules.
- Editorial links from guides, FAQs, and comparison content to money pages.
- Cross-links between complementary categories when intent overlaps.
## Priority rules
- Important categories should be reachable in few clicks.
- New seasonal or campaign pages need fast internal linking support.
- Orphan pages are not acceptable for strategic landing pages.
@@ -0,0 +1,27 @@
# Keyword Intent Framework
## Intent buckets
- Transactional: buy-now, price, delivery, in-stock, order intent.
- Commercial investigation: best, compare, review, top, versus, alternatives.
- Informational: how to choose, how to use, care guides, ingredient guides, compatibility guides.
- Navigational and brand: brand, collection, store name, product line, branded queries.
## Mapping rules
- Homepage should target broad category and brand-level demand, not all keywords.
- Category and subcategory pages should target the highest-volume commercial and transactional themes.
- Product pages should target explicit product, variant, model, SKU, brand, and long-tail modifiers.
- Guide and FAQ pages should support commercial pages and capture informational demand.
## Output fields
- Keyword theme
- Primary intent
- Suggested landing page type
- Funnel stage
- Priority
- Required content blocks
- Internal link targets
## Ecommerce caution points
- Do not create indexable pages for every low-value filter combination.
- Avoid cannibalization between category pages, collection pages, and blog content.
- Prefer strong category and brand hubs over thin near-duplicate pages.
@@ -0,0 +1,19 @@
# Schema Markup Map
## By page type
- Homepage: Organization, WebSite, SearchAction when appropriate.
- Category or collection pages: ItemList and BreadcrumbList when the page meaningfully lists products.
- Product pages: Product, Offer, AggregateRating, Review when the data is real and visible.
- FAQ sections: FAQPage only when the content is actually presented to users.
- Editorial pages: Article or BlogPosting where appropriate.
- Store or contact pages: LocalBusiness when location data exists and is accurate.
## Requirements
- Only mark up data that is visible and truthful.
- Keep price, availability, brand, SKU, and rating data synchronized with visible content.
- Validate JSON-LD output after implementation.
## Ecommerce cautions
- Do not fabricate ratings or reviews.
- Do not mark every accordion as FAQPage unless it truly qualifies.
- Keep structured data aligned with canonical URLs and page intent.
@@ -0,0 +1,25 @@
# SEO Measurement Framework
## Primary KPIs
- Non-brand clicks and impressions.
- Organic sessions by landing page group.
- Organic conversion rate.
- Revenue or lead value from organic traffic.
- Indexed page quality by page type.
## Secondary KPIs
- CTR on major page templates.
- Average position for priority keyword groups.
- Core Web Vitals on category and product pages.
- Share of traffic landing on strategic commercial pages versus weak informational pages.
## Monitoring dimensions
- By page type: homepage, category, collection, brand, product, content, help.
- By market or locale.
- By device.
- By branded versus non-branded traffic.
## Reporting approach
- Separate quick wins from structural improvements.
- Measure before and after major releases.
- Track technical fixes, content launches, and internal linking changes as distinct interventions.
@@ -0,0 +1,84 @@
# SEO-PLAN.md Template
## 1. Business Context
- Site or brand name
- Market and geography
- Audience segments
- Revenue model and priority categories
## 2. SEO Objectives
- Primary growth goals
- Non-brand traffic goals
- Conversion goals from organic traffic
- Constraints and dependencies
## 3. Search Intent Model
- Transactional intents
- Commercial investigation intents
- Informational intents
- Brand and navigational intents
## 4. Keyword and Page Mapping
- Homepage target themes
- Category pages
- Subcategory or collection pages
- Brand pages
- Product pages
- Editorial or guide pages
- FAQ and support pages
## 5. Information Architecture
- Planned taxonomy
- URL rules
- Faceted navigation policy
- Canonicalization rules
- Pagination or infinite scroll handling
## 6. On-Page SEO Requirements
- Title patterns
- Meta description patterns
- Heading rules
- Intro copy rules for category pages
- Product page content blocks
- FAQ and support content rules
## 7. Structured Data Plan
- Required schema types by page type
- Required properties
- Validation notes
## 8. Technical SEO Plan
- Indexing and crawl rules
- Robots and sitemaps
- Redirect policy
- Performance and Core Web Vitals goals
- Image optimization rules
- Renderability and JavaScript considerations
## 9. Internal Linking Strategy
- Global navigation
- Breadcrumbs
- Related products
- Category cross-links
- Editorial to commercial links
## 10. Content Expansion Plan
- High-priority landing pages
- Cluster content ideas
- Seasonal and campaign opportunities
## 11. Measurement and Reporting
- KPIs
- Dashboard inputs
- Search Console tracking
- Analytics events or goals
## 12. Priority Roadmap
- Quick wins
- Medium lifts
- Structural work
## 13. Risks and Assumptions
- Market competition risks
- Platform constraints
- Content or asset gaps
@@ -0,0 +1,32 @@
# Technical SEO Checklist
## Crawl and indexation
- Confirm indexable money pages and noindex low-value or duplicate pages.
- Define robots policy for search, cart, account, internal filters, and thin utility pages.
- Ensure XML sitemaps exist for key page groups and exclude noindex URLs.
## Canonicalization and duplication
- Define canonicals for categories, filtered states, sorting states, pagination, and product variants.
- Prevent duplicate content across collection pages, brand pages, and promotional landings.
## Rendering and architecture
- Ensure key content is available in server-rendered or reliably rendered HTML.
- Confirm crawlers can see titles, headings, main content, structured data, and internal links.
## Performance and Core Web Vitals
- Optimize LCP, INP, and CLS on category and product pages.
- Control image size, font loading, script weight, and third-party bloat.
- Avoid layout shifts from banners, lazy media, and client-only widgets.
## Media and assets
- Use descriptive image filenames where practical.
- Provide alt text with functional accuracy, not keyword stuffing.
- Generate responsive image variants and preload only what is truly critical.
## Navigation and page discovery
- Ensure deep categories and products are reachable through internal links.
- Use breadcrumbs and clear taxonomy-based navigation.
## International and local SEO when relevant
- Use hreflang carefully only when multiple locales truly exist.
- Align locale routing, canonicals, translated metadata, and sitemap structure.
@@ -0,0 +1,28 @@
---
name: ecommerce-store-evolution
description: 'Extend or refactor an existing ecommerce project with FastAPI, React, Next.js, admin panel, catalog changes, AGENTS.md updates, and safer rollout planning.'
argument-hint: 'Describe the current project and the features or refactor you need'
---
# Ecommerce Store Evolution
## When to use
- Extending an existing online store.
- Adding a new admin module, catalog flow, account area, or backend capability.
- Refactoring a commerce codebase without losing its current conventions.
## Procedure
1. Audit the existing repo and compare it with [extension checklist](./assets/extension-checklist.md).
2. Create or update AGENTS.md if the repo lacks clear delivery rules.
3. Before serious backend or frontend edits, create a timestamped snapshot under .backup/ and never modify or delete older backup entries.
4. Preserve stable patterns and change only what is necessary.
5. Write a small implementation plan using [rollout plan template](./assets/rollout-plan-template.md).
6. Implement backend and frontend changes with regression awareness.
## Architecture rule
- New backend code should go into the proper layers such as routers, models, schemas, services, repositories, config, and tests.
- New frontend code should go into the proper layers such as app or routes, pages, features, entities, shared components, api or services, hooks, config, styles, and tests.
- If the current project is too flat or mixed, improve the structure incrementally instead of adding more chaos.
## References
- [extension checklist](./assets/extension-checklist.md)
- [rollout plan template](./assets/rollout-plan-template.md)
@@ -0,0 +1,10 @@
# Extension Checklist
- What already exists in the storefront.
- What already exists in the admin panel or back office.
- Current auth model and role system.
- Current cart behavior and checkout assumptions.
- Current backend modules, migrations, and API style.
- Current design system or UI conventions.
- Which parts can be extended safely versus which parts need refactoring.
- Which gaps must be documented in AGENTS.md.
@@ -0,0 +1,18 @@
# Rollout Plan Template
## Goal
- What business or UX capability is being added or changed.
## Existing constraints
- Current architecture limits.
- Current data contract limits.
## Change plan
- Backend changes.
- Frontend storefront changes.
- Admin or back office changes.
- Migration or seed changes.
## Verification
- Manual flows to verify.
- High-risk regressions to watch.
@@ -0,0 +1,26 @@
---
name: ecommerce-store-foundation
description: 'Create a new ecommerce project with FastAPI, React, Next.js, PostgreSQL, storefront, admin panel, back office, and AGENTS.md. Use for greenfield online stores in monorepos or split repos.'
argument-hint: 'Describe the store, repo mode, design direction, and must-have features'
---
# Ecommerce Store Foundation
## When to use
- Building a new online store from scratch.
- Scaffolding a new FastAPI and React commerce stack.
- Setting up storefront plus admin panel or back office.
- Creating AGENTS.md before implementation.
## Procedure
1. Run the discovery questions from [discovery checklist](./assets/discovery-checklist.md).
2. Decide whether the target is a monorepo or split repos.
3. Create AGENTS.md first using the matching template.
4. Define entities, flows, roles, and integrations.
5. Scaffold backend, then storefront, then admin.
6. Finish with responsive polish, motion, content plan, and image prompt support.
## Templates
- Monorepo: [monorepo AGENTS template](./assets/monorepo-agents-template.md)
- Split frontend repo: [split frontend AGENTS template](./assets/split-frontend-agents-template.md)
- Split backend repo: [split backend AGENTS template](./assets/split-backend-agents-template.md)
- Image prompts: [image prompt template](./assets/image-prompt-template.md)
@@ -0,0 +1,12 @@
# Discovery Checklist
- What does the store sell and in which market.
- Is the delivery mode monorepo or split repos.
- Does the storefront need customer accounts, guest checkout, or both.
- Should anonymous carts live in localStorage, cookies, or server state.
- Which admin roles are required.
- Which catalog entities exist: categories, brands, attributes, variants, collections, bundles.
- Which business flows matter: promos, delivery, pickup, preorder, lead capture, or full checkout.
- Which external services are needed: payment, CRM, ERP, email, analytics, search, storage.
- Which visual direction fits the brand and audience.
- Which content and images already exist and which must be generated.
@@ -0,0 +1,17 @@
# Image Prompt Template
Use this template when the project needs visuals but the final assets do not exist yet.
Prompt structure:
- Brand and market context
- Exact subject
- Composition and camera distance
- Aspect ratio and framing
- Background and props
- Lighting and mood
- Material, texture, and styling details
- Output quality cues
- Negative constraints
Example skeleton:
Create a premium ecommerce hero image for a {brand type} store selling {product type}. Show {subject} in a {composition} composition, shot for a {aspect ratio} canvas. Use a {background style} background with {lighting style} lighting. Visual tone: {keywords}. Include room for headline text. Avoid watermarks, distorted hands, broken anatomy, cluttered backgrounds, oversaturated colors, and unreadable product details.
@@ -0,0 +1,30 @@
# AGENTS.md Template For Monorepo
## Product scope
- Store type and target audience.
- Required storefront pages and business flows.
- Required admin or back office flows.
## Repository structure
- Root folders, package manager, environments, and local run commands.
- Frontend and backend ownership boundaries.
- Shared schema or contract locations.
## Backend rules
- FastAPI service boundaries.
- Database stack, migrations, auth, and role model.
- API naming and validation conventions.
## Frontend rules
- React framework choice.
- Routing, layout structure, UI architecture, and data fetching strategy.
- Responsive, accessibility, and animation expectations.
## Admin rules
- Admin modules, roles, dashboards, audit-sensitive actions, and content workflows.
## Assets and content
- Source asset folders, placeholder strategy, and external image prompt workflow.
## Delivery rules
- Definition of done, testing expectations, and how to handle missing requirements.
@@ -0,0 +1,20 @@
# AGENTS.md Template For Split Backend Repo
## Repo role
- This repo owns FastAPI services, database models, auth, admin APIs, and integrations.
- It serves the storefront and admin frontend repo through explicit contracts.
## Backend scope
- Catalog, taxonomy, auth, customers, carts, orders, content, settings, and admin operations.
- Migrations, background jobs, storage, and integration boundaries.
## Contract rules
- Keep OpenAPI and schema naming stable.
- Document any breaking change for the frontend repo before implementation.
## Security and roles
- Separate customer and staff permissions.
- Apply RBAC for admin operations.
## Delivery rules
- Maintain migration safety and predictable local development.
@@ -0,0 +1,20 @@
# AGENTS.md Template For Split Frontend Repo
## Repo role
- This repo owns the storefront and admin UI surface.
- It consumes backend contracts from the paired backend repo.
## Frontend scope
- Storefront routes, account routes when needed, and admin routes or admin app.
- Design system, responsive rules, motion rules, and accessibility baseline.
## Data contract rules
- Do not invent backend fields without documenting the contract.
- Keep request and response assumptions aligned with the backend repo.
## Asset workflow
- Define source imagery, placeholder policy, and external generation prompt policy.
## Delivery rules
- Keep mobile storefront quality high.
- Keep admin workflows efficient and reliable.
@@ -0,0 +1,47 @@
---
name: ecommerce-test-implementation
description: 'Write automated tests for backend and frontend, then run them. Use for creating or extending pytest, frontend unit, integration, and UI tests in an ecommerce project and producing a test execution report.'
argument-hint: 'Describe whether to cover the whole project or focus on backend, frontend, checkout, auth, catalog, admin, or other flows'
---
# Ecommerce Test Implementation
## When to use
- After building a new ecommerce project.
- After adding or changing backend or frontend features.
- When the project lacks automated tests for important commerce flows.
## Goal
- Add meaningful automated tests for backend and frontend.
- Run the relevant test suites.
- Produce or update .ai/TEST-REPORT.md with coverage notes, executed commands, and failures.
## Required workflow
1. Read project configuration first: `pyproject.toml`, `package.json`, and existing test config files.
2. Detect the current test stack using [test stack matrix](./assets/test-stack-matrix.md).
3. Identify the highest-risk flows using [test coverage checklist](./assets/test-coverage-checklist.md).
4. Before serious backend or frontend edits, create a timestamped snapshot under .backup/ and leave older backup entries untouched.
5. Add or update tests in the project's existing style where possible.
6. If the project has no coherent test baseline, create a minimal sensible baseline rather than skipping tests.
7. Run the relevant backend and frontend tests.
8. Record results in .ai/TEST-REPORT.md using [test report template](./assets/test-report-template.md).
9. If tests fail, stop pretending everything is fine and recommend running the test-repair workflow.
## What to cover by default
- Backend: API contracts, auth, permissions, catalog, cart, orders, admin endpoints, validation, and regression-prone business logic.
- Frontend: page rendering, key user flows, empty/loading/error states, and critical UI interactions.
- If the project already has UI or end-to-end tooling, cover the most important high-value flows with it.
## Constraints
- Do not add shallow tests that only restate implementation with no confidence gain.
- Prefer high-signal tests over bloated low-value suites.
- Respect the existing framework and test runner unless it is clearly absent or broken.
## Outputs
- Test code in the project.
- .ai/TEST-REPORT.md.
- Clear next step when failures exist: run the test-repair workflow.
## References
- [test stack matrix](./assets/test-stack-matrix.md)
- [test coverage checklist](./assets/test-coverage-checklist.md)
- [test report template](./assets/test-report-template.md)
@@ -0,0 +1,27 @@
# Test Coverage Checklist
## Backend
- Auth and permission rules.
- Catalog reads and writes.
- Cart behavior.
- Order creation and lifecycle.
- Admin operations.
- Input validation and error responses.
- Critical business logic and edge cases.
## Frontend
- Key page rendering.
- Empty, loading, and error states.
- User interactions for catalog, cart, checkout, auth, and account.
- Admin UI interactions when the repo contains admin code.
## High-priority ecommerce flows
- Add to cart.
- Quantity updates and cart totals.
- Checkout or lead flow.
- Login and protected routes.
- Admin create or edit flows.
## Review quality
- Assertions should verify behavior, not just implementation details.
- Avoid fragile snapshot-heavy suites unless they truly add confidence.
@@ -0,0 +1,24 @@
# TEST-REPORT.md Template
## 1. Scope
- Areas covered
- Test frameworks used
- Commands executed
## 2. Added or Updated Tests
- Backend tests
- Frontend tests
- UI or end-to-end tests if any
## 3. Execution Results
- Passing suites
- Failing suites
- Skipped or unrun suites
## 4. Gaps
- Areas still missing coverage
- Risky flows still not tested
## 5. Next Step
- If failures exist, run the test-repair workflow.
- If green, note whether more coverage is still recommended.
@@ -0,0 +1,20 @@
# Test Stack Matrix
## Backend
- Prefer the existing Python test runner and fixtures setup.
- If the project is FastAPI and already uses `pytest`, extend `pytest` rather than introducing another runner.
- Respect async testing patterns already present in the project.
## Frontend
- Prefer the existing frontend test stack from `package.json`.
- Typical unit and integration options: Vitest or Jest with Testing Library.
- Typical UI or end-to-end options: Playwright when the project already uses it or clearly benefits from it.
## If the project has no test stack
- Backend default: `pytest`.
- Frontend default for React and Next.js component testing: Vitest plus Testing Library when compatible with the project.
- End-to-end tests should be added only if they materially improve coverage and the project can support them.
## Execution principle
- Run only the relevant suites for the change set when that is enough.
- If the task is broad, run both backend and frontend suites or document what was not run.
@@ -0,0 +1,41 @@
---
name: ecommerce-test-repair
description: 'Fix failing backend and frontend tests, then rerun them. Use for investigating test failures, repairing code or tests, and repeating the loop until suites pass or blockers are documented.'
argument-hint: 'Describe whether to fix all current failures or only backend or frontend test failures'
---
# Ecommerce Test Repair
## When to use
- After the test-implementation step finds failures.
- When backend or frontend automated tests are red.
- When regressions appear after refactors, SEO changes, or feature work.
## Goal
- Analyze failing tests honestly.
- Fix the underlying code or the tests, whichever is actually wrong.
- Rerun the affected suites.
- Produce or update .ai/TEST-REPAIR.md with failure analysis, fixes applied, rerun results, and remaining blockers.
## Required workflow
1. Read the latest .ai/TEST-REPORT.md if it exists.
2. Inspect actual failing output rather than guessing.
3. Before serious backend or frontend edits, create a timestamped snapshot under .backup/ and keep that folder append-only.
4. Classify failures using [failure triage checklist](./assets/failure-triage-checklist.md).
5. Fix root causes instead of patching symptoms when possible.
6. Rerun the affected tests.
7. Repeat until the suite is green or real blockers remain.
8. Write or update .ai/TEST-REPAIR.md using [test repair template](./assets/test-repair-template.md).
## Constraints
- Do not weaken tests just to make them pass.
- Do not rewrite assertions into meaninglessness.
- Do not ignore failing tests without documenting the blocker.
## Outputs
- Code or test fixes.
- Rerun results.
- .ai/TEST-REPAIR.md.
## References
- [failure triage checklist](./assets/failure-triage-checklist.md)
- [test repair template](./assets/test-repair-template.md)
@@ -0,0 +1,24 @@
# Failure Triage Checklist
## First classify the problem
- Real product bug.
- Broken or outdated test.
- Environment or fixture problem.
- Flaky timing or async issue.
- Wrong assumptions after a refactor.
## Backend-specific checks
- Contract mismatch.
- Validation error changes.
- Permissions or auth regression.
- Test data or fixture drift.
## Frontend-specific checks
- UI behavior changed intentionally or unintentionally.
- Query selectors too brittle.
- Async rendering not awaited correctly.
- Mock data drift.
## Repair rule
- Fix the real source of truth issue first.
- Only change tests when the implementation is correct and the test is outdated or wrong.
@@ -0,0 +1,28 @@
# TEST-REPAIR.md Template
## 1. Initial Failure State
- Failing suites
- Failing commands
- Main error categories
## 2. Root Cause Analysis
- Backend causes
- Frontend causes
- Environment causes if any
## 3. Fixes Applied
- Code fixes
- Test fixes
- Config or fixture fixes
## 4. Rerun Results
- Commands rerun
- Passing suites
- Remaining failures
## 5. Blockers
- Anything still preventing green status
## 6. Recommended Next Step
- Whether to continue fixing
- Whether to adjust architecture, fixtures, or test tooling
+100
View File
@@ -0,0 +1,100 @@
# Рекомендуемый стек MCP
Этот файл описывает рекомендуемый набор MCP для ecommerce-разработки на FastAPI + React или Next.js.
## Приоритет 1: добавить в первую очередь
### 1. Context7 или docs MCP
- Назначение: получать актуальную документацию и примеры по FastAPI, SQLAlchemy, Pydantic, Next.js, React, Playwright, pytest, Alembic и связанным инструментам.
- Почему это важно: снижает риск устаревших решений и помогает агенту ориентироваться на реальные версии библиотек.
- Лучше всего подходит для: архитектурных решений, работы с API библиотек, миграций, framework-specific паттернов и отладки незнакомых интеграций.
### 2. Playwright MCP
- Назначение: автоматизация браузера, проверка UI, скриншоты, инспекция DOM, диагностика консоли и e2e-валидация.
- Почему это важно: один из самых полезных MCP для storefront-флоу, checkout, auth, admin panel, фильтров и regression testing.
- Лучше всего подходит для: frontend-разработки, acceptance testing, визуальных проверок и воспроизведения browser-багов.
### 3. PostgreSQL MCP
- Назначение: смотреть схему, выполнять запросы, проверять миграции, валидировать данные и разбирать persistence-проблемы.
- Почему это важно: критически полезен для FastAPI backend в ecommerce, где есть каталог, заказы, пользователи, права и миграции.
- Лучше всего подходит для: backend-разработки, отладки данных, ревью миграций и ручной проверки business rules.
### 4. Docker или Compose MCP
- Назначение: управлять сервисами, смотреть логи, поднимать и останавливать стек, валидировать локальную containerized-среду.
- Почему это важно: особенно полезен, если backend, frontend, db, redis, search или storage запускаются через Compose.
- Лучше всего подходит для: локальной orchestration, просмотра логов сервисов, воспроизводимых сред и integration debugging.
### 5. GitLab MCP или GitHub MCP
- Назначение: работать с merge request или pull request, issues, CI pipelines, метаданными репозитория, review и automation context.
- Почему это важно: замыкает цикл между кодом, review и CI.
- Лучше всего подходит для: командной разработки, review cycle, issue-driven delivery и видимости пайплайнов.
- Рекомендация: если проект живет в GitLab, приоритет у GitLab MCP; иначе GitHub MCP.
## Приоритет 2: очень полезно для ecommerce-проектов
### 6. Redis MCP
- Назначение: смотреть cache, sessions, queues, rate limits, pubsub и временное состояние.
- Почему это важно: полезен, если корзины, сессии, async jobs, search cache или throttling используют Redis.
- Лучше всего подходит для: отладки cache invalidation, auth sessions, task queues и временного commerce-state.
### 7. S3 или MinIO MCP
- Назначение: смотреть buckets, uploads, media assets, exports и generated files.
- Почему это важно: в ecommerce почти всегда есть product images, баннеры, документы, import и export.
- Лучше всего подходит для: asset handling, media debugging и проверки storage workflows.
### 8. Browser или DevTools MCP
- Назначение: смотреть network, frontend console, performance, hydration issues, layout bugs и rendering diagnostics.
- Почему это важно: хорошо дополняет Playwright, когда нужен более низкоуровневый browser debugging.
- Лучше всего подходит для: performance, network failures, client exceptions и сложных rendering-проблем.
### 9. Sentry MCP
- Назначение: смотреть production errors, stack traces, release regressions и alert context.
- Почему это важно: особенно полезен после деплоя или на проекте, где уже есть реальные пользователи.
- Лучше всего подходит для: post-release debugging, bug triage и поиска реальных high-impact проблем.
## Приоритет 3: добавлять только по необходимости
### 10. OpenAPI или API testing MCP
- Назначение: валидировать REST-контракты, гонять API-сценарии, смотреть схемы и проверять integration flows.
- Почему это важно: полезен, если в проекте важна API-first валидация или команда опирается на contract testing.
- Лучше всего подходит для: backend QA, API verification, smoke tests и integration debugging.
### 11. Stripe MCP
- Назначение: смотреть оплаты, checkout sessions, webhooks, customers и billing flows.
- Почему это важно: нужен только если проект реально использует Stripe.
- Лучше всего подходит для: отладки платежей и проверки webhook flows.
### 12. Kubernetes MCP
- Назначение: смотреть workloads, логи, config, namespaces и deploy state.
- Почему это важно: полезен только если команда реально деплоит или дебажит через Kubernetes.
- Лучше всего подходит для: staging и production operations.
## Рекомендуемый базовый набор для этого стека
Если нужен сильный и практичный базовый набор, сначала стоит добавить:
1. Context7 или docs MCP
2. Playwright MCP
3. PostgreSQL MCP
4. Docker или Compose MCP
5. GitLab MCP или GitHub MCP
6. Redis MCP, если стек использует cache или queues
7. S3 или MinIO MCP, если стек использует media storage
## Правило выбора
- Добавляй те MCP, которые закрывают реальные пробелы в разработке, тестировании, отладке, review и эксплуатации.
- Не перегружай конфиг узкоспециализированными MCP, которые проекту не нужны.
- В приоритете инструменты, которые ускоряют цикл работы сразу по backend, frontend, тестам, CI и production debugging.
+364
View File
@@ -0,0 +1,364 @@
# shop-fullstack
Набор кастомизаций для GitHub Copilot в VS Code под ecommerce-проекты: FastAPI backend, React или Next.js frontend, storefront, admin panel, back office, PostgreSQL, mobile-first UX и двухшаговая подготовка через .ai/STORE-BRIEF.md перед генерацией кода.
## Что создано
В текущем репозитории:
- Агент: .github/agents/shop-fullstack-fastapi-react.agent.md
- Инструкции: .github/instructions/
- Промпты: .github/prompts/
- Skills: .github/skills/ecommerce-store-foundation, .github/skills/ecommerce-store-evolution, .github/skills/ecommerce-brief-preparation, .github/skills/ecommerce-build-from-brief, .github/skills/ecommerce-seo-strategy, .github/skills/ecommerce-seo-implementation, .github/skills/ecommerce-seo-review, .github/skills/ecommerce-code-review, .github/skills/ecommerce-test-implementation и .github/skills/ecommerce-test-repair
## Что умеет агент
- Создавать ecommerce-сайт с нуля.
- Дорабатывать существующий storefront, backend и admin panel.
- Работать в monorepo и split repo режиме.
- По умолчанию использовать FastAPI, PostgreSQL, React и Next.js.
- Сначала собирать нормализованный brief в .ai/STORE-BRIEF.md.
- После brief создавать или обновлять AGENTS.md.
- Для Python ориентироваться на конфигурацию pyproject и quality-toolchain проекта: mypy или ty, ruff, deptry.
- Для React держать код читаемым, предсказуемым и удобным для ручной доработки.
- Писать и прогонять автотесты для backend и frontend, а при падениях запускать отдельный fix-loop до зеленого статуса или явных blockers.
- Учитывать mobile-first адаптацию, анимации, категории, фильтры, сортировку, корзину, авторизацию, личный кабинет и back office.
- Подготавливать prompts для генерации изображений, если готовых ассетов нет.
## Рекомендуемый workflow
Основной сценарий теперь такой:
1. Сначала запустить подготовку brief.
2. Агент задает только важные вопросы.
3. Агент создает файл .ai/STORE-BRIEF.md.
4. После согласования brief запускается сборка сайта по .ai/STORE-BRIEF.md.
5. Перед кодом агент создает AGENTS.md, затем реализует backend, storefront и admin panel.
## Как использовать агента
### Вариант 1. Через выбор агента
1. Открой чат Copilot в VS Code.
2. Выбери агент shop-fullstack-fastapi-react.
3. Передай задачу в свободной форме и попроси сначала подготовить .ai/STORE-BRIEF.md.
Пример:
```text
Подготовь .ai/STORE-BRIEF.md для интернет-магазина косметики в monorepo. Backend на FastAPI и PostgreSQL, frontend на Next.js. Нужны storefront, admin panel, личный кабинет, фильтры, сортировка, корзина, анимации и адаптация под мобильные устройства. После brief я отдельно запущу сборку.
```
### Вариант 2. Через prompt-файлы
Доступны готовые сценарии:
- /Ecommerce Prepare Brief
- /Ecommerce Build From Brief
- /Ecommerce SEO Strategy
- /Ecommerce SEO Implementation
- /Ecommerce SEO Review
- /Ecommerce Code Review
- /Ecommerce Test Implementation
- /Ecommerce Test Repair
- /Ecommerce From Zero
- /Ecommerce Extend Existing
- /Ecommerce Visual Pack
Когда использовать основные новые сценарии:
- Ecommerce Prepare Brief: задает важные вопросы и создает .ai/STORE-BRIEF.md.
- Ecommerce Build From Brief: читает .ai/STORE-BRIEF.md, создает AGENTS.md и строит проект.
- Ecommerce SEO Strategy: создает .ai/SEO-PLAN.md или проводит SEO-аудит и формирует реализационный план.
- Ecommerce SEO Implementation: внедряет .ai/SEO-PLAN.md прямо в код проекта.
- Ecommerce SEO Review: проводит повторный SEO-аудит проекта и пишет .ai/SEO-REVIEW.md с приоритетами и планом исправлений.
- Ecommerce Code Review: делает жесткий code review всего проекта с учетом pyproject, package.json, версий языка и доступных современных возможностей.
- Ecommerce Test Implementation: пишет автотесты для backend и frontend, затем запускает их и пишет .ai/TEST-REPORT.md.
- Ecommerce Test Repair: разбирает падения тестов, чинит код или тесты, гоняет suite повторно и пишет .ai/TEST-REPAIR.md.
Когда использовать:
- Ecommerce From Zero: запуск нового магазина с нуля.
- Ecommerce Extend Existing: развитие уже существующего проекта.
- Ecommerce Visual Pack: подготовка визуального направления и prompts для генерации изображений.
### Вариант 3. Через skills
Skills подключаются автоматически по описанию задачи или через slash-команду, если VS Code их показывает.
- ecommerce-brief-preparation: превращает сырую идею в .ai/STORE-BRIEF.md.
- ecommerce-build-from-brief: строит проект по .ai/STORE-BRIEF.md.
- ecommerce-seo-strategy: готовит сильную SEO-стратегию, технический SEO-план, схему страниц, schema markup и измерение результата.
- ecommerce-seo-implementation: вносит SEO-изменения прямо в кодовую базу по .ai/SEO-PLAN.md.
- ecommerce-seo-review: проверяет фактическую SEO-реализацию и пишет .ai/SEO-REVIEW.md с findings и remediation plan.
- ecommerce-code-review: делает жесткий обзор качества Python, React, архитектуры, производительности и dependency hygiene с отчетом в .ai/CODE-REVIEW.md.
- ecommerce-test-implementation: добавляет backend и frontend автотесты, запускает их и фиксирует результат в .ai/TEST-REPORT.md.
- ecommerce-test-repair: чинит падения тестов и повторно прогоняет suite с отчетом в .ai/TEST-REPAIR.md.
- ecommerce-store-foundation: старт нового магазина.
- ecommerce-store-evolution: развитие существующего магазина.
## Как агент принимает решения
Если вводных не хватает, агент должен уточнить:
- monorepo или split repos
- нужен ли личный кабинет
- нужна ли гостевая корзина
- где хранить корзину: localStorage, cookie, серверное состояние
- нужен ли checkout или достаточно заявки
- какие модули обязательны в admin panel
- какой визуальный стиль нужен
Если стиль не задан, агент сначала предлагает несколько направлений. Если нет готовых изображений, агент готовит промпты для внешней генерации.
## Логика .ai/STORE-BRIEF.md и AGENTS.md
- .ai/STORE-BRIEF.md создается раньше кода и раньше AGENTS.md.
- .ai/STORE-BRIEF.md фиксирует нормализованные требования, ответы на вопросы, допущения, scope storefront, scope admin panel, интеграции, визуал и этапы сборки.
- На основе .ai/STORE-BRIEF.md агент создает AGENTS.md.
- В monorepo агент должен создать один корневой AGENTS.md для frontend и backend.
- В split repo агент должен создать отдельный AGENTS.md в frontend repo и backend repo.
- В AGENTS.md агент фиксирует архитектуру, структуру репозитория, рабочие правила, контракты, роли, требования к storefront и admin panel, а также правила работы с ассетами.
## Бэкапы перед серьезными изменениями
- Перед любым серьезным изменением backend или frontend агент должен создать snapshot в .backup/.
- В имени snapshot должна быть дата со временем до секунд, например .backup/20260520-143708-storefront/.
- Папка .backup считается append-only: внутри нее можно только создавать новые snapshot, изменять или удалять старые запрещено.
- Если сохранять еще нечего, потому что backend или frontend пока не существуют, пустой backup создавать не нужно.
## Архитектура кода
- Backend и frontend должны строиться как крупный проект, а не как плоский набор файлов.
- На backend код должен быть разложен по своим зонам ответственности: api или routers, models, schemas, services, repositories, db, config или core, integrations, tests.
- На frontend код должен быть разложен по своим зонам ответственности: app или routes, pages, features, entities, components, api или services, hooks, config, lib, styles, tests.
- Бизнес-логика не должна оседать в route handlers, page-файлах или UI-компонентах, если ей место в service или domain-слое.
Рекомендуемая структура FastAPI:
```text
backend/
app/
api/
v1/
routes/
dependencies/
core/
db/
models/
schemas/
repositories/
services/
integrations/
utils/
main.py
tests/
unit/
integration/
api/
```
Рекомендуемая структура Next.js или React:
```text
frontend/
src/
app/
pages/
widgets/
features/
entities/
shared/
ui/
api/
lib/
hooks/
config/
styles/
tests/
unit/
integration/
public/
```
Рекомендуемая структура admin panel или back office:
```text
frontend/
src/
app/
admin/
widgets/
dashboard/
data-table/
filters/
forms/
features/
catalog-management/
order-management/
customer-management/
role-management/
promotion-management/
content-management/
media-management/
settings-management/
entities/
shared/
ui/
api/
lib/
hooks/
config/
styles/
tests/
unit/
integration/
admin-e2e/
```
Рекомендуемая структура monorepo:
```text
project-root/
.ai/
.backup/
AGENTS.md
backend/
frontend/
shared/
types/
contracts/
constants/
infra/
docker/
scripts/
ci/
```
Рекомендуемая структура split repo:
```text
frontend-repo/
.ai/
.backup/
AGENTS.md
src/
public/
backend-repo/
.ai/
.backup/
AGENTS.md
app/
tests/
alembic/
```
Что хранить в слоях:
- api или routes: HTTP endpoint-ы, wiring зависимостей, transport-level логика, маппинг ответа.
- models: ORM-модели и persistence-структуры.
- schemas: request/response контракты и DTO.
- repositories: прямой доступ к данным, query-логика, чтение и запись.
- services: бизнес-правила, orchestration, сценарии, транзакции.
- db: session, engine, base metadata, migrations, подключение к базе.
- core или config: settings, security, logging, bootstrap и глобальные конфиги.
- integrations: платежки, CRM, ERP, email, storage, search и другие внешние системы.
- app или pages: route entry points, layouts и page-level composition.
- widgets: крупные UI-блоки, собранные из features и shared ui.
- features: конкретные сценарии вроде auth, cart, checkout, filters, admin actions.
- entities: доменные frontend-модули вроде product, category, cart, order, user.
- shared ui: переиспользуемые UI-компоненты и design-system primitives.
- shared api: typed clients, fetchers, query adapters, transport helpers.
- hooks: переиспользуемое stateful-поведение на клиенте.
- shared styles: tokens, themes, global styles, mixins, animation primitives.
- tests: unit, integration, api и ui или e2e тесты по слоям.
Правила импортов и границ слоев:
- На backend импорты должны быть абсолютными от корня `app`, например `from app.utils.slug import build_slug`, а не `from ..utils import ...`.
- На backend не нужно писать `__all__ = ...`; лучше использовать явные прямые импорты.
- Направление зависимостей на backend должно быть односторонним: api или routes -> services -> repositories -> models или db.
- models не должны импортировать api, routes или services.
- repositories работают с данными и запросами, но не должны тянуть HTTP-логику или presentation concerns.
- services содержат бизнес-логику и orchestration, а route handlers должны оставаться тонкими.
- На frontend лучше использовать alias от корня `src`, например `@/shared/ui/button`, а не глубокие относительные цепочки вроде `../../../../shared/ui/button`.
- Направление зависимостей на frontend должно быть таким: app или pages -> widgets -> features -> entities -> shared.
- shared не должен зависеть от entities, features, widgets, pages или app.
- Barrel exports лучше не использовать там, где они скрывают ownership, размазывают ответственность или создают циклические зависимости.
- Тесты могут импортировать production-код, но production-код не должен импортировать тестовые модули.
## Рекомендуемый шаблон запроса для первого этапа
```text
Нужно подготовить .ai/STORE-BRIEF.md для ecommerce-проекта.
Формат: monorepo или split repo.
Ниша: ...
Аудитория: ...
Дизайн: ...
Нужны страницы: ...
Нужен личный кабинет: да или нет.
Нужна админка: да.
Нужна гостевая корзина: да или нет.
Интеграции: ...
Особые требования: ...
Сначала задай только важные вопросы и создай .ai/STORE-BRIEF.md.
```
## Рекомендуемый шаблон запроса для второго этапа
```text
Используй .ai/STORE-BRIEF.md как источник правды.
Сначала создай или обнови AGENTS.md.
После этого полностью собери проект: backend, storefront, admin panel, UX-состояния, анимации и недостающие asset prompts.
```
## Что можно расширить дальше
- Добавить отдельные prompts под monorepo и split repo.
- Добавить skill под интеграции платежей, CRM и ERP.
- Добавить шаблоны seed-данных, demo-каталога и дизайн-системы.
## Quality rules
- Для Python агент сначала смотрит на `pyproject.toml` и только потом принимает решение по quality gates.
- Если проект настроен на `mypy`, код должен соответствовать его конфигурации и по умолчанию тяготеть к strict discipline.
- Если проект настроен на `ty`, агент должен ориентироваться на `ty`, а не механически советовать `mypy`.
- Если настроены `ruff` и `deptry`, агент должен учитывать их как реальные ограничения проекта.
- Для React и Next.js код должен оставаться читаемым и легко изменяемым программистом без лишней магии и чрезмерной абстракции.
## Code review workflow
Если нужен жесткий review всего проекта:
1. Запусти /Ecommerce Code Review.
2. Агент сначала прочитает конфигурацию проекта: `pyproject.toml`, `package.json`, `tsconfig.json` и related configs.
3. Затем он проверит Python-часть по реальным правилам проекта, включая `mypy` или `ty`, а также `ruff` и `deptry` при наличии.
4. React-часть будет проверена на читаемость, поддержку, корректность паттернов и уместное использование современных возможностей версии.
5. В результате агент создаст .ai/CODE-REVIEW.md с жесткими findings, приоритетами и планом исправлений.
## Test workflow
Если нужно покрыть проект автотестами и прогнать их:
1. Запусти /Ecommerce Test Implementation.
2. Агент сначала определит текущий backend и frontend test stack.
3. Затем он добавит или обновит автотесты для backend и frontend и прогонит relevant suites.
4. Результат он запишет в .ai/TEST-REPORT.md.
5. Если есть падения, запусти /Ecommerce Test Repair.
6. Этот шаг разберет реальные ошибки, починит код или тесты, снова прогонит тесты и создаст .ai/TEST-REPAIR.md.
Правильный принцип: тесты не должны зеленеть за счет ослабления полезных проверок.
## SEO workflow
Если нужно отдельно проработать органический рост:
1. Запусти /Ecommerce SEO Strategy.
2. Агент прочитает .ai/STORE-BRIEF.md, если он есть.
3. Для широкого SEO-задачи агент создаст .ai/SEO-PLAN.md.
4. В план войдут технический SEO, архитектура страниц, keyword-intent mapping, metadata, schema markup, internal linking, Core Web Vitals и measurement.
5. После этого запусти /Ecommerce SEO Implementation, чтобы агент внедрил .ai/SEO-PLAN.md в код проекта.
6. После внедрения запусти /Ecommerce SEO Review, чтобы агент создал .ai/SEO-REVIEW.md и зафиксировал найденные пробелы, риски и приоритет исправлений.
Важно: skill оптимизирует сайт под максимально сильную органическую базу, но не обещает гарантированное первое место в поиске, так как это зависит не только от кода и структуры сайта.
## Пошаговая инструкция
Пошаговый порядок команд и рекомендованный workflow описаны в [WORKFLOW-GUIDE.md](WORKFLOW-GUIDE.md).
+419
View File
@@ -0,0 +1,419 @@
# Пошаговый Workflow
Этот файл нужен как практическая инструкция: что запускать по порядку, какой prompt использовать, какой агент подходит лучше всего и какой результат должен появиться после каждого шага.
## Какого агента использовать
Лучший основной агент для всей цепочки в этом проекте: `shop-fullstack-fastapi-react`.
Почему именно он:
- он уже заточен под ecommerce
- он знает workflow через `.ai/STORE-BRIEF.md` и `AGENTS.md`
- перед серьезными backend/frontend изменениями он сначала делает append-only snapshot в `.backup/`
- он учитывает storefront, admin panel, backend, SEO, code review и quality rules
- он умеет работать с FastAPI, React, Next.js, PostgreSQL, monorepo и split repo
- он должен держать backend и frontend в нормальной крупнопроектной архитектуре с разнесением по слоям и папкам
Практически это означает следующее:
- если ты запускаешь slash-команды из этого репозитория, нужный агент уже привязан в prompt-файлах
- если запускаешь задачу вручную через обычный чат, лучше явно выбрать агент `shop-fullstack-fastapi-react`
## Если команда запущена почти без подробностей
Если пользователь запускает команду почти без контекста, правильное поведение теперь такое:
- агент не додумывает молча все важные требования
- агент задает короткий и конкретный набор вопросов
- вопросы зависят от текущего шага
Обычно это выглядит так:
- для brief: что за магазин, какой формат репозитория, какие страницы, нужна ли авторизация, корзина, админка, интеграции, стиль
- для build: есть ли готовый `.ai/STORE-BRIEF.md`, что собирать в первую очередь, есть ли ограничения
- для extend: что менять, что не ломать, какие текущие части критичны
- для SEO: стратегия нужна, внедрение или review
- для code review: проверять весь проект или только backend, frontend, SEO, performance, архитектуру
Если деталей почти нет совсем, агент должен сначала задать 3-7 самых важных вопросов и только потом продолжать работу.
## Главный порядок команд
Если ты создаешь новый проект с нуля, правильная цепочка обычно такая:
1. `/Ecommerce Prepare Brief`
2. `/Ecommerce Visual Pack` при необходимости
3. `/Ecommerce Build From Brief`
4. `/Ecommerce Test Implementation`
5. `/Ecommerce Test Repair` если тесты упали
6. `/Ecommerce Extend Existing` для следующих итераций и изменений
7. `/Ecommerce Code Review`
8. `/Ecommerce SEO Strategy`
9. `/Ecommerce SEO Implementation`
10. `/Ecommerce SEO Review`
11. `/Ecommerce Code Review` повторно перед релизом при крупных изменениях
Если проект уже существует, цепочка обычно такая:
1. `/Ecommerce Extend Existing`
2. `/Ecommerce Test Implementation`
3. `/Ecommerce Test Repair` если тесты упали
4. `/Ecommerce Code Review`
5. `/Ecommerce SEO Strategy`
6. `/Ecommerce SEO Implementation`
7. `/Ecommerce SEO Review`
8. `/Ecommerce Code Review` повторно, если после SEO было много изменений в коде
## Подробно по шагам
### Шаг 1. Подготовить нормальный brief из сырого текста
Команда:
```text
/Ecommerce Prepare Brief
```
Какой агент лучше всего подходит:
- `shop-fullstack-fastapi-react`
Что писать в запросе после запуска:
```text
Нужно подготовить .ai/STORE-BRIEF.md для ecommerce-проекта.
Формат: monorepo.
Ниша: магазин косметики.
Аудитория: женщины 24-45.
Дизайн: современный premium, mobile-first.
Нужны страницы: главная, каталог, категории, карточка товара, корзина, checkout, auth, account, admin panel.
Интеграции: платежи, email, analytics.
Сначала задай только важные вопросы и создай .ai/STORE-BRIEF.md.
```
Что делает этот шаг:
- берет твой сырой текст
- задает только важные вопросы
- нормализует требования
- создает `.ai/STORE-BRIEF.md`
Что должно появиться после шага:
- `.ai/STORE-BRIEF.md`
Когда переходить дальше:
- когда `.ai/STORE-BRIEF.md` уже заполнен и тебя устраивает
### Шаг 2. При необходимости определить визуальное направление и ассеты
Команда:
```text
/Ecommerce Visual Pack
```
Какой агент лучше всего подходит:
- `shop-fullstack-fastapi-react`
Когда запускать:
- если дизайн не определен
- если нужны prompts для генерации изображений
- если нужно зафиксировать визуальную систему до начала сборки
Что писать в запросе после запуска:
```text
Подготовь визуальное направление для магазина по .ai/STORE-BRIEF.md. Нужны 2-3 сильных варианта стилистики, рекомендации по типографике, цветам, motion и prompts для генерации hero и category images.
```
Что должно появиться после шага:
- визуальное направление в ответе
- при необходимости prompts для генерации изображений
### Шаг 3. Собрать проект по brief
Команда:
```text
/Ecommerce Build From Brief
```
Какой агент лучше всего подходит:
- `shop-fullstack-fastapi-react`
Что писать в запросе после запуска:
```text
Используй .ai/STORE-BRIEF.md как источник правды.
Сначала создай или обнови AGENTS.md.
После этого полностью собери проект: backend, storefront, admin panel, UX-состояния, анимации и недостающие asset prompts.
```
Что делает этот шаг:
- читает `.ai/STORE-BRIEF.md`
- создает `AGENTS.md`
- строит backend, storefront и admin panel
- учитывает quality rules проекта
Что должно появиться после шага:
- `AGENTS.md`
- код проекта
### Шаг 4. Доработать или переделать существующий проект
Команда:
```text
/Ecommerce Extend Existing
```
Какой агент лучше всего подходит:
- `shop-fullstack-fastapi-react`
Когда запускать:
- когда проект уже собран и нужно что-то изменить
- когда нужно добавить модули, переделать UX, расширить backend, доработать admin panel
Что писать в запросе после запуска:
```text
Доработай существующий проект: добавь wishlist, расширь фильтры каталога, улучши личный кабинет и добавь управление промокодами в admin panel. Сохрани текущую архитектуру, если она адекватна.
```
Что делает этот шаг:
- анализирует текущий код
- не ломает архитектуру без причины
- вносит точечные или структурные изменения
### Шаг 5. Написать и прогнать автотесты
Команда:
```text
/Ecommerce Test Implementation
```
Какой агент лучше всего подходит:
- `shop-fullstack-fastapi-react`
Что писать в запросе после запуска:
```text
Добавь и обнови автотесты для backend и frontend. Сначала определи текущий test stack проекта. Покрой самые рискованные ecommerce-флоу, затем запусти relevant suites и создай .ai/TEST-REPORT.md.
```
Что делает этот шаг:
- определяет backend и frontend test stack
- пишет или расширяет автотесты
- гоняет тесты
- фиксирует результат в `.ai/TEST-REPORT.md`
Что должно появиться после шага:
- тестовый код
- `.ai/TEST-REPORT.md`
### Шаг 6. Починить падения тестов и прогнать их заново
Команда:
```text
/Ecommerce Test Repair
```
Какой агент лучше всего подходит:
- `shop-fullstack-fastapi-react`
Когда запускать:
- если после предыдущего шага есть падающие тесты
- если после изменений в проекте test suite стал красным
Что писать в запросе после запуска:
```text
Разбери текущие падения тестов, прочитай .ai/TEST-REPORT.md и фактический output test runner. Почини корневую причину, затем снова прогони relevant suites и создай .ai/TEST-REPAIR.md.
```
Что делает этот шаг:
- читает реальные падения
- определяет, проблема в коде или в тестах
- чинит root cause
- гоняет тесты повторно
- пишет `.ai/TEST-REPAIR.md`
Что должно появиться после шага:
- исправления в коде или тестах
- `.ai/TEST-REPAIR.md`
### Шаг 7. Провести жесткий code review проекта
Команда:
```text
/Ecommerce Code Review
```
Какой агент лучше всего подходит:
- `shop-fullstack-fastapi-react`
Что писать в запросе после запуска:
```text
Сделай жесткий review всего проекта. Сначала прочитай pyproject.toml, package.json, tsconfig и другие конфиги. Проверь Python по mypy или ty, ruff и deptry, если они настроены. React проверь на читаемость, поддержку, производительность и уместность современных возможностей версии. Создай .ai/CODE-REVIEW.md.
```
Что делает этот шаг:
- читает конфиги проекта
- проверяет Python по реальным quality gates проекта
- проверяет React на читаемость и поддержку
- пишет жесткий отчет
Что должно появиться после шага:
- `.ai/CODE-REVIEW.md`
Когда запускать:
- после крупных этапов разработки
- перед релизом
- после большой переработки архитектуры
### Шаг 8. Построить SEO-стратегию
Команда:
```text
/Ecommerce SEO Strategy
```
Какой агент лучше всего подходит:
- `shop-fullstack-fastapi-react`
Что писать в запросе после запуска:
```text
Построй SEO-стратегию для проекта на основе .ai/STORE-BRIEF.md. Нужны technical SEO, keyword intent mapping, структура страниц, metadata, schema markup, internal linking и measurement. Создай .ai/SEO-PLAN.md.
```
Что делает этот шаг:
- создает SEO-план
- определяет архитектуру SEO
- формирует приоритеты по органическому росту
Что должно появиться после шага:
- `.ai/SEO-PLAN.md`
### Шаг 9. Внедрить SEO в код
Команда:
```text
/Ecommerce SEO Implementation
```
Какой агент лучше всего подходит:
- `shop-fullstack-fastapi-react`
Что писать в запросе после запуска:
```text
Внедри .ai/SEO-PLAN.md в код проекта. Примени metadata, canonicals, schema markup, sitemap, robots, internal linking, template-level SEO и indexation rules.
```
Что делает этот шаг:
- превращает SEO-план в реальные изменения в коде
- внедряет schema, metadata, canonical rules, sitemap и SEO-логику шаблонов
### Шаг 10. Проверить SEO после внедрения
Команда:
```text
/Ecommerce SEO Review
```
Какой агент лучше всего подходит:
- `shop-fullstack-fastapi-react`
Что писать в запросе после запуска:
```text
Проведи повторный SEO-аудит проекта после внедрения. Прочитай .ai/SEO-PLAN.md и проверь фактическую реализацию в коде. Создай .ai/SEO-REVIEW.md с приоритетами и remediation plan.
```
Что делает этот шаг:
- проверяет, что SEO действительно внедрено корректно
- пишет список рисков, пробелов и улучшений
Что должно появиться после шага:
- `.ai/SEO-REVIEW.md`
## Самая правильная цепочка для нового проекта
Если нужна короткая версия без лишних развилок, запускай так:
```text
1. /Ecommerce Prepare Brief
2. /Ecommerce Visual Pack
3. /Ecommerce Build From Brief
4. /Ecommerce Test Implementation
5. /Ecommerce Test Repair
6. /Ecommerce Code Review
7. /Ecommerce SEO Strategy
8. /Ecommerce SEO Implementation
9. /Ecommerce SEO Review
10. /Ecommerce Code Review
```
Пояснение:
- test implementation и test repair должны пройти до жесткого review
- первый review проверяет качество архитектуры и кода после сборки
- SEO-шаги идут после того, как структура страниц уже существует
- финальный review полезен после SEO-внедрения, если было много изменений в коде
## Самая правильная цепочка для уже существующего проекта
```text
1. /Ecommerce Extend Existing
2. /Ecommerce Test Implementation
3. /Ecommerce Test Repair
4. /Ecommerce Code Review
5. /Ecommerce SEO Strategy
6. /Ecommerce SEO Implementation
7. /Ecommerce SEO Review
8. /Ecommerce Code Review
```
## Когда можно использовать ручной запуск без prompt-файлов
Если не хочешь использовать slash-команды, можно просто выбрать агент `shop-fullstack-fastapi-react` вручную и писать задачу текстом.
Но правильнее использовать именно prompt-файлы, потому что:
- в них уже зашит правильный агент
- в них уже зашиты ожидания по шагу
- снижается шанс запустить не тот workflow
## Что должно лежать в корне проекта по ходу работы
В идеале после прохождения всей цепочки у тебя появятся такие файлы:
- `.ai/STORE-BRIEF.md`
- `AGENTS.md`
- `.ai/TEST-REPORT.md`
- `.ai/TEST-REPAIR.md`
- `.ai/SEO-PLAN.md`
- `.ai/SEO-REVIEW.md`
- `.ai/CODE-REVIEW.md`
Не все из них появляются сразу:
- `.ai/STORE-BRIEF.md` появляется после подготовки brief
- `AGENTS.md` появляется перед сборкой
- `.ai/TEST-REPORT.md` появляется после шага с написанием и прогоном тестов
- `.ai/TEST-REPAIR.md` появляется после шага исправления падений
- `.ai/SEO-PLAN.md` появляется на этапе SEO strategy
- `.ai/SEO-REVIEW.md` появляется после SEO review
- `.ai/CODE-REVIEW.md` появляется после code review
## Короткая памятка
- Хочешь превратить сырую идею в нормальное ТЗ: `/Ecommerce Prepare Brief`
- Хочешь собрать проект по brief: `/Ecommerce Build From Brief`
- Хочешь доработать существующий проект: `/Ecommerce Extend Existing`
- Хочешь жесткий review: `/Ecommerce Code Review`
- Хочешь написать и прогнать автотесты: `/Ecommerce Test Implementation`
- Хочешь починить падения тестов и снова прогнать suite: `/Ecommerce Test Repair`
- Хочешь SEO-план: `/Ecommerce SEO Strategy`
- Хочешь внедрить SEO в код: `/Ecommerce SEO Implementation`
- Хочешь проверить SEO после внедрения: `/Ecommerce SEO Review`
- Хочешь сначала определить визуал и prompts для изображений: `/Ecommerce Visual Pack`