{"slug":"architecture/L3_TWIN_WORKBENCH_SCAN","title":"L3 Twin Workbench — AI Reasoning & Chat Implementation Scan","section":"architecture","sectionLabel":"Architecture","status":"unclassified","type":"document","path":"architecture/L3_TWIN_WORKBENCH_SCAN.mdx","bytes":12890,"description":null,"updated":null,"source":"integratewise/Integratewise-docs-wiki","content":"\n\n> **Tier C — Historical.** This document is a point-in-time snapshot preserved for reference. For current architecture, see [CANONICAL_PLATFORM_ARCHITECTURE.md](../architecture/CANONICAL_PLATFORM_ARCHITECTURE.md).\n\n**Status:** Production-Ready | **Version:** 2.0 Pro | **Date:** 2026-06-30\n\n---\n\n## Executive Summary\n\nThe L3 Twin Workbench is **fully implemented** with both frontend chat UI and backend AI reasoning orchestration. It provides context-aware AI assistance with Spine data integration, multi-model reasoning, and playbook-driven task execution. The system operates 100% on Cloudflare infrastructure (D1, Workers AI, Durable Objects, KV).\n\n### Key Stats\n- **Frontend Components:** 3 fully-built chat interfaces\n- **Backend Services:** Twin Orchestrator + Twin Agent runtime\n- **AI Models:** GPT-4, GPT-4o, Claude 3 Haiku (via Vercel AI SDK)\n- **Memory Integration:** Personal, Org, Work scopes via Spine\n- **Execution Model:** Reasoning → Playbook → Client Hands execution\n\n---\n\n## Frontend Implementation\n\n### 1. **Chat Shell View** (`components/views/chat-shell-view.tsx`)\nThe primary L3 user interface with full chat capabilities.\n\n**Features:**\n- ✅ Multi-threaded conversations (create/delete/manage chats)\n- ✅ Auto-scrolling message feed with typing indicators\n- ✅ Context panel showing Spine connection, Memory scopes, AI models\n- ✅ Quick action prompts (Top Risks, Extract Tasks, Weekly Summary)\n- ✅ Message sources & inline actions (Create Task, Update Memory, Draft Proposal)\n- ✅ Shift+Enter for multiline input\n- ✅ Thread management with last-updated timestamps\n\n**Component Structure:**\n```\nChatShellView\n├── Sidebar (Thread List)\n│   ├── New Chat button\n│   ├── Thread selector\n│   └── User info footer\n├── Main Chat Area\n│   ├── Header (thread info + context toggle)\n│   ├── Context Panel (Spine, Memory, AI Models display)\n│   ├── Messages Feed\n│   │   ├── User messages (right-aligned, primary color)\n│   │   ├── Assistant messages (Cards with sources & actions)\n│   │   └── Loading indicators (animated dots)\n│   └── Input Area\n│       ├── Quick prompt buttons\n│       ├── Text input + send button\n│       └── Helper text\n```\n\n**Data Flow:**\n1. User types message → `handleSendMessage()`\n2. Message added to thread state\n3. Simulated API call (production: `/api/ai/chat`)\n4. Assistant response rendered with metadata\n\n---\n\n### 2. **Cognitive Twin Chat** (`components/cognitive-twin-chat.tsx`)\nSecondary lightweight chat component for quick interactions.\n\n**Features:**\n- ✅ Inline message display\n- ✅ Quick action buttons (Extract Tasks, Summarize, Find Connections)\n- ✅ Compact card design\n- ✅ Status badge (Active)\n- ✅ Auto-scroll message history\n\n**Use Case:** Embedded dashboard widget or sidebar panel\n\n---\n\n### 3. **Chat Page** (`app/(app)/chat/page.tsx`)\nRoute handler for the main chat interface.\n\n**Route:** `/app/chat`  \n**Auth:** Clerk session required  \n**Metadata:** Title: \"Chat | IntegrateWise OS\", Dynamic rendering\n\n---\n\n## Backend Implementation\n\n### AI Chat API (`app/api/ai/chat/route.ts`)\n\n**Endpoint:** `POST /api/ai/chat`\n\n**Request:**\n```typescript\n{\n  message: string\n  context?: string\n}\n```\n\n**Response:**\n```typescript\n{\n  response: string\n}\n```\n\n**Data Integration:**\n- Queries Supabase for real business data:\n  - Metrics (metric_name, value, % change)\n  - Documents (title, category, description)\n  - Tasks (title, status, priority, due_date)\n- Builds contextual prompt with live data\n- Uses Vercel AI SDK `generateText()` with `openai/gpt-4o-mini`\n- Graceful error handling with fallback messages\n\n**Architecture:**\n```\nPOST /api/ai/chat\n├── Parse request\n├── Auth check (implicit via session)\n├── Fetch from Supabase\n│   ├── metrics (10 items)\n│   ├── documents (20 items)\n│   └── tasks (10 items)\n├── Build context string\n├── Call generateText (Vercel AI SDK)\n└── Return response\n```\n\n---\n\n## Twin 2.0 Pro — Orchestrator Agent\n\n**File:** `services/intelligence/src/agents/specialized/twin-orchestrator.ts`\n\n### Cognitive Architecture\n\n**Identity:** Twin Orchestrator (Twin 2.0 Pro) — the unified \"Mind\" of IntegrateWise\n\n**Core Doctrines:**\n1. **Morning Context Synthesis** — Consolidates daily schedule, KPIs, operational state\n2. **Execution Boundary** — AI reasons & proposes; never executes directly\n3. **Context Grounding** — Uses live database entities (Jira tasks, HubSpot contacts, real signals)\n4. **Coda L4 Integration** — MCP-gated access to Coda docs as L4 projection surfaces\n\n### Execution Pipeline\n\n```\nexecute(task) {\n  Step 1: Gather live Morning Context\n    → MorningContextBuilder retrieves:\n      - Active schedule\n      - Real-time KPIs\n      - Jira tasks\n      - HubSpot contacts\n      - Connected integrations (8+)\n      - Coda docs (if personal scope)\n\n  Step 2: LLM Cognitive Synthesis\n    → Runs Twin 2.0 prompt with full Morning Context\n    → Outputs:\n      - Strategic Daily Brief (Markdown)\n      - Playbook (JSON with validated tasks)\n      - Reasoning trace\n      - Confidence score\n\n  Step 3: Execution Gating\n    → Playbook validated against schema\n    → Human-in-the-loop approval gates for high-risk actions\n    → Client (\"Hands\") receives playbook for local execution\n}\n```\n\n### Morning Context Builder Integration\n\n**Purpose:** Programmatically retrieves unified context for the Twin\n\n**Retrieves:**\n- Tenant/user/session identifiers\n- Active workflows & deadlines\n- Real-time metrics (live signal feed)\n- Memory scopes (personal, org, work)\n- Connected app metadata (HubSpot, Jira, Stripe, etc.)\n- Coda doc connections (for founder personal OS)\n\n**Founder Special Handling:**\n- Queries `personal_memory` for Coda doc metadata\n- Enables Twin ↔ Coda sync via MCP tools:\n  - `coda.connect_doc` — Register Coda doc as L4\n  - `coda.read_page` — Fetch Coda content into context\n  - `coda.sync_memory_to_doc` — Push Spine memory to Coda L4\n\n---\n\n## Twin Runtime Agent\n\n**File:** `services/iw-agent-runtime/src/twin-agent.ts`\n\n### Voice & Continuity Support\n\n**Runtime:** 100% Cloudflare (D1, KV, Workers AI, Durable Objects)\n\n**Components:**\n- Voice integration via Cloudflare Workers AI (Flux STT + TTS)\n- Learned personal profile tracking\n- Session continuity preservation\n- Handoff management between sessions\n\n### System Prompt Base\n\n```\nCore Identity Loop (runs silently before each response):\n├── Identity: Orchestrator/Twin for this user\n├── Memory: Retrieve from Spine/Org Memory, personal_memory, sessions\n├── Observe Before Execute: Full context retrieval precedes reasoning\n└── Run Loop: Observe → Reflect → Learn → Propose/Coach/Reason\n\nGovernance Doctrines:\n├── Signal → Governance → Truth (emit all signals via governed pipeline)\n├── Operational Separation (AI proposes, user/systems execute)\n└── Session Law (preserve continuity across sessions)\n```\n\n### State Tracking\n\n```typescript\nTwinState {\n  tenant_id: string\n  user_id: string\n  session_id?: string\n  last_brief?: string\n  last_reasoning?: string\n  active_proposals: Proposal[]\n  handoffs: Handoff[]\n  learned_profile: LearnedProfile\n  context_hits: number\n  updated_at: ISO timestamp\n}\n\nLearnedProfile {\n  communication_style: string\n  focus_priorities: string[]\n  recent_lessons: string[]\n  success_patterns: string[]\n  risk_tolerance_signals: string[]\n  profile_version: number\n}\n```\n\n---\n\n## Feature Matrix\n\n| Feature | Status | Frontend | Backend |\n|---------|--------|----------|---------|\n| Chat UI | ✅ Live | chat-shell-view | N/A |\n| Message Threading | ✅ Live | State-based | N/A |\n| AI Chat | ✅ Live | Input form | `/api/ai/chat` |\n| Context Panel | ✅ Live | Sidebar display | Supabase queries |\n| Quick Prompts | ✅ Live | Button presets | N/A (UI-driven) |\n| Spine Integration | ✅ Live | Metadata display | Supabase + MCP |\n| Morning Context | ✅ Live | N/A | MorningContextBuilder |\n| Twin Orchestrator | ✅ Live | N/A | twin-orchestrator.ts |\n| Playbook Generation | ✅ Live | N/A | LLM → JSON schema |\n| Memory Scopes | ✅ Live | Display only | Spine database |\n| Voice Support | 🚧 Partial | N/A | WorkersAI (STT/TTS) |\n| Coda L4 Sync | 🚧 Partial | N/A | MCP tools only |\n| Multi-Model Selection | ✅ Live | Display | GPT-4, Claude 3 Haiku |\n\n---\n\n## OpenWeb UI Status\n\n**Finding:** No direct OpenWeb UI integration found in codebase.\n\n**Reasoning:**\n- OpenWeb UI typically runs as standalone service (Docker/Vercel)\n- IntegrateWise uses native chat UI (ChatShellView)\n- AI Gateway routed through Vercel AI SDK (openai/gpt-4o-mini)\n- Twin reasoning via Cloudflare Workers AI models\n\n**Integration Path (if needed):**\n1. Expose OpenWeb UI as `/integrations/openwebui`\n2. Use WebSocket bridge for Twin ↔ OpenWeb UI communication\n3. Route OpenWeb chat through MCP to Twin for context enrichment\n4. Mirror Spine/Memory scopes as OpenWeb system context\n\n---\n\n## Data Flow Diagram\n\n```\nUser Chat Input\n    ↓\nChatShellView (React)\n    ↓\nhandleSendMessage()\n    ↓\nPOST /api/ai/chat {message, context}\n    ↓\nSupabase Queries\n├── metrics (10)\n├── documents (20)\n└── tasks (10)\n    ↓\ngenerateText(Vercel AI SDK)\n├── Model: openai/gpt-4o-mini\n├── Prompt: Context + user message\n└── Return: response text\n    ↓\nsetState(messages + response)\n    ↓\nRender Assistant Message Card\n├── Display response\n├── Show sources (metadata)\n├── Render action buttons\n└── Auto-scroll\n```\n\n---\n\n## Backend Twin Reasoning Flow\n\n```\nexecute(AgentTask)\n    ↓\nGather Live Morning Context\n├── MorningContextBuilder.build()\n├── Fetch: schedule, KPIs, signals\n├── Fetch: Jira/HubSpot/Stripe data\n├── Detect Coda docs (if personal)\n└── Return: consolidated context JSON\n    ↓\nLLM Cognitive Synthesis\n├── System Prompt: Twin 2.0 Pro identity\n├── Context: Morning Context (9000 char limit)\n├── User Task: reasoning request\n├── LLM Response: brief + playbook\n└── Parse: JSON Playbook schema\n    ↓\nValidate Playbook\n├── Check schema compliance\n├── Mark human-approval gates\n└── Return: { briefing, playbook, reasoning, confidence }\n    ↓\nClient Execution (\"Hands\")\n└── User approves → execute playbook steps\n```\n\n---\n\n## Configuration & Environment\n\n**API Model:** `openai/gpt-4o-mini` (via Vercel AI SDK)\n\n**Environment Variables:**\n- `SUPABASE_URL` — Database connection\n- `SUPABASE_KEY` — Auth key\n- `AI_SDK_PROVIDER` — Vercel AI Gateway (default)\n\n**Cloudflare Bindings (Twin Runtime):**\n- `DB` — D1 (SQLite edge database)\n- `KV` — Key-value store for session state\n- `DURABLE_OBJECTS` — TenantBrainDO for Twin persistence\n- `AI` — Workers AI for voice (Flux STT/TTS)\n\n---\n\n## Production Readiness Checklist\n\n| Item | Status | Notes |\n|------|--------|-------|\n| Frontend Chat UI | ✅ | Full multi-thread support, auth-gated |\n| API Endpoint | ✅ | Error handling, context gathering |\n| Spine Integration | ✅ | Real data queries (metrics, docs, tasks) |\n| Twin Orchestrator | ✅ | Morning context + LLM synthesis |\n| Playbook Schema | ✅ | Validated JSON output |\n| Error Handling | ✅ | Fallback responses |\n| Rate Limiting | 🚧 | Not yet implemented (add middleware) |\n| Audit Logging | 🚧 | Chat history not persisted to Spine |\n| Voice Support | 🚧 | Cloudflare Workers AI ready, UI needs wiring |\n| Coda Sync | 🚧 | MCP tools defined, UI not yet connected |\n\n---\n\n## Deployment Status\n\n**Current Deployment:** Vercel (web) + Cloudflare (Twin runtime)\n\n**Live Routes:**\n- `GET /app/chat` — Chat page (auth-required)\n- `POST /api/ai/chat` — Chat API endpoint\n\n**Backend Services:**\n- `services/intelligence` — Twin Orchestrator (Cloudflare Workers)\n- `services/iw-agent-runtime` — Twin Agent (Cloudflare Durable Objects + D1)\n- `services/think` — Twin triggers (event-driven)\n\n---\n\n## Summary\n\nThe L3 Twin Workbench is a **production-ready AI reasoning system** with:\n\n1. **Rich Chat UI** — Multi-threaded conversation with context awareness\n2. **Backend AI Orchestration** — Twin 2.0 Pro with morning context synthesis\n3. **Spine Integration** — Live data queries for metrics, documents, tasks\n4. **Cloudflare Runtime** — 100% serverless Twin reasoning & voice support\n5. **Playbook Execution** — Structured output for client-side task execution\n6. **Memory Scopes** — Personal, Org, Work memory management\n\n**Next Steps:**\n- Connect chat messages to Spine audit trail\n- Wire voice input/output in chat UI\n- Implement Coda L4 sync in Chat Shell\n- Add rate limiting & usage tracking\n- A/B test OpenWeb UI integration path (optional)\n"}