MarketAlly.AIPlugin.Extensions/MarketAlly.AIPlugin.Refacto.../API_REFERENCE.md

36 KiB
Executable File

API Reference

Table of Contents


Core Components

BaseAIPlugin

Abstract base class providing common functionality for all refactoring plugins.

Namespace

MarketAlly.AIPlugin.Refactoring.Core

Inheritance

public abstract class BaseAIPlugin : IAIPlugin, IDisposable

Constructor

protected BaseAIPlugin(
    IParameterExtractor? parameterExtractor = null,
    CentralizedErrorHandler? errorHandler = null,
    ILogger? logger = null,
    ISyntaxTreeCache? syntaxTreeCache = null,
    IAnalysisCache? analysisCache = null,
    IMemoryPressureMonitor? memoryMonitor = null)

Abstract Properties

public abstract IReadOnlyDictionary<string, Type> SupportedParameters { get; }

Abstract Methods

protected abstract Task<AIPluginResult> ExecuteInternalAsync(IReadOnlyDictionary<string, object> parameters);

Public Methods

public virtual async Task<AIPluginResult> ExecuteAsync(IReadOnlyDictionary<string, object> parameters)

Protected Helper Methods

Parameter Extraction
protected T GetParameter<T>(IReadOnlyDictionary<string, object> parameters, string key, T defaultValue = default!)
protected T GetParameter<T>(IReadOnlyDictionary<string, object> parameters, string[] keys, T defaultValue = default!)
File Processing
protected async Task<ProcessingResult> ProcessFileAsync(string filePath, CancellationToken cancellationToken = default)
protected async Task<Microsoft.CodeAnalysis.SyntaxTree> GetSyntaxTreeAsync(string filePath, CancellationToken cancellationToken = default)
Caching
protected async Task<TResult> GetOrAnalyzeAsync<TResult>(
    string filePath,
    Func<Task<TResult>> analyzer,
    CancellationToken cancellationToken = default) where TResult : class
Result Creation
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
protected async Task<TResult[]> ProcessMultipleFilesAsync<TResult>(
    IEnumerable<string> filePaths,
    Func<string, Task<TResult>> processor,
    CancellationToken cancellationToken = default)

Example Usage

public class CustomAnalysisPlugin : BaseAIPlugin
{
    public override IReadOnlyDictionary<string, Type> SupportedParameters =>
        new Dictionary<string, Type>
        {
            ["filePath"] = typeof(string),
            ["analysisOptions"] = typeof(AnalysisOptions)
        };

    protected override async Task<AIPluginResult> ExecuteInternalAsync(
        IReadOnlyDictionary<string, object> parameters)
    {
        var filePath = GetParameter<string>(parameters, "filePath");
        var options = GetParameter<AnalysisOptions>(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

MarketAlly.AIPlugin

Interface Definition

public interface IAIPlugin
{
    Task<AIPluginResult> ExecuteAsync(IReadOnlyDictionary<string, object> parameters);
}

AIPluginResult

Represents the result of a plugin execution.

Namespace

MarketAlly.AIPlugin

Properties

public class AIPluginResult
{
    public bool Success { get; set; }
    public string Message { get; set; }
    public object? Data { get; set; }
    public Dictionary<string, object> Metadata { get; set; }
    public Exception? Exception { get; set; }
}

Factory Methods

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

MarketAlly.AIPlugin.Refactoring.Pipeline

Constructor

public RefactoringPipeline(
    ILogger<RefactoringPipeline>? logger = null,
    IRefactoringTelemetry? telemetry = null)

Methods

Pipeline Execution
public async Task<PipelineResult> ExecuteAsync(
    RefactoringContext context,
    CancellationToken cancellationToken = default)
Stage Management
public void AddStage(IRefactoringStage stage)
public void RemoveStage(string stageName)
public void ConfigureStage(string stageName, IReadOnlyDictionary<string, object> configuration)
public IEnumerable<IRefactoringStage> GetStages()
Statistics
public PipelineStatistics GetStatistics()

Example Usage

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

MarketAlly.AIPlugin.Refactoring.Pipeline

Methods

Configuration
public RefactoringPipelineBuilder WithLogger(ILogger<RefactoringPipeline> logger)
public RefactoringPipelineBuilder WithTelemetry(IRefactoringTelemetry telemetry)
Stage Addition
public RefactoringPipelineBuilder AddStage(IRefactoringStage stage)
public RefactoringPipelineBuilder AddValidation()
public RefactoringPipelineBuilder AddFileDiscovery()
public RefactoringPipelineBuilder AddOperationExecution(IServiceProvider? serviceProvider = null)
Build
public IRefactoringPipeline Build()

Example Usage

var pipeline = new RefactoringPipelineBuilder()
    .WithLogger(logger)
    .WithTelemetry(telemetry)
    .AddValidation()
    .AddFileDiscovery()
    .AddOperationExecution()
    .Build();

IRefactoringStage

Interface for pipeline stages.

Namespace

MarketAlly.AIPlugin.Refactoring.Pipeline

Interface Definition

public interface IRefactoringStage
{
    string Name { get; }
    int Priority { get; }
    bool IsEnabled { get; set; }
    
    Task<RefactoringContext> ProcessAsync(RefactoringContext context, CancellationToken cancellationToken = default);
    Task<bool> CanProcessAsync(RefactoringContext context);
    Task InitializeAsync(IReadOnlyDictionary<string, object> configuration);
    Task CleanupAsync();
}

Base Implementation

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<RefactoringContext> ProcessAsync(RefactoringContext context, CancellationToken cancellationToken = default);
    public virtual Task<bool> CanProcessAsync(RefactoringContext context) => Task.FromResult(IsEnabled);
    public virtual Task InitializeAsync(IReadOnlyDictionary<string, object> configuration) => Task.CompletedTask;
    public virtual Task CleanupAsync() => Task.CompletedTask;
}

Configuration Management

PluginConfigurationManager

Manages hierarchical configuration loading and caching.

Namespace

MarketAlly.AIPlugin.Refactoring.Configuration

Interface

public interface IPluginConfigurationManager
{
    Task<TConfig> LoadConfigurationAsync<TConfig>(
        string pluginName,
        string? projectPath = null,
        CancellationToken cancellationToken = default) where TConfig : class, new();

    Task SaveConfigurationAsync<TConfig>(
        string pluginName,
        TConfig configuration,
        string? projectPath = null,
        CancellationToken cancellationToken = default) where TConfig : class;

    Task<bool> 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

public static class ConfigurationManagerFactory
{
    public static IPluginConfigurationManager Default { get; }
    public static IPluginConfigurationManager Create(ILogger<PluginConfigurationManager>? logger = null);
}

Example Usage

var configManager = ConfigurationManagerFactory.Default;
var config = await configManager.LoadConfigurationAsync<RefactoringConfiguration>("CodeAnalysis");

// Configuration automatically merges: project -> user -> global
Console.WriteLine($"Complexity threshold: {config.CodeAnalysis.ComplexityThreshold}");

Configuration Classes

RefactoringConfiguration

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

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<string> EnabledRules { get; set; } = new() { "long-method", "god-class", "duplicate-code" };
    public List<string> DisabledRules { get; set; } = new();
    public bool IncludeComplexity { get; set; } = true;
    public bool IncludeCodeSmells { get; set; } = true;
    public bool IncludeSuggestions { get; set; } = true;
}

PerformanceConfiguration

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

MarketAlly.AIPlugin.Refactoring.Caching

Interface

public interface ISyntaxTreeCache
{
    Task<SyntaxTree> GetOrCreateAsync(string filePath, CancellationToken cancellationToken = default);
    Task<SyntaxTree?> 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

public static class SyntaxTreeCacheFactory
{
    public static ISyntaxTreeCache Default { get; }
    public static ISyntaxTreeCache Create(
        TimeSpan? expiration = null,
        long? maxSizeBytes = null,
        ILogger<SyntaxTreeCache>? logger = null);
}

Example Usage

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

MarketAlly.AIPlugin.Refactoring.Caching

Interface

public interface IAnalysisCache
{
    Task<TResult> GetOrAnalyzeAsync<TResult>(
        string filePath,
        Func<Task<TResult>> analyzer,
        CancellationToken cancellationToken = default) where TResult : class;

    Task<TResult?> GetAsync<TResult>(string filePath, CancellationToken cancellationToken = default) where TResult : class;
    Task SetAsync<TResult>(string filePath, TResult result, CancellationToken cancellationToken = default) where TResult : class;
    Task InvalidateAsync(string filePath);
    Task ClearAsync();
    CacheStatistics GetStatistics();
}

Factory Access

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<AnalysisCache>? logger = null);
}

Example Usage

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

MarketAlly.AIPlugin.Refactoring.Performance

Constructor

public MemoryEfficientFileProcessor(IMemoryPressureMonitor memoryMonitor)

Methods

public async Task<ProcessingResult> ProcessLargeFileAsync(string filePath, CancellationToken cancellationToken = default)
public async Task<ProcessingResult> ProcessFileInMemoryAsync(string filePath, CancellationToken cancellationToken = default)
public async Task<ProcessingResult> ProcessFileStreamingAsync(string filePath, CancellationToken cancellationToken = default)

Example Usage

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

MarketAlly.AIPlugin.Refactoring.Performance

Extension Methods

public static async Task<T[]> ProcessWithAdaptiveConcurrencyAsync<T>(
    this IEnumerable<string> filePaths,
    Func<string, Task<T>> processor,
    CancellationToken cancellationToken = default)

public static async Task<T[]> ProcessConcurrentlyAsync<T>(
    this IEnumerable<Func<Task<T>>> tasks,
    CancellationToken cancellationToken = default)

Example Usage

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

MarketAlly.AIPlugin.Refactoring.Security

Static Methods

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<string>? allowedExtensions = null)
public static bool IsInDangerousDirectory(string filePath)

Example Usage

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

MarketAlly.AIPlugin.Refactoring.Security

Static Methods

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

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

MarketAlly.AIPlugin.Refactoring.Telemetry

Interface

public interface IRefactoringTelemetry
{
    Task<T> TrackOperationAsync<T>(
        string operationName,
        Func<Task<T>> operation,
        Dictionary<string, object>? tags = null,
        [CallerMemberName] string? callerName = null);

    void RecordMetric(string metricName, double value, Dictionary<string, object>? tags = null);
    void RecordCounter(string counterName, int value = 1, Dictionary<string, object>? tags = null);
    void RecordDuration(string operationName, TimeSpan duration, Dictionary<string, object>? tags = null);
    
    Activity? StartActivity(string activityName, Dictionary<string, object>? tags = null);
    void SetActivityData(Activity? activity, string key, object value);
    
    TelemetryStatistics GetStatistics();
    void Flush();
}

Factory Access

public static class TelemetryFactory
{
    public static IRefactoringTelemetry Default { get; }
    public static IRefactoringTelemetry Create(ILogger<RefactoringTelemetry>? logger = null);
    public static IPerformanceMonitor PerformanceMonitor { get; }
    public static IPerformanceMonitor CreatePerformanceMonitor(ILogger<SystemPerformanceMonitor>? logger = null);
}

Example Usage

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

MarketAlly.AIPlugin.Refactoring.Telemetry

Interface

public interface IPerformanceMonitor
{
    SystemPerformanceMetrics GetCurrentMetrics();
    void StartMonitoring();
    void StopMonitoring();
    Task<PerformanceReport> GenerateReportAsync(TimeSpan period);
}

Example Usage

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

MarketAlly.AIPlugin.Refactoring.Plugins

Constructor

public CentralizedErrorHandler(IErrorHandlingService errorService)

Methods

public void AddRecoveryStrategy(IErrorRecoveryStrategy strategy)
public async Task<AIPluginResult> HandleErrorAsync(string pluginName, string operation, Exception exception)

Global Access

public static class GlobalErrorHandler
{
    public static CentralizedErrorHandler Instance { get; }
}

Example Usage

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

MarketAlly.AIPlugin.Refactoring.Plugins

Constructor

public RefactoringException(
    string pluginName,
    string operation,
    RefactoringErrorCode errorCode,
    string message,
    Exception innerException = null)

Properties

public string PluginName { get; }
public string Operation { get; }
public RefactoringErrorCode ErrorCode { get; }
public Dictionary<string, object> Context { get; }

Error Codes

public enum RefactoringErrorCode
{
    Unknown,
    InvalidInput,
    FileNotFound,
    DirectoryNotFound,
    FileAccessDenied,
    ParseError,
    AnalysisError,
    ConfigurationError,
    TimeoutExceeded,
    OperationCancelled,
    InsufficientMemory,
    GitError,
    NetworkError,
    ApiError,
    SecurityViolation
}

Refactoring Plugins

Core Plugin Types

CodeAnalysisPlugin

public class CodeAnalysisPlugin : BaseAIPlugin
{
    public override IReadOnlyDictionary<string, Type> SupportedParameters =>
        new Dictionary<string, Type>
        {
            ["filePath"] = typeof(string),
            ["projectPath"] = typeof(string),
            ["analysisDepth"] = typeof(string),
            ["includeComplexity"] = typeof(bool),
            ["complexityThreshold"] = typeof(int)
        };
}

CodeFormatterPlugin

public class CodeFormatterPlugin : BaseAIPlugin
{
    public override IReadOnlyDictionary<string, Type> SupportedParameters =>
        new Dictionary<string, Type>
        {
            ["filePath"] = typeof(string),
            ["style"] = typeof(string),
            ["indentationSize"] = typeof(int),
            ["organizeUsings"] = typeof(bool),
            ["createBackup"] = typeof(bool)
        };
}

DocumentationGeneratorPlugin

public class DocumentationGeneratorPlugin : BaseAIPlugin
{
    public override IReadOnlyDictionary<string, Type> SupportedParameters =>
        new Dictionary<string, Type>
        {
            ["filePath"] = typeof(string),
            ["style"] = typeof(string),
            ["includeExamples"] = typeof(bool),
            ["scope"] = typeof(string)
        };
}

NamingConventionPlugin

public class NamingConventionPlugin : BaseAIPlugin
{
    public override IReadOnlyDictionary<string, Type> SupportedParameters =>
        new Dictionary<string, Type>
        {
            ["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:

public class GitHubClonePlugin : IAIPlugin
{
    public IReadOnlyDictionary<string, Type> SupportedParameters =>
        new Dictionary<string, Type>
        {
            ["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:

var cloneResult = await registry.CallFunctionAsync("github-clone", new Dictionary<string, object>
{
    ["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:

public class GitHubValidatePlugin : IAIPlugin
{
    public IReadOnlyDictionary<string, Type> SupportedParameters =>
        new Dictionary<string, Type>
        {
            ["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:

var validateResult = await registry.CallFunctionAsync("github-validate", new Dictionary<string, object>
{
    ["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:

public class GitHubStatusPlugin : IAIPlugin
{
    public IReadOnlyDictionary<string, Type> SupportedParameters =>
        new Dictionary<string, Type>
        {
            ["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:

var statusResult = await registry.CallFunctionAsync("github-status", new Dictionary<string, object>
{
    ["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:

public class GitHubUpdatePlugin : IAIPlugin
{
    public IReadOnlyDictionary<string, Type> SupportedParameters =>
        new Dictionary<string, Type>
        {
            ["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:

var updateResult = await registry.CallFunctionAsync("github-update", new Dictionary<string, object>
{
    ["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

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

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

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

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

public class AIPluginRegistry
{
    public void RegisterPlugin(IAIPlugin plugin)
    public void RegisterPlugin<T>() where T : IAIPlugin, new()
    public async Task<AIPluginResult> CallFunctionAsync(string pluginName, IReadOnlyDictionary<string, object> parameters)
    public IEnumerable<string> GetRegisteredPluginNames()
}

Example Usage

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<string, object>
{
    ["filePath"] = "/path/to/file.cs",
    ["analysisDepth"] = "comprehensive"
};

var result = await registry.CallFunctionAsync("CodeAnalysis", parameters);

// Clone a repository for analysis
var cloneParameters = new Dictionary<string, object>
{
    ["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 documentation.