# API Reference ## Table of Contents - [Core Components](#core-components) - [BaseAIPlugin](#baseaiplugin) - [IAIPlugin Interface](#iaiplugin-interface) - [AIPluginResult](#aipluginresult) - [Pipeline Architecture](#pipeline-architecture) - [RefactoringPipeline](#refactoringpipeline) - [RefactoringPipelineBuilder](#refactoringpipelinebuilder) - [IRefactoringStage](#irefactoringstage) - [Configuration Management](#configuration-management) - [PluginConfigurationManager](#pluginconfigurationmanager) - [Configuration Classes](#configuration-classes) - [Caching Infrastructure](#caching-infrastructure) - [SyntaxTreeCache](#syntaxtreecache) - [AnalysisCache](#analysiscache) - [Performance Components](#performance-components) - [MemoryEfficientFileProcessor](#memoryefficientfileprocessor) - [AdaptiveConcurrencyManager](#adaptiveconcurrencymanager) - [Security Components](#security-components) - [SecurePathValidator](#securepathvalidator) - [InputSanitizer](#inputsanitizer) - [Telemetry & Monitoring](#telemetry--monitoring) - [RefactoringTelemetry](#refactoringtelemetry) - [SystemPerformanceMonitor](#systemperformancemonitor) - [Error Handling](#error-handling) - [CentralizedErrorHandler](#centralizederrorhandler) - [RefactoringException](#refactoringexception) - [Refactoring Plugins](#refactoring-plugins) - [Core Plugin Types](#core-plugin-types) - [Git Repository Management Plugins](#git-repository-management-plugins) - [Git Repository Data Models](#git-repository-data-models) --- ## Core Components ### BaseAIPlugin Abstract base class providing common functionality for all refactoring plugins. #### Namespace ```csharp MarketAlly.AIPlugin.Refactoring.Core ``` #### Inheritance ```csharp public abstract class BaseAIPlugin : IAIPlugin, IDisposable ``` #### Constructor ```csharp protected BaseAIPlugin( IParameterExtractor? parameterExtractor = null, CentralizedErrorHandler? errorHandler = null, ILogger? logger = null, ISyntaxTreeCache? syntaxTreeCache = null, IAnalysisCache? analysisCache = null, IMemoryPressureMonitor? memoryMonitor = null) ``` #### Abstract Properties ```csharp public abstract IReadOnlyDictionary SupportedParameters { get; } ``` #### Abstract Methods ```csharp protected abstract Task ExecuteInternalAsync(IReadOnlyDictionary parameters); ``` #### Public Methods ```csharp public virtual async Task ExecuteAsync(IReadOnlyDictionary parameters) ``` #### Protected Helper Methods ##### Parameter Extraction ```csharp protected T GetParameter(IReadOnlyDictionary parameters, string key, T defaultValue = default!) protected T GetParameter(IReadOnlyDictionary parameters, string[] keys, T defaultValue = default!) ``` ##### File Processing ```csharp protected async Task ProcessFileAsync(string filePath, CancellationToken cancellationToken = default) protected async Task GetSyntaxTreeAsync(string filePath, CancellationToken cancellationToken = default) ``` ##### Caching ```csharp protected async Task GetOrAnalyzeAsync( string filePath, Func> analyzer, CancellationToken cancellationToken = default) where TResult : class ``` ##### Result Creation ```csharp protected AIPluginResult CreateSuccessResult(object data, string? message = null) protected AIPluginResult CreateErrorResult(string message, Exception? exception = null) protected AIPluginResult CreateValidationErrorResult(string parameterName, string validationMessage) ``` ##### Multi-File Processing ```csharp protected async Task ProcessMultipleFilesAsync( IEnumerable filePaths, Func> processor, CancellationToken cancellationToken = default) ``` #### Example Usage ```csharp public class CustomAnalysisPlugin : BaseAIPlugin { public override IReadOnlyDictionary SupportedParameters => new Dictionary { ["filePath"] = typeof(string), ["analysisOptions"] = typeof(AnalysisOptions) }; protected override async Task ExecuteInternalAsync( IReadOnlyDictionary parameters) { var filePath = GetParameter(parameters, "filePath"); var options = GetParameter(parameters, "analysisOptions", new AnalysisOptions()); var syntaxTree = await GetSyntaxTreeAsync(filePath); var result = await GetOrAnalyzeAsync(filePath, () => AnalyzeCode(syntaxTree, options)); return CreateSuccessResult(result, "Analysis completed successfully"); } } ``` --- ### IAIPlugin Interface Core interface for all AI refactoring plugins. #### Namespace ```csharp MarketAlly.AIPlugin ``` #### Interface Definition ```csharp public interface IAIPlugin { Task ExecuteAsync(IReadOnlyDictionary parameters); } ``` --- ### AIPluginResult Represents the result of a plugin execution. #### Namespace ```csharp MarketAlly.AIPlugin ``` #### Properties ```csharp public class AIPluginResult { public bool Success { get; set; } public string Message { get; set; } public object? Data { get; set; } public Dictionary Metadata { get; set; } public Exception? Exception { get; set; } } ``` #### Factory Methods ```csharp public static AIPluginResult Success(object data, string message = "Operation completed successfully") public static AIPluginResult Error(string message, Exception? exception = null) ``` --- ## Pipeline Architecture ### RefactoringPipeline Orchestrates multi-stage refactoring workflows with error handling and statistics. #### Namespace ```csharp MarketAlly.AIPlugin.Refactoring.Pipeline ``` #### Constructor ```csharp public RefactoringPipeline( ILogger? logger = null, IRefactoringTelemetry? telemetry = null) ``` #### Methods ##### Pipeline Execution ```csharp public async Task ExecuteAsync( RefactoringContext context, CancellationToken cancellationToken = default) ``` ##### Stage Management ```csharp public void AddStage(IRefactoringStage stage) public void RemoveStage(string stageName) public void ConfigureStage(string stageName, IReadOnlyDictionary configuration) public IEnumerable GetStages() ``` ##### Statistics ```csharp public PipelineStatistics GetStatistics() ``` #### Example Usage ```csharp var pipeline = new RefactoringPipeline(logger, telemetry); pipeline.AddStage(new ValidationStage()); pipeline.AddStage(new FileDiscoveryStage()); pipeline.AddStage(new OperationExecutionStage()); var context = new RefactoringContext { ProjectPath = "/path/to/project", Operations = { "analyze", "format" } }; var result = await pipeline.ExecuteAsync(context); ``` --- ### RefactoringPipelineBuilder Fluent builder for constructing refactoring pipelines. #### Namespace ```csharp MarketAlly.AIPlugin.Refactoring.Pipeline ``` #### Methods ##### Configuration ```csharp public RefactoringPipelineBuilder WithLogger(ILogger logger) public RefactoringPipelineBuilder WithTelemetry(IRefactoringTelemetry telemetry) ``` ##### Stage Addition ```csharp public RefactoringPipelineBuilder AddStage(IRefactoringStage stage) public RefactoringPipelineBuilder AddValidation() public RefactoringPipelineBuilder AddFileDiscovery() public RefactoringPipelineBuilder AddOperationExecution(IServiceProvider? serviceProvider = null) ``` ##### Build ```csharp public IRefactoringPipeline Build() ``` #### Example Usage ```csharp var pipeline = new RefactoringPipelineBuilder() .WithLogger(logger) .WithTelemetry(telemetry) .AddValidation() .AddFileDiscovery() .AddOperationExecution() .Build(); ``` --- ### IRefactoringStage Interface for pipeline stages. #### Namespace ```csharp MarketAlly.AIPlugin.Refactoring.Pipeline ``` #### Interface Definition ```csharp public interface IRefactoringStage { string Name { get; } int Priority { get; } bool IsEnabled { get; set; } Task ProcessAsync(RefactoringContext context, CancellationToken cancellationToken = default); Task CanProcessAsync(RefactoringContext context); Task InitializeAsync(IReadOnlyDictionary configuration); Task CleanupAsync(); } ``` #### Base Implementation ```csharp public abstract class BaseRefactoringStage : IRefactoringStage { protected readonly ILogger? Logger; public abstract string Name { get; } public abstract int Priority { get; } public bool IsEnabled { get; set; } = true; public abstract Task ProcessAsync(RefactoringContext context, CancellationToken cancellationToken = default); public virtual Task CanProcessAsync(RefactoringContext context) => Task.FromResult(IsEnabled); public virtual Task InitializeAsync(IReadOnlyDictionary configuration) => Task.CompletedTask; public virtual Task CleanupAsync() => Task.CompletedTask; } ``` --- ## Configuration Management ### PluginConfigurationManager Manages hierarchical configuration loading and caching. #### Namespace ```csharp MarketAlly.AIPlugin.Refactoring.Configuration ``` #### Interface ```csharp public interface IPluginConfigurationManager { Task LoadConfigurationAsync( string pluginName, string? projectPath = null, CancellationToken cancellationToken = default) where TConfig : class, new(); Task SaveConfigurationAsync( string pluginName, TConfig configuration, string? projectPath = null, CancellationToken cancellationToken = default) where TConfig : class; Task ConfigurationExistsAsync( string pluginName, string? projectPath = null, CancellationToken cancellationToken = default); void InvalidateCache(string pluginName, string? projectPath = null); ConfigurationSources GetConfigurationSources(string pluginName, string? projectPath = null); } ``` #### Factory Access ```csharp public static class ConfigurationManagerFactory { public static IPluginConfigurationManager Default { get; } public static IPluginConfigurationManager Create(ILogger? logger = null); } ``` #### Example Usage ```csharp var configManager = ConfigurationManagerFactory.Default; var config = await configManager.LoadConfigurationAsync("CodeAnalysis"); // Configuration automatically merges: project -> user -> global Console.WriteLine($"Complexity threshold: {config.CodeAnalysis.ComplexityThreshold}"); ``` --- ### Configuration Classes #### RefactoringConfiguration ```csharp public class RefactoringConfiguration { public CodeAnalysisConfiguration CodeAnalysis { get; set; } = new(); public FormattingConfiguration Formatting { get; set; } = new(); public DocumentationConfiguration Documentation { get; set; } = new(); public NamingConfiguration Naming { get; set; } = new(); public ExclusionsConfiguration Exclusions { get; set; } = new(); public PerformanceConfiguration Performance { get; set; } = new(); } ``` #### CodeAnalysisConfiguration ```csharp public class CodeAnalysisConfiguration { public int ComplexityThreshold { get; set; } = 10; public int MaxMethodLength { get; set; } = 50; public int MaxClassSize { get; set; } = 500; public AnalysisDepth AnalysisDepth { get; set; } = AnalysisDepth.Detailed; public List EnabledRules { get; set; } = new() { "long-method", "god-class", "duplicate-code" }; public List DisabledRules { get; set; } = new(); public bool IncludeComplexity { get; set; } = true; public bool IncludeCodeSmells { get; set; } = true; public bool IncludeSuggestions { get; set; } = true; } ``` #### PerformanceConfiguration ```csharp public class PerformanceConfiguration { public int MaxConcurrency { get; set; } = 3; public int MaxFilesPerProject { get; set; } = 100; public int CacheExpirationMinutes { get; set; } = 30; public bool EnableMemoryOptimization { get; set; } = true; public bool EnableProgressReporting { get; set; } = true; } ``` --- ## Caching Infrastructure ### SyntaxTreeCache File-system-aware caching for Roslyn syntax trees. #### Namespace ```csharp MarketAlly.AIPlugin.Refactoring.Caching ``` #### Interface ```csharp public interface ISyntaxTreeCache { Task GetOrCreateAsync(string filePath, CancellationToken cancellationToken = default); Task GetAsync(string filePath, CancellationToken cancellationToken = default); Task SetAsync(string filePath, SyntaxTree syntaxTree, CancellationToken cancellationToken = default); Task InvalidateAsync(string filePath); Task ClearAsync(); CacheStatistics GetStatistics(); } ``` #### Factory Access ```csharp public static class SyntaxTreeCacheFactory { public static ISyntaxTreeCache Default { get; } public static ISyntaxTreeCache Create( TimeSpan? expiration = null, long? maxSizeBytes = null, ILogger? logger = null); } ``` #### Example Usage ```csharp var cache = SyntaxTreeCacheFactory.Default; var syntaxTree = await cache.GetOrCreateAsync("/path/to/file.cs"); // Cache automatically invalidates when file changes ``` --- ### AnalysisCache Generic caching for analysis results with content-hash based keys. #### Namespace ```csharp MarketAlly.AIPlugin.Refactoring.Caching ``` #### Interface ```csharp public interface IAnalysisCache { Task GetOrAnalyzeAsync( string filePath, Func> analyzer, CancellationToken cancellationToken = default) where TResult : class; Task GetAsync(string filePath, CancellationToken cancellationToken = default) where TResult : class; Task SetAsync(string filePath, TResult result, CancellationToken cancellationToken = default) where TResult : class; Task InvalidateAsync(string filePath); Task ClearAsync(); CacheStatistics GetStatistics(); } ``` #### Factory Access ```csharp public static class AnalysisCacheFactory { public static IAnalysisCache Default { get; } public static IAnalysisCache Create( TimeSpan? memoryExpiration = null, TimeSpan? diskExpiration = null, long? maxMemorySizeBytes = null, string? diskCacheDirectory = null, ILogger? logger = null); } ``` #### Example Usage ```csharp var cache = AnalysisCacheFactory.Default; var analysisResult = await cache.GetOrAnalyzeAsync("/path/to/file.cs", async () => { // Expensive analysis operation return await PerformComplexAnalysis(); }); ``` --- ## Performance Components ### MemoryEfficientFileProcessor Provides memory-efficient file processing with streaming support. #### Namespace ```csharp MarketAlly.AIPlugin.Refactoring.Performance ``` #### Constructor ```csharp public MemoryEfficientFileProcessor(IMemoryPressureMonitor memoryMonitor) ``` #### Methods ```csharp public async Task ProcessLargeFileAsync(string filePath, CancellationToken cancellationToken = default) public async Task ProcessFileInMemoryAsync(string filePath, CancellationToken cancellationToken = default) public async Task ProcessFileStreamingAsync(string filePath, CancellationToken cancellationToken = default) ``` #### Example Usage ```csharp var processor = new MemoryEfficientFileProcessor(new MemoryPressureMonitor()); var result = await processor.ProcessLargeFileAsync("/path/to/large-file.cs"); // Automatically uses streaming for files > 50MB or under memory pressure ``` --- ### AdaptiveConcurrencyManager Manages dynamic concurrency based on system resources. #### Namespace ```csharp MarketAlly.AIPlugin.Refactoring.Performance ``` #### Extension Methods ```csharp public static async Task ProcessWithAdaptiveConcurrencyAsync( this IEnumerable filePaths, Func> processor, CancellationToken cancellationToken = default) public static async Task ProcessConcurrentlyAsync( this IEnumerable>> tasks, CancellationToken cancellationToken = default) ``` #### Example Usage ```csharp var filePaths = Directory.GetFiles("/path/to/project", "*.cs"); var results = await filePaths.ProcessWithAdaptiveConcurrencyAsync(async filePath => { return await AnalyzeFile(filePath); }); ``` --- ## Security Components ### SecurePathValidator Provides comprehensive path validation and security checks. #### Namespace ```csharp MarketAlly.AIPlugin.Refactoring.Security ``` #### Static Methods ```csharp public static string ValidatePath(string inputPath, string? basePath = null) public static string ValidateAndNormalizePath(string inputPath, string basePath) public static bool IsPathWithinBase(string fullPath, string basePath) public static bool IsFilePathSafeForAnalysis(string filePath) public static bool HasSafeFileExtension(string filePath, IEnumerable? allowedExtensions = null) public static bool IsInDangerousDirectory(string filePath) ``` #### Example Usage ```csharp try { var safePath = SecurePathValidator.ValidatePath(userInputPath); var isAnalysisSafe = SecurePathValidator.IsFilePathSafeForAnalysis(safePath); if (isAnalysisSafe) { // Proceed with file processing } } catch (SecurityException ex) { // Handle security violation } ``` --- ### InputSanitizer Provides input validation and sanitization for various attack vectors. #### Namespace ```csharp MarketAlly.AIPlugin.Refactoring.Security ``` #### Static Methods ```csharp public static bool IsInputSafe(this string input) public static string SanitizeInput(string input) public static bool ContainsXssPatterns(string input) public static bool ContainsSqlInjectionPatterns(string input) public static bool ContainsCommandInjectionPatterns(string input) public static string SanitizeFileName(string fileName) public static string CreateSafeIdentifier(string input) ``` #### Example Usage ```csharp var userInput = GetUserInput(); if (userInput.IsInputSafe()) { var sanitized = InputSanitizer.SanitizeInput(userInput); // Use sanitized input } else { // Reject unsafe input } ``` --- ## Telemetry & Monitoring ### RefactoringTelemetry OpenTelemetry-compatible telemetry system for monitoring refactoring operations. #### Namespace ```csharp MarketAlly.AIPlugin.Refactoring.Telemetry ``` #### Interface ```csharp public interface IRefactoringTelemetry { Task TrackOperationAsync( string operationName, Func> operation, Dictionary? tags = null, [CallerMemberName] string? callerName = null); void RecordMetric(string metricName, double value, Dictionary? tags = null); void RecordCounter(string counterName, int value = 1, Dictionary? tags = null); void RecordDuration(string operationName, TimeSpan duration, Dictionary? tags = null); Activity? StartActivity(string activityName, Dictionary? tags = null); void SetActivityData(Activity? activity, string key, object value); TelemetryStatistics GetStatistics(); void Flush(); } ``` #### Factory Access ```csharp public static class TelemetryFactory { public static IRefactoringTelemetry Default { get; } public static IRefactoringTelemetry Create(ILogger? logger = null); public static IPerformanceMonitor PerformanceMonitor { get; } public static IPerformanceMonitor CreatePerformanceMonitor(ILogger? logger = null); } ``` #### Example Usage ```csharp var telemetry = TelemetryFactory.Default; var result = await telemetry.TrackOperationAsync("CodeAnalysis", async () => { return await PerformCodeAnalysis(); }); telemetry.RecordMetric("complexity", 15.5); telemetry.RecordCounter("files_processed", 1); var stats = telemetry.GetStatistics(); Console.WriteLine($"Success rate: {stats.SuccessRate:P2}"); ``` --- ### SystemPerformanceMonitor Real-time system performance monitoring. #### Namespace ```csharp MarketAlly.AIPlugin.Refactoring.Telemetry ``` #### Interface ```csharp public interface IPerformanceMonitor { SystemPerformanceMetrics GetCurrentMetrics(); void StartMonitoring(); void StopMonitoring(); Task GenerateReportAsync(TimeSpan period); } ``` #### Example Usage ```csharp var monitor = TelemetryFactory.CreatePerformanceMonitor(); monitor.StartMonitoring(); // ... perform operations ... var report = await monitor.GenerateReportAsync(TimeSpan.FromMinutes(30)); Console.WriteLine($"Peak memory: {report.PeakMetrics.MemoryUsageBytes / 1024 / 1024}MB"); Console.WriteLine($"Average CPU: {report.AverageMetrics.CpuUsagePercent:F1}%"); monitor.StopMonitoring(); ``` --- ## Error Handling ### CentralizedErrorHandler Provides centralized error handling with recovery strategies. #### Namespace ```csharp MarketAlly.AIPlugin.Refactoring.Plugins ``` #### Constructor ```csharp public CentralizedErrorHandler(IErrorHandlingService errorService) ``` #### Methods ```csharp public void AddRecoveryStrategy(IErrorRecoveryStrategy strategy) public async Task HandleErrorAsync(string pluginName, string operation, Exception exception) ``` #### Global Access ```csharp public static class GlobalErrorHandler { public static CentralizedErrorHandler Instance { get; } } ``` #### Example Usage ```csharp var errorHandler = GlobalErrorHandler.Instance; errorHandler.AddRecoveryStrategy(new FileAccessRecoveryStrategy()); try { // Risky operation } catch (Exception ex) { var result = await errorHandler.HandleErrorAsync("MyPlugin", "ProcessFile", ex); if (result == null) { // Error was recovered, continue operation } else { // Error could not be recovered, handle gracefully } } ``` --- ### RefactoringException Structured exception with context information. #### Namespace ```csharp MarketAlly.AIPlugin.Refactoring.Plugins ``` #### Constructor ```csharp public RefactoringException( string pluginName, string operation, RefactoringErrorCode errorCode, string message, Exception innerException = null) ``` #### Properties ```csharp public string PluginName { get; } public string Operation { get; } public RefactoringErrorCode ErrorCode { get; } public Dictionary Context { get; } ``` #### Error Codes ```csharp public enum RefactoringErrorCode { Unknown, InvalidInput, FileNotFound, DirectoryNotFound, FileAccessDenied, ParseError, AnalysisError, ConfigurationError, TimeoutExceeded, OperationCancelled, InsufficientMemory, GitError, NetworkError, ApiError, SecurityViolation } ``` --- ## Refactoring Plugins ### Core Plugin Types #### CodeAnalysisPlugin ```csharp public class CodeAnalysisPlugin : BaseAIPlugin { public override IReadOnlyDictionary SupportedParameters => new Dictionary { ["filePath"] = typeof(string), ["projectPath"] = typeof(string), ["analysisDepth"] = typeof(string), ["includeComplexity"] = typeof(bool), ["complexityThreshold"] = typeof(int) }; } ``` #### CodeFormatterPlugin ```csharp public class CodeFormatterPlugin : BaseAIPlugin { public override IReadOnlyDictionary SupportedParameters => new Dictionary { ["filePath"] = typeof(string), ["style"] = typeof(string), ["indentationSize"] = typeof(int), ["organizeUsings"] = typeof(bool), ["createBackup"] = typeof(bool) }; } ``` #### DocumentationGeneratorPlugin ```csharp public class DocumentationGeneratorPlugin : BaseAIPlugin { public override IReadOnlyDictionary SupportedParameters => new Dictionary { ["filePath"] = typeof(string), ["style"] = typeof(string), ["includeExamples"] = typeof(bool), ["scope"] = typeof(string) }; } ``` #### NamingConventionPlugin ```csharp public class NamingConventionPlugin : BaseAIPlugin { public override IReadOnlyDictionary SupportedParameters => new Dictionary { ["filePath"] = typeof(string), ["convention"] = typeof(string), ["checkMeaningfulness"] = typeof(bool), ["aiSuggestions"] = typeof(bool) }; } ``` ### Git Repository Management Plugins Specialized plugins for Git repository operations including cloning, validation, status checking, and updates. #### GitHubClonePlugin **Plugin Name**: `github-clone` **Description**: Clone and validate GitHub repositories for project analysis with comprehensive options. **Namespace**: `MarketAlly.AIPlugin.Refactoring.Plugins` **Supported Parameters**: ```csharp public class GitHubClonePlugin : IAIPlugin { public IReadOnlyDictionary SupportedParameters => new Dictionary { ["repository_url"] = typeof(string), // Required: GitHub repository URL ["target_path"] = typeof(string), // Required: Local clone destination ["branch"] = typeof(string), // Optional: Specific branch (defaults to detected default) ["shallow_clone"] = typeof(bool), // Optional: Enable shallow clone (default: true) ["overwrite_existing"] = typeof(bool) // Optional: Overwrite existing directory (default: false) }; } ``` **Features**: - Repository URL validation and accessibility checking - Automatic default branch detection (main/master) - Shallow cloning for faster operations - Size and file count tracking - Comprehensive error handling with cleanup on failure - Timeout protection (configurable, default 30 minutes) **Returns**: `GitCloneResult` with clone metadata, commit information, and repository statistics. **Example Usage**: ```csharp var cloneResult = await registry.CallFunctionAsync("github-clone", new Dictionary { ["repository_url"] = "https://github.com/microsoft/typescript.git", ["target_path"] = "/analysis/projects/typescript", ["branch"] = "main", ["shallow_clone"] = true, ["overwrite_existing"] = false }); if (cloneResult.Success) { var data = (GitCloneResult)cloneResult.Data; Console.WriteLine($"Cloned {data.FileCount} files ({data.SizeBytes / 1024 / 1024} MB)"); Console.WriteLine($"Latest commit: {data.CommitHash} by {data.CommitAuthor}"); } ``` #### GitHubValidatePlugin **Plugin Name**: `github-validate` **Description**: Validate GitHub repository accessibility and retrieve metadata without cloning. **Namespace**: `MarketAlly.AIPlugin.Refactoring.Plugins` **Supported Parameters**: ```csharp public class GitHubValidatePlugin : IAIPlugin { public IReadOnlyDictionary SupportedParameters => new Dictionary { ["repository_url"] = typeof(string) // Required: Repository URL to validate }; } ``` **Features**: - URL format validation - Repository accessibility checking via `git ls-remote` - Default branch detection - Repository host validation (GitHub, GitLab, Bitbucket) - Public/private status detection - Owner and repository name parsing **Returns**: `GitRepositoryValidation` with accessibility status and repository metadata. **Example Usage**: ```csharp var validateResult = await registry.CallFunctionAsync("github-validate", new Dictionary { ["repository_url"] = "https://github.com/dotnet/aspnetcore.git" }); if (validateResult.Success) { var validation = (GitRepositoryValidation)validateResult.Data; if (validation.IsValid) { Console.WriteLine($"Repository: {validation.Owner}/{validation.Repository}"); Console.WriteLine($"Default branch: {validation.DefaultBranch}"); Console.WriteLine($"Host: {validation.RepositoryHost}"); } } ``` #### GitHubStatusPlugin **Plugin Name**: `github-status` **Description**: Get comprehensive status information for cloned repositories including commit details and remote updates. **Namespace**: `MarketAlly.AIPlugin.Refactoring.Plugins` **Supported Parameters**: ```csharp public class GitHubStatusPlugin : IAIPlugin { public IReadOnlyDictionary SupportedParameters => new Dictionary { ["repository_path"] = typeof(string), // Required: Local repository path ["check_remote_updates"] = typeof(bool) // Optional: Check for remote updates (default: true) }; } ``` **Features**: - Current branch detection - Latest commit information (hash, message, author, date) - Working directory cleanliness check - Remote update availability checking - Repository validity verification - Comprehensive Git status output **Returns**: `GitRepositoryStatus` with complete repository state information. **Example Usage**: ```csharp var statusResult = await registry.CallFunctionAsync("github-status", new Dictionary { ["repository_path"] = "/local/projects/my-repo", ["check_remote_updates"] = true }); if (statusResult.Success) { var status = (GitRepositoryStatus)statusResult.Data; Console.WriteLine($"Branch: {status.CurrentBranch}"); Console.WriteLine($"Latest commit: {status.LatestCommitSha[..8]} - {status.LatestCommitMessage}"); Console.WriteLine($"Clean: {status.IsClean}, Remote updates: {status.HasRemoteUpdates}"); } ``` #### GitHubUpdatePlugin **Plugin Name**: `github-update` **Description**: Pull latest changes from remote repository with conflict resolution options. **Namespace**: `MarketAlly.AIPlugin.Refactoring.Plugins` **Supported Parameters**: ```csharp public class GitHubUpdatePlugin : IAIPlugin { public IReadOnlyDictionary SupportedParameters => new Dictionary { ["repository_path"] = typeof(string), // Required: Local repository path ["force_update"] = typeof(bool) // Optional: Force update despite local changes (default: false) }; } ``` **Features**: - Automatic `git pull` execution - Uncommitted changes detection - Optional stashing of local changes before update - Commit hash comparison (before/after) - Changed files counting - Timeout protection (default 10 minutes) - Comprehensive error handling **Returns**: `GitUpdateResult` with update statistics and change information. **Example Usage**: ```csharp var updateResult = await registry.CallFunctionAsync("github-update", new Dictionary { ["repository_path"] = "/local/projects/my-repo", ["force_update"] = false }); if (updateResult.Success) { var update = (GitUpdateResult)updateResult.Data; if (update.HasChanges) { Console.WriteLine($"Updated from {update.PreviousCommitHash[..8]} to {update.NewCommitHash[..8]}"); Console.WriteLine($"Changed files: {update.ChangedFiles}"); if (update.StashedChanges) { Console.WriteLine("Local changes were stashed"); } } else { Console.WriteLine("Repository is up to date"); } } ``` ### Git Repository Data Models #### GitCloneResult ```csharp public class GitCloneResult { public bool Success { get; set; } public string? Error { get; set; } public string? Warning { get; set; } public string RepositoryUrl { get; set; } = string.Empty; public string TargetPath { get; set; } = string.Empty; public string Branch { get; set; } = string.Empty; public string CommitHash { get; set; } = string.Empty; public string CommitMessage { get; set; } = string.Empty; public string CommitAuthor { get; set; } = string.Empty; public DateTime ClonedAt { get; set; } public long SizeBytes { get; set; } public int FileCount { get; set; } } ``` #### GitRepositoryValidation ```csharp public class GitRepositoryValidation { public bool IsValid { get; set; } public bool IsAccessible { get; set; } public string RepositoryUrl { get; set; } = string.Empty; public string? RepositoryHost { get; set; } public string? Owner { get; set; } public string? Repository { get; set; } public string? DefaultBranch { get; set; } public bool IsPublic { get; set; } public string? Error { get; set; } } ``` #### GitRepositoryStatus ```csharp public class GitRepositoryStatus { public bool IsValid { get; set; } public string RepositoryPath { get; set; } = string.Empty; public string CurrentBranch { get; set; } = string.Empty; public string LatestCommitSha { get; set; } = string.Empty; public string LatestCommitMessage { get; set; } = string.Empty; public string LatestCommitAuthor { get; set; } = string.Empty; public string LatestCommitDate { get; set; } = string.Empty; public bool IsClean { get; set; } public string StatusOutput { get; set; } = string.Empty; public bool HasRemoteUpdates { get; set; } public string? Error { get; set; } } ``` #### GitUpdateResult ```csharp public class GitUpdateResult { public bool Success { get; set; } public string? Error { get; set; } public string RepositoryPath { get; set; } = string.Empty; public string PreviousCommitHash { get; set; } = string.Empty; public string NewCommitHash { get; set; } = string.Empty; public DateTime UpdatedAt { get; set; } public bool HasChanges { get; set; } public int ChangedFiles { get; set; } public bool StashedChanges { get; set; } } ``` ### Plugin Registration and Usage #### AIPluginRegistry ```csharp public class AIPluginRegistry { public void RegisterPlugin(IAIPlugin plugin) public void RegisterPlugin() where T : IAIPlugin, new() public async Task CallFunctionAsync(string pluginName, IReadOnlyDictionary parameters) public IEnumerable GetRegisteredPluginNames() } ``` #### Example Usage ```csharp var registry = new AIPluginRegistry(); registry.RegisterPlugin(new CodeAnalysisPlugin()); registry.RegisterPlugin(new CodeFormatterPlugin()); // Register Git repository management plugins registry.RegisterPlugin(new GitHubClonePlugin()); registry.RegisterPlugin(new GitHubValidatePlugin()); registry.RegisterPlugin(new GitHubStatusPlugin()); registry.RegisterPlugin(new GitHubUpdatePlugin()); var parameters = new Dictionary { ["filePath"] = "/path/to/file.cs", ["analysisDepth"] = "comprehensive" }; var result = await registry.CallFunctionAsync("CodeAnalysis", parameters); // Clone a repository for analysis var cloneParameters = new Dictionary { ["repository_url"] = "https://github.com/owner/repo.git", ["target_path"] = "/local/analysis/repo", ["branch"] = "main", ["shallow_clone"] = true }; var cloneResult = await registry.CallFunctionAsync("github-clone", cloneParameters); if (cloneResult.Success) { var cloneData = (GitCloneResult)cloneResult.Data; Console.WriteLine($"Repository cloned: {cloneData.CommitHash}"); } ``` --- ## Best Practices ### Plugin Development 1. Always inherit from `BaseAIPlugin` for common functionality 2. Implement proper parameter validation in `ValidatePluginSpecificParameters` 3. Use caching methods (`GetSyntaxTreeAsync`, `GetOrAnalyzeAsync`) for performance 4. Handle errors gracefully with descriptive messages 5. Use telemetry for monitoring and debugging ### Configuration 1. Use the JSON schema for validation and IntelliSense 2. Implement hierarchical configuration (project > user > global) 3. Cache configuration for performance 4. Validate configuration at startup ### Security 1. Always validate file paths using `SecurePathValidator` 2. Sanitize all user inputs with `InputSanitizer` 3. Use the security extension methods for common validations 4. Implement proper error handling for security violations ### Performance 1. Use memory-efficient processing for large files 2. Leverage adaptive concurrency for multi-file operations 3. Implement proper caching strategies 4. Monitor system resources during operations ### Monitoring 1. Use telemetry for all operations 2. Implement proper error tracking 3. Monitor system performance 4. Use structured logging with context --- *This API reference covers the complete public API surface of the MarketAlly.AIPlugin.Refactoring library. For additional examples and advanced usage patterns, refer to the main [README.md](README.md) documentation.*