﻿# WizWeb Autonomous Web Studio — Battle-Tested Cloud Architecture Blueprint

> **Autonomous, Multi-Brain, Cloud-Native Web Engineering Studio**
> Deployed at: `D:\xampp\htdocs\wizweb\` | Stack: Node.js (ESM), Vanilla CSS3 (Wizrdom v1.0 Design System), OpenRouter API, Playwright CDP.

---

## 1. Executive Summary

**WizWeb** is an autonomous cloud platform that converts raw human briefs, wireframe sketches, design documents, and technical specifications into production-ready, multi-page web applications.

Unlike fragile, local agent setups tied to desktop processes, WizWeb is built on a **resilient, decoupled Cloud-Native Architecture** featuring:
- **Zero-Dependency Multi-Tier Brain Allocation** via OpenRouter with automatic fallback cascades.
- **Enterprise Role-Based Access Control (RBAC)** separating Superadmin, Architect, Developer, and Viewer personas.
- **In-Dashboard Live Preview & Code Inspector** with multi-device responsive toggling (1440px / 768px / 375px) and live code persistence.
- **Strict Human-in-the-Loop Approval Gate** ensuring 100% architectural alignment before code generation.
- **Real Visual Quality Assurance** with Playwright browser screenshot grounding and CDP console error detection.
- **Zero-Dependency Native Packaging** using pure JavaScript ZIP generation.

---

## 2. End-to-End System Architecture

``mermaid
flowchart TD
    User([User / Browser Dashboard]) -->|HTTPS / REST & SSE| AuthGateway[WizWeb Auth & RBAC Gateway]
    
    subgraph RBAC_Tiers [Security & Role Access]
        AuthGateway -->|ENV Check| SuperAdmin[Superadmin: Root Access]
        AuthGateway -->|PBKDF2 Hash| Architect[Architect: Build & Route]
        AuthGateway -->|PBKDF2 Hash| Developer[Developer: Inspect & Edit Code]
        AuthGateway -->|PBKDF2 Hash| Viewer[Viewer: Read-Only Projects]
    end

    subgraph Dashboard_UI [Wizrdom v1.0 Single-Page Application]
        SuperAdmin --> UserMgmt[User Management Section]
        SuperAdmin --> VaultModal[OpenRouter Key & Balance Vault]
        Architect --> IntakePanel[Multi-Asset Intake: Brief, Images, PDFs, MD]
        Architect --> ModelOrch[Model Routing Orchestrator]
        Developer --> CodeInspector[In-Dashboard Live Preview & Code Inspector]
        Viewer --> ProjectLibrary[Project Archive & Live Previews]
    end

    subgraph Engine_Backend [WizWeb Cloud Engine: server.js]
        IntakePanel -->|POST /api/pipeline/start| Runner[FSM Pipeline Runner: runner.js]
        ModelOrch -->|POST /api/models| ConfigStore[(models.json)]
        UserMgmt -->|POST /api/users/*| UserStore[(users.json)]
        CodeInspector -->|POST /api/pipeline/save-file| SiteDir[projects/:slug/site/*]
        Runner -->|Direct REST Stream| OpenRouter[OpenRouter Cloud API Engine]
    end

    subgraph Visual_QA_Subsystem [Visual Grounding]
        Runner -->|Ephemeral Server| PlaywrightEyes[Playwright CDP Visual Engine]
        PlaywrightEyes -->|1440px / 375px Screenshots| QAFolder[projects/:slug/qa/]
        QAFolder -->|Multimodal Visual Input| OpenRouter
    end

    subgraph Output_Deliverables [Production Artifacts]
        SiteDir -->|Pure JS Deflate| ZipEngine[Zero-Dependency zip.js]
        ZipEngine -->|1-Click Download| DownloadArchive[projects/:slug/site.zip]
    end
``

---

## 3. The 5-Stage Lifecycle & Human Gate Flow

The WizWeb Finite State Machine (FSM) moves through 5 discrete, fully audited stages:

``mermaid
sequenceDiagram
    autonumber
    actor Arch as Architect / Superadmin
    actor Dev as Developer
    participant FSM as FSM Runner (runner.js)
    participant OR as OpenRouter API Cascades
    participant Disk as Project Filesystem
    participant QA as Playwright Visual Eyes

    Note over Arch,Disk: Stage 0: Multi-Asset Intake
    Arch->>FSM: Submit Text Brief + Mockups + Spec Files
    FSM->>Disk: Ingest into /projects/YYYY-MM-DD-[slug]/inputs/
    
    Note over FSM,OR: Stage 1: Product Specification (web-spec)
    FSM->>OR: Synthesize Functional Specs (Tier-1 Model)
    OR-->>FSM: 01-product-spec.md
    FSM->>Disk: Persist Specification

    Note over FSM,OR: Stage 2: Architectural Review (web-review)
    FSM->>OR: Adversarial Review & Edge Cases (Tier-2 Model)
    OR-->>FSM: 02-reviewed-spec.md
    FSM->>Disk: Persist Hardened Spec

    Note over FSM,Arch: HUMAN-IN-THE-LOOP APPROVAL GATE
    FSM->>FSM: PAUSE State: AWAITING_APPROVAL
    FSM-->>Arch: Present Diff & Review Spec in Dashboard
    Arch->>FSM: Sign Approval & Optional Amendments
    FSM->>Disk: State Updated: SPEC_APPROVED

    Note over FSM,OR: Stage 3: Build Plan & Decomposition (web-build-plan)
    FSM->>OR: Generate Multi-Page Component Breakdown (Tier-1 Model)
    OR-->>FSM: 03-build-plan.md
    FSM->>Disk: Persist Build Plan

    Note over FSM,OR: Stage 4: Multi-Page Code Generation (web-builder)
    FSM->>OR: Generate index.html, about.html, css/style.css, js/app.js (Coding Model)
    OR-->>FSM: Complete Source Code
    FSM->>Disk: Write /site/ Directory Files

    Note over FSM,QA: Stage 5: Visual Verification (Playwright Eyes & web-qa)
    FSM->>QA: Spin Ephemeral Server & Capture 1440px / 375px Screenshots + CDP Logs
    QA-->>Disk: desktop-preview.png, mobile-preview.png, console-errors.json
    FSM->>OR: Visual Quality Audit (Multimodal Model)
    OR-->>FSM: 05-qa-notes.md + Quality Verdict
    FSM->>Disk: State: COMPLETED (Auto-trigger pure JS ZIP build)

    Note over Dev,Disk: In-Dashboard Live Code Inspection
    Dev->>Disk: Inspect Code & Modify Files Live (/api/pipeline/save-file)
    Disk-->>Dev: Hot-Reload Responsive Iframe (Desktop / Tablet / Mobile)
``

---

## 4. Role-Based Access Control (RBAC) Matrix

WizWeb enforces strict, enterprise-grade access boundaries across four distinct roles:

| Privilege / Action | Superadmin | Architect | Developer | Viewer |
| :--- | :---: | :---: | :---: | :---: |
| **Credential Storage** | Strictly in .env | config/users.json (PBKDF2) | config/users.json (PBKDF2) | config/users.json (PBKDF2) |
| **Manage Users & Passwords** | ✅ Full Access | ❌ Forbidden | ❌ Forbidden | ❌ Forbidden |
| **OpenRouter Vault & Credits**| ✅ Full Access | ❌ Forbidden | ❌ Forbidden | ❌ Forbidden |
| **Configure Model Cascade** | ✅ Full Access | ✅ Full Access | ❌ Forbidden | ❌ Forbidden |
| **Build & Run New Pipelines** | ✅ Full Access | ✅ Full Access | ❌ Forbidden | ❌ Forbidden |
| **Approve Human Gate Specs** | ✅ Full Access | ✅ Full Access | ❌ Forbidden | ❌ Forbidden |
| **In-Dashboard Code Inspector**| ✅ Full Access | ✅ Full Access | ✅ Full Access | 🔒 Read-Only |
| **Live Code Editing & Saving** | ✅ Full Access | ✅ Full Access | ✅ Full Access | ❌ Forbidden |
| **View Projects & Previews** | ✅ Full Access | ✅ Full Access | ✅ Full Access | ✅ Full Access |
| **Delete Project Archives** | ✅ Full Access | ❌ Forbidden | ❌ Forbidden | ❌ Forbidden |

### Security Isolation Guarantees
- **Superadmin credentials** (SUPERADMIN_USERNAME, SUPERADMIN_PASSWORD) are **never stored in the database or JSON files**. They are injected solely through environment variables.
- **Standard users** are stored in App/config/users.json with high-iteration **PBKDF2-SHA512** salts and hashes.
- **Future M365 SSO Bridge:** Modularized in App/engine/auth.js so Phase 2 can map Microsoft Entra ID / M365 JWT claims (oles) directly into the WizWeb permission matrix without altering dashboard logic.

---

## 5. In-Dashboard Live Preview & Code Inspector

``mermaid
flowchart LR
    Dev([Developer / Architect]) -->|Select Project| TreeView[Project File Tree]
    TreeView -->|Click File| EditorPane[Code Editor: HTML / CSS / JS / MD]
    EditorPane -->|Edit Code| LiveBuffer[Live Editing Buffer]
    LiveBuffer -->|Click Save File / Ctrl+S| APISave[POST /api/pipeline/save-file]
    APISave -->|Persist to Disk| SiteDisk[(projects/:slug/site/*)]
    SiteDisk -->|Trigger Frame Reload| ResponsiveFrame[Live Preview Iframe]
    
    subgraph Viewport_Controls [Responsive Viewport Toggles]
        DesktopBtn[Desktop: 1440px]
        TabletBtn[Tablet: 768px]
        MobileBtn[Mobile: 375px]
    end
    
    Viewport_Controls -->|Resize Container| ResponsiveFrame
``

### Inspector Capabilities:
1. **Interactive File Tree:** Access all generated assets (index.html, bout.html, css/style.css, js/app.js, specifications, and build logs).
2. **Real-Time Code Editor:** Monospace syntax-styled editor with line indicators, unsaved modification tracking, and Ctrl+S shortcuts.
3. **Responsive Viewport Toggles:**
   - 💻 **Desktop Viewport:** 1440 × 900 px
   - 📱 **Tablet Viewport:** 768 × 1024 px
   - 📲 **Mobile Viewport:** 375 × 812 px
4. **Instant Hot-Reload:** Saving any file automatically refreshes the preview iframe without browser caching delays.
5. **Role-Enforced Locks:** Viewers have a locked, read-only editor with disabled save actions.

---

## 6. Multi-Asset Input Specification

WizWeb supports rich multi-modal intake to eliminate ambiguity:

| Input Category | Supported Formats | Storage Destination | Processing & Engine Injection |
| :--- | :--- | :--- | :--- |
| **Core Text Brief** | Plain text, Prompt strings | inputs/brief.md | Injected into all 5 agent system prompts. |
| **Visual References**| .png, .jpg, .jpeg, .webp | inputs/[filename] | Encoded as base64 data URIs and passed to multimodal models. |
| **Design Specifications** | .md, .txt, .json | inputs/[filename] | Read verbatim into prompt context as ground-truth design tokens. |
| **Requirements / Docs** | .pdf | inputs/[filename] | Text extracted and indexed in inputs-manifest.json. |

---

## 7. The 5 Architectural Pillars

### Pillar I: Zero-Trust Security Architecture
1. **No Hardcoded Credentials:** Superadmin credentials live exclusively in .env.
2. **PBKDF2 Password Protection:** Database passwords use 10,000-iteration PBKDF2 with SHA-512 and 16-byte random salts.
3. **Path Traversal Shield:** All file read and save endpoints use strict path normalization (path.resolve) and assert that requested paths start with the authorized root.
4. **Session Expiry:** Cryptographically random 256-bit session tokens auto-expire after 24 hours.

### Pillar II: Unbreakable Reliability & State Persistence
1. **Atomic FSM Transitions:** Pipeline states (INIT, SPEC_DRAFTED, AWAITING_APPROVAL, SPEC_APPROVED, BUILT, COMPLETED) are written synchronously to 
otes/pipeline-state.json.
2. **Automatic Failover Cascades:** Every pipeline stage defines primary, secondary, and tertiary model fallbacks in config/models.json. If an upstream model is rate-limited (HTTP 429) or times out (HTTP 504), failover triggers in under 500ms.
3. **Zero-Dependency Native Packaging:** engine/zip.js builds standard ZIP archives using native Node zlib Deflate, requiring zero external npm dependencies.

### Pillar III: Multi-Tier Brain Allocation
Model assignments are optimized according to task cognitive requirements:
- **Tier 1 (Reasoning / Planning):** deepseek/deepseek-r1 or nthropic/claude-3.7-sonnet with thinking budgets.
- **Tier 2 (Review / Adversarial Analysis):** nthropic/claude-3.5-sonnet or openai/gpt-4o.
- **Tier 3 (Code Synthesis):** nthropic/claude-3.7-sonnet or meta-llama/llama-3.3-70b-instruct.
- **Tier 4 (Visual QA):** openai/gpt-4o or google/gemini-2.0-flash.

### Pillar IV: Real Visual Verification (Playwright Robot Eyes)
1. Runs an ephemeral HTTP server on an isolated port serving the site/ directory.
2. Captures full-page desktop (1440 × 900) and mobile (375 × 812) PNGs.
3. Attaches CDP listeners to log unhandled JavaScript exceptions, network 404s, and CSS layout issues.
4. Feeds screenshots and console traces back into the QA model for multimodal verification.

### Pillar V: Human-in-the-Loop Approval Gate
Between Stage 2 (Review) and Stage 3 (Build Plan), execution halts. The project owner reviews  2-reviewed-spec.md, inputs custom amendments if necessary, and clicks **Approve Spec**. Only an authenticated Architect or Superadmin can unlock the gate.

---

## 8. Canonical Project Storage Tree

``text
D:\xampp\htdocs\wizweb/
├── Dockerfile                           # Production cloud container definition
├── docker-compose.yml                   # 1-command cloud orchestration
├── .env.example                         # Environment configuration template
├── .env                                 # Secrets & Superadmin credentials (gitignored)
├── .dockerignore
├── Docs/
│   └── readme.md                        # Architecture Blueprint, RBAC Matrix & Docs
├── projects/                            # Active and Completed Project Workspaces
│   └── YYYY-MM-DD-[slug]/
│       ├── inputs/                      # Brief and raw reference assets
│       │   ├── brief.md
│       │   ├── inputs-manifest.json
│       │   ├── wireframe.png
│       │   └── requirements.md
│       ├── notes/                       # Markdown specifications and FSM state
│       │   ├── 01-product-spec.md
│       │   ├── 02-reviewed-spec.md
│       │   ├── 03-build-plan.md
│       │   ├── 04-implementation-log.md
│       │   ├── 05-qa-notes.md
│       │   ├── build.log                # Real-time event log
│       │   └── pipeline-state.json      # FSM persistence file
│       ├── qa/                          # Visual verification screenshots & CDP logs
│       │   ├── desktop-preview.png
│       │   ├── mobile-preview.png
│       │   └── console-errors.json
│       ├── site/                        # Production website files
│       │   ├── index.html
│       │   ├── about.html
│       │   ├── css/style.css
│       │   └── js/app.js
│       └── site.zip                     # Pure JS generated deployment package
└── App/                                 # Standalone Dashboard & Backend
    ├── index.html                       # Wizrdom v1.0 Admin Dashboard SPA
    ├── package.json                     # Scripts & metadata
    ├── server.js                        # Native REST server, SSE stream & static host
    ├── smoke-test.js                    # Automated verification test suite
    ├── config/
    │   ├── models.json                  # Model routing & failover configuration
    │   └── users.json                   # PBKDF2 salted credentials database
    ├── css/
    │   └── wizrdom.css                  # Wizrdom Product Design System v1.0
    ├── js/
    │   └── app.js                       # UI controller, SSE listener, Code Inspector & RBAC
    └── engine/
        ├── auth.js                      # PBKDF2 hash, session manager & RBAC engine
        ├── openrouter.js                # Resilient OpenRouter client with failovers
        ├── playwright-eyes.js           # Ephemeral server & screenshot capturer
        ├── runner.js                    # 5-stage FSM pipeline orchestrator & logger
        └── zip.js                       # Zero-dependency pure JS ZIP generator
``

---

## 9. REST & SSE API Reference

| Method | Endpoint | Authorized Roles | Description |
| :--- | :--- | :---: | :--- |
| **Authentication** | | | |
| POST | /api/auth/login | Public | Authenticates credentials; returns 24-hr session token & permissions |
| GET | /api/auth/session | Authenticated | Verifies active session token and user profile |
| POST | /api/auth/logout | Authenticated | Revokes current session token |
| **User Management** | | | |
| GET | /api/users | Superadmin | Lists all database users (passwords omitted) |
| POST | /api/users | Superadmin | Creates a new user (architect, developer, viewer) |
| DELETE| /api/users/:id | Superadmin | Permanently deletes a user |
| POST | /api/users/:id/password | Superadmin | Resets user password with PBKDF2 re-hash |
| **Model & Vault Management** | | | |
| GET | /api/models | Superadmin, Architect | Reads current 5-stage model routing table (models.json) |
| POST | /api/models | Superadmin, Architect | Updates model routing and failover cascades |
| GET | /api/openrouter/models | Superadmin, Architect | Searches and filters the live OpenRouter model catalog |
| GET | /api/openrouter/vault | Superadmin | Queries API key validity, credit balance, and latency |
| **Pipeline & Project Operations** | | | |
| GET | /api/projects | All Roles | Lists all projects with their current FSM status |
| POST | /api/pipeline/start | Superadmin, Architect | Creates project with multi-asset intake; executes Stages 1 & 2 |
| POST | /api/pipeline/approve | Superadmin, Architect | Approves Human Gate spec; executes Stages 3, 4, 5 |
| GET | /api/pipeline/status?projectId=:id | All Roles | Returns live FSM state of a project |
| GET | /api/pipeline/logs?projectId=:id | All Roles | Returns recent build logs from 
otes/build.log |
| GET | /api/pipeline/events?projectId=:id | All Roles | **Server-Sent Events (SSE)** real-time live log stream |
| GET | /api/pipeline/download?projectId=:id| All Roles | Downloads generated site.zip package |
| GET | /api/pipeline/file?projectId=:id&file=:path | All Roles | Reads project source files, specs, and logs |
| POST | /api/pipeline/save-file | Superadmin, Architect, Developer | **Saves modified code file** to project site/ directory |
| DELETE| /api/projects/:id | Superadmin | Deletes project directory permanently |
| GET | /preview/:projectId/index.html | All Roles | Direct browser preview of the generated website |

---

## 10. Quickstart & Deployment Guide

### Option 1: Standalone Node.js (Local / VPS)
`powershell
cd "D:\xampp\htdocs\wizweb\App"
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="sk-or-v1-your-key-here"
node server.js
`
- Open: **http://localhost:3050**
- Default Superadmin: dmin / WizWebAdmin2026!

### Option 2: Docker Container (Cloud Production)
`ash
cd "D:\xampp\htdocs\wizweb"
cp .env.example .env
# Edit .env with your OpenRouter API key and Superadmin credentials
docker compose up -d --build
`
- Container exposes port 3050 mapped to host http://localhost:3050.

### Option 3: XAMPP Apache
Start Apache from XAMPP Control Panel and navigate to:
**http://localhost/wizweb/App/**

---

## 11. Automated Verification & Smoke Tests

WizWeb includes a comprehensive 7-point automated verification test suite:

`ash
cd "D:\xampp\htdocs\wizweb\App"
node smoke-test.js
`

### Verification Output:
`	ext
=================================================
🧪 WIZWEB CLOUD STUDIO - SYSTEM SMOKE TEST v2.0
=================================================

[Test 1] Checking models.json integrity...
✅ Config OK: 5 stages configured with failover trees.

[Test 2] Testing RBAC Authentication & Session Management...
✅ Superadmin Auth OK: Identified 'admin' with root privileges.
✅ Developer Auth OK: Verified Code Editing=TRUE, Build Sites=FALSE.
✅ Viewer Auth OK: Verified strict Read-Only mode.
✅ User Management CRUD OK: Created & deleted ephemeral user.

[Test 3] Testing multi-asset intake (brief + mock image + md file)...
✅ Intake OK: Verified inputs saved in projects/YYYY-MM-DD-[slug]/inputs

[Test 4] Testing real-time event logger...
✅ Logging OK: Captured log lines in notes/build.log.

[Test 5] Testing Human Approval Gate state transitions...
✅ Human Gate OK: State paused at AWAITING_APPROVAL and unlocked to SPEC_APPROVED.

[Test 6] Testing Multi-Page Site generation & Live File Editing...
✅ Multi-Page & File Editing OK: Generated index.html, about.html, css/style.css and verified live edits.

[Test 7] Testing 1-Click ZIP Packaging...
✅ ZIP Exporter OK: Generated valid archive (magic: 504b0304).

=================================================
🎉 ALL 7 SYSTEM SMOKE TESTS PASSED CLEANLY!
=================================================
`

---

## 12. Phase 2 Roadmap: Microsoft 365 / Entra ID SSO Bridge

The native PBKDF2 authentication engine in App/engine/auth.js is pre-structured for seamless enterprise SSO:

``mermaid
flowchart LR
    User([Corporate User]) -->|Login Request| AzureAD[Microsoft Entra ID / M365]
    AzureAD -->|OIDC / OAuth 2.0 PKCE| CallbackEndpoint[/api/auth/m365/callback]
    CallbackEndpoint -->|Validate JWT & Claims| TokenValidator[MSAL / JWT Validator]
    TokenValidator -->|Map Security Groups / App Roles| RBACRouter{Role Mapper}
    
    RBACRouter -->|'WizWeb-Architects'| ArchitectRole[Assign Role: architect]
    RBACRouter -->|'WizWeb-Developers'| DeveloperRole[Assign Role: developer]
    RBACRouter -->|'WizWeb-Viewers'| ViewerRole[Assign Role: viewer]
    
    ArchitectRole --> WizWebSession[Issue 24-hr WizWeb Session]
    DeveloperRole --> WizWebSession
    ViewerRole --> WizWebSession
``

- **Environment Flags:** M365_SSO_ENABLED=true, AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET.
- **Zero Schema Disruption:** The issued WizWeb session payload remains identical, allowing the frontend UI to operate without any breaking changes.