# OCLAWMA Comprehensive Architecture Guide

**Version:** 0.2.0  
**Last Updated:** February 22, 2026  
**Audience:** Architects, Security Teams, Contributors

---

## Table of Contents

1. [Executive Overview](#1-executive-overview)
2. [System Architecture](#2-system-architecture)
3. [Component Deep Dive](#3-component-deep-dive)
4. [Data Flow Architecture](#4-data-flow-architecture)
5. [Security Architecture](#5-security-architecture)
6. [Deployment Patterns](#6-deployment-patterns)
7. [Performance Characteristics](#7-performance-characteristics)
8. [Integration Points](#8-integration-points)
9. [Operational Considerations](#9-operational-considerations)
10. [Future Roadmap](#10-future-roadmap)

---

## 1. Executive Overview

### 1.1 Purpose

OCLAWMA (OpenClaw Workflow Management Agent) is a Python-based AI agent runtime optimized for 8K context models. It provides a modular, extensible framework for building AI-powered automation workflows with strong safety controls.

### 1.2 Key Differentiators

| Feature | OCLAWMA | Typical Alternatives |
|---------|---------|---------------------|
| Context Optimization | 8K-first design | Generic context handling |
| Skill Ecosystem | Pip-installable skills | Monolithic or limited |
| Safety Controls | Configurable per-mode | Often hardcoded |
| Provider Flexibility | Multi-provider with fallback | Single provider |
| Lazy Loading | On-demand skill loading | Load all at startup |

### 1.3 Architecture Principles

1. **Security by Design** - Safety controls at every layer
2. **Modularity** - Plugin-based skill system
3. **Efficiency** - Lazy loading, context compression
4. **Resilience** - Automatic fallback between providers
5. **Observability** - Comprehensive logging and metrics

---

## 2. System Architecture

### 2.1 High-Level System Diagram

```
┌─────────────────────────────────────────────────────────────────────────────────┐
│                              EXTERNAL INTERFACES                                 │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐            │
│  │    CLI      │  │   Python    │  │   Config    │  │   Skills    │            │
│  │   (Click)   │  │    API      │  │    Files    │  │   (Entry    │            │
│  │             │  │             │  │             │  │   Points)   │            │
│  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘            │
└─────────┼────────────────┼────────────────┼────────────────┼───────────────────┘
          │                │                │                │
          └────────────────┴────────────────┴────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────────────────┐
│                           OCLAWMA CORE FRAMEWORK                                 │
│                                                                                  │
│  ┌───────────────────────────────────────────────────────────────────────────┐  │
│  │                         Session Management                                 │  │
│  │  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │  │
│  │  │   Session    │  │ Conversation │  │   Context    │  │   Safety     │  │  │
│  │  │   Runner     │  │   History    │  │   Budget     │  │   Checker    │  │  │
│  │  └──────────────┘  └──────────────┘  └──────────────┘  └──────────────┘  │  │
│  └───────────────────────────────────────────────────────────────────────────┘  │
│                                    │                                            │
│  ┌─────────────────────────────────┴──────────────────────────────────────────┐  │
│  │                              Tool System                                    │  │
│  │  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐        │  │
│  │  │   Read   │ │  Write   │ │   Exec   │ │  Skills  │ │  Custom  │        │  │
│  │  │   Tool   │ │   Tool   │ │   Tool   │ │  (Lazy)  │ │   Tools  │        │  │
│  │  └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘        │  │
│  └───────────────────────────────────────────────────────────────────────────┘  │
│                                    │                                            │
│  ┌─────────────────────────────────┴──────────────────────────────────────────┐  │
│  │                           Provider System                                   │  │
│  │  ┌────────────┐  ┌────────────┐  ┌────────────┐  ┌────────────┐           │  │
│  │  │   Ollama   │  │    Kimi    │  │   OpenAI   │  │  Fallback  │           │  │
│  │  │  (Local)   │  │   (Cloud)  │  │  (Future)  │  │  (Hybrid)  │           │  │
│  │  └────────────┘  └────────────┘  └────────────┘  └────────────┘           │  │
│  └───────────────────────────────────────────────────────────────────────────┘  │
│                                                                                  │
└─────────────────────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────────────────┐
│                           INFRASTRUCTURE LAYER                                   │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐            │
│  │   Docker    │  │ Kubernetes  │  │    Local    │  │    CI/CD    │            │
│  │  (Container)│  │  (Orchestr.)│  │  (Dev Env)  │  │  (GitHub)   │            │
│  └─────────────┘  └─────────────┘  └─────────────┘  └─────────────┘            │
└─────────────────────────────────────────────────────────────────────────────────┘
```

### 2.2 Module Organization

```
oclawma/
├── __init__.py                 # Package metadata
├── __main__.py                 # Entry point: python -m oclawma
├── cli.py                      # Main CLI commands
├── cli_ui.py                   # Terminal UI utilities
├── completion.py               # Shell completion
├── config/                     # Configuration management
│   ├── __init__.py            # Config loading/saving
│   ├── cli.py                 # Config CLI commands
│   └── utils.py               # Config utilities
├── context/                    # Context management
│   ├── budget.py              # Token budget tracking
│   ├── compression.py         # Context compression
│   └── cli.py                 # Context CLI commands
├── learning/                   # Error pattern learning
│   ├── __init__.py            # Pattern detection
│   ├── integration.py         # Tool integration
│   └── cli.py                 # Learning CLI commands
├── memory/                     # Vector memory (RAG)
│   ├── cli.py                 # Memory CLI commands
│   ├── embeddings.py          # Embedding providers
│   ├── indexer.py             # Document indexing
│   ├── query.py               # Similarity search
│   └── store.py               # Vector store
├── providers/                  # LLM providers
│   ├── base.py                # Provider interface
│   ├── ollama.py              # Ollama integration
│   └── kimi.py                # Kimi integration
├── safety.py                   # Safety controls
├── safety_cli.py              # Safety CLI commands
├── session/                    # Session management
│   ├── __init__.py            # Session lifecycle
│   ├── history_summarizer.py  # Rolling summarization
│   └── runner.py              # Interactive runner
├── skills/                     # Skill system
│   ├── __init__.py            # Skill registry
│   ├── cli.py                 # Skills CLI commands
│   ├── entry_points.py        # Entry point discovery
│   ├── manifest.py            # Skill manifest parsing
│   ├── registry.py            # Skill registration
│   ├── skill.py               # Base skill class
│   └── token_cache.py         # Token counting cache
├── subagent/                   # Sub-agent management
│   ├── __init__.py            # Sub-agent lifecycle
│   └── cli.py                 # Sub-agent CLI commands
└── tools/                      # Built-in tools
    ├── base.py                # Tool interface
    ├── exec_tool.py           # Execute commands
    ├── read_tool.py           # Read files
    └── write_tool.py          # Write files
```

---

## 3. Component Deep Dive

### 3.1 CLI Layer

**Purpose:** User interface and command routing

**Key Features:**
- Command groups: `run`, `config`, `skills`, `memory`, `safety`
- Shell completion (bash/zsh)
- Rich terminal output with progress indicators
- Help system with examples

**Architecture:**
```python
# Command routing
@click.group()
def cli():
    """OCLAWMA CLI."""
    pass

@cli.command()
@click.option("--model", default="qwen2.5:3b")
@click.option("--provider", type=click.Choice(["ollama", "kimi", "auto"]))
def run(model, provider):
    """Start interactive session."""
    session = InteractiveSession(model=model, provider=provider)
    asyncio.run(session.run())
```

**Extension Points:**
Add new commands via Click decorators

### 3.2 Session Management

**Purpose:** Manage interactive AI conversations

**Key Classes:**

```python
class InteractiveSession:
    """Manages an interactive AI session."""
    
    def __init__(self, provider: BaseProvider, budget: ContextBudget):
        self.provider = provider
        self.history = ConversationHistory()
        self.budget = budget
        self.tool_registry = ToolRegistry()
        self.summarizer = RollingHistorySummarizer()
        self.safety_checker = SafetyChecker()
    
    async def run(self) -> SessionStats:
        """Main session loop."""
        while self.active:
            # Get user input
            user_input = await self._get_input()
            
            # Check for commands
            if user_input.startswith("/"):
                await self._handle_command(user_input)
                continue
            
            # Check budget
            if not self.budget.can_allocate(100):  # rough estimate
                await self._compress_context()
            
            # Generate response
            response = await self._generate_response(user_input)
            
            # Execute any tool calls
            results = await self._execute_tools(response)
            
            # Display response
            self._display_response(response, results)
```

**State Management:**
- Session state persisted to `~/.openclaw/sessions/`
- Graceful handling of interruptions
- Resume capability for long sessions

### 3.3 Provider System

**Purpose:** Abstract LLM backends with unified interface

**Interface:**
```python
class BaseProvider(ABC):
    """Abstract base for LLM providers."""
    
    @abstractmethod
    async def complete(
        self, 
        request: CompletionRequest
    ) -> CompletionResponse:
        """Generate a chat completion."""
        pass
    
    @abstractmethod
    async def stream_complete(
        self, 
        request: CompletionRequest
    ) -> AsyncIterator[CompletionResponse]:
        """Generate a streaming completion."""
        pass
    
    @abstractmethod
    def count_tokens(self, text: str) -> int:
        """Estimate token count."""
        pass
```

**Implementations:**

| Provider | Best For | Requirements |
|----------|----------|--------------|
| Ollama | Privacy, offline | Local Ollama server |
| Kimi | Power, reliability | KIMI_API_KEY env var |
| Fallback | Reliability | Both of above |

**Fallback Logic:**
```python
class FallbackProvider(BaseProvider):
    """Automatically switches between providers."""
    
    async def complete(self, request) -> CompletionResponse:
        try:
            return await self.primary.complete(request)
        except (ConnectionError, TimeoutError, ContextOverflowError):
            logger.warning("Primary failed, using fallback")
            return await self.fallback.complete(request)
```

### 3.4 Tool System

**Purpose:** Enable AI to interact with the system

**Built-in Tools:**

| Tool | Purpose | Safety Level |
|------|---------|--------------|
| `read` | Read file contents | SAFE |
| `write` | Write/modify files | CONFIRM |
| `exec` | Execute shell commands | STRICT |

**Tool Registration:**
```python
class ToolRegistry:
    """Registry for available tools."""
    
    def __init__(self):
        self._tools: dict[str, BaseTool] = {}
        self._register_builtin_tools()
    
    def _register_builtin_tools(self):
        self.register(ReadTool())
        self.register(WriteTool())
        self.register(ExecTool())
    
    def register(self, tool: BaseTool):
        self._tools[tool.name] = tool
    
    async def execute(self, name: str, params: dict) -> ToolResult:
        if name not in self._tools:
            return ToolResult(error=f"Unknown tool: {name}")
        return await self._tools[name].execute(**params)
```

**Tool Format:**
```python
@dataclass
class ToolResult:
    """Result of tool execution."""
    success: bool
    output: str = ""
    error: str = ""
    metadata: dict = field(default_factory=dict)
```

### 3.5 Skill System

**Purpose:** Extensible plugin architecture

**Skill Lifecycle:**
```
Discovery → Manifest Loading → Lazy Registration → On-Demand Loading → Execution
```

**Manifest Format:**
```yaml
# skill.yaml
name: docker_skill
version: 1.0.0
description: Docker container management
author: OCLAWMA Team
entry_point: docker_skill:DockerSkill

requirements:
  - docker>=6.0.0

tools:
  - name: docker_ps
    description: List running containers
    parameters: []
    returns: table
    token_count: 50
    
  - name: docker_run
    description: Run a container
    parameters:
      - name: image
        type: string
        required: true
      - name: ports
        type: dict
        required: false
    returns: string
    token_count: 100
```

**Lazy Loading:**
```python
class LazySkill(Skill):
    """Skill that loads only when needed."""
    
    def __init__(self, manifest: SkillManifest):
        self.manifest = manifest
        self._instance = None
    
    @property
    def tools(self) -> dict[str, BaseTool]:
        if self._instance is None:
            self._load()
        return self._instance.tools
    
    def _load(self):
        """Load the skill implementation."""
        module_name, class_name = self.manifest.entry_point.split(":")
        module = importlib.import_module(module_name)
        skill_class = getattr(module, class_name)
        self._instance = skill_class()
```

### 3.6 Context Management

**Purpose:** Optimize token usage for 8K context models

**Context Budget:**
```python
class ContextBudget:
    """Manages token budget for conversations."""
    
    def __init__(self, total: int = 8192):
        self.total = total
        self.used = 0
        self.thresholds = {
            "warning": 0.75,    # 6144 tokens
            "critical": 0.87,   # 7127 tokens
            "maximum": 1.0,     # 8192 tokens
        }
    
    def allocate(self, tokens: int) -> AllocationResult:
        """Attempt to allocate tokens."""
        if self.used + tokens > self.total:
            return AllocationResult(
                success=False,
                allocated=0,
                reason="Budget exceeded"
            )
        
        self.used += tokens
        
        # Check thresholds
        usage = self.usage_percent
        if usage >= self.thresholds["maximum"]:
            return AllocationResult(success=True, allocated=tokens, warning="MAXIMUM")
        elif usage >= self.thresholds["critical"]:
            return AllocationResult(success=True, allocated=tokens, warning="CRITICAL")
        elif usage >= self.thresholds["warning"]:
            return AllocationResult(success=True, allocated=tokens, warning="WARNING")
        
        return AllocationResult(success=True, allocated=tokens)
```

**Rolling Summarization:**
```python
class RollingHistorySummarizer:
    """Summarizes old conversation to save tokens."""
    
    def summarize(self, history: ConversationHistory) -> Summary:
        """Compress old messages into summary."""
        # Identify messages to summarize
        old_messages = self._select_messages(history, threshold=0.6)
        
        # Generate summary with LLM
        summary_text = await self._generate_summary(old_messages)
        
        # Extract key facts
        facts = await self._extract_facts(old_messages)
        
        # Replace messages with summary
        history.replace_with_summary(
            messages=old_messages,
            summary=summary_text,
            facts=facts
        )
        
        return Summary(
            text=summary_text,
            facts=facts,
            tokens_saved=self._calculate_savings(old_messages)
        )
```

---

## 4. Data Flow Architecture

### 4.1 Session Flow

```mermaid
sequenceDiagram
    participant User
    participant CLI
    participant Session
    participant Budget
    participant Provider
    participant Tools
    
    User->>CLI: Enter message
    CLI->>Session: process_message()
    Session->>Budget: check_budget()
    Budget-->>Session: OK / Need compression
    
    alt Budget OK
        Session->>Provider: complete()
        Provider-->>Session: LLM response
    else Need compression
        Session->>Session: compress_context()
        Session->>Provider: complete()
        Provider-->>Session: LLM response
    end
    
    Session->>Session: parse_tool_calls()
    
    loop For each tool call
        Session->>Tools: execute()
        Tools-->>Session: ToolResult
    end
    
    Session-->>CLI: Formatted response
    CLI-->>User: Display output
```

### 4.2 Skill Loading Flow

```mermaid
sequenceDiagram
    participant CLI
    participant Registry
    participant EntryPoints
    participant LazySkill
    participant SkillCode
    
    CLI->>Registry: discover_skills()
    Registry->>EntryPoints: entry_points(group="oclawma.skills")
    EntryPoints-->>Registry: EntryPoint objects
    
    loop For each entry point
        Registry->>Registry: load_manifest()
        Registry->>LazySkill: create(manifest)
        LazySkill-->>Registry: LazySkill instance
        Registry->>Registry: register(skill)
    end
    
    Note over CLI,SkillCode: Later... User invokes skill tool
    
    CLI->>LazySkill: tools[name].execute()
    LazySkill->>LazySkill: _load() [first time]
    LazySkill->>SkillCode: import module
    SkillCode-->>LazySkill: Skill class
    LazySkill->>SkillCode: instantiate()
    SkillCode-->>LazySkill: Skill instance
    LazySkill->>SkillCode: execute_tool()
    SkillCode-->>CLI: ToolResult
```

### 4.3 Provider Fallback Flow

```mermaid
sequenceDiagram
    participant Session
    participant FallbackProvider
    participant Ollama
    participant Kimi
    
    Session->>FallbackProvider: complete(request)
    FallbackProvider->>Ollama: complete(request)
    
    alt Ollama Success
        Ollama-->>FallbackProvider: Response
        FallbackProvider-->>Session: Response
    else Ollama Failure
        Ollama-->>FallbackProvider: Error
        FallbackProvider->>FallbackProvider: Log failure
        FallbackProvider->>Kimi: complete(request)
        Kimi-->>FallbackProvider: Response
        FallbackProvider-->>Session: Response
    end
```

---

## 5. Security Architecture

### 5.1 Defense Layers

```
┌─────────────────────────────────────────────────────────────────┐
│ Layer 1: User Interface                                          │
│ • Input validation via Click/Pydantic                           │
│ • Command parsing and sanitization                              │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│ Layer 2: Safety Configuration                                    │
│ • Configurable safety levels (strict/normal/permissive)         │
│ • Command blacklists per level                                  │
│ • Confirmation prompts for destructive operations               │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│ Layer 3: Tool Execution                                          │
│ • Tool registry validation                                      │
│ • Parameter type checking                                       │
│ • Dangerous command detection                                   │
│ • Subprocess isolation (no shell=True)                          │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│ Layer 4: Skill Isolation                                         │
│ • Entry point verification                                      │
│ • Lazy loading limits exposure                                  │
│ • Skill manifest validation                                     │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│ Layer 5: System Access                                           │
│ • File system restrictions                                      │
│ • Network access controls                                       │
│ • Resource limits (timeouts, memory)                            │
└─────────────────────────────────────────────────────────────────┘
```

### 5.2 Safety Levels

| Level | Commands Blocked | Confirmation Required | Use Case |
|-------|-----------------|----------------------|----------|
| **STRICT** | rm, sudo, chmod, chown, curl, wget | All writes | Production, CI/CD |
| **NORMAL** | sudo, rm -rf / | Destructive operations | Development |
| **PERMISSIVE** | None | None | Trusted environment |

### 5.3 Security Controls Matrix

| Threat | Control | Implementation |
|--------|---------|----------------|
| Command Injection | Input validation | `shlex.split()` + validation |
| Path Traversal | Path normalization | `Path.resolve()` + bounds check |
| Resource Exhaustion | Budget enforcement | `ContextBudget` class |
| Code Injection | Entry point verification | Restricted entry point loading |
| Secret Leakage | Config file permissions | `chmod 600` enforcement |
| Privilege Escalation | No sudo | Blocked in all safety levels |

---

## 6. Deployment Patterns

### 6.1 Local Development

```bash
# Virtual environment
python -m venv venv
source venv/bin/activate
pip install -e ".[dev]"

# Configure
oclawma config init

# Run with local model
oclawma run --provider ollama --model qwen2.5:3b
```

### 6.2 Docker Deployment

```dockerfile
FROM python:3.11-slim

WORKDIR /app
COPY . .
RUN pip install --no-cache-dir -e "."

# Non-root user
RUN useradd -m -u 1000 oclawma
USER oclawma

ENTRYPOINT ["oclawma"]
```

```bash
docker build -t oclawma:latest .
docker run -it --rm oclawma:latest run
```

### 6.3 Kubernetes Deployment

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: oclawma
spec:
  replicas: 1
  selector:
    matchLabels:
      app: oclawma
  template:
    metadata:
      labels:
        app: oclawma
    spec:
      securityContext:
        runAsNonRoot: true
        runAsUser: 1000
      containers:
      - name: oclawma
        image: oclawma:latest
        command: ["oclawma", "run", "--provider", "kimi"]
        env:
        - name: KIMI_API_KEY
          valueFrom:
            secretKeyRef:
              name: oclawma-secrets
              key: kimi-api-key
        resources:
          limits:
            cpu: "500m"
            memory: "512Mi"
        securityContext:
          allowPrivilegeEscalation: false
          readOnlyRootFilesystem: true
```

### 6.4 CI/CD Integration

```yaml
# .github/workflows/oclawma.yml
name: OCLAWMA Automation

on:
  schedule:
    - cron: '0 */6 * * *'  # Every 6 hours

jobs:
  automation:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
    
    - name: Setup OCLAWMA
      run: |
        pip install oclawma
        oclawma config init
    
    - name: Run automation
      env:
        KIMI_API_KEY: ${{ secrets.KIMI_API_KEY }}
      run: |
        oclawma run --dry-run << 'EOF'
        Review recent PRs and suggest improvements
        EOF
```

---

## 7. Performance Characteristics

### 7.1 Resource Usage

| Component | Memory | CPU | Notes |
|-----------|--------|-----|-------|
| Base Framework | ~50MB | Low | Without providers |
| Ollama Provider | ~100MB | Low | HTTP client only |
| Kimi Provider | ~50MB | Low | HTTP client only |
| Skill (loaded) | ~10-50MB | Varies | Depends on skill |
| Context Storage | ~1-10MB | Low | Conversation history |

### 7.2 Latency Budgets

| Operation | Target | Worst Case |
|-----------|--------|------------|
| CLI startup | < 500ms | < 1s |
| Skill discovery | < 100ms | < 500ms |
| Skill loading | < 1s | < 5s |
| LLM request | Provider dependent | - |
| Tool execution | < 5s | < 30s (timeout) |
| Context compression | < 2s | < 5s |

### 7.3 Throughput

| Metric | Value | Notes |
|--------|-------|-------|
| Max concurrent sessions | 1 (interactive) | Design limitation |
| Tool calls per session | Unlimited | With budget management |
| Skills loaded simultaneously | All discovered | Lazy loading enables this |
| Messages per session | ~100-200 | Before compression needed |

### 7.4 Scaling Considerations

**Horizontal Scaling:**
- Not applicable for interactive mode
- Sub-agents can run in parallel for batch tasks

**Vertical Scaling:**
- Memory: Increases with skill count and context size
- CPU: Minimal for framework, depends on tool execution

**Optimization Strategies:**
1. Use lazy loading for skills
2. Enable context compression
3. Set appropriate timeouts
4. Use local providers when possible

---

## 8. Integration Points

### 8.1 External Services

| Service | Integration | Purpose |
|---------|-------------|---------|
| Ollama | HTTP API | Local LLM inference |
| Kimi API | HTTP API | Cloud LLM inference |
| PyPI | Package index | Skill distribution |
| GitHub | Git repository | Version control |

### 8.2 Internal Interfaces

| Interface | Protocol | Consumers |
|-----------|----------|-----------|
| Entry Points | Python | Skill discovery |
| Tool Registry | Python | Session, CLI |
| Provider API | Python Abstract Base | Session |
| Config Files | YAML/JSON | All components |

### 8.3 Extension APIs

**Creating a Custom Provider:**
```python
from oclawma.providers.base import BaseProvider, CompletionRequest

class MyProvider(BaseProvider):
    async def complete(self, request: CompletionRequest):
        # Implementation
        pass
    
    def count_tokens(self, text: str) -> int:
        # Implementation
        pass
```

**Creating a Custom Skill:**
```python
from oclawma.skills.skill import Skill, BaseTool

class MySkill(Skill):
    def __init__(self):
        self.tools = {
            "my_tool": MyTool()
        }

class MyTool(BaseTool):
    name = "my_tool"
    description = "Does something useful"
    
    async def execute(self, param: str) -> ToolResult:
        # Implementation
        return ToolResult(success=True, output="Done")
```

**Creating a Custom Tool:**
```python
from oclawma.tools.base import BaseTool, ToolResult

class DatabaseTool(BaseTool):
    name = "query_db"
    description = "Query the database"
    
    async def execute(self, sql: str) -> ToolResult:
        # Implementation with safety checks
        if not self._is_safe_sql(sql):
            return ToolResult(success=False, error="Unsafe SQL")
        # Execute query
        return ToolResult(success=True, output=results)
```

---

## 9. Operational Considerations

### 9.1 Monitoring

**Key Metrics:**
- Session duration
- Token usage per session
- Tool call frequency
- Error rates
- Provider latency

**Logging:**
```python
# Structured logging
logger.info("session_started", 
    session_id=id,
    provider=provider_name,
    model=model_name
)

logger.info("tool_executed",
    tool=tool_name,
    duration_ms=elapsed,
    success=result.success
)
```

### 9.2 Troubleshooting

| Symptom | Possible Cause | Solution |
|---------|---------------|----------|
| Slow startup | Many skills installed | Remove unused skills |
| Context budget exceeded | Long conversation | Use `/compact` command |
| Tool execution fails | Safety level too strict | Adjust safety level |
| Provider connection error | Network/API key | Check config, test connection |
| Skill not found | Entry point misconfigured | Check skill.yaml |

### 9.3 Backup and Recovery

**Configuration:**
```bash
# Backup config
cp ~/.config/oclawma/config.yaml backup/

# Backup conversation history
tar czf oclawma-history.tar.gz ~/.openclaw/
```

**Recovery:**
```bash
# Restore config
cp backup/config.yaml ~/.config/oclawma/

# Clear corrupted cache
rm -rf ~/.openclaw/cache/
```

---

## 10. Future Roadmap

### 10.1 Planned Features

| Feature | Target Version | Description |
|---------|----------------|-------------|
| OpenAI Provider | 0.3.0 | Native GPT-4/3.5 support |
| Vector Memory v2 | 0.3.0 | Improved RAG with embeddings |
| Multi-Agent | 0.4.0 | Parallel sub-agent execution |
| Web UI | 0.4.0 | Browser-based interface |
| Plugin Marketplace | 0.5.0 | Curated skill repository |

### 10.2 Architecture Evolution

**Current (v0.2.0):**
- Single session, interactive
- File-based configuration
- Local skill discovery

**Near-term (v0.3-0.4):**
- Multi-session support
- Database-backed configuration
- Remote skill registry

**Long-term (v1.0):**
- Distributed agent networks
- Advanced orchestration
- Enterprise features (RBAC, audit, etc.)

### 10.3 Research Areas

1. **Context Optimization:** Better compression algorithms
2. **Tool Learning:** Auto-discovery of tool patterns
3. **Safety ML:** ML-based safety classification
4. **Multi-modal:** Image/audio tool support

---

## Appendix A: Glossary

| Term | Definition |
|------|------------|
| **Skill** | A plugin that adds tools to OCLAWMA |
| **Provider** | An LLM backend (Ollama, Kimi, etc.) |
| **Context Budget** | Token limit management system |
| **Tool** | A function the AI can call |
| **Session** | A single interactive conversation |
| **Lazy Loading** | Loading code only when needed |

## Appendix B: Configuration Reference

### Complete Configuration File

```yaml
# ~/.config/oclawma/config.yaml
version: "1.0"

# Default profile
active_profile: default

# Provider profiles
profiles:
  default:
    provider: ollama
    model: qwen2.5:3b
    base_url: http://localhost:11434
    
  cloud:
    provider: kimi
    model: k2.5
    api_key: ${KIMI_API_KEY}  # From environment
    
  auto:
    provider: auto
    primary: default
    fallback: cloud

# Context settings
context:
  budget: 8192
  warning_threshold: 0.75
  critical_threshold: 0.87
  enable_compression: true

# Safety settings
safety:
  default_level: normal
  confirm_destructive: true
  max_exec_time: 30
  blocked_commands:
    - sudo
    - rm -rf /

# Skill settings
skills:
  paths:
    - ~/.openclaw/skills
    - /usr/share/oclawma/skills
  auto_discover: true
  
# Logging
logging:
  level: INFO
  file: ~/.openclaw/logs/oclawma.log
  max_size: 10MB
  max_files: 5
```

## Appendix C: Migration Guide

### From v0.1.x to v0.2.0

1. **Config file format changed:**
   ```bash
   oclawma config migrate --from 0.1 --to 0.2
   ```

2. **Skill manifest updated:**
   - Add `entry_point` field
   - Update tool definitions

3. **API changes:**
   - `InteractiveSession` constructor signature
   - `ToolResult` now requires `success` field

---

**Document Version:** 2.0  
**Last Updated:** 2026-02-22  
**Next Review:** 2026-05-22
