Logic Execution Engine
Execute AI-generated logic flows with real platform integration
⚡ Logic Execution Engine
The Logic Execution Engine is a powerful system that executes AI-generated logic flows with real platform integration. It transforms AI-generated abstract logic into concrete actions using our platform systems (storage, theme, widgets, modules).
🎯 Overview
The Logic Execution Engine provides:
- Block-by-Block Execution: Executes logic flows following connections between blocks
- Platform Integration: Direct integration with storage-system, theme-system, widgets, and modules
- Context Management: Tracks variables, execution state, and flow progress
- Error Handling: Graceful error handling with detailed error messages
- Performance Tracking: Measures execution time for flows and individual blocks
- Debug Logging: Comprehensive logging for troubleshooting
🏗️ Architecture
┌─────────────────────────────────────────────────────────────┐
│ Logic Execution Engine │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Trigger │───▶│ Action │───▶│ Output │ │
│ │ Executor │ │ Executor │ │ Executor │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │ │ │ │
│ │ │ │ │
│ └─────────────────────┴────────────────────┘ │
│ │ │
│ ┌──────▼──────┐ │
│ │ Context │ │
│ │ Management │ │
│ └──────┬──────┘ │
│ │ │
│ ┌─────────────────────┼─────────────────────┐ │
│ │ │ │ │
│ ┌────▼────┐ ┌─────────▼──────┐ ┌──────▼──────┐ │
│ │ Storage │ │ Theme System │ │ Widgets │ │
│ │ System │ │ │ │ │ │
│ └─────────┘ └─────────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────┘
📦 Installation
The Logic Execution Engine is part of the @singularity-lib library:
import { LogicExecutionEngineService } from '@libs-structural/singularity-lib';
No additional installation required - it's automatically available when using singularity-lib.
🚀 Quick Start
Basic Usage
import { Component, inject } from '@angular/core';
import { LogicExecutionEngineService } from '@libs-structural/singularity-lib';
@Component({
selector: 'app-my-component',
template: `
<button (click)="executeFlow()">Execute Flow</button>
`
})
export class MyComponent {
private executionEngine = inject(LogicExecutionEngineService);
async executeFlow() {
// Execute a logic flow by ID
const result = await this.executionEngine.executeFlow('logic-flow-123');
if (result.success) {
console.log('Flow executed successfully!');
console.log('Duration:', result.duration);
console.log('Outputs:', result.outputs);
} else {
console.error('Execution failed:', result.error);
}
}
}
Complete Example with AI Generation
import { Component, inject, signal } from '@angular/core';
import { LogicAIService, LogicExecutionEngineService } from '@libs-structural/singularity-lib';
@Component({
selector: 'app-ai-logic-demo',
template: `
<div>
<!-- Generate Flow -->
<textarea [(ngModel)]="prompt"></textarea>
<button (click)="generateAndExecute()">
Generate & Execute
</button>
<!-- Results -->
@if (result()) {
<div class="results">
<h3>Execution Results</h3>
<pre>{{ result() | json }}</pre>
</div>
}
</div>
`
})
export class AiLogicDemoComponent {
private logicAI = inject(LogicAIService);
private executionEngine = inject(LogicExecutionEngineService);
prompt = signal('Create a user registration flow');
result = signal(null);
async generateAndExecute() {
// 1. Generate logic flow with AI
const generation = await this.logicAI.generateLogicFlow({
naturalLanguage: this.prompt(),
options: {
includeErrorHandling: true,
includeValidation: true
}
});
if (generation.success) {
// 2. Execute the generated flow
const execution = await this.executionEngine.executeFlow(
generation.logicFlow.id
);
this.result.set(execution);
}
}
}
🔧 Supported Block Types
The Execution Engine supports all logic block types:
1. Trigger Blocks
Purpose: Start execution, initialize context
// Trigger block automatically initializes:
// - Execution context
// - Trigger data in variables
// - Timestamp
2. Action Blocks
Purpose: Perform operations (most important for platform integration)
Supported Action Types:
- Storage Actions:
put,get,remove,list - Theme Actions:
apply,get - Widget Actions:
generate,update,delete - Module Actions:
load,unload - API Actions: HTTP requests
- Processing Actions: Data transformation
// Example: Storage action block
{
type: 'action',
properties: {
actionType: 'storage',
operation: 'put',
key: 'user-data',
value: { name: 'John', email: '[email protected]' }
}
}
3. Condition Blocks
Purpose: Evaluate boolean conditions for branching
// Example: Condition block
{
type: 'condition',
properties: {
condition: 'user.age >= 18'
}
}
4. Output Blocks
Purpose: Generate and return results
// Example: Output block
{
type: 'output',
properties: {
data: { success: true, message: 'User created' },
format: 'json'
}
}
5. Function Blocks
Purpose: Execute custom functions
// Example: Function block
{
type: 'function',
properties: {
functionName: 'validateEmail',
arguments: { email: '[email protected]' }
}
}
6. Variable Blocks
Purpose: Set and manage flow variables
// Example: Variable block
{
type: 'variable',
properties: {
variableName: 'userEmail',
value: '[email protected]'
}
}
7. Loop Blocks
Purpose: Iterate over collections
// Example: Loop block
{
type: 'loop',
properties: {
iterations: 5,
items: ['item1', 'item2', 'item3']
}
}
8. Branch Blocks
Purpose: Conditional path selection
// Example: Branch block
{
type: 'branch',
properties: {
condition: 'status === "active"'
}
}
🔌 Platform Integrations
Storage System Integration
Execute storage operations using GgStorage:
// Storage actions available:
- put(key, value) // Save data
- get(key) // Retrieve data
- remove(key) // Delete data
- list() // List all keys
Example Flow:
const flow = {
blocks: [
{
type: 'action',
properties: {
actionType: 'storage',
operation: 'put',
key: 'user-123',
value: { name: 'John Doe', email: '[email protected]' }
}
}
]
};
Theme System Integration
Apply and manage themes:
// Theme actions available:
- apply(themeId) // Apply theme
- get() // Get current theme
Example Flow:
const flow = {
blocks: [
{
type: 'action',
properties: {
actionType: 'theme',
operation: 'apply',
themeId: 'dark-mode'
}
}
]
};
Widget Generation Integration
Generate UI widgets dynamically:
// Widget actions available:
- generate(type, options) // Create widget
- update(widgetId) // Update widget
- delete(widgetId) // Remove widget
Example Flow:
const flow = {
blocks: [
{
type: 'action',
properties: {
actionType: 'widget',
operation: 'generate',
widgetType: 'button',
options: {
label: 'Click Me',
color: 'primary',
size: 'large'
}
}
}
]
};
Module Integration
Load and manage modules:
// Module actions available:
- load(moduleId) // Load module
- unload(moduleId) // Unload module
Example Flow:
const flow = {
blocks: [
{
type: 'action',
properties: {
actionType: 'module',
operation: 'load',
moduleId: 'user-management'
}
}
]
};
📊 Execution Context
The execution context tracks the state of a running flow:
interface ExecutionContext {
// Flow identification
treeId: string;
blockId: string;
startTime: Date;
// State management
variables: Map<string, any>;
callStack: string[];
executedBlocks: Set<string>;
// Execution tracking
executionPath: Array<{
blockId: string;
timestamp: Date;
duration: number;
success: boolean;
output?: any;
error?: string;
}>;
// Platform services
storage: GgStorage;
theme: ThemeApplicationService;
widgets: UniversalWidgetGeneratorService;
moduleIntegrator: EditorModuleIntegratorService;
}
📈 Execution Results
After execution, you receive a detailed result:
interface ExecutionResult {
success: boolean; // Overall success status
flowId: string; // Flow identifier
flowName: string; // Flow name
duration: number; // Total execution time (ms)
outputs: Record<string, any>; // Output values
executedBlocks: string[]; // IDs of executed blocks
executionPath: Array<{ // Step-by-step path
blockId: string;
timestamp: Date;
duration: number;
success: boolean;
output?: any;
error?: string;
}>;
variables: Record<string, any>; // Final variable state
error?: string; // Error message if failed
}
🎨 Interactive Demo
Try the Logic Execution Engine in our interactive demo:
Demo URL: /ai-demos/logic-execution
Features:
- Generate logic flows with AI
- Execute flows with real platform integration
- Visualize execution step-by-step
- View variables and context
- Track performance metrics
🧪 Testing
The execution engine includes comprehensive unit tests:
# Run tests
nx test singularity-lib
# Run specific test suite
nx test singularity-lib --testNamePattern="LogicExecutionEngineService"
Test Coverage:
- ✅ Flow execution with single/multiple blocks
- ✅ All block type executors
- ✅ Platform integration actions
- ✅ Error handling
- ✅ Execution state tracking
- ✅ Performance metrics
- ✅ Circular dependency prevention
🚨 Error Handling
The execution engine handles errors gracefully:
const result = await executionEngine.executeFlow('my-flow');
if (!result.success) {
console.error('Execution failed:', result.error);
// Check execution path for failures
result.executionPath.forEach(step => {
if (!step.success) {
console.error(`Block ${step.blockId} failed:`, step.error);
}
});
}
🔍 Debug Logging
Enable debug logging for troubleshooting:
// Execution engine automatically logs to console:
console.log('🚀 [Execution Engine] Starting flow execution');
console.log('⚡ [Action] Executing action: storage');
console.log('✅ [Execution Engine] Flow completed in 42.50ms');
Log Levels:
🚀Flow start/completion⚡Block execution💾Storage operations🎨Theme operations🧩Widget operations📦Module operations✅Success❌Errors
🎯 Best Practices
1. Use AI-Generated Flows
Let AI generate flows instead of manually creating them:
// ✅ Good: Use AI to generate
const generation = await logicAI.generateLogicFlow({
naturalLanguage: 'Create a user registration flow'
});
// ❌ Avoid: Manual flow creation (complex and error-prone)
const flow = { blocks: [...], connections: [...] };
2. Check Execution Results
Always check execution results for errors:
// ✅ Good: Check results
const result = await executionEngine.executeFlow(flowId);
if (!result.success) {
handleError(result.error);
}
// ❌ Avoid: Assuming success
await executionEngine.executeFlow(flowId);
// ... proceed without checking
3. Use Storage for Flow Persistence
Save generated flows for reuse:
// Flows are automatically saved by LogicAIService
const generation = await logicAI.generateLogicFlow(request);
// Flow is saved to storage as `logic-flow-{id}`
// Execute later
await executionEngine.executeFlow(generation.logicFlow.id);
4. Monitor Performance
Track execution metrics:
const result = await executionEngine.executeFlow(flowId);
console.log(`Executed ${result.executedBlocks.length} blocks`);
console.log(`Total duration: ${result.duration}ms`);
// Check slow blocks
result.executionPath.forEach(step => {
if (step.duration > 100) {
console.warn(`Slow block: ${step.blockId} (${step.duration}ms)`);
}
});
5. Handle Variables Properly
Access flow variables from results:
const result = await executionEngine.executeFlow(flowId);
// Access specific variables
const userData = result.variables['user_data'];
const theme = result.variables['current_theme'];
// Access outputs
const outputData = result.outputs['output_block-1'];
🔗 Related Documentation
- Logic AI Service - Generate flows with AI
- Logic Builder Types - Block and flow interfaces
- Storage System - Storage integration
- Theme System - Theme integration
- Widget System - Widget generation
💡 Examples
Example 1: User Registration Flow
// 1. Generate flow with AI
const generation = await logicAI.generateLogicFlow({
naturalLanguage: 'Create a user registration flow with email validation, password hashing, database storage, and welcome email',
options: {
includeErrorHandling: true,
includeValidation: true
}
});
// 2. Execute the flow
const result = await executionEngine.executeFlow(generation.logicFlow.id);
// 3. Check results
if (result.success) {
console.log('User registered successfully!');
console.log('User ID:', result.variables['user_id']);
}
Example 2: Data Processing Pipeline
// Generate a data processing flow
const generation = await logicAI.generateLogicFlow({
naturalLanguage: 'Create a data processing flow that fetches data from an API, validates it, transforms it, and saves to storage'
});
// Execute with monitoring
const result = await executionEngine.executeFlow(generation.logicFlow.id);
// Monitor performance
result.executionPath.forEach(step => {
console.log(`${step.blockId}: ${step.duration}ms`);
});
Example 3: Theme Switching
// Generate theme switching flow
const generation = await logicAI.generateLogicFlow({
naturalLanguage: 'Create a theme switching flow that applies a theme, saves user preference to storage, and generates a theme widget'
});
// Execute
const result = await executionEngine.executeFlow(generation.logicFlow.id);
// Check theme was applied
console.log('Current theme:', result.variables['current_theme']);
🎓 Summary
The Logic Execution Engine is a powerful system that:
- ✅ Executes AI-generated logic flows
- ✅ Integrates with all platform systems
- ✅ Tracks execution state and performance
- ✅ Handles errors gracefully
- ✅ Provides detailed results and logging
Get Started: Visit /ai-demos/logic-execution to try it live!
Last Updated: January 2025 Part of the GoGrab Space Singularity Logic Builder System