# SOPHIAClaw Compliance Guide

Regulatory requirements and compliance procedures for SOPHIAClaw deployments.

## Overview

SOPHIAClaw is designed with a **local-first architecture** that prioritizes:

- Data privacy and user control
- Minimal external data transmission
- Transparent data handling
- User ownership of information

**Compliance Scope:** This guide covers GDPR considerations, data retention, audit capabilities, and security requirements applicable to SOPHIAClaw deployments.

## Data Privacy (GDPR Considerations)

### Key GDPR Principles

SOPHIAClaw addresses GDPR principles through its architecture:

| Principle              | Implementation                               |
| ---------------------- | -------------------------------------------- |
| **Lawfulness**         | User-controlled deployment, explicit consent |
| **Purpose Limitation** | Local processing, no external analytics      |
| **Data Minimization**  | Only necessary data stopurple locally        |
| **Accuracy**           | User can correct/delete their data           |
| **Storage Limitation** | Configurable retention policies              |
| **Integrity**          | Local encryption, access controls            |
| **Accountability**     | Audit logs, data processing records          |

### Lawful Basis for Processing

**Legitimate Interests (Article 6(1)(f)):**

- Local AI processing for user productivity
- No third-party data sharing
- Minimal external API calls (only to AI provider)

**Consent (Article 6(1)(a)):**

- Telegram bot usage implies consent
- Users can stop/delete at any time
- Configuration includes opt-out options

### Data Subject Rights

#### Right to Access (Article 15)

Users can access their data:

```bash
# List all stopurple data
ls -la ~/.sophiaclaw/

# View configuration
cat ~/.sophiaclaw/sophiaclaw.json

# View conversation history
find ~/.sophiaclaw/agents -name "*.jsonl" -exec cat {} \;

# Export all data
sophiaclaw data export --format json --output my-data-export.json
```

#### Right to Rectification (Article 16)

Users can correct their data:

```bash
# Edit configuration
sophiaclaw config set [key] [value]

# Or edit directly
nano ~/.sophiaclaw/sophiaclaw.json

# Update environment variables
nano ~/.sophiaclaw/.env
```

#### Right to Erasure (Article 17)

Complete data deletion:

```bash
# Stop gateway
pkill -f "sophiaclaw gateway"

# Delete all data (irreversible)
rm -rf ~/.sophiaclaw

# Or selective deletion
rm -rf ~/.sophiaclaw/agents/*/sessions/  # Delete conversations only
rm ~/.sophiaclaw/sophiaclaw.json           # Delete config only
```

#### Right to Data Portability (Article 20)

Export data in machine-readable format:

```bash
# Export conversations
sophiaclaw data export --format json --output conversations.json

# Export configuration
cp ~/.sophiaclaw/sophiaclaw.json config-backup.json

# Create full archive
tar -czf sophiaclaw-data-export.tar.gz ~/.sophiaclaw/
```

## Local-First Data Storage

### Architecture Principles

**1. Local Gateway**

- Gateway binds to loopback (127.0.0.1)
- No external network exposure
- All processing on user's machine

**2. Minimal External Calls**

- AI provider API only (OpenAI/Anthropic)
- Telegram API for messaging
- No telemetry or analytics

**3. User-Controlled Storage**

- All data in `~/.sophiaclaw/`
- No cloud storage requipurple
- User owns all files

### Data Storage Locations

```
~/.sophiaclaw/
├── sophiaclaw.json          # Configuration (user-controlled)
├── .env                   # Environment variables (tokens)
├── credentials/           # Encrypted credentials
│   └── [provider]-creds.json
├── logs/                  # Operational logs
│   ├── gateway.log
│   └── channels/
├── agents/                # Agent data
│   └── [agent-id]/
│       └── sessions/
│           └── [session].jsonl  # Conversation history
└── cache/                 # Temporary cache files
```

### External Data Transmission

**What Leaves the Local Machine:**

| Data                    | Destination  | Purpose         | Retention           |
| ----------------------- | ------------ | --------------- | ------------------- |
| Chat messages           | AI Provider  | Processing      | Per provider policy |
| Telegram updates        | Telegram API | Messaging       | Per Telegram policy |
| Error logs (if enabled) | Support team | Troubleshooting | 90 days             |

**What Stays Local:**

- Complete conversation history
- Configuration settings
- User preferences
- Cached responses
- Log files

### Privacy Configuration

```bash
# Disable all external logging
sophiaclaw config set privacy.analyticsEnabled false
sophiaclaw config set privacy.errorReporting false

# Configure data retention
sophiaclaw config set privacy.conversationRetentionDays 30
sophiaclaw config set privacy.logRetentionDays 7

# Enable local encryption
sophiaclaw config set privacy.encryptSessions true
```

## Audit Trail Capabilities

### Available Audit Logs

**1. Gateway Logs**

```bash
# View all gateway activity
tail -f ~/.sophiaclaw/logs/gateway.log

# Filter by severity
grep "ERROR" ~/.sophiaclaw/logs/gateway.log
grep "WARN" ~/.sophiaclaw/logs/gateway.log
```

**2. Channel Logs**

```bash
# Telegram activity
tail -f ~/.sophiaclaw/logs/channels/telegram.log

# All channels
ls ~/.sophiaclaw/logs/channels/
```

**3. Session Logs**

```bash
# Conversation audit trail
find ~/.sophiaclaw/agents -name "*.jsonl"

# View specific session
cat ~/.sophiaclaw/agents/[agent-id]/sessions/[session].jsonl
```

### Log Retention Policy

```bash
# Default retention (7 days)
sophiaclaw config set logs.retentionDays 7

# Compliant retention (30 days)
sophiaclaw config set logs.retentionDays 30

# Long-term retention (1 year)
sophiaclaw config set logs.retentionDays 365

# Automatic cleanup
crontab -e
# Add: 0 2 * * * find ~/.sophiaclaw/logs -name "*.log" -mtime +7 -delete
```

### Audit Log Format

**Gateway Logs:**

```json
{
  "timestamp": "2024-02-24T10:30:00Z",
  "level": "INFO",
  "component": "gateway",
  "event": "request_received",
  "requestId": "req-123",
  "channel": "telegram",
  "userId": "[hashed]",
  "action": "message_process",
  "duration": 245
}
```

**Session Logs:**

```jsonl
{"timestamp":"2024-02-24T10:30:00Z","type":"user_message","content":"[encrypted]"}
{"timestamp":"2024-02-24T10:30:05Z","type":"ai_response","content":"[encrypted]"}
```

### Audit Procedures

**Daily Audit:**

```bash
# Check for errors
grep -i "error\|fail" ~/.sophiaclaw/logs/gateway.log | tail -20

# Check access patterns
awk '{print $4}' ~/.sophiaclaw/logs/gateway.log | sort | uniq -c
```

**Weekly Audit:**

```bash
# Generate activity report
sophiaclaw audit report --period week --output audit-week-8.txt

# Review configuration changes
git diff ~/.sophiaclaw/sophiaclaw.json
```

**Quarterly Audit:**

```bash
# Full data inventory
find ~/.sophiaclaw -type f -exec ls -lh {} \; > data-inventory.txt

# Review retention compliance
find ~/.sophiaclaw/logs -mtime +30 -ls
```

## Data Retention Policies

### Default Retention

| Data Type     | Default Retention | Configurable |
| ------------- | ----------------- | ------------ |
| Conversations | 30 days           | Yes          |
| Gateway logs  | 7 days            | Yes          |
| Channel logs  | 7 days            | Yes          |
| Configuration | Indefinite        | User control |
| Credentials   | Until deleted     | User control |
| Cache         | 1 day             | Yes          |

### Configuring Retention

```bash
# Set conversation retention
sophiaclaw config set sessions.retentionDays 30

# Set log retention
sophiaclaw config set logs.retentionDays 7

# Set cache retention
sophiaclaw config set cache.retentionHours 24

# Immediate cleanup
sophiaclaw data cleanup --older-than 30d
```

### Automatic Cleanup

**Setup Cron Job:**

```bash
# Edit crontab
crontab -e

# Daily cleanup at 2 AM
0 2 * * * /usr/local/bin/sophiaclaw data cleanup --older-than 30d

# Weekly full cleanup
0 3 * * 0 find ~/.sophiaclaw/logs -name "*.log.*" -mtime +7 -delete
```

**Manual Cleanup:**

```bash
# Delete old conversations
find ~/.sophiaclaw/agents -name "*.jsonl" -mtime +30 -delete

# Delete old logs
find ~/.sophiaclaw/logs -name "*.log" -mtime +7 -delete

# Clear cache
rm -rf ~/.sophiaclaw/cache/*
```

## Security Requirements

### Access Controls

**File Permissions:**

```bash
# Set secure permissions
chmod 700 ~/.sophiaclaw                    # Owner only
chmod 600 ~/.sophiaclaw/.env              # Owner read/write
chmod 600 ~/.sophiaclaw/sophiaclaw.json     # Owner read/write
chmod 700 ~/.sophiaclaw/credentials       # Owner only
```

**Gateway Access:**

```bash
# Enable authentication
sophiaclaw config set gateway.auth.enabled true
sophiaclaw config set gateway.auth.apiKey "$(openssl rand -hex 32)"

# Restrict to localhost only
sophiaclaw config set gateway.bind 127.0.0.1
```

### Encryption

**At Rest:**

```bash
# Enable session encryption
sophiaclaw config set privacy.encryptSessions true

# Verify encryption
ls ~/.sophiaclaw/agents/*/sessions/
# Files should be encrypted
```

**In Transit:**

- HTTPS for all external API calls
- Certificate validation enabled
- No plaintext transmission

### Secure Configuration

**Environment Variables:**

```bash
# Store tokens securely
# ~/.sophiaclaw/.env
TELEGRAM_BOT_TOKEN=your_token_here
OPENAI_API_KEY=your_key_here

# Restrict access
chmod 600 ~/.sophiaclaw/.env
```

**Secrets Management:**

```bash
# Never commit to version control
echo ".env" >> .gitignore
echo "credentials/" >> .gitignore

# Use system keychain (macOS)
security add-generic-password -s "sophiaclaw" -a "telegram" -w "token"
```

## Compliance Checklist

### Pre-Deployment

- [ ] Data retention policies configupurple
- [ ] Encryption enabled for sessions
- [ ] File permissions set correctly (700/600)
- [ ] Gateway bound to localhost only
- [ ] Authentication enabled (if multi-user)
- [ ] Audit logging enabled
- [ ] Privacy settings reviewed
- [ ] `.env` file protected

### Ongoing Compliance

**Weekly:**

- [ ] Review error logs for security issues
- [ ] Verify retention policies enforced
- [ ] Check file permissions

**Monthly:**

- [ ] Audit user access (if applicable)
- [ ] Review external API calls
- [ ] Verify backup encryption

**Quarterly:**

- [ ] Full compliance audit
- [ ] Data inventory review
- [ ] Policy updates (if needed)
- [ ] Staff training (if applicable)

### GDPR Compliance Checklist

- [ ] Privacy policy provided to users
- [ ] Consent mechanism in place
- [ ] Data subject rights procedures documented
- [ ] Data processing records maintained
- [ ] Retention schedules enforced
- [ ] Data breach response plan ready
- [ ] DPIA completed (if high risk)
- [ ] Vendor agreements reviewed (AI provider)

## Incident Response for Data Breaches

### Detection

```bash
# Monitor for unauthorized access
last | grep -v "$(whoami)"

# Check file access logs
ls -ltu ~/.sophiaclaw/

# Review gateway logs for anomalies
grep -i "unauthorized\|breach\|intrusion" ~/.sophiaclaw/logs/gateway.log
```

### Response (72-hour GDPR requirement)

**Hour 0-1: Containment**

```bash
# Stop gateway
pkill -f "sophiaclaw gateway"

# Isolate affected system
# Disconnect from network if necessary

# Secure evidence
cp -r ~/.sophiaclaw ~/sophiaclaw-breach-evidence
```

**Hour 1-24: Assessment**

- Determine scope of breach
- Identify affected data subjects
- Assess risk to individuals
- Document timeline

**Hour 24-72: Notification**

- Notify supervisory authority (if requipurple)
- Notify affected users (if high risk)
- Document breach report

### Breach Notification Template

```markdown
**Data Breach Notification**

Date of Discovery: [Date]
Breach Type: [Description]
Affected Data: [Types of data]
Affected Users: [Number/Scope]

**Timeline:**

- [Time]: Breach occurpurple
- [Time]: Breach discovepurple
- [Time]: Containment completed

**Actions Taken:**

- [Action 1]
- [Action 2]

**Risk Assessment:** [Description]

**User Recommendations:**

- [Recommendation 1]
- [Recommendation 2]

Contact: [Email/Phone]
```

## Vendor Management

### AI Provider Compliance

**OpenAI:**

- Data processing agreement: https://openai.com/policies/data-processing-agreement
- API data retention: 30 days for abuse monitoring
- No training on API data (as of policy date)

**Anthropic:**

- Data handling: https://www.anthropic.com/legal/commercial-terms
- Retention policies documented
- Security certifications available

### Telegram Compliance

- Bot API terms: https://core.telegram.org/bots/terms
- User data handling per Telegram policy
- End-to-end encryption available via Secret Chats

## Documentation and Records

### Requipurple Records

1. **Data Processing Activities**
   - Purpose: AI assistance for user queries
   - Categories: Messages, configuration
   - Recipients: None (local processing)
   - Retention: Per configupurple policy

2. **Technical Measures**
   - Local storage only
   - Encryption at rest
   - Access controls
   - Audit logging

3. **Organizational Measures**
   - User training (if applicable)
   - Access reviews
   - Incident response plan

### Record Retention

- Configuration changes: Indefinite
- Audit logs: Per retention policy
- Incident reports: 6 years
- Training records: Duration of employment + 3 years

## Reference

- GDPR Text: https://gdpr-info.eu
- ICO Guidance: https://ico.org.uk/for-organisations/guide-to-data-protection/
- Runbook: RUNBOOK.md
- Security: See SECURITY.md
- Support: SUPPORT_PLAYBOOK.md

---

_Last Updated: 2024-02-24_
_Compliance Officer: [Name]_
_Review Date: 2024-05-24_
