# Weft Sandbox Architecture
## Living Preview System for Dark Factory Artifacts

*Version 1.0 - March 8, 2026*

---

## Overview

The **Weft Sandbox** is an isolated runtime environment that makes Dark Factory-generated components immediately interactive, even before backend integration. It allows customers to *experience* generated UI components - clicking buttons, filling forms, navigating flows - while seeing exactly what each action *would* do when connected to real systems.

**Core Principle:** Generated code should be tangible, not theoretical.

---

## Architecture Components

### 1. Sandbox Container

```
┌─────────────────────────────────────────────────────────┐
│                     WEFT SANDBOX                            │
├─────────────────────────────────────────────────────────┤
│  ┌───────────────────────────────────────────────────┐  │
│  │              ISOLATED IFRAME                           │  │
│  │  ┌───────────────┐ ┌───────────────┐ ┌─────────────┐  │  │
│  │  │  Generated   │ │   Mock Data   │ │ Stub Hooks  │  │  │
│  │  │  Component   │ │   Provider    │ │   Layer     │  │  │
│  │  └───────────────┘ └───────────────┘ └─────────────┘  │  │
│  └───────────────────────────────────────────────────┘  │
├─────────────────────────────────────────────────────────┤
│                   ACTION LOGGER                             │
│  ┌───────────────────────────────────────────────────┐  │
│  │ 10:42:01 │ CLICK    │ Submit Order → POST /api/orders │  │
│  │ 10:42:03 │ RESPONSE │ 201 Created (mock)              │  │
│  │ 10:42:03 │ NAVIGATE │ → /orders/confirmation         │  │
│  └───────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘
```

### 2. Core Systems

#### 2.1 Mock Data Provider

Automatically generates realistic placeholder data based on component schema:

```typescript
interface MockDataProvider {
  // Generate mock data from component schema
  generateFromSchema(schema: ComponentSchema): MockData;
  
  // Allow manual override for specific fields
  override(path: string, value: any): void;
  
  // Reset to auto-generated data
  reset(): void;
  
  // Export current mock data for documentation
  export(): MockDataExport;
}

// Example: Component expects an "Order" entity
// Mock Provider auto-generates:
{
  "order": {
    "id": "ORD-2026-001",
    "customer": "Acme Corp",
    "items": [
      { "sku": "WIDGET-A", "qty": 5, "price": 29.99 },
      { "sku": "GADGET-B", "qty": 2, "price": 149.99 }
    ],
    "total": 449.93,
    "status": "pending"
  }
}
```

#### 2.2 Stub Hooks Layer

Intercepts all component interactions and routes them to mock responses:

```typescript
interface StubHooksLayer {
  // Register an API stub
  registerStub(config: StubConfig): void;
  
  // Intercept fetch/axios calls
  interceptNetwork(): void;
  
  // Log all actions without blocking
  passthrough(action: Action): ActionResult;
}

interface StubConfig {
  method: 'GET' | 'POST' | 'PUT' | 'DELETE';
  endpoint: string;  // e.g., '/api/orders'
  mockResponse: object;
  mockDelay?: number;  // Simulate network latency
  mockStatus?: number; // HTTP status code
}
```

#### 2.3 Action Logger

Records every user interaction with full context:

```typescript
interface ActionLog {
  timestamp: Date;
  actionType: 'CLICK' | 'INPUT' | 'SUBMIT' | 'NAVIGATE' | 'API_CALL';
  element: {
    type: string;      // 'button', 'input', 'link'
    id?: string;
    text?: string;
    selector: string;  // CSS selector for reference
  };
  wouldTrigger: {
    endpoint?: string;
    method?: string;
    payload?: object;
    navigation?: string;
  };
  mockResult: object;
}
```

---

## Integration with Dark Factory

### Generation Flow

```
┌───────────────┐     ┌───────────────┐     ┌───────────────┐
│  User Spec    │────▶│ Dark Factory  │────▶│   Artifact    │
│  "I need an   │     │  Generator    │     │   Bundle      │
│  order form"  │     │               │     │               │
└───────────────┘     └───────────────┘     └───────┬───────┘
                                              │
                                              ▼
┌─────────────────────────────────────────────┐
│              ARTIFACT BUNDLE                │
├───────────────┬───────────────┬─────────────┤
│  Component    │  OpenAPI Spec   │ Weft Config │
│  Code (.tsx)  │  (endpoints)    │ (mocks)     │
└───────────────┴───────────────┴─────────────┘
                       │
                       ▼
┌─────────────────────────────────────────────┐
│              WEFT SANDBOX                   │
│  Renders component with mocks & logging     │
│  Customer clicks "Submit" → sees:           │
│  "Would POST to /api/orders with payload"   │
└─────────────────────────────────────────────┘
```

### Weft Config (Generated per Artifact)

```typescript
// weft.config.ts - Auto-generated by Dark Factory
export const weftConfig: WeftConfig = {
  artifact: {
    id: 'order-form-v1',
    name: 'Order Entry Form',
    generatedAt: '2026-03-08T14:30:00Z',
    intentHash: 'abc123'  // Links to original spec
  },
  
  mockData: {
    customers: [
      { id: 'C001', name: 'Acme Corp', credit: 50000 },
      { id: 'C002', name: 'Globex Inc', credit: 25000 }
    ],
    products: [
      { sku: 'WIDGET-A', name: 'Widget Alpha', price: 29.99, stock: 150 },
      { sku: 'GADGET-B', name: 'Gadget Beta', price: 149.99, stock: 42 }
    ]
  },
  
  apiStubs: [
    {
      method: 'POST',
      endpoint: '/api/orders',
      description: 'Create new order',
      requestSchema: {
        customerId: 'string',
        items: 'OrderItem[]',
        notes: 'string?'
      },
      mockResponse: {
        success: true,
        orderId: 'ORD-{{timestamp}}',
        estimatedDelivery: '{{date+3}}'
      },
      mockStatus: 201
    },
    {
      method: 'GET',
      endpoint: '/api/customers',
      description: 'List available customers',
      mockResponse: '{{mockData.customers}}'
    }
  ],
  
  navigation: {
    onSuccess: '/orders/confirmation',
    onCancel: '/orders'
  }
};
```

---

## Ghost Mechanic Integration

When something breaks, Ghost Mechanic can:

1. **Read the Action Log** - See exactly what the user did
2. **Access the Weft Config** - Understand what *should* happen
3. **Compare Expected vs Actual** - Identify the gap
4. **Propose a Fix** - With full context of original intent

```
┌───────────────┐     ┌───────────────┐     ┌───────────────┐
│  User Report  │────▶│ Ghost Mechanic│────▶│  Proposed Fix │
│ "Submit fails"│     │               │     │               │
└───────────────┘     └───────┬───────┘     └───────────────┘
                        │
                        ▼
              ┌─────────────────────────────┐
              │  CONTEXT AVAILABLE:        │
              │  - Action Log (what user   │
              │    actually clicked)       │
              │  - Weft Config (expected   │
              │    behavior)               │
              │  - Original Intent (from   │
              │    generation spec)        │
              │  - Component Code          │
              └─────────────────────────────┘
```

---

## User Experience Flow

### 1. Generate Component
```
User: "I need an inventory transfer form between warehouses"
Dark Factory: Generates component + weft.config.ts
```

### 2. Preview in Sandbox
```
┌──────────────────────────────────────────────────────────┐
│  DARK FACTORY - Inventory Transfer Form               │
├──────────────────────────────────────────────────────────┤
│  [Code] [Preview] [API Spec] [Download]               │
├──────────────────────────────────────────────────────────┤
│                                                        │
│   ┌────────────────────────────────────────────┐     │
│   │  Inventory Transfer                          │     │
│   │                                              │     │
│   │  From: [Warehouse A      ▼]                  │     │
│   │  To:   [Warehouse B      ▼]                  │     │
│   │                                              │     │
│   │  Product: [Widget Alpha  ▼]                  │     │
│   │  Quantity: [50        ]                      │     │
│   │                                              │     │
│   │         [📦 Transfer]  [Cancel]               │     │
│   └────────────────────────────────────────────┘     │
│                                                        │
├────────────────────── ACTION LOG ──────────────────────┤
│  10:42:15 │ SELECT  │ From: Warehouse A               │
│  10:42:18 │ SELECT  │ To: Warehouse B                 │
│  10:42:22 │ SELECT  │ Product: Widget Alpha            │
│  10:42:25 │ INPUT   │ Quantity: 50                     │
│  10:42:28 │ CLICK   │ Transfer → Would POST to:        │
│          │         │ /api/inventory/transfer          │
│          │         │ Payload: {from: "WH-A", to: "WH-B",│
│          │         │          sku: "WIDGET-A", qty: 50}│
└──────────────────────────────────────────────────────────┘
```

### 3. Export for Integration

The customer gets:
- **Component Code** - Ready to integrate
- **OpenAPI Spec** - All endpoints documented
- **Integration Guide** - Step-by-step wiring instructions
- **Mock Server** - Optional standalone mock server for continued testing

---

## Technical Implementation

### Sandbox Runtime Options

1. **iframe + postMessage** (Recommended)
   - Isolated execution
   - Cross-origin safety
   - Easy action logging via message passing

2. **Web Container (Stackblitz WebContainer API)**
   - Full Node.js environment in browser
   - More powerful but heavier
   - Good for complex artifacts

3. **Server-Side Rendering + Hydration**
   - Pre-render with mock data
   - Hydrate for interactivity
   - Good for performance-sensitive demos

### Key Files (per Artifact)

```
artifact-bundle/
├── component/
│   ├── index.tsx          # Main component
│   ├── types.ts           # TypeScript interfaces
│   └── styles.module.css  # Scoped styles
├── weft/
│   ├── weft.config.ts     # Sandbox configuration
│   ├── mock-data.json     # Auto-generated mock data
│   └── api-stubs.ts       # Mock API implementations
├── docs/
│   ├── openapi.yaml       # API specification
│   └── integration.md     # Integration guide
└── manifest.json          # Artifact metadata
```

---

## Future Enhancements

1. **Visual Diff Mode** - Compare two versions of a component side-by-side
2. **Record & Replay** - Save interaction sequences for testing
3. **A/B Preview** - Show multiple generation variants
4. **Collaboration** - Share sandbox sessions for review
5. **Hot Reload** - Edit code in sandbox, see changes live

---

## Summary

The Weft Sandbox transforms Dark Factory from "code generator" to "working prototype factory." Customers don't just get code—they get an experience they can touch, click, and validate before committing to integration.

Combined with Ghost Mechanic for debugging, this creates a complete self-service loop:

```
Specify → Generate → Preview → Test → Fix → Deploy
   ↑                                        │
   └──────────────────────────────────────────┘
                  Iterate
```

---

*"Code you can touch before you commit."*
— Weft Sandbox
