# AI System Prompt: Filevine Document Viewer Extension

> **Purpose**: High-level system instructions for AI coding agents working on this project.  
> **Last Updated**: 2025-01-12

## Project Overview

The **Filevine Document Viewer** is a Chrome/Edge browser extension that enables legal professionals to browse, download, and view documents from their Filevine projects using specialized local viewers. The extension uses a hybrid authentication approach, extracting tokens from active Filevine sessions to make API calls without requiring additional user login.

**Key Goals**:
1. Seamless authentication leveraging active Filevine sessions
2. File discovery and browsing within projects
3. Local file processing with specialized viewers (starting with DICOM)
4. Extensible architecture for adding new file viewers

## File and Folder Structure

```
filevine-plugin/
├── manifest.json           # Chrome Extension MV3 manifest
├── package.json            # Node dependencies (minimal)
├── src/
│   ├── background/         # Background service worker
│   │   ├── index.js        # Message routing & initialization
│   │   ├── auth.js         # Token management & validation
│   │   ├── api.js          # Filevine API client
│   │   └── downloads.js    # Download queue & IndexedDB storage
│   ├── content/            # Content scripts (injected into Filevine pages)
│   │   ├── index.js        # Entry point
│   │   ├── detector.js     # Session/page change detection
│   │   └── extractor.js    # Token extraction from page context
│   ├── popup/              # Extension popup UI
│   │   ├── popup.html      # Popup markup
│   │   ├── popup.css       # Popup styles
│   │   └── popup.js        # UI controller
│   ├── viewers/            # File viewer plugins
│   │   ├── registry.js     # Viewer registration system
│   │   └── dicom/          # DICOM viewer (placeholder)
│   │       └── viewer.html # DICOM viewer UI
│   └── lib/                # Shared utilities
│       └── constants.js    # API URLs, message types, constants
├── public/
│   └── icons/              # Extension icons
├── docs/
│   └── DESIGN.md           # Full design specification
├── .ai/                     # AI agent documentation
│   ├── ARCHITECTURE.md      # System architecture overview
│   ├── SERVICES.md          # Complete service catalog
│   ├── DATA_FLOW.md         # Data flow diagrams
│   ├── DECISIONS.md         # Architecture Decision Records
│   ├── CURRENT_TASK.md      # Active work context
│   └── TROUBLESHOOTING.md   # Known issues and solutions
├── AI_INSTRUCTIONS.md       # Master documentation map (THIS FILE'S PARENT)
└── AI_System_Prompt.md      # This file
```

## Documentation System

This project uses a **documentation-first development** approach. All AI agents should:

1. **Read documentation before coding**: Start with `.ai/ARCHITECTURE.md` and relevant sections of `.ai/SERVICES.md`
2. **Update documentation when changing code**: Any service changes must update `.ai/SERVICES.md`
3. **Record decisions**: Architectural choices go in `.ai/DECISIONS.md`
4. **Document flows**: Data flow changes go in `.ai/DATA_FLOW.md`
5. **Track current work**: Update `.ai/CURRENT_TASK.md` with progress

### Documentation File Purposes

| File | Contains | When to Update |
|------|----------|----------------|
| `.ai/ARCHITECTURE.md` | System overview, tech stack, component diagram | New components, external deps |
| `.ai/SERVICES.md` | Service catalog with interfaces & dependencies | Any service change |
| `.ai/DATA_FLOW.md` | Sequence diagrams for key operations | Flow changes |
| `.ai/DECISIONS.md` | ADRs explaining WHY | Architectural choices |
| `.ai/CURRENT_TASK.md` | Active work context | Every session |
| `.ai/TROUBLESHOOTING.md` | Problems & solutions | Bug fixes |
| `AI_INSTRUCTIONS.md` | Master map of all documentation | When adding new docs |
| `AI_System_Prompt.md` | High-level system instructions | This file |

## How to Use the Documentation System

### Starting a New Task

1. **Read first** (in order):
   - `.ai/CURRENT_TASK.md` — Check for existing context
   - `.ai/ARCHITECTURE.md` — Understand system overview
   - `.ai/SERVICES.md` — Find relevant services (read specific sections only)
   - `.ai/DATA_FLOW.md` — Understand flows you're touching

2. **Update `.ai/CURRENT_TASK.md`** with:
   - Objective
   - Relevant files
   - Planned approach

3. **Do the work**

4. **Update documentation** before finishing:
   - Modified services → Update `.ai/SERVICES.md`
   - New patterns → Update `.ai/ARCHITECTURE.md`
   - Decisions made → Add to `.ai/DECISIONS.md`
   - Problems solved → Add to `.ai/TROUBLESHOOTING.md`
   - Progress → Update `.ai/CURRENT_TASK.md`

### Minimal Context Pattern

When starting fresh with minimal context, load files in this order:

```
1. .ai/ARCHITECTURE.md (always, ~500 tokens)
2. .ai/SERVICES.md → Section for service you're modifying (~300 tokens)
3. Specific source file(s) only
```

**Do NOT load entire codebase.** Use documentation to navigate.

## Key Services Overview

| Service | Purpose | Location |
|---------|---------|----------|
| **BackgroundService** | Message routing & initialization | `src/background/index.js` |
| **AuthManager** | Token management & validation | `src/background/auth.js` |
| **FilevineClient** | Filevine API client | `src/background/api.js` |
| **DownloadManager** | Download queue & storage | `src/background/downloads.js` |
| **ContentScript** | Content script entry point | `src/content/index.js` |
| **TokenDetector** | Session/page change detection | `src/content/detector.js` |
| **TokenExtractor** | Token extraction from page | `src/content/extractor.js` |
| **PopupController** | Popup UI controller | `src/popup/popup.js` |
| **ViewerRegistry** | Viewer registration system | `src/viewers/registry.js` |
| **Constants** | Shared constants | `src/lib/constants.js` |

See `.ai/SERVICES.md` for detailed documentation of each service.

## Critical Implementation Notes

### Authentication
- **Hybrid approach**: Extract tokens from Filevine page, use in background worker
- **Numeric User ID**: Must get from `GetUserOrgsWithToken`, NOT from JWT `sub` claim
- **Required headers**: All three `x-fv-*` headers required on every API call

### API Endpoints
- **Base URL**: `https://api.filevineapp.com/fv-app/v2` (NOT `api.filevine.io`)
- **Endpoint casing**: Use PascalCase (`/Projects` not `/projects`)
- **Rate limits**: 100/min burst, 600/hr sustained

### File Storage
- **IndexedDB**: Used for file blob storage (no size limits)
- **Session storage**: Used for auth tokens (cleared on browser close)
- **Cleanup**: Implement auto-expire for old files

## Development Workflow

1. **Load extension**: `chrome://extensions` → Load unpacked → Select `filevine-plugin` directory
2. **Make changes**: Edit source files
3. **Reload extension**: Click reload in `chrome://extensions`
4. **Test**: Navigate to Filevine, open extension popup
5. **Debug**: 
   - Background: `chrome://extensions` → Service worker link
   - Content script: DevTools on Filevine page
   - Popup: Right-click popup → Inspect

## Testing Strategy

- **Manual testing**: Primary method (see `README.md` for checklist)
- **Unit tests**: Not yet implemented (future)
- **Integration tests**: Not yet implemented (future)

## Common Tasks

### Adding a New Service
1. Create file in appropriate `src/` subdirectory
2. Add entry to `.ai/SERVICES.md` Quick Reference Index
3. Add full documentation section in `.ai/SERVICES.md`
4. Update `.ai/ARCHITECTURE.md` if major component
5. Update `.ai/DATA_FLOW.md` if changes data flows

### Adding a New Viewer
1. Create viewer HTML file in `src/viewers/{viewer-name}/`
2. Register in `src/viewers/registry.js`
3. Update `VIEWER_TYPES` in `src/lib/constants.js`
4. Document in `.ai/SERVICES.md` if complex

### Debugging Authentication
1. Check content script logs (DevTools on Filevine page)
2. Check background worker logs (`chrome://extensions` → service worker)
3. Verify tokens in storage: `localStorage.getItem('fv_access_token')`
4. Check network tab for API calls

## Related Documentation

- **`.ai/ARCHITECTURE.md`** — System architecture details
- **`.ai/SERVICES.md`** — Complete service catalog
- **`.ai/DATA_FLOW.md`** — Data flow diagrams
- **`.ai/DECISIONS.md`** — Architecture Decision Records
- **`.ai/TROUBLESHOOTING.md`** — Common issues and solutions
- **`AI_INSTRUCTIONS.md`** — Master documentation map
- **`docs/DESIGN.md`** — Full design specification
- **`README.md`** — Quick start guide

## Instructions for Creating Instruction Files

When creating or updating instruction files:

1. **Follow templates**: Use templates from `AI_INSTRUCTIONS.md` as reference
2. **Be specific**: Include file paths, code snippets, examples
3. **Link everything**: Cross-reference related documentation
4. **Keep updated**: Update when code changes
5. **Use consistent format**: Follow existing documentation style

### What Should Be Included

- **Purpose**: What the file/documentation is for
- **Structure**: How it's organized
- **Examples**: Code examples and usage patterns
- **Dependencies**: What it depends on and what depends on it
- **Configuration**: Environment variables, settings
- **Error handling**: What can go wrong and how it's handled
- **Performance**: Typical latencies, bottlenecks
- **Related**: Links to other documentation

## Quick Reference

- **Master Map**: `AI_INSTRUCTIONS.md` — Links to all documentation
- **Start Here**: `.ai/ARCHITECTURE.md` — System overview
- **Service Details**: `.ai/SERVICES.md` — Service catalog
- **Data Flows**: `.ai/DATA_FLOW.md` — Flow diagrams
- **Why Decisions**: `.ai/DECISIONS.md` — ADRs
- **Current Work**: `.ai/CURRENT_TASK.md` — Active context
- **Problems**: `.ai/TROUBLESHOOTING.md` — Known issues
