# Keak Docs Full-text index of all documentation pages, intended for LLM consumption. /docs/ai-infrastructure/database/telemetry/keak-code # Keak-Code Telemetry DB The Keak-Code IDE tracks every AI generation session to measure variant quality, understand user behavior, and link generated variants to production experiments. This document explains how data flows through the system. ## System Architecture ``` ┌─────────────────────────────────────────────────────────────────────────────┐ │ KEAK-CODE IDE (Electron) │ │ ┌─────────────────────────┐ ┌──────────────────────────────────────┐ │ │ │ use-cro-telemetry.ts │ │ use-keafab-generator.ts │ │ │ │ (drawer open/close) │ │ (generation lifecycle) │ │ │ └───────────┬─────────────┘ └───────────────────┬──────────────────┘ │ │ │ │ │ │ └──────────────────┬───────────────────┘ │ │ ▼ │ │ ┌─────────────────────────┐ │ │ │ telemetryService.ts │ │ │ └───────────┬─────────────┘ │ └────────────────────────────────┼────────────────────────────────────────────┘ │ HTTP ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ │ DASHBOARD (Next.js) │ │ /app/api/telemetry/* endpoints │ └────────────────────────────────┼────────────────────────────────────────────┘ │ Supabase Client ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ │ TELEMETRY DATABASE (Supabase) │ │ Separate instance from Dashboard database │ │ (TELEMETRY_SUPABASE_URL) │ └─────────────────────────────────────────────────────────────────────────────┘ ``` The telemetry database is a **dedicated Supabase instance**, separate from the main Dashboard database. The API endpoints live in the Dashboard codebase (`/app/api/telemetry/*`), but write to this separate database via `TELEMETRY_SUPABASE_URL`. ## The User Journey ### 1. User Clicks an Element When a user clicks an element in the preview to open the CRO drawer, the `use-cro-telemetry.ts` hook initializes telemetry: ``` User clicks element │ ▼ ┌─────────────────────────────────┐ │ startSession(projectId) │ → Creates session record (or reuses existing) └─────────────────┬───────────────┘ ▼ ┌─────────────────────────────────┐ │ lookupChat(projectId, keakId) │ → Check if conversation exists for this element └─────────────────┬───────────────┘ │ ┌───────┴───────┐ │ │ Found Not Found │ │ Resume trackChatStart() │ │ │ ├── element_selector │ ├── original_code │ └── source (file context) │ │ └───────┬───────┘ ▼ setChatId() → Ready for generation ``` **Key behavior**: Chats use UPSERT on `(project_id, keak_id)`. The same element always resumes the same conversation, even across different sessions. ### 2. User Submits a Prompt When the user submits a prompt to generate a variant, `use-keafab-generator.ts` orchestrates the telemetry: ``` User submits prompt │ ▼ ┌─────────────────────────────────────────────────────────┐ │ Determine generation_type: │ │ • INITIAL → first prompt in conversation │ │ • RETRY → user clicked retry button │ │ • FOLLOWUP → user submitted follow-up instructions │ └─────────────────────────────────┬───────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────┐ │ If previous variant exists, mark its outcome: │ │ • Retry → trackVariantRetry() → REPLACED │ │ • Followup → trackVariantFollowup() → SKIPPED │ └─────────────────────────────────┬───────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────┐ │ trackGenerationStart() │ │ Records BEFORE the LLM call: │ │ • chatId, sessionId │ │ • userPrompt, generationType │ │ • screenshotUrl, mediaUrls │ └─────────────────────────────────┬───────────────────────┘ │ ▼ Call KeaFab API │ ▼ ┌─────────────────────────────────────────────────────────┐ │ trackGenerationComplete() │ │ Records AFTER the LLM responds: │ │ • durationMs, inputTokens, outputTokens │ │ • llm_response (analysis + changes) │ │ AND creates a new variant record │ └─────────────────────────────────────────────────────────┘ ``` **Why two phases?** Recording start time separately allows accurate duration measurement even if the LLM call fails. ### 3. User Previews the Variant Each time the generated code is rendered in the preview iframe: ``` trackVariantPreview(variantId, newCode) │ ├── Increment preview_count ├── Set first_previewed_at (if first time) ├── Update last_previewed_at │ └── Compare newCode vs original variant_code │ ┌───────┴───────┐ │ │ Same Different │ │ Stay PENDING Set EDITED has_edits: true final_code: newCode ``` **Edit detection**: The system automatically detects when users modify the generated code before accepting. ### 4. User Takes Final Action ``` ┌──────────────────┬────────────────────┬─────────────────────────┐ │ Action │ Endpoint │ Outcome Set │ ├──────────────────┼────────────────────┼─────────────────────────┤ │ Accept variant │ /variants/accept │ ACCEPTED │ │ Give feedback │ /variants/feedback │ (sets feedback field) │ │ Clear chat │ /chats/clear │ CLEARED (non-terminal) │ └──────────────────┴────────────────────┴─────────────────────────┘ ``` Note: `/chats/clear` only affects variants NOT already in `REPLACED` or `ACCEPTED` states. ### 5. Launch as Experiment (Optional) When a variant is deployed as a Dashboard A/B test: ```typescript telemetry.linkVariantToExperiment(variantId, experimentId) ``` This sets `experiment_id` on the variant, linking it to the Dashboard `tests` table. ## Variant Lifecycle State Machine ``` ┌──────────────┐ │ PENDING │ ← Created on generation complete └──────┬───────┘ │ ┌──────────────────────┼──────────────────────┐ │ │ │ ▼ ▼ ▼ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ EDITED │ │ ACCEPTED │ │ REPLACED │ │ (preview with │ │ (user applied │ │ (user clicked │ │ code edits) │ │ to codebase) │ │ retry) │ └────────┬────────┘ └─────────────────┘ └─────────────────┘ │ │ ▼ ▼ ┌─────────────────┐ ┌─────────────────┐ │ ACCEPTED │ │ SKIPPED │ │ (accept after │ │ (followup) │ │ editing) │ └─────────────────┘ └─────────────────┘ ┌─────────────────┐ │ CLEARED │ ← Chat cleared (only for PENDING/EDITED) └─────────────────┘ ``` ## Database Schema ### sessions Tracks work periods within the IDE. | Column | Type | Description | |--------|------|-------------| | `id` | uuid | Primary key | | `project_id` | uuid | Associated project | | `user_id` | uuid | Authenticated user | | `created_at` | timestamptz | Session start | ### chats Element-specific conversations, keyed by `(project_id, keak_id)`. | Column | Type | Description | |--------|------|-------------| | `id` | uuid | Primary key | | `project_id` | uuid | Associated project | | `keak_id` | text | Element identifier (injected into DOM) | | `element_selector` | text | CSS selector for the element | | `original_code` | text | Original element HTML/JSX | | `created_at` | timestamptz | Chat creation | **Unique constraint**: `(project_id, keak_id)` - enables UPSERT pattern. ### source\_code File context snapshots, deduplicated by content. | Column | Type | Description | |--------|------|-------------| | `id` | uuid | Primary key | | `chat_id` | uuid | FK → chats.id | | `path` | text | File path in project | | `code` | text | Full source content | | `created_at` | timestamptz | Capture time | ### generations LLM request records with two-phase lifecycle. | Column | Type | Description | |--------|------|-------------| | `id` | uuid | Primary key | | `chat_id` | uuid | FK → chats.id | | `session_id` | uuid | FK → sessions.id | | `user_prompt` | text | User's instruction | | `generation_type` | enum | INITIAL, RETRY, FOLLOWUP | | `llm_model` | text | Model identifier | | `model_tier` | text | Pricing tier | | `screenshot_url` | text | Captured screenshot | | `media` | text\[] | Additional media URLs | | `duration_ms` | integer | Generation time (set on complete) | | `input_tokens` | integer | Prompt tokens (set on complete) | | `output_tokens` | integer | Response tokens (set on complete) | | `llm_response` | text | Raw response (set on complete) | | `created_at` | timestamptz | Start time | ### variants Generated code with outcome tracking. | Column | Type | Description | |--------|------|-------------| | `id` | uuid | Primary key | | `generation_id` | uuid | FK → generations.id | | `chat_id` | uuid | FK → chats.id | | `experiment_id` | integer | FK → Dashboard tests.id | | `variant_code` | text | Original generated code | | `final_code` | text | Code after user edits | | `has_edits` | boolean | Whether user modified code | | `validation_score` | integer | Code validation score | | `outcome` | enum | PENDING, EDITED, ACCEPTED, REPLACED, CLEARED, SKIPPED | | `feedback` | enum | LIKE, DISLIKE, or null | | `preview_count` | integer | Number of previews | | `first_previewed_at` | timestamptz | First preview | | `last_previewed_at` | timestamptz | Last preview | | `created_at` | timestamptz | Creation time | | `updated_at` | timestamptz | Last update | ## API Reference All endpoints require authentication and are prefixed with `/api/telemetry`. **Client**: These endpoints are called by `telemetryService.ts` in the Keak-Code IDE (`keak-code/src/renderer/src/services/telemetryService.ts`). ### Sessions | Endpoint | Method | Description | |----------|--------|-------------| | `/sessions/create` | POST | Create session for project | ### Chats | Endpoint | Method | Description | |----------|--------|-------------| | `/chats/lookup` | GET | Find chat by `projectId` + `keakId` | | `/chats/start` | POST | Create/upsert chat with element context | | `/chats/clear` | POST | Mark non-terminal variants as CLEARED | ### Generations | Endpoint | Method | Description | |----------|--------|-------------| | `/generations/start` | POST | Record generation start (returns `generationId`) | | `/generations/complete` | POST | Update metrics + create variant (returns `variantId`) | ### Variants | Endpoint | Method | Description | |----------|--------|-------------| | `/variants/lookup` | GET | Get latest variant for chat | | `/variants/update` | PATCH | Generic field update | | `/variants/preview` | POST | Track preview + detect edits | | `/variants/accept` | POST | Mark as ACCEPTED | | `/variants/retry` | POST | Mark as REPLACED | | `/variants/followup` | POST | Mark as SKIPPED | | `/variants/feedback` | POST | Set LIKE/DISLIKE feedback | ## Notes - This database is **separate from the Dashboard database** (different Supabase instance) - All timestamps use `timestamptz` (timezone-aware) - UUIDs are generated server-side with `gen_random_uuid()` - The `desktop_projects` table in Dashboard DB corresponds to `project_id` here --- /docs/ai-infrastructure/keafab/ # KeaFab API Documentation KeaFab is Keak's AI-powered **Conversion Rate Optimization (CRO) variant generation API**. It takes UI components and generates optimized variants designed to improve conversion metrics. ## What is KeaFab? KeaFab is a specialized AI service that: - **Analyzes UI components** using vision models to understand visual hierarchy and content - **Routes to specialized optimizers** based on component type (hero, nav, pricing, etc.) - **Generates CRO-optimized variants** with copy, layout, and style improvements - **Validates output** to ensure code quality and constraint compliance Unlike generic LLM prompts, KeaFab uses domain-specific CRO expertise encoded into specialized agents, each trained on conversion optimization best practices for their component type. ## Why Specialized CRO AI? Generic AI models can rewrite code, but they lack: 1. **CRO Domain Knowledge** - Understanding of conversion psychology, awareness levels, friction points 2. **Component-Specific Strategies** - Hero sections need different optimization than pricing tables 3. **Constraint Awareness** - Preserving `data-keak-id` attributes, component references, and assets 4. **Selection Intent Matching** - Adjusting change scope based on what the user selected KeaFab solves these by routing to **6 specialized optimizers**, each with CRO expertise for their component type. ## High-Level Architecture ```mermaid flowchart LR subgraph Inputs SC[Screenshot] CODE[Component Code] PRMPT([User Prompt]) end ROUTER[Router] subgraph Optimizers HERO[Hero] NAV[Nav] PRICING[Pricing] SOCIAL[Social Proof] FORM[Form] FEAT[Feature Section] end VALIDATOR[Validator] OUT[Variant] SC --> ROUTER CODE --> ROUTER PRMPT -.-> ROUTER ROUTER -->|hero| HERO ROUTER -->|nav| NAV ROUTER -->|pricing| PRICING ROUTER -->|social_proof| SOCIAL ROUTER -->|form| FORM ROUTER -->|feature_section| FEAT HERO --> VALIDATOR NAV --> VALIDATOR PRICING --> VALIDATOR SOCIAL --> VALIDATOR FORM --> VALIDATOR FEAT --> VALIDATOR VALIDATOR --> OUT ``` **Three-Phase Pipeline:** | Phase | Agent | Model | Purpose | |-------|-------|-------|---------| | 1 | Router | GPT-4.1-nano | Classify component type (hero, nav, pricing, etc.) | | 2 | Optimizer | Gemini-3-flash | Generate CRO-optimized variant with vision analysis | | 3 | Validator | Claude-Haiku-4.5 | Check constraints and fix violations | ## Key Features ### Specialized Optimizers Six component-specific optimizers, each with CRO expertise: | Optimizer | Focus Areas | |-----------|-------------| | **Hero** | Awareness levels, copy audit, friction reduction, CTA optimization | | **Nav** | Link hierarchy, CTA prominence, label clarity | | **Pricing** | Plan anchoring, comparison clarity, value framing | | **Form** | Field reduction, label optimization, trust signals | | **Social Proof** | Attribution, specificity, credibility | | **Feature Section** | Feature→benefit reframing, scannability | ### Real-Time Streaming Server-Sent Events (SSE) provide progress updates during generation: ``` router → "Classifying component..." optimizer → "Optimizing hero..." validator → "Validating constraints..." complete → Final variant delivered ``` ### Constraint Validation KeaFab uses a two-stage validation pipeline: **1. Heuristic Detection** (`validation.py`) Fast regex-based checks that detect common issues: - HTML syntax in JSX (`class=` instead of `className`) - HTML event handlers (`onclick` instead of `onClick`) - HTML string styles (`style="..."` instead of `style={{}}`) - HTML comments (`` instead of `{/* */}`) - Missing or duplicated `data-keak-id` - Unbalanced tags **2. AI Validator** (only if issues detected) Full validation against 11 constraints: - `data-keak-id` preserved exactly once on root element - All `data-*` attributes maintained - Valid JSX syntax with balanced tags - No placeholder content - Original assets preserved - JSX syntax enforced (className, onClick, htmlFor) - JSX style objects (not string styles) - JSX comments (`{/* */}`) ## Documentation Structure | Page | Description | |------|-------------| | [Architecture](./architecture) | Deep dive into the 3-phase pipeline and design decisions | | [API Reference](./api-reference) | Endpoints, schemas, and usage examples | | [Optimizers](./optimizers) | How specialized optimizers work | | [DSPy Signatures](./dspy-signatures) | AI model integration and prompt engineering | | [Client Integration](./client-integration) | How Keak-Code integrates with KeaFab | ## Quick Example **Request:** ```json { "full_page": "
The best solution for your needs
\n \nEnterprise teams ship faster with our automated deployment platform
\n \nJoin 500+ enterprise teams
\n{error}
}