# Troubleshooting Guide

Common issues and solutions for SOPHIAClaw community edition.

---

## Gateway Issues

### "Gateway not running" or connection refused

**Symptoms:**

- `sophiaclaw agent` fails with "connection refused"
- CLI cannot connect to local gateway

**Solutions:**

```bash
# 1. Start the gateway
sophiaclaw gateway start

# 2. If already running, restart it
sophiaclaw gateway restart

# 3. Run in verbose mode to see errors
sophiaclaw gateway --port 37521 --verbose

# 4. Check if port is already in use
ss -ltnp | grep 37521
# or on macOS
lsof -i :37521
```

**Kill zombie gateway:**

```bash
pkill -f sophiaclaw-gateway
sophiaclaw gateway start
```

---

### Gateway crashes on startup

**Check logs:**

```bash
# View recent logs
sophiaclaw logs tail --lines 100

# Check for specific errors
sophiaclaw doctor
```

**Common causes:**

- Port already in use (see above)
- Invalid configuration (`~/.sophiaclaw/sophiaclaw.json`)
- Missing Node.js version (requires 22+)
- Corrupted session files

**Fix corrupt config:**

```bash
# Backup existing config
cp ~/.sophiaclaw/sophiaclaw.json ~/.sophiaclaw/sophiaclaw.json.backup

# Run doctor to repair
sophiaclaw doctor --repair
```

---

### systemd linger (Linux only)

Service stops after logout:

```bash
# Enable lingering for your user
sudo loginctl enable-linger $USER
```

---

## Credential Issues

### "Invalid API key" or authentication failures

**Symptoms:**

- Model API calls fail with 401/403 errors
- `sophiaclaw doctor` shows auth warnings

**Solutions:**

```bash
# 1. Verify credentials exist
ls -la ~/.sophiaclaw/credentials/

# 2. Check credential format (should be encrypted or valid JSON)
cat ~/.sophiaclaw/credentials/*.json

# 3. Re-enter credentials
sophiaclaw config set <provider>.apiKey YOUR_KEY

# 4. For OAuth tokens, refresh
sophiaclaw auth refresh
```

**Credential encryption:**

If using encrypted credentials:

```bash
# Ensure keychain access is available
# macOS: Keychain should be unlocked
# Linux: Secret Service API should be running (gnome-keyring-daemon)

# Re-encrypt if needed
sophiaclaw security encrypt-credentials
```

---

### "Cannot read credentials" permission errors

**Fix permissions:**

```bash
# Linux/macOS
chmod 600 ~/.sophiaclaw/credentials/*.json
chmod 700 ~/.sophiaclaw/credentials/
```

---

## Model Issues

### "Model not available" or model routing failures

**Symptoms:**

- `sophiaclaw agent --model <name>` fails
- Default model routing not working

**Solutions:**

```bash
# 1. List available models
sophiaclaw models list

# 2. Test connectivity
sophiaclaw doctor

# 3. Check OpenRouter/Anthropic/etc. credentials
sophiaclaw config get openrouter.apiKey

# 4. Verify model is not rate-limited
sophiaclaw usage today
```

**Anthropic OAuth token expired:**

```bash
# Claude Code users
claude setup-token

# Or paste fresh token
sophiaclaw config set anthropic.apiKey YOUR_TOKEN
```

---

### High API costs / budget exceeded

**Check spending:**

```bash
sophiaclaw usage today
sophiaclaw usage month
```

**Set limits:**

```bash
sophiaclaw config set daily_budget_limit 10
sophiaclaw config set monthly_budget_limit 200
```

**Cost-optimized routing:**

Ensure you're using the default tiered model routing (Gemini Flash for simple queries, Claude for complex).

---

## Channel Issues

### "Channel not responding"

**Symptoms:**

- Telegram/Discord/Slack bot not responding to messages
- `sophiaclaw channel list` shows issues

**Solutions:**

```bash
# 1. Check channel status
sophiaclaw channel list

# 2. Verify specific channel
sophiaclaw channel verify <channel-name>

# 3. Test gateway connectivity
sophiaclaw channels status --probe

# 4. Re-add channel if needed
sophiaclaw channel remove <channel-name>
sophiaclaw channel add <type> --bot-token YOUR_TOKEN
```

**Telegram specific:**

- Bot token must start with digits:letters format
- Bot must be added to group with proper permissions
- Privacy mode may be enabled in BotFather

**Discord specific:**

- Bot needs Application ID and Bot Token
- Must have Send Messages permission in channel
- Slash commands must be registered (wait up to 1 hour for global registration)

---

### iMessage not syncing (macOS)

**Symptoms:**

- iMessage channel shows but no messages received

**Solutions:**

1. Ensure Messages app is running
2. Check Accessibility permissions (System Settings → Privacy)
3. Restart Messages app
4. Re-run `sophiaclaw channel add imessage`

---

## Log Issues

### "Cannot access logs" or log corruption

**Check log location:**

```bash
# List logs
ls -la ~/.sophiaclaw/agents/*/sessions/

# View recent entries
sophiaclaw logs tail --lines 50
```

**Log integrity verification:**

```bash
# Verify log hashes
sophiaclaw security verify-logs
```

**Compress old logs:**

```bash
sophiaclaw logs compress
```

**Cleanup old logs:**

```bash
sophiaclaw logs cleanup
```

---

### Large log storage

**Check storage:**

```bash
sophiaclaw logs stats
```

**Set retention policy:**

```bash
sophiaclaw logs retention --keep-days 30 --compress-after 7
```

---

## Permission Issues

### "Permission denied" errors

**Check directory permissions:**

```bash
# State directory
ls -la ~/.sophiaclaw/

# Should be 700 (owner only)
chmod 700 ~/.sophiaclaw/
chmod 600 ~/.sophiaclaw/sophiaclaw.json
```

**macOS specific:**

- Accessibility permissions: System Settings → Privacy → Accessibility
- Automation permissions: System Settings → Privacy → Automation
- Files and Folders: System Settings → Privacy → Files and Folders

**Linux specific:**

- Ensure user has read/write access to `~/.sophiaclaw/`
- Check SELinux/AppArmor if used

---

## Session Issues

### "Session not found" or history missing

**Check session persistence:**

```bash
# List sessions
sophiaclaw sessions list

# Verify session files exist
ls -la ~/.sophiaclaw/agents/<agentId>/sessions/
```

**Session janitor not running:**

Nightly context resets may not have run. Manually trigger:

```bash
sophiaclaw sessions summary --latest
```

---

### Multiple state directories

**Symptoms:**

- History split between installs
- Missing sessions

**Check for multiple state dirs:**

```bash
# Default location
ls -la ~/.sophiaclaw/

# Check if SOPHIACLAW_STATE_DIR is set
echo $SOPHIACLAW_STATE_DIR
```

**Fix:**
Consolidate to one location or update `SOPHIACLAW_STATE_DIR` environment variable.

---

## Resource Issues

### High memory usage

**Check resource usage:**

```bash
sophiaclaw status --resources
```

**Default thresholds:**

- Warning: 80% memory usage
- Critical: 95% memory usage

**Actions:**

- Restart gateway: `sophiaclaw gateway restart`
- Clear session cache if large
- Reduce concurrent sessions

---

### "Too many open files" errors

**Check file descriptor usage:**

```bash
lsof -p $(pgrep -f sophiaclaw) | wc -l
```

**Increase limit:**

```bash
# Temporary (current session)
ulimit -n 65536

# Permanent (Linux, add to /etc/security/limits.conf)
your-username soft nofile 65536
your-username hard nofile 65536
```

---

## Doctor Command

### Run health checks

```bash
# Basic health check
sophiaclaw doctor

# Auto-repair issues
sophiaclaw doctor --repair

# Deep scan (check for extra gateway installs)
sophiaclaw doctor --deep

# Non-interactive mode (for scripts)
sophiaclaw doctor --non-interactive
```

**Doctor checks:**

- ✅ Gateway health + restart if needed
- ✅ Config normalization (legacy migrations)
- ✅ State dir permissions + integrity
- ✅ Model auth (OAuth expiry, can refresh expiring tokens)
- ✅ Channel status warnings
- ✅ Sandbox image (if enabled)
- ✅ Service config (launchd/systemd/schtasks)
- ✅ Port collision diagnostics
- ✅ Node/Bun version warnings

---

## macOS App Issues

### Menubar app not starting

**Check launch agents:**

```bash
launchctl print gui/$UID | grep sophiaclaw
```

**Restart app:**

- Quit from menubar → Quit SophiaClaw
- Relaunch from Applications folder

**Check logs:**

```bash
# Use unified log query
./scripts/clawlog.sh --follow
```

---

### App shows "Gateway not connected"

**Verify gateway running:**

```bash
ss -ltnp | grep 37521
# or
lsof -i :37521
```

**Restart gateway via app:**

1. Click SophiaClaw menubar icon
2. Settings → Gateway → Restart

---

## Getting More Help

### Check documentation

- [Getting Started](/docs/guides/GETTING_STARTED.md)
- [Security Overview](/docs/security.md)
- [Architecture](/docs/architecture.md)
- [Gateway Doctor](/docs/gateway/doctor.md)

### Run diagnostics

```bash
# Full system health
sophiaclaw doctor

# Export logs for support
sophiaclaw logs export --last 24h --output /tmp/sophiaclaw-logs.zip
```

### Community support

- **Discord:** [Join community](https://discord.gg/sophiaclaw)
- **GitHub Issues:** https://github.com/sophiaclaw/sophiaclaw/issues
- **Documentation:** https://docs.sophiaclaw.ai

---
