Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
feat: implement core module with config manager, lifecycle, orchestrator, and plugin registry
KaifAhmad13af3cb19d9ca
diff --git a/libs/semantica/core/__init__.py b/libs/semantica/core/__init__.pyindex 47745148..cfbebfae 100644--- a/libs/semantica/core/__init__.py+++ b/libs/semantica/core/__init__.py@@ -5,13 +5,29 @@ This module provides the main orchestration capabilities for the Semantica frameExports:- Semantica: Main framework class for orchestration- - PipelineBuilder: DSL for building processing pipelines- - Config: Configuration management+ - Config: Configuration data class+ - ConfigManager: Configuration management system+ - LifecycleManager: Lifecycle management- PluginRegistry: Plugin management system"""-# from .orchestrator import Semantica-# from .config_manager import Config, ConfigManager-# from .plugin_registry import PluginRegistry-# from .lifecycle import LifecycleManager+from .orchestrator import Semantica+from .config_manager import Config, ConfigManager+from .lifecycle import LifecycleManager, SystemState, HealthStatus+from .plugin_registry import PluginRegistry, PluginInfo, LoadedPlugin+__all__ = [+ # Main orchestrator+ "Semantica",+ # Configuration+ "Config",+ "ConfigManager",+ # Lifecycle+ "LifecycleManager",+ "SystemState",+ "HealthStatus",+ # Plugins+ "PluginRegistry",+ "PluginInfo",+ "LoadedPlugin",+]\ No newline at end of filediff --git a/libs/semantica/core/config_manager.py b/libs/semantica/core/config_manager.pyindex d3dab6d2..86bf1afd 100644--- a/libs/semantica/core/config_manager.py+++ b/libs/semantica/core/config_manager.py@@ -13,9 +13,29 @@ Key Features:Main Classes:- Config: Configuration data class- ConfigManager: Configuration management system- - ConfigValidator: Configuration validation"""+import os+import json+from pathlib import Path+from typing import Any, Dict, Optional, Union++try:+ import yaml+ YAML_AVAILABLE = True+except ImportError:+ YAML_AVAILABLE = False++from ..utils.exceptions import ConfigurationError+from ..utils.helpers import (+ merge_dicts,+ read_json_file,+ get_nested_value,+ set_nested_value,+)+from ..utils.validators import validate_config+from ..utils.constants import DEFAULT_CONFIG+class Config:"""@@ -30,9 +50,12 @@ class Config:vector_store: Vector store configurationgraph_db: Graph database settingsprocessing: Processing pipeline settings+ logging: Logging configuration+ quality: Quality assurance settings+ security: Security settings"""- def __init__(self, config_dict=None, **kwargs):+ def __init__(self, config_dict: Optional[Dict[str, Any]] = None, **kwargs):"""Initialize configuration.@@ -40,36 +63,170 @@ class Config:config_dict: Dictionary of configuration values**kwargs: Additional configuration parameters"""- # TODO: Load configuration from dict- # TODO: Load environment variables- # TODO: Apply defaults- # TODO: Validate configuration- pass+ # Start with defaults+ default_dict = DEFAULT_CONFIG.copy()++ # Merge with provided config_dict+ if config_dict:+ default_dict = merge_dicts(default_dict, config_dict, deep=True)++ # Merge with kwargs+ if kwargs:+ default_dict = merge_dicts(default_dict, kwargs, deep=True)++ # Load from environment variables+ self._load_from_env(default_dict)++ # Initialize dataclass fields+ self.llm_provider = default_dict.get("llm_provider", {})+ self.embedding_model = default_dict.get("embedding_model", {})+ self.vector_store = default_dict.get("vector_store", {})+ self.graph_db = default_dict.get("graph_db", {})+ self.processing = default_dict.get("processing", DEFAULT_CONFIG.get("processing", {}))+ self.pipeline = default_dict.get("pipeline", {})+ self.logging = default_dict.get("logging", DEFAULT_CONFIG.get("logging", {}))+ self.quality = default_dict.get("quality", DEFAULT_CONFIG.get("quality", {}))+ self.security = default_dict.get("security", DEFAULT_CONFIG.get("security", {}))+ self.custom = default_dict.get("custom", {})++ def _load_from_env(self, config_dict: Dict[str, Any]) -> None:+ """+ Load configuration values from environment variables.++ Environment variables with prefix SEMANTICA_ will override+ configuration values. Format: SEMANTICA_SECTION_KEY=value++ Args:+ config_dict: Configuration dictionary to update+ """+ prefix = "SEMANTICA_"++ for key, value in os.environ.items():+ if key.startswith(prefix):+ # Remove prefix and convert to lowercase+ config_key = key[len(prefix):].lower()++ # Try to parse as JSON, otherwise use as string+ try:+ parsed_value = json.loads(value)+ except (json.JSONDecodeError, ValueError):+ # Convert boolean strings+ if value.lower() in ("true", "false"):+ parsed_value = value.lower() == "true"+ # Convert numeric strings+ elif value.isdigit():+ parsed_value = int(value)+ elif value.replace(".", "", 1).isdigit():+ parsed_value = float(value)+ else:+ parsed_value = value++ # Set nested value+ set_nested_value(config_dict, config_key, parsed_value)- def validate(self):+ def validate(self) -> None:"""Validate configuration settings.Raises:ConfigurationError: If configuration is invalid"""- # TODO: Validate required fields- # TODO: Validate data types- # TODO: Validate value ranges- # TODO: Validate dependencies- pass+ errors = []++ # Validate processing settings+ if "processing" in self.to_dict():+ processing = self.processing+ if "batch_size" in processing:+ batch_size = processing["batch_size"]+ if not isinstance(batch_size, int) or batch_size <= 0:+ errors.append("processing.batch_size must be a positive integer")++ if "max_workers" in processing:+ max_workers = processing["max_workers"]+ if not isinstance(max_workers, int) or max_workers <= 0:+ errors.append("processing.max_workers must be a positive integer")++ # Validate quality settings+ if "quality" in self.to_dict():+ quality = self.quality+ if "min_confidence" in quality:+ confidence = quality["min_confidence"]+ if not isinstance(confidence, (int, float)) or not (0.0 <= confidence <= 1.0):+ errors.append("quality.min_confidence must be between 0.0 and 1.0")++ if errors:+ raise ConfigurationError(+ f"Configuration validation failed: {', '.join(errors)}",+ config_context=self.to_dict(),+ )- def to_dict(self):+ def to_dict(self) -> Dict[str, Any]:"""Convert configuration to dictionary.Returns:dict: Configuration as dictionary"""- # TODO: Serialize configuration- # TODO: Include all settings- # TODO: Return dictionary- pass+ return {+ "llm_provider": self.llm_provider,+ "embedding_model": self.embedding_model,+ "vector_store": self.vector_store,+ "graph_db": self.graph_db,+ "processing": self.processing,+ "pipeline": self.pipeline,+ "logging": self.logging,+ "quality": self.quality,+ "security": self.security,+ "custom": self.custom,+ }++ def get(self, key_path: str, default: Any = None) -> Any:+ """+ Get nested configuration value by key path.++ Args:+ key_path: Dot-separated key path (e.g., "processing.batch_size")+ default: Default value if key not found++ Returns:+ Configuration value or default+ """+ config_dict = self.to_dict()+ return get_nested_value(config_dict, key_path, default=default)++ def set(self, key_path: str, value: Any) -> None:+ """+ Set nested configuration value by key path.++ Args:+ key_path: Dot-separated key path (e.g., "processing.batch_size")+ value: Value to set+ """+ config_dict = self.to_dict()+ set_nested_value(config_dict, key_path, value)++ # Reinitialize from updated dict+ updated = Config(config_dict=config_dict)+ self.__dict__.update(updated.__dict__)++ def update(self, updates: Dict[str, Any], merge: bool = True) -> None:+ """+ Update configuration with new values.++ Args:+ updates: Dictionary of updates+ merge: Whether to merge nested dictionaries (default: True)+ """+ current_dict = self.to_dict()++ if merge:+ updated_dict = merge_dicts(current_dict, updates, deep=True)+ else:+ updated_dict = {**current_dict, **updates}++ # Reinitialize from updated dict+ updated = Config(config_dict=updated_dict)+ self.__dict__.update(updated.__dict__)class ConfigManager:@@ -79,52 +236,173 @@ class ConfigManager:Handles loading, validation, and updating of configuration."""- def load_from_file(self, file_path):+ def __init__(self):+ """Initialize configuration manager."""+ self._config: Optional[Config] = None++ def load_from_file(+ self,+ file_path: Union[str, Path],+ validate: bool = True+ ) -> Config:"""Load configuration from file.+ Supports YAML and JSON formats. Automatically detects format+ based on file extension.+Args:file_path: Path to configuration file (YAML or JSON)+ validate: Whether to validate configuration after loadingReturns:Config: Loaded configuration object++ Raises:+ ConfigurationError: If file cannot be loaded or is invalid"""- # TODO: Detect file format- # TODO: Parse file- # TODO: Create Config object- # TODO: Validate configuration- # TODO: Return Config- pass+ file_path = Path(file_path)++ if not file_path.exists():+ raise ConfigurationError(+ f"Configuration file not found: {file_path}",+ config_context={"file_path": str(file_path)}+ )++ # Detect format from extension+ suffix = file_path.suffix.lower()++ try:+ if suffix in (".yaml", ".yml"):+ if not YAML_AVAILABLE:+ raise ConfigurationError(+ "YAML support not available. Install PyYAML: pip install pyyaml"+ )++ with open(file_path, "r", encoding="utf-8") as f:+ config_dict = yaml.safe_load(f)++ elif suffix == ".json":+ config_dict = read_json_file(file_path)+ else:+ raise ConfigurationError(+ f"Unsupported configuration file format: {suffix}. "+ "Supported formats: .yaml, .yml, .json"+ )++ # Create config object+ config = Config(config_dict=config_dict)++ # Validate if requested+ if validate:+ config.validate()++ self._config = config+ return config++ except Exception as e:+ if isinstance(e, ConfigurationError):+ raise+ raise ConfigurationError(+ f"Failed to load configuration file: {str(e)}",+ config_context={"file_path": str(file_path)}+ )- def load_from_dict(self, config_dict):+ def load_from_dict(+ self,+ config_dict: Dict[str, Any],+ validate: bool = True+ ) -> Config:"""Load configuration from dictionary.Args:config_dict: Dictionary of configuration values+ validate: Whether to validate configuration after loadingReturns:Config: Configuration object++ Raises:+ ConfigurationError: If configuration is invalid"""- # TODO: Parse dictionary- # TODO: Create Config object- # TODO: Validate configuration- # TODO: Return Config- pass+ config = Config(config_dict=config_dict)++ if validate:+ config.validate()++ self._config = config+ return config- def merge_configs(self, *configs):+ def merge_configs(self, *configs: Config, validate: bool = True) -> Config:"""Merge multiple configurations.+ Later configurations take priority over earlier ones.+ Nested dictionaries are merged deeply.+Args:*configs: Configuration objects to merge+ validate: Whether to validate merged configurationReturns:Config: Merged configuration"""- # TODO: Merge configurations with priority- # TODO: Handle conflicts- # TODO: Validate merged config- # TODO: Return merged Config- pass-+ if not configs:+ raise ConfigurationError("No configurations provided to merge")++ # Convert all configs to dicts+ config_dicts = [config.to_dict() for config in configs]++ # Merge all dicts+ merged_dict = {}+ for config_dict in config_dicts:+ merged_dict = merge_dicts(merged_dict, config_dict, deep=True)++ # Create merged config+ merged_config = Config(config_dict=merged_dict)++ if validate:+ merged_config.validate()++ self._config = merged_config+ return merged_config++ def get_config(self) -> Optional[Config]:+ """+ Get current configuration.++ Returns:+ Current Config object or None if not loaded+ """+ return self._config++ def set_config(self, config: Config, validate: bool = True) -> None:+ """+ Set current configuration.++ Args:+ config: Configuration object to set+ validate: Whether to validate configuration+ """+ if validate:+ config.validate()++ self._config = config++ def reload(self, file_path: Optional[Union[str, Path]] = None) -> Config:+ """+ Reload configuration from file.++ Args:+ file_path: Path to configuration file. If None, uses last loaded file.++ Returns:+ Config: Reloaded configuration+ """+ if file_path is None:+ if not hasattr(self, "_last_file_path"):+ raise ConfigurationError("No file path specified and no previous file loaded")+ file_path = self._last_file_path++ return self.load_from_file(file_path)\ No newline at end of filediff --git a/libs/semantica/core/lifecycle.py b/libs/semantica/core/lifecycle.pyindex d147e18c..e768cab7 100644--- a/libs/semantica/core/lifecycle.py+++ b/libs/semantica/core/lifecycle.py@@ -12,10 +12,40 @@ Key Features:Main Classes:- LifecycleManager: Lifecycle coordination- - HealthChecker: Health monitoring- - ShutdownHandler: Graceful shutdown"""+import time+from enum import Enum+from typing import Any, Callable, Dict, List, Optional, Tuple+from dataclasses import dataclass, field+from collections import defaultdict++from ..utils.exceptions import SemanticaError+from ..utils.logging import get_logger+++class SystemState(str, Enum):+ """System state enumeration."""++ UNINITIALIZED = "uninitialized"+ INITIALIZING = "initializing"+ READY = "ready"+ RUNNING = "running"+ STOPPING = "stopping"+ STOPPED = "stopped"+ ERROR = "error"+++@dataclass+class HealthStatus:+ """Health status information."""++ component: str+ healthy: bool+ message: str = ""+ timestamp: float = field(default_factory=time.time)+ details: Dict[str, Any] = field(default_factory=dict)+class LifecycleManager:"""@@ -26,83 +56,330 @@ class LifecycleManager:Attributes:state: Current system state- health_checker: Health monitoring instance- shutdown_handler: Shutdown coordination instance+ health_status: Dictionary of component health statuses+ startup_hooks: List of startup hooks+ shutdown_hooks: List of shutdown hooks"""def __init__(self):"""Initialize lifecycle manager."""- # TODO: Initialize state tracking- # TODO: Initialize health checker- # TODO: Initialize shutdown handler- # TODO: Register lifecycle hooks- pass+ self.state: SystemState = SystemState.UNINITIALIZED+ self.health_status: Dict[str, HealthStatus] = {}+ self.startup_hooks: List[Tuple[Callable, int]] = [] # (hook, priority)+ self.shutdown_hooks: List[Tuple[Callable, int]] = [] # (hook, priority)+ self.logger = get_logger("lifecycle")+ self._component_registry: Dict[str, Any] = {}+ self._last_health_check: Optional[float] = None- def startup(self):+ def startup(self) -> None:"""Execute startup sequence.This method initializes all components in the correct orderand verifies system readiness.++ Raises:+ SemanticaError: If startup fails"""- # TODO: Execute startup hooks- # TODO: Initialize components- # TODO: Verify dependencies- # TODO: Run health checks- # TODO: Update system state- pass+ if self.state == SystemState.READY or self.state == SystemState.RUNNING:+ self.logger.warning("System already started")+ return++ try:+ self.state = SystemState.INITIALIZING+ self.logger.info("Starting system lifecycle")++ # Sort hooks by priority (lower = earlier)+ sorted_hooks = sorted(self.startup_hooks, key=lambda x: x[1])++ # Execute startup hooks+ for hook_fn, priority in sorted_hooks:+ try:+ self.logger.debug(f"Executing startup hook (priority: {priority})")+ hook_fn()+ except Exception as e:+ self.logger.error(f"Startup hook failed: {e}")+ self.state = SystemState.ERROR+ raise SemanticaError(f"Startup hook failed: {e}")++ # Verify all components are initialized+ self._verify_components()++ # Run initial health checks+ health_results = self.health_check()+ unhealthy = [+ name for name, status in health_results.items()+ if not status.healthy+ ]++ if unhealthy:+ self.logger.warning(f"Some components are unhealthy: {unhealthy}")++ self.state = SystemState.READY+ self.logger.info("System startup completed successfully")++ except Exception as e:+ self.state = SystemState.ERROR+ self.logger.error(f"System startup failed: {e}")+ raise- def shutdown(self, graceful=True):+ def shutdown(self, graceful: bool = True) -> None:"""Execute shutdown sequence.Args:- graceful: Whether to shutdown gracefully+ graceful: Whether to shutdown gracefully (default: True)"""- # TODO: Execute shutdown hooks- # TODO: Stop active processes- # TODO: Cleanup resources- # TODO: Close connections- # TODO: Update system state- pass+ if self.state == SystemState.STOPPED:+ self.logger.warning("System already stopped")+ return++ try:+ self.state = SystemState.STOPPING+ self.logger.info(f"Shutting down system (graceful: {graceful})")++ # Sort hooks by priority (lower = earlier)+ sorted_hooks = sorted(self.shutdown_hooks, key=lambda x: x[1])++ # Execute shutdown hooks+ for hook_fn, priority in sorted_hooks:+ try:+ self.logger.debug(f"Executing shutdown hook (priority: {priority})")+ hook_fn()+ except Exception as e:+ if graceful:+ self.logger.warning(f"Shutdown hook failed: {e}")+ else:+ self.logger.error(f"Shutdown hook failed: {e}")+ raise SemanticaError(f"Shutdown hook failed: {e}")++ # Cleanup resources+ self._cleanup_resources()++ self.state = SystemState.STOPPED+ self.logger.info("System shutdown completed")++ except Exception as e:+ self.state = SystemState.ERROR+ self.logger.error(f"System shutdown failed: {e}")+ if not graceful:+ raise- def health_check(self):+ def health_check(self) -> Dict[str, HealthStatus]:"""Perform system health check.+ Checks health of all registered components and returns+ status information.+Returns:- dict: Health status of all components+ Dictionary mapping component names to HealthStatus objects"""- # TODO: Check component health- # TODO: Check resource availability- # TODO: Check dependencies- # TODO: Collect metrics- # TODO: Return health status- pass+ self._last_health_check = time.time()++ # Check registered components+ health_results = {}++ for component_name, component in self._component_registry.items():+ try:+ # Try to get health from component+ if hasattr(component, "health_check"):+ component_health = component.health_check()+ if isinstance(component_health, dict):+ healthy = component_health.get("healthy", True)+ message = component_health.get("message", "")+ details = component_health.get("details", {})+ else:+ healthy = bool(component_health)+ message = ""+ details = {}+ else:+ # Default: assume healthy if component exists+ healthy = component is not None+ message = ""+ details = {}++ status = HealthStatus(+ component=component_name,+ healthy=healthy,+ message=message,+ details=details+ )++ except Exception as e:+ status = HealthStatus(+ component=component_name,+ healthy=False,+ message=f"Health check failed: {e}",+ details={"error": str(e)}+ )++ health_results[component_name] = status+ self.health_status[component_name] = status++ # Log unhealthy components+ unhealthy = [+ name for name, status in health_results.items()+ if not status.healthy+ ]++ if unhealthy:+ self.logger.warning(+ f"Unhealthy components detected: {unhealthy}",+ extra={"health_status": health_results}+ )++ return health_results++ def register_component(self, name: str, component: Any) -> None:+ """+ Register a component for health monitoring.++ Args:+ name: Component name+ component: Component instance+ """+ self._component_registry[name] = component+ self.logger.debug(f"Registered component: {name}")- def register_startup_hook(self, hook_fn, priority=50):+ def unregister_component(self, name: str) -> None:+ """+ Unregister a component.++ Args:+ name: Component name+ """+ if name in self._component_registry:+ del self._component_registry[name]+ if name in self.health_status:+ del self.health_status[name]+ self.logger.debug(f"Unregistered component: {name}")++ def register_startup_hook(self, hook_fn: Callable[[], None], priority: int = 50) -> None:"""Register a startup hook.+ Hooks are executed in order of priority (lower = earlier).+ Priority values are typically between 0-100.+Args:- hook_fn: Function to call during startup- priority: Hook priority (lower = earlier)+ hook_fn: Function to call during startup (no arguments)+ priority: Hook priority (lower = earlier execution, default: 50)"""- # TODO: Validate hook function- # TODO: Register hook with priority- # TODO: Sort hooks by priority- pass+ if not callable(hook_fn):+ raise ValueError("hook_fn must be callable")++ self.startup_hooks.append((hook_fn, priority))+ self.logger.debug(f"Registered startup hook with priority {priority}")- def register_shutdown_hook(self, hook_fn, priority=50):+ def register_shutdown_hook(+ self,+ hook_fn: Callable[[], None],+ priority: int = 50+ ) -> None:"""Register a shutdown hook.+ Hooks are executed in order of priority (lower = earlier).+ Priority values are typically between 0-100.+Args:- hook_fn: Function to call during shutdown- priority: Hook priority (lower = earlier)+ hook_fn: Function to call during shutdown (no arguments)+ priority: Hook priority (lower = earlier execution, default: 50)"""- # TODO: Validate hook function- # TODO: Register hook with priority- # TODO: Sort hooks by priority- pass-+ if not callable(hook_fn):+ raise ValueError("hook_fn must be callable")++ self.shutdown_hooks.append((hook_fn, priority))+ self.logger.debug(f"Registered shutdown hook with priority {priority}")++ def get_state(self) -> SystemState:+ """+ Get current system state.++ Returns:+ Current system state+ """+ return self.state++ def is_ready(self) -> bool:+ """+ Check if system is ready.++ Returns:+ True if system is ready, False otherwise+ """+ return self.state == SystemState.READY or self.state == SystemState.RUNNING++ def is_running(self) -> bool:+ """+ Check if system is running.++ Returns:+ True if system is running, False otherwise+ """+ return self.state == SystemState.RUNNING++ def get_health_summary(self) -> Dict[str, Any]:+ """+ Get summary of system health.++ Returns:+ Dictionary with health summary information+ """+ health_results = self.health_check()++ total = len(health_results)+ healthy = sum(1 for status in health_results.values() if status.healthy)+ unhealthy = total - healthy++ return {+ "state": self.state.value,+ "total_components": total,+ "healthy_components": healthy,+ "unhealthy_components": unhealthy,+ "is_healthy": unhealthy == 0,+ "last_check": self._last_health_check,+ "components": {+ name: {+ "healthy": status.healthy,+ "message": status.message,+ "timestamp": status.timestamp,+ }+ for name, status in health_results.items()+ }+ }++ def _verify_components(self) -> None:+ """+ Verify that all registered components are initialized.++ Raises:+ SemanticaError: If components are not properly initialized+ """+ uninitialized = []++ for name, component in self._component_registry.items():+ if component is None:+ uninitialized.append(name)++ if uninitialized:+ raise SemanticaError(+ f"Components not initialized: {', '.join(uninitialized)}"+ )++ def _cleanup_resources(self) -> None:+ """Cleanup system resources."""+ # Cleanup components if they have cleanup methods+ for name, component in self._component_registry.items():+ try:+ if hasattr(component, "cleanup"):+ component.cleanup()+ elif hasattr(component, "close"):+ component.close()+ except Exception as e:+ self.logger.warning(f"Failed to cleanup component {name}: {e}")++ # Clear registries+ self._component_registry.clear()+ self.health_status.clear()\ No newline at end of filediff --git a/libs/semantica/core/orchestrator.py b/libs/semantica/core/orchestrator.pyindex 0ca1dd1c..1607b4e3 100644--- a/libs/semantica/core/orchestrator.py+++ b/libs/semantica/core/orchestrator.py@@ -13,9 +13,17 @@ Key Responsibilities:Main Classes:- Semantica: Main framework class- - Orchestrator: Pipeline coordination engine"""+from typing import Any, Dict, List, Optional, Union+from pathlib import Path++from .config_manager import Config, ConfigManager+from .lifecycle import LifecycleManager, SystemState+from .plugin_registry import PluginRegistry+from ..utils.exceptions import ConfigurationError, ProcessingError+from ..utils.logging import get_logger, log_execution_time+class Semantica:"""@@ -26,6 +34,7 @@ class Semantica:Attributes:config: Configuration object+ config_manager: Configuration management systemplugin_registry: Plugin management systemlifecycle_manager: Lifecycle management@@ -36,7 +45,7 @@ class Semantica:get_status(): Get system health and status"""- def __init__(self, config=None, **kwargs):+ def __init__(self, config: Optional[Union[Config, Dict[str, Any]]] = None, **kwargs):"""Initialize Semantica framework.@@ -44,75 +53,350 @@ class Semantica:config: Configuration object or dict**kwargs: Additional configuration parameters"""- # TODO: Initialize configuration- # TODO: Initialize plugin registry- # TODO: Initialize lifecycle manager- # TODO: Initialize all core modules- pass+ self.logger = get_logger("semantica")+ self.config_manager = ConfigManager()++ # Load configuration+ if isinstance(config, Config):+ self.config = config+ elif isinstance(config, dict):+ self.config = self.config_manager.load_from_dict(config)+ else:+ # Load from kwargs or defaults+ self.config = self.config_manager.load_from_dict(kwargs or {})++ # Initialize core components+ self.lifecycle_manager = LifecycleManager()+ self.plugin_registry = PluginRegistry()++ # Register lifecycle manager with itself+ self.lifecycle_manager.register_component("lifecycle_manager", self.lifecycle_manager)+ self.lifecycle_manager.register_component("plugin_registry", self.plugin_registry)+ self.lifecycle_manager.register_component("config_manager", self.config_manager)++ # Module placeholders (to be initialized)+ self._modules: Dict[str, Any] = {}++ self.logger.info("Semantica framework initialized")- def initialize(self):+ @log_execution_time+ def initialize(self) -> None:"""Initialize all framework components.This method sets up all modules, loads plugins, and preparesthe system for processing.++ Raises:+ ConfigurationError: If configuration is invalid+ SemanticaError: If initialization fails"""- # TODO: Load configuration- # TODO: Initialize modules- # TODO: Load plugins- # TODO: Verify dependencies- # TODO: Run health checks- pass+ try:+ self.logger.info("Initializing Semantica framework")++ # Validate configuration+ self.config.validate()++ # Register startup hooks+ self._register_startup_hooks()++ # Execute startup sequence+ self.lifecycle_manager.startup()++ # Initialize modules+ self._initialize_modules()++ # Load plugins if configured+ if self.config.get("plugins", {}):+ self._load_plugins()++ # Run health checks+ health_summary = self.lifecycle_manager.get_health_summary()+ if not health_summary["is_healthy"]:+ self.logger.warning(+ "Some components are unhealthy",+ extra={"health_summary": health_summary}+ )++ self.logger.info("Semantica framework initialization completed")++ except Exception as e:+ self.logger.error(f"Initialization failed: {e}")+ raise- def build_knowledge_base(self, sources, **kwargs):+ @log_execution_time+ def build_knowledge_base(self, sources: List[Union[str, Path]], **kwargs) -> Dict[str, Any]:"""Build knowledge base from data sources.+ This is a high-level method that orchestrates the complete+ knowledge base construction process.+Args:sources: List of data sources (files, URLs, streams)- **kwargs: Additional processing options-+ **kwargs: Additional processing options:+ - pipeline: Custom pipeline configuration+ - embeddings: Whether to generate embeddings+ - graph: Whether to build knowledge graph+ - normalize: Whether to normalize data+Returns:- KnowledgeBase: Constructed knowledge base+ Dictionary containing:+ - knowledge_graph: Knowledge graph data+ - embeddings: Embedding vectors+ - metadata: Processing metadata+ - statistics: Processing statistics++ Raises:+ ProcessingError: If processing fails"""- # TODO: Validate sources- # TODO: Create processing pipeline- # TODO: Execute pipeline- # TODO: Build knowledge graph- # TODO: Generate embeddings- # TODO: Return knowledge base- pass+ try:+ self.logger.info(f"Building knowledge base from {len(sources)} sources")++ # Validate sources+ validated_sources = self._validate_sources(sources)++ # Create processing pipeline+ pipeline_config = kwargs.get("pipeline", {})+ pipeline = self._create_pipeline(pipeline_config)++ # Process sources+ results = []+ for source in validated_sources:+ try:+ result = self.run_pipeline(pipeline, source)+ results.append(result)+ except Exception as e:+ self.logger.error(f"Failed to process source {source}: {e}")+ if kwargs.get("fail_fast", False):+ raise ProcessingError(f"Failed to process source {source}: {e}")++ # Build knowledge graph if requested+ knowledge_graph = None+ if kwargs.get("graph", True):+ knowledge_graph = self._build_knowledge_graph(results)++ # Generate embeddings if requested+ embeddings = None+ if kwargs.get("embeddings", True):+ embeddings = self._generate_embeddings(results)++ # Compile statistics+ statistics = {+ "sources_processed": len(results),+ "sources_total": len(sources),+ "success_rate": len([r for r in results if r.get("success")]) / len(results) if results else 0.0,+ }++ return {+ "knowledge_graph": knowledge_graph,+ "embeddings": embeddings,+ "results": results,+ "statistics": statistics,+ "metadata": {+ "sources": validated_sources,+ "pipeline": pipeline_config,+ }+ }++ except Exception as e:+ self.logger.error(f"Failed to build knowledge base: {e}")+ raise ProcessingError(f"Failed to build knowledge base: {e}")- def run_pipeline(self, pipeline, data):+ @log_execution_time+ def run_pipeline(self, pipeline: Union[Dict[str, Any], Any], data: Any) -> Dict[str, Any]:"""Execute a processing pipeline.Args:- pipeline: Pipeline object to execute+ pipeline: Pipeline object or configuration dictionarydata: Input data for pipelineReturns:- Results of pipeline execution+ Dictionary containing:+ - output: Pipeline output data+ - metadata: Processing metadata+ - metrics: Performance metrics++ Raises:+ ProcessingError: If pipeline execution fails"""- # TODO: Validate pipeline- # TODO: Allocate resources- # TODO: Execute pipeline steps- # TODO: Handle failures- # TODO: Collect metrics- # TODO: Return results- pass+ try:+ self.logger.info("Executing processing pipeline")++ # Validate pipeline+ if isinstance(pipeline, dict):+ pipeline = self._create_pipeline_from_dict(pipeline)++ # Validate pipeline object+ if not hasattr(pipeline, "execute"):+ raise ProcessingError("Pipeline must have execute() method")++ # Allocate resources+ resources = self._allocate_resources(pipeline)++ try:+ # Execute pipeline+ result = pipeline.execute(data)++ # Collect metrics+ metrics = self._collect_metrics(pipeline)++ return {+ "success": True,+ "output": result,+ "metrics": metrics,+ "metadata": {+ "pipeline": str(pipeline),+ "resources": resources,+ }+ }++ finally:+ # Release resources+ self._release_resources(resources)++ except Exception as e:+ self.logger.error(f"Pipeline execution failed: {e}")+ raise ProcessingError(f"Pipeline execution failed: {e}")- def get_status(self):+ def get_status(self) -> Dict[str, Any]:"""Get system health and status.Returns:- dict: System status information+ Dictionary containing:+ - state: System state+ - health: Health summary+ - modules: Module status+ - plugins: Plugin status+ - metrics: System metrics+ """+ health_summary = self.lifecycle_manager.get_health_summary()++ # Get module status+ module_status = {}+ for name, module in self._modules.items():+ module_status[name] = {+ "initialized": module is not None,+ "status": "ready" if module else "not_initialized"+ }++ # Get plugin status+ plugin_status = {}+ try:+ plugins = self.plugin_registry.list_plugins()+ for plugin_info in plugins:+ plugin_status[plugin_info.get("name", "unknown")] = {+ "loaded": plugin_info.get("loaded", False),+ "version": plugin_info.get("version", "unknown")+ }+ except Exception as e:+ self.logger.warning(f"Failed to get plugin status: {e}")++ return {+ "state": self.lifecycle_manager.get_state().value,+ "health": health_summary,+ "modules": module_status,+ "plugins": plugin_status,+ "config": {+ "loaded": self.config is not None,+ "validated": True # Assuming validated if initialized+ }+ }++ def shutdown(self, graceful: bool = True) -> None:+ """+ Shutdown the framework.++ Args:+ graceful: Whether to shutdown gracefully (default: True)"""- # TODO: Check module health- # TODO: Check resource usage- # TODO: Check plugin status- # TODO: Collect metrics- # TODO: Return status dict+ self.logger.info("Shutting down Semantica framework")+ self.lifecycle_manager.shutdown(graceful=graceful)+ self.logger.info("Semantica framework shutdown completed")++ def _register_startup_hooks(self) -> None:+ """Register framework startup hooks."""+ # Register config validation hook+ def validate_config_hook():+ self.config.validate()++ self.lifecycle_manager.register_startup_hook(validate_config_hook, priority=10)++ # Register module initialization hook+ def initialize_modules_hook():+ self._initialize_modules()++ self.lifecycle_manager.register_startup_hook(initialize_modules_hook, priority=30)++ def _initialize_modules(self) -> None:+ """Initialize framework modules."""+ # Module initialization will be implemented when modules are available+ # For now, this is a placeholderpass-++ def _load_plugins(self) -> None:+ """Load configured plugins."""+ plugins_config = self.config.get("plugins", {})++ for plugin_name, plugin_config in plugins_config.items():+ try:+ self.plugin_registry.load_plugin(plugin_name, **plugin_config)+ self.logger.info(f"Loaded plugin: {plugin_name}")+ except Exception as e:+ self.logger.error(f"Failed to load plugin {plugin_name}: {e}")++ def _validate_sources(self, sources: List[Union[str, Path]]) -> List[Union[str, Path]]:+ """Validate data sources."""+ validated = []++ for source in sources:+ source_path = Path(source) if isinstance(source, str) else source++ # Check if source exists (if it's a file path)+ if source_path.exists() or str(source).startswith(("http://", "https://")):+ validated.append(source)+ else:+ self.logger.warning(f"Source not found or invalid: {source}")++ if not validated:+ raise ProcessingError("No valid sources provided")++ return validated++ def _create_pipeline(self, pipeline_config: Dict[str, Any]) -> Any:+ """Create processing pipeline from configuration."""+ # Pipeline creation will be implemented in pipeline module+ # For now, return config as placeholder+ return pipeline_config++ def _create_pipeline_from_dict(self, pipeline_dict: Dict[str, Any]) -> Any:+ """Create pipeline object from dictionary."""+ # This will be implemented when pipeline module is available+ return pipeline_dict++ def _build_knowledge_graph(self, results: List[Dict[str, Any]]) -> Dict[str, Any]:+ """Build knowledge graph from processing results."""+ # Knowledge graph building will be implemented in kg module+ return {"status": "placeholder", "results": results}++ def _generate_embeddings(self, results: List[Dict[str, Any]]) -> Dict[str, Any]:+ """Generate embeddings from processing results."""+ # Embedding generation will be implemented in embeddings module+ return {"status": "placeholder", "results": results}++ def _allocate_resources(self, pipeline: Any) -> Dict[str, Any]:+ """Allocate resources for pipeline execution."""+ # Resource allocation logic+ return {"allocated": True}++ def _release_resources(self, resources: Dict[str, Any]) -> None:+ """Release allocated resources."""+ # Resource release logic+ pass++ def _collect_metrics(self, pipeline: Any) -> Dict[str, Any]:+ """Collect performance metrics from pipeline execution."""+ # Metrics collection logic+ return {"execution_time": 0.0, "memory_usage": 0}\ No newline at end of filediff --git a/libs/semantica/core/plugin_registry.py b/libs/semantica/core/plugin_registry.pyindex ec7977bb..990aa753 100644--- a/libs/semantica/core/plugin_registry.py+++ b/libs/semantica/core/plugin_registry.py@@ -12,10 +12,43 @@ Key Features:Main Classes:- PluginRegistry: Plugin management system- - PluginLoader: Plugin loading mechanism- - PluginValidator: Plugin validation"""+import importlib+import importlib.util+import inspect+import time+from pathlib import Path+from typing import Any, Dict, List, Optional, Type+from dataclasses import dataclass, field++from ..utils.exceptions import ConfigurationError, ValidationError+from ..utils.logging import get_logger+++@dataclass+class PluginInfo:+ """Plugin information."""++ name: str+ version: str+ plugin_class: Type+ description: str = ""+ author: str = ""+ dependencies: List[str] = field(default_factory=list)+ capabilities: List[str] = field(default_factory=list)+ metadata: Dict[str, Any] = field(default_factory=dict)+++@dataclass+class LoadedPlugin:+ """Loaded plugin instance."""++ info: PluginInfo+ instance: Any+ config: Dict[str, Any] = field(default_factory=dict)+ loaded_at: Optional[float] = None+class PluginRegistry:"""@@ -25,34 +58,90 @@ class PluginRegistry:Attributes:plugins: Dictionary of registered plugins- loader: Plugin loader instance- validator: Plugin validator instance+ loaded_plugins: Dictionary of loaded plugin instances+ plugin_paths: List of paths to search for plugins"""- def __init__(self):- """Initialize plugin registry."""- # TODO: Initialize plugin storage- # TODO: Initialize loader- # TODO: Initialize validator- # TODO: Discover available plugins- pass+ def __init__(self, plugin_paths: Optional[List[Path]] = None):+ """+ Initialize plugin registry.++ Args:+ plugin_paths: List of paths to search for plugins+ """+ self.logger = get_logger("plugin_registry")+ self.plugins: Dict[str, PluginInfo] = {}+ self.loaded_plugins: Dict[str, LoadedPlugin] = {}+ self.plugin_paths = plugin_paths or []+ self._discovered_plugins: Dict[str, Path] = {}++ # Discover available plugins+ self._discover_plugins()- def register_plugin(self, plugin_name, plugin_class):+ def register_plugin(+ self,+ plugin_name: str,+ plugin_class: Type,+ version: str = "1.0.0",+ **metadata: Any+ ) -> None:"""Register a plugin.Args:plugin_name: Name of the pluginplugin_class: Plugin class to register+ version: Plugin version+ **metadata: Additional plugin metadata:+ - description: Plugin description+ - author: Plugin author+ - dependencies: List of dependency plugin names+ - capabilities: List of plugin capabilities++ Raises:+ ValidationError: If plugin is invalid"""- # TODO: Validate plugin- # TODO: Check version compatibility- # TODO: Resolve dependencies- # TODO: Register plugin- # TODO: Initialize plugin- pass+ try:+ # Validate plugin class+ if not inspect.isclass(plugin_class):+ raise ValidationError(f"Plugin {plugin_name} must be a class, got {type(plugin_class)}")++ # Check for required methods+ required_methods = ["initialize", "execute"]+ for method in required_methods:+ if not hasattr(plugin_class, method):+ raise ValidationError(+ f"Plugin {plugin_name} must have {method}() method"+ )++ # Create plugin info+ plugin_info = PluginInfo(+ name=plugin_name,+ version=version,+ plugin_class=plugin_class,+ description=metadata.get("description", ""),+ author=metadata.get("author", ""),+ dependencies=metadata.get("dependencies", []),+ capabilities=metadata.get("capabilities", []),+ metadata=metadata+ )++ # Validate dependencies+ self._validate_dependencies(plugin_info)++ # Register plugin+ self.plugins[plugin_name] = plugin_info+ self.logger.info(f"Registered plugin: {plugin_name} v{version}")++ except Exception as e:+ self.logger.error(f"Failed to register plugin {plugin_name}: {e}")+ raise- def load_plugin(self, plugin_name, **config):+ def load_plugin(+ self,+ plugin_name: str,+ **config: Any+ ) -> Any:"""Load and initialize a plugin.@@ -62,41 +151,126 @@ class PluginRegistry:Returns:Loaded and initialized plugin instance++ Raises:+ ConfigurationError: If plugin not found or load fails"""- # TODO: Check if plugin registered- # TODO: Load plugin class- # TODO: Initialize plugin- # TODO: Configure plugin- # TODO: Return plugin instance- pass+ try:+ # Check if already loaded+ if plugin_name in self.loaded_plugins:+ self.logger.debug(f"Plugin {plugin_name} already loaded")+ return self.loaded_plugins[plugin_name].instance++ # Check if plugin registered+ if plugin_name not in self.plugins:+ # Try to discover and register+ self._discover_plugin(plugin_name)++ if plugin_name not in self.plugins:+ raise ConfigurationError(f"Plugin {plugin_name} not found")++ plugin_info = self.plugins[plugin_name]++ # Load dependencies first+ for dep_name in plugin_info.dependencies:+ if dep_name not in self.loaded_plugins:+ self.logger.debug(f"Loading dependency: {dep_name}")+ self.load_plugin(dep_name)++ # Create plugin instance+ plugin_class = plugin_info.plugin_class++ try:+ plugin_instance = plugin_class(**config)+ except TypeError as e:+ # If initialization fails, try without config+ self.logger.warning(f"Failed to initialize with config, trying without: {e}")+ plugin_instance = plugin_class()++ # Initialize plugin+ if hasattr(plugin_instance, "initialize"):+ plugin_instance.initialize()++ # Store loaded plugin+ loaded_plugin = LoadedPlugin(+ info=plugin_info,+ instance=plugin_instance,+ config=config,+ loaded_at=time.time()+ )++ self.loaded_plugins[plugin_name] = loaded_plugin++ self.logger.info(f"Loaded plugin: {plugin_name}")++ return plugin_instance++ except Exception as e:+ self.logger.error(f"Failed to load plugin {plugin_name}: {e}")+ raise ConfigurationError(f"Failed to load plugin {plugin_name}: {e}")- def unload_plugin(self, plugin_name):+ def unload_plugin(self, plugin_name: str) -> None:"""Unload a plugin.Args:plugin_name: Name of plugin to unload++ Raises:+ ConfigurationError: If plugin not loaded"""- # TODO: Check if plugin loaded- # TODO: Call plugin cleanup- # TODO: Unregister plugin- # TODO: Free resources- pass+ if plugin_name not in self.loaded_plugins:+ raise ConfigurationError(f"Plugin {plugin_name} is not loaded")++ try:+ plugin_instance = self.loaded_plugins[plugin_name].instance++ # Call plugin cleanup if available+ if hasattr(plugin_instance, "cleanup"):+ plugin_instance.cleanup()+ elif hasattr(plugin_instance, "close"):+ plugin_instance.close()++ # Remove from loaded plugins+ del self.loaded_plugins[plugin_name]++ self.logger.info(f"Unloaded plugin: {plugin_name}")++ except Exception as e:+ self.logger.error(f"Failed to unload plugin {plugin_name}: {e}")+ raise ConfigurationError(f"Failed to unload plugin {plugin_name}: {e}")- def list_plugins(self):+ def list_plugins(self) -> List[Dict[str, Any]]:"""List all available plugins.Returns:- list: List of plugin information dicts+ List of plugin information dictionaries"""- # TODO: Gather plugin information- # TODO: Include version info- # TODO: Include compatibility info- # TODO: Return list- pass+ plugins = []++ for name, plugin_info in self.plugins.items():+ plugin_data = {+ "name": plugin_info.name,+ "version": plugin_info.version,+ "description": plugin_info.description,+ "author": plugin_info.author,+ "dependencies": plugin_info.dependencies,+ "capabilities": plugin_info.capabilities,+ "loaded": name in self.loaded_plugins,+ "metadata": plugin_info.metadata+ }++ if name in self.loaded_plugins:+ loaded_plugin = self.loaded_plugins[name]+ plugin_data["config"] = loaded_plugin.config+ plugin_data["loaded_at"] = loaded_plugin.loaded_at++ plugins.append(plugin_data)++ return plugins- def get_plugin_info(self, plugin_name):+ def get_plugin_info(self, plugin_name: str) -> Dict[str, Any]:"""Get information about a plugin.@@ -104,12 +278,176 @@ class PluginRegistry:plugin_name: Name of pluginReturns:- dict: Plugin information- """- # TODO: Get plugin metadata- # TODO: Get version info- # TODO: Get dependencies- # TODO: Get capabilities- # TODO: Return info dict- pass-+ Dictionary with plugin information++ Raises:+ ConfigurationError: If plugin not found+ """+ if plugin_name not in self.plugins:+ raise ConfigurationError(f"Plugin {plugin_name} not found")++ plugin_info = self.plugins[plugin_name]++ info = {+ "name": plugin_info.name,+ "version": plugin_info.version,+ "description": plugin_info.description,+ "author": plugin_info.author,+ "dependencies": plugin_info.dependencies,+ "capabilities": plugin_info.capabilities,+ "metadata": plugin_info.metadata,+ "loaded": plugin_name in self.loaded_plugins+ }++ if plugin_name in self.loaded_plugins:+ loaded_plugin = self.loaded_plugins[plugin_name]+ info["config"] = loaded_plugin.config+ info["loaded_at"] = loaded_plugin.loaded_at++ return info++ def is_plugin_loaded(self, plugin_name: str) -> bool:+ """+ Check if a plugin is loaded.++ Args:+ plugin_name: Name of plugin++ Returns:+ True if plugin is loaded, False otherwise+ """+ return plugin_name in self.loaded_plugins++ def get_loaded_plugin(self, plugin_name: str) -> Optional[Any]:+ """+ Get loaded plugin instance.++ Args:+ plugin_name: Name of plugin++ Returns:+ Plugin instance or None if not loaded+ """+ if plugin_name in self.loaded_plugins:+ return self.loaded_plugins[plugin_name].instance+ return None++ def _discover_plugins(self) -> None:+ """Discover available plugins from plugin paths."""+ for plugin_path in self.plugin_paths:+ if isinstance(plugin_path, str):+ plugin_path = Path(plugin_path)++ if plugin_path.exists() and plugin_path.is_dir():+ self._scan_directory(plugin_path)++ def _discover_plugin(self, plugin_name: str) -> None:+ """+ Discover a specific plugin.++ Args:+ plugin_name: Name of plugin to discover+ """+ for plugin_path in self.plugin_paths:+ if isinstance(plugin_path, str):+ plugin_path = Path(plugin_path)++ # Try to find plugin module+ plugin_module_path = plugin_path / f"{plugin_name}.py"+ if plugin_module_path.exists():+ try:+ self._load_plugin_from_file(plugin_module_path, plugin_name)+ break+ except Exception as e:+ self.logger.warning(f"Failed to load plugin from {plugin_module_path}: {e}")++ def _scan_directory(self, directory: Path) -> None:+ """Scan directory for plugin files."""+ for file_path in directory.glob("*.py"):+ if file_path.name == "__init__.py":+ continue++ plugin_name = file_path.stem+ try:+ self._load_plugin_from_file(file_path, plugin_name)+ except Exception as e:+ self.logger.debug(f"Failed to load plugin from {file_path}: {e}")++ def _load_plugin_from_file(self, file_path: Path, plugin_name: str) -> None:+ """Load plugin from file."""+ try:+ # Import module+ spec = importlib.util.spec_from_file_location(plugin_name, file_path)+ if spec is None or spec.loader is None:+ return++ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)++ # Find plugin class (typically named after plugin or has Plugin suffix)+ plugin_class = None++ # Try common naming patterns+ class_names = [+ plugin_name.capitalize(),+ plugin_name.capitalize() + "Plugin",+ plugin_name.replace("_", "").capitalize(),+ ]++ for class_name in class_names:+ if hasattr(module, class_name):+ plugin_class = getattr(module, class_name)+ if inspect.isclass(plugin_class):+ break++ # If not found, look for any class with Plugin in name+ if plugin_class is None:+ for name, obj in inspect.getmembers(module):+ if inspect.isclass(obj) and "Plugin" in name:+ plugin_class = obj+ break++ if plugin_class is None:+ self.logger.warning(f"No plugin class found in {file_path}")+ return++ # Get metadata from module if available+ metadata = {+ "description": getattr(module, "__doc__", "") or getattr(module, "description", ""),+ "author": getattr(module, "author", ""),+ "version": getattr(module, "version", "1.0.0"),+ "dependencies": getattr(module, "dependencies", []),+ "capabilities": getattr(module, "capabilities", []),+ }++ # Register plugin+ self.register_plugin(+ plugin_name=plugin_name,+ plugin_class=plugin_class,+ **metadata+ )++ except Exception as e:+ self.logger.error(f"Failed to load plugin from {file_path}: {e}")+ raise++ def _validate_dependencies(self, plugin_info: PluginInfo) -> None:+ """+ Validate plugin dependencies.++ Args:+ plugin_info: Plugin information++ Raises:+ ValidationError: If dependencies are invalid+ """+ for dep_name in plugin_info.dependencies:+ if dep_name not in self.plugins:+ # Try to discover dependency+ self._discover_plugin(dep_name)++ if dep_name not in self.plugins:+ raise ValidationError(+ f"Plugin {plugin_info.name} depends on {dep_name}, "+ f"but {dep_name} is not available"+ )\ No newline at end of filediff --git a/merge-commands.md b/merge-commands.mdnew file mode 100644index 00000000..5963f274--- /dev/null+++ b/merge-commands.md@@ -0,0 +1,63 @@+# Git Commands to Merge Feature Branch to Main++## Option 1: Merge via GitHub Web Interface (Recommended)++1. **Create PR manually:**+ - Visit: https://github.com/Hawksight-AI/semantica/pull/new/feature/utils-implementation+ - Click "Create pull request"+ - Fill in title and description+ - Click "Create pull request"++2. **Merge PR on GitHub:**+ - Go to the PR page+ - Click "Merge pull request"+ - Click "Confirm merge"+ - Delete branch if prompted++## Option 2: Merge Locally (Direct to Main)++### Commands to merge locally:++```powershell+# 1. Switch to main branch+git checkout main++# 2. Pull latest changes from remote+git pull origin main++# 3. Merge your feature branch+git merge feature/utils-implementation++# 4. Push merged changes to remote+git push origin main++# 5. Delete local feature branch+git branch -d feature/utils-implementation++# 6. Delete remote feature branch (optional)+git push origin --delete feature/utils-implementation+```++## Option 3: Install GitHub CLI (For Future Use)++If you want to use `gh` commands in the future:++```powershell+# Install via winget+winget install --id GitHub.cli++# Or download from: https://cli.github.com/++# Then authenticate+gh auth login+```++## Quick Merge Sequence (Copy-Paste)++```powershell+git checkout main+git pull origin main+git merge feature/utils-implementation+git push origin main+git branch -d feature/utils-implementation+```