Intelligence Coordination System

Central intelligence system that coordinates all AI operations across the monorepo

Intelligence Coordination System

The Intelligence Coordination System is the central brain of the GoGrab AI library. It coordinates all AI operations, integrates deeply with storage-system, prompt-system, and theme-system, and enables team-wide learning through MongoDB sync.

Overview

The Intelligence Coordinator acts as the central orchestrator for all AI generation requests. Instead of calling AI providers directly, components interact with the coordinator, which:

  1. Analyzes the request - Understands what needs to be generated
  2. Builds platform context - Knows all available widgets, themes, storage schemas
  3. Selects optimal AI model - Uses the AI Orchestrator for intelligent routing
  4. Enhances with context - Adds theme utilities, component patterns, best practices
  5. Generates production code - Creates complete, tested, documented code
  6. Stores learnings - Saves patterns for team-wide improvement

Architecture

┌─────────────────────────────────────────────────────────────┐
│                  Intelligence Coordinator                     │
│                                                               │
│  ┌────────────┐  ┌────────────┐  ┌────────────┐            │
│  │  Platform  │  │   AI       │  │  Adaptive  │            │
│  │  Context   │  │ Storage    │  │  Prompts   │            │
│  └────────────┘  └────────────┘  └────────────┘            │
│                                                               │
│  ┌────────────────────────────────────────────────────────┐ │
│  │           AI Orchestrator (Model Selection)            │ │
│  └────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
                              │
                ┌─────────────┼─────────────┐
                │             │             │
            ┌───▼───┐     ┌───▼───┐     ┌──▼────┐
            │OpenAI │     │Claude │     │Gemini │
            └───────┘     └───────┘     └───────┘

Core Components

1. Intelligence Coordinator Service

The main orchestrator that coordinates all generation requests.

import { inject } from '@angular/core';
import {
  IntelligenceCoordinatorService,
  GenerationRequest
} from '@gograb-ai';

const coordinator = inject(IntelligenceCoordinatorService);

// Define what you want to generate
const request: GenerationRequest = {
  type: 'component',
  description: 'Create a user profile card with stats and avatar',
  context: {
    targetType: 'component',
    complexity: 'simple',
    userIntent: 'display user information with visual stats'
  },
  features: ['theme', 'storage', 'responsive'],
  requirements: {
    useTheme: true,
    useStorage: true,
    useAuth: false,
    responsive: true,
    accessibility: 'aa',
    includeTests: true,
    includeMockApi: true
  }
};

// Generate
coordinator.coordinateGeneration(request).subscribe(result => {
  console.log('Generated component:', result.code);
  console.log('Mock API:', result.mockApi);
  console.log('Tests:', result.tests);
  console.log('Confidence:', result.confidence);
});

2. Platform Context

The system builds and maintains a complete understanding of your platform:

interface PlatformContext {
  widgets: WidgetRegistry;           // All available widgets
  components: ComponentRegistry;     // Reusable components
  themes: ThemeRegistry;            // Theme utilities and patterns
  storage: StorageRegistry;         // Storage schemas
  routes: RouteRegistry;            // Route patterns
  patterns: PatternLibrary;         // Design and code patterns
  utilities: UtilityRegistry;       // Utility classes
}

The coordinator scans your codebase to understand:

This knowledge is used to generate code that fits perfectly into your existing ecosystem.

3. AI Storage Service

Provides intelligent storage for AI data with MongoDB integration:

import { inject } from '@angular/core';
import { AIStorageService } from '@gograb-ai';

const aiStorage = inject(AIStorageService);

// Store generation with user feedback
await aiStorage.storeGenerationWithLearning(generation, {
  rating: 4.5,
  modifications: [
    {
      type: 'modification',
      location: 'component.ts line 15',
      before: 'this.data = data;',
      after: 'this.data = signal(data);',
      reason: 'Use signal for reactive state'
    }
  ]
});

// Find similar generations using vector search
const similar = await aiStorage.findSimilarGenerations(
  'user profile card with stats',
  { threshold: 0.8, limit: 5 }
);

// Search team knowledge
const knowledge = await aiStorage.searchTeamKnowledge(
  'best practices for user profiles',
  { limit: 10 }
);

4. Adaptive Prompt Service

Makes prompts intelligent by learning which work best:

import { inject } from '@angular/core';
import { AdaptivePromptService } from '@gograb-ai';

const adaptivePrompt = inject(AdaptivePromptService);

// Select optimal prompt for context
const prompt = await adaptivePrompt.selectOptimalPrompt(
  {
    targetType: 'widget',
    complexity: 'simple',
    userIntent: 'Create a button',
    features: ['theme']
  },
  'Create a primary action button'
);

// Record success for learning
await adaptivePrompt.recordPromptSuccess(
  prompt,
  generation,
  4.5 // user rating
);

// Get statistics
const stats = adaptivePrompt.getPromptStatistics();
console.log('Average success rate:', stats.averageSuccessRate);
console.log('Best category:', stats.bestPerformingCategory);

Features

Context-Aware Generation

The coordinator understands your platform and generates code that fits:

// Automatically knows to:
// - Use .ux-* utility classes from theme-system
// - Inject StorageService when useStorage: true
// - Apply glass-card pattern for admin interfaces
// - Include proper accessibility attributes
// - Generate responsive designs
// - Create vitest tests

const result = await coordinator.coordinateGeneration({
  type: 'widget',
  description: 'Admin panel card with stats',
  context: { targetType: 'widget', complexity: 'simple' },
  features: ['theme', 'storage'],
  requirements: {
    useTheme: true,
    useStorage: true,
    responsive: true,
    accessibility: 'aa',
    includeTests: true
  }
});

// Generated code uses:
// - glass-card utility class
// - StorageService integration
// - Proper responsive breakpoints
// - WCAG AA compliance
// - Complete unit tests

Team Learning

All learnings are stored in MongoDB and shared across the team:

// User A generates a component and provides feedback
await aiStorage.storeCodeLearning({
  id: 'learning-1',
  originalCode: '...',
  originalPattern: 'user-card',
  userModifications: [...],
  improvement: {
    type: 'performance-optimization',
    description: 'Use signal instead of direct assignment',
    impactLevel: 'moderate',
    applicableTo: ['component'],
    confidence: 0.85
  },
  vectorEmbedding: [...],
  confidence: 0.85,
  timestamp: Date.now(),
  sharedWithTeam: true
});

// User B's generation automatically benefits
const learnings = await aiStorage.findApplicableLearnings(
  'creating user card component',
  10
);
// Returns relevant learnings from User A and others

Intelligent Model Selection

The coordinator uses the AI Orchestrator to select the optimal model:

// Automatically analyzes:
// - Task type (code generation, review, documentation)
// - Complexity (simple, moderate, complex, expert)
// - Required capabilities (reasoning, long context, etc.)
// - Performance requirements (speed, quality, cost)
// - Token count estimation

// Selects best model:
// - Claude Sonnet for complex reasoning
// - GPT-4 Turbo for fast iterations
// - Claude Haiku for simple tasks
// - Gemini Pro for long context

// With automatic fallback on errors

Storage Integration

Deep integration with storage-system:

// Storage configuration
const config = {
  databases: {
    context: {
      name: 'ai-context',
      priority: 'high',
      sync: 'offline-first',
      ttl: 3600000 // 1 hour
    },
    learning: {
      name: 'ai-learning',
      priority: 'normal',
      sync: 'online-first',
      enableVectorSearch: true
    },
    generations: {
      name: 'ai-generations',
      priority: 'normal',
      sync: 'offline-first',
      versioning: true
    },
    prompts: {
      name: 'ai-prompts',
      priority: 'high',
      sync: 'online-first'
    }
  }
};

Usage Examples

Generate a Widget

const result = await coordinator.coordinateGeneration({
  type: 'widget',
  description: 'User stats card showing followers, posts, and likes',
  context: {
    targetType: 'widget',
    complexity: 'simple',
    userIntent: 'display user statistics in a card format'
  },
  features: ['theme', 'responsive'],
  requirements: {
    useTheme: true,
    useStorage: false,
    responsive: true,
    accessibility: 'aa',
    includeTests: true
  }
});

// Result contains:
// - component.ts (with signals, inject pattern)
// - component.html (with utility classes)
// - component.scss (minimal, utilities handle most)
// - component.spec.ts (vitest unit tests)

Generate a Component with Storage

const result = await coordinator.coordinateGeneration({
  type: 'component',
  description: 'User management table with CRUD operations',
  context: {
    targetType: 'component',
    complexity: 'intermediate',
    userIntent: 'manage users with full CRUD'
  },
  features: ['theme', 'storage', 'crud'],
  requirements: {
    useTheme: true,
    useStorage: true,
    responsive: true,
    accessibility: 'aa',
    includeTests: true,
    includeMockApi: true
  }
});

// Result includes:
// - Full CRUD component with StorageService
// - Mock API endpoints for testing
// - Storage schema definition
// - Complete unit tests

Generate a Page

const result = await coordinator.coordinateGeneration({
  type: 'page',
  description: 'Dashboard page with stats widgets, recent activity, and quick actions',
  context: {
    targetType: 'page',
    complexity: 'complex',
    userIntent: 'admin dashboard with multiple widgets'
  },
  features: ['theme', 'storage', 'responsive', 'multi-widget'],
  requirements: {
    useTheme: true,
    useStorage: true,
    responsive: true,
    accessibility: 'aa',
    includeTests: true,
    includeMockApi: true
  }
});

// Result includes:
// - Page component with layout
// - Multiple child widgets
// - Route configuration
// - Mock API for all data
// - Integration tests

Platform Context Management

Building Context

The coordinator automatically builds platform context:

// Manually trigger context build
const context = await coordinator.buildPlatformContext();

// Context includes:
console.log(context.themes.utilities); 
// ['.ux-bg-primary', '.ux-text-primary', '.glass-card', ...]

console.log(context.widgets.available);
// ['button', 'card', 'table', 'chart', ...]

console.log(context.patterns.design);
// ['admin-panel', 'user-card', 'stats-display', ...]

Refreshing Context

Context is automatically refreshed when stale (>1 hour old):

// Force refresh
await coordinator.refreshPlatformContext();

// Check context age
const hasContext = coordinator.hasContext();
const age = coordinator.contextAge(); // milliseconds

Statistics and Monitoring

Generation Stats

const stats = coordinator.getGenerationStats();

console.log('Total generations:', stats.totalGenerations);
console.log('Success rate:', stats.successRate);
console.log('Average confidence:', stats.averageConfidence);
console.log('Most generated:', stats.mostGenerated);

Storage Stats

const storageStats = aiStorage.getStorageStatistics();

console.log('Total learnings:', storageStats.totalLearnings);
console.log('Cache hit rate:', storageStats.cacheHitRate);
console.log('Database sizes:', storageStats.databaseSizes);

Prompt Stats

const promptStats = adaptivePrompt.getPromptStatistics();

console.log('Total prompts:', promptStats.totalPrompts);
console.log('Average success rate:', promptStats.averageSuccessRate);
console.log('Best category:', promptStats.bestPerformingCategory);
console.log('Recent trends:', promptStats.recentTrends);

Best Practices

1. Provide Clear Context

// Good
{
  description: 'User profile card showing avatar, name, role, and stats',
  context: {
    targetType: 'widget',
    complexity: 'simple',
    userIntent: 'display user information in a compact card format'
  }
}

// Avoid
{
  description: 'card',
  context: {
    targetType: 'widget',
    complexity: 'simple',
    userIntent: 'make a card'
  }
}

2. Enable Features You Need

// Only enable what you need
requirements: {
  useTheme: true,        // Always enable for consistency
  useStorage: true,      // Only if data persistence needed
  useAuth: false,        // Only if auth required
  responsive: true,      // Always enable
  accessibility: 'aa',   // Minimum AA level
  includeTests: true,    // Always generate tests
  includeMockApi: false  // Only for data-driven components
}

3. Provide Feedback

// After generation, provide feedback
await aiStorage.storeGenerationWithLearning(generation, {
  rating: 4.5,
  modifications: [
    // List any changes you made
    {
      type: 'modification',
      location: '...',
      before: '...',
      after: '...',
      reason: 'Better pattern'
    }
  ]
});

4. Review Generated Code

Always review generated code before using in production:

Troubleshooting

Context Not Building

// Check if context is building
if (coordinator.isBuildingContext()) {
  console.log('Context is being built, please wait...');
}

// Force rebuild
await coordinator.refreshPlatformContext();

Low Confidence Scores

If generations have low confidence scores:

  1. Provide more detailed descriptions
  2. Specify exact features needed
  3. Add context about existing components
  4. Review and update prompt templates

Storage Sync Issues

// Check sync status
const stats = aiStorage.storageStats();
console.log('Sync status:', stats.syncStatus);

// Manually trigger sync
await aiStorage.syncToTeam('code-learning', data);

Migration Guide

From Direct AI Services

Before:

const openai = inject(OpenAIService);
const result = await openai.complete([
  { role: 'user', content: 'Generate a button' }
]);

After:

const coordinator = inject(IntelligenceCoordinatorService);
const result = await coordinator.coordinateGeneration({
  type: 'widget',
  description: 'Generate a button',
  // ... requirements
});

From Button Generator

Before:

const buttonGen = inject(ButtonGenerationService);
const designs = await buttonGen.generateButtonDesigns(request);

After:

const widgetGen = inject(UniversalWidgetGeneratorService);
const design = await widgetGen.generateWidget({
  widgetType: WidgetType.BUTTON,
  // ... requirements
});

Next Steps

Related