2008robocode-crypto/code-generation-system
0
1"""2Runtime simulator to validate that generated configs can actually execute.3Simulates app initialization and operation to detect execution errors early.4"""5 6from typing import Any, Dict, List, Optional7import json8 9 10class RuntimeSimulator:11 """Simulates execution of generated application configuration."""12 13 def __init__(self, config: Dict[str, Any]):14 self.config = config15 self.errors = []16 self.warnings = []17 self.simulation_log = []18 19 def validate_executability(self) -> bool:20 """Check if config can be executed without errors."""21 checks = [22 self._check_database_schema,23 self._check_api_endpoints,24 self._check_ui_pages,25 self._check_authentication,26 self._check_business_logic,27 self._simulate_user_flow,28 ]29 30 for check in checks:31 try:32 check()33 except Exception as e:34 self.errors.append(f"{check.__name__}: {str(e)}")35 36 return len(self.errors) == 037 38 def _check_database_schema(self):39 """Simulate database initialization."""40 db_schema = self.config.get("database_schema", [])41 42 if not db_schema:43 self.warnings.append("No database schema defined")44 return45 46 for table in db_schema:47 # Check table can be created48 if not self._can_create_table(table):49 raise ValueError(f"Cannot create table '{table.get('name')}'")50 51 self.simulation_log.append(f"✓ Database table '{table['name']}' initialized")52 53 def _can_create_table(self, table: Dict[str, Any]) -> bool:54 """Check if a table can be created."""55 required = ["name", "fields", "primary_key"]56 if not all(k in table for k in required):57 return False58 59 if not isinstance(table["fields"], list):60 return False61 62 primary_key = table["primary_key"]63 field_names = [f.get("name") if isinstance(f, dict) else f for f in table["fields"]]64 65 if primary_key not in field_names:66 raise ValueError(f"Primary key '{primary_key}' not found in fields")67 68 return True69 70 def _check_api_endpoints(self):71 """Simulate API initialization."""72 api_schema = self.config.get("api_schema", [])73 74 if not api_schema:75 self.warnings.append("No API endpoints defined")76 return77 78 valid_methods = ["GET", "POST", "PUT", "DELETE", "PATCH"]79 80 for endpoint in api_schema:81 if not isinstance(endpoint, dict):82 raise ValueError("API endpoint is not a dict")83 84 if "path" not in endpoint or "method" not in endpoint:85 raise ValueError(f"API endpoint missing path or method: {endpoint}")86 87 if endpoint["method"] not in valid_methods:88 raise ValueError(f"Invalid HTTP method: {endpoint['method']}")89 90 self.simulation_log.append(f"✓ API endpoint '{endpoint['method']} {endpoint['path']}' registered")91 92 def _check_ui_pages(self):93 """Simulate UI initialization."""94 ui_schema = self.config.get("ui_schema", [])95 96 if not ui_schema:97 self.warnings.append("No UI pages defined")98 return99 100 for page in ui_schema:101 if not isinstance(page, dict):102 raise ValueError("UI page is not a dict")103 104 if "path" not in page or "title" not in page:105 raise ValueError(f"UI page missing path or title: {page}")106 107 if "components" not in page or not isinstance(page["components"], list):108 raise ValueError(f"UI page '{page['path']}' has no components")109 110 self.simulation_log.append(f"✓ UI page '{page['path']}' ({page['title']}) registered")111 112 def _check_authentication(self):113 """Simulate authentication system initialization."""114 auth_config = self.config.get("auth_config", {})115 roles = self.config.get("roles", [])116 117 if not auth_config:118 self.warnings.append("No auth config defined")119 return120 121 if "type" not in auth_config:122 raise ValueError("Auth config missing 'type'")123 124 if not roles:125 raise ValueError("No roles defined for authorization")126 127 role_names = set()128 for role in roles:129 if not isinstance(role, dict) or "name" not in role:130 raise ValueError(f"Invalid role definition: {role}")131 role_names.add(role["name"])132 133 self.simulation_log.append(f"✓ Authentication system initialized with {len(roles)} roles")134 135 def _check_business_logic(self):136 """Validate business logic consistency."""137 business_logic = self.config.get("business_logic", {})138 139 if isinstance(business_logic, dict):140 for key, value in business_logic.items():141 if value is None:142 self.warnings.append(f"Business logic '{key}' is None")143 144 self.simulation_log.append(f"✓ Business logic validated ({len(business_logic)} rules)")145 146 def _simulate_user_flow(self):147 """Simulate a typical user flow."""148 # Typical flow: login → access dashboard → perform action149 150 # Check login page exists151 ui_pages = self.config.get("ui_schema", [])152 login_page = next((p for p in ui_pages if "login" in p.get("path", "").lower()), None)153 154 if not login_page:155 self.warnings.append("No login page found")156 157 # Check for dashboard158 dashboard = next((p for p in ui_pages if "dashboard" in p.get("path", "").lower()), None)159 160 if dashboard:161 self.simulation_log.append("✓ User flow validated: Login → Dashboard")162 else:163 self.warnings.append("No dashboard page found in user flow")164 165 def get_report(self) -> Dict[str, Any]:166 """Generate execution report."""167 return {168 "is_executable": len(self.errors) == 0,169 "errors": self.errors,170 "warnings": self.warnings,171 "simulation_log": self.simulation_log,172 "total_checks": len(self.simulation_log) + len(self.errors) + len(self.warnings),173 }174 175 176def validate_config_executable(config: Dict[str, Any]) -> tuple[bool, Dict[str, Any]]:177 """Quick check if config is executable."""178 simulator = RuntimeSimulator(config)179 is_executable = simulator.validate_executability()180 return is_executable, simulator.get_report()181 