---
# System prepended metadata

title: PRD Wizard Implementation Plan

---

# PRD Wizard Implementation Plan

## Abstract

The PRD Wizard is a collaborative Product Requirements Document editor that brings AI-assisted writing capabilities to the product planning workflow. Inspired by modern AI code editors, it enables product teams to draft, refine, and convert PRDs into actionable development tasks—all within a real-time collaborative environment.

The system integrates with GitHub, Notion, and Slack to pull contextual information (issues, pages, discussions) that inform the PRD content. An AI assistant helps users expand sections, refine language, and ultimately generate structured Lightsprint tasks from the finalized document.

**Key Value Propositions:**
- **Collaborative editing** with real-time cursors and presence (like Google Docs)
- **AI-powered assistance** for writing, expanding, and refining PRD content
- **Contextual integration** with existing tools (GitHub, Notion, Slack)
- **Seamless task generation** that converts PRDs into actionable Lightsprint tasks

---

## Overview of Approach

### Architecture Philosophy

The implementation follows Lightsprint's existing patterns while introducing new capabilities:

1. **Database-First Design**: All features are backed by persistent storage. PRD content, chat history, integrations, and generated tasks are stored in PostgreSQL with proper relational constraints.

2. **Real-Time Collaboration via Yjs**: We use Yjs CRDTs (Conflict-free Replicated Data Types) for document synchronization. This allows multiple users to edit simultaneously without conflicts, with changes merging automatically.

3. **Streaming AI Responses**: All AI interactions (chat, task generation, command actions) use Server-Sent Events (SSE) for streaming responses, providing immediate feedback to users.

4. **OAuth-Based Integrations**: Notion and Slack use OAuth 2.0 with PKCE for secure token exchange. GitHub leverages the existing GitHub App installation tokens.

5. **Service Layer Abstraction**: Integration logic is encapsulated in service files, keeping API routes thin and testable.

### Data Flow

```
┌─────────────────────────────────────────────────────────────────────────┐
│                           USER INTERFACE                                 │
├─────────────────────────────────────────────────────────────────────────┤
│  PRD List Page          PRD Editor Page           Settings Page         │
│  - View all PRDs        - Tiptap + Yjs editor     - OAuth connections   │
│  - Create/delete        - AI chat panel           - GitHub installs     │
│                         - Integration browser                           │
│                         - Task generation                               │
└──────────────────────────────┬──────────────────────────────────────────┘
                               │
                               ▼
┌─────────────────────────────────────────────────────────────────────────┐
│                           API LAYER                                      │
├─────────────────────────────────────────────────────────────────────────┤
│  /api/prds/*              /api/integrations/*      /api/*/oauth         │
│  - CRUD operations        - GitHub context         - Notion OAuth       │
│  - Chat (SSE)             - Notion search/pages    - Slack OAuth        │
│  - Task generation        - Slack channels/search                       │
│  - Collaborators                                                        │
│  - Integrations                                                         │
└──────────────────────────────┬──────────────────────────────────────────┘
                               │
                               ▼
┌─────────────────────────────────────────────────────────────────────────┐
│                         SERVICE LAYER                                    │
├─────────────────────────────────────────────────────────────────────────┤
│  github-context.service    notion.service          slack.service        │
│  - Repo/issue/PR access    - Page/database access  - Channel/message    │
│  - Code search             - Block → markdown      - Thread replies     │
│  - Installation tokens     - Rich text parsing     - User resolution    │
└──────────────────────────────┬──────────────────────────────────────────┘
                               │
                               ▼
┌─────────────────────────────────────────────────────────────────────────┐
│                         DATABASE LAYER                                   │
├─────────────────────────────────────────────────────────────────────────┤
│  prd_documents    prd_collaborators    prd_versions    prd_comments     │
│  prd_chat_*       prd_integrations     prd_generated_tasks              │
│  notion_connections    slack_connections    *_oauth_states              │
└─────────────────────────────────────────────────────────────────────────┘
```

### Technology Stack

| Layer | Technology | Purpose |
|-------|------------|---------|
| Editor | Tiptap 3.x | Rich text editing with extensible architecture |
| Collaboration | Yjs + y-websocket | CRDT-based real-time sync |
| AI | Anthropic SDK | Chat, suggestions, task generation |
| Streaming | Server-Sent Events | Real-time AI response delivery |
| Database | PostgreSQL + Drizzle | Persistent storage with type safety |
| Real-time Events | Socket.IO (existing) | Presence and notifications |

---

## Detailed Implementation

### Phase 1: Foundation (Database & Types)

**Objective:** Establish the data model that supports all PRD features.

#### 1.1 Database Schema Extensions

The schema introduces 12 new tables organized into logical groups:

**PRD Core (4 tables)**

| Table | Purpose | Key Fields |
|-------|---------|------------|
| `prd_documents` | Primary PRD storage | `content` (JSONB sections), `status`, `workspaceId`, `projectId` |
| `prd_collaborators` | Access control | `userId`, `role` (owner/editor/commenter/viewer) |
| `prd_versions` | Version history | `contentSnapshot`, `versionNumber`, `changeType` |
| `prd_comments` | Inline/section comments | `sectionId`, `startOffset`, `endOffset`, `selectedText` |

The `content` field in `prd_documents` stores a structured JSONB object:
```typescript
{
  sections: [
    {
      id: string,
      type: 'overview' | 'problem_statement' | 'objectives' | ...,
      title: string,
      content: string,  // Rich text HTML
      order: number,
      isRequired: boolean,
      aiGenerated: boolean
    }
  ],
  metadata: {
    targetAudience: string,
    successMetrics: string[],
    timeline: string,
    priority: 'low' | 'medium' | 'high' | 'critical'
  }
}
```

**AI & Chat (2 tables)**

| Table | Purpose | Key Fields |
|-------|---------|------------|
| `prd_chat_sessions` | Conversation containers | `prdId`, `userId`, `sectionContext` |
| `prd_chat_messages` | Individual messages | `role`, `content`, `toolCalls`, `suggestedChanges` |

Chat sessions are scoped to a PRD and optionally to a specific section, allowing context-aware AI assistance.

**Integration & Tasks (2 tables)**

| Table | Purpose | Key Fields |
|-------|---------|------------|
| `prd_integrations` | External context sources | `integrationType`, `externalUrl`, `cachedContent` |
| `prd_generated_tasks` | PRD → Task mapping | `prdId`, `taskId`, `batchId`, `confidenceScore` |

Integration types include: `github_issue`, `github_pr`, `github_discussion`, `notion_page`, `notion_database`, `slack_thread`, `slack_channel`, `custom_url`, `uploaded_document`.

**OAuth (4 tables)**

| Table | Purpose | Scope |
|-------|---------|-------|
| `notion_connections` | Notion access tokens | Per-user |
| `slack_connections` | Slack bot tokens | Per-workspace |
| `notion_oauth_states` | PKCE flow state | Temporary (5min TTL) |
| `slack_oauth_states` | PKCE flow state | Temporary (5min TTL) |

**Task Table Extension**

Add two columns to the existing `tasks` table:
- `source_prd_id`: Links task back to originating PRD
- `prd_section_id`: Which section generated this task

#### 1.2 TypeScript Type Definitions

Create `src/lib/types/prd.ts` with comprehensive type definitions:

```typescript
// Section types - 13 predefined categories
export type PRDSectionType =
  | 'overview' | 'problem_statement' | 'objectives'
  | 'user_stories' | 'functional_requirements'
  | 'non_functional_requirements' | 'technical_considerations'
  | 'scope' | 'out_of_scope' | 'dependencies'
  | 'risks' | 'success_criteria' | 'custom';

// Status workflow
export type PRDStatus =
  | 'draft'           // Initial state
  | 'in_review'       // Under team review
  | 'approved'        // Signed off
  | 'ready_for_tasks' // Ready for task generation
  | 'generating_tasks'// AI processing
  | 'completed'       // Tasks created
  | 'archived';       // No longer active

// Collaborator permissions
export type PRDCollaboratorRole = 'owner' | 'editor' | 'commenter' | 'viewer';

// Real-time presence for collaborative editing
export interface PRDPresenceUser {
  userId: string;
  name: string;
  color: string;
  cursorPosition?: { sectionId: string; offset: number };
  isActive: boolean;
  lastSeen: Date;
}
```

#### 1.3 Real-time Event Types

Extend `src/lib/server/realtime.ts` with PRD-specific events:

```typescript
| { type: 'prd.created'; projectId: string; prd: any }
| { type: 'prd.updated'; projectId: string; prdId: string; changes: any }
| { type: 'prd.deleted'; projectId: string; prdId: string }
| { type: 'prd.presenceUpdated'; projectId: string; prdId: string; userId: string; presence: any }
| { type: 'prd.commentAdded'; projectId: string; prdId: string; comment: any }
```

---

### Phase 2: Integration Services

**Objective:** Build the service layer that connects to external platforms.

#### 2.1 GitHub Context Service

**File:** `src/lib/server/services/integrations/github-context.service.ts`

This service extends the existing GitHub App functionality to fetch contextual information:

```typescript
// Core functions
listUserRepositories(userId: string): Promise<Repository[]>
listRepoIssues(installationId: number, fullName: string, options?: ListOptions): Promise<Issue[]>
getIssue(installationId: number, fullName: string, issueNumber: number): Promise<IssueWithComments>
listRepoPullRequests(installationId: number, fullName: string, options?: ListOptions): Promise<PR[]>
getPullRequest(installationId: number, fullName: string, prNumber: number): Promise<PRWithDetails>
searchRepoCode(installationId: number, fullName: string, query: string): Promise<CodeSearchResult[]>
getFileContent(installationId: number, fullName: string, path: string, ref?: string): Promise<string>

// Formatting helpers for AI context
formatIssueAsText(issue: IssueWithComments): string
formatPRAsText(pr: PRWithDetails): string
```

**Key Implementation Details:**
- Uses existing GitHub App installation tokens (no new OAuth needed)
- Filters PR results from issues endpoint (GitHub returns PRs as issues)
- Includes file change stats for PRs (additions/deletions per file)
- Text formatting produces AI-friendly markdown

#### 2.2 Notion Service

**File:** `src/lib/server/services/integrations/notion.service.ts`

Integrates with Notion's API to fetch pages and databases:

```typescript
getNotionConnection(userId: string): Promise<NotionConnection | null>
searchNotion(userId: string, query: string, options?: SearchOptions): Promise<SearchResult[]>
listDatabases(userId: string): Promise<Database[]>
getPageContent(userId: string, pageId: string): Promise<PageWithContent>
```

**Block-to-Markdown Conversion:**

The service converts Notion's block structure to markdown:

| Notion Block | Markdown Output |
|--------------|-----------------|
| `paragraph` | Plain text |
| `heading_1/2/3` | `#`, `##`, `###` |
| `bulleted_list_item` | `- item` |
| `numbered_list_item` | `1. item` |
| `to_do` | `- [ ]` or `- [x]` |
| `quote` | `> text` |
| `code` | ` ```lang\ncode\n``` ` |
| `callout` | `> emoji text` |
| `image` | `![](url)` |

**Rich Text Formatting:**
- Bold: `**text**`
- Italic: `*text*`
- Strikethrough: `~~text~~`
- Code: `` `text` ``
- Links: `[text](url)`

#### 2.3 Slack Service

**File:** `src/lib/server/services/integrations/slack.service.ts`

Connects to Slack workspaces for message context:

```typescript
getSlackConnection(workspaceId: string): Promise<SlackConnection | null>
listChannels(workspaceId: string, options?: ChannelOptions): Promise<Channel[]>
getChannelHistory(workspaceId: string, channelId: string, options?: HistoryOptions): Promise<Message[]>
getThreadReplies(workspaceId: string, channelId: string, threadTs: string): Promise<Message[]>
searchMessages(workspaceId: string, query: string, options?: SearchOptions): Promise<SearchResult[]>
getUser(workspaceId: string, userId: string): Promise<User>
getUsers(workspaceId: string, userIds: string[]): Promise<User[]>  // Batched
getChannelContentAsText(workspaceId: string, channelId: string, options?: ExportOptions): string
```

**Key Implementation Details:**
- Workspace-scoped tokens (shared across workspace members)
- Batch user fetching (10 users per request to avoid rate limits)
- Thread expansion for complete conversation context
- ISO timestamp formatting for readability

---

### Phase 3: OAuth Flows

**Objective:** Implement secure OAuth connections for Notion and Slack.

#### 3.1 Notion OAuth (Per-User)

**Endpoints:**
- `GET /api/user/notion-oauth` - Check connection status, get auth URL
- `POST /api/user/notion-oauth` - Complete OAuth with code/state
- `DELETE /api/user/notion-oauth` - Disconnect

**Flow:**
1. User clicks "Connect Notion" → redirects to Notion authorization
2. Notion redirects back to `/api/user/notion-oauth/callback` with code
3. Frontend extracts code from URL params, sends to POST endpoint
4. Server exchanges code for access token, stores in `notion_connections`
5. Connection status shown in settings

**PKCE Implementation:**
- State parameter stored in `notion_oauth_states` with 5-minute TTL
- Code verifier generated and stored with state
- Prevents CSRF and authorization code interception attacks

#### 3.2 Slack OAuth (Per-Workspace)

**Endpoints:**
- `GET /api/workspaces/[workspaceId]/slack-oauth` - Check status, get auth URL
- `POST /api/workspaces/[workspaceId]/slack-oauth` - Complete OAuth
- `DELETE /api/workspaces/[workspaceId]/slack-oauth` - Disconnect

**Flow:**
Similar to Notion, but scoped to workspace rather than user. Any workspace member can initiate, but the connection is shared.

**Required Scopes:**
- `channels:read` - List public channels
- `channels:history` - Read message history
- `groups:read` - List private channels (user is member of)
- `groups:history` - Read private channel history
- `search:read` - Search messages
- `users:read` - Resolve user names

---

### Phase 4: API Endpoints

**Objective:** Build the REST API for PRD operations.

#### 4.1 PRD CRUD Operations

**`/api/prds`**
- `GET` - List PRDs accessible to user (via workspace membership or direct collaboration)
- `POST` - Create new PRD with default sections template

**`/api/prds/[id]`**
- `GET` - Fetch PRD with content, collaborators, integrations
- `PATCH` - Update PRD content, status, or metadata
- `DELETE` - Delete PRD (cascades to related records)

**Default Sections Template:**
When creating a new PRD, initialize with 12 standard sections:
1. Overview
2. Problem Statement
3. Objectives
4. User Stories
5. Functional Requirements
6. Non-Functional Requirements
7. Technical Considerations
8. Scope
9. Out of Scope
10. Dependencies
11. Risks
12. Success Criteria

#### 4.2 Collaboration Endpoints

**`/api/prds/[id]/collaborators`**
- `GET` - List collaborators with roles
- `POST` - Invite collaborator (email → user lookup)
- `DELETE` - Remove collaborator

**Access Control Logic:**
```
Owner: Full control, can delete PRD, manage all collaborators
Editor: Can edit content, add comments, view integrations
Commenter: Can add comments, cannot edit content
Viewer: Read-only access
```

#### 4.3 AI Chat Endpoint

**`POST /api/prds/[id]/chat`** (SSE Streaming)

**Request:**
```json
{
  "message": "Expand the user stories section with more detail",
  "sessionId": "optional-existing-session",
  "sectionContext": "user_stories"
}
```

**SSE Events:**
```
event: session
data: {"sessionId": "abc123"}

event: content
data: {"text": "Here are "}

event: content
data: {"text": "expanded user stories..."}

event: done
data: {}
```

**System Prompt Context:**
The AI receives:
- Full PRD content (all sections)
- Current section context (if specified)
- Recent chat history from session
- Integration context summaries (if attached)

#### 4.4 Task Generation Endpoint

**`POST /api/prds/[id]/generate-tasks`** (SSE Streaming)

**Request:**
```json
{
  "projectId": "optional-target-project"
}
```

**SSE Events:**
```
event: batch_started
data: {"batchId": "batch123", "estimatedTasks": 5}

event: task_generated
data: {"task": {"title": "...", "description": "...", "complexity": "medium", ...}}

event: task_created
data: {"taskId": "task456", "title": "..."}

event: completed
data: {"totalTasks": 5, "batchId": "batch123"}
```

**AI Prompt Strategy:**
1. Analyze all PRD sections for actionable items
2. Extract 3-10 discrete tasks with clear boundaries
3. For each task, generate:
   - Title (imperative verb phrase)
   - Description (context and acceptance criteria)
   - Complexity (low/medium/high/critical)
   - Todo list (5-8 checkbox items)
   - Related PRD sections
   - Dependencies on other generated tasks
4. Order tasks by execution dependency

#### 4.5 Integration Context Endpoints

**GitHub (via existing installations):**
```
GET /api/integrations/github/repos
GET /api/integrations/github/repos/[fullName]/issues
GET /api/integrations/github/repos/[fullName]/issues/[number]
GET /api/integrations/github/repos/[fullName]/pulls
GET /api/integrations/github/repos/[fullName]/pulls/[number]
```

**Notion (via user OAuth):**
```
GET /api/integrations/notion/search?q=query
GET /api/integrations/notion/pages/[id]
```

**Slack (via workspace OAuth):**
```
GET /api/integrations/slack/channels
GET /api/integrations/slack/channels/[id]
GET /api/integrations/slack/search?q=query
```

**Adding Integration to PRD:**
```
POST /api/prds/[id]/integrations
{
  "integrationType": "github_issue",
  "externalId": "owner/repo#123",
  "externalUrl": "https://github.com/owner/repo/issues/123"
}
```

The server fetches and caches the content, storing it in `prd_integrations` for AI context.

---

### Phase 5: Editor Components

**Objective:** Build the rich text editor with real-time collaboration.

#### 5.1 Tiptap Editor Architecture

**Base Editor (`TiptapEditor.svelte`):**

A standalone Tiptap editor for single-user editing scenarios:

```svelte
<script lang="ts">
  import { Editor } from '@tiptap/core';
  import StarterKit from '@tiptap/starter-kit';
  import Placeholder from '@tiptap/extension-placeholder';
  import Highlight from '@tiptap/extension-highlight';
  import Typography from '@tiptap/extension-typography';
  import Underline from '@tiptap/extension-underline';
  import Link from '@tiptap/extension-link';
  import TaskList from '@tiptap/extension-task-list';
  import TaskItem from '@tiptap/extension-task-item';

  // Initialize editor with extensions
  let editor = new Editor({
    extensions: [
      StarterKit,
      Placeholder.configure({ placeholder: 'Start writing...' }),
      Highlight.configure({ multicolor: true }),
      Typography,
      Underline,
      Link.configure({ openOnClick: false }),
      TaskList,
      TaskItem.configure({ nested: true })
    ],
    content: initialContent,
    onUpdate: ({ editor }) => dispatch('update', editor.getHTML())
  });
</script>
```

**Exported Methods:**
- `focus()`, `blur()` - Focus management
- `getHTML()`, `getText()` - Content extraction
- `toggleBold()`, `toggleItalic()`, `toggleUnderline()`, `toggleStrike()` - Inline formatting
- `toggleCode()`, `toggleCodeBlock()` - Code formatting
- `toggleBulletList()`, `toggleOrderedList()`, `toggleTaskList()` - Lists
- `setHeading(level)` - Headings 1-4
- `insertLink(url)` - Link insertion

#### 5.2 Collaborative Editor (`CollaborativeTiptapEditor.svelte`)

Extends the base editor with Yjs for real-time sync:

```svelte
<script lang="ts">
  import * as Y from 'yjs';
  import { WebsocketProvider } from 'y-websocket';
  import Collaboration from '@tiptap/extension-collaboration';
  import CollaborationCursor from '@tiptap/extension-collaboration-cursor';

  // Create Yjs document
  const ydoc = new Y.Doc();

  // Connect to WebSocket provider
  const provider = new WebsocketProvider(
    WS_URL,
    `prd-${prdId}`,  // Room name
    ydoc
  );

  // Initialize editor with collaboration extensions
  let editor = new Editor({
    extensions: [
      // ... base extensions
      Collaboration.configure({ document: ydoc }),
      CollaborationCursor.configure({
        provider,
        user: { name: currentUser.name, color: currentUser.color }
      })
    ]
  });

  // Track connection status
  provider.on('status', ({ status }) => {
    connectionStatus = status;
  });

  // Track connected users
  provider.awareness.on('change', () => {
    connectedUsers = Array.from(provider.awareness.getStates().values());
  });
</script>
```

**Visual Indicators:**
- Connection status badge (connected/disconnected/syncing)
- User avatars with assigned colors
- Remote cursors with user labels
- Selection highlights for other users

#### 5.3 Editor Toolbar (`EditorToolbar.svelte`)

Formatting controls organized by category:

```
┌───────────────────────────────────────────────────────────────┐
│ [B] [I] [U] [S] [</>] │ [H1] [H2] [H3] [H4] │ [•] [1.] [☐] │
│ Text Formatting       │ Headings            │ Lists         │
├───────────────────────────────────────────────────────────────┤
│ ["] [```] │ [🔗 Link] │ [↶] [↷]                              │
│ Blocks    │           │ Undo/Redo                            │
└───────────────────────────────────────────────────────────────┘
```

Each button reflects current selection state (active/inactive) and triggers corresponding editor commands.

#### 5.4 AI Features

**Command Menu (`PRDCommandMenu.svelte`):**

Triggered by `Cmd+K` or text selection, shows AI actions:

| Action | Description |
|--------|-------------|
| Expand section | Add more detail to current section |
| Simplify language | Make text more concise |
| Add acceptance criteria | Generate AC for requirements |
| Convert to tasks | Preview task generation for selection |
| Ask AI... | Open chat with selected context |

**Implementation:**
- Floating menu positioned at cursor/selection
- Keyboard navigation (arrow keys, enter to select)
- Each action calls `/api/prds/[id]/command` with action type and context

#### 5.5 Task Generation Modal (`TaskGenerationModal.svelte`)

Multi-step workflow for generating tasks:

**Step 1: Configuration**
- Select target project (or create new)
- Review PRD summary
- See attached integrations

**Step 2: Generation (Streaming)**
- Progress indicator
- Tasks appear as cards as they're generated
- Each card shows: title, description, complexity badge, todo preview

**Step 3: Review & Edit**
- Expand/collapse task details
- Edit title, description inline
- Reorder or remove tasks
- View dependencies between tasks

**Step 4: Creation**
- "Create X Tasks" button
- Progress as tasks are created
- Success summary with links to created tasks

#### 5.6 Integration Browser (`IntegrationContextBrowser.svelte`)

Three-tab modal for browsing external content:

**GitHub Tab:**
```
Repositories (dropdown)
└── Issues / Pull Requests (tabs)
    └── List with: number, title, state, author, date
        └── Click → Detail view with description, comments
            └── "Add to PRD" button
```

**Notion Tab:**
```
Search input
└── Results: pages and databases with icons
    └── Click → Content preview (converted to markdown)
        └── "Add to PRD" button
```

**Slack Tab:**
```
Channels (list)
└── Click → Recent messages
    └── Thread expansion
        └── "Add to PRD" button

Search input
└── Message results across all channels
```

---

### Phase 6: Frontend Pages

**Objective:** Build the user-facing pages for PRD management.

#### 6.1 PRD List Page (`/prds`)

**Layout:**
```
┌─────────────────────────────────────────────────────────────┐
│  PRDs                                    [+ New PRD]        │
│  Workspace: [Dropdown ▼]                                    │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────────────────────────────────────────────────┐   │
│  │ Mobile App Redesign PRD                             │   │
│  │ Draft • Created Jan 15 • 3 collaborators            │   │
│  │                                        [Edit] [🗑️]   │   │
│  └─────────────────────────────────────────────────────┘   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │ API V2 Requirements                                 │   │
│  │ In Review • Created Jan 10 • 5 collaborators        │   │
│  │                                        [Edit] [🗑️]   │   │
│  └─────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────┘
```

**Features:**
- Workspace filter
- Status badges with distinct colors
- Collaborator count
- Delete with confirmation modal
- Empty state with "Create your first PRD" CTA

#### 6.2 PRD Editor Page (`/prds/[id]`)

**Layout:**
```
┌─────────────────────────────────────────────────────────────────────────┐
│  ← Back   │ [PRD Title - editable]   │ Status: [Draft ▼] │ 👤👤👤      │
│           │                          │                    │ Collaborators│
├───────────┴──────────────────────────┴────────────────────┴─────────────┤
│  [Integrations] [Share] [Generate Tasks ▼] [Export]                     │
├─────────────────────────────────────────────────────┬───────────────────┤
│                                                     │                   │
│  Section Navigation (left sidebar)                  │   AI Chat Panel   │
│  • Overview ────────────────────────────────────    │   ────────────    │
│  • Problem Statement                                │   [Chat history]  │
│  • Objectives                                       │                   │
│  • User Stories                                     │   [User msg]      │
│  • ...                                              │   [AI response]   │
│                                                     │                   │
│  ════════════════════════════════════════════════   │   ────────────    │
│                                                     │                   │
│  ## Overview                          [Toolbar]     │   [Input field]   │
│  ┌─────────────────────────────────────────────┐   │   [Send button]   │
│  │                                             │   │                   │
│  │  [Tiptap Editor Content]                    │   │                   │
│  │                                             │   │                   │
│  │  Remote cursors visible here                │   │                   │
│  │                                             │   │                   │
│  └─────────────────────────────────────────────┘   │                   │
│                                                     │                   │
└─────────────────────────────────────────────────────┴───────────────────┘
```

**Features:**
- Inline title editing
- Status dropdown with workflow transitions
- Real-time collaborator avatars with presence
- Section navigation sidebar
- Collapsible AI chat panel
- Integration browser modal
- Task generation modal
- Export to markdown/PDF

---

### Phase 7: Settings Integration

**Objective:** Add integration management to settings pages.

#### 7.1 Integration Settings Component

**File:** `src/lib/components/settings/IntegrationSettings.svelte`

**GitHub Section:**
- Lists all GitHub App installations
- Shows: account name, type (org/user), repository scope
- Status: Active/Suspended badge
- Actions: Manage (link to GitHub), Reinstall (if suspended)
- "Add installation" link

**Notion Section:**
- Connection status with workspace info
- If connected: workspace icon/name, connected date, disconnect button
- If not connected: "Connect Notion" button → OAuth flow

**Slack Note:**
- Message directing to workspace settings for Slack configuration

#### 7.2 Workspace Settings Enhancement

Add Slack integration panel to workspace settings:
- Similar UI pattern to Notion in user settings
- Team name and connection date when connected
- "Connect Slack" button → workspace-scoped OAuth

---

## Migration Strategy

### Database Migration Order

1. **0064_powerful_mulholland_black.sql** - All new tables
   - PRD core tables (documents, collaborators, versions, comments)
   - AI tables (chat sessions, messages)
   - Integration tables (integrations, generated tasks)
   - OAuth tables (connections, states)
   - Task table columns (source_prd_id, prd_section_id)

2. **0065_unusual_prism.sql** - File metadata columns
   - Add file_name, file_size, file_mime_type to prd_integrations

### Rollback Considerations

- All new tables can be dropped without affecting existing data
- Task table columns are nullable, safe to remove
- OAuth connections are isolated; removal doesn't affect core functionality

---

## Testing Strategy

### Unit Tests

| Area | Test Cases |
|------|------------|
| Schema | Table relationships, constraints, indexes |
| Services | API mocking for GitHub/Notion/Slack |
| Type guards | PRDSection, PRDStatus validation |

### Integration Tests

| Flow | Steps |
|------|-------|
| PRD CRUD | Create → Read → Update → Delete |
| Collaboration | Add collaborator → Verify access → Remove |
| OAuth | Initiate → Callback → Verify token storage |
| Chat | Send message → Receive stream → Verify storage |

### E2E Scenarios

1. **Full PRD Lifecycle**
   - Create PRD → Edit sections → Invite collaborator → Generate tasks → View on Kanban

2. **Collaborative Editing**
   - Open PRD in two browsers → Verify cursor sync → Make edits → Verify merge

3. **Integration Flow**
   - Connect Notion → Add page to PRD → Verify in AI context → Generate tasks

### Manual Testing Checklist

- [ ] Create PRD with default sections
- [ ] Edit content with rich text formatting
- [ ] Real-time sync between multiple users
- [ ] AI chat responds contextually
- [ ] Command+K menu functions
- [ ] GitHub integration shows repos/issues
- [ ] Notion OAuth connect/disconnect
- [ ] Slack OAuth connect/disconnect
- [ ] Task generation creates valid tasks
- [ ] Tasks link back to PRD

---

## File Inventory

### New Files (41 total)

**Database & Types (5)**
```
drizzle/0064_powerful_mulholland_black.sql
drizzle/0065_unusual_prism.sql
drizzle/meta/0064_snapshot.json
drizzle/meta/0065_snapshot.json
src/lib/types/prd.ts
```

**Services (3)**
```
src/lib/server/services/integrations/github-context.service.ts
src/lib/server/services/integrations/notion.service.ts
src/lib/server/services/integrations/slack.service.ts
```

**Components (7)**
```
src/lib/components/prd-editor/index.ts
src/lib/components/prd-editor/TiptapEditor.svelte
src/lib/components/prd-editor/CollaborativeTiptapEditor.svelte
src/lib/components/prd-editor/EditorToolbar.svelte
src/lib/components/prd-editor/PRDCommandMenu.svelte
src/lib/components/prd-editor/TaskGenerationModal.svelte
src/lib/components/prd-editor/IntegrationContextBrowser.svelte
```

**API Routes (20)**
```
src/routes/api/prds/+server.ts
src/routes/api/prds/[id]/+server.ts
src/routes/api/prds/[id]/chat/+server.ts
src/routes/api/prds/[id]/command/+server.ts
src/routes/api/prds/[id]/generate-tasks/+server.ts
src/routes/api/prds/[id]/collaborators/+server.ts
src/routes/api/prds/[id]/integrations/+server.ts
src/routes/api/prds/[id]/integrations/[integrationId]/+server.ts
src/routes/api/prds/[id]/documents/+server.ts
src/routes/api/integrations/github/repos/+server.ts
src/routes/api/integrations/github/repos/[fullName]/issues/+server.ts
src/routes/api/integrations/github/repos/[fullName]/issues/[number]/+server.ts
src/routes/api/integrations/github/repos/[fullName]/pulls/+server.ts
src/routes/api/integrations/github/repos/[fullName]/pulls/[number]/+server.ts
src/routes/api/integrations/notion/search/+server.ts
src/routes/api/integrations/notion/pages/[id]/+server.ts
src/routes/api/integrations/slack/channels/+server.ts
src/routes/api/integrations/slack/channels/[id]/+server.ts
src/routes/api/integrations/slack/search/+server.ts
src/routes/api/user/notion-oauth/+server.ts (or callback)
src/routes/api/slack-oauth/callback/+server.ts
src/routes/api/workspaces/[workspaceId]/slack-oauth/+server.ts
```

**Pages (4)**
```
src/routes/prds/+page.svelte
src/routes/prds/+page.server.ts
src/routes/prds/[id]/+page.svelte
src/routes/prds/[id]/+page.server.ts
```

**Utilities (1)**
```
src/lib/utils/prd-chat-handler.ts
```

**Settings (1)**
```
src/lib/components/settings/IntegrationSettings.svelte
```

### Modified Files (8 total)

```
package.json                                    (+15 dependencies)
bun.lock                                        (lockfile update)
drizzle/meta/_journal.json                      (+2 migration entries)
drizzle/0000_init.sql                           (minor adjustment)
drizzle/0049_split_task_ui_state.sql            (adjustment)
drizzle/0054_lazy_hulk.sql                      (adjustment)
src/lib/server/db/schema.ts                     (+491 lines)
src/lib/server/realtime.ts                      (+10 lines)
src/lib/components/UserSettings.svelte          (minor)
src/lib/components/WorkspaceSettings.svelte     (+213 lines)
src/lib/components/settings/AccountSettings.svelte (refactor)
src/routes/settings/+page.svelte                (+25 lines)
```

---

## Appendix: Default PRD Sections

```typescript
export const DEFAULT_PRD_SECTIONS: PRDSection[] = [
  {
    id: nanoid(),
    type: 'overview',
    title: 'Overview',
    content: '',
    order: 0,
    isRequired: true,
    aiGenerated: false
  },
  {
    id: nanoid(),
    type: 'problem_statement',
    title: 'Problem Statement',
    content: '',
    order: 1,
    isRequired: true,
    aiGenerated: false
  },
  {
    id: nanoid(),
    type: 'objectives',
    title: 'Objectives',
    content: '',
    order: 2,
    isRequired: true,
    aiGenerated: false
  },
  {
    id: nanoid(),
    type: 'user_stories',
    title: 'User Stories',
    content: '',
    order: 3,
    isRequired: false,
    aiGenerated: false
  },
  {
    id: nanoid(),
    type: 'functional_requirements',
    title: 'Functional Requirements',
    content: '',
    order: 4,
    isRequired: true,
    aiGenerated: false
  },
  {
    id: nanoid(),
    type: 'non_functional_requirements',
    title: 'Non-Functional Requirements',
    content: '',
    order: 5,
    isRequired: false,
    aiGenerated: false
  },
  {
    id: nanoid(),
    type: 'technical_considerations',
    title: 'Technical Considerations',
    content: '',
    order: 6,
    isRequired: false,
    aiGenerated: false
  },
  {
    id: nanoid(),
    type: 'scope',
    title: 'Scope',
    content: '',
    order: 7,
    isRequired: true,
    aiGenerated: false
  },
  {
    id: nanoid(),
    type: 'out_of_scope',
    title: 'Out of Scope',
    content: '',
    order: 8,
    isRequired: false,
    aiGenerated: false
  },
  {
    id: nanoid(),
    type: 'dependencies',
    title: 'Dependencies',
    content: '',
    order: 9,
    isRequired: false,
    aiGenerated: false
  },
  {
    id: nanoid(),
    type: 'risks',
    title: 'Risks',
    content: '',
    order: 10,
    isRequired: false,
    aiGenerated: false
  },
  {
    id: nanoid(),
    type: 'success_criteria',
    title: 'Success Criteria',
    content: '',
    order: 11,
    isRequired: true,
    aiGenerated: false
  }
];
```
