# Artisan 2nd Brain: Cloud & Integration Guide

This guide outlines the steps to operate and transition your Artisan 2nd Brain workspace between Sandbox operations, Live cloud databases, and external enterprise API layers.

## 1. Dual-Authentication Flow

Our workspace supports two distinct user entry paths to satisfy preview requirements and live production reliability:

### A. Local Demo Sandbox
- **Access Route:** Click **"Explore Demo Sandbox"** on the landing page.
- **Persistence Method:** Local Storage Cache (fully offgrid).
- **Behavior:** No registration keys required. Restores a rich default profile with simulated active inventory, pre-designed formulation templates, calendar events, and real-time chat histories that persist perfectly to the browser cache.

### B. Live Workspace (SSO Auth)
- **Access Route:** Click **"Access Live Workspace (SSO)"**.
- **Persistence Method:** Live Firestore database synchronizations in real-time.
- **Authentication:** Powered by **Firebase Auth** (Google Single Sign-On).

---

## 2. Real-Time Security & Chat persistence

We have resolved the ephemeral chat bug! The multi-agent conversational engine is bound to a persistent database layer:

### Database Schema Matching (`/firebase-blueprint.json`)
The `messages` table schema verifies secure communication formats:
```json
"Message": {
  "type": "object",
  "properties": {
    "sender": { "type": "string" },
    "content": { "type": "string" },
    "timestamp": { "type": "string" },
    "type": { "type": "string" },
    "createdAt": { "type": "string", "format": "date-time" },
    "uid": { "type": "string" }
  },
  "required": ["sender", "content", "timestamp", "type", "uid"]
}
```

### Security Protection (`/firestore.rules`)
All database access is constrained to secure, verified owners to ensure user privacy:
```javascript
match /messages/{id} {
  allow read: if isAuthenticated() && (resource == null || resource.data.uid == request.auth.uid);
  allow create: if isAuthenticated() && isValidMessage(incoming()) && isValidId(id);
  allow update: if isDocOwner() && isValidMessage(incoming()) && uidNotModified();
  allow delete: if isDocOwner();
}
```

---

## 3. Diamond Lifetime Member Privileges (VIP)

The platform includes hardcoded enterprise logic for our flagship Diamond Tier accounts:
- **Registered User Email:** `mdominique1025@gmail.com`
- **Automatic Upgrades:** When logged in via SSO under this email, standard trials and limitations are bypassed.
- **Visual Integration:** Custom badges across the navigation sidebars (`"Diamond Lifetime"`), subscription panels (`"Active Lifetime Access"`), and profile screens (`"Diamond Lifetime Workshop"`) confirm lifetime billing status without relying on external Stripe query calls.

---

## 4. Security & Governance Architecture

The workspace features an enterprise security and governance stack accessible via the **"Security & Governance"** navigation tab:

### A. Google Cloud Model Armor & ShieldGemma Sandbox
1. **Interactive Probe Sandbox**: In the `Security & Governance` hub, select the *Model Armor* tab to test prompts against simulated threat vectors (system prompt extraction, credential dumping, BOLA probing).
2. **Automated Intercepts**: When a prompt exceeds the risk threshold ($\ge 0.70$), Model Armor blocks execution and logs a unique audit trace identifier.
3. **Redaction Pipeline**: Output responses automatically redact any accidental environment variables or API keys before returning data to the client.

### B. SPIFFE Workload Identities & DPoP Tool Receipts
1. **Attestation Identities**: Each AI specialist operates under an attested SPIFFE identifier (`spiffe://artisan.internal/ns/production/sa/agent-{role}`).
2. **DPoP Cryptographic Proofs**: Tool dispatches (`create_task`, `update_inventory`, `create_asset`, etc.) generate an HMAC-SHA256 signature with an ephemeral nonce and DPoP thumbprint, ensuring that actions cannot be forged, replayed, or altered in transit.

### C. CI/CD Governance & Secret Detection
1. **Automated GitHub Actions**: `.github/workflows/security-governance.yml` executes Gemini CLI and Gitleaks secret scanners on pull requests and commits to prevent accidental credential commits.
2. **Policy-as-Code Firestore Testing**: Automated checks ensure that `firestore.rules` maintain top-level default-deny rules and strict `isOwner` validation across all database collections.

---

## 5. Connecting External Production APIs

For next-phase expansion, integrate the following hooks into your Express web server (`server.ts`):

- **Inventory/Shopify Sync:** Create a webhook endpoint `/api/shopify/order` to automatically update inventory figures whenever raw bases or soaps are purchased.
- **Stripe Billing:** Leverage the `IntegrationHub` configuration to connect secure API tokens on the Cloud Console to let normal standard tiers buy upgrades.

---

## 6. Visual Logistics & Kanban Operations

### A. Supply Line QR Label Tags
In the **Supplies** tab, click the QR icon on any inventory raw material.
1. **Interactive QR Code:** The applet generates a high-contrast QR sticker embedded with a deep link to your specific workspace workspace relative URI.
2. **Batch Check & Traceability:** The sticker display houses real-time estimated physical stock values, SKU identifiers, and a direct query of connected production batch histories.
3. **Printable Stickers:** Click **"Print Physical Sticker"** to bring up a browser print system with double-bordered, high-density label formatting for visual box stickers.
4. **URL Router Auto-Query:** Scanning the label redirects browser focus. On mount, if `itemId` is found in URL queries, the Supplies dialogue automatically slides open to display that raw material's details.

### B. Progression Kanban Board
In the **Production** tab, select any collection and switch from *Series Overview* to the **Production Board**.
1. **Status Board Lanes:** The Board structures batches across five progressive phases: `Raw Material Prep` ➔ `Pouring & Molding` ➔ `Curing Shelf` ➔ `Packaging & Labels` ➔ `Released Stock`.
2. **Step Checklists:** Inside each card, the artisan can tick off specific operational tasks per stage (e.g. ingredient weighing, folding therapeutics, trim/packaging checks).
3. **Drag & Flow Triggers:** Buttons let you shift batches easily up and down stages. Reaching the **Released Stock** phase marks them as fully compliant and ready for trade logistics.

---

## 7. Caching & Dependency Optimization (Troubleshooting)

To ensure high availability and prevent browser loading failures within the AI Studio iFrame and proxy layers, we implemented active caching prevention and dependency optimization rules:

### A. Development Server Asset Caching
In development mode, modern browsers and iFrame containers heavily cache scripts and dynamic chunk files. When Vite re-optimizes dependencies (creating new hashes), the browser may attempt to fetch stale chunk names (e.g., `chunk-QG5TPNJU.js`), triggering a white screen of death.
- **Resolution:** We embedded custom Cache-Control middleware in `server.ts` during development to instruct browsers to bypass the cache:
  ```ts
  res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate");
  ```

### B. Forced Dependency Bundling
By default, Vite dynamically pre-bundles dependencies during active workspace exploration, which causes sudden chunk updates that disrupt active sessions.
- **Resolution:** Added `optimizeDeps: { force: true }` and custom server headers to `vite.config.ts`. This forces Vite to perform complete dependency resolution on dev server boot, ensuring persistent chunk references during hot reloads.

