Improving Universe Code Generation

Plan to enhance the AI-powered module/universe code generation to produce domain-specific, production-ready code.

Improving Universe Code Generation

Executive Summary

The current code generation produces generic placeholder code instead of domain-specific implementations. When a user requests "a fitness center platform with member management, class scheduling, trainer profiles, and workout tracking", the system generates a single module with generic Item entities instead of proper Member, Class, Trainer, and Workout entities.

Current State Analysis

What's Being Generated (Actual)

Location: modules/other/fitness-center/

Issues Identified:

Issue Severity Details
Generic Entity Names Critical Uses Item instead of Member, Booking, Class, Trainer, Workout
Wrong Category High Module saved to modules/other/ instead of modules/business/ or modules/fitness/
Generic Components High ItemList, ItemCard, ItemForm instead of domain-specific components
Missing Domain Fields Critical Item has only id, name, description, createdAt - no domain fields
Old Angular Patterns Medium Uses @Input()/@Output() instead of modern signals with input()/output()
Generic Typing Medium Uses unknown[] instead of properly typed arrays
Single Module Critical Creates ONE module instead of multiple related modules for each entity

What Should Be Generated (Expected)

For prompt: "Create a fitness center platform with member management, class scheduling, trainer profiles, and workout tracking"

Expected Structure:

modules/business/fitness-center/
├── member-management/
│   ├── src/lib/models/member.model.ts          # Member entity with proper fields
│   ├── src/lib/components/member-list/
│   ├── src/lib/components/member-form/
│   ├── src/lib/components/member-card/
│   └── src/lib/actions/create-member.action.ts
├── class-scheduling/
│   ├── src/lib/models/class.model.ts           # Class entity with schedule fields
│   ├── src/lib/components/class-calendar/
│   ├── src/lib/components/class-booking/
│   └── src/lib/actions/book-class.action.ts
├── trainer-profiles/
│   ├── src/lib/models/trainer.model.ts         # Trainer with certifications, schedule
│   ├── src/lib/components/trainer-card/
│   └── src/lib/components/trainer-schedule/
└── workout-tracking/
    ├── src/lib/models/workout.model.ts         # Workout with exercises, sets, reps
    ├── src/lib/components/workout-logger/
    └── src/lib/components/progress-chart/

Expected Member Entity:

export interface Member {
  id: string;
  firstName: string;
  lastName: string;
  email: string;
  phone?: string;
  membershipType: 'basic' | 'premium' | 'vip';
  membershipStatus: 'active' | 'inactive' | 'suspended' | 'expired';
  joinDate: Date;
  expirationDate?: Date;
  emergencyContact?: {
    name: string;
    phone: string;
    relationship: string;
  };
  healthInfo?: {
    conditions?: string[];
    allergies?: string[];
  };
  createdAt: Date;
  updatedAt: Date;
}

Root Cause Analysis

1. Entity Extraction Failure

File: libs/libs-ai/module-generator/src/lib/services/module-knowledge.service.ts

2. Template Placeholder Resolution

File: libs/libs-ai/module-generator/src/lib/templates/crud-module.template.ts

3. Category Classification

File: libs/libs-ai/module-generator/src/lib/services/module-generator.service.ts

4. Single Module Generation

Implementation Plan

Phase 1: Fix Entity Extraction (Priority: Critical)

Objective: Extract domain-specific entities from natural language prompts

Tasks:

  1. Enhance ModuleKnowledgeService.extractEntitiesFromPrompt()

    • Add NLP-based entity recognition
    • Build entity vocabulary for common domains (fitness, retail, healthcare, etc.)
    • Extract relationships between entities
  2. Create domain-specific entity templates

    • MemberEntity template for fitness/membership apps
    • ProductEntity template for e-commerce
    • PatientEntity template for healthcare
    • BookingEntity template for scheduling apps
  3. Implement field inference from entity type

    • Member → email, phone, membershipType, etc.
    • Product → price, sku, inventory, etc.
    • Booking → datetime, duration, status, etc.

Files to Modify:

Phase 2: Fix Multi-Module Generation (Priority: Critical)

Objective: Generate multiple related modules instead of a single generic module

Tasks:

  1. Update orchestrator to create module-per-entity structure
  2. Generate proper inter-module relationships
  3. Create shared types/interfaces for related modules
  4. Generate navigation between modules

Files to Modify:

Phase 3: Fix Category Classification (Priority: High)

Objective: Properly categorize modules based on domain

Tasks:

  1. Create industry category mapping

    const INDUSTRY_CATEGORIES = {
      fitness: ['gym', 'workout', 'fitness', 'member', 'trainer', 'class'],
      healthcare: ['patient', 'doctor', 'appointment', 'medical', 'clinic'],
      retail: ['product', 'inventory', 'order', 'customer', 'cart'],
      services: ['booking', 'appointment', 'service', 'client'],
    };
    
  2. Update manifest generation to use proper category

  3. Create category-specific output directories

Files to Modify:

Phase 4: Modernize Generated Code (Priority: Medium)

Objective: Generate Angular 20 compliant code

Tasks:

  1. Update component templates to use signals

    • Replace @Input() with input()
    • Replace @Output() with output()
    • Use computed() for derived state
  2. Use inject() instead of constructor injection

  3. Add proper TypeScript typing (no unknown[])

  4. Include theme system integration

    • Use CSS variables from @theme-system/*
    • Follow existing component patterns

Files to Modify:

Phase 5: Add Validation & Testing (Priority: Medium)

Objective: Ensure generated code compiles and follows patterns

Tasks:

  1. Add TypeScript compilation validation post-generation
  2. Add lint validation (eslint rules)
  3. Add pattern compliance checking
  4. Create integration tests for generation flow

Success Criteria

Metric Current Target
Entity Extraction Accuracy ~0% >80%
Domain-Specific Fields 0 fields 5+ per entity
Modules per Platform 1 3-5
Category Accuracy 0% >90%
Signal Usage 0% 100%
TypeScript Strict Compliance Partial Full

API Gaps Identified

During testing, these 404 errors were observed:

  1. GET /api/catalog/modules - Endpoint doesn't exist

    • Need to create CatalogController for module registry
  2. GET /api/spaces/:spaceId/universes/:universeId - Inconsistent ID format

    • Frontend uses universe_1767... format
    • Backend expects different format

Action Required: Create missing API endpoints or fix ID format consistency.

Dependencies

Risks

Risk Probability Impact Mitigation
LLM hallucination in entity extraction Medium High Use structured prompts with validation
Breaking existing generation flows High Medium Feature flag new generation path
Performance impact of multi-module gen Medium Low Parallel file generation

Timeline Estimate

References