Skip to content

CEO Basic Implementation Guide ​

Practical implementation of CEO (Context/Execution Orchestrator) core functionality for v0. Focus on intent parsing and budget allocation without advanced cognitive features.

Implementation Goals (v0) ​

βœ… In Scope:

  • Parse user query into structured intent
  • Allocate basic computational budget
  • Route to ACS for provider selection
  • Handle basic error cases

❌ Out of Scope (v1):

  • Advanced cognitive load management
  • User preference learning
  • Complex risk assessment
  • Metacognitive reasoning

30-Minute Implementation ​

Step 1: Core Types (5 minutes) ​

typescript
// types/ceo.ts
export interface UserQuery {
  text: string;
  user_id?: string;
  session_id?: string;
  context?: Record<string, any>;
}

export interface ParsedIntent {
  primary_goal: string;
  domain: 'code' | 'documentation' | 'research' | 'general';
  complexity: 'simple' | 'medium' | 'complex';
  urgency: 'low' | 'medium' | 'high';
  keywords: string[];
}

export interface ResourceBudget {
  max_latency_ms: number;
  max_cost_cents: number;
  quality_threshold: number; // 0.0-1.0
  max_providers: number;
}

export interface CEORequest {
  query: UserQuery;
  intent: ParsedIntent;
  budget: ResourceBudget;
  request_id: string;
  timestamp: Date;
}

Step 2: Intent Parser (10 minutes) ​

typescript
// services/intent-parser.ts
export class BasicIntentParser {
  private domainKeywords = {
    code: ['function', 'class', 'bug', 'error', 'debug', 'implement', 'refactor'],
    documentation: ['docs', 'readme', 'guide', 'tutorial', 'explain', 'how to'],
    research: ['research', 'papers', 'analysis', 'study', 'comparison', 'evaluation'],
    general: [] // fallback
  };

  private complexityIndicators = {
    simple: ['what is', 'how to', 'example', 'quick'],
    medium: ['implement', 'create', 'build', 'design'],
    complex: ['architecture', 'system', 'optimize', 'scale', 'integrate']
  };

  private urgencyIndicators = {
    high: ['urgent', 'asap', 'critical', 'immediately', 'broken', 'down'],
    medium: ['soon', 'today', 'important'],
    low: ['eventually', 'when possible', 'research']
  };

  parseIntent(query: UserQuery): ParsedIntent {
    const text = query.text.toLowerCase();
    const words = text.split(/\s+/);

    return {
      primary_goal: this.extractPrimaryGoal(text),
      domain: this.classifyDomain(text, words),
      complexity: this.assessComplexity(text, words),
      urgency: this.assessUrgency(text, words),
      keywords: this.extractKeywords(words)
    };
  }

  private extractPrimaryGoal(text: string): string {
    // Simple goal extraction - can be enhanced later
    const actionWords = ['find', 'create', 'debug', 'implement', 'explain', 'analyze'];
    
    for (const action of actionWords) {
      if (text.includes(action)) {
        return action;
      }
    }
    
    return 'search'; // default
  }

  private classifyDomain(text: string, words: string[]): ParsedIntent['domain'] {
    let bestDomain: ParsedIntent['domain'] = 'general';
    let maxScore = 0;

    for (const [domain, keywords] of Object.entries(this.domainKeywords)) {
      const score = keywords.filter(keyword => text.includes(keyword)).length;
      if (score > maxScore) {
        maxScore = score;
        bestDomain = domain as ParsedIntent['domain'];
      }
    }

    return bestDomain;
  }

  private assessComplexity(text: string, words: string[]): ParsedIntent['complexity'] {
    // Check for complexity indicators
    for (const [level, indicators] of Object.entries(this.complexityIndicators)) {
      if (indicators.some(indicator => text.includes(indicator))) {
        return level as ParsedIntent['complexity'];
      }
    }

    // Fallback: word count heuristic
    if (words.length > 20) return 'complex';
    if (words.length > 10) return 'medium';
    return 'simple';
  }

  private assessUrgency(text: string, words: string[]): ParsedIntent['urgency'] {
    for (const [level, indicators] of Object.entries(this.urgencyIndicators)) {
      if (indicators.some(indicator => text.includes(indicator))) {
        return level as ParsedIntent['urgency'];
      }
    }
    
    return 'medium'; // default
  }

  private extractKeywords(words: string[]): string[] {
    // Simple keyword extraction - filter common words
    const stopWords = new Set(['the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by', 'is', 'are', 'was', 'were']);
    
    return words
      .filter(word => word.length > 3 && !stopWords.has(word))
      .slice(0, 10); // limit keywords
  }
}

Step 3: Budget Allocator (10 minutes) ​

typescript
// services/budget-allocator.ts
export class BasicBudgetAllocator {
  private defaultBudgets = {
    simple: {
      max_latency_ms: 2000,
      max_cost_cents: 5,
      quality_threshold: 0.7,
      max_providers: 1
    },
    medium: {
      max_latency_ms: 5000,
      max_cost_cents: 15,
      quality_threshold: 0.8,
      max_providers: 2
    },
    complex: {
      max_latency_ms: 10000,
      max_cost_cents: 50,
      quality_threshold: 0.85,
      max_providers: 3
    }
  };

  private urgencyModifiers = {
    low: { latency: 2.0, cost: 0.5 },    // More time, less cost
    medium: { latency: 1.0, cost: 1.0 }, // Base values
    high: { latency: 0.5, cost: 2.0 }    // Less time, more cost
  };

  allocateBudget(intent: ParsedIntent, userPrefs?: Record<string, any>): ResourceBudget {
    // Start with base budget for complexity level
    const baseBudget = { ...this.defaultBudgets[intent.complexity] };
    
    // Apply urgency modifiers
    const modifier = this.urgencyModifiers[intent.urgency];
    baseBudget.max_latency_ms *= modifier.latency;
    baseBudget.max_cost_cents *= modifier.cost;

    // Apply domain-specific adjustments
    this.applyDomainAdjustments(baseBudget, intent.domain);

    // Apply user preferences if available
    if (userPrefs) {
      this.applyUserPreferences(baseBudget, userPrefs);
    }

    // Ensure reasonable bounds
    return this.validateBudget(baseBudget);
  }

  private applyDomainAdjustments(budget: ResourceBudget, domain: ParsedIntent['domain']): void {
    const domainMultipliers = {
      code: { latency: 1.2, cost: 1.1, quality: 1.05, providers: 1.0 },
      documentation: { latency: 0.8, cost: 0.9, quality: 0.95, providers: 1.0 },
      research: { latency: 1.5, cost: 1.3, quality: 1.1, providers: 1.2 },
      general: { latency: 1.0, cost: 1.0, quality: 1.0, providers: 1.0 }
    };

    const multipliers = domainMultipliers[domain];
    budget.max_latency_ms *= multipliers.latency;
    budget.max_cost_cents *= multipliers.cost;
    budget.quality_threshold *= multipliers.quality;
    budget.max_providers = Math.ceil(budget.max_providers * multipliers.providers);
  }

  private applyUserPreferences(budget: ResourceBudget, prefs: Record<string, any>): void {
    // Apply user-specific overrides
    if (prefs.prefer_speed) {
      budget.max_latency_ms *= 0.7;
      budget.max_cost_cents *= 1.2;
    }
    
    if (prefs.prefer_quality) {
      budget.quality_threshold = Math.min(0.95, budget.quality_threshold * 1.1);
      budget.max_cost_cents *= 1.3;
    }
    
    if (prefs.prefer_cost) {
      budget.max_cost_cents *= 0.8;
      budget.max_latency_ms *= 1.3;
    }
  }

  private validateBudget(budget: ResourceBudget): ResourceBudget {
    return {
      max_latency_ms: Math.max(1000, Math.min(30000, budget.max_latency_ms)),
      max_cost_cents: Math.max(1, Math.min(200, budget.max_cost_cents)),
      quality_threshold: Math.max(0.5, Math.min(0.95, budget.quality_threshold)),
      max_providers: Math.max(1, Math.min(5, budget.max_providers))
    };
  }
}

Step 4: CEO Main Service (5 minutes) ​

typescript
// services/ceo.ts
import { v4 as uuidv4 } from 'uuid';
import { BasicIntentParser } from './intent-parser';
import { BasicBudgetAllocator } from './budget-allocator';

export class BasicCEO {
  private intentParser: BasicIntentParser;
  private budgetAllocator: BasicBudgetAllocator;

  constructor() {
    this.intentParser = new BasicIntentParser();
    this.budgetAllocator = new BasicBudgetAllocator();
  }

  async processQuery(query: UserQuery): Promise<CEORequest> {
    try {
      // Parse user intent
      const intent = this.intentParser.parseIntent(query);
      
      // Allocate resources
      const budget = this.budgetAllocator.allocateBudget(intent);

      // Create structured request
      const request: CEORequest = {
        query,
        intent,
        budget,
        request_id: uuidv4(),
        timestamp: new Date()
      };

      return request;
      
    } catch (error) {
      throw new Error(`CEO processing failed: ${error.message}`);
    }
  }

  async healthCheck(): Promise<boolean> {
    // Basic health check
    try {
      const testQuery: UserQuery = { text: "test query" };
      const result = await this.processQuery(testQuery);
      return !!result.request_id;
    } catch {
      return false;
    }
  }
}

Usage Examples ​

Basic Usage ​

typescript
import { BasicCEO } from './services/ceo';

const ceo = new BasicCEO();

// Process user query
const query: UserQuery = {
  text: "Help me debug this authentication bug in my React app",
  user_id: "user123",
  session_id: "session456"
};

const request = await ceo.processQuery(query);

console.log('Intent:', request.intent);
// Output: { primary_goal: 'debug', domain: 'code', complexity: 'medium', urgency: 'medium', keywords: [...] }

console.log('Budget:', request.budget);
// Output: { max_latency_ms: 5000, max_cost_cents: 16, quality_threshold: 0.8, max_providers: 2 }

Integration with ACS ​

typescript
// In your orchestration pipeline
async function handleUserQuery(queryText: string) {
  const ceo = new BasicCEO();
  const acs = new BasicACS(); // ACS implementation
  
  // CEO processes intent and budget
  const ceoRequest = await ceo.processQuery({ text: queryText });
  
  // ACS uses CEO output for provider selection
  const acsRequest = {
    intent: ceoRequest.intent,
    budget: ceoRequest.budget,
    request_id: ceoRequest.request_id
  };
  
  const result = await acs.executeRequest(acsRequest);
  
  return {
    request_id: ceoRequest.request_id,
    result: result,
    metadata: {
      intent: ceoRequest.intent,
      budget_used: result.cost_cents
    }
  };
}

Testing Your Implementation ​

Unit Tests ​

typescript
import { BasicCEO } from '../services/ceo';

describe('BasicCEO', () => {
  let ceo: BasicCEO;
  
  beforeEach(() => {
    ceo = new BasicCEO();
  });

  test('should parse simple code query', async () => {
    const query = { text: "How do I create a React component?" };
    const result = await ceo.processQuery(query);
    
    expect(result.intent.domain).toBe('code');
    expect(result.intent.complexity).toBe('simple');
    expect(result.budget.max_latency_ms).toBeLessThan(5000);
  });

  test('should handle complex urgent queries', async () => {
    const query = { text: "Critical bug in production authentication system architecture" };
    const result = await ceo.processQuery(query);
    
    expect(result.intent.complexity).toBe('complex');
    expect(result.intent.urgency).toBe('high');
    expect(result.budget.max_latency_ms).toBeLessThan(8000); // Reduced for urgency
  });

  test('should perform health check', async () => {
    const isHealthy = await ceo.healthCheck();
    expect(isHealthy).toBe(true);
  });
});

Integration Test ​

typescript
test('CEO + ACS integration', async () => {
  const ceo = new BasicCEO();
  const query = { text: "Find React testing best practices" };
  
  const ceoRequest = await ceo.processQuery(query);
  
  // Verify CEO output is suitable for ACS
  expect(ceoRequest.intent.domain).toBeDefined();
  expect(ceoRequest.budget.max_cost_cents).toBeGreaterThan(0);
  expect(ceoRequest.request_id).toBeDefined();
});

Next Steps ​

  1. Enhance Intent Parsing: Add more sophisticated NLP
  2. User Preferences: Implement user preference learning
  3. A/B Testing: Test different budget allocation strategies
  4. Monitoring: Add metrics and logging
  5. Error Recovery: Implement robust error handling

Common Issues & Debugging ​

Issue: Intent misclassification ​

Solution: Check domain keywords and add more training data

Issue: Budget allocation too restrictive ​

Solution: Review complexity multipliers and urgency modifiers

Issue: Performance problems ​

Solution: Cache parsed intents and optimize keyword matching


Next: ACS Basic Implementation β†’