## AI Master Prompt: Mind Weaver - Personal Superintelligence Platform
**PROJECT OVERVIEW:**
Mind Weaver is a sophisticated SaaS application designed to empower individuals on their journey towards personal superintelligence. It addresses the growing challenge of information overload and the difficulty in synthesizing vast amounts of data into actionable insights and creative ideas. The platform acts as a personal AI assistant, helping users organize, connect, and leverage their knowledge base to enhance learning, problem-solving, and creative output. The core value proposition lies in transforming raw information into structured, interconnected knowledge, thereby unlocking deeper understanding and facilitating the discovery of novel connections and ideas, ultimately fostering 'personal superintelligence'.
**TECH STACK:**
- **Frontend:** React (Next.js App Router)
- **Styling:** Tailwind CSS
- **ORM:** Drizzle ORM
- **Database:** PostgreSQL (via Neon or similar serverless provider)
- **Authentication:** NextAuth.js (using PostgreSQL adapter)
- **UI Components:** shadcn/ui
- **State Management:** Zustand or React Context API for global state, component-local state as needed.
- **API Layer:** Next.js API Routes (or Server Actions for mutations)
- **AI Integration:** OpenAI API (or compatible models) for summarization, question answering, and idea generation.
- **Other:** React Hook Form for form management, Zod for schema validation, Axios for HTTP requests (if needed).
**DATABASE SCHEMA (Drizzle ORM - PostgreSQL):**
```typescript
// schema.ts
import { pgTable, uuid, text, timestamp, pgEnum, foreignKey } from 'drizzle-orm/pg-core';
import { InferSelectModel, InferInsertModel } from 'drizzle-orm';
import { relations } from 'drizzle-orm';
// User Authentication Schema
export const users = pgTable('users', {
id: uuid('id').primaryKey().defaultRandom(),
name: text('name'),
email: text('email').notNull().unique(),
emailVerified: timestamp('emailVerified', { mode: 'date' }),
image: text('image'),
createdAt: timestamp('createdAt').defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow(),
});
export type User = InferSelectModel<typeof users>;
export type NewUser = InferInsertModel<typeof users>;
// Knowledge Item Schema
export const knowledgeItems = pgTable('knowledge_items', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
title: text('title').notNull(),
content: text('content'), // Can be long text for summaries, notes, etc.
sourceUrl: text('sourceUrl'), // Optional URL if content is from the web
sourceType: pgEnum('source_type', ['web', 'file', 'manual', 'api']),
tags: text('tags').array(), // Array of tags
createdAt: timestamp('createdAt').defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow(),
});
export type KnowledgeItem = InferSelectModel<typeof knowledgeItems>;
export type NewKnowledgeItem = InferInsertModel<typeof knowledgeItems>;
// User Knowledge Item Relations
export const userRelations = relations(users, ({ many }) => ({
knowledgeItems: many(knowledgeItems),
}));
export const knowledgeItemRelations = relations(knowledgeItems, ({ one }) => ({
user: one(users, {
fields: [knowledgeItems.userId],
references: [users.id],
}),
}));
// Optional: For more advanced features like tagging or categorization
export const tags = pgTable('tags', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
name: text('name').notNull(),
});
export const knowledgeItemTags = pgTable('knowledge_item_tags', {
knowledgeItemId: uuid('knowledge_item_id').notNull().references(() => knowledgeItems.id, { onDelete: 'cascade' }),
tagId: uuid('tag_id').notNull().references(() => tags.id, { onDelete: 'cascade' }),
});
// Relations for tags
export const tagRelations = relations(tags, ({ many }) => ({
knowledgeItems: many(knowledgeItemTags),
}));
export const knowledgeItemTagRelations = relations(knowledgeItemTags, ({ one }) => ({
knowledgeItem: one(knowledgeItems, {
fields: [knowledgeItemTags.knowledgeItemId],
references: [knowledgeItems.id],
}),
tag: one(tags, {
fields: [knowledgeItemTags.tagId],
references: [tags.id],
}),
}));
// Placeholder for potential AI-generated insights or connections
// export const aiInsights = pgTable('ai_insights', {
// id: uuid('id').primaryKey().defaultRandom(),
// userId: uuid('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
// relatedKnowledgeItemId: uuid('related_knowledge_item_id').references(() => knowledgeItems.id, { onDelete: 'set null' }),
// insight: text('insight').notNull(),
// type: pgEnum('insight_type', ['connection', 'summary', 'idea']),
// createdAt: timestamp('createdAt').defaultNow(),
// });
```
**CORE FEATURES & USER FLOW:**
1. **User Authentication (NextAuth.js):
* Flow: Landing Page -> Sign Up/Login Button -> OAuth (Google, GitHub) or Email/Password Form -> Redirect to Dashboard.
* Edge Cases: Invalid credentials, existing email, account lockout (if implemented), email verification (optional for MVP).
2. **Knowledge Base Management:
* **Adding Items:**
* User clicks 'Add New Item' button on Dashboard or dedicated 'Knowledge' page.
* Form appears (modal or dedicated page) with fields: Title (required), Content (rich text editor), Source URL (optional), Source Type (dropdown: Web, File, Manual, API), Tags (input with auto-suggest/creation).
* User fills fields, clicks 'Save'.
* **Web Source:** User provides URL. Backend scrapes content (using libraries like `cheerio` or external service), processes it, and saves to `knowledgeItems` table. Title can be auto-populated.
* **File Upload:** User uploads PDF, DOCX, TXT. Backend extracts text (using libraries like `pdf-parse`, `mammoth`), saves content.
* **Manual:** User directly types/pastes content.
* **AI Source:** User provides prompt, AI generates content, saved.
* Validation: Title is mandatory. Zod schema validation on frontend and backend.
* **Viewing Items:**
* Dashboard shows a summary list (e.g., recent items, items by tag).
* 'Knowledge' page displays all items in a searchable, filterable, sortable table (using shadcn/ui DataTable).
* Clicking an item opens a detail view (modal or separate page) showing all fields, including source, tags, and potentially AI-generated summaries/connections.
* **Editing/Deleting Items:**
* Within the item detail view or table actions, 'Edit' and 'Delete' buttons are available.
* Edit navigates to the same form as 'Add New Item', pre-filled.
* Delete prompts confirmation before removing the item and associated relations.
3. **AI-Powered Summarization & Synthesis:
* **On Demand:** Within the item detail view, a 'Summarize' button triggers an API call to OpenAI.
* The `content` of the item is sent to the AI with a prompt like: "Provide a concise summary of the following text, highlighting key takeaways:
`[item.content]`".
* The response is displayed below the content or in a dedicated 'AI Insights' section. This could be cached or stored in `aiInsights` table if implemented.
* **Cross-Item Synthesis:** A feature on the 'Knowledge' page or Dashboard allows users to select multiple items (e.g., via checkboxes) and request a synthesized summary or connection analysis.
* User selects items, clicks 'Synthesize'.
* Backend sends the concatenated content of selected items (or representative parts) to the AI with a prompt like: "Analyze the following pieces of information and identify common themes, potential contradictions, or novel connections between them:
`[item1.content]
[item2.content]
...`".
* The synthesized output is displayed.
4. **Intelligent Q&A:
* **Interface:** A dedicated 'Ask AI' page or a persistent chat-like interface on the Dashboard.
* **Flow:** User types a question (e.g., "What are the main arguments for X based on my data?").
* The system retrieves relevant `knowledgeItems` based on keywords in the query or potentially uses embeddings for semantic search (advanced).
* The user's question and the retrieved content are sent to the AI API with a prompt like: "Based on the following context, answer the user's question. If the information is not present, state that clearly.
Context:
`[Relevant content from user's knowledge items]`
User Question:
`[User's question]`".
* The AI's response is displayed.
5. **Creative Idea Generation:
* **Trigger:** A button like 'Generate Ideas' on the Dashboard or Knowledge page.
* **Flow:** User can optionally select specific knowledge items or tags to focus the generation.
* Backend constructs a prompt based on selected items/tags or the general knowledge base, e.g., "Given the following topics and information [summary of selected data], generate 5 novel project ideas or article titles related to [core theme]."
* The AI's suggestions are displayed.
**API & DATA FETCHING:**
- **Next.js API Routes / Server Actions:**
* `POST /api/auth/...`: Handled by NextAuth.js.
* `POST /api/knowledge`: Create new knowledge item (handles text, URL scraping, file upload processing).
* `GET /api/knowledge`: Fetch list of knowledge items (with filtering, sorting, pagination).
* `GET /api/knowledge/[id]`: Fetch single knowledge item details.
* `PUT /api/knowledge/[id]`: Update knowledge item.
* `DELETE /api/knowledge/[id]`: Delete knowledge item.
* `POST /api/ai/summarize`: Trigger summarization for a given text/item ID.
* `POST /api/ai/synthesize`: Trigger synthesis for selected item IDs.
* `POST /api/ai/qna`: Handle user question against knowledge base.
* `POST /api/ai/generate-ideas`: Trigger idea generation.
- **Data Fetching:**
* **Server Components:** Fetch data directly within Server Components for initial page loads (e.g., dashboard summaries).
* **Client Components:** Use libraries like `react-query` (or SWR) or Zustand for fetching and caching data in client-side components, especially for dynamic lists, forms, and interactive elements.
* **Mutations:** Use Server Actions or API routes with mutations for creating, updating, deleting data. Provide optimistic UI updates where appropriate.
* **Requests:** Axios or native `fetch` API.
* **Responses:** JSON format.
* **Edge Cases:** Handle API errors gracefully (4xx, 5xx), display loading states, show empty states for no data.
**COMPONENT BREAKDOWN (Next.js App Router Structure):**
- **`app/`**
* **`(auth)` group:**
* `layout.tsx`: Auth layout (minimal header/footer).
* `login/page.tsx`: Login form/OAuth buttons.
* `signup/page.tsx`: Signup form.
* **`(app)` group (Protected Routes):**
* `layout.tsx`: Main application layout (sidebar, header, content area).
* **`providers.tsx`:** (Client Component) Wraps children with Context Providers (Auth, Zustand Store, Theme).
* **`dashboard/page.tsx`:** (Server Component, then Client) Overview page. Displays recent items, quick stats, quick add form, AI Q&A input.
* **`knowledge/page.tsx`:** (Server Component, then Client) Main knowledge management page. Contains `KnowledgeTable` component.
* **`knowledge/[id]/page.tsx`:** (Server Component, then Client) Detail view for a single knowledge item. Includes `KnowledgeDetailView` component with AI interaction buttons.
* **`new/page.tsx`:** (Client Component) Form page for adding new knowledge items (`KnowledgeForm`).
* **`settings/page.tsx`:** (Client Component) User settings page (profile, integrations, subscription).
* **`api/`**
* `auth/[...nextauth]/route.ts`: NextAuth.js handler.
* `knowledge/route.ts`: API routes for knowledge CRUD.
* `ai/route.ts`: API routes for AI interactions.
* **`layout.tsx`:** Root layout (html, body, global styles).
* **`page.tsx`:** Landing page.
- **`components/`**
* **`ui/` (shadcn/ui based):** Button, Input, Card, Dialog, Table, Form, etc.
* **`auth/`:** `AuthButton`, `UserAvatarMenu`.
* **`knowledge/`:**
* `KnowledgeForm.tsx`: (Client) Form for adding/editing items. Uses React Hook Form + Zod.
* `KnowledgeTable.tsx`: (Client) Uses shadcn/ui DataTable for displaying/managing items.
* `KnowledgeListItem.tsx`: (Client/Server) Represents a single item in lists/tables.
* `KnowledgeDetailView.tsx`: (Client) Displays full item details, triggers AI actions.
* **`ai/`:**
* `AISummary.tsx`: Displays AI summaries.
* `AIQnAForm.tsx`: Input for asking questions.
* `AIChatDisplay.tsx`: Displays Q&A history.
* `AIGeneratedIdeas.tsx`: Displays generated ideas.
* **`layout/`:** `Sidebar`, `Header`, `Footer`.
* **`common/`:** `LoadingSpinner`, `ErrorMessage`, `EmptyState`.
- **`lib/`:**
* `db.ts`: Drizzle ORM client initialization.
* `auth.ts`: NextAuth.js configuration.
* `openai.ts`: OpenAI API client setup.
* `utils.ts`: Utility functions.
* `validators.ts`: Zod validation schemas.
- **`store/`:**
* `useStore.ts`: Zustand global state store definition.
**UI/UX DESIGN & VISUAL IDENTITY:**
- **Design Style:** "Minimalist Clean with AI Accents". Focus on clarity, readability, and intuitive navigation. Subtle use of gradients and glowing effects to represent AI intelligence.
- **Color Palette:**
* Primary: Deep Blue (`#1E3A8A` - Slate 800)
* Secondary: Soft Teal (`#2DD4BF` - Emerald 400)
* Accent/AI Glow: Electric Purple/Blue Gradient (`#8B5CFE` to `#3B82F6`)
* Background: Off-White (`#F8FAFC` - Zinc 50) or Dark Mode variant (Near Black `#020617` - Black 950)
* Text: Dark Gray (`#18181B` - Zinc 900) / Light Gray (`#E4E4E7` - Stone 200)
- **Typography:**
* Headings: Inter (Bold, SemiBold)
* Body Text: Inter (Regular)
* Use clear hierarchy. Font sizes: 36px (H1), 24px (H2), 18px (H3), 16px (Body), 14px (Small text).
- **Layout:**
* Use a consistent sidebar for navigation in authenticated state.
* Main content area should be spacious, using cards and clear sections.
* Responsive design: Mobile-first approach. Sidebar collapses into a hamburger menu on small screens. Content adapts fluidly.
- **Sections:** Content divided using subtle borders or background color changes. Ample whitespace.
- **Brand Elements:** A simple, abstract logo representing interconnectedness or a neural network, possibly incorporating the accent gradient.
**ANIMATIONS:**
- **Page Transitions:** Subtle fade-in/slide-in animations for new pages/content (e.g., using `Framer Motion` if desired, or CSS transitions).
- **Hover Effects:** Slight scale-up or color change on interactive elements (buttons, links, cards).
- **Loading States:** Use skeleton loaders or spinners (from shadcn/ui) during data fetching. AI processing can show a pulsing glow effect.
- **Micro-interactions:** Smooth opening/closing of modals, form validation feedback.
**EDGE CASES:**
- **Empty States:** Display user-friendly messages and calls-to-action when knowledge bases are empty, search yields no results, or AI has no relevant data (e.g., "Your knowledge base is empty. Add your first piece of information!", "No results found. Try broadening your search.").
- **Authentication:** Handled by NextAuth.js. Redirect unauthenticated users to login. Protect relevant routes (`(app)` group).
- **Error Handling:** Global error boundaries and specific error handling for API calls. Display user-friendly error messages (e.g., "Failed to load data. Please try again.", "AI service is temporarily unavailable."). Use Zod for request/response validation.
- **Authorization:** Ensure users can only access and modify their own data (check `userId` on all DB operations).
- **AI Rate Limiting/Costs:** Implement safeguards against excessive API calls. Display usage indicators if necessary. Consider fallback responses or throttling.
- **Data Scraping Failures:** Handle cases where web scraping fails (e.g., website blocks scrapers, invalid URL). Provide feedback to the user.
- **Large Content:** Optimize handling and display of very large text content. Consider pagination or lazy loading for long AI responses.
**SAMPLE DATA:**
1. **User:**
```json
{
"id": "uuid-user-1",
"name": "Alice Smith",
"email": "alice.smith@example.com",
"emailVerified": "2023-10-27T10:00:00Z",
"image": "/path/to/alice_avatar.jpg"
}
```
2. **Knowledge Item (Web Article):**
```json
{
"id": "uuid-item-1",
"userId": "uuid-user-1",
"title": "The Future of Renewable Energy",
"content": "Renewable energy sources like solar and wind are becoming increasingly cost-competitive with fossil fuels. Advancements in battery storage technology are crucial for overcoming intermittency issues...",
"sourceUrl": "https://example-news.com/renewable-energy-future",
"sourceType": "web",
"tags": ["energy", "sustainability", "technology"],
"createdAt": "2023-10-26T14:30:00Z"
}
```
3. **Knowledge Item (Manual Note):**
```json
{
"id": "uuid-item-2",
"userId": "uuid-user-1",
"title": "Meeting Notes - Project Phoenix",
"content": "Discussed Q4 roadmap. Key decisions: Prioritize feature X, allocate additional resources to team Y. Potential risks include Z.",
"sourceUrl": null,
"sourceType": "manual",
"tags": ["project-phoenix", "meeting", "roadmap"],
"createdAt": "2023-10-25T09:00:00Z"
}
```
4. **Knowledge Item (AI Generated Snippet):**
```json
{
"id": "uuid-item-3",
"userId": "uuid-user-1",
"title": "AI Summary: Quantum Computing Basics",
"content": "Quantum computing leverages quantum-mechanical phenomena like superposition and entanglement to perform calculations. Unlike classical bits (0 or 1), qubits can exist in multiple states simultaneously, enabling exponential speedups for certain problems...",
"sourceUrl": null,
"sourceType": "api", // Indicates it was generated/fetched via AI
"tags": ["ai", "quantum computing", "technology"],
"createdAt": "2023-10-24T11:00:00Z"
}
```
5. **Knowledge Item (Research Paper Abstract):**
```json
{
"id": "uuid-item-4",
"userId": "uuid-user-1",
"title": "Abstract: Neural Network Optimization Techniques",
"content": "This paper reviews various optimization algorithms for training deep neural networks, including SGD variants, Adam, and RMSprop. We analyze their convergence properties and performance on benchmark datasets...",
"sourceUrl": "https://example-journal.com/nn-optimization-abstract",
"sourceType": "web",
"tags": ["machine learning", "neural networks", "optimization", "research"],
"createdAt": "2023-10-23T16:00:00Z"
}
```
6. **Tag:**
```json
{
"id": "uuid-tag-1",
"userId": "uuid-user-1",
"name": "energy"
}
```
7. **Knowledge Item Tag Relation:**
```json
{
"knowledgeItemId": "uuid-item-1",
"tagId": "uuid-tag-1"
}
```
**(Turkish Translations for UI Elements):**
- **App Title:** "Zihin Dokuyucu"
- **Buttons:** "Kaydet" (Save), "Ekle" (Add), "Düzenle" (Edit), "Sil" (Delete), "Özetle" (Summarize), "Sorgula" (Query), "Fikir Üret" (Generate Ideas), "Giriş Yap" (Login), "Kayıt Ol" (Sign Up), "Ayarlar" (Settings).
- **Labels:** "Başlık" (Title), "İçerik" (Content), "Kaynak URL" (Source URL), "Kaynak Türü" (Source Type), "Etiketler" (Tags), "Soru" (Question).
- **Placeholders:** "Bilgiyi buraya girin..." (Enter information here...), "Bilgi eklemeye başlayın..." (Start adding knowledge...).
- **Page Titles:** "Gösterge Paneli" (Dashboard), "Bilgi Bankası" (Knowledge Base), "Yeni Bilgi Ekle" (Add New Knowledge).
- **Messages:** "Bilgileriniz yükleniyor..." (Loading your knowledge...), "Özet oluşturuluyor..." (Generating summary...), "Sonuç bulunamadı." (No results found.).