# oAI — Development Guide

## Project Structure

```
oAI/
├── Models/              # Data models
│   ├── Message.swift           # Chat message model
│   ├── Conversation.swift      # Saved conversation model
│   ├── ModelInfo.swift         # AI model metadata
│   └── Settings.swift          # App settings enums
│
├── Views/               # SwiftUI views
│   ├── Main/                   # Primary UI components
│   │   ├── ChatView.swift      # Main chat interface
│   │   ├── MessageRow.swift    # Individual message display
│   │   ├── InputBar.swift      # Message input with commands
│   │   ├── HeaderView.swift    # Top bar (provider/model/status)
│   │   └── FooterView.swift    # Bottom stats bar
│   │
│   └── Screens/                # Modal/sheet views
│       ├── SettingsView.swift  # Settings with tabs
│       ├── ModelSelectorView.swift
│       ├── ConversationListView.swift
│       └── HelpView.swift
│
├── ViewModels/          # Observable view models
│   └── ChatViewModel.swift     # Main chat logic & state
│
├── Providers/           # AI provider implementations
│   ├── Provider.swift          # Protocol definition
│   ├── OpenRouterProvider.swift
│   ├── AnthropicProvider.swift
│   ├── OpenAIProvider.swift
│   └── OllamaProvider.swift
│
├── Services/            # Business logic & data
│   ├── DatabaseService.swift   # SQLite operations (GRDB)
│   ├── SettingsService.swift   # Settings persistence
│   ├── ProviderRegistry.swift  # AI provider management
│   ├── MCPService.swift        # File access (MCP)
│   ├── WebSearchService.swift  # DuckDuckGo/Google search
│   ├── GitSyncService.swift    # Git synchronization
│   ├── ContextSelectionService.swift  # Smart context
│   ├── EmbeddingService.swift  # Semantic search
│   ├── EmailService.swift      # Email monitoring (IMAP)
│   └── EmailHandlerService.swift  # Email AI responder
│
└── Resources/
    └── oAI.help/               # macOS Help Book
```

## Key Technologies

- **SwiftUI** - Modern declarative UI framework
- **GRDB** - SQLite database wrapper for persistence
- **MarkdownUI** - Markdown rendering with syntax highlighting
- **os.Logger** - Native logging framework
- **Network Framework** - Pure Swift IMAP/SMTP implementation
- **Security Framework** - Keychain and encryption services

## Database Schema

**Conversations**: id, name, createdAt, updatedAt
**Messages**: id, conversationId, role, content, tokens, cost, timestamp
**Message Metadata**: message_id, importance_score, user_starred, summary
**Message Embeddings**: message_id, embedding (BLOB), model, dimension
**Conversation Summaries**: id, conversationId, startIndex, endIndex, summary
**Email Logs**: id, sender, subject, status, timestamp

**Location:** `~/Library/Application Support/oAI/oai_conversations.db`

## Building

### Build Scripts

| Script | Architecture | Output |
|--------|-------------|--------|
| `build.sh` | Apple Silicon (arm64) | Installs directly to `/Applications` |
| `build-dmg.sh` | Apple Silicon (arm64) | `oAI-<version>-AppleSilicon.dmg` on Desktop |
| `build-dmg-universal.sh` | Universal (arm64 + x86_64) | `oAI-<version>-Universal.dmg` on Desktop |
| `build_nb/sv/da/de/en.sh` | Apple Silicon (arm64) | Build + launch in specific language |

All scripts: find Developer ID cert, clean-build via `xcodebuild`, re-sign with `codesign --options runtime --timestamp`, verify. Version is read from `MARKETING_VERSION` in `project.pbxproj`.

### Manual Build Commands

```bash
# Clean build
xcodebuild clean -scheme oAI

# Debug build
xcodebuild -scheme oAI -configuration Debug

# Run tests
xcodebuild test -scheme oAI
```

**Output:** `~/Library/Developer/Xcode/DerivedData/oAI-*/Build/Products/Debug/oAI.app`

In Xcode: `⌘B` build, `⌘R` run, `⌘⇧K` clean, `⌘.` stop.

### XProtect Note

XProtect 5331 flags Debug builds (bash + IMAP + file access = RAT signature match). Use `./build.sh` (Developer ID signed) for all local testing.

## Logs

```
~/Library/Logs/oAI.log
```

## Performance Notes

- **Context Selection**: 50-80% token reduction for long conversations
- **Semantic Search**: ~$0.02-0.15/month for heavy users
- **Conversation Export**: Markdown format for human readability
- **Database**: Indexed queries for fast conversation retrieval
- **Streaming**: Efficient memory usage with `AsyncThrowingStream`

## Contributing

Contributions are welcome! By submitting a pull request you agree that your contribution will be licensed under the AGPL-3.0.

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

Please ensure:
- Code follows Swift style guidelines
- All tests pass
- Documentation is updated
- Commit messages are descriptive

## Acknowledgments

- **MarkdownUI** - Excellent markdown rendering library
- **GRDB** - Robust SQLite wrapper for Swift
- **Anthropic, OpenAI, OpenRouter** - AI API providers
