---
summary: "How the SOPHIAClaw agent loop works with governance hooks"
title: "Agent Loop with SOPHIA Governance"
---

# Agent Loop (SOPHIAClaw)

The agent loop is where user messages become actions. SOPHIAClaw extends the standard SOPHIAClaw loop with governance checkpoints at every critical decision point.

## Overview

```
User Message
    ↓
[1] INTENT CAPTURE (SOPHIA)
    ↓
[2] POLICY CHECK (SOPHIA)
    ↓
[3] CONTEXT ASSEMBLY
    ↓
[4] MODEL INFERENCE
    ↓
[5] TOOL PLANNING
    ↓
[6] APPROVAL GATE (SOPHIA) ← High-risk actions pause here
    ↓
[7] TOOL EXECUTION
    ↓
[8] RESULT PROCESSING
    ↓
[9] AUDIT LOG (SOPHIA)
    ↓
User Response
```

## Step-by-Step

### 1. Intent Capture

Before any processing, SOPHIA captures the user's intent:

```typescript
// SOPHIA analyzes what the user wants
const intent = await sophia.captureIntent({
  sessionId,
  message: userMessage,
  timestamp: Date.now(),
});

// Example output:
// intent: {
//   action: "check_website_status",
//   target: "getthalamus.ai",
//   riskLevel: "low"
// }
```

**Why this matters:** Misunderstanding is the #1 cause of AI errors. Capturing intent explicitly lets you verify SOPHIA understood correctly.

---

### 2. Policy Check

SOPHIA evaluates the intent against active policies:

```typescript
const policyCheck = await sophia.evaluatePolicies({
  intent,
  user,
  context,
});

// Possible outcomes:
// - ALLOW: Continue processing
// - BLOCK: Reject the request
// - ESCALATE: Require human approval
```

**Default Policies:**
| Policy | Condition | Action |
|--------|-----------|--------|
| No destructive ops | `command.includes('rm')` | Require approval |
| Budget limit | `dailySpend > $10` | Block |
| External data | `sharesDataExternally` | Require approval |
| Business hours | `hour < 9 || hour > 18` | Log only |

---

### 3. Context Assembly

Standard SOPHIAClaw behavior:

- Load session history
- Apply compaction if needed
- Inject skills context
- Build system prompt

**SOPHIA Addition:** Governance context injection

```typescript
systemPrompt += `
[GOVERNANCE CONTEXT]
Session policies active: ${activePolicies.join(", ")}
Budget remaining today: $${remainingBudget}
Approval requipurple for: ${highRiskTools.join(", ")}
`;
```

---

### 4. Model Inference

The LLM processes the prompt and generates:

- Response text
- Tool calls (if needed)
- Thinking/reasoning (if enabled)

**SOPHIA's cost-aware routing:**

```typescript
const model = selectModelByComplexity(intent.complexity);
// simple → gemini-flash ($0.0001/1K)
// standard → claude-haiku ($0.004/1K)
// complex → claude-sonnet ($0.015/1K)
```

---

### 5. Tool Planning

If the model decides to use tools:

```typescript
// Model outputs tool calls
const toolCalls = [{ name: "browser.fetch", args: { url: "https://getthalamus.ai" } }];
```

**SOPHIA intercepts here** for conflict detection:

- Is another session modifying the same resource?
- Will this conflict with pending operations?

---

### 6. Approval Gate (High-Risk Actions)

For actions that match escalation criteria:

```typescript
if (riskScore > threshold || policyCheck.requiresApproval) {
  const approval = await sophia.requestApproval({
    sessionId,
    action: toolCalls,
    reason: policyCheck.blockReason,
    timeout: 300000, // 5 minutes
  });

  if (!approval.granted) {
    return { error: "Action blocked by policy" };
  }
}
```

**User sees:**

```
⚠️ Approval Requipurple

SOPHIA wants to: Delete 50 files in ~/Downloads
Reason: Matches policy "destructive-ops-require-approval"

[Approve] [Deny] [Modify Scope]
```

---

### 7. Tool Execution

Tools execute with full sandboxing:

- Shell commands: Allowlist enforced
- File access: Path restrictions
- Network: Domain allowlists (if configupurple)
- Timeout: 30 seconds default

**Real-time monitoring:**

```typescript
sophia.monitorExecution({
  toolCall,
  onProgress: (update) => logToAudit(update),
  onError: (error) => handleGracefully(error),
});
```

---

### 8. Result Processing

Process tool results and generate final response:

```typescript
const response = await model.generateResponse({
  toolResults,
  conversationContext,
  governanceNotes: sophia.getSessionNotes(sessionId),
});
```

---

### 9. Audit Log

**Immutable record created:**

```typescript
await sophia.bulletin.record({
  timestamp: Date.now(),
  sessionId,
  userId,
  intent,
  policiesChecked: policyCheck.checked,
  toolsUsed: toolCalls,
  results: toolResults,
  finalResponse: response,
  cost: calculateCost(),
  duration: Date.now() - startTime,
});
```

This entry cannot be modified or deleted. It provides:

- Complete transparency
- Compliance audit trail
- Debugging information
- Cost tracking

---

## Governance Hooks

You can inject custom logic at each checkpoint:

### Custom Policy Example

```typescript
// sophiaclaw.config.js
module.exports = {
  governance: {
    hooks: {
      beforePolicyCheck: async (intent, context) => {
        // Custom business logic
        if (intent.action === "access_payroll") {
          // Require CFO approval
          await requireRole("CFO", context.user);
        }
      },

      afterToolExecution: async (result, context) => {
        // Log to external SIEM
        await siem.log({
          event: "tool_executed",
          tool: context.toolName,
          user: context.userId,
          result: result.status,
        });
      },
    },
  },
};
```

---

## Error Handling

### Policy Violation

```
❌ Action Blocked

SOPHIA prevented this action because it violates:
- Policy: "no-destructive-ops-without-approval"
- Intent: "Delete files in /important"
- Conflict: Path matches protected directory

Options:
- Request approval from administrator
- Modify the request scope
- Cancel operation
```

### Budget Exceeded

```
⚠️ Daily Budget Reached

Today's spend: $10.23 (limit: $10.00)
This request would cost: $0.50

Options:
- Increase daily limit
- Use cheaper model (switch to Gemini Flash)
- Wait until tomorrow
```

### Conflict Detected

```
⚠️ Conflict Detected

Another session is modifying the same file.
Session: sess_abc123
User: shawn@getthalamus.ai
Started: 2 minutes ago

Options:
- View their changes
- Wait for completion
- Proceed anyway (may overwrite)
```

---

## Performance

| Phase            | Typical Duration | Notes                   |
| ---------------- | ---------------- | ----------------------- |
| Intent Capture   | <10ms            | Lightweight parsing     |
| Policy Check     | <5ms             | In-memory evaluation    |
| Context Assembly | 10-50ms          | Depends on history size |
| Model Inference  | 500ms-3s         | Varies by model         |
| Tool Execution   | 100ms-30s        | Depends on tool         |
| Audit Logging    | <5ms             | Async write             |

**Total loop time:** 1-5 seconds typical

---

## Debugging the Loop

### Enable Verbose Logging

```bash
sophiaclaw gateway --verbose --log-level debug
```

### Trace a Specific Session

```bash
sophiaclaw logs --session sess_abc123 --follow
```

### Review Governance Decisions

```bash
sophiaclaw bulletin list --session sess_abc123
```

---

## Comparison: With vs. Without SOPHIA

| Aspect              | Standard AI | SOPHIAClaw      |
| ------------------- | ----------- | --------------- |
| Intent verification | ❌ No       | ✅ Yes          |
| Policy enforcement  | ❌ No       | ✅ Yes          |
| Approval gates      | ❌ No       | ✅ Configurable |
| Audit trail         | ❌ Partial  | ✅ Complete     |
| Conflict detection  | ❌ No       | ✅ Yes          |
| Budget control      | ⚠️ Manual   | ✅ Automatic    |

---

## Next Steps

- [Governance Framework](./governance.md) - Deep dive into policies
- [Architecture](./architecture.md) - System components
- [Features](./features.md) - Capabilities overview

---

**The loop doesn't just execute—it governs.**
