You are tasked with building a comprehensive, fully functional MVP of a web application called 'ThoughtForge' using Next.js (App Router), Tailwind CSS, and Drizzle ORM. The application aims to solve the problem of over-reliance on LLMs for writing, which can lead to a lack of deep thinking and eroded trust. ThoughtForge will empower users to engage in a more profound writing process, enhancing their understanding, critical thinking skills, and credibility.
**1. PROJECT OVERVIEW:**
ThoughtForge is a next-generation writing and thinking platform designed to foster deep understanding and build trust through authentic intellectual engagement. It addresses the growing trend of users passively accepting LLM-generated content, which bypasses the crucial cognitive benefits of the writing process. The core value proposition is to transform writing from a mere output task into a rigorous process of self-discovery, critical analysis, and knowledge construction. It helps users 'forge' their thoughts, ensuring that the final output is a true reflection of their deepened understanding, not just a synthesized response.
**2. TECH STACK:**
- **Frontend:** React (Next.js App Router)
- **Styling:** Tailwind CSS
- **ORM:** Drizzle ORM
- **Database:** PostgreSQL (via Neon, Supabase, or similar)
- **Authentication:** NextAuth.js (or Clerk)
- **UI Components:** shadcn/ui
- **State Management:** React Context API / Zustand (for global state if needed)
- **Form Handling:** React Hook Form + Zod for validation
- **Other:** React Query (or TanStack Query) for server state management, potentially a charting library for visualizing progress.
**3. DATABASE SCHEMA (Drizzle ORM for PostgreSQL):**
```typescript
// schema.ts
import { pgTable, serial, text, timestamp, varchar, integer, boolean, jsonb, uuid }
from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
export const users = pgTable('users', {
id: uuid('id').primaryKey(),
name: text('name'),
email: varchar('email', { length: 255 }).notNull().unique(),
emailVerified: timestamp('emailVerified', { mode: 'date' }),
image: text('image'),
createdAt: timestamp('createdAt').defaultNow()
});
export const accounts = pgTable('accounts', {
id: serial('id').primaryKey(),
userId: uuid('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
type: varchar('type', { length: 255 }).$type<import('next-auth/providers').ProviderType>().notNull(),
provider: varchar('provider', { length: 255 }).notNull(),
providerAccountId: varchar('providerAccountId', { length: 255 }).notNull(),
refresh_token: text('refresh_token'),
access_token: text('access_token'),
expires_at: integer('expires_at'),
token_type: varchar('token_type', { length: 255 }),
scope: varchar('scope', { length: 255 }),
id_token: text('id_token'),
session_state: varchar('session_state', { length: 255 })
});
export const sessions = pgTable('sessions', {
sessionToken: varchar('sessionToken', { length: 255 }).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()
});
// Core Application Tables
export const documents = pgTable('documents', {
id: uuid('id').primaryKey(),
userId: uuid('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
title: varchar('title', { length: 255 }).notNull(),
createdAt: timestamp('createdAt').defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow(),
contentStructure: jsonb('contentStructure'), // Stores the structured outline
currentVersionContent: text('currentVersionContent'), // Stores the latest full content
initialQuestion: text('initialQuestion') // The core question the document answers
});
export const documentVersions = pgTable('documentVersions', {
id: uuid('id').primaryKey(),
documentId: uuid('documentId').notNull().references(() => documents.id, { onDelete: 'cascade' }),
versionNumber: integer('versionNumber').notNull(),
content: text('content').notNull(),
changeLog: text('changeLog'),
createdAt: timestamp('createdAt').defaultNow()
});
export const documentAnalysis = pgTable('documentAnalysis', {
id: uuid('id').primaryKey(),
documentId: uuid('documentId').notNull().references(() => documents.id, { onDelete: 'cascade' }),
thinkingScore: integer('thinkingScore'), // e.g., 1-100 based on depth, questioning, structure
trustScore: integer('trustScore'), // e.g., 1-100 based on originality, reasoned arguments
llmContributionPercentage: integer('llmContributionPercentage'), // Estimated % from LLM
originalityCheck: boolean('originalityCheck').default(false),
analysisDate: timestamp('analysisDate').defaultNow()
});
// Relations (Example for documents)
export const userRelations = relations(users, ({ many }) => ({
documents: many(documents)
}));
export const documentRelations = relations(documents, ({ one, many }) => ({
user: one(users, {
fields: [documents.userId],
references: [users.id]
}),
versions: many(documentVersions),
analysis: one(documentAnalysis)
}));
// Add relations for other tables as needed...
```
**4. CORE FEATURES & USER FLOW:**
* **User Authentication:**
* **Flow:** User lands on the homepage. Clicks 'Sign Up' or 'Login'. Redirected to NextAuth.js pages (or Clerk). Options: Google, GitHub, Email/Password.
* **Post-Login:** Redirected to the main dashboard.
* **Edge Case:** Handle verification emails, password resets, OAuth callback errors.
* **Document Creation / 'Forging' Process:**
* **Flow:**
1. User clicks 'New Document' on the dashboard.
2. Presented with a modal/page asking for the 'Initial Question' (e.g., "What are the key benefits of microservices?").
3. The system suggests a structured outline (e.g., Introduction, Problem Definition, Proposed Solution, Benefits, Drawbacks, Conclusion) using an LLM prompt internally. User can accept or modify this structure.
4. User is taken to the main editor view. The editor displays the selected structure (e.g., sections like 'Introduction', 'Problem Definition').
5. User clicks into a section (e.g., 'Introduction').
6. **'Deepen Thought' Button:** User clicks this. The UI calls an API endpoint (`/api/generate-prompts`). This endpoint uses the current section's content (or lack thereof) and the document's `initialQuestion` to craft targeted prompts for the user (e.g., "Expand on the core problem microservices aim to solve.", "What are common misconceptions about microservices?").
7. **LLM Assistance:** User selects a generated prompt or types their own. Clicks 'Get LLM Draft'. An API call (`/api/generate-content`) is made. The LLM generates text based on the prompt and context.
8. **Editing & Refinement:** The LLM-generated text appears in the editor. Crucially, the UI visually distinguishes LLM-generated text (e.g., subtle background highlight, a small LLM icon). The user is encouraged to edit, rephrase, add their own insights, and remove parts they disagree with.
9. **Saving:** User saves progress. The system saves the `currentVersionContent` and potentially creates a new entry in `documentVersions` if significant changes are made or on explicit user action. The `contentStructure` is also updated.
10. **Analysis Trigger:** Upon saving or explicit user request, an analysis process is triggered (async background job or API call to `/api/analyze-document`).
* **Edge Cases:** Handling empty content, user rejecting all LLM suggestions, complex structural changes, large document saving.
* **Document Analysis & Scoring:**
* **Flow:** After content is saved/analyzed, the user can view the 'Analysis' tab/section.
* The `documentAnalysis` data (thinking score, trust score, LLM percentage) is displayed using cards or a dashboard widget.
* The system provides feedback: "Your 'Problem Definition' section shows deep engagement. Consider elaborating on the 'Drawbacks' with specific examples."
* The `originalityCheck` flag is set based on internal checks (can be a placeholder initially).
* **Edge Cases:** Analysis not yet complete, errors during analysis.
* **Version History:**
* **Flow:** User navigates to the 'Versions' tab for a document.
* A list of past `documentVersions` is displayed, sortable by date.
* User can select a version to view its content and `changeLog`.
* Option to 'Restore' a previous version (creates a new current version).
* **Edge Cases:** No previous versions, restoring a version overwrites current work (needs confirmation).
**5. API & DATA FETCHING:**
- **Base URL:** `/api/*`
- **Endpoints:**
* `POST /api/documents`: Create a new document.
* `GET /api/documents`: Fetch list of user's documents for dashboard.
* `GET /api/documents/[id]`: Fetch a single document's details (including structure, current content, analysis).
* `PUT /api/documents/[id]`: Save/update document content and structure.
* `POST /api/documents/[id]/versions`: Create a new version.
* `GET /api/documents/[id]/versions`: Fetch version history.
* `POST /api/generate-prompts`: (Internal/Challenger prompts) Generates targeted questions/prompts for a given section/document context. Requires document `id`, section identifier, current content.
* `POST /api/generate-content`: (LLM Integration) Generates text based on a user prompt/context. Requires prompt, document `id`, section identifier.
* `POST /api/analyze-document`: Triggers the scoring and analysis process for a document.
- **Data Fetching:** Use React Query (`useQuery`, `useMutation`) for efficient server state management. Fetch document lists on dashboard load, fetch individual documents when opened. Mutations for create, update, delete operations.
- **Request/Response:** Standard JSON. Use Zod for request/response validation on API routes.
**6. COMPONENT BREAKDOWN (Next.js App Router Structure):**
* **(app)/layout.tsx:** Root layout (includes Head, providers, main layout structure).
* **(app)/page.tsx:** Landing Page (Public).
* **(app)/auth/[...nextauth]/route.ts:** NextAuth.js route handler.
* **(app)/dashboard/layout.tsx:** Authenticated layout (sidebar, header).
* **(app)/dashboard/page.tsx:** User Dashboard (List of documents, 'New Document' button).
* `DocumentList`: Fetches and displays `documents` from `/api/documents`.
* `NewDocumentButton`: Triggers modal/navigation to create.
* **(app)/dashboard/editor/[id]/page.tsx:** The main document editor page.
* `EditorLayout`: Main layout for the editor (e.g., split pane: outline/sections on left, editor on right).
* `SectionOutline`: Displays `contentStructure` from `documents` data. Allows navigation between sections.
* `RichTextEditor`: The core editing component (e.g., using TipTap, Quill, or similar). Manages local state, integrates with LLM suggestions.
* `PromptGeneratorButton`: Triggers `/api/generate-prompts`.
* `LLMResponseDisplay`: Shows LLM output, allows user to accept/edit/reject. Visually distinct.
* `SaveButton`: Triggers `PUT /api/documents/[id]`.
* `AnalysisButton`: Triggers `/api/analyze-document` or navigates to analysis view.
* `VersionHistoryButton`: Navigates to version history view.
* **(app)/dashboard/editor/[id]/analysis.tsx:** Document analysis view.
* `AnalysisCard`: Displays `thinkingScore`, `trustScore`, `llmContributionPercentage` from `documentAnalysis`.
* `FeedbackSection`: Provides textual feedback based on analysis results.
* **(app)/dashboard/editor/[id]/versions.tsx:** Document version history view.
* `VersionList`: Fetches and displays `documentVersions`.
* `VersionViewer`: Displays content of a selected version.
* `RestoreVersionButton`: Calls an API to restore a version.
* **(app)/settings/page.tsx:** User settings page (profile, account management).
* **components/ui/\*:\* shadcn/ui components (Button, Card, Input, Dialog, etc.)
* **components/AuthProvider.tsx:** Context provider for authentication status.
* **lib/db.ts:** Drizzle ORM database connection setup.
* **lib/auth.ts:** NextAuth.js configuration.
* **lib/utils.ts:** Utility functions.
**7. UI/UX DESIGN & VISUAL IDENTITY:**
- **Style:** Minimalist Clean with subtle professional touches.
- **Color Palette:**
- Primary: `#0A7AFF` (Vibrant Blue for actions, links)
- Secondary: `#6B7280` (Gray for secondary text, borders)
- Accent: `#FBBF24` (Yellow/Amber for attention, warnings, LLM indicators)
- Background: `#FFFFFF` (White for main background)
- Card/Element BG: `#F9FAFB` (Slightly off-white for cards/sections)
- Text: `#1F2937` (Dark Gray/Black for primary text)
- **Typography:** Inter (sans-serif) for readability. Clear hierarchy using font weights and sizes.
- **Layout:** Focus on a clean, uncluttered interface. Use of whitespace. Main editor likely a two-column layout (structure/nav on left, editor on right). Sidebar for main navigation in authenticated sections.
- **Responsiveness:** Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Editor adapts gracefully, potentially stacking columns or using modals.
**8. SAMPLE/MOCK DATA:**
* **User Document List:**
```json
[
{ "id": "doc-uuid-1", "title": "Microservices Benefits Analysis", "updatedAt": "2023-10-27T10:00:00Z", "initialQuestion": "What are the key benefits of microservices?" },
{ "id": "doc-uuid-2", "title": "Q4 Product Roadmap Ideas", "updatedAt": "2023-10-26T15:30:00Z", "initialQuestion": "What should be our focus for Q4?" },
{ "id": "doc-uuid-3", "title": "Research Paper Outline: AI Ethics", "updatedAt": "2023-10-25T09:15:00Z", "initialQuestion": "What are the primary ethical concerns surrounding advanced AI?" }
]
```
* **Document Content (Simplified Example for `currentVersionContent`):**
```
{
"Introduction": "The adoption of microservices architecture has been a significant trend...",
"ProblemDefinition": "Traditionally, monolithic applications faced challenges in scalability and deployment cycles. LLM Suggested: This section was largely drafted by an AI assistant. Refine required.",
"Benefits": "Key advantages include independent scaling, technology diversity, and faster development cycles...",
"Drawbacks": "However, microservices introduce complexities in distributed systems management, inter-service communication, and operational overhead.",
"Conclusion": "In conclusion, while microservices offer compelling benefits, careful consideration of their inherent complexities is crucial for successful implementation."
}
```
* **Document Analysis:**
```json
{
"id": "doc-uuid-1",
"thinkingScore": 75,
"trustScore": 80,
"llmContributionPercentage": 20,
"originalityCheck": true,
"analysisDate": "2023-10-27T11:00:00Z"
}
```
* **Version History Item:**
```json
{
"id": "ver-uuid-1",
"versionNumber": 1,
"content": "{\"Introduction\": \"Initial draft content...\"}",
"changeLog": "Initial draft created.",
"createdAt": "2023-10-27T09:00:00Z"
}
```
* **Generated Prompts (Example response from `/api/generate-prompts`):**
```json
{
"prompts": [
"Elaborate on the specific challenges faced by monolithic applications.",
"Provide a real-world example of a company that benefited from microservices.",
"What are the common pitfalls when migrating from monolith to microservices?"
]
}
```
**9. TURKISH TRANSLATIONS:**
- **App Title:** Fikir Damlası (ThoughtForge)
- **Document Title:** Doküman
- **Initial Question:** Başlangıç Sorusu
- **New Document:** Yeni Doküman
- **Save:** Kaydet
- **Cancel:** İptal
- **Edit:** Düzenle
- **View:** Görüntüle
- **Delete:** Sil
- **Settings:** Ayarlar
- **Dashboard:** Kontrol Paneli
- **Analysis:** Analiz
- **Versions:** Versiyonlar
- **Thinking Score:** Düşünme Skoru
- **Trust Score:** Güven Skoru
- **LLM Contribution:** YZ Katkısı
- **Originality Check:** Özgünlük Kontrolü
- **Deepen Thought:** Düşünceyi Derinleştir
- **Get LLM Draft:** YZ Taslağı Al
- **Accept:** Kabul Et
- **Reject:** Reddet
- **Sign Up:** Kaydol
- **Login:** Giriş Yap
- **Logout:** Çıkış Yap
- **User Profile:** Kullanıcı Profili
- **Are you sure?** Emin misin?
- **This action cannot be undone.** Bu işlem geri alınamaz.
- **Loading...** Yükleniyor...
- **No documents found.** Hiç doküman bulunamadı.
- **Create your first document!** İlk dokümanını oluştur!
**10. ANIMATIONS & EDGE CASES:**
- **Animations:**
- Subtle fade-ins for new content blocks.
- Smooth transitions between sections in the editor.
- Button hover effects (slight scale or color change).
- Loading spinners/skeletons when data is fetching or LLM is processing.
- Transitions for collapsing/expanding sidebar.
- **Edge Cases:**
- **Authentication:** Proper handling of expired tokens, session management, redirecting unauthenticated users.
- **Empty States:** Displaying helpful messages and clear calls-to-action when lists (documents, versions) are empty.
- **Error Handling:** Graceful error display for API failures (e.g., using toast notifications), network issues. Specific error messages for LLM API failures.
- **Validation:** Robust client-side (Zod) and server-side validation for all form inputs and API payloads.
- **LLM Rate Limits/Errors:** Implement backoff strategies and user feedback for LLM API issues.
- **Data Integrity:** Ensure database constraints are maintained, use transactions for critical operations.
- **Concurrency:** Handle potential race conditions if multiple users could edit the same document (though MVP focuses on single-user editing per document).