Gograb Ai Singularity Improvements
Documentation for Plans
GoGrab AI Vibe Platform - Module-First Architecture
Vision Statement
Build the "Ferrari of vibe coding" by generating complete, reusable modules (not just pages) that follow gograb-space's proven modular architecture, powered by AI and integrated with our superior foundation systems.
Current State Analysis
What We Already Have (editor monorepo)
AI Generation:
- Image generation UI (multi-provider: DALL-E, FLUX, Stable Diffusion, etc.)
- Video generation UI (RunwayML, Pika, Luma, Stability)
- AI chat with multi-provider support
- AI orchestrator for intelligent model selection
Foundation Systems:
- storage-system: Next-gen intelligent storage with MongoDB sync
- theme-system: Runtime theme switching with CSS variables
- widgets: 40+ widget types with UniversalWidgetGenerator
- editor-ui: Visual page editor with drag-drop
- singularity-lib: Logic Builder UI (currently returns mocks only)
- prompt-system: Template management for prompts
Problems:
- Image generation: Model/provider mismatch (DALLE trying to use "flux-1-pro")
- Singularity Logic Builder: Only returns mocks, not real executable logic
- No module contract system: Generating pages, not reusable modules
- Missing inter-module communication patterns
What gograb-space Has (module patterns to adopt)
Module Architecture:
- BrowserModuleContract: Standard interface all modules implement
- ModuleManifest: Metadata with navigation, embeddable components, public actions
- ModuleIntegratorService: Orchestrates module lifecycle
- Dynamic module loading via Angular lazy loading
- EmbeddableComponentRegistry: Share components between modules
- CrossModuleActionService: Execute actions across modules
- NavigationManagerService: Unified navigation
- AssetSharingService: Share assets between modules
Development Pattern:
- Modules as NX libraries in libs/modules/
- Each module: components + services + models + manifest + routes
- Mock API included for development
- Multi-tenant aware by default
The "Ferrari of Vibe Coding" Architecture
Key Differentiator
Other platforms (Lovable, v0, Bolt):
- Generate standalone pages
- No reusability
- Weak foundation
- No inter-module communication
Our platform:
- Generate complete, reusable modules following BrowserModuleContract
- Embeddable components shared between modules
- Public actions invokable from anywhere
- Built on theme-system, storage-system, widgets
- Real backend logic via Singularity Logic Builder
- AI-powered with multiple providers
Phase 1: Fix Existing AI Features (Week 1)
1.1 Fix Image Generation Provider/Model Matching
Problem: Component defaults to "flux-1-pro" but switches provider without updating model
File: libs/gograb-ai/src/lib/components/image-generation/image-generation.component.ts
Solution:
// Add effect to auto-update model when provider changes
constructor() {
effect(() => {
const provider = this.selectedProvider();
const currentModel = this.selectedModel();
// Get valid models for provider
const validModels = this.getModelsForProvider(provider);
// If current model not valid, switch to default
if (!validModels.includes(currentModel)) {
const defaultModel = DEFAULT_IMAGE_MODELS[provider];
this.selectedModel.set(defaultModel);
}
});
}
private getModelsForProvider(provider: ImageProvider): string[] {
const modelsByProvider = {
[ImageProvider.DALLE]: DALLE_MODELS.map(m => m.id),
[ImageProvider.FLUX]: FLUX_MODELS.map(m => m.id),
[ImageProvider.STABLE_DIFFUSION]: STABLE_DIFFUSION_MODELS.map(m => m.id),
// ... etc
};
return modelsByProvider[provider] || [];
}
Test: Switch between providers in UI, verify model auto-updates
1.2 Create Secure API Key Management
Problem: API keys hardcoded or scattered, no centralized management
Create: libs/gograb-ai/src/lib/services/secure-api-key.service.ts
Features:
- Store keys encrypted in storage-system
- Per-provider key management
- Environment variable fallback
- Validation before use
- UI component for managing keys
Interface:
interface ApiKeyConfig {
provider: 'openai' | 'anthropic' | 'flux' | 'stability' | 'runway' | 'pika' | 'luma';
apiKey: string;
isValid: boolean;
lastValidated?: Date;
source: 'env' | 'user' | 'config';
}
@Injectable({ providedIn: 'root' })
export class SecureApiKeyService {
// Store in storage-system (encrypted)
private storage = inject(GgStorage);
validateApiKey(provider: string, key: string): Observable<boolean>
getApiKey(provider: string): Promise<string | null>
setApiKey(provider: string, key: string): Promise<void>
deleteApiKey(provider: string): Promise<void>
}
UI Component: libs/gograb-ai/src/lib/components/api-key-manager/
1.3 Test All AI Providers
For each provider (OpenAI, FLUX, Stability, Runway, Pika, Luma):
- Create test suite (*.spec.ts)
- Test API key validation
- Test generation with real API (optional, with key)
- Test error handling
- Update provider status UI
Phase 2: Adopt gograb-space Module Architecture (Week 2)
2.1 Create Module Contracts in editor monorepo
Create: libs/core-angular/src/lib/contracts/
// editor-module-contract.ts - Similar to BrowserModuleContract
export interface EditorModuleContract {
readonly manifest: EditorModuleManifest;
configure(config: any): Observable<void>;
initialize(): Observable<void>;
start(): Observable<void>;
stop(): Observable<void>;
destroy(): Observable<void>;
}
// editor-module-manifest.ts
export interface EditorModuleManifest {
id: string;
version: string;
name: string;
description: string;
// Navigation
navigation: ModuleNavigationConfig;
// Embeddable components (widgets)
embeddableComponents: EmbeddableComponentConfig[];
// Public actions
publicActions: PublicActionConfig[];
// Routes
routes: ModuleRoute[];
// Dependencies on our systems
dependencies: {
requiresStorage?: boolean;
requiresTheme?: boolean;
requiresWidgets?: boolean;
customDependencies?: string[];
};
}
export interface EmbeddableComponentConfig {
id: string;
componentType: Type<any>;
displayName: string;
description: string;
category: 'widget' | 'form' | 'dashboard' | 'layout';
inputs?: ComponentInput[];
usesThemeSystem: boolean;
usesStorage: boolean;
}
2.2 Create Module Integrator for editor
Create: libs/core-angular/src/lib/services/editor-module-integrator.service.ts
Responsibilities:
- Discover modules with @ModuleDecorator
- Validate module contracts
- Register routes dynamically
- Register embeddable components
- Manage module lifecycle
- Connect to theme-system, storage-system, widgets
Integration Points:
@Injectable({ providedIn: 'root' })
export class EditorModuleIntegrator {
private themeService = inject(ThemeApplicationService);
private storage = inject(GgStorage);
private widgetGen = inject(UniversalWidgetGeneratorService);
private router = inject(Router);
async loadModule(moduleId: string): Promise<void> {
// 1. Load module dynamically
const module = await this.dynamicImport(moduleId);
// 2. Validate contract
this.validateContract(module);
// 3. Initialize with our systems
await module.configure({
storage: this.storage,
theme: this.themeService,
widgets: this.widgetGen
});
// 4. Register routes
this.registerModuleRoutes(module.manifest.routes);
// 5. Register embeddable components
this.registerEmbeddableComponents(module.manifest.embeddableComponents);
// 6. Start module
await module.start();
}
}
2.3 Example: Convert User Management to Module Pattern
Goal: Demonstrate the pattern by converting a simple CRUD module
Create: libs/modules/user-management/ (in editor monorepo)
Structure:
libs/modules/user-management/
├── src/
│ ├── lib/
│ │ ├── components/
│ │ │ ├── user-list.component.ts
│ │ │ ├── user-form.component.ts
│ │ │ └── user-detail.component.ts
│ │ ├── services/
│ │ │ └── user-api.service.ts
│ │ ├── models/
│ │ │ └── user.types.ts
│ │ └── user-management.module.ts # Implements EditorModuleContract
│ └── index.ts
Manifest:
export const USER_MODULE_MANIFEST: EditorModuleManifest = {
id: 'user-management',
name: 'User Management',
version: '1.0.0',
description: 'Manage users with CRUD operations',
navigation: {
menuItems: [
{
id: 'users-main',
label: 'Users',
icon: 'people',
route: '/users',
order: 10
}
]
},
embeddableComponents: [
{
id: 'user-list-widget',
componentType: UserListWidgetComponent,
displayName: 'User List',
description: 'Displays list of users',
category: 'widget',
usesThemeSystem: true,
usesStorage: true
}
],
publicActions: [
{
id: 'create-user',
actionClass: CreateUserAction,
displayName: 'Create User',
description: 'Open user creation form'
}
],
routes: [
{ path: 'users', component: UserListComponent },
{ path: 'users/create', component: UserFormComponent },
{ path: 'users/:id', component: UserDetailComponent }
],
dependencies: {
requiresStorage: true,
requiresTheme: true,
requiresWidgets: false
}
};
Phase 3: Make Singularity Logic Builder Work (Week 3)
3.1 Connect Logic Builder to Real AI
Problem: libs/singularity-lib/src/lib/services/logic-ai.service.ts returns mocks (lines 114-159)
Solution: Use AIFactoryService to generate real logic
// libs/singularity-lib/src/lib/services/logic-ai.service.ts
async generateLogicFlow(request: LogicGenerationRequest): Promise<LogicFlow> {
this._isGenerating.set(true);
try {
// Use AI to generate logic flow
const aiService = this.aiFactory.getBestAvailableService();
const systemPrompt = `You are an expert logic flow designer for the editor platform.
You have access to:
- Storage System: Multi-database with MongoDB sync
- Theme System: Adaptive themes with CSS variables
- Widget System: 40+ widget types
- Editor System: Visual page builder
Generate executable logic flows using these building blocks.`;
const enhancedPrompt = `${systemPrompt}
User Request: ${request.naturalLanguage}
Generate a structured logic flow with:
1. Trigger block (what starts the flow)
2. Condition blocks (decision points)
3. Action blocks (operations: storage, widget generation, API calls)
4. Output block (results)
Use our platform APIs and systems.
Return JSON with this structure:
{
"blocks": [
{ "id": "1", "type": "trigger", "config": {...} },
{ "id": "2", "type": "action", "actionType": "storage-write", "config": {...} },
{ "id": "3", "type": "output", "config": {...} }
],
"connections": [
{ "from": "1", "to": "2" },
{ "from": "2", "to": "3" }
]
}`;
const aiResponse = await aiService.complete([
{ role: 'system', content: systemPrompt },
{ role: 'user', content: enhancedPrompt }
], {
temperature: 0.3,
maxTokens: 4000
}).toPromise();
// Parse AI response into LogicFlow
const logicFlow = this.parseAIResponseToBlocks(aiResponse);
// Save to storage-system
await this.storage.put(`logic-flow-${logicFlow.id}`, logicFlow);
return logicFlow;
} finally {
this._isGenerating.set(false);
}
}
3.2 Create Logic Execution Engine
Create: libs/singularity-lib/src/lib/services/logic-execution-engine.service.ts
Purpose: Execute logic flows generated by AI
interface ExecutionContext {
storage: GgStorage;
theme: ThemeApplicationService;
widgets: UniversalWidgetGeneratorService;
variables: Map<string, any>;
}
@Injectable({ providedIn: 'root' })
export class LogicExecutionEngine {
private storage = inject(GgStorage);
private theme = inject(ThemeApplicationService);
private widgets = inject(UniversalWidgetGeneratorService);
async executeFlow(flowId: string): Promise<ExecutionResult> {
// Load flow from storage
const flow = await this.storage.get<LogicFlow>(`logic-flow-${flowId}`);
const context: ExecutionContext = {
storage: this.storage,
theme: this.theme,
widgets: this.widgets,
variables: new Map()
};
// Execute blocks in order
for (const block of flow.blocks) {
await this.executeBlock(block, context);
}
return {
success: true,
outputs: Object.fromEntries(context.variables)
};
}
private async executeBlock(block: LogicBlock, context: ExecutionContext): Promise<void> {
switch (block.type) {
case 'trigger':
// Start execution
break;
case 'action':
await this.executeAction(block, context);
break;
case 'condition':
// Evaluate condition
break;
case 'output':
// Generate output
break;
}
}
private async executeAction(block: LogicBlock, context: ExecutionContext): Promise<void> {
switch (block.actionType) {
case 'storage-write':
await context.storage.put(block.config.key, block.config.value);
break;
case 'widget-generate':
const widget = await context.widgets.generateWidget(block.config.type, block.config.options);
context.variables.set('generatedWidget', widget);
break;
case 'theme-apply':
await context.theme.applyTheme(block.config.themeId);
break;
// ... more actions
}
}
}
3.3 Pre-Built Logic Block Templates
Create: libs/singularity-lib/src/lib/templates/block-templates/
Storage Blocks:
- "Save to Storage"
- "Query Storage"
- "Update Storage"
- "Delete from Storage"
Widget Blocks:
- "Generate Widget"
- "Update Widget"
- "Delete Widget"
Module Blocks:
- "Create Module"
- "Add Component to Module"
- "Generate Module Manifest"
AI Blocks:
- "Generate Text"
- "Generate Image"
- "Analyze Content"
Phase 4: AI-Powered Module Generation (Week 4)
4.1 Create Module Generation Service
Create: libs/gograb-ai/src/lib/services/ai-module-generator.service.ts
Purpose: Generate complete modules using AI
@Injectable({ providedIn: 'root' })
export class AIModuleGeneratorService {
private aiOrchestrator = inject(AIOrchestratorService);
private widgetGen = inject(UniversalWidgetGeneratorService);
private logicAI = inject(LogicAIService);
async generateModule(prompt: string): Promise<GeneratedModule> {
// 1. Analyze prompt to understand what module to build
const analysis = await this.analyzeModuleRequirements(prompt);
// 2. Generate module manifest
const manifest = await this.generateModuleManifest(analysis);
// 3. Generate UI components (using widget generator)
const components = await this.generateComponents(analysis);
// 4. Generate backend logic (using Singularity)
const logic = await this.generateLogic(analysis);
// 5. Generate routes
const routes = this.generateRoutes(manifest, components);
// 6. Package everything as a module
return {
manifest,
components,
logic,
routes,
code: this.generateModuleCode(manifest, components, logic, routes)
};
}
private async analyzeModuleRequirements(prompt: string): Promise<ModuleAnalysis> {
const aiResponse = await this.aiOrchestrator.analyzePrompt(prompt);
return {
moduleType: aiResponse.moduleType, // 'crud', 'dashboard', 'form', 'custom'
entities: aiResponse.entities, // ['User', 'Product', etc.]
features: aiResponse.features, // ['list', 'create', 'edit', 'delete']
storage: aiResponse.needsStorage,
theme: aiResponse.needsTheme,
widgets: aiResponse.widgetTypes
};
}
private async generateComponents(analysis: ModuleAnalysis): Promise<ComponentDesign[]> {
const components: ComponentDesign[] = [];
for (const feature of analysis.features) {
if (feature === 'list') {
// Generate list component using widget generator
const listWidget = await this.widgetGen.generateWidget('table', {
entity: analysis.entities[0],
columns: ['name', 'email', 'status'],
actions: ['edit', 'delete']
});
components.push(listWidget);
}
if (feature === 'create' || feature === 'edit') {
// Generate form component
const formWidget = await this.widgetGen.generateWidget('form', {
entity: analysis.entities[0],
fields: analysis.fields,
validation: true
});
components.push(formWidget);
}
}
return components;
}
}
4.2 Vibe Code Service
Create: libs/editor-ui/src/lib/services/vibe-code.service.ts
Purpose: Orchestrate AI module generation + logic + UI
@Injectable({ providedIn: 'root' })