# MASTER SPECIFICATION & SYSTEM ARCHITECTURE
**Project:** Artisan 2nd Brain — Workshop Studio Management System  
**Applet ID:** `c4c38da0-a794-41ac-a866-e0647152f0fa`  
**Target Environment:** Cloud Run (Containerized Node.js 20 + Express + React 18 + Vite)  
**Primary User / Owner:** `mdominique1025@gmail.com` (Diamond Lifetime Tier)  
**Database Instance:** Cloud Firestore (`ai-studio-c4c38da0-a794-41ac-a866-e0647152f0fa`)  
**Security Posture:** Default-Deny Row-Level Security Rules + Server-Side Gemini API Isolation  

---

## 1. Executive Summary & Purpose

The Artisan Workshop Studio is a unified operational platform, formulation laboratory, financial ledger, and multi-agent AI assistant engineered for artisanal product manufacturers, formulators (cosmetics, soaps, candles, botanicals, culinary crafts), and small-batch production workshops.

The application combines:
1. **Practical Workshop Operations:** Recipe formulation, saponification/lye calculators, batch scaling, curing tracking, raw material inventory with QR labels, COGS/margin pricing, compliance logs, CRM leads, and financial bookkeeping.
2. **Specialized Multi-Agent AI System:** A team of domain-specific assistants (Studio Lead, Formulator, Business Strategist, Marketing Specialist, Wealth Advisor, Niche Expert, Mentor) providing context-grounded advice.
3. **Real Business RAG Engine:** Live retrieval of recipes, inventory stock, regulatory documents, and tasks injected directly into LLM reasoning prompts.
4. **Hardened Data Security:** Firebase Authentication, Firestore row-level security policies (`isOwner(userId)`), server-side API secret isolation, and parameter bounds sanitization.

---

## 2. System Architecture & Tech Stack

```
                                  [ Client Browser ]
                                          │
                     ┌────────────────────┴────────────────────┐
                     │                                         │
              (Static Assets & UI)                    (API Requests)
                     ▼                                         ▼
            [ React 18 + Vite ]                        [ Express Server ]
         - Tailwind CSS (Neumorphic)                      (Port 3000)
         - Lucide React Icons                                  │
         - Sonner Notifications                                ├─► Gemini 2.5 Flash / Pro (Server-Side)
         - Context (ArtisanContext)                            ├─► Real-Time RAG Context Retrieval
                     │                                         └─► Input Sanitization & Rate Limiter
                     ▼
          [ Google Cloud Firestore ]
         - Default-Deny Security Rules
         - Isolated User Data (UID Bound)
```

### Core Technologies
- **Frontend:** React 18, TypeScript, Tailwind CSS, Vite
- **Backend / Host:** Node.js, Express (compiled via `esbuild` to `dist/server.cjs` for production)
- **AI Engine:** Google Gemini (`@google/genai` TypeScript SDK) running exclusively server-side
- **Database & Identity:** Firebase Authentication & Cloud Firestore
- **State Management:** React Context (`ArtisanContext.tsx`) syncing bidirectional Firestore collections with local offline sandbox support.

---

## 3. Directory & File Manifest

```
├── /index.html                   # HTML entry point (SEO, title, and OpenGraph tags)
├── /metadata.json                # AI Studio applet metadata & permissions
├── /package.json                 # Project dependencies & build/dev/start scripts
├── /server.ts                    # Express server entry point (Vite middleware, API proxy)
├── /firestore.rules              # Deployed Firestore Default-Deny security policies
├── /firebase-applet-config.json  # Firebase client credentials
├── /src/
│   ├── main.tsx                  # React DOM bootstrap
│   ├── App.tsx                   # Top-level application router and layout
│   ├── firebase.ts               # Client Firebase SDK initialization
│   ├── types.ts                  # Shared TypeScript interfaces & types
│   ├── index.css                 # Global Tailwind CSS directives & custom utility classes
│   ├── components/               # Shared visual components
│   │   ├── NavBar.tsx            # Navigation rail & collapse controls
│   │   ├── Header.tsx            # Header status bar, user auth, and quick action bar
│   │   ├── Workshop/             # Core artisan operational components
│   │   │   ├── ArtisanCalculators.tsx # Formulation, lye SAP, superfat calculators
│   │   │   ├── FormulationManager.tsx # Recipe builder and ingredient ratios
│   │   │   ├── InventorySupplies.tsx  # Raw materials stock, reorder alerts, QR tags
│   │   │   ├── StudioLedger.tsx       # Double-entry transactions, cash flow
│   │   │   └── KanbanBoard.tsx        # Production pipeline (Prep -> Curing -> Released)
│   │   └── ui/                   # Reusable UI primitives (dialogs, tabs, switches)
│   ├── features/                 # Modular functional hubs
│   │   ├── AgentFeatures.tsx     # Multi-agent interactive workspace & chat interface
│   │   ├── AgentDiagnostics.tsx  # API latency, token telemetry, agent health monitors
│   │   ├── COGSHub.tsx           # Unit costing, packaging margins, retail pricing
│   │   ├── CollectionsHub.tsx    # Seasonal lines, release series, product associations
│   │   ├── ComplianceHub.tsx     # Safety data sheets (MSDS), batch logs, regulations
│   │   ├── CRMHub.tsx            # Retail buyer records, interaction history, outreach
│   │   ├── DocumentsHub.tsx      # Standard operating procedures (SOPs), templates
│   │   ├── MarketingHub.tsx      # Marketing campaign builder, ad performance tracking
│   │   ├── OnboardingForm.tsx    # First-time studio profile setup wizard
│   │   ├── ProductionHub.tsx     # Active batch curing tracking & product shelf life
│   │   ├── RecipeLibrary.tsx     # Master formulation records, SAP notes, batch scaler
│   │   ├── SecurityGovernanceHub.tsx # Security posture status, RAG index, rules viewer
│   │   ├── SmartNotebook.tsx     # Laboratory scratchpad & research notes
│   │   ├── SourcingHub.tsx       # Raw material vendor quotes & suppliers
│   │   ├── StudioPlanner.tsx     # Timeline scheduler & workshop events calendar
│   │   ├── StudioProfile.tsx     # Operational overview and billing indicators
│   │   ├── SubscriptionManager.tsx # Tier configuration and feature access gates
│   │   ├── TaskBoard.tsx         # Operational checklists & agent dispatch board
│   │   └── WholesaleHub.tsx      # Wholesale order queues, tiered volume pricing
│   ├── services/                 # Backend & client service modules
│   │   ├── agentService.ts       # Client API proxy (relays Firebase auth bearer token)
│   │   ├── agentServiceServer.ts # Server-side Gemini reasoning engine & tool calling
│   │   ├── ragService.ts         # In-memory vector-like RAG retrieval engine
│   │   └── realSecurityService.ts# Input sanitization, anti-injection, and tool validator
│   └── utils/
│       ├── demoData.ts           # Offline preview and initial sandbox records
│       └── helper.ts             # Date formatters, math utilities, and currency helpers
└── /docs/ (Root Documentation)
    ├── MASTER.md                 # This master specification document
    ├── README.md                 # Project overview and local execution guide
    ├── ARCHITECTURE.md           # Architectural breakdown and module index
    ├── FEATURE_INVENTORY.md      # Comprehensive feature matrix and routes
    ├── GUIDE.md                  # User manual and operational walkthrough
    ├── MODEL_METERING.md         # Resource consumption & cost metrics
    └── STATE_OWNERSHIP.md        # State hierarchy & persistence specifications
```

---

## 4. Security & Access Control Model

### A. Authentication & User Isolation
- Firebase Auth supports Google Sign-In and Email authentication.
- Authenticated user UID is bound to every created document across collections.
- Special VIP email rule: User `mdominique1025@gmail.com` is automatically granted the **Diamond Lifetime** tier with unrestricted system-wide access.

### B. Firestore Security Rules (`firestore.rules`)
- **Default-Deny Base Rule:**
  ```javascript
  match /{document=**} {
    allow read, write: if false;
  }
  ```
- **Owner-Only Document Access:**
  Collections (`inventory`, `recipes`, `documents`, `tasks`, `transactions`, `prospects`, `campaigns`, `profiles`, `messages`) require `request.auth.uid == resource.data.uid`.
- **Integrity Validation:** Prevents mutating `uid` ownership on updates and blocks unauthenticated reads or writes.

### C. Gemini API Key Confinement
- The `GEMINI_API_KEY` is loaded from server environment variables (`process.env.GEMINI_API_KEY`).
- Express route `/api/agent/response` acts as a server proxy. The secret key is never sent to or visible in client browser network inspection.

### D. Real Input Sanitization & Tool Parameter Bounds
- `src/services/realSecurityService.ts` sanitizes prompt text, removes HTML/script injection vectors, and normalizes Unicode.
- Tool parameter schemas (`create_task`, `update_inventory`, `update_finance`) enforce type checks and bounds (e.g., non-negative inventory, maximum values) and prevent prototype pollution (`__proto__`, `constructor`).

---

## 5. RAG (Retrieval-Augmented Generation) Pipeline

When a user submits an inquiry or task to an agent:
1. **Query Tokenization & Scoring:** The prompt is analyzed in `src/services/ragService.ts` for keywords and domain concepts.
2. **Business State Indexing:** Active formulations, raw material stock levels, SOP documentation, and pending tasks are searched.
3. **Dynamic Context Injection:** The top matching snippets are assembled into a structured context block (`--- RETRIEVED RELEVANT BUSINESS KNOWLEDGE ---`) and prepended to the Gemini model prompt.
4. **Tool Execution:** When the model suggests operational actions (`update_inventory`, `create_task`), sanitized parameters are dispatched and executed on the database state.

---

## 6. Build, Deployment, & Environment

### Local Development
```bash
npm install
npm run dev
# Starts server at http://localhost:3000 via tsx
```

### Production Build
```bash
npm run build
# 1. vite build (bundles client SPA into dist/)
# 2. esbuild server.ts --bundle --platform=node --format=cjs --packages=external --sourcemap --outfile=dist/server.cjs
```

### Production Launch
```bash
npm start
# Launches node dist/server.cjs binding host 0.0.0.0 and port 3000
```

---

## 7. Operational Status

- **Build Status:** Verified (Compilation and TypeScript validation: 0 errors)
- **Database Status:** Connected (`ai-studio-c4c38da0-a794-41ac-a866-e0647152f0fa`) with deployed security rules
- **AI Service:** Active via server-side Gemini 2.5 Flash / Pro
- **Production Readiness:** 100% Ready for live business usage and Cloud Run deployment
