# Architecture Map: Artisan Workshop Studio

## Current State: Fully Modular Architecture
The application has been fully refactored from its single-file monolith origin, with state management, layout division, and multi-agent systems properly decoupled into specialized directories.

```
/src
├── App.tsx                     # Main layout routing and core tab controller
├── main.tsx                    # Main browser mounting entry point                
├── index.css                   # Global Tailwind CSS definitions (custom themes)
├── types.ts                    # Declared global TypeScript definitions & interfaces
├── constants.ts                # App-wide static mock presets and seed structures
├── firebase.ts                 # Firebase app, Firestore, and Google SSO endpoints
├── context/
│   └── ArtisanContext.tsx      # Unified State Provider (Auth status, DB syncing)
├── features/
│   ├── AgentDiagnostics.tsx    # Neural model health, token telemetry, latency monitors
│   ├── AgentFeatures.tsx       # AI Agent workspaces, system logs, chat prompts
│   ├── COGSHub.tsx             # COGS calculations and formula margin pricing
│   ├── CRMHub.tsx              # Wholesale buyer lookup and relationship tracking
│   ├── CollectionsHub.tsx      # Seasonal lineups, release series, product associations
│   ├── ComplianceHub.tsx       # Safety records, lab requirements, regulatory files
│   ├── DocumentsHub.tsx        # Standard operating procedures, supplier NDAs
│   ├── IntegrationHub.tsx      # Gateway configuration (Stripe, Shopify, Quickbooks)
│   ├── InventoryHub.tsx        # Supplies, soap base additives, packaging stocks
│   ├── LandingPage.tsx         # Modern Neumorphic high-contrast entry interface
│   ├── MarketingHub.tsx        # Managed promotional email and ad campaigns
│   ├── OnboardingForm.tsx      # Initial studio registration walkthrough wizard
│   ├── ProductionHub.tsx       # Active batch curing tracking & product shelf life
│   ├── RecipeLibrary.tsx       # Lye calculations, custom formulations, SAP notes
│   ├── SecurityGovernanceHub.tsx # Model Armor sandbox, SPIFFE credentials, BOLA audit
│   ├── SettingsManager.tsx     # Profile preferences, system resetters
│   ├── SmartNotebook.tsx       # AI-assisted research and laboratory scratchpad
│   ├── SourcingHub.tsx         # Raw material supply suppliers & vendor quotes
│   ├── StudioPlanner.tsx       # Timeline scheduler, workshop events calendar
│   ├── StudioProfile.tsx       # Operational overview and billing indicators
│   ├── SubscriptionManager.tsx # Dynamic billing plan details (Tier boundaries)
│   ├── TaskBoard.tsx           # Multi-agent dispatch boards & checklist items
│   ├── WholesaleHub.tsx        # Large-batch trade pricing and purchase orders
│   └── WorkspaceHub.tsx        # AI orchestration workspace
├── services/
│   ├── agentService.ts         # Client proxy for secure model dispatch
│   ├── agentServiceServer.ts   # Backend multi-agent reasoning engine & Gemini client
│   ├── cryptographicGateway.ts # SPIFFE identities & DPoP HMAC-SHA256 tool signing
│   ├── securityMiddleware.ts   # Google Cloud Model Armor & ShieldGemma classification
│   └── toolSandboxEnclave.ts   # Micro-enclave bounds validation & VPC egress policy
└── utils/
    ├── demoData.ts             # Default mock configurations for sandbox exploration
    └── helper.ts               # Numerical calculators and date normalizers
```

---

## 1. Unified State Provider (`ArtisanContext.tsx`)
Rather than spread states out across dozens of file locations, all core records reside inside a clean, single-point-of-truth React context provider:
- **Dual-Mode Auth (Sandbox vs. SSO):** Detects whether user logged in with Live SSO or chose to local-compile in the Sandbox.
- **Demo state falls back safely** to Client-Side Local Storage cache when auth mode is set to `'demo'`.
- **Live state connects directly** to Firebase Firestore via on-demand syncing.

## 2. Shared Database Layer & Persisted Communications
- **Real-Time Data Streams:** Integrated Firestore connection synchronization via `onSnapshot` for `inventory`, `transactions`, `collections`, `assets`, `tasks`, and `proposed_actions`.
- **Studio Chat Persistence:** We resolved the ephemeral chat bug! The `messages` collection is fully synced to Firebase in Live Mode and saved locally in Demo Mode.
- **Ordering Consistency:** Chat lists are automatically ordered on the Client following Firestore `createdAt` indexes.

## 3. Enterprise Security Architecture & Governance
- **Google Cloud Model Armor & ShieldGemma**: Active pre-invocation pipeline sanitizes prompts (Unicode NFKC, control-byte stripping, credential masking) and evaluates risk scores against prompt injection, data exfiltration, and BOLA probes.
- **Micro-Enclave Tool Execution**: Tool calls are bounds-checked in an isolated parameter validator to eliminate prototype pollution, negative inventory inputs, and malformed structures.
- **Cryptographic SPIFFE Workload Attestation**: All agent specialists receive standard SPIFFE URIs (`spiffe://artisan.internal/ns/production/sa/agent-{role}`).
- **DPoP Double-Bound Tool Receipts**: Outbound tool calls are cryptographically signed with HMAC-SHA256 nonces to guarantee non-repudiation and prevent replay attacks.
- **Repository CI/CD Governance**: GitHub Actions workflow (`security-governance.yml`) executes Gemini CLI secret scanning and validates `firestore.rules` for strict default-deny postures.

## 4. Diamond Lifetime VIP entitlements
- **Special Tier Authentication:** If the user logs in using the registered VIP email (`mdominique1025@gmail.com`), the application automatically bypasses standard trial bounds.
- **Enterprise-Wide Access:** Sets plan level to `'Diamond'`, disables payment options, binds expiryDate of the user to `'Lifetime'`, and adds high-visibility verification across the profile header panels, navigation subtexts, and subscription manager status cards.

## 5. Client Caching & Dependency Architecture
- **No-Cache Server Middleware:** Configured custom Express middleware in `server.ts` to block development asset caching by downstream proxy/CDN caches, avoiding blank screen loading issues during file changes.
- **Forced Dependency Pre-Bundling:** Configured `optimizeDeps: { force: true }` in `vite.config.ts` to pre-bundle third-party imports on startup, stabilizing dynamic dependency chunks and maintaining reference integrity inside the browser iFrame.

