# System Architecture

> How the pieces fit together. Diagrams use Mermaid (render on GitHub).

## 1. Components at a glance

| Component | Tech | Role |
|---|---|---|
| **Commerce backend** | Medusa.js (Node 20+, TypeScript) | Products, cart, orders, payments, discounts, customers, the Admin REST API, custom modules. |
| **Admin UI** | Medusa Admin (React, ships with Medusa) | Where the owner runs the business. Extended with our widgets/routes (Store Copilot, Content, A/B, Analytics). |
| **Storefront** | Next.js (Medusa `nextjs-starter`) | The customer-facing shop. Themeable. Server-rendered for SEO. |
| **Database** | PostgreSQL | Single source of truth for all commerce + custom data. |
| **AI services** | Claude + Gemini (HTTP APIs) | Store Copilot (Claude tool-use), background agents (Gemini), storefront AI. |
| **Marketing agents** | Existing `scripts/run-agents.mjs` + n8n | Pillar-2 background marketing automation (reused from this repo). |
| **Cache/events** | Medusa in-memory modules (MVP) / optional Redis | Caching, event bus, background workflows. |
| **Search** | Postgres full-text (MVP) / MeiliSearch or Algolia (later) | Storefront product search. |
| **Platform Control API + MCP** | REST layer over the Medusa Admin API + custom modules, exposed as an **MCP server** | **The primary control surface.** Lets Claude (in chat) do everything: products, orders, **test orders**, theme/content edits, SEO/listings, support-agent config. Live, typed successor to the n8n/`claude-wp-manager` bridge. |
| **CI/CD auto-deploy** | GitHub Actions → SSH to the cPanel host | Ships platform **code** changes automatically (build + `medusa db:migrate` + restart) so nothing is uploaded by hand. |
| **External channels** | Meta Ads API, Amazon SP-API, Flipkart Seller API | Ad-performance insights + multichannel product listing. |

## 2. High-level diagram

```mermaid
flowchart TB
    OWNER["Owner in Claude chat"]
    subgraph Customer
      SF["Storefront (Next.js)<br/>renders live from DB"]
    end

    subgraph Server["cPanel host (Node + Postgres)"]
      MCP["Platform Control API + MCP<br/>(primary control surface)"]
      API["Medusa Backend<br/>(commerce API + custom modules)"]
      ADMIN["Medusa Admin (React)<br/>+ embedded Store Copilot"]
      DB[("PostgreSQL")]
      AGENTS["Marketing Agent Runner<br/>(reused scripts / n8n)"]
    end

    subgraph AI["AI providers (HTTPS)"]
      CLAUDE["Claude API<br/>(copilot tool-use)"]
      GEMINI["Gemini API<br/>(bulk agent runs)"]
    end

    subgraph Deploy["Self-evolving platform"]
      REPO["This Git repo"]
      GHA["GitHub Actions<br/>auto-deploy"]
    end

    subgraph External["Integrations & channels"]
      PAY["Razorpay / Stripe / PayPal"]
      MAIL["Email + Mailchimp"]
      META["Meta Ads insights"]
      MKT["Amazon / Flipkart listing"]
    end

    OWNER -->|chat| CLAUDE
    CLAUDE -->|MCP tool calls| MCP
    MCP --> API
    SF -->|Store API| API
    ADMIN -->|Admin API| API
    API --> DB
    API -->|on-demand revalidate| SF
    AGENTS --> GEMINI
    AGENTS --> DB
    API --> PAY
    API --> MAIL
    AGENTS --> META
    AGENTS --> MKT
    OWNER -.code change.-> REPO --> GHA -->|build+migrate+restart| Server
```

## 3. Many clients, one Control-API core

> **Updated after review (see `07-architecture-hardening.md`).** The **Control API is the
> permanent center**; the storefront, the **Admin UI**, **Claude (via MCP)**, and **n8n** are
> all *clients* of it. AI is a powerful client — **not** the core. If AI is down or
> rate-limited, the owner still runs everything (refunds, labels, inventory) from the
> **Admin UI fallback**.

- **Store API** (public) — the Next.js storefront calls this for catalog, cart, checkout.
- **Control API / Admin API** (authenticated) — the **Admin UI, the MCP/Claude adapter, and
  n8n** all call this to manage the business. It speaks **domain verbs** (`createProduct`), so
  no client needs to know Medusa is underneath, and there is no parallel "AI backdoor."

## 4. Key request flows

### 4a. Customer places an order

```mermaid
sequenceDiagram
    participant C as Customer
    participant SF as Storefront (Next.js)
    participant API as Medusa Backend
    participant PAY as Razorpay/Stripe
    participant DB as Postgres
    C->>SF: Browse, add to cart
    SF->>API: Store API (cart, line items)
    API->>DB: persist cart
    C->>SF: Checkout
    SF->>API: create payment session
    API->>PAY: init payment
    PAY-->>C: pay (UPI/card)
    PAY-->>API: webhook: paid
    API->>DB: create order, capture
    API-->>SF: order confirmation
```

### 4b. Owner uses the Store Copilot

```mermaid
sequenceDiagram
    participant O as Owner
    participant AD as Admin (Copilot widget)
    participant CL as Claude (tool-use)
    participant API as Medusa Admin API
    O->>AD: "Add bagru cotton kurti ₹1,250, 20 in stock"
    AD->>CL: message + tool schemas (createProduct, setInventory…)
    CL-->>AD: tool_call createProduct{...}
    AD->>O: Confirm? (write action)
    O-->>AD: Yes
    AD->>API: POST /admin/products
    API-->>AD: created product
    AD->>CL: tool_result
    CL-->>AD: "Done — created 'Bagru Cotton Kurti'."
```

The confirmation step (write actions only) is a hard guardrail — see `02-ai-agents.md §4`.

### 4c. Background marketing agent run (reused system)

```mermaid
sequenceDiagram
    participant SCH as Scheduler (n8n / cron)
    participant RUN as Agent Runner
    participant API as Medusa Backend
    participant G as Gemini
    participant DB as Postgres
    SCH->>RUN: every 6h
    RUN->>API: read live store data (top products, orders)
    RUN->>G: agent prompt + brand + store context
    G-->>RUN: JSON {summary, items, next_actions}
    RUN->>DB: insert ai_agent_run row
    Note over API: Admin surfaces deliverables on the<br/>Marketing screen
```

### 4d. Live theme/content edit from Claude (zero deploy)

```mermaid
sequenceDiagram
    participant O as Owner (Claude chat)
    participant CL as Claude
    participant MCP as Platform MCP
    participant API as Backend
    participant DB as Postgres
    participant SF as Storefront (Next.js)
    O->>CL: "make the hero festive red, move reviews above products"
    CL->>MCP: updateThemeTokens / reorderSections (tool calls)
    MCP->>API: write theme_setting / content_block
    API->>DB: persist (structured + schema-validated)
    API->>SF: on-demand revalidate (path/tag)
    SF-->>O: store reflects the change in seconds — no rebuild, no upload
```

This is the flow that replaces the WooCommerce "edit → redeploy → repeat 20×" loop.

### 4e. Platform code change → auto-deploy (self-evolving)

```mermaid
sequenceDiagram
    participant O as Owner (Claude chat)
    participant CC as Claude Code (this repo)
    participant GH as GitHub Actions
    participant H as cPanel host
    O->>CC: "add a new 'lookbook' section type"
    CC->>CC: edit code, commit, push
    CC->>GH: push triggers the deploy workflow
    GH->>H: SSH → git pull, npm ci, build, medusa db:migrate
    GH->>H: restart Passenger apps
    H-->>O: new capability is live — nothing uploaded by hand
```

Two change tiers: **Tier 1** (theme/content/products/orders) is live data via 4d;
**Tier 2** (new code/features) is auto-deployed via 4e. Neither needs a manual upload.

## 5. Hosting shape (cPanel + Node + Postgres)

The owner's cPanel host runs Node apps via Passenger and provides PostgreSQL. We run **two
Node apps + one database**:

```mermaid
flowchart LR
    subgraph cPanel
      direction TB
      P1["Passenger app #1<br/>Medusa backend<br/>:9000"]
      P2["Passenger app #2<br/>Next.js storefront<br/>:8000"]
      PG[("PostgreSQL DB")]
      P1 --> PG
      P2 -->|Store API| P1
    end
    NET((Internet)) -->|store.domain| P2
    NET -->|admin.domain or /app| P1
```

- **Caching/events/workflows:** Medusa v2's default modules are **in-memory/local**, which
  is fine for one store on a single process. Redis is **optional**; if durable background
  jobs or multi-process scaling are needed later, point Medusa at managed Redis (e.g.
  Upstash, free tier, over TLS) — no architecture change required.
- **Search:** start with Postgres full-text search (no extra service). Swap to MeiliSearch
  or Algolia later via Medusa's search plugin interface.

Full deploy steps and the host-capability checklist are in `05-deployment-cpanel.md`.

## 6. Why this shape

- **One backend, two clients** keeps logic in Medusa and avoids duplicating business rules.
- **Copilot rides the Admin API** → no special-case AI code path; reuse Medusa's auth/perms.
- **In-memory defaults** keep the cPanel footprint small; Redis is a later opt-in, not a
  prerequisite — important because shared hosts rarely offer Redis.
- **Reusing the agent runner** means Pillar-2 marketing AI is mostly migration, not new code.
- **The MCP control layer rides the same Admin API** a human uses, so "control from Claude
  chat" needs no parallel backend — and it's the typed, live successor to today's n8n bridge.
- **DB-driven storefront + on-demand revalidation** is what makes theme edits deploy-free; the
  storefront never hard-codes look/content, it reads `theme_setting`/`content_block` at runtime.
- **CI/CD auto-deploy** keeps even code-level changes hands-off, so the platform can evolve
  from Claude without the manual upload step that caused the original frustration.
