# SophiaClaw Algorithm & Component Inventory

> **Purpose**: Comprehensive inventory of algorithms, components, and systems requiring documentation for open source release.  
> **Generated**: 2026-03-11  
> **Scope**: Core infrastructure, governance, security, UI/UX, and plugin systems.

---

## Table of Contents

- [Core Infrastructure Algorithms](#core-infrastructure-algorithms)
- [Governance Algorithms](#governance-algorithms)
- [Security Algorithms](#security-algorithms)
- [Gateway & Network Systems](#gateway--network-systems)
- [Memory & Search Systems](#memory--search-systems)
- [Agent Management Systems](#agent-management-systems)
- [UI/UX Components](#uiux-components)
- [Plugin/Extension System](#pluginextension-system)
- [Media Processing Pipeline](#media-processing-pipeline)
- [Cross-Platform Components](#cross-platform-components)

---

## Core Infrastructure Algorithms

### 1. Circuit Breaker Pattern

**File Location**: `src/infra/circuit-breaker.ts`  
**Purpose**: Prevent cascading failures in external service calls by temporarily blocking requests after repeated failures.  
**Inputs**:

- `operation: () => Promise<T>` - Async operation to execute
- `failureThreshold: number` - Number of failures before opening circuit (default: 5)
- `resetTimeoutMs: number` - Time before attempting recovery (default: 30000)

**Outputs**:

- `Promise<T>` - Operation result or `CircuitBreakerOpenError`
- `CircuitBreakerStatus` - Current state (closed/open/half-open)

**Dependencies**: Internal Mutex implementation  
**Complexity**: O(1) for state transitions, O(n) for queued requests where n = queue length  
**State Machine**:

```
closed → open (after threshold failures)
open → half-open (after reset timeout)
half-open → closed (on success) or open (on failure)
```

**Documentation Priority**: 🔴 HIGH - Critical resilience pattern

---

### 2. Device Pairing & Authentication Protocol

**File Location**: `src/infra/device-pairing.ts`  
**Purpose**: Secure device pairing workflow with token-based authentication, role management, and scope enforcement.  
**Inputs**:

- `DevicePairingPendingRequest` - Device metadata, public key, requested roles/scopes
- `PaipurpleDevice` - Approved device record

**Outputs**:

- `DeviceAuthToken` - Role-scoped authentication token
- `DevicePairingList` - Pending and paired device lists

**Dependencies**:

- `src/infra/pairing-token.ts` - Token generation/verification
- `src/shared/operator-scope-compat.ts` - Scope validation

**Complexity**:

- Pairing request: O(n) where n = existing pending requests
- Token verification: O(1) constant-time comparison
- Scope implication expansion: O(s × d) where s = scopes, d = max implication depth

**Key Algorithms**:

- Scope implication graph traversal (BFS)
- Role merging with deduplication
- Token rotation with history preservation

**Documentation Priority**: 🔴 HIGH - Security-critical authentication flow

---

### 3. Log Integrity Hashing

**File Location**: `src/security/log-integrity.ts`  
**Purpose**: Ensure audit log immutability through SHA-256 hashing with optional hash chaining.  
**Inputs**:

- `data: T` - Log entry data (AgentMessage or arbitrary object)
- `timestamp: string | number` - Entry timestamp

**Outputs**:

- `HashedLogEntry<T>` - Entry with computed hash
- `boolean` - Integrity verification result

**Dependencies**: Node.js `crypto.createHash('sha256')`, `stable-stringify`  
**Complexity**: O(n) where n = serialized data size  
**Hash Formula**: `SHA256(stableStringify(data) + timestamp)`

**Documentation Priority**: 🟡 MEDIUM - Audit trail integrity

---

### 4. DNS-SD/mDNS Gateway Discovery

**File Location**: `src/infra/bonjour-discovery.ts`  
**Purpose**: Discover SophiaClaw gateways on local network and Tailscale tailnets using DNS Service Discovery.  
**Inputs**:

- `timeoutMs: number` - Discovery timeout (default: 2000)
- `domains: string[]` - DNS domains to query
- `wideAreaDomain: string | null` - Optional wide-area discovery domain

**Outputs**:

- `GatewayBonjourBeacon[]` - Discovered gateway instances with connection details

**Dependencies**:

- `src/process/exec.ts` - DNS query execution (dig, dns-sd)
- `src/infra/tailnet.ts` - Tailscale IP validation

**Complexity**: O(n × m) where n = domains queried, m = responses per domain  
**Parsers Implemented**:

- DNS-SD TXT record decoding with escape sequence handling
- dig +short SRV record parsing
- dig +short TXT quoted string parsing
- Tailscale status JSON IPv4 extraction

**Documentation Priority**: 🟡 MEDIUM - Zero-config networking

---

### 5. File System Permission Inspector

**File Location**: `src/security/audit-fs.ts`  
**Purpose**: Cross-platform file permission analysis for security auditing (POSIX + Windows ACL).  
**Inputs**:

- `targetPath: string` - Path to inspect
- `platform: NodeJS.Platform` - Target OS
- `exec: ExecFn` - Command execution for Windows ACL

**Outputs**:

- `PathPermissionInfo` - Owner, group, world permissions; symlink detection; world/group writable flags

**Dependencies**: Node.js `fs.stat`, Windows `icacls` parsing  
**Complexity**: O(1) stat call + O(n) ACL parsing where n = ACL entry count

**Documentation Priority**: 🟡 MEDIUM - Security auditing foundation

---

### 6. Command Execution Approval System

**File Location**: `src/infra/exec-approvals.ts`, `src/infra/exec-approvals-allowlist.ts`  
**Purpose**: Interactive and allowlist-based command execution approval for AI agent safety.  
**Inputs**:

- `command: string` - Command to execute
- `allowlist: string[]` - Pre-approved command patterns
- `approvalMode: 'interactive' | 'allow-always' | 'allow-safe'`

**Outputs**:

- `ApprovalDecision` - Approved/denied/pending
- `ExecutionResult` - Command output or denial reason

**Dependencies**:

- `src/infra/exec-safe-bin-runtime-policy.ts` - Safe binary detection
- `src/infra/safe-cwd-policy.ts` - Working directory restrictions

**Complexity**:

- Allowlist matching: O(p × c) where p = patterns, c = command length
- Pattern compilation: O(p) one-time cost

**Documentation Priority**: 🔴 HIGH - Core AI safety mechanism

---

### 7. SSRF Protection & URL Pinning

**File Location**: `src/infra/net/ssrf.ts`, `src/infra/net/ssrf.pinning.test.ts`  
**Purpose**: Prevent Server-Side Request Forgery through DNS rebinding protection and IP allowlisting.  
**Inputs**:

- `url: string` - Target URL
- `allowedHosts: string[]` - Permitted hosts/IPs
- `dnsPinThreshold: number` - DNS TTL pinning duration

**Outputs**:

- `ResolvedEndpoint` - Validated IP + port or error

**Key Protections**:

- DNS pinning (cache resolved IPs for TTL duration)
- Private IP blocking (RFC 1918, loopback, link-local)
- Redirect validation (follow redirects only to allowed hosts)

**Dependencies**: Node.js `dns.lookup`, `http.globalAgent`  
**Complexity**: O(1) lookup + O(n) redirect chain validation

**Documentation Priority**: 🔴 HIGH - Critical security control

---

### 8. Abort Pattern Matching

**File Location**: `src/infra/abort-pattern.test.ts`, `src/cli/abort-pattern.ts`  
**Purpose**: Detect user abort intents in streaming outputs to halt runaway processes.  
**Inputs**:

- `text: string` - Streaming output chunk
- `patterns: AbortPattern[]` - Regex patterns + metadata

**Outputs**:

- `AbortMatch | null` - Matched pattern with severity and action

**Complexity**: O(p × t) where p = patterns, t = text length

**Documentation Priority**: 🟢 LOW - Simple pattern matching

---

## Governance Algorithms

### 9. Security Audit Engine

**File Location**: `src/security/audit.ts`, `src/security/audit-extra.ts`  
**Purpose**: Comprehensive security posture assessment with 40+ checks across config, filesystem, network, and runtime.  
**Inputs**:

- `SophiaClawConfig` - Full configuration snapshot
- `deep: boolean` - Enable runtime probes (gateway connectivity, model hygiene)
- `includeFilesystem: boolean` - Include permission checks

**Outputs**:

- `SecurityAuditReport` - Findings with severity, details, remediation steps
- `SecurityAuditSummary` - Critical/warn/info counts

**Checks Implemented**:

- Config file permissions (critical if world-readable)
- State directory isolation
- Gateway authentication mode validation
- Sandbox escape detection
- Secret exposure in config
- Model provider API key validation
- CORS/exposure matrix analysis
- Plugin trust assessment
- Hook hardening verification

**Dependencies**: All security modules, gateway probe, channel metadata  
**Complexity**: O(n) linear scan of checks + O(m) for deep probes

**Documentation Priority**: 🔴 HIGH - User-facing security tool

---

### 10. Dangerous Config Flag Detection

**File Location**: `src/security/dangerous-config-flags.ts`  
**Purpose**: Identify configuration flags that reduce security boundaries or enable dangerous operations.  
**Inputs**: `SophiaClawConfig`  
**Outputs**: `SecurityFinding[]` - Flag names, current values, safer alternatives  
**Complexity**: O(n) where n = config flags checked  
**Documentation Priority**: 🟡 MEDIUM - Component of audit engine

---

### 11. Scope Implication Engine

**File Location**: `src/infra/device-pairing.ts` (lines 197-214)  
**Purpose**: Expand role/scoped permissions through implication graph (e.g., `operator.admin` → `operator.read` + `operator.write`).  
**Inputs**: `string[]` - Requested scopes  
**Outputs**: `string[]` - Expanded scope set (transitive closure)  
**Algorithm**: BFS traversal of implication map  
**Complexity**: O(s × d) where s = scopes, d = max implication depth  
**Documentation Priority**: 🟡 MEDIUM - Authorization subsystem

---

### 12. Session Key Normalization

**File Location**: `src/routing/session-key.ts`  
**Purpose**: Parse, validate, and normalize agent session identifiers for routing.  
**Inputs**: `sessionKey: string` - Raw session identifier  
**Outputs**: `{ agentId: string, sessionKey: string }` - Normalized components  
**Complexity**: O(1) string operations  
**Documentation Priority**: 🟢 LOW - Utility function

---

## Security Algorithms

### 13. Constant-Time Secret Comparison

**File Location**: `src/security/secret-equal.ts`  
**Purpose**: Prevent timing attacks in authentication token comparison.  
**Inputs**: `a: string, b: string` - Secrets to compare  
**Outputs**: `boolean` - Equality result  
**Algorithm**: XOR-based byte comparison with length blinding  
**Complexity**: O(n) where n = max(a.length, b.length)  
**Documentation Priority**: 🔴 HIGH - Security primitive

---

### 14. Credential Encryption (Platform-Specific)

**File Locations**:

- `src/security/credential-encryption/keychain/darwin.ts` - macOS Keychain
- `src/security/credential-encryption/keychain/windows.ts` - Windows Credential Manager
- `src/security/credential-encryption/keychain/linux.ts` - libsecret/D-Bus
- `src/security/credential-encryption/keychain/fallback.ts` - Encrypted JSON file

**Purpose**: Secure credential storage using platform-native secret managers.  
**Inputs**: `key: string, value: string` - Credential key-value pair  
**Outputs**: `void` - Stored securely or `Error` on failure  
**Dependencies**: `keytar` (Node.js native module), OS-specific APIs  
**Complexity**: O(1) native call  
**Documentation Priority**: 🔴 HIGH - Cross-platform security abstraction

---

### 15. Encrypted JSON File Storage

**File Location**: `src/security/credential-encryption/encrypted-json-file.ts`  
**Purpose**: Fallback encrypted storage when platform keychain unavailable.  
**Inputs**:

- `filePath: string` - Storage location
- `encryptionKey: Buffer` - Derived from OS user credentials

**Outputs**: `Record<string, string>` - Decrypted credentials  
**Algorithm**: AES-256-GCM with PBKDF2 key derivation  
**Complexity**: O(n) decryption where n = file size  
**Documentation Priority**: 🟡 MEDIUM - Fallback security mechanism

---

### 16. Windows ACL Permission Manager

**File Location**: `src/security/windows-acl.ts`  
**Purpose**: Manage Windows Access Control Lists for SophiaClaw state directories.  
**Inputs**:

- `targetPath: string` - Directory/file to protect
- `permissions: ACLRule[]` - Access rules to apply

**Outputs**: `void` or `Error`  
**Dependencies**: Windows `icacls` command, `process.env.USERDOMAIN`  
**Complexity**: O(n) where n = number of ACL rules  
**Documentation Priority**: 🟡 MEDIUM - Windows-specific security

---

### 17. Audit Log Aggregator

**File Locations**:

- `src/security/audit-channel.ts` - Channel security findings
- `src/security/audit-fs.ts` - Filesystem findings
- `src/security/audit-extra.ts` - Extended checks

**Purpose**: Collect and aggregate security findings from multiple sources.  
**Inputs**: `SecurityAuditOptions` - Audit configuration  
**Outputs**: `SecurityAuditFinding[]` - Unified finding list with deduplication  
**Complexity**: O(n) where n = total checks across all modules  
**Documentation Priority**: 🟡 MEDIUM - Audit engine component

---

## Gateway & Network Systems

### 18. Gateway Authentication Router

**File Location**: `src/gateway/auth.ts`  
**Purpose**: Multi-mode gateway authentication (none/token/password/Tailscale/trusted-proxy).  
**Inputs**:

- `ResolvedGatewayAuth` - Configured auth mode + credentials
- `IncomingMessage` - HTTP request with headers
- `RateLimiter` - Optional rate limiter

**Outputs**:

- `GatewayAuthResult { ok, method, user, reason }`

**Auth Methods**:

1. **No auth** - Local loopback only
2. **Token** - Bearer token validation (constant-time)
3. **Password** - Basic auth password check
4. **Tailscale** - X-Tailscale-User header verification
5. **Trusted Proxy** - X-Real-IP from allowlisted proxies
6. **Device Token** - Paired device token validation

**Dependencies**:

- `src/gateway/auth-rate-limit.ts` - Rate limiting
- `src/infra/tailscale.ts` - Tailscale identity lookup
- `src/gateway/net.ts` - Client IP resolution

**Complexity**: O(1) per auth method + O(n) for Tailscale whois  
**Documentation Priority**: 🔴 HIGH - Gateway security gateway

---

### 19. Auth Rate Limiter

**File Location**: `src/gateway/auth-rate-limit.ts`  
**Purpose**: Prevent brute-force attacks through sliding window rate limiting.  
**Inputs**:

- `clientId: string` - IP or session identifier
- `scope: string` - Rate limit scope (e.g., 'shared-secret')
- `attempts: number` - Max attempts per window
- `windowMs: number` - Time window duration

**Outputs**:

- `RateLimitCheckResult { allowed, remaining, retryAfterMs }`

**Algorithm**: Sliding window counter with per-client tracking  
**Complexity**: O(1) lookup/insert with Map-based storage  
**Documentation Priority**: 🟡 MEDIUM - Security hardening

---

### 20. Client IP Resolution (Proxy-Aware)

**File Location**: `src/gateway/net.ts`  
**Purpose**: Safely resolve client IP from HTTP requests behind proxies.  
**Inputs**:

- `remoteAddr: string` - Direct connection IP
- `forwardedFor: string | undefined` - X-Forwarded-For header
- `realIp: string | undefined` - X-Real-IP header
- `trustedProxies: string[]` - Allowlisted proxy addresses

**Outputs**: `string | undefined` - Client IP or undefined if unresolvable  
**Algorithm**:

1. If remote address is trusted proxy, parse X-Forwarded-For leftmost non-trusted IP
2. If X-Real-IP enabled and remote is trusted, use X-Real-IP
3. Otherwise, use remote address

**Complexity**: O(n) where n = forwarded-for chain length  
**Documentation Priority**: 🟡 MEDIUM - Network infrastructure

---

### 21. Gateway Connection Manager

**File Location**: `src/gateway/call.ts`  
**Purpose**: Establish and manage WebSocket connections to SophiaClaw gateway.  
**Inputs**:

- `connection: GatewayConnection` - Connection details (URL, auth)
- `methods: string[]` - RPC methods to call

**Outputs**:

- `GatewayClient` - Connected client with method proxies

**Features**:

- Automatic reconnection with exponential backoff
- Request/response correlation via message IDs
- Timeout handling with abort signals

**Complexity**: O(1) connection setup + O(n) message routing  
**Documentation Priority**: 🟡 MEDIUM - Core connectivity

---

### 22. Node Registry & Invoke System

**File Location**: `src/gateway/node-registry.ts`  
**Purpose**: Manage registered nodes (sub-processes) and handle remote invocations.  
**Inputs**:

- `nodeId: string` - Node identifier
- `method: string` - Method to invoke
- `params: Record<string, unknown>` - Method parameters

**Outputs**:

- `InvokeResult` - Return value or error

**Complexity**: O(1) registration + O(n) invoke routing  
**Documentation Priority**: 🟡 MEDIUM - Distributed execution

---

## Memory & Search Systems

### 23. Fallback Memory Manager

**File Location**: `src/memory/search-manager.ts`  
**Purpose**: Primary/fallback memory backend selection with automatic failover.  
**Inputs**:

- `cfg: SophiaClawConfig` - Configuration
- `agentId: string` - Agent identifier
- `purpose: 'default' | 'status'` - Usage context

**Outputs**:

- `MemorySearchManager` - Primary or fallback manager instance

**Algorithm**:

1. Try QMD (Quadrature Memory Database) if configured
2. On failure, fall back to built-in index
3. Cache manager instances per agent + config
4. Evict cache on primary failure to enable retry

**Dependencies**:

- `src/memory/qmd-manager.ts` - QMD backend
- `src/memory/manager.ts` - Built-in index

**Complexity**: O(1) cache lookup + O(n) initialization on cache miss  
**Documentation Priority**: 🟡 MEDIUM - Resilient architecture

---

### 24. Memory Index Manager

**File Location**: `src/memory/manager.ts`  
**Purpose**: In-memory search index with embedding-based retrieval.  
**Inputs**:

- `query: string` - Search query
- `maxResults: number` - Result limit
- `minScore: number` - Minimum similarity threshold

**Outputs**:

- `MemorySearchResult[]` - Ranked results with scores

**Algorithm**:

- Vector similarity search (cosine distance)
- BM25 keyword ranking
- Recency-weighted hybrid scoring

**Complexity**: O(n × d) for n documents with d-dimensional embeddings  
**Documentation Priority**: 🔴 HIGH - Core AI memory

---

### 25. QMD Memory Backend

**File Location**: `src/memory/qmd-manager.ts`  
**Purpose**: External quadrature memory database integration for persistent, multi-agent memory.  
**Inputs**:

- `qmdConfig: ResolvedQmdConfig` - Connection settings
- `agentId: string` - Agent identifier

**Outputs**: Same as Memory Index Manager  
**Complexity**: O(log n) database queries  
**Documentation Priority**: 🟡 MEDIUM - External integration

---

### 26. Memory Backend Configuration Resolver

**File Location**: `src/memory/backend-config.ts`  
**Purpose**: Resolve memory backend from configuration with validation.  
**Inputs**: `SophiaClawConfig`  
**Outputs**: `ResolvedMemoryBackendConfig` - Normalized backend type + config  
**Complexity**: O(1) config lookup  
**Documentation Priority**: 🟢 LOW - Configuration utility

---

## Agent Management Systems

### 27. Agent Scope Resolver

**File Location**: `src/agents/agent-scope.ts`  
**Purpose**: Resolve agent identity and scope for multi-tenant deployments.  
**Inputs**:

- `env: NodeJS.ProcessEnv` - Environment variables
- `config: SophiaClawConfig` - Configuration

**Outputs**:

- `AgentScope` - Resolved agent ID, role, permissions

**Complexity**: O(1) environment/config resolution  
**Documentation Priority**: 🟡 MEDIUM - Multi-tenancy foundation

---

### 28. API Key Rotation Manager

**File Location**: `src/agents/api-key-rotation.ts`  
**Purpose**: Rotate model provider API keys on failure with cooldown management.  
**Inputs**:

- `profiles: AuthProfile[]` - Available API key profiles
- `lastFailures: Map<string, number>` - Failure timestamps

**Outputs**:

- `SelectedProfile` - Next profile to attempt
- `CooldownExpiry` - When profile becomes available again

**Algorithm**: Round-robin with exponential backoff per profile  
**Complexity**: O(n) where n = profile count  
**Documentation Priority**: 🟡 MEDIUM - Reliability subsystem

---

### 29. Auth Profile Cooldown Manager

**File Location**: `src/agents/auth-profiles.ts`  
**Purpose**: Track authentication failures and enforce cooldown periods.  
**Inputs**:

- `profileId: string` - Profile identifier
- `failureCount: number` - Consecutive failures
- `cooldownMs: number` - Cooldown duration

**Outputs**:

- `isAvailable: boolean` - Profile availability
- `retryAfterMs: number` - Time until retry allowed

**Complexity**: O(1) per profile  
**Documentation Priority**: 🟢 LOW - Supporting component

---

### 30. Bash Process Registry

**File Location**: `src/agents/bash-process-registry.ts`  
**Purpose**: Track and manage spawned bash processes for cleanup and abort.  
**Inputs**:

- `processId: string` - Unique identifier
- `process: ChildProcess` - Node.js child process

**Outputs**:

- `registered: boolean` - Registration result
- `abortSignal: AbortController` - Cancellation handle

**Complexity**: O(1) Map operations  
**Documentation Priority**: 🟢 LOW - Process management utility

---

### 31. Apply Patch Engine

**File Location**: `src/agents/apply-patch.ts`  
**Purpose**: Apply unified diff patches to files with conflict detection.  
**Inputs**:

- `patch: string` - Unified diff format
- `basePath: string` - Directory to patch

**Outputs**:

- `PatchResult` - Applied/rejected hunks with reasons

**Algorithm**:

- Parse diff headers and hunks
- Match file paths (case-insensitive on Windows)
- Apply context-aware patches with fuzz factor
- Generate reject files for failed hunks

**Complexity**: O(n × m) where n = hunks, m = file size  
**Documentation Priority**: 🟡 MEDIUM - Code modification subsystem

---

## UI/UX Components

### 32. Terminal UI Engine

**File Location**: `src/tui/tui.ts`  
**Purpose**: Interactive terminal user interface with chat, commands, and session management.  
**Inputs**:

- `GatewayChatClient` - WebSocket connection to gateway
- `config: SophiaClawConfig` - User configuration

**Outputs**:

- Interactive terminal interface ( Ink framework)
- Event stream (keypress, commands, chat messages)

**Key Components**:

- Chat log renderer with message types (text, tool, card, image)
- Custom editor with history navigation (up/down arrows)
- Slash command auto-complete
- Burst coalescing for multiline paste (50ms window)
- Waiting status messages with animated phrases

**Dependencies**: `@mariozechner/pi-tui`, `ink`, `react`  
**Complexity**: O(n) render updates where n = visible messages  
**Documentation Priority**: 🔴 HIGH - Primary CLI interface

---

### 33. Submit Burst Coalescer

**File Location**: `src/tui/tui.ts` (lines 82-180)  
**Purpose**: Combine rapid multiline paste submissions into single message on macOS terminals.  
**Inputs**:

- `submit(value: string)` - Individual text fragments
- `burstWindowMs: number` - Coalescing window (default: 50)

**Outputs**:

- Coalesced `submit(value: string)` - Single combined message

**Algorithm**: Sliding window buffer with timer-based flush  
**Complexity**: O(1) per submit  
**Documentation Priority**: 🟢 LOW - UX polish

---

### 34. OSC8 Hyperlink Renderer

**File Location**: `src/tui/osc8-hyperlinks.ts`  
**Purpose**: Render clickable links in terminal using OSC8 escape sequences.  
**Inputs**: `url: string, label: string`  
**Outputs**: ANSI escape sequence string  
**Format**: `\x1b]8;;<url>\x1b\\<label>\x1b]8;;\x1b\\`  
**Documentation Priority**: 🟢 LOW - Terminal formatting utility

---

### 35. Gateway Chat Client

**File Location**: `src/tui/gateway-chat.ts`  
**Purpose**: WebSocket chat client for gateway communication in TUI.  
**Inputs**:

- `connection: { url: string, token: string }` - Gateway details
- `sessionId: string` - Chat session identifier

**Outputs**:

- Message stream (user, assistant, tool events)
- Connection state updates

**Complexity**: O(1) message send/receive  
**Documentation Priority**: 🟢 LOW - TUI component

---

### 36. macOS SwiftUI App State

**File Location**: `apps/macos/Sources/SOPHIAClaw/Core/AppState.swift`  
**Purpose**: Centralized state management for macOS menubar app.  
**Inputs**:

- User interactions (settings, approvals, chat)
- Gateway events (connection state, messages)
- File system watcher (config changes)

**Outputs**:

- `@Published` properties trigger UI updates
- Notification center broadcasts for cross-component sync

**Key Features**:

- Connection state machine (disconnected/connecting/connected/error)
- Config file watcher using kqueue (FSEvents fallback)
- Keychain integration for secrets
- Session/policy list management

**Dependencies**: `Combine`, `AppKit`, `SOPHIAClawShared`  
**Complexity**: O(1) state updates  
**Documentation Priority**: 🔴 HIGH - Primary macOS interface

---

### 37. macOS Permission Manager

**File Location**: `apps/macos/Sources/SOPHIAClaw/Core/PermissionManager.swift`  
**Purpose**: Manage macOS system permissions (accessibility, screen recording, automation).  
**Inputs**:

- `permissionType: PermissionType` - Permission to check
- `request: Bool` - Whether to prompt user

**Outputs**:

- `permissionStatus: AuthorizationStatus` - Granted/denied/restricted  
  **Dependencies**: macOS `NSAppleEventManager`, Private frameworks  
  **Documentation Priority**: 🟡 MEDIUM - Platform-specific UX

---

### 38. macOS WebSocket Bridge

**File Locations**:

- `apps/macos/Sources/SOPHIAClaw/Services/WebSocket/WebSocketService.swift`
- `apps/macos/Sources/SOPHIAClaw/Services/Bridge/BridgeCoordinator.swift`

**Purpose**: Maintain persistent WebSocket connection to gateway for real-time updates.  
**Inputs**:

- `URLRequest` - Gateway connection details
- `WebSocketDelegate` - Message handlers

**Outputs**:

- Message events (chat, approvals, state updates)
- Connection lifecycle events (connected/disconnected/error)

**Complexity**: O(1) message routing  
**Documentation Priority**: 🟡 MEDIUM - macOS connectivity

---

## Plugin/Extension System

### 39. Plugin HTTP Auth Middleware

**File Location**: `src/gateway/server.plugin-http-auth.test.ts`  
**Purpose**: Authenticate plugin HTTP endpoints using gateway session keys.  
**Inputs**:

- `request: Request` - Incoming HTTP request
- `sessionKey: string` - Gateway session key

**Outputs**:

- `authorized: boolean` - Request validity
- `pluginId: string` - Authenticated plugin identifier

**Complexity**: O(1) token validation  
**Documentation Priority**: 🟡 MEDIUM - Plugin security

---

### 40. Channel Plugin Registry

**File Location**: `src/channels/plugins/index.ts`  
**Purpose**: Discover and enumerate installed channel plugins (Telegram, WhatsApp, etc.).  
**Inputs**: `extensionsDirectory: string`  
**Outputs**: `ChannelPlugin[]` - Plugin metadata + capabilities  
**Complexity**: O(n) directory scan + O(m) package.json parsing  
**Documentation Priority**: 🟡 MEDIUM - Plugin discovery

---

### 41. Plugin SDK Infrastructure

**File Locations**:

- `src/plugin-sdk/infra/` - Plugin infrastructure types
- `src/plugin-sdk/security/` - Plugin security primitives
- `src/plugin-sdk/gateway/` - Plugin-gateway protocol

**Purpose**: Provide TypeScript types and utilities for plugin development.  
**Key Exports**:

- `PluginManifest` - Plugin metadata schema
- `ChannelCapability` - Supported channel types
- `GatewayProtocol` - RPC method definitions

**Documentation Priority**: 🟡 MEDIUM - Developer API surface

---

### 42. Extension Entrypoint Resolver

**File Location**: `extensions/*/index.ts` (pattern across all extensions)  
**Purpose**: Standardize plugin entry points with exported `activate()` function.  
**Inputs**: `ExtensionAPI` - Provided by core  
**Outputs**: `ExtensionInstance` - Activated plugin  
**Documentation Priority**: 🟢 LOW - Plugin convention

---

## Media Processing Pipeline

### 43. Media Understanding Pipeline

**File Locations**:

- `src/media/` - Media processing utilities
- `src/media-understanding/` - AI-powered media analysis

**Purpose**: Extract semantic understanding from images, audio, and video.  
**Inputs**:

- `MediaAttachment` - File path or URL
- `mediaType: 'image' | 'audio' | 'video'`

**Outputs**:

- `MediaUnderstanding` - Captions, transcripts, object detection
- `Embedding` - Vector representation for memory storage

**Algorithms**:

- Image captioning (multimodal LLM)
- Speech-to-text (whisper.cpp / cloud APIs)
- Scene/object detection (CLIP embeddings)
- Optical character recognition (Tesseract)

**Dependencies**: External model providers, ONNX runtime  
**Complexity**: O(n) inference where n = media size  
**Documentation Priority**: 🔴 HIGH - AI capability differentiator

---

### 44. Media Attachment Normalizer

**File Location**: `src/gateway/server-methods/attachment-normalize.ts`  
**Purpose**: Normalize media attachments across channels (Telegram, WhatsApp, Discord, etc.).  
**Inputs**: `ChannelAttachment` - Platform-specific attachment  
**Outputs**: `NormalizedAttachment` - Unified schema with URLs + metadata  
**Complexity**: O(1) per attachment type  
**Documentation Priority**: 🟢 LOW - Normalization utility

---

## Cross-Platform Components

### 45. Credential Storage Abstraction

**File Location**: `src/security/credential-encryption/` (entire directory)  
**Purpose**: Unified API for secure credential storage across platforms.  
**Interface**:

```typescript
interface CredentialStorage {
  save(key: string, value: string): Promise<void>;
  load(key: string): Promise<string | null>;
  delete(key: string): Promise<void>;
}
```

**Implementations**:

- Darwin: macOS Keychain (Security.framework)
- Windows: Credential Manager (Advapi32.dll)
- Linux: libsecret (GNOME Keyring / KWallet)
- Fallback: AES-256-GCM encrypted JSON file

**Documentation Priority**: 🔴 HIGH - Cross-platform security

---

### 46. Platform Detection Utilities

**File Location**: `src/infra/platform.ts` (if exists), `src/shared/platform.ts`  
**Purpose**: Detect OS, architecture, and runtime environment.  
**Outputs**:

- `platform: 'darwin' | 'linux' | 'win32'`
- `arch: 'x64' | 'arm64'`
- `isRosetta: boolean` - macOS ARM translation detection

**Documentation Priority**: 🟢 LOW - Utility module

---

### 47. Homebrew Integration

**File Location**: `src/infra/brew.ts`  
**Purpose**: Interact with Homebrew package manager on macOS/Linux.  
**Inputs**:

- `formula: string` - Package name
- `action: 'install' | 'uninstall' | 'list'`

**Outputs**:

- `BrewResult` - Success/failure + output

**Dependencies**: `brew` command-line tool  
**Complexity**: O(n) package installation time  
**Documentation Priority**: 🟢 LOW - Platform utility

---

### 48. System Presence Detector

**File Location**: `src/infra/system-presence.ts`  
**Purpose**: Check for required system dependencies (Node.js, Docker, Git, etc.).  
**Inputs**: `dependency: string` - Tool to detect  
**Outputs**: `PresenceResult { installed, version, path }`  
**Complexity**: O(1) which/where.exe lookup  
**Documentation Priority**: 🟢 LOW - Bootstrap utility

---

## Summary by Documentation Priority

### 🔴 HIGH Priority (Critical for Open Source)

1. Circuit Breaker Pattern - Resilience architecture
2. Device Pairing Protocol - Security-critical auth
3. Command Execution Approval - AI safety core
4. SSRF Protection - Network security
5. Security Audit Engine - User-facing tool
6. Constant-Time Secret Comparison - Security primitive
7. Credential Encryption - Cross-platform security
8. Gateway Authentication Router - Access control
9. Memory Index Manager - AI memory core
10. Terminal UI Engine - Primary CLI interface
11. macOS AppState - Primary macOS interface
12. Media Understanding Pipeline - AI capability
13. Credential Storage Abstraction - Platform abstraction

### 🟡 MEDIUM Priority (Important Supporting Systems)

1. Log Integrity Hashing - Audit immutability
2. DNS-SD Gateway Discovery - Zero-config networking
3. Filesystem Permission Inspector - Security auditing
4. Dangerous Config Detection - Audit component
5. Scope Implication Engine - Authorization
6. Auth Rate Limiter - Brute-force protection
7. Client IP Resolution - Proxy handling
8. Gateway Connection Manager - Connectivity
9. Fallback Memory Manager - Resilience
10. Auth Profile Cooldown - Reliability
11. Apply Patch Engine - Code modification
12. macOS Permission Manager - Platform integration
13. macOS WebSocket Bridge - App connectivity
14. Plugin HTTP Auth - Plugin security
15. Channel Plugin Registry - Plugin discovery

### 🟢 LOW Priority (Utilities & Internal Components)

1. Abort Pattern Matching
2. Session Key Normalization
3. Memory Backend Config Resolver
4. Auth Profile Cooldown Manager
5. Bash Process Registry
6. OSC8 Hyperlink Renderer
7. Gateway Chat Client (TUI)
8. Extension Entrypoint Resolver
9. Media Attachment Normalizer
10. Platform Detection Utilities
11. Homebrew Integration
12. System Presence Detector

---

## Documentation Guidelines

### For Each Algorithm

1. **Conceptual Overview**: What problem does this solve?
2. **Architecture Diagram**: Visual representation of data flow
3. **API Reference**: Function signatures with types
4. **Usage Examples**: Practical code examples
5. **Error Handling**: Failure modes and recovery
6. **Security Considerations**: Threat model and mitigations
7. **Performance Characteristics**: Big-O complexity, benchmarks
8. **Testing Strategy**: Unit, integration, E2E test coverage

### Cross-Cutting Concerns

- **Security**: All authentication/authorization flows need threat modeling
- **Multi-Platform**: Document platform-specific behavior differences
- **Backwards Compatibility**: Note breaking changes between versions
- **Configuration**: Document all config flags and environment variables

---

## Next Steps

1. **Prioritize HIGH priority items** for initial documentation pack
2. **Create architecture diagrams** for top 5 systems
3. **Write user guides** for Security Audit, Device Pairing, TUI
4. **Generate API documentation** from TypeScript types (TypeDoc)
5. **Add code comments** to algorithms missing JSDoc
6. **Create examples repository** with usage patterns
7. **Record demo videos** for UI/UX components

---

_Generated: 2026-03-11 | SophiaClaw Open Source Documentation Initiative_
