## AI Master Prompt: Code Guardian MVP Generation
### PROJECT OVERVIEW:
**App Title:** Code Guardian
**Concept:** Code Guardian is a cutting-edge SaaS platform designed to combat the rise of 'slop' – low-quality, mindlessly generated AI content, specifically focusing on code. The application analyzes AI-generated code snippets based on economic incentives driving good code: cheaper generation, easier maintenance, faster feature delivery, and long-term reliability. It provides developers, tech leads, and organizations with tools to assess, score, and improve the quality and maintainability of AI-assisted code. By promoting adherence to best practices and economic viability, Code Guardian aims to foster a healthier, more sustainable software development ecosystem, ensuring that AI coding tools contribute to producing robust, efficient, and cost-effective software, rather than just faster, but ultimately more expensive, low-quality output.
**Value Proposition:** Ensure your AI-generated code is not just fast, but also high-quality, cost-effective, and maintainable in the long run. Gain confidence in your AI coding tools by verifying their output against economic and best-practice standards. Reduce technical debt and accelerate reliable feature delivery.
**Problem Solved:** Addresses the growing concern of "slop" in AI-generated code, where rapid generation may compromise quality, leading to increased technical debt, higher maintenance costs, and slower long-term development velocity. It provides an objective, economically-driven evaluation of code quality beyond simple linting.
### TECH STACK:
* **Framework:** Next.js (App Router)
* **UI Library:** shadcn/ui (built with Tailwind CSS)
* **Styling:** Tailwind CSS
* **Language:** TypeScript
* **Database:** PostgreSQL (with Drizzle ORM)
* **Authentication:** NextAuth.js (for robust authentication, supporting email/password, Google, GitHub)
* **State Management:** React Context API / Zustand (for global state)
* **Form Handling:** react-hook-form
* **Validation:** Zod
* **API Layer:** Server Actions (Next.js App Router) / tRPC (optional for advanced typesafe APIs)
* **Deployment:** Vercel (recommended)
### DATABASE SCHEMA (Drizzle ORM - PostgreSQL):
```typescript
// schema.ts
import { pgTable, uuid, text, timestamp, integer, boolean, pgEnum } from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
// User Authentication
export const users = pgTable('users', {
id: uuid('id').primaryKey(),
name: text('name'),
email: text('email').notNull().unique(),
emailVerified: timestamp('emailVerified', { mode: 'date' }),
image: text('image'),
createdAt: timestamp('createdAt', { mode: 'date' }).defaultNow(),
updatedAt: timestamp('updatedAt', { mode: 'date' }).defaultNow(),
});
export const accounts = pgTable('accounts', {
id: uuid('id').primaryKey(),
userId: uuid('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
type: text('type').$type< 'oauth' | 'email'>().notNull(),
provider: text('provider').notNull(),
providerAccountId: text('providerAccountId').notNull(),
refresh_token: text('refresh_token'),
access_token: text('access_token'),
expires_at: integer('expires_at'),
token_type: text('token_type'),
scope: text('scope'),
id_token: text('id_token'),
session_state: text('session_state'),
});
export const sessions = pgTable('sessions', {
sessionToken: text('sessionToken').primaryKey(),
userId: uuid('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
expires: timestamp('expires', { mode: 'date' }).notNull(),
});
export const verificationTokens = pgTable('verificationTokens', {
identifier: text('identifier').notNull(),
token: text('token').notNull(),
expires: timestamp('expires', { mode: 'date' }).notNull(),
}).primaryKey(identifier, token);
// Core Application Data
export const projects = pgTable('projects', {
id: uuid('id').primaryKey(),
userId: uuid('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
name: text('name').notNull(),
createdAt: timestamp('createdAt', { mode: 'date' }).defaultNow(),
updatedAt: timestamp('updatedAt', { mode: 'date' }).defaultNow(),
});
export const codeSnippets = pgTable('codeSnippets', {
id: uuid('id').primaryKey(),
projectId: uuid('projectId').notNull().references(() => projects.id, { onDelete: 'cascade' }),
source: text('source').notNull(), // e.g., 'upload', 'git', 'ide'
fileName: text('fileName'),
language: text('language'), // e.g., 'javascript', 'python'
rawCode: text('rawCode').notNull(),
analysisResult: jsonb('analysisResult'), // Store structured analysis data
qualityScore: integer('qualityScore'), // 0-100
createdAt: timestamp('createdAt', { mode: 'date' }).defaultNow(),
updatedAt: timestamp('updatedAt', { mode: 'date' }).defaultNow(),
});
// --- Relations ---
export const usersRelations = relations(users, ({ many }) => ({
projects: many(projects),
}));
export const projectsRelations = relations(projects, ({ one, many }) => ({
user: one(users, { fields: [projects.userId],'].'user' }),
codeSnippets: many(codeSnippets),
}));
export const codeSnippetsRelations = relations(codeSnippets, ({ one }) => ({
project: one(projects, { fields: [codeSnippets.projectId],'].'project' }),
}));
// Analysis configuration (example, can be extended)
export const analysisConfigs = pgTable('analysisConfigs', {
id: uuid('id').primaryKey(),
userId: uuid('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
projectId: uuid('projectId').references(() => projects.id, { onDelete: 'set null' }), // Global or project-specific
configName: text('configName').notNull(),
// Store specific rules, weights, thresholds etc.
// This could be a JSONB field or separate tables for complex rules
rules: jsonb('rules'),
createdAt: timestamp('createdAt', { mode: 'date' }).defaultNow(),
updatedAt: timestamp('updatedAt', { mode: 'date' }).defaultNow(),
});
// Add indexes for performance
// ... create indexes on foreign keys and frequently queried fields
// Dummy JSONB type for example
// import { JSONB } from 'k-jsonb';
// analysisResult: JSONB('analysisResult').default(JSONB.NULL),
// rules: JSONB('rules').default(JSONB.NULL),
```
### CORE FEATURES & USER FLOW:
**1. User Authentication & Management:**
* **Flow:** User lands on the homepage. Clicks 'Sign Up' or 'Login'. Presented with options: Email/Password, Google OAuth, GitHub OAuth. Upon successful authentication, user is redirected to their dashboard. User can access 'Settings' to manage profile, subscription, and API keys.
* **Details:** Implement NextAuth.js. Secure password handling (hashing). Session management via JWT or database sessions.
**2. Project Creation & Management:**
* **Flow:** Authenticated user navigates to 'Projects'. Clicks 'New Project'. Enters project name. Project is created and listed. User can view, edit, or delete projects.
* **Details:** Uses `projects` table. Basic CRUD operations via Server Actions. Project names should be unique per user.
**3. Code Snippet Upload & Analysis:**
* **Flow:** User selects a project. Clicks 'Upload Code Snippet' or 'Analyze from IDE/Git'. Uploads a file (e.g., `.js`, `.py`) or pastes code directly. Selects analysis configuration (default or custom). Submits for analysis. Analysis is performed asynchronously. Results are displayed on the snippet's detail page.
* **Details:** Handles file uploads (multipart/form-data). Basic language detection. Triggers analysis function (can be a separate microservice or internal function).
**4. Code Quality Analysis Engine:**
* **Flow (Internal):** Receives raw code. Detects language. Applies a series of checks based on the selected configuration:
* **Readability:** Line length, cyclomatic complexity (using libraries like `escomplex` for JS), function length, code structure.
* **Maintainability:** Variable naming conventions, commenting density, code duplication (simple checks), modularity.
* **Performance Potential:** Identification of anti-patterns (e.g., inefficient loops, unnecessary computations) - *this is heuristic and not a full profiler.*
* **Economic Factors:** Simplicity score (subjective, based on complexity and dependencies), estimated maintenance effort (based on complexity and length).
* **Best Practice Adherence:** Checks against common style guides (e.g., ESLint rules if JS/TS), common framework idioms.
* **Details:** This is the core logic. Can be implemented using AST (Abstract Syntax Tree) parsers (e.g., Babel, Acorn for JS) and specialized libraries. Output is structured JSON. A scoring algorithm aggregates these checks into a final score (0-100).
**5. Results Visualization & Reporting:**
* **Flow:** User views the analysis results for a snippet. Sees an overall quality score. A dashboard highlights key metrics (e.g., Complexity: High, Readability: Medium). Detailed breakdown with explanations and suggestions for improvement. Option to download a PDF report.
* **Details:** Use charting libraries (e.g., Chart.js, Recharts) for visualization. Present findings clearly with actionable advice.
**6. IDE/Git Integration (MVP Scope):**
* **Flow (IDE - VS Code):** Install extension. Authenticate with Code Guardian. Select code in editor -> Right-click -> 'Analyze with Code Guardian'. Analysis runs in the background. Results shown as a comment or in a side panel.
* **Flow (Git):** Connect GitHub repository. Configure webhook for pull requests. When a PR is opened/updated, Code Guardian analyzes new/modified code. Results are posted as a PR comment.
* **Details:** Requires developing a VS Code extension and setting up GitHub webhooks. MVP might focus on one integration type initially (e.g., manual upload + basic Git integration).
### API & DATA FETCHING:
* **Approach:** Primarily use Next.js Server Actions for mutations (CRUD operations) and protected API routes (for complex or non-form-related actions).
* **Authentication:** All API routes and Server Actions must be protected and check user authentication.
* **Data Fetching:** Use `fetch` within Server Components or Route Handlers. For client-side data fetching, consider libraries like SWR or React Query if needed, but prioritize Server Components and Server Actions for MVP.
* **Example API Routes/Server Actions:
* `POST /api/projects` (Server Action): Create a new project. Body: `{ name: string }`. Returns: `{ project: Project }`.
* `POST /api/projects/[projectId]/snippets` (Server Action): Upload code snippet. Body: `FormData` containing `file` or `code`, `source`, `language`. Returns: `{ snippet: CodeSnippet }`.
* `GET /api/projects/[projectId]/snippets/[snippetId]` (Route Handler): Get snippet details and analysis. Returns: `{ snippet: CodeSnippetWithAnalysis }`.
* `GET /api/users/me/projects` (Route Handler): Get user's projects. Returns: `Project[]`.
* **Error Handling:** Implement consistent error handling. Return meaningful error messages and status codes.
### COMPONENT BREAKDOWN (Next.js App Router):
* **(App) Layouts & Pages:**
* `app/(marketing)/layout.tsx`: Marketing site layout.
* `app/(marketing)/page.tsx`: Landing Page.
* `app/(marketing)/pricing/page.tsx`: Pricing Page.
* `app/(auth)/layout.tsx`: Auth pages layout (login, signup).
* `app/(auth)/login/page.tsx`: Login Page.
* `app/(auth)/signup/page.tsx`: Sign Up Page.
* `app/(auth)/reset-password/page.tsx`: Password Reset Page.
* `app/(app)/layout.tsx`: Main application layout (dashboard, sidebar, header).
* `app/(app)/dashboard/page.tsx`: User Dashboard overview (recent projects, recent analyses).
* `app/(app)/projects/page.tsx`: List of user's projects.
* `app/(app)/projects/[projectId]/page.tsx`: Project detail page (list of snippets).
* `app/(app)/projects/[projectId]/snippets/[snippetId]/page.tsx`: Code snippet analysis result page.
* `app/(app)/settings/page.tsx`: User settings page.
* `app/(app)/settings/billing/page.tsx`: Billing/Subscription management.
* `app/(app)/settings/integrations/page.tsx`: API keys and Integration settings.
* **(UI) Components (`components/ui/*` using shadcn/ui):
* `Button`, `Input`, `Card`, `Form`, `Dialog`, `DropdownMenu`, `Table`, `Alert`, `Progress`, `Badge`, `Avatar`, `Tabs`, `Sheet` (for mobile sidebar/settings).
* **(Feature) Components (`components/features/*`):
* `AuthButtons`: Login/Signup/User menu buttons.
* `ProjectList`: Renders a list of projects (e.g., using `Table` or `Card` components).
* `ProjectForm`: Modal/Page for creating/editing projects.
* `SnippetUploadForm`: Form for uploading code files or pasting text.
* `CodeEditor`: Embedded code editor (e.g., Monaco Editor, CodeMirror) for pasting code.
* `AnalysisResultCard`: Displays summary of analysis results.
* `DetailedAnalysis`: Component showing breakdown of metrics, charts, suggestions.
* `CodeViewer`: Displays code snippets with syntax highlighting.
* `MetricsTable`: Table to display various quality metrics.
* `SettingsForm`: Form for user profile updates.
* `SubscriptionManager`: Component to display/manage subscription plans.
* `IntegrationConnectors`: Buttons/forms to connect GitHub, etc.
* **State Management:**
* `app/providers.tsx`: Global providers (Auth, Theme, QueryClient).
* Context API or Zustand for managing global state like user authentication status, theme settings.
* Component-level state for forms, modals, and local UI interactions.
### UI/UX DESIGN & VISUAL IDENTITY:
* **Design Style:** Minimalist Clean with subtle gradient accents and modern typography.
* **Color Palette:**
* Primary (Dark background variant): `#1A1D24` (Deep Navy/Near Black)
* Secondary (Slightly lighter background): `#2A2F3A` (Charcoal Gray)
* Accent (Primary action color): `#4F46E5` (Vibrant Indigo/Purple)
* Accent Hover/Gradient: `#8B5CF6` (Lighter Purple)
* Text (Primary): `#E5E7EB` (Light Gray)
* Text (Secondary): `#9CA3AF` (Muted Gray)
* Success/Green: `#22C55E`
* Warning/Yellow: `#F59E0B`
* Error/Red: `#EF4444`
* **Typography:**
* Headings: Inter (Variable Font, weights 600-800)
* Body Text: Inter (Variable Font, weights 400-500)
* Code Font: Fira Code or Source Code Pro (Monospaced)
* **Layout:**
* Dashboard/App Area: Sidebar on the left (collapsible), main content area on the right. Clean cards, clear hierarchy.
* Marketing Pages: Standard sections, clear CTAs, focus on value proposition.
* Use `max-w-7xl` or similar for content width, with responsive adjustments.
* **Visual Elements:** Subtle use of gradients in buttons, headers, or backgrounds. Clean icons. Focus on data visualization clarity.
* **Responsive Rules:** Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Content adjusts fluidly. Use Tailwind's responsive prefixes (`sm:`, `md:`, `lg:`, `xl:`).
### ANIMATIONS:
* **Page Transitions:** Subtle fade-in/fade-out transitions between pages (using Next.js `app/` router features or a library like `Framer Motion`).
* **Component Transitions:** Smooth appearance/disappearance for elements like modals, dropdowns, tooltips (default from shadcn/ui).
* **Hover Effects:** Subtle scale or background color changes on interactive elements (buttons, links).
* **Loading States:** Use spinners (`lucide-react` icons) or skeleton loaders (`react-loading-skeleton`) for data fetching and asynchronous operations. Integrate with Tailwind CSS for consistent styling.
* **Chart Animations:** Simple, non-intrusive animations for data visualizations (e.g., bars rising, lines drawing).
### EDGE CASES:
* **Authentication:** Handle expired sessions, token refresh, multiple login attempts, unauthorized access gracefully.
* **Empty States:** Design clear and helpful empty states for dashboards, project lists, snippet lists when no data is available. Include CTAs to guide users (e.g., "Create your first project").
* **Form Validation:** Implement real-time validation using Zod and react-hook-form for all user inputs (login, signup, project names, settings). Provide clear error messages next to fields.
* **API Errors:** Catch API errors (network issues, server errors) and display user-friendly messages. Implement retry mechanisms where appropriate.
* **File Uploads:** Handle large file uploads (consider chunking or limits), invalid file types, upload failures.
* **Analysis Failures:** If the analysis engine encounters an error (e.g., unsupported language, syntax error in code), report this clearly to the user without crashing the app.
* **Rate Limiting:** Implement rate limiting on API endpoints to prevent abuse.
* **Permissions:** Ensure users can only access and modify their own projects and data.
### SAMPLE/MOCK DATA:
**1. User:**
```json
{
"id": "clxzy8r3e0000abc123def",
"name": "Alice Developer",
"email": "alice@example.com",
"image": "https://example.com/alice.jpg"
}
```
**2. Project:**
```json
{
"id": "clxzy8r3e0000xyz789uvw",
"userId": "clxzy8r3e0000abc123def",
"name": "AI Code Refactoring Initiative",
"createdAt": "2024-03-15T10:00:00Z"
}
```
**3. Code Snippet (Pre-Analysis):**
```json
{
"id": "clxzy8r3e00001a2b3c4d5",
"projectId": "clxzy8r3e0000xyz789uvw",
"source": "upload",
"fileName": "utils.js",
"language": "javascript",
"rawCode": "function processData(data) {\n let result = [];\n for(var i=0; i<data.length; i++){ \n if(data[i].value > 10) { \n result.push(data[i].name.toUpperCase()); \n }\n }\n return result;\n}",
"createdAt": "2024-03-15T10:05:00Z"
}
```
**4. Code Snippet (Post-Analysis):**
```json
{
"id": "clxzy8r3e00001a2b3c4d5",
"projectId": "clxzy8r3e0000xyz789uvw",
"source": "upload",
"fileName": "utils.js",
"language": "javascript",
"rawCode": "function processData(data) {\n let result = [];\n for(var i=0; i<data.length; i++){ \n if(data[i].value > 10) { \n result.push(data[i].name.toUpperCase()); \n }\n }\n return result;\n}",
"analysisResult": {
"readability": {"score": 60, "details": "Variable 'i' could be more descriptive. Consider using map/filter."},
"maintainability": {"score": 55, "details": "Use of 'var' is discouraged. Function length is acceptable."},
"performancePotential": {"score": 70, "details": "Loop is basic, potential for optimization if data set is very large, but generally acceptable."},
"economicScore": {"score": 65, "details": "Code is relatively simple but uses older syntax. Maintenance effort is moderate."},
"bestPractices": {"score": 75, "details": "Uses ES5 syntax. Consider ES6+ features like 'let', 'const', arrow functions, and array methods."}
},
"qualityScore": 65,
"createdAt": "2024-03-15T10:05:00Z",
"updatedAt": "2024-03-15T10:15:00Z"
}
```
**5. Analysis Configuration:**
```json
{
"id": "clxzy8r3e0000cfg678def",
"userId": "clxzy8r3e0000abc123def",
"projectId": null, // Global config
"configName": "Default JavaScript Analysis",
"rules": {
"maxLineLength": 100,
"requireConstLet": true,
"discourageVar": true,
"complexityThreshold": 10,
"enableDuplicationCheck": false
}
}
```
**6. Git Integration Settings:**
```json
{
"id": "clxzy8r3e0000git123def",
"userId": "clxzy8r3e0000abc123def",
"projectId": "clxzy8r3e0000xyz789uvw",
"githubToken": "********", // Store securely encrypted
"webhookSecret": "********", // Store securely encrypted
"autoAnalyzePRs": true
}
```
**7. User Subscription:**
```json
{
"id": "clxzy8r3e0000sub456def",
"userId": "clxzy8r3e0000abc123def",
"plan": "pro", // 'free', 'basic', 'pro', 'enterprise'
"stripeCustomerId": "cus_123abc",
"isActive": true,
"currentPeriodEnd": "2025-03-15T10:00:00Z"
}
```
**TURKISH TRANSLATIONS (for UI elements):**
* **App Title:** Code Guardian
* **Login:** Giriş Yap
* **Sign Up:** Kayıt Ol
* **Dashboard:** Kontrol Paneli
* **Projects:** Projelerim
* **New Project:** Yeni Proje
* **Upload Code:** Kod Yükle
* **Analyze:** Analiz Et
* **Code Snippet:** Kod Parçacığı
* **Quality Score:** Kalite Puanı
* **Analysis Results:** Analiz Sonuçları
* **Settings:** Ayarlar
* **Billing:** Faturalandırma
* **Integrations:** Entegrasyonlar
* **Save:** Kaydet
* **Cancel:** İptal
* **Loading...:** Yükleniyor...
* **Error:** Hata
* **Success:** Başarılı
* **View Details:** Detayları Gör
* **Edit:** Düzenle
* **Delete:** Sil
* **No projects found:** Henüz proje oluşturmadınız.
* **Get started:** Başlayın
* **Analyze AI Code:** Yapay Zeka Kodunu Analiz Edin
* **Enter project name:** Proje adını girin
* **Paste code here:** Kodu buraya yapıştırın
* **Upload file:** Dosya yükle
* **Analysis Configuration:** Analiz Ayarları
* **Default:** Varsayılan
* **Custom:** Özel
* **Metrics:** Metrikler
* **Details:** Detaylar
* **Suggestions:** Öneriler
* **Connect GitHub:** GitHub'ı Bağla
* **Sync Repository:** Depoyu Senkronize Et
* **Analyze Pull Requests:** Pull Request'leri Analiz Et
* **Subscription Plan:** Abonelik Planı
* **Upgrade Plan:** Plan Yükselt
* **Readability:** Okunabilirlik
* **Maintainability:** Sürdürülebilirlik
* **Performance:** Performans
* **Economic Viability:** Ekonomik Değer
* **Best Practices:** İyi Pratikler
* **High:** Yüksek
* **Medium:** Orta
* **Low:** Düşük