# Sr. Fullstack Developer Perspective

## Codebase Analysis & Implementation Recommendations

### 1. Three Use Cases & Onboarding Framework

**Current Implementation:** `src/wizard/onboarding.ts` (467 lines)

**Code Issues:**

1. **Monolithic Function**: `runOnboardingWizard()` does too much
2. **Tight Coupling**: Hardcoded step sequence
3. **Missing Abstraction**: No persona detection or flow customization

**Refactoring Plan:**

#### Step 1: Extract Persona Detection

```typescript
// src/wizard/persona-detector.ts
export interface UserPersona {
  type: "developer" | "hybrid" | "enduser";
  technicalLevel: number;
  preferredInterface: "cli" | "gui" | "both";
  automationPreference: boolean;
}

export async function detectUserPersona(env: RuntimeEnv): Promise<UserPersona> {
  // Analyze CLI history, environment, user responses
  // Return appropriate persona
}
```

#### Step 2: Create Flow Registry

```typescript
// src/wizard/flow-registry.ts
export interface OnboardingStep {
  id: string;
  title: string;
  description: string;
  requiredFor: UserPersona['type'][];
  execute: (context: OnboardingContext) => Promise<void>;
}

export class FlowRegistry {
  private steps: Map<string, OnboardingStep> = new Map();

  registerStep(step: OnboardingStep): void { ... }

  getFlowForPersona(persona: UserPersona): OnboardingStep[] {
    return Array.from(this.steps.values())
      .filter(step => step.requiredFor.includes(persona.type))
      .sort((a, b) => a.order - b.order);
  }
}
```

#### Step 3: Configuration Sync Service

```typescript
// src/config/sync-service.ts
export class ConfigSyncService {
  async syncCliToDesktop(cliConfig: SophiaClawConfig): Promise<void> { ... }
  async syncDesktopToCli(desktopConfig: any): Promise<void> { ... }
  async detectConflicts(): Promise<Conflict[]> { ... }
  async resolveConflict(conflict: Conflict): Promise<void> { ... }
}
```

**Estimated Effort:** 2-3 weeks refactoring

### 2. Log Storage Optimization

**Current Implementation:** `src/config/sessions/transcript.ts`

**Performance Issues:**

1. **Synchronous File Operations**: Blocking I/O in critical path
2. **No Compression**: Large session files consume disk space
3. **Linear Search**: O(n) lookup for session metadata

**Optimization Implementation:**

#### Content Hashing

```typescript
// src/config/sessions/integrity.ts
import { createHash } from "node:crypto";

export function hashSessionEntry(entry: SessionEntry): string {
  const serialized = JSON.stringify(entry);
  return createHash("sha256").update(serialized).digest("hex");
}

export function verifySessionIntegrity(entry: SessionEntry, expectedHash: string): boolean {
  return hashSessionEntry(entry) === expectedHash;
}
```

#### Compression Pipeline

```typescript
// src/config/sessions/compression.ts
import { createGzip, createGunzip } from "node:zlib";
import { pipeline } from "node:stream/promises";

export async function compressSession(
  sessionId: string,
  options?: { level?: number },
): Promise<void> {
  const inputPath = getSessionPath(sessionId);
  const outputPath = `${inputPath}.gz`;

  await pipeline(
    fs.createReadStream(inputPath),
    createGzip({ level: options?.level || 6 }),
    fs.createWriteStream(outputPath),
  );

  // Replace original with compressed
  await fs.rename(outputPath, inputPath);
}
```

#### Indexed Lookup

```typescript
// src/config/sessions/index.ts
import Database from 'better-sqlite3';

export class SessionIndex {
  private db: Database.Database;

  constructor() {
    this.db = new Database(':memory:'); // or persistent file
    this.initializeSchema();
  }

  private initializeSchema(): void {
    this.db.exec(`
      CREATE TABLE IF NOT EXISTS sessions (
        id TEXT PRIMARY KEY,
        agent_id TEXT NOT NULL,
        created_at INTEGER NOT NULL,
        last_accessed INTEGER NOT NULL,
        size_bytes INTEGER NOT NULL,
        compressed BOOLEAN DEFAULT FALSE,
        hash TEXT,
        metadata JSON
      );

      CREATE INDEX IF NOT EXISTS idx_sessions_agent_time
      ON sessions(agent_id, created_at);
    `);
  }

  async addSession(session: SessionMetadata): Promise<void> { ... }
  async findSessionsByAgent(
    agentId: string,
    timeRange?: { start: Date; end: Date }
  ): Promise<SessionMetadata[]> { ... }
}
```

**Performance Targets:**

- Session lookup: <10ms p95
- Compression ratio: 70%+ for text logs
- Memory usage: <50MB for index

### 3. Performance, Resource Usage & Circuit Breakers

**Code Analysis Findings:**

#### Existing Strengths

- Good async/await patterns
- Gateway timeout handling
- Exponential backoff in `waitForGatewayReachable()`

#### Critical Gaps

1. **No Central Error Handling**: Ad-hoc try/catch blocks
2. **Resource Leaks**: Unclosed file descriptors, database connections
3. **Missing Circuit Breakers**: For external API calls

**Implementation Plan:**

#### Central Error Handler

```typescript
// src/errors/handler.ts
export class ErrorHandler {
  static async handle(error: unknown, context: ErrorContext): Promise<HandledError> {
    // Log structured error
    // Determine recovery strategy
    // Return user-friendly message
    // Potentially retry or circuit break
  }

  static wrapAsync<T>(fn: () => Promise<T>, context: ErrorContext): Promise<T> {
    try {
      return await fn();
    } catch (error) {
      return this.handle(error, context);
    }
  }
}
```

#### Resource Monitor

```typescript
// src/monitoring/resource-monitor.ts
export class ResourceMonitor {
  private fileDescriptors: Set<number> = new Set();
  private memoryUsage: NodeJS.MemoryUsage;

  trackFileDescriptor(fd: number): void {
    this.fileDescriptors.add(fd);
    if (this.fileDescriptors.size > 1000) {
      this.alert("High file descriptor count");
    }
  }

  releaseFileDescriptor(fd: number): void {
    this.fileDescriptors.delete(fd);
  }

  checkMemory(): void {
    this.memoryUsage = process.memoryUsage();
    if (this.memoryUsage.heapUsed > 500 * 1024 * 1024) {
      // 500MB
      this.alert("High memory usage");
    }
  }
}
```

#### Circuit Breaker Service

```typescript
// src/resilience/circuit-breaker.ts
import { CircuitBreaker } from "opossum";

export class CircuitBreakerService {
  private breakers: Map<string, CircuitBreaker> = new Map();

  async executeWithBreaker<T>(
    service: string,
    operation: string,
    fn: () => Promise<T>,
    options?: CircuitBreakerOptions,
  ): Promise<T> {
    let breaker = this.breakers.get(`${service}:${operation}`);
    if (!breaker) {
      breaker = new CircuitBreaker(fn, {
        timeout: options?.timeout || 30000,
        errorThresholdPercentage: options?.errorThreshold || 50,
        resetTimeout: options?.resetTimeout || 60000,
      });
      this.breakers.set(`${service}:${operation}`, breaker);
    }

    return breaker.fire();
  }
}
```

### 4. Security of Access Keys, Secrets & Permissions

**Code Vulnerabilities:**

#### 1. Plaintext Credential Storage

**File:** `src/infra/keychain.ts` (only macOS keychain)

**Fix:** Universal encryption layer

```typescript
// src/security/credential-encryption.ts
export async function encryptCredential(
  plaintext: string,
  keyId: string = "default",
): Promise<EncryptedCredential> {
  const key = await getEncryptionKey(keyId);
  const iv = crypto.randomBytes(12);
  const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);

  const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);

  const authTag = cipher.getAuthTag();

  return {
    encrypted: encrypted.toString("base64"),
    iv: iv.toString("base64"),
    authTag: authTag.toString("base64"),
    keyId,
    algorithm: "aes-256-gcm",
  };
}
```

#### 2. Missing Input Validation

**Fix:** Comprehensive validation layer

```typescript
// src/security/input-validation.ts
import { z } from "zod";

export const ToolCallSchema = z.object({
  toolName: z.string().min(1).max(100),
  parameters: z.record(z.any()),
  sessionId: z.string().uuid(),
  // ... validation rules
});

export function validateToolCall(input: unknown): ValidatedToolCall {
  return ToolCallSchema.parse(input);
}
```

#### 3. Secret Leakage in Logs

**Fix:** Automatic redaction

```typescript
// src/security/log-redaction.ts
const SENSITIVE_PATTERNS = [
  /sk-[a-zA-Z0-9]{20,}/,
  /Bearer [a-zA-Z0-9._-]+/,
  /password=["']?[^"'\s]+["']?/i,
  /api[_-]?key=["']?[^"'\s]+["']?/i,
];

export function redactSecrets(text: string): string {
  let redacted = text;
  for (const pattern of SENSITIVE_PATTERNS) {
    redacted = redacted.replace(pattern, "[REDACTED]");
  }
  return redacted;
}
```

### 5. UI/UX Text Cleanup

**Implementation Status:** Already fixed in source

**Remaining Tasks:**

1. Rebuild distribution files
2. Verify all compiled assets updated
3. Add lint rule to prevent generic text

### 6. Model Orchestrator Configuration

**Current Code:** `src/commands/auth-choice.apply.openrouter.ts`

**Enhancements Needed:**

#### Desktop App Integration

```typescript
// apps/shared/Sources/SOPHIAClawShared/Models/ModelConfiguration.swift
struct ModelConfiguration: Codable {
  var provider: String
  var model: String
  var apiKey: String?
  var customEndpoint: URL?

  static func fromCliConfig(_ config: SophiaClawConfig) -> ModelConfiguration {
    // Convert CLI config to desktop app format
  }

  func toCliConfig() -> SophiaClawConfig {
    // Convert desktop config to CLI format
  }
}
```

#### Configuration Sync

```typescript
// src/config/model-sync.ts
export async function syncModelConfiguration(
  source: "cli" | "desktop",
  target: "cli" | "desktop",
): Promise<void> {
  // Read config from source
  // Transform to target format
  // Write to target
  // Verify synchronization
}
```

## Development Workflow Recommendations

### 1. Testing Strategy

- **Unit Tests**: 80%+ coverage for new code
- **Integration Tests**: Cross-component testing
- **E2E Tests**: Full onboarding flow testing

### 2. Code Quality

- **TypeScript Strict Mode**: Enable for all new files
- **Linting**: Oxlint with custom security rules
- **Code Review**: Security-focused reviews for sensitive code

### 3. Performance Monitoring

- **Benchmarks**: Establish performance baselines
- **Profiling**: Regular performance profiling
- **Memory Analysis**: Leak detection in CI/CD

## Implementation Timeline

### Sprint 1 (2 weeks)

- Persona detection MVP
- Content hashing for logs
- Central error handler

### Sprint 2 (2 weeks)

- Compression pipeline
- Resource monitor
- Input validation layer

### Sprint 3 (2 weeks)

- Circuit breaker service
- Credential encryption
- Configuration sync

### Sprint 4 (2 weeks)

- Performance optimization
- Security hardening
- Testing coverage

## Success Metrics

1. **Code Quality**: 0 critical SonarQube issues
2. **Performance**: <100ms p95 for critical operations
3. **Security**: 0 high-risk vulnerabilities
4. **Test Coverage**: 80%+ line coverage
5. **Technical Debt**: <5% code duplication
