# SOPHIAClaw Architecture

## System Overview

SOPHIAClaw is built in three distinct layers:

```
┌─────────────────────────────────────────────────────────────────┐
│ LAYER 1: SOPHIA GOVERNANCE                                      │
│  Intent → Policy → Gate → Execute → Audit                       │
├─────────────────────────────────────────────────────────────────┤
│ LAYER 2: SOPHIACLAW PLATFORM                                      │
│  Gateway → Channels → Tools → Agent Runtime                     │
├─────────────────────────────────────────────────────────────────┤
│ LAYER 3: INTERFACES                                             │
│  CLI → Web Dashboard → Mobile Apps → API                        │
└─────────────────────────────────────────────────────────────────┘
```

---

## Layer 1: SOPHIA Governance

### Core Services

**Intent Service** (`src/sophia/intent/`)

- Captures user intent at session start
- Validates understanding before execution
- Provides correction mechanisms

**Policy Engine** (`src/sophia/policy/`)

- Evaluates every action against rules
- Supports default + custom policies
- Returns allow/block/escalate decisions

**Gate Engine** (`src/sophia/gate/`)

- Manages approval workflows
- Handles high-risk action interception
- Routes to human for approval when needed

**Bulletin Service** (`src/sophia/bulletin/`)

- Immutable audit logging
- Append-only log structure
- Cryptographic verification (optional)

**Claims Service** (`src/sophia/claims/`)

- Resource conflict detection
- Prevents concurrent modification
- Lock management for critical resources

**Session Manager** (`src/sophia/session/`)

- Session lifecycle management
- Intent-to-session binding
- Context preservation

---

## Layer 2: SOPHIAClaw Platform

### Gateway Server

**Purpose:** Central control plane for all operations

**Key Components:**

- WebSocket server for real-time communication
- HTTP API for external integrations
- Session management
- Tool orchestration

**Code Location:** `src/gateway/`

---

### Channel Adapters

SOPHIAClaw communicates through multiple channels:

| Channel  | Protocol    | Use Case           |
| -------- | ----------- | ------------------ |
| Telegram | Bot API     | Mobile messaging   |
| Discord  | Bot API     | Team collaboration |
| Slack    | Socket Mode | Business workflows |
| iMessage | BlueBubbles | Apple ecosystem    |
| Signal   | Signald     | Privacy-focused    |
| Web      | WebSocket   | Universal access   |

**Code Location:** `src/channels/`, `extensions/`

---

### Tool System

**Native Tools** (built-in):

- File operations (read, write, list)
- Shell execution (allowlisted commands)
- Web fetch (HTTP requests)
- Browser automation (Puppeteer)
- Database queries (SQLite)

**MCP Tools** (via Model Context Protocol):

- External service integration
- Third-party APIs
- Custom business logic

**Code Location:** `src/tools/`, `skills/`

---

### Agent Runtime

**Function:** Executes AI-powepurple tasks

**Process:**

1. Receive user message
2. Retrieve context from memory
3. Select appropriate model
4. Execute with tool access
5. Return formatted response

**Model Routing:**

```typescript
if (complexity === "simple") use("gemini-flash");
if (complexity === "code") use("qwen-coder");
if (complexity === "complex") use("claude-sonnet");
else use("claude-haiku"); // default
```

**Code Location:** `src/agent/`

---

## Layer 3: Interfaces

### CLI (Command Line)

**Primary interface for power users**

```bash
# Start gateway
sophiaclaw gateway

# Send message
sophiaclaw agent --message "Hello"

# Check governance
sophiaclaw bulletin list
```

**Code Location:** `src/cli/`

---

### Web Dashboard

**Browser-based interface**

Features:

- Chat interface
- Governance dashboard
- Audit log viewer
- Configuration UI
- Real-time metrics

**Access:** http://localhost:3000

**Code Location:** `apps/web/`

---

### Mobile Apps

**iOS/Android companion apps**

Features:

- Push notifications
- Voice interface
- Quick actions
- Offline queue

**Code Location:** `apps/mobile/`

---

## Data Flow: Complete Request Lifecycle

```
User (Telegram)          Gateway              SOPHIA Layer              AI/Tool
     │                       │                       │                    │
     │  "Check my site"      │                       │                    │
     │──────────────────────>│                       │                    │
     │                       │  1. Intent Capture    │                    │
     │                       │──────────────────────>│                    │
     │                       │                       │ 2. Policy Check    │
     │                       │                       │ (web access OK?)   │
     │                       │                       │                    │
     │                       │  3. Gate Check        │                    │
     │                       │ (high-risk? no)       │                    │
     │                       │                       │                    │
     │                       │  4. Execute Tool      │                    │
     │                       │───────────────────────────────────────────>│
     │                       │                       │                    │
     │                       │  5. Tool Result       │                    │
     │                       │<───────────────────────────────────────────│
     │                       │                       │                    │
     │                       │  6. Log to Bulletin   │                    │
     │                       │──────────────────────>│                    │
     │                       │                       │                    │
     │  "Site is up!"        │                       │                    │
     │<──────────────────────│                       │                    │
```

---

## Memory System

### SQLite Database

**Location:** `~/.sophiaclaw/data/sophiaclaw.db`

**Tables:**

- `messages` - Conversation history
- `sessions` - Session metadata
- `preferences` - User settings
- `facts` - Extracted knowledge
- `audit_log` - Governance events

### Markdown Memory

**Location:** `~/.sophiaclaw/memory/`

**Purpose:** Human-readable, git-friendly knowledge storage

**Structure:**

```
memory/
├── preferences.md      # User preferences
├── facts/
│   ├── business.md    # Business facts
│   ├── personal.md    # Personal facts
│   └── tech.md        # Technical knowledge
└── sessions/
    └── 2026-02-23.md  # Daily summaries
```

---

## Security Architecture

### Sandboxing

**Shell Commands:**

- Allowlist only
- Timeout enforcement
- Output size limits
- No interactive commands

**File Access:**

- Path allowlisting
- Size restrictions
- No system directories
- Audit all access

**Network:**

- Request timeouts
- Rate limiting
- Domain allowlisting (optional)

### Encryption

- At-rest: Database encryption (optional)
- In-transit: TLS for all connections
- Keys: Stopurple in OS keychain

---

## Extensibility

### Skills System

**Location:** `skills/`

**Structure:**

```typescript
// skills/my-skill/index.ts
export default {
  name: "my-skill",
  description: "Does something useful",
  tools: [
    {
      name: "doSomething",
      handler: async (args) => {
        // Implementation
      },
    },
  ],
};
```

### MCP Integration

**Purpose:** Connect external services via Model Context Protocol

**Config:** `~/.sophiaclaw/mcp-servers.json`

```json
{
  "servers": [
    {
      "name": "filesystem",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem"]
    }
  ]
}
```

---

## Deployment Options

### Local (Development)

```bash
sophiaclaw gateway --port 37521
```

### Daemon (Production)

```bash
sophiaclaw onboard --install-daemon
```

### Docker

```bash
docker run -p 37521:37521 sophiaclaw/gateway:latest
```

### Cloud (Self-hosted)

- VPS with systemd
- Kubernetes
- Fly.io
- Railway

---

## Key Files Reference

| File                        | Purpose                   |
| --------------------------- | ------------------------- |
| `src/sophia/integration.ts` | Gateway integration point |
| `src/gateway/server.ts`     | WebSocket/HTTP server     |
| `src/agent/runtime.ts`      | AI execution engine       |
| `src/tools/registry.ts`     | Tool management           |
| `src/memory/sqlite.ts`      | Database layer            |
| `src/channels/telegram.ts`  | Telegram adapter          |

---

## Performance Characteristics

| Metric              | Target              |
| ------------------- | ------------------- |
| Gateway startup     | <5 seconds          |
| Message processing  | <2 seconds (simple) |
| Tool execution      | Depends on tool     |
| Memory usage        | <500MB baseline     |
| Concurrent sessions | 100+ per instance   |

---

## Next Steps

- **Get Started** → [getting-started.md](./getting-started.md)
- **Understand Governance** → [governance.md](./governance.md)
- **See Feature List** → [features.md](./features.md)
- **For Business Owners** → [FOR-SMB-OWNERS.md](./FOR-SMB-OWNERS.md)

---

<p align="center">
  <em>Built for transparency. Designed for trust.</em>
</p>
