## AI Master Prompt for Rust VM Optimizer MVP
**1. PROJECT OVERVIEW**
**Application Name:** Rust VM Optimizer
**Problem Solved:** Developers often struggle with identifying and optimizing performance bottlenecks in their Rust code, especially when dealing with complex scenarios like tail-call optimization, low-level VM emulation, and advanced compiler features. Existing tools might offer general performance insights but lack specialized capabilities for niche areas like Rust's `become` keyword or specific VM architectures (e.g., Uxn CPU). This leads to suboptimal performance, longer development cycles, and difficulty in achieving peak efficiency.
**Core Value Proposition:** Rust VM Optimizer provides a highly specialized, AI-powered platform for Rust developers to proactively diagnose and resolve performance issues. It offers deep insights into advanced Rust features (like tail-call optimization) and virtual machine performance, delivering actionable, automated recommendations to significantly enhance code efficiency and developer productivity. It aims to be the go-to tool for optimizing performance-critical Rust applications.
**2. TECH STACK**
* **Framework:** Next.js (App Router)
* **Language:** TypeScript
* **Styling:** Tailwind CSS
* **ORM:** Drizzle ORM (PostgreSQL or SQLite compatible)
* **UI Library:** shadcn/ui (for accessible, reusable components)
* **State Management:** React Context API / Zustand (for global state)
* **Authentication:** NextAuth.js (for robust authentication)
* **Database:** PostgreSQL (recommended for production) or SQLite (for development/simplicity)
* **API Layer:** Server Actions / Route Handlers (Next.js App Router)
* **Code Analysis:** Potentially integrate with existing Rust static analysis tools or build custom parsers/analyzers (e.g., using `syn` and `quote` crates if backend analysis is planned, though MVP focuses on frontend analysis and AI suggestions based on user input).
* **AI Integration:** OpenAI API (or similar) for generating optimization suggestions.
* **Charting:** Recharts or Chart.js for visualizing performance metrics.
* **Form Handling:** React Hook Form (optional, can use server actions directly)
**3. DATABASE SCHEMA**
**Users Table:**
* `id`: UUID (Primary Key)
* `name`: VARCHAR(255)
* `email`: VARCHAR(255) (Unique)
* `emailVerified`: TIMESTAMP(6) (Nullable)
* `image`: VARCHAR(255) (Nullable)
* `createdAt`: TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP
* `updatedAt`: TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
**Projects Table:**
* `id`: UUID (Primary Key)
* `userId`: UUID (Foreign Key to Users.id)
* `name`: VARCHAR(255)
* `description`: TEXT (Nullable)
* `createdAt`: TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP
* `updatedAt`: TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
**Analyses Table:**
* `id`: UUID (Primary Key)
* `projectId`: UUID (Foreign Key to Projects.id)
* `codeSnippet`: TEXT (The Rust code submitted for analysis)
* `analysisType`: VARCHAR(100) (e.g., 'tail-call', 'vm-performance', 'general')
* `results`: JSON (Stores structured analysis results, e.g., identified issues, performance metrics, suggestions)
* `generatedSuggestions`: TEXT (Nullable, AI-generated optimization suggestions)
* `status`: VARCHAR(50) DEFAULT 'pending' (e.g., 'pending', 'processing', 'completed', 'failed')
* `createdAt`: TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP
* `completedAt`: TIMESTAMP(6) (Nullable)
**Relations:**
* One-to-Many: `Users` to `Projects`
* One-to-Many: `Projects` to `Analyses`
**4. CORE FEATURES & USER FLOW**
**A. User Authentication:**
* **Flow:** User lands on the homepage. Clicks 'Sign In/Sign Up'. Presented with options (e.g., GitHub, Google, Email/Password via NextAuth.js). Successful authentication redirects to the user dashboard.
* **Edge Cases:** Invalid credentials, email verification (if using email), OAuth callback errors.
**B. Project Management:**
* **Flow:** Authenticated user navigates to 'Projects'. Clicks 'Create New Project'. Enters project name and optional description. Project is saved and listed. User can click on a project to view its analyses or delete it.
* **Edge Cases:** Duplicate project names (handled by UI or DB constraints), deleting a project with existing analyses.
**C. Code Analysis Submission:**
* **Flow:** User selects a project. Navigates to 'New Analysis'. Selects analysis type (e.g., 'Tail-Call Optimization'). Pastes Rust code snippet into a code editor (e.g., Monaco Editor integrated via `react-monaco-editor`). Clicks 'Analyze'. The request is sent to the backend.
* **Backend:** Server Action/Route Handler receives the code and analysis type. Creates an 'Analyses' record with status 'processing'. Initiates the analysis logic (simulated for MVP, real analysis can be complex).
* **Analysis Logic (MVP Simulation):** For 'tail-call', the system might parse the code (simplified AST or regex for keywords) to identify potential tail-call sites or `become` usage. For 'vm-performance', it might look for patterns related to known Uxn CPU operations or provide prompts for manual metric input.
* **AI Suggestion Generation:** Once basic analysis is done, a prompt is sent to the OpenAI API including the code and initial findings. The AI returns optimization suggestions.
* **Update DB:** Analysis record is updated with 'completed' status, results (JSON), and AI suggestions.
* **Edge Cases:** Large code snippets (consider limits), invalid Rust syntax (return error), analysis timeouts, API errors (OpenAI).
**D. View Analysis Results:**
* **Flow:** User navigates to a specific analysis within a project. The UI displays the submitted code snippet, the structured analysis results (e.g., "Potential tail-call site found at line X"), and the AI-generated optimization suggestions. Performance metrics (if any) are displayed using charts.
* **Edge Cases:** Analysis failed, no results found, empty suggestions.
**E. GitHub Integration (Conceptual for MVP, basic implementation):**
* **Flow:** User goes to 'Settings' or 'Project Settings'. Connects GitHub account via OAuth. Allows the app to access repositories. User can trigger analysis on a specific branch/commit via a webhook or a manual button.
* **Backend:** Webhook endpoint receives triggers. Fetches code, initiates analysis, and potentially posts results back to a GitHub commit status or comment.
* **Edge Cases:** GitHub API rate limits, authentication issues, private repositories.
**5. API & DATA FETCHING** (Using Next.js App Router conventions)
* **Server Actions:** For mutations like creating/updating projects, submitting code for analysis.
* `'/api/projects/create'`: POST `(name, description) => Promise<Project>`
* `'/api/analyses/submit'`: POST `(projectId, codeSnippet, analysisType) => Promise<Analysis>`
* **Route Handlers (API Routes):** For fetching data, GitHub webhooks.
* `GET '/api/projects'`: Fetches projects for the logged-in user.
* `GET '/api/projects/[projectId]'`: Fetches a specific project and its analyses.
* `GET '/api/analyses/[analysisId]'`: Fetches a specific analysis result.
* `POST '/api/webhooks/github'`: Handles GitHub webhook events.
* **Data Fetching in Components:** Use Server Components where possible for initial data load. Use client-side fetching (e.g., `fetch` in `useEffect` or libraries like SWR/React Query) for dynamic data or data that updates after initial load, passing data as props from Server Components or fetching within Client Components.
* **Example Request/Response (Submit Analysis):**
* **Request:** `{ projectId: '...', codeSnippet: '...', analysisType: 'tail-call' }`
* **Response (Success):** `{ id: '...', status: 'completed', results: {...}, generatedSuggestions: '...' }`
* **Response (Error):** `{ error: 'Invalid code syntax', details: '...' }`
**6. COMPONENT BREAKDOWN (Next.js App Router)**
* **`app/layout.tsx`:** Root layout (includes `<html>`, `<body>`, global providers, shadcn/ui ThemeProvider).
* **`app/page.tsx`:** Landing Page (Marketing content, features, call to action).
* **`app/(auth)/signin/page.tsx`:** Sign In page.
* **`app/(auth)/signup/page.tsx`:** Sign Up page (if separate).
* **`app/(protected)/dashboard/page.tsx`:** User Dashboard - Overview of projects, recent analyses, quick actions.
* `components/ProjectList.tsx`: Displays user's projects.
* `components/RecentAnalyses.tsx`: Shows recent analysis results.
* **`app/(protected)/projects/[projectId]/page.tsx`:** Project Detail Page - Lists all analyses for a project.
* `components/AnalysisListItem.tsx`: Individual analysis item in the list.
* `components/NewAnalysisButton.tsx`
* **`app/(protected)/analyses/[analysisId]/page.tsx`:** Analysis Results Page.
* `components/CodeViewer.tsx`: Displays submitted code (e.g., using Monaco Editor).
* `components/ResultsDisplay.tsx`: Shows structured analysis findings.
* `components/SuggestionsDisplay.tsx`: Renders AI-generated suggestions.
* `components/PerformanceChart.tsx`: Displays charts (e.g., Recharts).
* **`app/(protected)/settings/page.tsx`:** User Settings Page (Profile, GitHub integration).
* `components/ProfileForm.tsx`
* `components/GitHubConnectButton.tsx`
* **`components/ui/`:** Reusable components from shadcn/ui (Button, Input, Card, Table, Sheet, Dialog, etc.).
* **`components/layout/`:** Navbar, Sidebar, Footer components.
* **`components/loading/`:** Spinner, Skeleton Loaders.
* **`components/forms/`:** Specific form components if needed.
**State Management:** Server Components fetch data directly. Client Components needing dynamic state will use `useState`, `useReducer`, or a global state manager like Zustand for session data, UI state (modals, etc.), and fetched data that doesn't change often.
**7. UI/UX DESIGN & VISUAL IDENTITY**
* **Design Style:** Modern, Clean, Professional, Tech-focused.
* **Color Palette:**
* Primary: Deep Blue (`#1E3A8A` - Indigo-700)
* Secondary: Teal (`#14B8A6` - Teal-500)
* Accent: Light Gray/Off-white (`#F3F4F6` - Gray-100 for background)
* Text: Dark Gray (`#1F2937` - Gray-900)
* Subtle Background: Light Blue/Gray (`#EFF6FF` - Blue-100)
* **Typography:** Sans-serif font like Inter or Poppins for a modern feel. Clear hierarchy using font weights and sizes.
* **Layout:** Sidebar navigation for core sections (Dashboard, Projects, Settings). Main content area displays project details, analyses, etc. Use cards for grouping information. Generous whitespace.
* **Responsiveness:** Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Content adapts fluidly. Tailwind CSS's responsive modifiers (`sm:`, `md:`, `lg:`) will be heavily used.
* **Visual Elements:** Subtle gradients in headers or buttons. Clean icons. Code editor should be well-integrated and readable.
**8. SAMPLE/MOCK DATA**
**User:**
* `{ id: 'uuid-user-1', name: 'Alex', email: 'alex@example.com', image: 'url/to/image.png' }`
**Project:**
* `{ id: 'uuid-proj-1', userId: 'uuid-user-1', name: 'Uxn Emulator Core', description: 'High-performance Uxn CPU emulation', createdAt: 'timestamp', updatedAt: 'timestamp' }`
**Analysis (Tail-Call):**
* `{ id: 'uuid-analysis-1', projectId: 'uuid-proj-1', codeSnippet: 'fn factorial(n: i32) -> i32 {
if n == 0 {
1
} else {
n * factorial(n - 1) // Non-tail call
}
}', analysisType: 'tail-call', status: 'completed', results: { 'issues': [{ 'line': 5, 'message': 'Non-tail recursive call detected. Consider refactoring for optimization.' }] }, generatedSuggestions: 'Refactor the factorial function to use an accumulator pattern for tail-call optimization:
```rust
fn factorial_tailrec(n: i32, acc: i32) -> i32 {
if n == 0 {
acc
} else {
factorial_tailrec(n - 1, n * acc)
}
}
// Initial call: factorial_tailrec(5, 1)
```', createdAt: 'timestamp', completedAt: 'timestamp' }`
**Analysis (VM Performance - conceptual):**
* `{ id: 'uuid-analysis-2', projectId: 'uuid-proj-1', codeSnippet: '// ... VM related code ...', analysisType: 'vm-performance', status: 'completed', results: { 'metrics': { 'instructions_per_sec': 1.5e6, 'avg_cycle_time_ns': 666.6 }, 'observations': ['Instruction decoding loop appears to be a bottleneck.'], 'recommendations': ['Profile instruction decoding logic.', 'Explore alternative instruction encoding strategies.'] }, generatedSuggestions: 'Further analysis of the instruction fetch and decode stages could yield significant improvements. Consider optimizing memory access patterns for instruction cache efficiency.Benchmarking against known efficient VM implementations might reveal further optimization targets.', createdAt: 'timestamp', completedAt: 'timestamp' }`
**Analysis (Pending):**
* `{ id: 'uuid-analysis-3', projectId: 'uuid-proj-1', codeSnippet: '// ... code ...', analysisType: 'tail-call', status: 'pending', results: null, generatedSuggestions: null, createdAt: 'timestamp', completedAt: null }`
**9. TURKISH TRANSLATIONS**
* **App Title:** Rust VM Optimizasyon Aracı (Rust VM Optimizer)
* **Sign In:** Giriş Yap
* **Sign Up:** Kayıt Ol
* **Dashboard:** Kontrol Paneli
* **Projects:** Projeler
* **New Project:** Yeni Proje
* **Analyses:** Analizler
* **New Analysis:** Yeni Analiz
* **Settings:** Ayarlar
* **Analyze:** Analiz Et
* **Code Snippet:** Kod Parçacığı
* **Analysis Type:** Analiz Türü
* **Tail-Call Optimization:** Kuyruk Çağrısı Optimizasyonu
* **VM Performance:** VM Performansı
* **Results:** Sonuçlar
* **Suggestions:** Öneriler
* **Submit:** Gönder
* **Loading...:** Yükleniyor...
* **Completed:** Tamamlandı
* **Pending:** Bekliyor
* **Error:** Hata
* **Project Name:** Proje Adı
* **Description:** Açıklama
* **Save:** Kaydet
* **Cancel:** İptal
* **Connect GitHub:** GitHub Bağla
**10. ANIMATIONS**
* **Page Transitions:** Subtle fade-in/fade-out using Next.js's built-in capabilities or libraries like `Framer Motion` (if needed, keep it minimal for MVP).
* **Button Hovers:** Slight scale-up or background color change on hover (`transition-transform`, `transition-colors` in Tailwind).
* **Loading States:** Use `shadcn/ui`'s `Spinner` or `Skeleton` components with smooth transitions. Loading indicators should be clear and unobtrusive.
* **Chart Interactions:** Tooltips on hover for charts.
* **Form Feedback:** Subtle animations for validation errors or success messages.
**11. EDGE CASES**
* **Authentication:** Handle expired sessions, redirecting to login. Ensure protected routes are properly guarded.
* **Database Errors:** Graceful error handling for DB connection issues or query failures. Display user-friendly error messages.
* **API Errors:** Handle potential errors from external APIs (e.g., OpenAI, GitHub) with informative messages and retry mechanisms where appropriate.
* **Empty States:** Design user-friendly empty states for Projects list, Analyses list, etc., with clear calls to action (e.g., "You haven't created any projects yet. Create one now!").
* **Code Input:** Handle very large code inputs (e.g., truncation or pagination if necessary, though limits are better). Basic syntax validation before submission or clear error reporting from the analysis engine.
* **Analysis Failures:** If an analysis process fails (either custom logic or AI API call), mark the analysis as 'failed' and provide details to the user.
* **Rate Limiting:** Implement exponential backoff or queueing for API calls to OpenAI and GitHub to respect rate limits.
* **Security:** Sanitize all user inputs. Use environment variables for API keys and secrets. Implement appropriate authorization checks for all data access.
* **Code Parser Robustness:** If building custom Rust parsers, ensure they are robust against malformed or incomplete Rust code snippets, providing helpful error messages.