# AI Layer — Three Pillars

The AI is what makes this platform different from a plain Medusa store. There are three
distinct AI systems; keep them separate in your head because they have different jobs,
different cost profiles, and different providers.

| Pillar | Where | What it does | Provider (default) |
|---|---|---|---|
| **1. Store Copilot** | **Claude chat** (+ admin) | *Does things* in the store on command, agentically, via the Platform MCP | **Claude** (tool-use) |
| **2. Marketing agents** | Background | 25 scheduled agents producing SEO/content/social/CRO deliverables | **Gemini** (cheap, high volume) |
| **3. Storefront AI** | Customer site | Search, recommendations, support chat | Mix (see §3) |

## 1. Pillar 1 — Store Copilot ("Business Assistant")

This is the "Amboras Business Assistant" from the reference screenshots — but its **primary
home is Claude chat**, the way the owner already works. A **Platform MCP connector** exposes
the store to Claude so the owner can run the whole business from chat; the same assistant is
*also* embedded in the admin as a secondary surface. Both share one tool layer.

**How it works — tool-use over the Platform Control API.** Claude is given a set of **tools**
(via MCP) that map to Medusa Admin API operations + our custom modules. The owner's message +
tool schemas go to Claude; Claude replies with tool calls; the control layer executes them
against Medusa and feeds results back until the task is done. Because it uses the *same Admin
API a human uses*, it inherits Medusa's permissions and validation — there is no separate
"AI backdoor." This is the live, typed successor to today's n8n + `claude-wp-manager` bridge.

**Example tools (each backed by an existing Medusa Admin endpoint):**

| Tool | Backing endpoint | Read/Write |
|---|---|---|
| `searchProducts` | `GET /admin/products` | read |
| `createProduct` | `POST /admin/products` | **write** |
| `updateVariantPrice` | `POST /admin/price-lists…` | **write** |
| `setInventory` | `POST /admin/inventory-items…` | **write** |
| `listOrders` | `GET /admin/orders` | read |
| `createDiscount` | `POST /admin/promotions` | **write** |
| `salesReport` | analytics module query | read |
| `draftContent` | content module + LLM | write (draft only) |
| `updateTheme` / `reorderSections` | `theme_setting` / `content_block` | **write** (live, no deploy) |
| `createTestOrder` | draft order + test-mode payment | **write** (test) |
| `optimizeListing` | product + SEO fields (title/desc/schema/alt) | **write** |
| `runMarketingAgent` | agent runner (Pillar 2) | action |
| `configureSupportAgent` | support-agent settings | **write** |
| `adInsights` | Meta Ads API | read |
| `syncToMarketplace` | Amazon/Flipkart channel | **write** (credential-gated) |

**What the owner runs from chat (action, not advice):**
- *"Restyle the homepage for Diwali and move reviews up"* → live theme/content edit, no deploy.
- *"Write and optimize the listing for the new bagru kurti"* → titles, descriptions, JSON-LD
  schema, image alt text, collection placement — written, not just suggested.
- *"Place a test order to check Razorpay UPI checkout"* → a test-mode order end-to-end.
- *"Run the SEO and ecommerce agents on the saree category"* → kicks off Pillar-2 agents.
- *"Tune the support agent's tone and escalation rules"* → support-agent config.

**Why Claude here:** the copilot is an agentic, multi-step, tool-calling workload where
correctness matters (it's editing the live store). Use the latest Claude model for the
copilot. The existing repo already calls the Anthropic API (`scripts/run-agents.mjs`
`callAnthropic`) — reuse that key and request pattern, upgraded to the tool-use message shape.

**Brand grounding:** the copilot's system prompt is seeded with the brand block already in
`agents/manifest.json` (niche: block prints / jaipuri razai / sarees; audience; competitors)
so its drafts and suggestions sound like Jaipur Handloomia, not generic e-commerce.

## 2. Pillar 2 — Marketing agents (reused, not rebuilt)

This repo already runs **25 marketing agents** (keyword research, content strategy, SEO
writer, AEO/GEO, technical/on-page/off-page SEO, local, ecommerce SEO, schema, brand
authority, AI monitoring, CRO, reviews, trends, image SEO, YouTube, programmatic, social,
GSC, analytics, backlink outreach…). They run on a schedule via n8n/Gemini and output JSON
deliverables. **We keep all of it.**

**What changes:** instead of operating blind, the agents now read **live store data** from
Medusa (best-sellers, low-stock items, recent orders, search terms) so their output is
grounded in what's actually happening in the shop. Their JSON output shape is unchanged:

```json
{ "summary": "...", "items": [{ "title": "...", "detail": "...",
  "priority": "high|medium|low", "type": "finding|deliverable|recommendation|task" }],
  "next_actions": ["..."] }
```

That identical shape is why migration is cheap — see `03-data-model.md` for how runs move
from `data/*.json` into an `ai_agent_run` table the admin reads.

**Why Gemini here:** 25 agents every 6 hours is high-volume, low-stakes text generation —
the cheap path. Mirrors the current production setup (`callGemini`, `gemini-2.5-flash`).

**Surfacing in the admin:** a "Marketing" screen lists agents, statuses, and latest
deliverables (priority-tagged) — the same information architecture as today's
`artifact/dashboard.html`, rebuilt as a native admin route.

**Campaign-driven & coordinated (not 25 always-on) — see `08-growth-and-sales-engine.md §10`.**
Instead of running all 25 agents every 6h (noise, cost, duplicate work), a **Campaign
Coordinator** runs only the agents that serve the **active campaign** (e.g. Diwali), enforces
priorities, and de-duplicates keywords/content. Every agent is **classified by revenue impact**
— `direct-revenue` (CRO, ecommerce-SEO, review, retention) / `awareness` (social, Pinterest,
YouTube, brand) / `support` (technical-SEO, schema, analytics) — so revenue drivers run first.

**Inventory-aware (the stock guard) — see `08 §11`.** Agents read **live stock** via the event
bus and **never recommend or promote out-of-stock, dead, or low-margin SKUs**; the guard swaps
in in-stock alternatives instead. This protects trust and stops traffic to dead links.

## 3. Pillar 3 — Storefront AI (customer-facing)

| Feature | Approach | Phase |
|---|---|---|
| **AI search** | Natural-language product search ("warm cotton razai for winter gifting") over the catalog; start with Postgres FTS + LLM query expansion, upgrade to vector search later | v2 |
| **Recommendations** | "You may also like" / "complete the set" from order history + product attributes | v2 |
| **Support chat** | Customer chat that answers from product data, policies, and order status (read-only tools); escalates to human/email | v2 |

These are v2 because they touch the customer experience and should land after the core store
and admin are proven.

## 4. Guardrails (non-negotiable)

1. **Confirm before write.** The Store Copilot may *read* freely, but any **write** (create/
   update/delete product, price, inventory, discount, order change) requires an explicit
   owner confirmation in the UI before execution. The diff/summary of the change is shown.
2. **Least privilege.** The copilot's API token carries only the permissions the owner has.
3. **No secret exposure.** API keys live in server env vars, never sent to the browser or
   embedded in storefront/admin bundles. LLM calls that need keys are proxied server-side.
4. **Audit trail.** Every copilot write is logged (who/what/when, before→after) so actions
   are traceable.
5. **Cost ceiling.** Reuse the existing `config/control.json` style limits (max items/run,
   model choice, global pause) so AI spend stays bounded and the owner can pause everything.

## 5. Provider strategy summary

- **Claude** → Store Copilot (agentic tool-use; correctness-critical). Latest Claude model.
- **Gemini** → background marketing agents (cheap, high volume). `gemini-2.5-flash`.
- **Storefront AI** → start cheap (Gemini/FTS), add vector search/embeddings in v2.
- Keys and call patterns reuse `scripts/run-agents.mjs` (`callAnthropic` / `callGemini`),
  centralized into a small server-side AI service module in the Medusa backend.
- **All AI sits behind the Control API as a client, via a Task Router seam** (reasoning→Claude,
  batch→Gemini, vision/image→best model) — so providers/models can change without touching the
  platform, and the business runs from the Admin UI if AI is unavailable. See
  `07-architecture-hardening.md §1–2`. AI writes go through **draft→preview→publish** (07 §5) and
  are **logged end-to-end** (07 §13).
