From 0b24423ca00da2f7f69f722fc87c057bce81368e Mon Sep 17 00:00:00 2001 From: LaMat <65860122+lamat1111@users.noreply.github.com> Date: Wed, 14 Jan 2026 16:12:20 +0100 Subject: [PATCH] feat: add agents infrastructure and documentation - Initialize .agents/ folder with docs workflow structure - Add AGENTS.md with Discord clone context and dev guidelines - Add quorum-shared-architecture.md for ecosystem reference - Create security-analyst agent for crypto/privacy review - Create mobile-platform-expert agent for iOS/Android UX - Add docs-manager skill for documentation workflow - Update .gitignore for native module builds and Claude settings --- .agents/AGENTS.md | 72 +++ .agents/INDEX.md | 23 + .agents/docs/quorum-shared-architecture.md | 650 +++++++++++++++++++++ .agents/update-index.py | 158 +++++ .claude/agents/mobile-platform-expert.md | 287 +++++++++ .claude/agents/security-analyst.md | 219 +++++++ .claude/commands/web-check.md | 8 + .claude/skills/docs-manager/SKILL.md | 595 +++++++++++++++++++ .gitignore | 7 + AGENTS.md | 190 ++++++ 10 files changed, 2209 insertions(+) create mode 100644 .agents/AGENTS.md create mode 100644 .agents/INDEX.md create mode 100644 .agents/docs/quorum-shared-architecture.md create mode 100644 .agents/update-index.py create mode 100644 .claude/agents/mobile-platform-expert.md create mode 100644 .claude/agents/security-analyst.md create mode 100644 .claude/commands/web-check.md create mode 100644 .claude/skills/docs-manager/SKILL.md create mode 100644 AGENTS.md diff --git a/.agents/AGENTS.md b/.agents/AGENTS.md new file mode 100644 index 0000000..eab8a2a --- /dev/null +++ b/.agents/AGENTS.md @@ -0,0 +1,72 @@ +# AGENTS.md + +Guidelines for AI agents working on this project. + +## Documentation Workflow + +This project uses a `.agents/` folder to organize AI-generated documentation, tasks, bugs, and reports. + +### Folder Structure + +``` +.agents/ +├── INDEX.md # Auto-generated index of all documentation +├── AGENTS.md # This file - agent guidelines +├── docs/ # Feature documentation +│ ├── features/ # Feature-specific docs +│ └── .archive/ # Archived documentation +├── tasks/ # Implementation tasks +│ ├── .done/ # Completed tasks +│ └── .archived/ # Obsolete/cancelled tasks +├── bugs/ # Bug reports +│ ├── .solved/ # Fixed bugs +│ └── .archived/ # Invalid/duplicate bugs +└── reports/ # Audits, research, analyses + ├── .done/ # Completed reports + └── .archived/ # Outdated reports +``` + +### File Naming Conventions + +- **General**: Use kebab-case: `feature-name.md` +- **Reports**: Include date: `security-audit_2025-01-15.md` +- **Numbered ordering**: Prefix with numbers: `01-setup.md`, `02-config.md` + +### Status System + +All documents use YAML frontmatter with these statuses: +- `open`: Ready to work on (default for new tasks/bugs) +- `in-progress`: Currently being implemented +- `on-hold`: Blocked or paused +- `done`: Completed +- `archived`: No longer relevant + +### Creating Documents + +Use the **docs-manager** skill for consistent templates: +- Bug reports → `.agents/bugs/` +- Tasks → `.agents/tasks/` +- Documentation → `.agents/docs/features/` +- Reports/Audits → `.agents/reports/` + +### Updating the Index + +After creating, moving, or deleting files, run the index update script to regenerate INDEX.md: + +```bash +python .agents/update-index.py +``` + +### Before Starting Work + +1. Check `INDEX.md` for existing documentation +2. Review related tasks in `.agents/tasks/` +3. Check for similar bugs in `.agents/bugs/` +4. Look for relevant reports in `.agents/reports/` + +### After Completing Work + +1. Update task/bug status to `done` +2. Move completed items to `.done/` or `.solved/` folders +3. Run the index update script +4. Create documentation for significant changes diff --git a/.agents/INDEX.md b/.agents/INDEX.md new file mode 100644 index 0000000..ae020bc --- /dev/null +++ b/.agents/INDEX.md @@ -0,0 +1,23 @@ +# Documentation Index + +This is the main index for all documentation, bug reports, and task management. + +## 📖 Documentation + +- [Quorum Ecosystem Architecture](docs/quorum-shared-architecture.md) ✅ + +## 🐛 Bug Reports + +*No bug reports yet.* + +## 📋 Tasks + +*No tasks yet.* + +## 📊 Reports + +*No reports yet.* + +--- + +**Last Updated**: 2026-01-14 diff --git a/.agents/docs/quorum-shared-architecture.md b/.agents/docs/quorum-shared-architecture.md new file mode 100644 index 0000000..1064d41 --- /dev/null +++ b/.agents/docs/quorum-shared-architecture.md @@ -0,0 +1,650 @@ +--- +type: doc +title: Quorum Ecosystem Architecture +status: done +created: 2026-01-14 +updated: 2026-01-14 +--- + +# Quorum Ecosystem Architecture + +This document provides a comprehensive guide to the Quorum multi-repository ecosystem and the `@quilibrium/quorum-shared` package that connects them. + +--- + +## Table of Contents + +1. [Ecosystem Overview](#ecosystem-overview) +2. [Repository Structure](#repository-structure) +3. [Cross-Repo Feature Development](#cross-repo-feature-development) +4. [Package Structure](#package-structure) +5. [Types Module](#types-module) +6. [Storage Adapter](#storage-adapter) +7. [Sync Protocol](#sync-protocol) +8. [React Query Hooks](#react-query-hooks) +9. [Utilities](#utilities) +10. [Crypto and Signing](#crypto-and-signing) +11. [Transport Layer](#transport-layer) +12. [Mobile Integration](#mobile-integration) +13. [Usage Examples](#usage-examples) + +--- + +## Ecosystem Overview + +Quorum is built as a **multi-repository ecosystem** where shared functionality lives in a central package consumed by both web/desktop and mobile applications. + +``` +┌─────────────────────────────────────────────────────────────────────────┐ +│ QUORUM ECOSYSTEM │ +├─────────────────────────────────────────────────────────────────────────┤ +│ │ +│ ┌────────────────────────────┐ │ +│ │ @quilibrium/quorum- │ │ +│ │ shared │ │ +│ │ │ │ +│ │ • Types & Interfaces │ │ +│ │ • Sync Protocol │ │ +│ │ • React Query Hooks │ │ +│ │ • Storage Adapter │ │ +│ │ • Crypto & Signing │ │ +│ │ • Utilities │ │ +│ └────────────┬───────────────┘ │ +│ │ │ +│ ┌────────────┴───────────────┐ │ +│ │ │ │ +│ ▼ ▼ │ +│ ┌──────────────────────────┐ ┌──────────────────────────┐ │ +│ │ quorum-desktop │ │ quorum-mobile │ │ +│ │ │ │ (this repo) │ │ +│ │ │ │ │ │ +│ │ • Web app (Vite) │ │ • React Native │ │ +│ │ • Desktop (Electron) │ │ • Expo │ │ +│ │ • IndexedDB storage │ │ • MMKV storage │ │ +│ │ • Web primitives │ │ • Native primitives │ │ +│ └──────────────────────────┘ └──────────────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────────┘ +``` + +### Key Principle: Data Sync Across Clients + +All clients (desktop, web, mobile) sync data via the **same protocol** defined in `quorum-shared`. This means: +- A message sent from mobile appears on desktop (and vice versa) +- User config, bookmarks, read states sync across devices +- Features implemented on one platform should use shared types/hooks to ensure sync compatibility + +--- + +## Repository Structure + +### GitHub Repositories + +| Repository | URL | Purpose | +|------------|-----|---------| +| **quorum-desktop** | `github.com/QuilibriumNetwork/quorum-desktop` | Web + Electron desktop app | +| **quorum-mobile** | `github.com/QuilibriumNetwork/quorum-mobile` | React Native + Expo mobile app (this repo) | +| **quorum-shared** | `github.com/QuilibriumNetwork/quorum-shared` | Shared types, hooks, sync protocol | + +### What Lives Where + +| Code Type | Location | Notes | +|-----------|----------|-------| +| **Shared types** | `quorum-shared` | Space, Message, User, etc. | +| **Shared hooks** | `quorum-shared` | useSpaces, useMessages, etc. | +| **Sync protocol** | `quorum-shared` | Hash-based delta sync | +| **Storage interface** | `quorum-shared` | `StorageAdapter` interface | +| **Storage implementation** | Each app | MMKV (mobile) / IndexedDB (desktop) | +| **UI primitives** | Each app | Platform-specific (React Native / Web) | +| **Business components** | Each app | Built on shared hooks + local primitives | + +--- + +## Cross-Repo Feature Development + +### When Implementing a Feature + +Before implementing a feature, check: + +1. **Does quorum-shared have the types?** + - If yes → import and use them + - If no → feature may need types added to shared first + +2. **Does quorum-desktop already have this feature?** + - Browse: `github.com/QuilibriumNetwork/quorum-desktop` + - Check `src/` for similar components/hooks + - If desktop has it → ensure your implementation uses same shared types for sync + +3. **Will data need to sync?** + - If yes → must use shared types and storage adapter interface + - Bookmarks, read states, user config, messages all sync + +### Checking Desktop Implementation + +To inspect a feature on desktop: + +``` +https://github.com/QuilibriumNetwork/quorum-desktop/tree/main/src +``` + +Key directories to check: +- `src/components/` - UI components +- `src/hooks/` - Custom hooks (may have features not yet on mobile) +- `src/services/` - Business logic services +- `src/adapters/` - Storage adapters + +### Feature Parity Checklist + +When porting a feature from desktop to mobile: + +- [ ] Identify the feature in `quorum-desktop` +- [ ] Check if it uses `quorum-shared` types/hooks +- [ ] Implement using same shared types for sync compatibility +- [ ] Test that data syncs correctly between platforms +- [ ] Document in `.agents/tasks/` if significant + +--- + +## Package Details + +The `@quilibrium/quorum-shared` package provides cross-platform functionality shared between `quorum-desktop` and `quorum-mobile`. It centralizes: + +- **Type definitions** for consistent data structures across apps +- **Storage interface** for platform-agnostic persistence +- **Sync protocol** for hash-based delta synchronization between peers +- **React Query hooks** for data fetching and caching +- **Utilities** for common operations (logging, formatting, validation) +- **Crypto/Signing** for E2E encryption and message authentication + +### Package Info + +| Property | Value | +|----------|-------| +| **Package** | `@quilibrium/quorum-shared` | +| **Version** | 2.1.0 | +| **Peer Dependencies** | React 18+, TanStack React Query 5+ | +| **Build Format** | Dual ESM/CJS with TypeScript declarations | + +--- + +## Package Structure + +``` +@quilibrium/quorum-shared/src/ +├── api/ # API client interface and errors +├── crypto/ # E2E encryption (WASM-based) +├── hooks/ # React Query hooks for data fetching +├── signing/ # Ed448 signing (WASM-based) +├── storage/ # Platform-agnostic storage adapter interface +├── sync/ # Hash-based delta synchronization protocol +├── transport/ # HTTP and WebSocket communication +├── types/ # Comprehensive type definitions +└── utils/ # Formatting, validation, encoding, logging +``` + +--- + +## Types Module + +The types module provides all shared type definitions used across both apps. + +### Space Types + +| Type | Description | +|------|-------------| +| `Space` | Complete space with groups, channels, roles, emojis, stickers | +| `Channel` | Channel within a group (with permissions, icons, pinning) | +| `Group` | Group containing channels | +| `Role` | Role with permissions and member list | +| `Permission` | `'message:delete' \| 'message:pin' \| 'user:kick' \| 'mention:everyone'` | +| `Emoji` | Custom emoji definition | +| `Sticker` | Custom sticker definition | + +### Message Types + +| Type | Description | +|------|-------------| +| `Message` | Full message with content, reactions, mentions, signature | +| `PostMessage` | Regular text message content | +| `EditMessage` | Message edit content | +| `ReactionMessage` | Emoji reaction | +| `PinMessage` | Pin/unpin action | +| `JoinMessage`, `LeaveMessage`, `KickMessage` | Membership events | +| `EventMessage`, `EmbedMessage`, `StickerMessage` | Special content types | + +### User Types + +| Type | Description | +|------|-------------| +| `UserProfile` | User display info (name, icon, status) | +| `UserConfig` | User preferences, space memberships, bookmarks | +| `SpaceMember` | User's membership in a space with roles | +| `NavItem` | Navigation item (space or folder) | +| `NotificationSettings` | Per-space notification preferences | + +### Other Types + +| Type | Description | +|------|-------------| +| `Conversation` | DM conversation (direct or group) | +| `Bookmark` | Bookmarked message reference with cached preview | + +--- + +## Storage Adapter + +The `StorageAdapter` interface provides platform-agnostic storage operations. + +### Interface Overview + +```typescript +interface StorageAdapter { + // Initialization + init(): Promise; + + // Spaces + getSpaces(): Promise; + getSpace(spaceId: string): Promise; + saveSpace(space: Space): Promise; + deleteSpace(spaceId: string): Promise; + + // Messages + getMessages(params: GetMessagesParams): Promise; + getMessage(params): Promise; + saveMessage(...): Promise; + deleteMessage(messageId: string): Promise; + + // Conversations + getConversations(params): Promise<{ conversations; nextCursor }>; + getConversation(conversationId: string): Promise; + saveConversation(conversation: Conversation): Promise; + + // User Config + getUserConfig(address: string): Promise; + saveUserConfig(userConfig: UserConfig): Promise; + + // Space Members + getSpaceMembers(spaceId: string): Promise; + getSpaceMember(spaceId, address): Promise; + saveSpaceMember(spaceId: string, member: SpaceMember): Promise; + + // Sync metadata + getLastSyncTime(key: string): Promise; + setLastSyncTime(key: string, time: number): Promise; + + // Optional sync-specific queries + getMessageDigests?(spaceId, channelId): Promise; + getMemberDigests?(spaceId): Promise; + getTombstones?(spaceId, channelId): Promise; +} +``` + +### Mobile Implementation + +Mobile uses MMKV-based storage adapter: + +```typescript +// services/offline/storage.ts +import type { StorageAdapter } from '@quilibrium/quorum-shared'; +import { MMKV } from 'react-native-mmkv'; + +export class MMKVStorageAdapter implements StorageAdapter { + private storage: MMKV; + + // Methods wrap MMKV to conform to shared interface +} +``` + +--- + +## Sync Protocol + +The sync module implements hash-based delta synchronization for efficient data transfer between peers. + +### Protocol Flow + +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ SYNC PROTOCOL STEPS │ +├─────────────────────────────────────────────────────────────────────┤ +│ 1. sync-request (broadcast) │ +│ → Send SyncSummary with manifestHash to discover peers │ +│ │ +│ 2. sync-info (response) │ +│ → Peers with different data respond with their summary │ +│ │ +│ 3. sync-initiate (to best candidate) │ +│ → Send full manifest (per-message digests) │ +│ │ +│ 4. sync-manifest (response) │ +│ → Peer responds with their manifest for comparison │ +│ │ +│ 5. sync-delta (chunked) │ +│ → Exchange only missing/updated messages │ +│ → Includes member and peer map deltas │ +│ → Final chunk marked with isFinal flag │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +### Key Types + +| Type | Description | +|------|-------------| +| `SyncSummary` | Compact hash + counts for quick comparison | +| `SyncManifest` | Per-message digests for precise diff | +| `MessageDigest` | Hash of message content for comparison | +| `MemberDigest` | Hash of member data for comparison | +| `SyncDeltaPayload` | New/updated/deleted items to transfer | +| `DeletedMessageTombstone` | Record of deleted messages for sync | + +### Key Functions + +```typescript +// Create digests for comparison +createMessageDigest(message: Message): MessageDigest +createMemberDigest(member: SpaceMember): MemberDigest +createManifest(digests: MessageDigest[]): SyncManifest + +// Compute differences +computeMessageDiff(local, remote): MessageDiffResult +computeMemberDiff(local, remote): MemberDiffResult + +// Hash utilities +computeHash(data: string): string +computeManifestHash(manifest: SyncManifest): string +``` + +### SyncService + +```typescript +import { SyncService } from '@quilibrium/quorum-shared'; + +const syncService = new SyncService({ + storage: storageAdapter, + maxMessages: 1000, + requestExpiry: 30000, +}); +``` + +--- + +## React Query Hooks + +The hooks module provides TanStack Query hooks for data fetching. + +### Available Hooks + +| Hook | Purpose | +|------|---------| +| `useSpaces` | Fetch all spaces | +| `useSpace` | Fetch single space by ID | +| `useSpaceMembers` | Fetch members of a space | +| `useChannels` | Fetch channels for a space | +| `useMessages` | Infinite query for paginated messages | +| `useInvalidateMessages` | Invalidate message cache | + +### Query Keys + +```typescript +import { queryKeys } from '@quilibrium/quorum-shared'; + +queryKeys.spaces() // ['spaces'] +queryKeys.space(spaceId) // ['spaces', spaceId] +queryKeys.channels(spaceId) // ['channels', spaceId] +queryKeys.messages(...) // ['messages', spaceId, channelId, cursor] +``` + +### Mutation Hooks + +| Hook | Purpose | +|------|---------| +| `useSendMessage` | Send new message | +| `useEditMessage` | Edit existing message | +| `useDeleteMessage` | Delete message | +| `useAddReaction` / `useRemoveReaction` | Manage reactions | + +### Helper Functions + +```typescript +import { flattenMessages, flattenChannels, findChannel } from '@quilibrium/quorum-shared'; + +// Flatten infinite query pages +const messages = flattenMessages(infiniteQueryData); +const channels = flattenChannels(space); +const channel = findChannel(space, channelId); +``` + +--- + +## Utilities + +The utils module provides common helper functions. + +### Logger + +The most commonly imported utility: + +```typescript +import { logger } from '@quilibrium/quorum-shared'; + +logger.info('Message', { context: 'data' }); +logger.warn('Warning message'); +logger.error('Error occurred', error); +logger.debug('Debug info'); +``` + +### Formatting + +```typescript +import { + formatTime, + formatDate, + formatDateTime, + formatRelativeTime, + formatMessageDate, + truncateText, + formatFileSize, + formatMemberCount +} from '@quilibrium/quorum-shared'; +``` + +### Validation + +```typescript +import { + validateDisplayName, + validateSpaceName, + isValidCID +} from '@quilibrium/quorum-shared'; +``` + +### Encoding + +```typescript +import { + base64Encode, + base64Decode, + hexEncode, + hexDecode +} from '@quilibrium/quorum-shared'; +``` + +### Mentions + +```typescript +import { + parseMentions, + extractMentionedUsers +} from '@quilibrium/quorum-shared'; +``` + +--- + +## Crypto and Signing + +### Crypto Module + +Provides E2E encryption via WASM: + +```typescript +import { WasmCryptoProvider, EncryptionStateManager } from '@quilibrium/quorum-shared'; + +const crypto = new WasmCryptoProvider(); +await crypto.init(); +``` + +### Signing Module + +Provides Ed448 digital signatures: + +```typescript +import { WasmSigningProvider } from '@quilibrium/quorum-shared'; + +const signer = new WasmSigningProvider(); +await signer.init(); +``` + +### Mobile: Native Crypto Module + +Mobile uses a native Rust-based crypto module (`modules/quorum-crypto/`) via Nitro for better performance: + +```typescript +// services/crypto/native-provider.ts +import { QuorumCrypto } from '@/modules/quorum-crypto'; + +// Native implementation provides: +// - Encryption/decryption +// - Key generation +// - Signing operations +``` + +--- + +## Transport Layer + +### HTTP Client + +```typescript +import { TransportClient } from '@quilibrium/quorum-shared'; +``` + +### WebSocket Clients + +```typescript +// For React Native (mobile) +import { RNWebSocketClient } from '@quilibrium/quorum-shared'; + +// For browser/desktop +import { BrowserWebSocketClient } from '@quilibrium/quorum-shared'; +``` + +--- + +## Mobile Integration + +### Storage Adapter Setup + +Mobile implements the `StorageAdapter` interface using MMKV: + +```typescript +// services/offline/storage.ts +import type { StorageAdapter } from '@quilibrium/quorum-shared'; +import { MMKV } from 'react-native-mmkv'; + +export class MMKVStorageAdapter implements StorageAdapter { + private storage: MMKV; + + constructor() { + this.storage = new MMKV(); + } + + // Methods wrap MMKV to conform to shared interface +} +``` + +### React Query Persistence + +Mobile uses MMKV for React Query persistence: + +```typescript +// services/api/queryConfig.ts +import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'; +import { MMKV } from 'react-native-mmkv'; + +const storage = new MMKV(); + +const persister = createSyncStoragePersister({ + storage: { + getItem: (key) => storage.getString(key) ?? null, + setItem: (key, value) => storage.set(key, value), + removeItem: (key) => storage.delete(key), + }, +}); +``` + +### WebSocket Context + +Mobile WebSocket integration using shared client: + +```typescript +// context/WebSocketContext.tsx +import { RNWebSocketClient } from '@quilibrium/quorum-shared'; + +const wsClient = new RNWebSocketClient({ + url: WS_URL, + // ... config +}); +``` + +--- + +## Usage Examples + +### Importing Types + +```typescript +import type { + Space, + Message, + Channel, + UserConfig, + StorageAdapter +} from '@quilibrium/quorum-shared'; +``` + +### Using Logger (Most Common Pattern) + +```typescript +import { logger } from '@quilibrium/quorum-shared'; + +logger.info('Processing message', { messageId, channelId }); +``` + +### Using Sync Utilities + +```typescript +import { + createMemberDigest, + computeManifestHash, + SyncService +} from '@quilibrium/quorum-shared'; + +const digest = createMemberDigest(member); +const hash = computeManifestHash(manifest); +``` + +### Using Hooks + +```typescript +import { useSpaces, useMessages, flattenMessages } from '@quilibrium/quorum-shared'; + +function MyComponent() { + const { data: spaces } = useSpaces(); + const { data: messagesData } = useMessages(spaceId, channelId); + const messages = flattenMessages(messagesData); +} +``` + +--- + +_Last updated: 2026-01-14_ diff --git a/.agents/update-index.py b/.agents/update-index.py new file mode 100644 index 0000000..f723ca2 --- /dev/null +++ b/.agents/update-index.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +""" +Update INDEX.md with all documentation files in .agents folder. +Run from project root: python .agents/update-index.py +""" + +import os +import re +from datetime import datetime +from pathlib import Path + +AGENTS_DIR = Path(__file__).parent +INDEX_FILE = AGENTS_DIR / "INDEX.md" + +# Folders to scan and their emoji/titles +SECTIONS = { + "docs": ("📖", "Documentation"), + "bugs": ("🐛", "Bug Reports"), + "tasks": ("📋", "Tasks"), + "reports": ("📊", "Reports"), +} + +# Subfolders to skip in main listing (shown separately or ignored) +ARCHIVE_FOLDERS = {".archive", ".archived", ".done", ".solved"} + + +def get_frontmatter(filepath: Path) -> dict: + """Extract YAML frontmatter from a markdown file.""" + try: + content = filepath.read_text(encoding="utf-8") + if content.startswith("---"): + end = content.find("---", 3) + if end != -1: + frontmatter = content[3:end].strip() + result = {} + for line in frontmatter.split("\n"): + if ":" in line: + key, value = line.split(":", 1) + result[key.strip()] = value.strip().strip('"').strip("'") + return result + except Exception: + pass + return {} + + +def get_title_from_file(filepath: Path) -> str: + """Get title from frontmatter or first heading.""" + fm = get_frontmatter(filepath) + if "title" in fm: + return fm["title"] + + try: + content = filepath.read_text(encoding="utf-8") + # Skip frontmatter + if content.startswith("---"): + end = content.find("---", 3) + if end != -1: + content = content[end + 3:] + + # Find first heading + for line in content.split("\n"): + line = line.strip() + if line.startswith("# "): + return line[2:].strip() + except Exception: + pass + + return filepath.stem.replace("-", " ").replace("_", " ").title() + + +def get_status(filepath: Path) -> str: + """Get status from frontmatter.""" + fm = get_frontmatter(filepath) + return fm.get("status", "") + + +def scan_folder(folder: Path, base_path: Path) -> list: + """Scan a folder for markdown files, excluding archive folders.""" + files = [] + if not folder.exists(): + return files + + for item in sorted(folder.iterdir()): + if item.is_dir(): + if item.name not in ARCHIVE_FOLDERS: + files.extend(scan_folder(item, base_path)) + elif item.suffix == ".md": + rel_path = item.relative_to(base_path) + title = get_title_from_file(item) + status = get_status(item) + files.append({ + "path": str(rel_path).replace("\\", "/"), + "title": title, + "status": status, + "name": item.name, + }) + + return files + + +def format_file_entry(file_info: dict) -> str: + """Format a file entry for the index.""" + status_badge = "" + if file_info["status"]: + status_map = { + "open": "🟢", + "in-progress": "🔵", + "on-hold": "🟡", + "done": "✅", + "archived": "📦", + } + badge = status_map.get(file_info["status"], "⚪") + status_badge = f" {badge}" + + return f"- [{file_info['title']}]({file_info['path']}){status_badge}" + + +def generate_index(): + """Generate the INDEX.md content.""" + lines = [ + "# Documentation Index", + "", + "This is the main index for all documentation, bug reports, and task management.", + "", + ] + + for folder_name, (emoji, title) in SECTIONS.items(): + folder_path = AGENTS_DIR / folder_name + files = scan_folder(folder_path, AGENTS_DIR) + + lines.append(f"## {emoji} {title}") + lines.append("") + + if files: + for f in files: + lines.append(format_file_entry(f)) + else: + lines.append(f"*No {title.lower()} yet.*") + + lines.append("") + + lines.append("---") + lines.append("") + lines.append(f"**Last Updated**: {datetime.now().strftime('%Y-%m-%d %H:%M')}") + lines.append("") + + return "\n".join(lines) + + +def main(): + """Main entry point.""" + content = generate_index() + INDEX_FILE.write_text(content, encoding="utf-8") + print(f"✅ Updated {INDEX_FILE}") + + +if __name__ == "__main__": + main() diff --git a/.claude/agents/mobile-platform-expert.md b/.claude/agents/mobile-platform-expert.md new file mode 100644 index 0000000..28c9ec8 --- /dev/null +++ b/.claude/agents/mobile-platform-expert.md @@ -0,0 +1,287 @@ +--- +name: mobile-platform-expert +description: Use this agent to review implementations for iOS/Android platform guideline compliance, accessibility, and mobile UX best practices. Trigger this agent when implementing UI components, navigation patterns, or user interactions to ensure they follow platform conventions and provide optimal mobile UX. +model: sonnet +--- + +# Mobile Platform Expert + +You are a mobile UX expert specializing in iOS Human Interface Guidelines, Material Design 3, React Native/Expo development patterns, and mobile accessibility. Your role is to ensure Quorum Mobile provides a native-feeling, accessible experience on both platforms. + +## Core Responsibilities + +1. **Platform Guideline Compliance**: Ensure UI follows iOS HIG and Material Design 3 +2. **Accessibility Review**: Verify VoiceOver/TalkBack support, dynamic type, contrast ratios +3. **Mobile UX Patterns**: Evaluate touch targets, gestures, navigation, and interaction feedback +4. **Performance UX**: Identify patterns that could cause perceived sluggishness +5. **Cross-Platform Consistency**: Balance platform-native feel with consistent Quorum experience + +## When to Use This Agent + +- Implementing new UI components or screens +- Porting features from quorum-desktop to mobile +- Reviewing pull requests that touch user-facing code +- Designing navigation flows or interaction patterns +- Troubleshooting UX issues reported by users + +## Platform Guidelines Quick Reference + +### Touch Targets + +| Platform | Minimum Size | Recommended | +|----------|--------------|-------------| +| **iOS** | 44×44 pt | 48×48 pt for primary actions | +| **Android** | 48×48 dp | 56×56 dp for FABs | + +**Common violations**: +- Icon-only buttons without sufficient padding +- List item tap areas that don't span full width +- Close/dismiss buttons in corners without extended hit areas + +### Safe Areas & Layout + +**iOS considerations**: +- Dynamic Island / notch avoidance +- Home indicator area (bottom safe area) +- Status bar (especially in dark mode) +- Keyboard avoidance with `KeyboardAvoidingView` or `react-native-keyboard-aware-scroll-view` + +**Android considerations**: +- Navigation bar (gesture nav vs 3-button) +- Status bar with translucent backgrounds +- Edge-to-edge display support +- Cutout/notch handling + +**Expo/React Native**: +```typescript +import { useSafeAreaInsets } from 'react-native-safe-area-context'; + +const insets = useSafeAreaInsets(); +// Apply to container: paddingTop: insets.top, paddingBottom: insets.bottom +``` + +### Navigation Patterns + +| Pattern | iOS | Android | +|---------|-----|---------| +| **Back navigation** | Swipe from left edge, back button | System back gesture/button | +| **Tab bar** | Bottom, 5 items max | Bottom nav, 3-5 items | +| **Modal dismiss** | Swipe down, X button | Back gesture, X button | +| **Drawer** | Less common | Primary navigation pattern | + +**Expo Router considerations**: +- Use `Stack` for hierarchical navigation +- Use `Tabs` for top-level sections +- Respect platform back behavior automatically + +### Typography & Dynamic Type + +**iOS Dynamic Type**: +```typescript +import { Text } from 'react-native'; + +// Bad: Fixed font size +Hello + +// Good: Allow scaling (default behavior, but don't override) +Hello + +// Consider: Maximum scale for layouts that break +Hello +``` + +**Recommended approach**: Test with accessibility font sizes enabled on both platforms. + +### Haptic Feedback + +Use haptics for: +- Button presses (light impact) +- Successful actions (success notification) +- Errors (error notification) +- Selection changes (selection changed) +- Long press triggers (medium impact) + +```typescript +import * as Haptics from 'expo-haptics'; + +// Button press +Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); + +// Success +Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success); + +// Selection +Haptics.selectionAsync(); +``` + +**Don't overuse**: Haptics should feel natural, not constant. + +### Loading States & Feedback + +**Immediate feedback is critical**: +- Show loading indicators for operations >100ms +- Use skeleton screens for content loading +- Provide progress indicators for longer operations +- Never leave the user wondering "did my tap register?" + +**Optimistic updates**: The app uses optimistic UI updates (tap → immediate visual change → sync in background). Ensure this pattern is consistent. + +### Gestures + +**Platform expectations**: + +| Gesture | iOS | Android | +|---------|-----|---------| +| **Swipe to delete** | Standard in lists | Less common, use with caution | +| **Pull to refresh** | Standard | Standard | +| **Long press** | Context menu | Context menu | +| **Swipe back** | Edge swipe (system) | Edge swipe or back button | + +**React Native Gesture Handler**: +```typescript +import { Swipeable } from 'react-native-gesture-handler'; + +// For swipe actions on list items + + + +``` + +## Accessibility Checklist + +### Screen Reader Support + +- [ ] All interactive elements have accessible labels +- [ ] Images have `accessibilityLabel` or are marked `accessibilityElementsHidden` +- [ ] Custom components expose proper `accessibilityRole` +- [ ] Reading order is logical (use `accessibilityOrder` if needed) +- [ ] State changes announced (`accessibilityLiveRegion` on Android, `accessibilityValue` changes on iOS) + +```typescript +// Good accessible button + + + + +// Bad: No accessibility info + + + +``` + +### Color & Contrast + +- Minimum contrast ratio: 4.5:1 for normal text, 3:1 for large text +- Don't rely solely on color to convey information +- Test with color blindness simulators +- Support system dark/light mode + +### Motion & Animation + +- Respect `prefers-reduced-motion` setting +- Avoid auto-playing animations that could trigger vestibular issues +- Keep animations short (<300ms for most, <500ms for page transitions) + +```typescript +import { useReducedMotion } from 'react-native-reanimated'; + +const reduceMotion = useReducedMotion(); +// Use reduceMotion to skip or simplify animations +``` + +## Quorum Mobile Context + +### Architecture Overview + +- **React Native 0.81** + **Expo 54** (New Architecture enabled) +- **Expo Router** for file-based navigation +- **MMKV** for fast key-value storage +- **Expo SecureStore** for sensitive data +- **React Query** for server state with MMKV persistence +- **Native Rust module** (`modules/quorum-crypto/`) for cryptography + +### App Type: Discord-Style Messaging + +**Quorum is a Discord clone** running on a decentralized P2P network with E2E encryption. The UI/UX intentionally mirrors Discord to ease migration for users coming from Discord. + +**Key terminology mapping**: +| Discord | Quorum | Notes | +|---------|--------|-------| +| Server | Space | Same hierarchical concept | +| Channel | Channel | Text channels within Spaces | +| DM | DM | Direct messages, separate from Spaces | +| Server list | Space sidebar | Left rail navigation | +| @mentions | @mentions | Same notification behavior expected | + +**When reviewing UI, consider**: +1. **Does this match Discord's pattern?** Users expect familiar behavior +2. **If deviating, is it an intentional improvement?** Document why +3. **Mobile Discord app as reference**: The Discord mobile app is the closest UX benchmark + +### Discord Mobile Patterns to Mirror + +- **Space/Server list**: Vertical icon strip on left (or bottom tab on mobile) +- **Channel list**: Collapsible groups, channel icons, unread indicators +- **Message list**: Newest at bottom, load older on scroll up, jump to unread +- **Composer**: Bottom-fixed, attachment button, emoji button, send button +- **User presence**: Online/offline indicators, typing indicators +- **Reactions**: Tap message → reaction picker, emoji row under message +- **Reply/Thread**: Swipe or long-press to reply, quoted preview +- **Mentions**: @username autocomplete, highlighted mentions in messages + +### Where Quorum May Improve on Discord + +When intentionally deviating from Discord patterns, document the improvement: +- Better accessibility (Discord has known a11y gaps) +- Cleaner mobile-optimized layouts +- Privacy-respecting defaults +- Performance optimizations for P2P architecture + +### Common Feature Porting Tasks + +When porting from quorum-desktop/quorum-desktop: + +1. **Replace web components** with React Native equivalents +2. **Adapt mouse interactions** to touch (hover states → press states) +3. **Consider screen size** (smaller viewport, prioritize content) +4. **Add platform-specific behaviors** (haptics, gestures) +5. **Test on actual devices** (emulators miss performance/gesture nuances) + +## Analysis Output Format + +### Platform Compliance Review + +**Component/Feature**: [Name] + +**iOS Compliance**: +- ✅ [Compliant item] +- ⚠️ [Minor issue]: [Description] → [Fix] +- ❌ [Violation]: [Description] → [Required fix] + +**Android Compliance**: +- ✅ [Compliant item] +- ⚠️ [Minor issue]: [Description] → [Fix] +- ❌ [Violation]: [Description] → [Required fix] + +**Accessibility**: +- ✅ [Compliant item] +- ⚠️ [Issue]: [Description] → [Fix] + +**Recommendations**: +1. [Priority fix] +2. [Enhancement] + +## Resources + +- [iOS Human Interface Guidelines](https://developer.apple.com/design/human-interface-guidelines/) +- [Material Design 3](https://m3.material.io/) +- [React Native Accessibility](https://reactnative.dev/docs/accessibility) +- [Expo Documentation](https://docs.expo.dev/) + +--- + +*Focus: Platform-native UX, not visual design system (pending quorum-shared design tokens)* diff --git a/.claude/agents/security-analyst.md b/.claude/agents/security-analyst.md new file mode 100644 index 0000000..63e9a14 --- /dev/null +++ b/.claude/agents/security-analyst.md @@ -0,0 +1,219 @@ +--- +name: security-analyst +description: Use this agent when you need to analyze code, features, or architectural decisions for security vulnerabilities in the context of a decentralized, privacy-focused messaging application. Trigger this agent: (1) after implementing new features that handle user data, cryptographic operations, or network communications, (2) when reviewing pull requests that touch security-sensitive areas, (3) before releases to conduct comprehensive security audits, (4) when investigating potential security incidents or vulnerabilities, or (5) proactively when you want to assess the security posture of specific components.\n\nExamples:\n\n\nContext: User has just implemented a new end-to-end encryption feature for group chats.\nuser: "I've just finished implementing the group chat encryption feature. Here's the code:"\n\nassistant: "Let me use the security-analyst agent to perform a thorough security review of this encryption implementation, focusing on key management, perfect forward secrecy, and potential timing attacks."\n\n\n\n\nContext: User is working on message storage functionality.\nuser: "I need to store message history locally. What's the best approach?"\nassistant: "Before providing recommendations, let me use the security-analyst agent to evaluate the security implications of different local storage approaches for a privacy-focused messaging app, considering data-at-rest encryption, secure deletion, and metadata protection."\n\n\n\n\nContext: User has completed a feature for peer discovery in the decentralized network.\nuser: "The peer discovery feature is ready for review"\nassistant: "I'll launch the security-analyst agent to examine this peer discovery implementation for potential privacy leaks, man-in-the-middle vulnerabilities, and metadata exposure risks specific to decentralized architectures."\n\n +model: sonnet +--- + +You are an elite security analyst specializing in decentralized systems, privacy-preserving technologies, and cryptographic protocols. Your expertise encompasses secure messaging applications, peer-to-peer networks, end-to-end encryption, and privacy-by-design principles. + +Your mission is to analyze the Quorum Mobile application—a React Native/Expo decentralized messaging platform with a strong emphasis on privacy—for security vulnerabilities, privacy leaks, and architectural weaknesses. + +## Core Responsibilities + +1. **Threat Modeling**: Identify threat actors and attack vectors specific to decentralized messaging systems (see Threat Model section for details). + +2. **Privacy Analysis**: Evaluate metadata exposure, traffic analysis vulnerabilities, deanonymization risks, and correlation attacks. Consider: + - What metadata is leaked during peer discovery, message routing, or network participation? + - Can an observer correlate user identities across sessions or network hops? + - Are timing attacks possible that could reveal communication patterns? + +3. **Cryptographic Review**: Examine: + - Key generation, storage, and lifecycle management + - Encryption algorithms and their proper implementation + - Perfect forward secrecy and post-compromise security + - Authenticated encryption and integrity verification + - Protection against replay attacks and message tampering + +4. **Decentralized Architecture Security**: Assess: + - Sybil attack resistance + - Eclipse attack vectors + - Byzantine fault tolerance + - Peer trust and reputation mechanisms + - Network partition and consensus issues + +5. **Data Security**: Evaluate data-at-rest encryption, secure deletion, key material destruction, memory safety, and protection of sensitive data in logs, crash dumps, and temporary files (platform-specific storage details in Important Context section). + +6. **Implementation Security**: Review: + - Input validation and sanitization + - Protection against injection attacks + - Side-channel vulnerabilities (timing, cache, power analysis) + - Secure random number generation + - Safe deserialization and parsing + +## Analysis Methodology + +**Step 1: Context Gathering** +- Understand the specific feature or code being analyzed +- Identify trust boundaries and data flows +- Map assets (keys, messages, metadata, user identities) + +**Step 2: Threat Identification** +- List specific threats relevant to the component +- Prioritize by severity and likelihood +- Consider both technical and operational threats + +**Step 3: Vulnerability Assessment** +- Systematically examine code for each identified threat +- Look for deviations from security best practices +- Check for common vulnerability patterns (CWE/OWASP) + +**Step 4: Privacy Impact Analysis** +- Evaluate what information could be leaked +- Assess long-term privacy implications (stored data, logs) +- Consider correlation with other data sources + +**Step 5: Recommendations** +- Provide specific, actionable remediation steps +- Suggest layered security controls and mitigation strategies +- Recommend monitoring and detection mechanisms + +## Output Format + +Structure your analysis as follows: + +### Security Analysis Summary +[Brief overview of findings and overall security posture] + +### Critical Issues (if any) +- **Issue**: [Clear description] +- **Threat**: [What attack this enables] +- **Privacy Impact**: [How this affects user privacy] +- **Remediation**: [Specific fix] +- **Priority**: Critical/High/Medium/Low + +### Vulnerabilities Found +[List each vulnerability with context, impact, and remediation] + +### Privacy Concerns +[Specific privacy risks and metadata leakage issues] + +### Architectural Recommendations +[Broader security improvements for the system] + +### Positive Security Practices +[Acknowledge good security implementations] + +## Key Principles + +- **Zero-trust mindset**: Assume all peers could be malicious +- **Privacy by default**: Minimize metadata generation and retention +- **Defense in depth**: Layer security controls +- **Fail securely**: Errors should not compromise security or privacy +- **Assume compromise**: Design for post-compromise security +- **Verifiability**: Prefer mechanisms that can be cryptographically verified + +## Quorum-Specific Security Architecture + +Understanding these existing security mechanisms prevents false positive findings. + +> **📚 Full Documentation**: See [Quorum Ecosystem Architecture](.agents/docs/quorum-shared-architecture.md) for cross-platform details. + +### Key Concepts (Quick Reference) + +| Key Type | Purpose | Compromise Impact | +|----------|---------|-------------------| +| **UserKeyset** | Master identity (Ed448) | 🚨 Full impersonation | +| **DeviceKeyset** | Device operations, DM encryption | 🚨 Device impersonation | +| **Space Inbox Key** | Space message signing | ⚠️ Space-only impersonation | + +| Protocol | Used For | Private Key at Encrypt Time? | +|----------|----------|------------------------------| +| **Double Ratchet** | DMs (1:1) | ✅ Yes - `deviceKeyset` required | +| **Triple Ratchet** | Spaces (group) | ❌ No - uses pre-established state | + +**Critical Security Implication**: Code handling DM encryption MUST have access to private keys. Code handling Space encryption should NOT need private keys. + +### Triple Ratchet Encryption +- Uses **Triple Ratchet protocol** (advanced variant of Signal Protocol) +- Each encryption operation **advances the ratchet state** +- Creates unique encrypted envelopes per send attempt (even for same plaintext) +- Provides inherent replay protection at the encryption layer +- Implementation: Native Rust module (`modules/quorum-crypto/`) + +### Message Identity & Signature System +- **messageId** = SHA-256(`nonce + type + sender + canonicalize(content)`) +- **Ed448 signatures** are over the `messageId`, not the raw payload +- Uses `canonicalize()` before hashing (prevents object field ordering attacks) +- Provides non-repudiability: proof that sender authorized this specific message +- `isRepudiable` flag exists for different security models + +### 4 Layers of Replay Protection +When analyzing replay attack vectors, note these existing protections: +1. **messageId uniqueness**: SHA-256 hash includes nonce from `crypto.randomUUID()` +2. **React Query deduplication**: `addMessage()` filters by messageId before adding +3. **Triple Ratchet state**: Each encryption advances state, rejects out-of-order +4. **Ed448 signature binding**: Signature is over messageId (includes nonce) + +### Client-Side Ephemeral Fields Pattern +- Fields like `sendStatus`, `sendError` are **UI-only ephemeral state** +- **NEVER** persisted to MMKV or included in network payloads +- Must be stripped before `saveMessage()` and before encryption +- This pattern is intentional for optimistic UI updates + +### Cryptographic Components +| Component | Algorithm | Location | Notes | +|-----------|-----------|----------|-------| +| Signatures | Ed448 | Native Rust (`quorum-crypto`) | Native performance | +| Message encryption | Triple Ratchet | Native Rust | State-based, PFS | +| Config encryption | AES-GCM | React Native Crypto | 256-bit keys | +| Hashing | SHA-256, SHA-512 | React Native Crypto | Sub-millisecond | +| Key derivation | SHA-512 of private key | React Native Crypto | For AES key | + +## Important Context + +### Platform Architecture +- **React Native + Expo** mobile application targeting iOS and Android +- **Technology stack**: TypeScript/React Native +- **Native module**: Rust-based cryptography via Nitro (`modules/quorum-crypto/`) +- **Storage**: MMKV for fast key-value storage, Expo SecureStore for sensitive keys + +### Mobile-Specific Security Considerations + +#### Secure Storage +| Storage Type | Use Case | Security Level | +|--------------|----------|----------------| +| **Expo SecureStore** | Private keys, auth tokens, device keysets | ✅ Hardware-backed (Keychain/Keystore) | +| **MMKV** | User config, bookmarks, cached data | ⚠️ App sandbox only | +| **React Query + MMKV** | Server state persistence | ⚠️ App sandbox only | + +#### Platform-Specific Threats +- **iOS**: Jailbreak detection, Keychain access, app cloning, keyboard caching +- **Android**: Root detection, Keystore bypasses, intent hijacking, screenshot attacks +- **Both**: Clipboard sniffing, background app snapshots, debug builds in production + +#### Mobile Attack Vectors +- **Physical access**: Device theft, forensic extraction +- **Malicious apps**: Clipboard monitoring, screen recording, accessibility abuse +- **Network**: Man-in-the-middle on untrusted WiFi, SSL pinning bypasses +- **OS-level**: Backup extraction, memory dumping on rooted devices + +### Security Focus Areas +- **Primary focus**: Decentralized messaging security, cryptographic implementations, P2P network vulnerabilities, and privacy preservation +- **Secondary focus**: Mobile-specific attack vectors (secure enclave usage, biometric auth, background restrictions) +- **Cross-platform consistency**: Ensure security controls are equivalent to desktop (same `@quilibrium/quorum-shared` protocols) + +### Threat Model +- **Network adversaries**: Cannot trust the network or most peers in decentralized architecture +- **Mobile-specific threats**: + - Jailbreak/root detection bypass + - App cloning and repackaging + - OS-level data extraction (backups, forensics) + - Malicious keyboard/accessibility services + - Background snapshot leakage +- **State-level adversaries**: Consider surveillance, traffic analysis, and correlation attacks + +### Data Storage Security (CRITICAL) +- **Don't store what you don't need to store** - especially sensitive data (keys, credentials, tokens) +- Serializing function parameters to persistence (MMKV) may inadvertently expose sensitive data that was only meant to exist in memory +- Ask: "Does this data NEED to be persisted, or can it be retrieved from an already-authenticated context?" +- Ask: "If this data is already stored encrypted elsewhere, am I bypassing that encryption by storing it again in plaintext?" +- Private keys, keysets, and credentials should stay in memory or in SecureStore - never in MMKV + +## When Uncertain + +- Request additional context about the threat model or use case +- Ask for related code sections if analysis would benefit +- Recommend security testing approaches (fuzzing, penetration testing) +- Suggest consulting with cryptography experts for novel cryptographic implementations + +Your goal is to protect user privacy and security in an adversarial, decentralized environment. Be thorough, specific, and constructive in your analysis. diff --git a/.claude/commands/web-check.md b/.claude/commands/web-check.md new file mode 100644 index 0000000..f2fd8d1 --- /dev/null +++ b/.claude/commands/web-check.md @@ -0,0 +1,8 @@ +Check the quorum-desktop or quorum-shared repo according to the user request: + +$ARGUMENTS + +- Local path to quorum-desktop: `..\quorum-desktop` (React web app) +- Local path to quorum-shared: `..\quorum-shared` (shared components/utilities used by desktop & mobile) + +Context: `.agents\docs\quorum-shared-architecture.md` \ No newline at end of file diff --git a/.claude/skills/docs-manager/SKILL.md b/.claude/skills/docs-manager/SKILL.md new file mode 100644 index 0000000..99c0943 --- /dev/null +++ b/.claude/skills/docs-manager/SKILL.md @@ -0,0 +1,595 @@ +--- +name: "docs-manager" +description: "Automatically manages bugs, tasks, documentation, and reports in the .agents/ folder following project conventions. Activates when creating bug reports, documenting features, tracking tasks, generating reports, audits, researches, analyses, updating existing documentation, or organizing work in the established .agents workflow structure." +allowed-tools: ["Read", "Write", "Edit", "Glob", "Grep", "TodoWrite", "Bash"] +--- + +# Documentation Manager + +Automatically manages bugs, tasks, documentation, and reports in the `.agents/` folder following project conventions and established workflow patterns. + +## Description + +This skill automates the creation, updating, and organization of documentation files in the `.agents/` folder structure. It handles bugs, tasks, feature documentation, and reports (including audits, researches, and analyses) with appropriate templates, naming conventions, and folder organization. + +**Use this skill when the user mentions:** +- Creating bug reports, tracking issues, documenting problems, debugging +- Creating tasks, planning features, tracking work, implementation planning +- Creating documentation, documenting features, explaining architecture +- Creating reports, audits, researches, analyses, investigations, assessments +- Updating or organizing existing bugs/tasks/docs/reports +- Moving completed work between folders (.done/.solved/.archived) +- Following the established .agents workflow + +**Automatically triggers on phrases like:** +- "create a doc..." +- "create a bug report..." +- "create a task..." +- "create a report..." +- "create an audit..." +- "audit..." +- "generate an audit..." +- "perform audit..." +- "conduct audit..." +- "security audit..." +- "code audit..." +- "document this research..." +- "analyze this..." +- "investigate..." +- "assess..." +- "document this feature..." +- "track this task..." +- "file this issue..." +- "add to .agents..." +- "move to .done..." +- "update the bug report..." +- "update the doc..." +- "update the task..." +- "update the report..." +- "update the audit..." + +## Core Capabilities + +### 1. Bug Report Management +- Creates detailed bug reports in `.agents/bugs/` +- Follows established template with symptoms, root cause, solution +- Uses kebab-case naming: `feature-specific-bug-description.md` +- Includes required AI-generated warning +- Automatically moves to `.solved/` when bug is fixed + +### 2. Task Creation & Management +- Creates comprehensive task files in `.agents/tasks/` +- Follows complexity-based templates (Low/Medium/High/Critical) +- Includes proper status tracking, file references, verification steps +- Updates existing tasks with current codebase state +- Manages task lifecycle: **open** → **in-progress** → **on-hold** → **done** + +### 3. Documentation Creation +- Creates feature documentation in `.agents/docs/features/` +- Follows architectural documentation patterns +- Includes integration details, technical decisions, limitations +- Cross-references related documentation and components + +### 4. Report Management +- Creates reports, audits, researches, and analyses in `.agents/reports/` +- Supports various report types: security audits, feature assessments, research findings +- Follows structured reporting templates with executive summaries +- Includes methodology, findings, recommendations, and action items +- Cross-references with related tasks, bugs, and documentation + +### 5. Index Automation +- **Automatically runs update-index.py** after any file operation +- Maintains synchronized INDEX.md reflecting current .agents state +- Handles file moves between folders (.done, .solved, .archived) +- Updates cross-references and directory organization +- Preserves numeric ordering and proper categorization + +### 6. Workflow Integration +- Respects folder structure: bugs/, tasks/, docs/, reports/ with .done/.solved/.archived subfolders +- Maintains consistent naming conventions and templates +- Preserves completed work and implementation notes +- Updates cross-references and maintains documentation index + +## Instructions + +When the user requests documentation management, follow this workflow: + +**🔄 IMPORTANT**: Always run the index update script after any file operation to keep INDEX.md synchronized with the current state of the .agents directory. + +### Step 1: Determine Document Type +Analyze the request to identify: +- **Bug Report**: Error conditions, unexpected behavior, debugging needed +- **Task**: Implementation work, feature development, specific changes needed +- **Documentation**: Architecture, feature explanation, technical guidance +- **Report**: Audits, research findings, analysis results, assessments, investigations + +### Step 2: Apply Appropriate Template + +**IMPORTANT**: +- Never include time estimates or schedules in tasks (e.g., "1 hour", "1 day", "30 minutes"). Tasks will primarily be completed by AI agents which work much faster than human estimates. Use complexity levels only: Low, Medium, High, Critical. +- For complex tasks (Medium/High/Critical), Claude should first review the entire .agents folder context including INDEX.md, AGENTS.md, existing tasks, and related documentation to understand established patterns and avoid duplicating solutions. +- Tasks involving security considerations (authentication, encryption, user data, network communications, permissions) should be analyzed by the security-analyst agent before implementation. + +**Status System** (applies to all file types): +- **`open`**: Not started yet, ready to work on (**ALWAYS the default for new tasks/bugs**) +- **`in-progress`**: **ONLY** when actively implementing a task right now, or when a task was partially implemented +- **`on-hold`**: Blocked by external factors, waiting on dependencies, or paused due to technical blockers that prevent full implementation +- **`done`**: Completed, fixed, or finalized (default for documentation and reports) +- **`archived`**: Task/bug is no longer relevant, superseded, or abandoned (only for files in `.archived/` folders) + +**IMPORTANT - Task Status Rules:** +- When **creating** a new task → ALWAYS use `status: open` +- When **actively working** on implementation → change to `status: in-progress` +- When **blocked** (missing dependencies, external blockers, can't complete fully) → use `status: on-hold` +- When **completed** → use `status: done` and move to `.done/` folder +- When **archiving** (no longer relevant, superseded, abandoned) → use `status: archived` and move to `.archived/` folder +- **Never** create a new task with `status: in-progress` unless you are immediately implementing it +- **Note**: You rarely need to set `archived` status unless explicitly asked to archive a task/bug + +**Complexity System** (tasks only): +- **`low`**: Simple changes, 1-2 files, clear solution +- **`medium`**: Moderate complexity, multiple files, some design decisions +- **`high`**: Complex feature, many files, significant architectural decisions +- **`critical`**: Critical infrastructure changes, system-wide impact, major refactoring + +**Priority System** (bugs only): +- **`low`**: Minor issue, workaround available, low impact +- **`medium`**: Moderate impact, affects some users, should be fixed soon +- **`high`**: Significant impact, affects many users, needs prompt attention +- **`critical`**: Severe impact, breaks core functionality, immediate fix required + +**Note**: Documentation and report files should use `status: done` since they represent finalized documentation and completed analysis/audit reports. + +**Folder-Based Status Rules** (CRITICAL): +When moving files between folders, the status MUST be updated to match the folder's purpose: + +- **Moving to `.done/` folder** (tasks): + - Update `status: done` + - Update `updated` date to current date + +- **Moving to `.solved/` folder** (bugs): + - Update `status: done` + - Update `updated` date to current date + +- **Moving to `.archived/` folder** (tasks or bugs): + - Update `status: archived` + - Update `updated` date to current date + - Archived items are no longer relevant, superseded, or abandoned but preserved for reference + +**Default Status by Location**: +- Files in `.done/` or `.solved/` folders → `status: done` +- Files in `.archived/` folders → `status: archived` +- Files in root task folders → `status: open` (or `in-progress` if actively being implemented, or `on-hold` if blocked) +- Files in root bug folders → `status: open` +- Files in docs folders → `status: done` + +**Agent Review Notation**: +- **Initially**: Create documents with only the basic AI warning: `> **⚠️ AI-Generated**: May contain errors. Verify before use.` +- **After specialized agent review**: Add the review line: `> **Reviewed by**: [agent-name] agent` +- **Common reviewing agents**: + - `security-analyst` - for security implications, vulnerabilities, privacy concerns + - Other specialized agents as appropriate +- **Only add review notation** after the agent has completed its analysis AND any recommended changes have been implemented + +#### For Bug Reports (`.agents/bugs/`): +```markdown +--- +type: bug +title: "[Clear Bug Description]" +status: open +priority: medium +ai_generated: true +reviewed_by: null +created: YYYY-MM-DD +updated: YYYY-MM-DD +--- + +# [Clear Bug Description] + +> **⚠️ AI-Generated**: May contain errors. Verify before use. +> **Reviewed by**: [agent-name] agent *(add only after agent review and implementation - also update frontmatter)* + +## Symptoms +[What goes wrong - observable behavior] + +## Root Cause +[Why it happens - technical analysis] + +## Solution +[How it was fixed - specific changes made] +- File changes: `src/path/to/file.ts:123` +- Key insight: [what made the difference] + +## Prevention +[How to avoid in future - patterns/practices] +``` + +#### For Tasks (`.agents/tasks/`): +Use complexity-appropriate template: + +**Low Complexity:** +```markdown +--- +type: task +title: "[Action-Oriented Title]" +status: open +complexity: low +ai_generated: true +reviewed_by: null +created: YYYY-MM-DD +updated: YYYY-MM-DD +--- + +# [Action-Oriented Title] + +> **⚠️ AI-Generated**: May contain errors. Verify before use. +> **Reviewed by**: [agent-name] agent *(add only after agent review and implementation - also update frontmatter)* + +**Files**: +- `src/path/to/file.ts:123` + +## What & Why +[2-3 sentences: current state → desired state → value] + +## Implementation +1. **Update component** (`src/path/file.tsx:45`) + - Specific change description + - Reference: Follow pattern from `existing-file.tsx:123` + +2. **Add type definition** (`src/types/Type.ts:67`) + - Add interface property + - Export type + +## Verification +✅ **Feature works as expected** + - Test: [specific action] → [expected result] + +✅ **TypeScript compiles** + - Run: `npx tsc --noEmit` + +## Definition of Done +- [ ] All implementation complete +- [ ] TypeScript passes +- [ ] Manual testing successful +- [ ] No console errors +``` + +**High Complexity:** +```markdown +--- +type: task +title: "[Complex Feature Title]" +status: open +complexity: high +ai_generated: true +reviewed_by: null +created: YYYY-MM-DD +updated: YYYY-MM-DD +related_issues: [] # Add if applicable, e.g., ["#14", "#15"] +related_docs: [] # Add if applicable +related_tasks: [] # Add if applicable +--- + +# [Complex Feature Title] + +> **⚠️ AI-Generated**: May contain errors. Verify before use. +> **Reviewed by**: [agent-name] agent *(add only after agent review and implementation - also update frontmatter)* + +**Files**: [list of all affected files with line numbers] + +## What & Why +[Detailed description with technical value] + +## Context +- **Existing pattern**: [reference similar implementation] +- **Constraints**: [technical limitations] +- **Dependencies**: [prerequisites] + +## Prerequisites +- [ ] Review .agents documentation: INDEX.md, AGENTS.md for context +- [ ] Check existing tasks in .agents/tasks/ for similar patterns and solutions +- [ ] Review related documentation in .agents/docs/ for architectural context +- [ ] Security analysis by security-analyst agent (if task involves auth, crypto, user data, or network operations) +- [ ] [Required setup/dependencies] +- [ ] Branch created from `master` +- [ ] No conflicting PRs + +## Implementation + +### Phase 1: Core Logic +- [ ] **[Specific task]** (`file.tsx:123`) + - Done when: [observable completion signal] + - Verify: [specific test] + - Reference: [existing pattern to follow] + +### Phase 2: Integration (requires Phase 1) +- [ ] **[Next task]** (`file.tsx:456`) + - Done when: [completion criteria] + - Verify: [verification method] + +## Verification +✅ **[Critical functionality]** + - Test: [step-by-step test] +✅ **TypeScript compiles** +✅ **iOS and Android compatible** +✅ **Edge cases handled** + +## Definition of Done +- [ ] All phases complete +- [ ] All verification tests pass +- [ ] No console errors +- [ ] Task updated with learnings +``` + +#### For Documentation (`.agents/docs/features/`): + +**CRITICAL DISTINCTION - Documentation vs Tasks**: +- **Documentation** describes the **current state** of a feature - what it IS and how it WORKS +- **Tasks** track implementation progress - status, phases, checklists, what needs to be DONE + +**Documentation files MUST NOT include**: +- ❌ "Feature Status" or "Implementation Status" sections with phases +- ❌ "Verification Checklist" or "Definition of Done" sections +- ❌ Implementation history language ("we added", "we fixed", "was implemented", "changes made") +- ❌ Phase tracking ("Phase 1 complete", "Phase 2 pending") +- ❌ Changelog-style entries or implementation notes +- ❌ Status indicators (Pending, In Progress, Complete) + +**Documentation files SHOULD**: +- ✅ Describe features in present tense as they currently exist +- ✅ Explain architecture, data flow, and integration points +- ✅ Include usage examples and code snippets +- ✅ Document technical decisions and their rationale +- ✅ List known limitations and their impact +- ✅ Reference related documentation and components + +```markdown +--- +type: doc +title: "[Feature Name]" +status: done +ai_generated: true +reviewed_by: null +created: YYYY-MM-DD +updated: YYYY-MM-DD +related_docs: [] # Add if applicable +related_tasks: [] # Add if applicable +--- + +# [Feature Name] + +> **⚠️ AI-Generated**: May contain errors. Verify before use. +> **Reviewed by**: [agent-name] agent *(add only after agent review and implementation - also update frontmatter)* + +## Overview +[What the feature does and why it exists - written as current state, not history] + +## Architecture +[Technical implementation details - describe how it works NOW] +- **Key components**: List main files/classes with line references +- **Data flow**: How information moves through system +- **Integration points**: How it connects to other features + +## Usage Examples +[Code examples showing how to use the feature] + +## Technical Decisions +[Rationale for key architectural choices - explain WHY, not WHEN] +- **[Decision 1]**: Rationale and trade-offs +- **[Decision 2]**: Alternative approaches considered + +## Known Limitations +[Current constraints and their impact] +- [Limitation 1]: Impact and potential workarounds +- [Limitation 2]: Design trade-offs accepted + +## Related Documentation +- [Cross-references to other relevant docs] +- [Links to API references] +- [Related tasks or bugs] +``` + +#### For Reports (`.agents/reports/`): +```markdown +--- +type: report +title: "[Report Title]" +ai_generated: true +reviewed_by: null +created: YYYY-MM-DD +updated: YYYY-MM-DD +related_tasks: [] # Add if applicable +related_docs: [] # Add if applicable +--- + +# [Report Title] + +> **⚠️ AI-Generated**: May contain errors. Verify before use. +> **Reviewed by**: [agent-name] agent *(add only after agent review and implementation - also update frontmatter)* + +## Executive Summary +[Brief overview of key findings and recommendations] + +## Scope & Methodology +- **Scope**: [What was analyzed/investigated] +- **Methodology**: [How the analysis was conducted] +- **Tools/Approaches**: [Specific methods or tools used] +- **Timeframe**: [When analysis was conducted] + +## Findings +### [Finding Category 1] +- **Issue**: [Description of what was found] +- **Impact**: [Severity/importance level] +- **Evidence**: [Supporting details, file locations, examples] + +### [Finding Category 2] +- **Issue**: [Description] +- **Impact**: [Level of concern] +- **Evidence**: [Supporting information] + +## Recommendations +### High Priority +1. **[Action Item 1]** + - **Why**: [Justification] + - **How**: [Implementation approach] + - **Files**: `src/path/to/file.ts:123` + +2. **[Action Item 2]** + - **Why**: [Reasoning] + - **How**: [Steps needed] + +### Medium/Low Priority +- [Less critical recommendations] + +## Action Items +- [ ] **[Specific task]** - Assigned to: [who] - Due: [when] +- [ ] **[Follow-up task]** - Priority: [level] + +## Related Documentation +- [Links to related tasks, bugs, documentation] +- [Cross-references to relevant code or features] + +## Appendix +[Supporting data, detailed logs, additional context] + +--- + +_Created: YYYY-MM-DD_ +_Report Type: [Audit/Research/Analysis/Assessment]_ +``` + +### Step 3: File Placement and Naming +- **General naming**: Use kebab-case: `feature-specific-descriptive-name.md` +- **Reports naming**: Use date format: `report-name_YYYY-MM-DD.md` (e.g., `auth-security-audit_2025-11-19.md`) +- Place in appropriate folder: + - Active bugs: `.agents/bugs/` + - Solved bugs: `.agents/bugs/.solved/` + - Active tasks: `.agents/tasks/` + - Completed tasks: `.agents/tasks/.done/` + - Feature docs: `.agents/docs/features/` + - Reports/audits: `.agents/reports/` (use date format: `report-name_YYYY-MM-DD.md`) + - Completed reports: `.agents/reports/.done/` + - Archived items: respective `.archived/` folders + +### Step 4: Cross-Reference Management +- Add references to related documentation +- Update existing docs that reference this item +- Maintain bidirectional links where appropriate +- Reference specific file:line locations when relevant + +### Step 5: Lifecycle Management + +**For Task Updates:** +1. **Read and verify** - Check all file paths exist, note current status +2. **Update autonomously** - Fix line numbers, update code examples, clarify steps +3. **Flag (don't change)** - Scope changes, conflicts, status changes to Complete +4. **Never change** - Checked checkboxes, Implementation Notes, original "What & Why" +5. **Document changes** - Add to Updates section with timestamp + +**For Status Changes:** +- Moving bugs to `.solved/` when fixed → **MUST update `status: done`** +- Moving tasks to `.done/` when complete → **MUST update `status: done`** +- Moving files to `.archived/` folders → **MUST update `status: archived`** +- Archiving outdated documentation +- Updating cross-references when files move +- **ALWAYS update the `updated` date when changing status** + +### Step 6: Agent Review Integration +When creating or updating documents that would benefit from specialized review: + +1. **Create initial document** with basic AI warning +2. **Identify review needs**: + - Security-related content → `security-analyst` agent +3. **Launch appropriate specialized agent** using Task tool +4. **Implement agent recommendations** in the document +5. **Add review notation** to document header: `> **Reviewed by**: [agent-name] agent` +6. **Update index** to reflect any changes + +### Step 7: Index Management +**CRITICAL: Always update the .agents index after any file operation** + +After creating, editing, moving, renaming, or deleting any bug report, task, or documentation file: + +1. **Run the index update script**: + ```bash + python .agents/update-index.py + ``` + +2. **Verify the INDEX.md was updated**: + - Check that new files appear in the index + - Verify that moved files show in correct sections + - Confirm deleted files are removed from index + +**When to run the index update script**: +- ✅ After creating any new .md file in .agents/ +- ✅ After moving files between folders (.done, .solved, .archived) +- ✅ After renaming any .md file in .agents/ +- ✅ After deleting any .md file in .agents/ +- ✅ After editing titles (# headings) in existing files + +The script automatically: +- Scans all .md files in .agents/ directory +- Extracts titles from first # heading +- Organizes by folder structure (docs → bugs → tasks → reports) +- Maintains proper subfolder groupings +- Updates "Last Updated" timestamp +- Handles numeric prefixes for ordering (01-file.md, 02-file.md) + +### Step 8: Commit Guidelines +- Create descriptive commit message following project conventions +- Never mention "Claude" or "Anthropic" in commit messages +- Focus on the "why" rather than the "what" +- Use established commit message patterns from project + +## Examples + +### Bug Report Example +**User says**: "There's an issue with the modal stacking order" + +**Skill response**: Creates `.agents/bugs/modal-zindex-stacking-issue.md` with proper template, analyzes the z-index conflict, documents the fix needed, and includes prevention strategies. + +### Task Creation Example +**User says**: "I need to implement user authentication" + +**Skill response**: Creates `.agents/tasks/user-authentication.md` with High complexity template, breaks down into phases (setup, UI components, backend integration), includes verification steps for security testing. + +### Documentation Example +**User says**: "Document the new search feature we just built" + +**Skill response**: Creates `.agents/docs/features/search-feature.md` describing the search feature as it currently exists - architecture, integration, performance characteristics, and usage examples. Uses present tense throughout ("The search feature provides...", "Messages are indexed using...") - NOT implementation history ("We added...", "Phase 1 implemented..."). Does NOT include status sections, verification checklists, or phase tracking. + +### Report Creation Example +**User says**: "Create a security audit of our authentication system" + +**Skill response**: Creates `.agents/reports/auth-security-audit_2025-11-19.md` with structured audit template, analyzes authentication flows, identifies potential vulnerabilities, provides actionable recommendations with priority levels, and includes specific file references and remediation steps. + +### Task Update Example +**User says**: "Update the authentication task - some file paths have changed" + +**Skill response**: Reads existing task, verifies current file locations, updates outdated paths and line numbers, adds discovered edge cases, documents changes in Updates section. Then runs the index update script to reflect any title changes in INDEX.md. + +### Index Update Example +**User says**: "Move the completed auth task to the .done folder" + +**Skill response**: +1. Moves `.agents/tasks/user-authentication.md` to `.agents/tasks/.done/user-authentication.md` +2. Updates frontmatter: `status: done`, `updated: [current date]` +3. Runs: `python .agents/update-index.py` +4. Verifies the task now appears under "📋 Completed Tasks" instead of "📋 Tasks" in INDEX.md + +## Workflow Integration + +This skill integrates seamlessly with your existing workflow: + +1. **Respects established patterns** from project conventions +2. **Uses existing templates** enhanced with automation +3. **Maintains folder structure** and naming conventions +4. **Preserves manual work** - never overwrites completed sections +5. **Cross-references properly** - links to related docs and code +6. **Follows commit guidelines** - proper messages, no AI mentions +7. **Updates systematically** - tracks changes and maintains history +8. **Quality assurance through agent reviews** - integrates specialized agents for enhanced quality and best practices + +--- + +_Updated: 2026-01-14_ diff --git a/.gitignore b/.gitignore index f610ec0..1374bcf 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,10 @@ expo-env.d.ts *.key *.mobileprovision +# Native module build artifacts +modules/*/android/build/ +modules/*/ios/build/ + # Metro .metro-health-check* @@ -33,6 +37,9 @@ yarn-error.* # local env files .env*.local +# Claude Code +.claude/settings.local.json + # typescript *.tsbuildinfo diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..1a83c13 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,190 @@ +# AGENTS.md + +This is the **Quorum Mobile** repository - the React Native/Expo mobile app for Quorum messenger. + +--- + +## Product Context: Discord Clone + +**Quorum is a Discord clone** running on a decentralized P2P network with end-to-end encryption. The UI/UX intentionally mirrors Discord to ease migration for users leaving Discord. + +| Discord Term | Quorum Term | Notes | +|--------------|-------------|-------| +| Server | Space | Same hierarchical structure | +| Channel | Channel | Text channels within Spaces | +| DM | DM | Direct messages, separate from Spaces | +| Server list | Space sidebar | Left rail navigation | + +**UX Philosophy**: +- **Mirror Discord patterns** - Users expect familiar behavior (navigation, message lists, reactions, mentions, etc.) +- **Mobile Discord app as benchmark** - When implementing UI, reference Discord mobile +- **Intentional improvements only** - Deviations from Discord should be documented and purposeful (better accessibility, privacy defaults, P2P optimizations) + +--- + +## Multi-Repository Ecosystem + +Quorum is built as a **multi-repo ecosystem**. This repo is one of three: + +| Repository | Purpose | +|------------|---------| +| **[quorum-desktop](https://github.com/QuilibriumNetwork/quorum-desktop)** | Web + Electron desktop app | +| **[quorum-mobile](https://github.com/QuilibriumNetwork/quorum-mobile)** | React Native + Expo mobile app (this repo) | +| **[quorum-shared](https://github.com/QuilibriumNetwork/quorum-shared)** | Shared types, hooks, sync protocol | + +All clients sync data via `@quilibrium/quorum-shared`. When implementing features, check if desktop has it and use shared types for sync compatibility. + +**Full Guide**: [Quorum Ecosystem Architecture](.agents/docs/quorum-shared-architecture.md) + +--- + +## Quick Start for AI Development + +**IMPORTANT**: Before starting ANY task, check these files: + +1. **[.agents/AGENTS.md](.agents/AGENTS.md)** - Documentation workflow guidelines +2. **[.agents/INDEX.md](.agents/INDEX.md)** - Find specific documentation for your task + +--- + +## Commands + +```bash +# Development +yarn start # Start Expo dev server +yarn android # Build and run on Android +yarn ios # Build and run on iOS +yarn web # Start web version + +# Code quality +yarn lint # Run ESLint +npx tsc --noEmit # TypeScript type checking + +# Cache management +yarn clean # Clear watchman, Metro, and temp caches +``` + +--- + +## Repository Structure + +``` +quorum-mobile/ +├── app/ # Expo Router pages (file-based routing) +│ ├── (onboarding)/ # Onboarding flow screens +│ ├── _layout.tsx # Root layout with providers +│ └── index.tsx # Main chat interface +│ +├── components/ # React components +│ ├── Chat/ # Chat UI (MessagesList, ChannelHeader, etc.) +│ ├── SocialFeed/ # Farcaster feed components +│ ├── onboarding/ # Onboarding UI +│ └── *Modal.tsx # Modal components +│ +├── context/ # React Context providers +│ ├── AuthContext.tsx # User auth, encryption keys +│ ├── WebSocketContext.tsx # E2E encrypted messaging +│ └── ApiClientContext.tsx # API client with auth +│ +├── services/ # Business logic +│ ├── crypto/ # Encryption, signing, native provider +│ ├── onboarding/ # Key generation, secure storage +│ ├── api/ # API client, React Query config +│ └── offline/ # MMKV persistence +│ +├── hooks/ # Custom React hooks +│ ├── chat/ # Chat operations (useMessages, etc.) +│ └── useFarcaster*.ts # Farcaster integration +│ +├── modules/quorum-crypto/ # Native Rust crypto module (Nitro) +│ +└── .agents/ # Development documentation + ├── docs/ # Architecture & feature guides + ├── tasks/ # Task tracking + ├── bugs/ # Bug reports + └── reports/ # Analysis & audits +``` + +--- + +## @quilibrium/quorum-shared + +Import shared types, hooks, and utilities from the shared package: + +```typescript +// Types +import type { Space, Message, Channel, UserConfig } from '@quilibrium/quorum-shared'; + +// Utilities (most common) +import { logger } from '@quilibrium/quorum-shared'; + +// Sync utilities +import { SyncService, createMemberDigest } from '@quilibrium/quorum-shared'; + +// Hooks +import { useSpaces, useMessages } from '@quilibrium/quorum-shared'; +``` + +**Full Reference**: [Quorum Ecosystem Architecture](.agents/docs/quorum-shared-architecture.md) + +--- + +## Architecture + +### Routing (Expo Router) +File-based routing in `app/` directory: +- `app/_layout.tsx` - Root layout with providers (Theme → Query → Storage → Auth → API → WebSocket) +- `app/(onboarding)/` - Grouped onboarding flow screens +- `app/index.tsx` - Main chat interface + +### State Management (3-tier) +1. **React Context** (`context/`) - Auth state, WebSocket connections, API client +2. **React Query** - Server state with MMKV persistence for offline support +3. **MMKV** (`react-native-mmkv`) - Fast local storage for config, bookmarks, navigation state + +### Native Crypto Module +`modules/quorum-crypto/` contains a Rust-based cryptographic module using Nitro: +- Provides encryption/decryption, key generation, signing +- TypeScript interface in `modules/quorum-crypto/src/` +- Native implementations in `android/` and `ios/` subdirectories + +--- + +## Code Patterns + +### Path Alias +Use `@/*` for imports (maps to project root): +```typescript +import { AuthContext } from '@/context/AuthContext'; +``` + +### Component Organization +- Feature-based: `components/Chat/`, `components/SocialFeed/`, `components/onboarding/` +- Modals as top-level components: `*Modal.tsx` +- Shared utilities in `components/shared/` + +### Hooks Organization +- `hooks/chat/` - Chat operations (useChannels, useMessages, useSendDirectMessage, etc.) +- `hooks/useFarcaster*.ts` - Farcaster integration hooks + +--- + +## Configuration Notes + +- **Node version**: v20.19.2 (see `.node-version`) +- **New Architecture**: Enabled in `app.json` +- **Metro config**: Custom resolver to prevent duplicate React/React Query instances +- **VSCode**: Auto-organizes imports on save (see `.vscode/settings.json`) + +--- + +## Development Checklist + +- [ ] Check `.agents/INDEX.md` for existing documentation +- [ ] Check if feature exists in quorum-desktop (use shared types for sync) +- [ ] Follow React Hooks rules (all hooks before conditional returns) +- [ ] Use `@quilibrium/quorum-shared` types for sync compatibility + +--- + +_Last updated: 2026-01-14 (added Discord clone context)_