PROJECT OVERVIEW:
The application, named 'SpecSync', is a SaaS platform designed to bridge the gap between natural language software specifications and structured code. It addresses the problem highlighted in the Hacker News post 'Reports of code's death are greatly exaggerated', specifically the tension between intuitive English specifications and the precision required for reliable software development. As AI tools increasingly allow 'vibe coding' (generating code from English descriptions), the risk of 'vibe leaks' – unexpected bugs and scaling issues arising from imprecise abstractions – grows. SpecSync analyzes English specifications, identifies potential ambiguities, inconsistencies, and scaling risks, and proactively suggests structured data schemas and code drafts (e.g., Drizzle ORM schemas, Next.js API routes, React component templates). Its core value proposition is to enhance the reliability and scalability of AI-assisted development by providing a layer of rigorous analysis and structured output, empowering developers and product managers to iterate more confidently and effectively.
TECH STACK:
- **Frontend Framework:** Next.js (App Router)
- **UI Library:** shadcn/ui (for pre-built, accessible components)
- **Styling:** Tailwind CSS (for utility-first styling)
- **State Management:** React Context API / Zustand (for global state, e.g., user authentication, fetched data)
- **ORM:** Drizzle ORM (PostgreSQL or SQLite)
- **Database:** PostgreSQL (preferred for scalability) or SQLite (for local development/simplicity)
- **Authentication:** NextAuth.js (for secure user authentication)
- **AI Integration:** OpenAI API (or similar LLM provider) for spec analysis and code generation.
- **Form Handling:** React Hook Form with Zod for validation.
- **Deployment:** Vercel (recommended)
DATABASE SCHEMA (PostgreSQL):
1. **users Table:**
* `id` (UUID, primary key)
* `name` (VARCHAR(255))
* `email` (VARCHAR(255), unique)
* `emailVerified` (TIMESTAMP(6))
* `image` (VARCHAR(255))
* `createdAt` (TIMESTAMP(6), default NOW())
* `updatedAt` (TIMESTAMP(6))
2. **specs Table:** (Represents user-submitted specifications)
* `id` (UUID, primary key)
* `userId` (UUID, foreign key to users.id, indexed)
* `title` (VARCHAR(255), not null)
* `content` (TEXT, not null)
* `analysisResult` (JSONB) - Stores structured results from AI analysis (e.g., identified risks, ambiguities, suggested schemas).
* `generatedSchema` (JSONB) - Stores the generated Drizzle ORM schema.
* `generatedCodeSnippets` (JSONB) - Stores generated code drafts (e.g., API routes, component stubs).
* `createdAt` (TIMESTAMP(6), default NOW())
* `updatedAt` (TIMESTAMP(6))
3. **projects Table:** (Optional, for organizing multiple specs)
* `id` (UUID, primary key)
* `userId` (UUID, foreign key to users.id, indexed)
* `name` (VARCHAR(255), not null)
* `description` (TEXT)
* `createdAt` (TIMESTAMP(6), default NOW())
* `updatedAt` (TIMESTAMP(6))
*Relations:* A user can have multiple projects, and each project can have multiple specs. A spec belongs to one project (or directly to a user if projects aren't used).
CORE FEATURES & USER FLOW:
**1. User Authentication:**
* **Flow:** User lands on the homepage. Clicks 'Sign Up' or 'Login'. Redirected to NextAuth.js pages (e.g., email/password or OAuth provider like Google). Upon successful authentication, user is redirected to their dashboard.
* **Edge Cases:** Invalid credentials, OAuth errors, account verification (if email/password used).
**2. Specification Input & Management:**
* **Flow:** Authenticated user navigates to 'My Specs' or 'New Spec'. Clicks 'New Spec'. Enters a title and the specification text in the provided editor. Clicks 'Analyze Spec'. The content is saved to the `specs` table.
* **UI:** A page with a form: `title` (input), `content` (textarea/rich text editor). Buttons: 'Save Draft', 'Analyze Spec'.
* **Edge Cases:** Empty title/content, very long specifications.
**3. AI-Powered Analysis:**
* **Flow:** User clicks 'Analyze Spec' on a saved specification. The `content` is sent to the backend API (`/api/analyze`). The API endpoint calls the configured LLM (e.g., OpenAI) with a specific prompt (detailed in `aiMasterPrompt`'s AI Instruction section) to identify ambiguities, inconsistencies, potential scaling issues, and missing requirements. The structured analysis result is returned and saved in `specs.analysisResult` and then displayed to the user.
* **UI:** A dedicated 'Analysis' view for the spec, showing identified risks, suggested improvements, and extracted entities/relationships. Visual indicators (e.g., colored highlights, icons) for different risk levels.
* **Edge Cases:** LLM API errors, rate limiting, irrelevant analysis results, analysis timeouts.
**4. Schema Generation:**
* **Flow:** After analysis (or triggered separately), the user clicks 'Generate Schema'. The `analysisResult` and potentially the original `content` are sent to the backend (`/api/generate-schema`). The LLM is prompted to generate a Drizzle ORM schema definition based on the identified entities and relationships. The resulting schema is saved in `specs.generatedSchema` and displayed to the user in a code editor view.
* **UI:** A code editor pane displaying the generated Drizzle schema (e.g., `schema.ts`). Options to copy the schema or suggest modifications.
* **Edge Cases:** Inability to infer schema, conflicting entity definitions, generation errors.
**5. Code Snippet Generation:**
* **Flow:** User clicks 'Generate Code Snippets' (potentially based on the generated schema). The backend (`/api/generate-code`) receives the schema and spec context. LLM is prompted to generate basic CRUD API routes (Next.js App Router handlers in `app/api/...`) and potentially basic React component stubs (e.g., a form component for creating an item, a table component for listing items) for the main entities. Snippets are saved in `specs.generatedCodeSnippets` and displayed.
* **UI:** Code editor panes for different generated snippets (e.g., API routes, React components). Options to copy or download.
* **Edge Cases:** Generation of insecure code, incomplete snippets, non-functional code, compatibility issues.
**6. Iteration & Refinement:**
* **Flow:** User reviews the analysis, schema, and code. They can modify the original specification based on the feedback, or directly edit the generated schema/code snippets (locally). The platform encourages re-analyzing and re-generating after modifications to ensure consistency.
* **UI:** Clear 'Edit Spec', 'Re-analyze', 'Re-generate Schema', 'Re-generate Code' buttons. Version history for specs could be a future enhancement.
API & DATA FETCHING:
- **`POST /api/auth/[...nextauth]`:** Handles authentication via NextAuth.js.
- **`POST /api/specs`:** Creates a new specification. Request body: `{ title: string, content: string }`. Response: `{ id: string, ...specDetails }`.
- **`GET /api/specs`:** Fetches all specifications for the logged-in user. Response: `[{ id: string, title: string, createdAt: string }, ...]`. Uses server-side fetching in the dashboard.
- **`GET /api/specs/[id]`:** Fetches a single specification's details. Response: `{ id: string, title: string, content: string, analysisResult: JSON, generatedSchema: JSON, generatedCodeSnippets: JSON, ... }`. Fetched client-side or server-side based on the page.
- **`PUT /api/specs/[id]/analyze`:** Triggers AI analysis for a specific spec. Sends `spec.content` to the LLM. Request body: `{ content: string }`. Response: `{ analysisResult: JSON }`. Updates `specs.analysisResult`.
- **`PUT /api/specs/[id]/schema`:** Triggers schema generation. Sends `spec.content` and `specs.analysisResult` to LLM. Request body: `{ content: string, analysisResult: JSON }`. Response: `{ generatedSchema: JSON }`. Updates `specs.generatedSchema`.
- **`PUT /api/specs/[id]/code`:** Triggers code snippet generation. Sends `specs.generatedSchema` and `spec.content` to LLM. Request body: `{ schema: JSON, content: string }`. Response: `{ generatedCodeSnippets: JSON }`. Updates `specs.generatedCodeSnippets`.
**Data Fetching Strategy:**
- Dashboard (`/dashboard`): Fetch list of specs using `GET /api/specs` on the server-side (or client-side if preferred).
- Spec Detail Page (`/specs/[id]`): Fetch full spec details using `GET /api/specs/[id]` on the client-side using SWR or React Query, allowing for refetching after analysis/generation.
- Data passed to components will typically be JSON objects or arrays retrieved from API calls.
COMPONENT BREAKDOWN (Next.js App Router Structure):
- **`app/layout.tsx`:** Root layout (HTML, head, body, global providers like ThemeProvider, AuthProvider).
- **`app/page.tsx`:** Landing page (Marketing content, call-to-action).
- **`app/dashboard/page.tsx`:** User dashboard. Lists recent specs. Button to create a new spec. Requires authentication.
- **`app/specs/new/page.tsx`:** Page for creating a new specification. Contains the `SpecForm` component.
- **`app/specs/[id]/page.tsx`:** Page for viewing and analyzing a specific specification. Contains `SpecViewer`, `AnalysisResults`, `SchemaGenerator`, `CodeGenerator` components.
- **`app/api/...`:** API routes as described above.
- **`components/ui/`:** Re-exported components from shadcn/ui (e.g., `Button`, `Input`, `Card`, `Textarea`, `CodeBlock`, `Dialog`, `Alert`, `Spinner`).
- **`components/auth/`:** Authentication related components (e.g., `SignInForm`, `SignUpForm`, `OAuthButtons`).
- **`components/spec/`:** Components related to spec management:
* `SpecList` (`Dashboard`): Displays specs in a table or list.
* `SpecForm` (`/specs/new`, `/specs/[id]`): Form for entering/editing spec title and content. Integrates with `TextEditor` and `ValidationSummary`.
* `TextEditor` (`SpecForm`): Rich text editor for spec content (e.g., TipTap, Quill, or a simple textarea with Markdown support).
* `AnalysisResults` (`/specs/[id]`): Displays AI analysis findings. Uses `Alert` or `Card` components, potentially highlighting text.
* `SchemaDisplay` (`/specs/[id]`): Displays generated Drizzle ORM schema using `CodeBlock`.
* `CodeSnippetDisplay` (`/specs/[id]`): Displays generated code snippets (API routes, components) using `CodeBlock`.
* `ActionButtons` (`/specs/[id]`): Buttons for triggering analysis, schema generation, code generation.
- **`components/layout/`:** Layout components.
* `Navbar`
* `Footer`
* `Sidebar` (Optional)
- **`lib/`:** Utility functions, AI service clients, database connection logic (Drizzle).
- **`hooks/`:** Custom React hooks (e.g., `useAnalyzeSpec`, `useGenerateSchema`).
- **`providers/`:** Context providers (e.g., `AuthSessionProvider`, `ThemeProvider`).
**State Management:**
- `AuthSession`: Global state for user authentication status (managed by NextAuth.js adapter/provider).
- `SpecFormData`: Local state within `SpecForm` for title and content.
- `AnalysisData`, `SchemaData`, `CodeData`: Client-side state (e.g., using `useState` or SWR/Zustand) on the spec detail page, fetched from APIs. Loading and error states managed for each.
UI/UX DESIGN & VISUAL IDENTITY:
- **Design Style:** Modern, Clean, and Professional with subtle AI/tech undertones.
- **Color Palette:**
* Primary: Deep Blue (`#2563eb` - Tailwind `blue-600`)
* Secondary: Teal/Cyan (`#14b8a6` - Tailwind `teal-500`)
* Accent/Accent Hover: Light Purple/Blue (`#8b5cf6` - Tailwind `purple-500` -> `#a78bfa` - `purple-400`)
* Background: Off-white/Light Gray (`#f8fafc` - Tailwind `gray-50`)
* Dark Background (for code blocks): Dark Gray (`#1e293b` - Tailwind `slate-800`)
* Text (Light Mode): Dark Gray (`#1e293b`)
* Text (Dark Mode): Light Gray (`#f8fafc`)
* Error/Warning: Red (`#ef4444` - Tailwind `red-500`), Orange (`#f97316` - Tailwind `orange-500`)
- **Typography:** Sans-serif fonts. `Inter` or `Manrope` for body text. `Poppins` or `Montserrat` for headings. Ensure good readability and hierarchy.
- **Layout:** Clean, spacious layout using Tailwind CSS's grid and flexbox. Consistent padding and margins. Sidebar for navigation in wider screens, collapsible or hidden on smaller screens. Main content area clearly defined.
- **Key Components Styling:**
* **Navbar:** Minimalistic, with logo, nav links, and user profile/auth button.
* **Code Blocks:** Use `CodeBlock` component (from shadcn/ui or custom) with syntax highlighting and a copy button. Dark background.
* **Forms:** Clean input fields, clear labels, validation messages integrated subtly.
* **Analysis Results:** Use `Alert` or custom `Card` components with icons to denote risk levels (e.g., info, warning, danger).
- **Responsive Rules:** Mobile-first approach. Layouts adapt fluidly. Navigation may change (e.g., hamburger menu on mobile). Ensure code blocks and forms are usable on small screens.
ANIMATIONS:
- **Page Transitions:** Subtle fade-in/out transitions between pages using Next.js `AnimatePresence` or similar libraries.
- **Hover Effects:** Gentle scale or background color changes on buttons and interactive elements.
- **Loading States:** Use `Spinner` components from shadcn/ui with skeleton loaders for data fetching. Disable buttons and show spinners during API calls.
- **Micro-interactions:** Smooth expansion/collapse of analysis details, subtle feedback on form submission.
EDGE CASES:
- **Authentication:** Handle unauthenticated users gracefully (redirect to login/signup). Protect API routes and dashboard pages.
- **Empty States:** Display informative messages and clear calls-to-action when lists are empty (e.g., 'No specifications yet. Create your first one!').
- **Error Handling:** Global error handling for API calls. Display user-friendly error messages using `Alert` or `Toast` notifications. Log detailed errors server-side.
- **Validation:** Client-side validation using React Hook Form + Zod for all user inputs (spec title, content length, etc.). Server-side validation for critical data.
- **API Rate Limiting:** Implement strategies to handle LLM API rate limits (e.g., exponential backoff, queuing).
- **Long Running Tasks:** Use background jobs or asynchronous processing for AI analysis/generation if they take too long, providing progress updates to the user.
- **Data Consistency:** Ensure generated schema and code align with the analyzed specification. Provide mechanisms for users to correct discrepancies.
SAMPLE/MOCK DATA:
1. **User:**
```json
{
"id": "uuid-user-1",
"name": "Alice Developer",
"email": "alice@example.com"
}
```
2. **Spec (Initial):**
```json
{
"id": "uuid-spec-1",
"userId": "uuid-user-1",
"title": "User Profile Page",
"content": "Create a page for users to view and edit their profile information. It should include fields for name, email, and profile picture. Ensure email is unique. We need to store user profiles.",
"analysisResult": null, "generatedSchema": null, "generatedCodeSnippets": null,
"createdAt": "2023-10-27T10:00:00Z", "updatedAt": "2023-10-27T10:00:00Z"
}
```
3. **Spec (After Analysis):**
```json
{
"id": "uuid-spec-1",
"userId": "uuid-user-1",
"title": "User Profile Page",
"content": "Create a page for users to view and edit their profile information. It should include fields for name, email, and profile picture. Ensure email is unique. We need to store user profiles.",
"analysisResult": {
"risks": [
{"level": "info", "message": "Consider adding fields for username, bio, and join date to the user profile.", "suggestion": "Add username, bio, joinDate fields.", "category": "completeness"},
{"level": "warning", "message": "'Profile picture' implies a file upload. Ensure storage and handling mechanisms are considered.", "suggestion": "Specify profile picture storage (e.g., S3 bucket, local filesystem).
", "category": "scalability/implementation"}
],
"entities": {"User": {"fields": {"id": "UUID", "name": "String", "email": "String (unique)", "profilePictureUrl": "String"}, "relations": []}},
"missingRequirements": ["Authentication/Authorization for editing", "Image upload handling"]
},
"generatedSchema": null, "generatedCodeSnippets": null,
"createdAt": "2023-10-27T10:00:00Z", "updatedAt": "2023-10-27T10:05:00Z"
}
```
4. **Generated Drizzle Schema:**
```typescript
// schema.ts
import { pgTable, uuid, varchar, timestamp } from 'drizzle-orm/pg-core';
import { sql } from 'drizzle-orm';
export const users = pgTable('users', {
id: uuid('id').primaryKey(),
name: varchar('name', { length: 255 }),
email: varchar('email', { length: 255 }).notNull().unique(),
profilePictureUrl: varchar('profile_picture_url', { length: 255 }),
createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }).default(sql`NOW()`),
updatedAt: timestamp('updated_at', { withTimezone: true, mode: 'string' }).default(sql`NOW()`),
});
```
5. **Generated API Route (e.g., `app/api/users/[id]/route.ts` for GET):**
```typescript
// app/api/users/[id]/route.ts
import { NextResponse } from 'next/server';
import { db } from '@/lib/db'; // Assuming db connection is exported from lib/db
import { users } from '@/lib/db/schema'; // Import schema
import { eq } from 'drizzle-orm';
export async function GET(request: Request, { params }: { params: { id: string } }) {
try {
const user = await db.query.users.findFirst({
where: eq(users.id, params.id),
});
if (!user) {
return NextResponse.json({ error: 'User not found' }, { status: 404 });
}
return NextResponse.json(user);
} catch (error) {
console.error('Failed to fetch user:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
```
6. **Mock User Data (for UI Dev):**
```json
[
{"id": "uuid-user-1", "name": "Alice Developer", "email": "alice@example.com", "profilePictureUrl": "/images/alice.png"},
{"id": "uuid-user-2", "name": "Bob Manager", "email": "bob@example.com", "profilePictureUrl": "/images/bob.png"}
]
```
7. **Mock Spec List:**
```json
[
{"id": "uuid-spec-1", "title": "User Profile Page", "status": "analyzed", "createdAt": "2023-10-27T10:00:00Z"},
{"id": "uuid-spec-2", "title": "Product Catalog API", "status": "draft", "createdAt": "2023-10-26T09:00:00Z"}
]
```
8. **Analysis Warning Example:**
```json
{"level": "warning", "message": "Potential race condition if multiple users update the same record simultaneously. Consider implementing optimistic locking or database-level locking.", "category": "concurrency"}
```
9. **Ambiguity Example:**
```json
{"level": "info", "message": "The term 'recent orders' is vague. Specify the time frame (e.g., last 7 days, last 30 days).", "category": "ambiguity"}
```
10. **Generated Component Stub (React Form):**
```typescript
// components/forms/UserProfileForm.tsx
import React from 'react';
import { useForm } from 'react-hook-form';
import { Button, Input, Label } from '@/components/ui'; // Assuming shadcn/ui components
interface UserProfileFormData {
name: string;
email: string;
profilePictureUrl: string;
}
interface UserProfileFormProps {
initialData?: Partial<UserProfileFormData>;
onSubmit: (data: UserProfileFormData) => void;
}
export const UserProfileForm: React.FC<UserProfileFormProps> = ({ initialData = {}, onSubmit }) => {
const { register, handleSubmit, formState: { errors } } = useForm<UserProfileFormData>({
defaultValues: initialData,
});
return (
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div>
<Label htmlFor="name">Name</Label>
<Input id="name" {...register('name', { required: 'Name is required' })} />
{errors.name && <p className="text-red-500 text-sm">{errors.name.message}</p>}
</div>
<div>
<Label htmlFor="email">Email</Label>
<Input id="email" type="email" {...register('email', { required: 'Email is required', pattern: { value: /\S+@\S+.\S+/, message: 'Invalid email address' } })} />
{errors.email && <p className="text-red-500 text-sm">{errors.email.message}</p>}
</div>
<div>
<Label htmlFor="profilePictureUrl">Profile Picture URL</Label>
<Input id="profilePictureUrl" {...register('profilePictureUrl')} />
{/* Add upload button/logic here for actual file uploads */}
</div>
<Button type="submit">Save Profile</Button>
</form>
);
};
```