# Familiar User Guide

**Version 2.5.0 | Signal-Grade Encryption | HIPAA-Ready**

---

## Table of Contents

1. [Quick Start](#quick-start)
2. [Installation](#installation)
3. [Configuration](#configuration)
4. [Channels](#channels)
5. [Mobile App (PWA)](#mobile-app-pwa)
6. [Skills](#skills)
7. [Security](#security)
8. [Multi-User Management](#multi-user-management)
9. [Mesh Networking](#mesh-networking)
10. [HIPAA Compliance](#hipaa-compliance)
11. [LLM Providers](#llm-providers)
12. [Memory System](#memory-system)
13. [Scheduling & Automation](#scheduling--automation)
14. [Admin Dashboard](#admin-dashboard)
15. [CLI Reference](#cli-reference)
16. [Troubleshooting](#troubleshooting)
17. [API Reference](#api-reference)
18. [Uninstall & Clean Slate](#uninstall--clean-slate)

---

## Quick Start

```bash
# 1. Extract and install
unzip familiar-v1_0_3.zip && cd familiar
chmod +x install.sh && FAMILIAR_ZIP=../familiar-v1_0_3.zip ./install.sh

# 2. Set API key
export ANTHROPIC_API_KEY="sk-ant-..."

# 3. Run
~/.familiar/bin/familiar
```

**First conversation:**
```
You: Hello
Familiar: Hello! I'm Familiar, your AI assistant. I can help with email, 
         calendar, tasks, research, and much more. What would you like to do?

You: What can you do?
Familiar: I have 21 skills available:
         • Calendar - Schedule events, check availability
         • Email - Read, compose, organize mail
         • Tasks - Todo lists, reminders, projects
         • Browser - Web research, automation
         • Knowledge - Notes, documents, search
         ...
```

---

## Installation

### Supported Platforms

| Platform | Architecture | Status |
|----------|--------------|--------|
| Raspberry Pi 4/5 | ARM64 | ✅ Recommended |
| Raspberry Pi 3 | ARMv7 | ✅ Supported |
| Ubuntu 20.04+ | x64/ARM64 | ✅ Supported |
| Debian 11+ | x64/ARM64 | ✅ Supported |
| macOS 12+ | x64/ARM64 | ✅ Supported |
| Windows (WSL2) | x64 | ✅ Supported |

### System Requirements

- **Minimum:** 1GB RAM, 2GB storage, Python 3.9+
- **Recommended:** 2GB+ RAM, 8GB storage, Python 3.11+
- **For mesh networking:** Multiple devices on same network

### Installation Methods

#### Method 1: Automated Installer (Recommended)

```bash
unzip familiar-v1_0_3.zip
cd familiar
chmod +x install.sh
FAMILIAR_ZIP=../familiar-v1_0_3.zip ./install.sh
```

The installer automatically:
- Detects your platform
- Installs system dependencies
- Creates Python virtual environment
- Sets up directory structure
- Installs systemd/launchd service
- Configures PATH

#### Method 2: Manual Installation

```bash
# 1. Create directories
mkdir -p ~/.familiar/{app,data,logs,secure,bin}
chmod 700 ~/.familiar/secure ~/.familiar/data

# 2. Extract files
unzip familiar.zip -d ~/.familiar/app

# 3. Create virtual environment
python3 -m venv ~/.familiar/venv
source ~/.familiar/venv/bin/activate

# 4. Install dependencies
pip install -r ~/.familiar/app/requirements.txt

# 5. Create config
cp ~/.familiar/app/config.sample.yaml ~/.familiar/config.yaml
```

#### Method 3: Docker (Coming Soon)

```bash
docker run -d \
  -v ~/.familiar:/data \
  -e ANTHROPIC_API_KEY=sk-ant-... \
  -p 5000:5000 \
  familiar/familiar:latest
```

### Directory Structure

```
~/.familiar/
├── config.yaml          # Main configuration
├── .env                 # API keys and secrets
├── app/                 # Familiar source code
├── data/                # Persistent data
│   ├── memory.json      # Long-term memory
│   ├── history.json     # Conversation history
│   └── sessions/        # User sessions
├── secure/              # Encryption keys
│   ├── keys.json        # X3DH identity keys
│   └── sessions.json    # Encrypted session states
├── logs/                # Log files
├── skills/              # Custom skills
└── bin/                 # CLI wrapper
    └── familiar
```

### Post-Installation Verification

```bash
# Check installation
~/.familiar/bin/familiar --version

# Run self-test
~/.familiar/bin/familiar --self-test

# Check configuration
~/.familiar/bin/familiar --check-config
```

---

## Configuration

### Main Configuration File

Location: `~/.familiar/config.yaml`

```yaml
# ═══════════════════════════════════════════════════════════════
# FAMILIAR CONFIGURATION
# ═══════════════════════════════════════════════════════════════

# ─────────────────────────────────────────────────────────────────
# LLM PROVIDER SETTINGS
# ─────────────────────────────────────────────────────────────────
llm:
  # Primary provider: anthropic, openai, ollama
  default_provider: anthropic
  
  # Anthropic Claude
  anthropic_model: claude-sonnet-4-6
  # Options: claude-opus-4-6, claude-sonnet-4-6, claude-haiku-4-5-20251001
  
  # OpenAI
  openai_model: gpt-4o
  # Options: gpt-4o, gpt-4-turbo, gpt-3.5-turbo
  
  # Ollama (local)
  ollama_model: llama3.2
  ollama_base_url: http://localhost:11434
  # Popular models: llama3.2, mistral, codellama, phi3
  
  # Generation settings
  max_tokens: 4096
  temperature: 0.7
  
  # Cost controls
  daily_budget_usd: 10.00
  warn_at_percentage: 80

# ─────────────────────────────────────────────────────────────────
# AGENT BEHAVIOR
# ─────────────────────────────────────────────────────────────────
agent:
  name: Familiar
  persona: a helpful AI assistant
  
  # Conversation
  max_conversation_history: 50
  context_window_tokens: 100000
  
  # Features
  memory_enabled: true
  skills_enabled: true
  scheduler_enabled: true
  proactive_enabled: false
  
  # Permissions
  security_mode: balanced  # paranoid, balanced, permissive
  allow_shell_commands: true
  allow_file_write: true
  allow_network_requests: true

# ─────────────────────────────────────────────────────────────────
# CHANNELS
# ─────────────────────────────────────────────────────────────────
channels:
  # Command Line Interface
  cli_enabled: true
  cli_prompt: "You: "
  cli_color_output: true
  
  # Telegram
  telegram_enabled: false
  telegram_token: null  # Get from @BotFather
  telegram_allowed_users: []  # List of Telegram user IDs
  telegram_allowed_groups: []  # List of group IDs
  telegram_admin_users: []  # Users with admin commands
  
  # Discord
  discord_enabled: false
  discord_token: null
  discord_allowed_servers: []
  discord_allowed_channels: []
  
  # Web Dashboard
  dashboard_enabled: true
  dashboard_port: 5000
  dashboard_host: 127.0.0.1  # Change to 0.0.0.0 for network access
  dashboard_require_auth: true

# ─────────────────────────────────────────────────────────────────
# SECURITY
# ─────────────────────────────────────────────────────────────────
security:
  # Encryption at rest
  encrypt_sessions: true
  encrypt_memory: true
  encrypt_history: true
  
  # Session management
  session_timeout_minutes: 60
  max_sessions_per_user: 5
  
  # Trust system
  auto_trust_upgrade: true
  trust_upgrade_threshold: 10  # Interactions before upgrade
  
  # Input validation
  max_input_length: 50000
  sanitize_html: true
  block_prompt_injection: true

# ─────────────────────────────────────────────────────────────────
# MESH NETWORKING (Multi-Device)
# ─────────────────────────────────────────────────────────────────
mesh:
  enabled: false
  role: standalone  # standalone, gateway, node
  
  # Gateway settings (central hub)
  gateway_port: 18789
  gateway_host: 0.0.0.0
  
  # Node settings (connects to gateway)
  gateway_url: null  # ws://gateway-ip:18789
  
  # Security (auto-generated on first run)
  # Keys stored in ~/.familiar/secure/

# ─────────────────────────────────────────────────────────────────
# COMPLIANCE
# ─────────────────────────────────────────────────────────────────
compliance:
  mode: none  # none, hipaa, soc2
  audit_logging: true
  retention_days: 365
  pii_detection: true
  data_classification: false

# ─────────────────────────────────────────────────────────────────
# OBSERVABILITY
# ─────────────────────────────────────────────────────────────────
observability:
  log_level: INFO  # DEBUG, INFO, WARNING, ERROR
  log_file: ~/.familiar/logs/familiar.log
  log_max_size_mb: 100
  log_backup_count: 5
  
  # Tracing
  tracing_enabled: true
  trace_llm_calls: true
  trace_skill_calls: true
  
  # Metrics
  metrics_enabled: true
  cost_tracking: true

# ─────────────────────────────────────────────────────────────────
# RESILIENCE
# ─────────────────────────────────────────────────────────────────
resilience:
  enabled: true
  max_retries: 3
  base_delay_seconds: 1.0
  max_delay_seconds: 60.0
  exponential_backoff: true
  
  # Circuit breaker
  circuit_breaker_enabled: true
  failure_threshold: 5
  recovery_timeout_seconds: 30

# ─────────────────────────────────────────────────────────────────
# SKILLS CONFIGURATION
# ─────────────────────────────────────────────────────────────────
skills:
  # Enable/disable specific skills
  calendar:
    enabled: true
    provider: google  # google, outlook, caldav
  
  email:
    enabled: true
    provider: gmail  # gmail, outlook, imap
    check_interval_minutes: 5
  
  browser:
    enabled: true
    headless: true
    timeout_seconds: 30
  
  gpio:
    enabled: false  # Enable on Raspberry Pi
    allowed_pins: [17, 27, 22, 23, 24, 25]
```

### Environment Variables

Location: `~/.familiar/.env`

```bash
# ═══════════════════════════════════════════════════════════════
# FAMILIAR SECRETS
# ═══════════════════════════════════════════════════════════════

# LLM API Keys (at least one required)
ANTHROPIC_API_KEY=sk-ant-api03-...
OPENAI_API_KEY=sk-...

# Channel Tokens
TELEGRAM_BOT_TOKEN=123456789:ABCdefGHIjklMNOpqrsTUVwxyz
DISCORD_BOT_TOKEN=MTIzNDU2Nzg5...

# Email (for email skill)
GMAIL_CLIENT_ID=...
GMAIL_CLIENT_SECRET=...

# Calendar (for calendar skill)
GOOGLE_CALENDAR_CREDENTIALS=~/.familiar/credentials/google.json

# Encryption (auto-generated, don't change)
FAMILIAR_ENCRYPTION_KEY=...

# Database (optional, for distributed setups)
REDIS_URL=redis://localhost:6379
```

**Important:** Keep `.env` secure with `chmod 600 ~/.familiar/.env`

---

## Channels

### CLI (Command Line Interface)

The default interactive interface.

```bash
# Start CLI
familiar

# With specific config
familiar --config /path/to/config.yaml

# Verbose mode
familiar --verbose
```

**CLI Commands:**

| Command | Description |
|---------|-------------|
| `/help` | Show available commands |
| `/skills` | List enabled skills |
| `/memory` | Show memory status |
| `/clear` | Clear conversation history |
| `/export` | Export conversation |
| `/settings` | Show current settings |
| `/quit` | Exit Familiar |

**Example Session:**

```
You: /skills

Familiar: 📦 Enabled Skills:
         ├── calendar (Google Calendar)
         ├── email (Gmail)
         ├── tasks (Local)
         ├── browser (Playwright)
         ├── knowledge (Vector DB)
         └── ... 12 more

You: Schedule a meeting with Sarah tomorrow at 2pm

Familiar: I'll create that calendar event:
         
         📅 Meeting with Sarah
         📆 Tomorrow, 2:00 PM - 3:00 PM
         
         Should I send Sarah an invitation? I'll need her email address.

You: Yes, sarah@company.com

Familiar: ✓ Event created and invitation sent to sarah@company.com
```

### Telegram

Full-featured Telegram bot integration.

**Setup:**

1. Message @BotFather on Telegram
2. Send `/newbot` and follow prompts
3. Copy the token
4. Add to config:

```yaml
channels:
  telegram_enabled: true
  telegram_token: "123456789:ABCdefGHIjklMNOpqrsTUVwxyz"
  telegram_allowed_users: [your_user_id]
```

5. Start: `familiar --telegram`

**Getting Your User ID:**
- Message @userinfobot on Telegram
- Or send any message to your bot and check logs

**Telegram Features:**

| Feature | Description |
|---------|-------------|
| Text messages | Natural conversation |
| Voice messages | Speech-to-text processing |
| Documents | Read PDFs, Word, text files |
| Images | Image analysis and OCR |
| Inline keyboards | Interactive responses |
| Commands | `/start`, `/help`, `/settings` |

**Group Chat Setup:**

```yaml
channels:
  telegram_allowed_groups: [-1001234567890]
  telegram_group_prefix: "@familiar"  # Require mention in groups
```

**Admin Commands:**

```
/admin status     - System status
/admin users      - List users
/admin broadcast  - Send to all users
/admin reload     - Reload configuration
```

### Discord

Full Discord bot integration.

**Setup:**

1. Go to [Discord Developer Portal](https://discord.com/developers/applications)
2. Create application → Add bot
3. Enable Message Content Intent
4. Copy token
5. Generate invite URL with permissions:
   - Send Messages
   - Read Message History
   - Add Reactions
   - Embed Links
   - Attach Files

```yaml
channels:
  discord_enabled: true
  discord_token: "MTIzNDU2Nzg5..."
  discord_allowed_servers: [1234567890]
  discord_command_prefix: "!"
```

**Discord Commands:**

```
!help          - Show help
!ask <query>   - Ask Familiar
!task <task>   - Create task
!remind <msg>  - Set reminder
!search <q>    - Web search
```

### Web Dashboard

Browser-based interface with full functionality.

**Start Dashboard:**

```bash
familiar --dashboard
# Opens http://localhost:5000
```

**Features:**

- Real-time chat interface
- Conversation history
- Settings management
- User administration
- Skill status monitoring
- Cost/usage tracking
- Log viewer

**Network Access:**

```yaml
channels:
  dashboard_host: 0.0.0.0  # Allow network access
  dashboard_port: 5000
  dashboard_require_auth: true
```

**With HTTPS (recommended for network):**

```bash
# Generate self-signed certificate
openssl req -x509 -newkey rsa:4096 -nodes \
  -keyout ~/.familiar/key.pem \
  -out ~/.familiar/cert.pem \
  -days 365

# Configure
familiar --dashboard --ssl-cert ~/.familiar/cert.pem --ssl-key ~/.familiar/key.pem
```

### SMS (via Twilio)

```yaml
channels:
  sms_enabled: true
  twilio_account_sid: "AC..."
  twilio_auth_token: "..."
  twilio_phone_number: "+1234567890"
  sms_allowed_numbers: ["+1987654321"]
```

### Signal (via signal-cli)

```yaml
channels:
  signal_enabled: true
  signal_phone_number: "+1234567890"
  signal_config_path: ~/.local/share/signal-cli
```

### iMessage (macOS only)

```yaml
channels:
  imessage_enabled: true
  imessage_allowed_contacts: ["email@example.com", "+1234567890"]
```

### Microsoft Teams

```yaml
channels:
  teams_enabled: true
  teams_app_id: "..."
  teams_app_password: "..."
  teams_tenant_id: "..."
```

### WhatsApp (via WhatsApp Business API)

```yaml
channels:
  whatsapp_enabled: true
  whatsapp_phone_number_id: "..."
  whatsapp_access_token: "..."
```

---

## Mobile App (PWA)

Familiar includes a Progressive Web App (PWA) that works on any smartphone. Install it directly from your browser — no app store required.

### Installation

**iPhone (Safari):**
1. Open `http://your-familiar-server:5000` in Safari
2. Tap the Share button (square with arrow)
3. Scroll down and tap "Add to Home Screen"
4. Tap "Add"

**Android (Chrome):**
1. Open `http://your-familiar-server:5000` in Chrome
2. Tap the menu (⋮) in the top right
3. Tap "Add to Home Screen" or "Install app"
4. Tap "Install"

### Features

| Feature | Description |
|---------|-------------|
| Offline Support | Messages queue when offline, sync when back online |
| Push Notifications | Get alerts when Familiar responds |
| Touch Gestures | Native swipe, pull, and long-press interactions |
| Background Sync | Queued messages send automatically |
| Home Screen Icon | Launches like a native app |

### Touch Gestures

The mobile app supports native touch interactions:

| Gesture | Action |
|---------|--------|
| Swipe from left edge → | Open sidebar/conversations |
| Swipe left on sidebar | Close sidebar |
| Pull down on messages | Refresh and sync |
| Long press on message | Context menu (copy, retry, delete) |
| Tap buttons | Haptic feedback (vibration) |

### Configuration

Enable the dashboard with network access:

```yaml
# ~/.familiar/config.yaml
dashboard:
  enabled: true
  host: 0.0.0.0    # Allow network access
  port: 5000
  pwa_enabled: true
```

### Offline Behavior

When offline:
- Messages are stored locally in IndexedDB
- A visual indicator shows offline status
- Queued message count is displayed
- Background sync retries when connection returns

```
┌─────────────────────────────────┐
│ 📴 You're offline               │
│ 3 messages waiting to send      │
└─────────────────────────────────┘
```

### Push Notifications

Enable push notifications for real-time alerts:

```yaml
dashboard:
  push_notifications: true
  vapid_public_key: "..."   # Auto-generated
  vapid_private_key: "..."  # Auto-generated
```

Users must grant notification permission in their browser. The app will prompt on first interaction.

### Security

The PWA inherits all Familiar security features:

- **HTTPS required** for production (self-signed OK for local)
- **Signal-grade encryption** for message transport
- **Biometric lock** option (device-dependent)
- **Secure storage** via browser's IndexedDB
- **No data stored remotely** — everything stays on your server

### Troubleshooting

**App won't install:**
- Ensure you're using HTTPS (or localhost)
- Check that `manifest.json` is accessible
- Clear browser cache and retry

**Notifications not working:**
- Check notification permissions in browser settings
- Verify VAPID keys are configured
- Ensure service worker is registered

**Messages not syncing:**
- Check network connectivity
- Verify server is running
- Look for errors in browser console (F12)

**Gestures not responding:**
- Ensure JavaScript is enabled
- Try clearing browser cache
- Check for browser compatibility

---

## Skills

Familiar includes 17 built-in skills. Each skill provides specific capabilities.

### Calendar

Manage events across calendar providers.

**Capabilities:**
- Create, update, delete events
- Check availability
- Send invitations
- Handle recurring events
- Natural language scheduling

**Configuration:**

```yaml
skills:
  calendar:
    enabled: true
    provider: google  # google, outlook, caldav
    default_duration_minutes: 60
    working_hours_start: 9
    working_hours_end: 17
    timezone: America/Los_Angeles
```

**Setup Google Calendar:**

1. Go to [Google Cloud Console](https://console.cloud.google.com)
2. Create project → Enable Calendar API
3. Create OAuth credentials
4. Download `credentials.json` to `~/.familiar/credentials/`
5. First run will open browser for authorization

**Examples:**

```
You: Schedule team standup every weekday at 9am
Familiar: ✓ Created recurring event:
         📅 Team Standup
         🔄 Every weekday at 9:00 AM
         📍 No location set
         
You: What's on my calendar tomorrow?
Familiar: Tomorrow, January 15th:
         • 9:00 AM - Team Standup (30 min)
         • 11:00 AM - Client Call with Acme Corp (1 hr)
         • 2:00 PM - Dentist Appointment (1 hr)
         
         You have 5.5 hours of open time.

You: Move the dentist to Thursday
Familiar: ✓ Moved "Dentist Appointment" to Thursday, January 17th at 2:00 PM
```

### Email

Read, compose, and manage email.

**Capabilities:**
- Read inbox, sent, drafts
- Compose and send email
- Search messages
- Manage labels/folders
- Handle attachments
- Summarize threads

**Configuration:**

```yaml
skills:
  email:
    enabled: true
    provider: gmail  # gmail, outlook, imap
    check_interval_minutes: 5
    max_emails_per_fetch: 50
    auto_categorize: true
```

**Setup Gmail:**

1. Enable Gmail API in Google Cloud Console
2. Create OAuth credentials (same as Calendar)
3. Add scopes: `gmail.readonly`, `gmail.send`, `gmail.modify`

**Examples:**

```
You: Check my email
Familiar: 📬 Inbox Summary (12 unread):
         
         🔴 Urgent:
         • John Smith - "Contract Review Needed" (2 hours ago)
         
         📋 Action Required:
         • HR Department - "Benefits Enrollment Deadline" (yesterday)
         • IT Support - "Password Reset Confirmation" (yesterday)
         
         📰 Updates:
         • Newsletter - Weekly Tech Digest (today)
         • ... 8 more

You: Summarize the contract email from John
Familiar: John is asking you to review the vendor contract for ABC Corp
         before Friday. Key points:
         • Contract value: $50,000
         • Term: 2 years with auto-renewal
         • He flagged Section 4.2 (liability) for your attention
         • Attached: ABC_Contract_v2.pdf
         
         Should I draft a response?

You: Draft a reply saying I'll review it by Thursday
Familiar: 📝 Draft email:
         
         To: john.smith@company.com
         Subject: Re: Contract Review Needed
         
         Hi John,
         
         Thanks for sending this over. I'll review the contract and 
         provide my feedback by Thursday EOD. I'll pay special attention 
         to Section 4.2 as you mentioned.
         
         Best regards
         
         [Send] [Edit] [Discard]
```

### Tasks

Todo lists, projects, and reminders.

**Capabilities:**
- Create tasks and subtasks
- Set due dates and priorities
- Create projects
- Track completion
- Set reminders
- Recurring tasks

**Configuration:**

```yaml
skills:
  tasks:
    enabled: true
    storage: local  # local, todoist, asana
    default_reminder_minutes: 30
    auto_schedule: true
```

**Examples:**

```
You: Add a task to call Mom on Sunday
Familiar: ✓ Task created:
         📌 Call Mom
         📅 Due: Sunday, January 19th
         🔔 Reminder: Sunday at 10:00 AM

You: Show my tasks
Familiar: 📋 Your Tasks:
         
         Overdue:
         ⚠️ Submit expense report (Due: Jan 10)
         
         Today:
         □ Review contract for John
         □ Team standup prep
         
         This Week:
         □ Call Mom (Sunday)
         □ Dentist appointment (Thursday)
         
         Projects:
         • Website Redesign (3/7 tasks complete)
         • Q1 Planning (0/5 tasks complete)

You: Create a project for the office move
Familiar: 📁 Project created: Office Move
         
         I can help you break this down. Common tasks include:
         • Notify employees
         • Hire movers
         • Update address with vendors
         • IT infrastructure setup
         • ... 
         
         Want me to add these as subtasks?
```

### Browser

Web research and automation.

**Capabilities:**
- Search the web
- Read web pages
- Fill forms
- Take screenshots
- Extract data
- Automated workflows

**Configuration:**

```yaml
skills:
  browser:
    enabled: true
    engine: playwright  # playwright, selenium
    headless: true
    timeout_seconds: 30
    user_agent: "Familiar/2.1"
    block_ads: true
```

**Setup:**

```bash
# Install browser
pip install playwright
playwright install chromium
```

**Examples:**

```
You: Search for the best Italian restaurants nearby
Familiar: 🔍 Searching for Italian restaurants...
         
         Top rated near you:
         1. Trattoria Roma (4.8⭐) - 0.5 mi
            "Authentic pasta, intimate setting"
            $$ | Open until 10 PM
            
         2. Luigi's Kitchen (4.6⭐) - 1.2 mi
            "Family recipes since 1985"
            $$ | Open until 9 PM
            
         3. Pasta Palace (4.5⭐) - 0.8 mi
            "Great lunch specials"
            $ | Open until 11 PM
         
         Want me to make a reservation?

You: What's the news about AI today?
Familiar: 📰 Top AI News (January 14, 2025):
         
         • "OpenAI announces GPT-5 preview" - TechCrunch
           Summary: New model shows 40% improvement...
           
         • "EU finalizes AI Act implementation" - Reuters
           Summary: New regulations take effect March 1...
           
         • "Anthropic raises $2B Series D" - Bloomberg
           Summary: Valuation reaches $25B...
```

### Knowledge

Personal knowledge base and document management.

**Capabilities:**
- Store notes and documents
- Semantic search
- Auto-tagging
- Link related items
- Export to various formats

**Configuration:**

```yaml
skills:
  knowledge:
    enabled: true
    storage_path: ~/.familiar/knowledge
    embedding_model: local  # local, openai
    auto_tag: true
    ocr_enabled: true
```

**Examples:**

```
You: Remember that the wifi password is "SecureNetwork2024"
Familiar: ✓ Saved to knowledge base:
         📝 WiFi Password
         🏷️ Tags: #credentials #network #home

You: What's the wifi password?
Familiar: The WiFi password is: SecureNetwork2024
         (Saved on January 10, 2025)

You: Save this PDF as meeting notes
[Attachment: meeting_notes.pdf]
Familiar: ✓ Document saved:
         📄 Meeting Notes - Q1 Planning
         📅 January 14, 2025
         🏷️ Auto-tagged: #meeting #planning #q1
         
         Summary: Discussed Q1 objectives including...
```

### Voice

Speech-to-text and text-to-speech.

**Capabilities:**
- Transcribe audio
- Voice responses
- Voice commands
- Multiple languages
- Speaker identification

**Configuration:**

```yaml
skills:
  voice:
    enabled: true
    stt_provider: whisper  # whisper, google, azure
    tts_provider: local    # local, elevenlabs, google
    wake_word: "hey familiar"
    language: en-US
```

### GPIO (Raspberry Pi)

Control hardware pins on Raspberry Pi.

**Capabilities:**
- Read/write digital pins
- PWM control
- I2C/SPI devices
- Sensor reading
- Relay control

**Configuration:**

```yaml
skills:
  gpio:
    enabled: true
    allowed_pins: [17, 27, 22, 23, 24, 25]
    pin_names:
      17: "Living Room Light"
      27: "Garage Door"
      22: "Temperature Sensor"
```

**Examples:**

```
You: Turn on the living room light
Familiar: ✓ Living Room Light (GPIO 17) turned ON

You: What's the temperature?
Familiar: 🌡️ Temperature Sensor (GPIO 22): 72.4°F / 22.4°C
         Humidity: 45%
```

### Planner

Complex task breakdown and planning.

**Capabilities:**
- Break down complex goals
- Create action plans
- Estimate timelines
- Identify dependencies
- Track milestones

**Examples:**

```
You: Help me plan a website redesign
Familiar: 📋 Website Redesign Plan
         
         Phase 1: Discovery (Week 1-2)
         □ Audit current site performance
         □ Gather stakeholder requirements
         □ Analyze competitor sites
         □ Define success metrics
         
         Phase 2: Design (Week 3-4)
         □ Create wireframes
         □ Design mockups
         □ Get stakeholder approval
         ...
         
         Estimated timeline: 8 weeks
         Dependencies identified: 3
         
         Should I create these as tasks?
```

### Triage

Intelligent prioritization and routing.

**Capabilities:**
- Prioritize incoming items
- Route to appropriate handlers
- Urgency detection
- Categorization
- Escalation rules

**Examples:**

```
You: Triage my inbox
Familiar: 📊 Inbox Triage Complete:
         
         🔴 Urgent (respond today):
         • CEO - "Board meeting prep" 
         • Client - "System down!"
         
         🟡 Important (this week):
         • HR - "Performance review"
         • Vendor - "Contract renewal"
         
         🟢 Low Priority:
         • Newsletter subscriptions (5)
         • Promotional emails (12)
         
         ⚪ Auto-archived:
         • Spam/marketing (23 items)
         
         Should I draft responses for the urgent items?
```

### Messaging

Cross-platform message management.

**Capabilities:**
- Unified inbox
- Send to any platform
- Message templates
- Scheduled sending
- Read receipts

### Proactive

Autonomous monitoring and alerts.

**Capabilities:**
- Monitor conditions
- Trigger alerts
- Scheduled checks
- Anomaly detection
- Automated responses

**Configuration:**

```yaml
skills:
  proactive:
    enabled: true
    checks:
      - name: "Weather Alert"
        condition: "temperature > 100 or weather == 'storm'"
        action: "notify"
        interval_minutes: 60
      
      - name: "Calendar Reminder"
        condition: "event in 15 minutes"
        action: "notify"
        interval_minutes: 5
```

### Triggers

Event-based automation.

**Capabilities:**
- Time-based triggers
- Event-based triggers
- Webhook triggers
- Conditional logic
- Chain actions

**Examples:**

```yaml
skills:
  triggers:
    rules:
      - name: "Morning Briefing"
        trigger:
          type: time
          schedule: "0 7 * * *"  # 7 AM daily
        action:
          type: run_skill
          skill: email
          command: "summarize inbox"
          
      - name: "New Email Alert"
        trigger:
          type: event
          event: "email.received"
          condition: "from contains 'boss'"
        action:
          type: notify
          channel: telegram
          message: "New email from your boss: {subject}"
```

### Google Drive

Cloud storage integration.

**Capabilities:**
- List files
- Search documents
- Read content
- Upload files
- Share management

### Nonprofit

Specialized tools for nonprofit organizations.

**Capabilities:**
- Donor management
- Grant tracking
- Campaign coordination
- Volunteer scheduling
- Board communications
- Compliance reporting

**Configuration:**

```yaml
skills:
  nonprofit:
    enabled: true
    organization_name: "Example Foundation"
    fiscal_year_start: "July"
    donor_tiers:
      - name: "Supporter"
        min_amount: 0
      - name: "Champion"
        min_amount: 1000
      - name: "Benefactor"
        min_amount: 10000
```

### Marketplace

Discover and install community skills.

**Capabilities:**
- Browse available skills
- Install from repository
- Update skills
- Publish custom skills
- Rate and review

### Web API

Create custom integrations.

**Capabilities:**
- REST API endpoints
- Webhook handlers
- Custom integrations
- Rate limiting
- Authentication

**Example - Custom Webhook:**

```yaml
skills:
  webapi:
    enabled: true
    endpoints:
      - path: /api/notify
        method: POST
        action: send_notification
        auth_required: true
```

---

## Security

### Trust Levels

Familiar uses a progressive trust system with 4 levels:

| Level | Name | Capabilities |
|-------|------|--------------|
| 0 | Guest | Read-only, basic queries |
| 1 | User | Standard operations, no system access |
| 2 | Trusted | File operations, automation |
| 3 | Admin | Full access, configuration changes |

**Capability Matrix:**

| Capability | Guest | User | Trusted | Admin |
|------------|-------|------|---------|-------|
| Ask questions | ✅ | ✅ | ✅ | ✅ |
| Use skills | ❌ | ✅ | ✅ | ✅ |
| Read files | ❌ | ❌ | ✅ | ✅ |
| Write files | ❌ | ❌ | ✅ | ✅ |
| Execute shell | ❌ | ❌ | ❌ | ✅ |
| Change config | ❌ | ❌ | ❌ | ✅ |
| Manage users | ❌ | ❌ | ❌ | ✅ |

### Encryption at Rest

All sensitive data is encrypted using Fernet (AES-128-CBC):

- Session data
- Conversation history
- Memory contents
- User credentials

**Key Management:**

```bash
# Generate new encryption key
python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"

# Add to .env
FAMILIAR_ENCRYPTION_KEY=your_generated_key
```

### Signal-Grade Transport Encryption

For mesh networking, Familiar implements the Signal Protocol:

**Components:**
- **X3DH**: Extended Triple Diffie-Hellman for initial key exchange
- **Double Ratchet**: Per-message key rotation
- **X25519**: Elliptic curve Diffie-Hellman
- **Ed25519**: Digital signatures
- **XSalsa20-Poly1305**: Authenticated encryption

**Security Properties:**
- Forward secrecy
- Post-compromise recovery
- Replay protection
- Deniable authentication

### Input Validation

All inputs are validated:
- Maximum length limits
- HTML sanitization
- Prompt injection detection
- Shell command blocking (configurable)

### Audit Logging

All actions are logged:

```json
{
  "timestamp": "2025-01-14T10:30:00Z",
  "user_id": "user_123",
  "action": "skill.email.send",
  "details": {
    "to": "recipient@example.com",
    "subject": "Meeting Follow-up"
  },
  "ip_address": "192.168.1.100",
  "trust_level": 2
}
```

---

## Multi-User Management

### Adding Users

**Via CLI:**

```bash
familiar --add-user \
  --username "sarah" \
  --email "sarah@example.com" \
  --trust-level 2 \
  --channels telegram,cli
```

**Via Config:**

```yaml
users:
  - username: sarah
    email: sarah@example.com
    trust_level: 2
    channels: [telegram, cli]
    telegram_id: 123456789
    
  - username: john
    email: john@example.com
    trust_level: 1
    channels: [discord]
    discord_id: "987654321"
```

### User Permissions

```yaml
users:
  - username: sarah
    trust_level: 2
    permissions:
      skills:
        calendar: true
        email: true
        browser: false
        gpio: false
      
      capabilities:
        read_files: true
        write_files: false
        shell_commands: false
```

### Budgets

Control costs per user:

```yaml
users:
  - username: sarah
    budget:
      daily_usd: 5.00
      monthly_usd: 100.00
      warn_at_percentage: 80
```

---

## Mesh Networking

Connect multiple Familiar instances securely.

### Architecture

```
                    ┌──────────────────┐
                    │  Gateway Node    │
                    │  (Central Pi)    │
                    │  Port: 18789     │
                    └────────┬─────────┘
                             │
              ┌──────────────┼──────────────┐
              │              │              │
       ┌──────▼─────┐ ┌──────▼─────┐ ┌──────▼─────┐
       │   Node A   │ │   Node B   │ │   Node C   │
       │  (Office)  │ │   (Home)   │ │  (Mobile)  │
       └────────────┘ └────────────┘ └────────────┘
```

### Gateway Setup

On the central Pi:

```yaml
# ~/.familiar/config.yaml
mesh:
  enabled: true
  role: gateway
  gateway_port: 18789
  gateway_host: 0.0.0.0
```

```bash
# Start gateway
familiar --mesh-gateway
```

### Node Setup

On each additional device:

```yaml
# ~/.familiar/config.yaml
mesh:
  enabled: true
  role: node
  node_name: "Office Pi"
  gateway_url: ws://192.168.1.100:18789
```

```bash
# Connect to gateway
familiar --mesh-node
```

### Secure Key Exchange

On first connection, nodes perform X3DH key exchange:

1. Gateway publishes prekey bundle
2. Node initiates with ephemeral key
3. Both derive shared secret
4. Double Ratchet begins
5. All subsequent messages encrypted

### Cross-Node Messaging

```
You (Office): @home Turn off the lights
Familiar: ✓ Sent command to Home node
         Response: Living room lights turned off
```

### Shared State

Nodes can share:
- Memory (with permissions)
- Task lists
- Calendar events
- Knowledge base

```yaml
mesh:
  sharing:
    memory: true
    tasks: true
    calendar: read_only
    knowledge: true
```

---

## HIPAA Compliance

For healthcare and other regulated environments.

### Enabling HIPAA Mode

```yaml
compliance:
  mode: hipaa
  
  # Required for HIPAA
  audit_logging: true
  encrypt_at_rest: true
  session_timeout_minutes: 15
  auto_logout: true
  
  # PHI handling
  pii_detection: true
  pii_redaction: true
  data_classification: true
  
  # Retention
  retention_days: 2190  # 6 years
  
  # Access controls
  require_authentication: true
  mfa_enabled: true
  access_logging: true
```

### HIPAA Checklist

Familiar provides:

| Requirement | Implementation |
|-------------|----------------|
| Access Controls | Trust levels, user permissions |
| Audit Controls | Comprehensive logging |
| Integrity Controls | Checksums, encryption |
| Transmission Security | TLS, Signal encryption |
| Encryption | AES-256 at rest |
| Authentication | Multi-factor support |
| Automatic Logoff | Session timeouts |

### Audit Log Format (HIPAA)

```json
{
  "timestamp": "2025-01-14T10:30:00.000Z",
  "event_type": "phi_access",
  "user_id": "nurse_sarah",
  "patient_id": "REDACTED",
  "action": "view_record",
  "data_accessed": ["demographics", "medications"],
  "ip_address": "192.168.1.50",
  "device_id": "station_3",
  "success": true,
  "session_id": "sess_abc123"
}
```

### Running Compliance Check

```bash
familiar --compliance-check hipaa

HIPAA Compliance Check
═══════════════════════════════════════

✅ Encryption at rest: Enabled (AES-256)
✅ Audit logging: Enabled
✅ Session timeout: 15 minutes
✅ Access controls: Configured
✅ Transmission security: TLS 1.3
⚠️ MFA: Not configured (recommended)
✅ Data retention: 6 years configured

Overall: COMPLIANT (with recommendations)
```

---

## LLM Providers

### Anthropic Claude (Recommended)

```yaml
llm:
  default_provider: anthropic
  anthropic_model: claude-sonnet-4-6
```

**Models:**

| Model | Best For | Cost |
|-------|----------|------|
| claude-opus-4-6 | Complex reasoning | $$$ |
| claude-sonnet-4-6 | Balanced performance | $$ |
| claude-haiku-4-5-20251001 | Fast, simple tasks | $ |

### OpenAI

```yaml
llm:
  default_provider: openai
  openai_model: gpt-4o
```

**Models:**

| Model | Best For | Cost |
|-------|----------|------|
| gpt-4o | Best overall | $$$ |
| gpt-4-turbo | Long context | $$ |
| gpt-3.5-turbo | Fast, cheap | $ |

### Ollama (Local, Free)

Run AI locally without API costs:

```bash
# Install Ollama
curl -fsSL https://ollama.ai/install.sh | sh

# Download a model
ollama pull llama3.2

# Start server
ollama serve
```

```yaml
llm:
  default_provider: ollama
  ollama_model: llama3.2
  ollama_base_url: http://localhost:11434
```

**Popular Ollama Models:**

| Model | Size | Best For |
|-------|------|----------|
| llama3.2 | 3B/8B | General purpose |
| mistral | 7B | Fast, capable |
| codellama | 7B | Code generation |
| phi3 | 3B | Small, efficient |

### Model Routing

Use different models for different tasks:

```yaml
llm:
  routing:
    default: claude-sonnet-4-6
    
    rules:
      - condition: "task == 'coding'"
        model: codellama
        provider: ollama
        
      - condition: "complexity > 0.8"
        model: claude-opus-4-6
        provider: anthropic
        
      - condition: "cost_sensitive"
        model: llama3.2
        provider: ollama
```

---

## Memory System

### Short-term Memory

Conversation context within a session:

```yaml
agent:
  max_conversation_history: 50
  context_window_tokens: 100000
```

### Long-term Memory

Persistent knowledge across sessions:

```yaml
agent:
  memory_enabled: true
  memory_storage: ~/.familiar/data/memory.json
  memory_max_items: 10000
```

**Memory Commands:**

```
You: Remember that my favorite color is blue
Familiar: ✓ I'll remember that your favorite color is blue.

You: What's my favorite color?
Familiar: Your favorite color is blue.

You: Forget my favorite color
Familiar: ✓ I've forgotten your favorite color preference.
```

### Episodic Memory

Event-based memory with temporal context:

```yaml
agent:
  episodic_memory_enabled: true
  episodic_decay_days: 90  # Older memories decay
```

### Memory Search

```
You: What did we discuss last week about the project?
Familiar: Last week (January 7-13), we discussed:
         
         • Project timeline - moved deadline to Feb 15
         • Budget concerns - approved $5000 increase
         • New team member - Sarah joining Monday
         
         Want me to show the full conversations?
```

---

## Scheduling & Automation

### Scheduled Tasks

```yaml
scheduler:
  enabled: true
  tasks:
    - name: "Morning Briefing"
      schedule: "0 7 * * *"  # 7 AM daily
      action: |
        Summarize my inbox, calendar for today, and any overdue tasks
        
    - name: "Weekly Report"
      schedule: "0 17 * * 5"  # 5 PM Friday
      action: |
        Generate a summary of this week's completed tasks and 
        accomplishments
        
    - name: "Database Backup"
      schedule: "0 2 * * *"  # 2 AM daily
      action: |
        Run backup skill for all data
```

### Natural Language Scheduling

```
You: Remind me every Monday at 9am to submit my timesheet
Familiar: ✓ Scheduled recurring reminder:
         📌 Submit timesheet
         🔄 Every Monday at 9:00 AM
         
You: In 2 hours, remind me to call the dentist
Familiar: ✓ Reminder set for 3:30 PM today:
         📌 Call the dentist
```

### Automation Workflows

```yaml
automations:
  - name: "Invoice Processing"
    trigger:
      type: email
      condition: "subject contains 'Invoice' and has_attachment"
    actions:
      - extract_attachment
      - save_to: "~/Documents/Invoices/{date}/"
      - add_task: "Review invoice from {sender}"
      - notify: "New invoice received from {sender}"
```

---

## Admin Dashboard

### Accessing the Dashboard

```bash
familiar --dashboard
# Open http://localhost:5000
```

### Dashboard Features

**Home:**
- System status
- Active sessions
- Recent activity
- Quick actions

**Conversations:**
- View all conversations
- Search history
- Export transcripts
- Delete conversations

**Users:**
- List all users
- Edit permissions
- View activity
- Manage budgets

**Skills:**
- Enable/disable skills
- Configure settings
- View usage stats

**Analytics:**
- Token usage
- Cost tracking
- Popular queries
- Response times

**Settings:**
- Configuration editor
- API key management
- Backup/restore
- System logs

### Admin API

```bash
# Get system status
curl http://localhost:5000/api/status

# List users
curl http://localhost:5000/api/users

# Get usage stats
curl http://localhost:5000/api/analytics/usage?period=7d
```

---

## CLI Reference

### Basic Commands

```bash
# Start interactive mode
familiar

# Start specific channel
familiar --telegram
familiar --discord
familiar --dashboard

# Run single command
familiar --command "What's on my calendar today?"

# Specify config
familiar --config /path/to/config.yaml

# Verbose output
familiar --verbose
familiar -v

# Debug mode
familiar --debug
```

### Management Commands

```bash
# User management
familiar --add-user --username NAME --email EMAIL
familiar --list-users
familiar --remove-user USERNAME

# Configuration
familiar --check-config
familiar --show-config

# Maintenance
familiar --self-test
familiar --backup
familiar --restore BACKUP_FILE

# Compliance
familiar --compliance-check hipaa

# Service
familiar --daemon          # Run as daemon
familiar --stop            # Stop daemon
familiar --status          # Check status
```

### Interactive Commands

Once in interactive mode:

| Command | Description |
|---------|-------------|
| `/help` | Show help |
| `/skills` | List skills |
| `/skill <name>` | Skill info |
| `/memory` | Memory status |
| `/memory search <q>` | Search memory |
| `/history` | Conversation history |
| `/clear` | Clear history |
| `/export` | Export conversation |
| `/settings` | View settings |
| `/set <key> <val>` | Change setting |
| `/user` | User info |
| `/trust` | Trust level |
| `/cost` | Usage costs |
| `/quit` | Exit |

---

## Troubleshooting

### Common Issues

#### "Module not found" errors

```bash
# Ensure venv is activated
source ~/.familiar/venv/bin/activate

# Reinstall dependencies
pip install -r ~/.familiar/app/requirements.txt
```

#### "API key invalid"

```bash
# Check key is set
echo $ANTHROPIC_API_KEY

# Check .env file
cat ~/.familiar/.env

# Test key
curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "content-type: application/json" \
  -d '{"model":"claude-sonnet-4-6","max_tokens":10,"messages":[{"role":"user","content":"Hi"}]}'
```

#### Telegram bot not responding

1. Check token is correct
2. Verify bot is not blocked
3. Check allowed users list
4. View logs: `journalctl -u familiar -f`

#### High memory usage

```yaml
# Reduce conversation history
agent:
  max_conversation_history: 20

# Disable unused skills
skills:
  browser:
    enabled: false
```

#### Slow responses

```yaml
# Use faster model
llm:
  default_provider: ollama
  ollama_model: phi3  # Smaller, faster

# Or use Haiku for simple queries
llm:
  anthropic_model: claude-haiku-4-5-20251001
```

### Viewing Logs

```bash
# Systemd logs
journalctl -u familiar -f

# Application logs
tail -f ~/.familiar/logs/familiar.log

# Debug level
familiar --debug
```

### Resetting Familiar

For a full reset guide including all file locations, clean slate scripts,
and troubleshooting stale state issues, see the
[Uninstall & Clean Slate](#uninstall--clean-slate) section at the end of
this guide.

Quick reference:

```bash
# Config only (keeps all data)
rm ~/.familiar/config.yaml

# Full data reset (back up first)
cp -r ~/.familiar ~/.familiar.bak.$(date +%Y%m%d)
rm -rf ~/.familiar/

# Or use the clean slate script
./scripts/familiar-clean-slate.sh              # full reset
./scripts/familiar-clean-slate.sh --keep-config  # keep config.yaml
./scripts/familiar-clean-slate.sh --data-only    # data only
```

### Getting Help

1. Check this guide
2. View logs for errors
3. Run `familiar --self-test`
4. GitHub Issues: github.com/familiar-ai/familiar/issues

---

## API Reference

### Python API

```python
from familiar import Agent, Config

# Initialize
config = Config.load("~/.familiar/config.yaml")
agent = Agent(config)

# Send message
response = await agent.chat("What's on my calendar?")
print(response.text)

# Use specific skill
result = await agent.invoke_skill("calendar", "list_events", {
    "start": "2025-01-14",
    "end": "2025-01-15"
})

# Access memory
agent.memory.store("key", "value")
value = agent.memory.retrieve("key")
```

### REST API

When dashboard is running:

```bash
# Chat endpoint
curl -X POST http://localhost:5000/api/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "Hello"}'

# Skill invocation
curl -X POST http://localhost:5000/api/skills/calendar/list_events \
  -H "Content-Type: application/json" \
  -d '{"start": "2025-01-14"}'

# Memory
curl http://localhost:5000/api/memory/search?q=wifi
```

### Webhook Integration

```yaml
skills:
  webapi:
    webhooks:
      - path: /webhook/github
        secret: "your_webhook_secret"
        action: |
          New commit to {repository}: {commit_message}
          
      - path: /webhook/stripe
        action: |
          Payment received: ${amount} from {customer_email}
```

---

## Appendix

### Keyboard Shortcuts (CLI)

| Key | Action |
|-----|--------|
| `Ctrl+C` | Cancel current input |
| `Ctrl+D` | Exit |
| `Ctrl+L` | Clear screen |
| `↑/↓` | History navigation |
| `Tab` | Auto-complete |

### Configuration Defaults

Full default configuration:
`~/.familiar/app/config.sample.yaml`

### Security Best Practices

1. Use strong encryption key
2. Enable MFA for admin users
3. Restrict network access
4. Regular backups
5. Monitor audit logs
6. Keep software updated
7. Use HIPAA mode for sensitive data

### Performance Tuning

For Raspberry Pi:

```yaml
# Use efficient model
llm:
  default_provider: ollama
  ollama_model: phi3

# Reduce memory
agent:
  max_conversation_history: 10
  
# Disable unused features
skills:
  browser:
    enabled: false
```

---

## Uninstall & Clean Slate

This section covers how to fully remove Familiar and all data it has written to
disk. Use this when troubleshooting installation issues, starting fresh for
testing, or permanently removing Familiar from a system.

> **Why this matters:** Familiar writes data across several locations beyond the
> install directory — credentials, OAuth tokens, encryption keys, conversation
> history, and cached models. Deleting only the install directory leaves these
> behind, which can cause confusing bugs on reinstall (stale tokens being picked
> up, mismatched encryption keys, old config overriding new settings).
> A clean slate means removing all of them.

---

### What Familiar Writes to Disk

Understanding the full file map prevents surprises during testing:

**Core data directory — `~/.familiar/`**

This is the primary location for everything Familiar stores at runtime.

```
~/.familiar/
├── config.yaml              # Main configuration
├── .env                     # API keys and environment variables
├── data/
│   ├── memory.json          # Conversation memory
│   ├── history.json         # Full conversation history
│   ├── scheduled_tasks.json # Scheduled tasks
│   ├── audit.db             # Audit log (SQLite)
│   ├── rbac.json            # Role-based access control rules
│   ├── contacts.json        # Contact list (meetings skill)
│   ├── meetings.json        # Meeting records
│   ├── email_triage.json    # Email triage state
│   ├── tasks.json           # Task list (tasks/proactive skills)
│   ├── nonprofit.json       # Nonprofit skill data
│   ├── .encryption_salt     # Encryption key derivation salt
│   ├── google_token.json            # Google OAuth — Calendar
│   ├── google_token_drive.json      # Google OAuth — Drive
│   ├── google_token_contacts.json   # Google OAuth — Contacts
│   ├── google_token_gmail.json      # Google OAuth — Gmail/Triage
│   ├── knowledge/           # Knowledge base collections + embeddings
│   ├── mesh/                # Mesh peer registry and shared memories
│   ├── browser/             # Browser skill cache and archive
│   ├── browser_cookies/     # Browser session cookies
│   ├── screenshots/         # Screenshots taken by browser skill
│   ├── downloads/           # Files downloaded by browser skill
│   ├── calendar/            # Cached calendar data
│   ├── gdrive/              # Cached Drive data
│   ├── triggers/            # Automation triggers and webhooks
│   ├── voice/               # Voice recordings and transcripts
│   │   └── piper_models/    # Downloaded TTS voice models (large)
│   ├── models/              # Downloaded embedding models
│   └── plans/               # Planner skill plan files
├── secure/                  # Mesh encryption keys (X3DH/Double Ratchet)
│   ├── keys.json            # Long-term identity and prekey pairs
│   └── sessions.json        # Active Double Ratchet sessions
├── backups/                 # Backups created by the backup skill
├── skills/                  # User-installed custom skills
├── plugins/                 # Plugin directory
├── logs/                    # Application logs
├── traces.jsonl             # OpenTelemetry traces (if enabled)
└── audit.jsonl              # Audit log (flat file, if HIPAA mode)
```

**Install directory (set during installation)**

By default `~/familiar/` or wherever you extracted the zip. Contains the
application code and virtualenv:

```
~/familiar/
├── venv/          # Python virtual environment (~500MB with dependencies)
├── familiar/      # Application source
├── run.sh
└── config.sample.yaml
```

**In-project `.env` file**

If you ran the onboarding wizard, a `.env` may also exist inside the install
directory itself alongside the source code.

---

### Quick Reference: Levels of Reset

Choose the level that matches what you need:

| Level | What it removes | Use when |
|-------|----------------|----------|
| **Config only** | `config.yaml` | Settings got corrupted or you want defaults |
| **Credentials** | OAuth tokens, `.env`, API keys | Changing accounts or providers |
| **User data** | Memory, history, tasks, conversations | Starting a fresh context |
| **Full data** | All of `~/.familiar/` | Clean reinstall, switching environments |
| **Complete** | Data + install directory + venv | Removing Familiar entirely |

---

### Level 1 — Reset Configuration Only

Config got into a bad state but you want to keep your data:

```bash
# Back up first
cp ~/.familiar/config.yaml ~/.familiar/config.yaml.bak

# Remove config — Familiar regenerates defaults on next run
rm ~/.familiar/config.yaml

# If you also have a .env in the install directory
rm ~/familiar/familiar/.env   # adjust path to your install location
```

---

### Level 2 — Reset Credentials and OAuth Tokens

Use this when switching Google accounts, revoking API keys, or debugging
authentication failures. Leaves your conversation history and data intact.

```bash
# Google OAuth tokens (all services)
rm -f ~/.familiar/data/google_token.json
rm -f ~/.familiar/data/google_token_drive.json
rm -f ~/.familiar/data/google_token_contacts.json
rm -f ~/.familiar/data/google_token_gmail.json

# API keys / environment variables
rm -f ~/.familiar/.env
rm -f ~/familiar/familiar/.env   # adjust path to your install location

# Encryption salt — only remove if also removing encrypted data files
# Removing this without removing the encrypted data will make data unreadable
# rm -f ~/.familiar/data/.encryption_salt
```

> **Note on the encryption salt:** The salt is used to derive the encryption key
> from your password. Deleting it without deleting the encrypted data files will
> make those files permanently unreadable. Only remove the salt as part of a
> full data reset.

---

### Level 3 — Reset User Data (Keep Config and Credentials)

Start with a fresh memory, history, and task state without reconfiguring:

```bash
# Core conversation state
rm -f ~/.familiar/data/memory.json
rm -f ~/.familiar/data/history.json
rm -f ~/.familiar/data/scheduled_tasks.json

# Skill data
rm -f ~/.familiar/data/tasks.json
rm -f ~/.familiar/data/contacts.json
rm -f ~/.familiar/data/meetings.json
rm -f ~/.familiar/data/email_triage.json
rm -f ~/.familiar/data/nonprofit.json
rm -f ~/.familiar/data/rbac.json

# Cached external data
rm -rf ~/.familiar/data/calendar/
rm -rf ~/.familiar/data/gdrive/
rm -rf ~/.familiar/data/knowledge/

# Plans and triggers
rm -rf ~/.familiar/data/plans/
rm -rf ~/.familiar/data/triggers/

# Audit log (keeps compliance trail, remove only intentionally)
# rm -f ~/.familiar/data/audit.db
# rm -f ~/.familiar/audit.jsonl
```

---

### Level 4 — Full Data Reset

Removes everything in `~/.familiar/` — all data, credentials, keys, and config.
The install directory and virtualenv are preserved so you can run immediately
after without reinstalling.

```bash
# Back up if you want to preserve anything
cp -r ~/.familiar ~/.familiar.bak.$(date +%Y%m%d)

# Full removal
rm -rf ~/.familiar/

# Familiar will recreate the directory structure on next run
# You will need to reconfigure (API keys, channels, etc.)
```

---

### Level 5 — Complete Uninstall

Removes everything: data, install directory, and virtualenv. Use this for a
completely clean reinstall or to remove Familiar from the system entirely.

```bash
# 1. Stop Familiar if running
pkill -f "familiar" 2>/dev/null || true

# 2. Remove all user data
rm -rf ~/.familiar/

# 3. Remove install directory (adjust path to your install location)
rm -rf ~/familiar/

# 4. Remove any systemd service if you set one up
sudo systemctl stop familiar 2>/dev/null || true
sudo systemctl disable familiar 2>/dev/null || true
sudo rm -f /etc/systemd/system/familiar.service
sudo systemctl daemon-reload

# 5. (Optional) Remove Ollama models if installed for Familiar
# Ollama stores models in ~/.ollama/models/ — only remove if
# you don't use Ollama for anything else
# ollama rm llama3.2
# ollama rm mistral

# 6. (Optional) Remove Proton Mail Bridge if installed for Familiar
# sudo systemctl stop protonmail-bridge 2>/dev/null || true
# sudo systemctl disable protonmail-bridge 2>/dev/null || true
# sudo rm -f /etc/systemd/system/protonmail-bridge.service
# sudo apt remove protonmail-bridge   # or however you installed it
```

---

### Clean Slate Script

For testing and development, this script performs a full data reset while
preserving the install directory and virtualenv. Run it between test sessions
to guarantee a clean starting state.

```bash
#!/usr/bin/env bash
# familiar-clean-slate.sh
# Resets all Familiar data for a clean test run.
# Does NOT remove the install directory or virtualenv.
#
# Usage: bash familiar-clean-slate.sh
#        bash familiar-clean-slate.sh --keep-config   # preserves config.yaml

set -e
KEEP_CONFIG=false
[[ "$1" == "--keep-config" ]] && KEEP_CONFIG=true

echo "🧹 Familiar Clean Slate"
echo "========================"
echo ""

# Stop Familiar if running
if pgrep -f "familiar" > /dev/null 2>&1; then
    echo "Stopping Familiar..."
    pkill -f "familiar" 2>/dev/null || true
    sleep 1
fi

# Back up config if keeping it
if $KEEP_CONFIG && [ -f ~/.familiar/config.yaml ]; then
    cp ~/.familiar/config.yaml /tmp/familiar_config_backup.yaml
    echo "✓ Config backed up to /tmp/familiar_config_backup.yaml"
fi

# Remove data directory
if [ -d ~/.familiar ]; then
    rm -rf ~/.familiar
    echo "✓ Removed ~/.familiar/"
fi

# Restore config if requested
if $KEEP_CONFIG && [ -f /tmp/familiar_config_backup.yaml ]; then
    mkdir -p ~/.familiar
    cp /tmp/familiar_config_backup.yaml ~/.familiar/config.yaml
    echo "✓ Config restored"
fi

echo ""
echo "✅ Clean slate ready."
echo "   Familiar will recreate all directories on next run."
echo "   You will need to reconnect channels and re-enter API keys."
```

Save this as `scripts/familiar-clean-slate.sh` in your install directory and
make it executable:

```bash
chmod +x scripts/familiar-clean-slate.sh

# Full reset
./scripts/familiar-clean-slate.sh

# Reset data but keep config.yaml
./scripts/familiar-clean-slate.sh --keep-config
```

---

### Verifying a Clean State

After any reset, confirm nothing was left behind:

```bash
# Should return "not found" or be empty
ls ~/.familiar/ 2>/dev/null && echo "Directory exists" || echo "✓ ~/.familiar not found"

# Check for any Familiar processes still running
pgrep -a -f familiar && echo "⚠ Familiar still running" || echo "✓ No Familiar processes"

# Check for leftover .env in common locations
find ~ -maxdepth 4 -name ".env" -path "*/familiar*" 2>/dev/null

# Check for leftover OAuth tokens
find ~ -maxdepth 4 -name "google_token*.json" 2>/dev/null
```

---

### Troubleshooting Stale State Issues

Common symptoms of leftover files causing bugs on reinstall:

**"Authentication failed" immediately after fresh install**
Old OAuth tokens in `~/.familiar/data/google_token*.json` are being picked up.
Remove them with Level 2 reset.

**Conversations from a previous install appearing**
`~/.familiar/data/history.json` and `memory.json` were not removed.
Run Level 3 reset.

**"Decryption failed" or garbled data on startup**
The encryption salt in `~/.familiar/data/.encryption_salt` doesn't match the
password being used, or encrypted data files exist from a different key.
Run Level 4 reset — there is no way to recover this data without the original
password and salt.

**Config changes not taking effect**
A `config.yaml` from a previous install is being loaded. Check both
`~/.familiar/config.yaml` and the `.env` file in your install directory.

**Mesh connections failing after reinstall**
The identity keys in `~/.familiar/secure/` are from the old install.
Remote nodes have the old public keys cached. Remove `~/.familiar/secure/`
and restart — remote nodes will re-handshake on next connection.

**Skills behaving unexpectedly**
Stale skill data in `~/.familiar/data/` (tasks, triggers, knowledge base).
Run Level 3 reset targeting the specific skill's data files.

---

*Familiar v1.3.9 — The Mother of Monsters*

*Signal-grade encryption • HIPAA-ready • Self-hosted AI*

*Built for humanity, by humans.*
