1101 lines
35 KiB
Markdown
Executable File
1101 lines
35 KiB
Markdown
Executable File
# API Reference - MarketAlly.AIPlugin.Learning
|
|
|
|
## Table of Contents
|
|
|
|
- [Core Interfaces](#core-interfaces)
|
|
- [Service Implementations](#service-implementations)
|
|
- [Data Models](#data-models)
|
|
- [Configuration Classes](#configuration-classes)
|
|
- [Exception Types](#exception-types)
|
|
- [Plugin Interfaces](#plugin-interfaces)
|
|
- [Usage Examples](#usage-examples)
|
|
|
|
---
|
|
|
|
## Core Interfaces
|
|
|
|
### ILearningOrchestrator
|
|
|
|
Main orchestration service interface for coordinating learning sessions.
|
|
|
|
```csharp
|
|
public interface ILearningOrchestrator : IDisposable
|
|
{
|
|
/// <summary>
|
|
/// Executes a complete learning session with all phases
|
|
/// </summary>
|
|
/// <param name="session">Learning session configuration</param>
|
|
/// <returns>Comprehensive results with metrics and analysis</returns>
|
|
Task<ComprehensiveLearningResult> ExecuteCompleteLearningSessionAsync(
|
|
ComprehensiveLearningSession session);
|
|
}
|
|
```
|
|
|
|
**Implementation**: `LearningOrchestrator`
|
|
**Lifecycle**: Transient (create per session)
|
|
**Thread Safety**: Single-threaded per instance
|
|
|
|
---
|
|
|
|
### IUnifiedContextService
|
|
|
|
Revolutionary service combining real-time code intelligence with historical memory.
|
|
|
|
```csharp
|
|
public interface IUnifiedContextService
|
|
{
|
|
/// <summary>
|
|
/// Prepares comprehensive context combining current code analysis with historical insights
|
|
/// </summary>
|
|
/// <param name="query">Query describing the operation or question</param>
|
|
/// <param name="filePath">Optional specific file to analyze</param>
|
|
/// <param name="maxTokens">Maximum tokens for the complete context</param>
|
|
/// <returns>Comprehensive context with real-time and historical data</returns>
|
|
Task<ComprehensiveContext> PrepareFullContextAsync(
|
|
string query,
|
|
string? filePath = null,
|
|
int maxTokens = 8000);
|
|
|
|
/// <summary>
|
|
/// Initializes a new learning session with project context
|
|
/// </summary>
|
|
/// <param name="projectPath">Path to the project being analyzed</param>
|
|
/// <param name="topic">Topic or focus area for the session</param>
|
|
/// <returns>Session context with project information</returns>
|
|
Task<LearningSessionContext> InitializeLearningSessionAsync(
|
|
string projectPath,
|
|
string topic);
|
|
|
|
/// <summary>
|
|
/// Stores a learning insight for future reference
|
|
/// </summary>
|
|
/// <param name="insight">The insight or lesson learned</param>
|
|
/// <param name="category">Category for organization (e.g., "refactoring", "performance")</param>
|
|
/// <param name="filePath">Optional file path associated with the insight</param>
|
|
/// <param name="metadata">Optional metadata for the insight</param>
|
|
Task StoreLearningInsightAsync(
|
|
string insight,
|
|
string category,
|
|
string? filePath = null,
|
|
Dictionary<string, object>? metadata = null);
|
|
|
|
/// <summary>
|
|
/// Finds similar past issues or patterns for guidance
|
|
/// </summary>
|
|
/// <param name="currentIssue">Description of the current issue or task</param>
|
|
/// <param name="projectPath">Optional project path for context</param>
|
|
/// <returns>List of relevant historical insights</returns>
|
|
Task<List<HistoricalInsight>> FindSimilarPastIssuesAsync(
|
|
string currentIssue,
|
|
string? projectPath = null);
|
|
|
|
/// <summary>
|
|
/// Retrieves decisions related to a symbol or operation type
|
|
/// </summary>
|
|
/// <param name="symbolName">Name of the symbol (class, method, etc.)</param>
|
|
/// <param name="operationType">Optional operation type filter</param>
|
|
/// <returns>List of related previous decisions</returns>
|
|
Task<List<PreviousDecision>> GetRelatedDecisionsAsync(
|
|
string symbolName,
|
|
string? operationType = null);
|
|
|
|
/// <summary>
|
|
/// Stores a refactoring decision with outcome for future learning
|
|
/// </summary>
|
|
/// <param name="decision">The decision that was made</param>
|
|
/// <param name="reasoning">Reasoning behind the decision</param>
|
|
/// <param name="filePath">File path where the decision was applied</param>
|
|
/// <param name="successful">Whether the decision was successful</param>
|
|
Task StoreRefactoringDecisionAsync(
|
|
string decision,
|
|
string reasoning,
|
|
string filePath,
|
|
bool successful);
|
|
|
|
/// <summary>
|
|
/// Finalizes a learning session and stores summary metrics
|
|
/// </summary>
|
|
/// <param name="sessionSummary">Summary of the session</param>
|
|
/// <param name="metrics">Session metrics and statistics</param>
|
|
/// <returns>Session summary with finalization details</returns>
|
|
Task<SessionSummary> FinalizeLearningSessionAsync(
|
|
string sessionSummary,
|
|
Dictionary<string, object> metrics);
|
|
}
|
|
```
|
|
|
|
**Implementation**: `UnifiedContextService`
|
|
**Lifecycle**: Singleton (shared across sessions)
|
|
**Thread Safety**: Thread-safe with concurrent collections
|
|
|
|
---
|
|
|
|
### ILLMContextService
|
|
|
|
Intelligent LLM context preparation service with advanced code analysis.
|
|
|
|
```csharp
|
|
public interface ILLMContextService
|
|
{
|
|
/// <summary>
|
|
/// Prepares optimized context for LLM consumption
|
|
/// </summary>
|
|
/// <param name="query">The query or task description</param>
|
|
/// <param name="maxTokens">Maximum tokens for the context</param>
|
|
/// <returns>Optimized LLM context</returns>
|
|
Task<LLMContext> PrepareContextAsync(string query, int maxTokens = 4000);
|
|
|
|
/// <summary>
|
|
/// Prepares context focused on specific code file analysis
|
|
/// </summary>
|
|
/// <param name="filePath">Path to the file to analyze</param>
|
|
/// <param name="query">Specific query about the file</param>
|
|
/// <param name="maxTokens">Maximum tokens for the context</param>
|
|
/// <returns>File-focused LLM context</returns>
|
|
Task<LLMContext> PrepareCodeAnalysisContextAsync(
|
|
string filePath,
|
|
string query,
|
|
int maxTokens = 4000);
|
|
|
|
/// <summary>
|
|
/// Gets dependency context for a specific symbol
|
|
/// </summary>
|
|
/// <param name="symbolName">Name of the symbol to analyze</param>
|
|
/// <returns>Dependency context with related symbols</returns>
|
|
Task<DependencyContext> GetDependencyContextAsync(string symbolName);
|
|
|
|
/// <summary>
|
|
/// Analyzes potential impact of changes at specific location
|
|
/// </summary>
|
|
/// <param name="filePath">File path where change will be made</param>
|
|
/// <param name="lineNumber">Line number of the change</param>
|
|
/// <returns>Change impact analysis</returns>
|
|
Task<ChangeImpactContext> AnalyzeChangeImpactAsync(string filePath, int lineNumber);
|
|
|
|
/// <summary>
|
|
/// Gets code relationships for a symbol (callers, callees, dependencies)
|
|
/// </summary>
|
|
/// <param name="symbolName">Symbol to analyze relationships for</param>
|
|
/// <returns>Code relationship context</returns>
|
|
Task<CodeRelationshipContext> GetCodeRelationshipsAsync(string symbolName);
|
|
}
|
|
```
|
|
|
|
**Implementation**: `LLMContextService`
|
|
**Lifecycle**: Singleton (caching benefits)
|
|
**Thread Safety**: Thread-safe with cache synchronization
|
|
|
|
---
|
|
|
|
### ISecurityService
|
|
|
|
Comprehensive security validation and sanitization service.
|
|
|
|
```csharp
|
|
public interface ISecurityService
|
|
{
|
|
/// <summary>
|
|
/// Validates that a path is safe and within allowed boundaries
|
|
/// </summary>
|
|
/// <param name="path">Path to validate</param>
|
|
/// <returns>True if path is safe, false otherwise</returns>
|
|
bool IsPathSafe(string path);
|
|
|
|
/// <summary>
|
|
/// Checks if a file is allowed based on security policies
|
|
/// </summary>
|
|
/// <param name="filePath">File path to check</param>
|
|
/// <returns>True if file access is allowed</returns>
|
|
bool IsFileAllowed(string filePath);
|
|
|
|
/// <summary>
|
|
/// Sanitizes user input by removing unsafe characters
|
|
/// </summary>
|
|
/// <param name="input">Input string to sanitize</param>
|
|
/// <returns>Sanitized input string</returns>
|
|
string SanitizeInput(string input);
|
|
|
|
/// <summary>
|
|
/// Validates learning configuration for security compliance
|
|
/// </summary>
|
|
/// <param name="config">Configuration to validate</param>
|
|
/// <returns>Validation result with any errors</returns>
|
|
ValidationResult ValidateConfiguration(LearningConfiguration config);
|
|
|
|
/// <summary>
|
|
/// Generates a cryptographically secure session identifier
|
|
/// </summary>
|
|
/// <returns>Secure session ID</returns>
|
|
string GenerateSecureSessionId();
|
|
|
|
/// <summary>
|
|
/// Validates that a directory is within working directory bounds
|
|
/// </summary>
|
|
/// <param name="directory">Directory path to validate</param>
|
|
/// <returns>True if directory is within bounds</returns>
|
|
bool IsDirectoryWithinBounds(string directory);
|
|
|
|
/// <summary>
|
|
/// Checks if an operation is allowed based on current session context
|
|
/// </summary>
|
|
/// <param name="operation">Operation to validate</param>
|
|
/// <param name="context">Current session context</param>
|
|
/// <returns>True if operation is allowed</returns>
|
|
bool IsOperationAllowed(string operation, SessionContext context);
|
|
}
|
|
```
|
|
|
|
**Implementation**: `SecurityService`
|
|
**Lifecycle**: Singleton (stateless validation)
|
|
**Thread Safety**: Thread-safe (immutable state)
|
|
|
|
---
|
|
|
|
## Service Implementations
|
|
|
|
### LearningOrchestrator
|
|
|
|
```csharp
|
|
public class LearningOrchestrator : ILearningOrchestrator, IDisposable
|
|
{
|
|
// Constructor with dependency injection
|
|
public LearningOrchestrator(
|
|
ILogger<LearningOrchestrator> logger,
|
|
IOptions<LearningConfiguration> configOptions,
|
|
ISecurityService securityService,
|
|
ILLMContextService llmContextService,
|
|
IUnifiedContextService unifiedContextService,
|
|
GitManager gitManager,
|
|
CompilationManager compilationManager,
|
|
ReportsManager reportsManager,
|
|
RefactorIQIntegration refactorIQIntegration);
|
|
|
|
// Main execution method
|
|
public async Task<ComprehensiveLearningResult> ExecuteCompleteLearningSessionAsync(
|
|
ComprehensiveLearningSession session);
|
|
|
|
// Proper disposal pattern
|
|
public void Dispose();
|
|
protected virtual void Dispose(bool disposing);
|
|
}
|
|
```
|
|
|
|
**Key Features:**
|
|
- **Phase-based execution**: Git setup → Analysis → Iterations → Reporting
|
|
- **Correlation ID tracking**: Traces operations across service calls
|
|
- **Resource management**: Proper disposal of all resources
|
|
- **Security integration**: Validates all inputs and file access
|
|
- **Error recovery**: Handles failures gracefully with detailed reporting
|
|
|
|
### UnifiedContextService
|
|
|
|
```csharp
|
|
public class UnifiedContextService : IUnifiedContextService
|
|
{
|
|
// Constructor
|
|
public UnifiedContextService(
|
|
ILLMContextService llmContextService,
|
|
IOptions<LearningConfiguration> options,
|
|
ILogger<UnifiedContextService> logger);
|
|
|
|
// Core context preparation method
|
|
public async Task<ComprehensiveContext> PrepareFullContextAsync(
|
|
string query,
|
|
string? filePath = null,
|
|
int maxTokens = 8000);
|
|
}
|
|
```
|
|
|
|
**Key Features:**
|
|
- **Context combination**: Merges real-time and historical data
|
|
- **Token optimization**: Respects LLM token limits intelligently
|
|
- **Caching**: Performance optimization with concurrent cache
|
|
- **Mock integration**: Ready for Context project when available
|
|
|
|
---
|
|
|
|
## Data Models
|
|
|
|
### ComprehensiveContext
|
|
|
|
```csharp
|
|
public class ComprehensiveContext
|
|
{
|
|
/// <summary>Original query that generated this context</summary>
|
|
public string Query { get; set; } = string.Empty;
|
|
|
|
/// <summary>File path if context is file-specific</summary>
|
|
public string? FilePath { get; set; }
|
|
|
|
/// <summary>Maximum tokens requested for this context</summary>
|
|
public int MaxTokens { get; set; }
|
|
|
|
/// <summary>When this context was generated</summary>
|
|
public DateTime GeneratedAt { get; set; }
|
|
|
|
/// <summary>Correlation ID for tracing</summary>
|
|
public string CorrelationId { get; set; } = string.Empty;
|
|
|
|
/// <summary>Current/real-time code analysis</summary>
|
|
public LLMContext? CurrentCodeAnalysis { get; set; }
|
|
|
|
/// <summary>Historical insights from past sessions</summary>
|
|
public List<HistoricalInsight> HistoricalInsights { get; set; } = new();
|
|
|
|
/// <summary>Previous decisions about similar code</summary>
|
|
public List<PreviousDecision> RelatedDecisions { get; set; } = new();
|
|
|
|
/// <summary>Project-wide context information</summary>
|
|
public ProjectContextInfo? ProjectContext { get; set; }
|
|
|
|
/// <summary>Estimated total tokens in this context</summary>
|
|
public int EstimatedTotalTokens { get; set; }
|
|
}
|
|
```
|
|
|
|
### LLMContext
|
|
|
|
```csharp
|
|
public class LLMContext
|
|
{
|
|
/// <summary>Code chunks relevant to the query</summary>
|
|
public List<CodeChunk> CodeChunks { get; set; } = new();
|
|
|
|
/// <summary>Dependencies and related symbols</summary>
|
|
public List<SymbolInfo> Dependencies { get; set; } = new();
|
|
|
|
/// <summary>Estimated token count for this context</summary>
|
|
public int EstimatedTokens { get; set; }
|
|
|
|
/// <summary>Context generation metadata</summary>
|
|
public Dictionary<string, object> Metadata { get; set; } = new();
|
|
|
|
/// <summary>Files that might be affected by changes</summary>
|
|
public List<string> AffectedFiles { get; set; } = new();
|
|
|
|
/// <summary>Code relationships and dependencies</summary>
|
|
public CodeRelationshipMap RelationshipMap { get; set; } = new();
|
|
}
|
|
```
|
|
|
|
### HistoricalInsight
|
|
|
|
```csharp
|
|
public class HistoricalInsight
|
|
{
|
|
/// <summary>Unique identifier for the insight</summary>
|
|
public string Id { get; set; } = string.Empty;
|
|
|
|
/// <summary>Full content of the insight</summary>
|
|
public string Content { get; set; } = string.Empty;
|
|
|
|
/// <summary>Brief summary of the insight</summary>
|
|
public string Summary { get; set; } = string.Empty;
|
|
|
|
/// <summary>Relevance score (0.0 to 1.0)</summary>
|
|
public double Relevance { get; set; }
|
|
|
|
/// <summary>When this insight was recorded</summary>
|
|
public DateTime Timestamp { get; set; }
|
|
|
|
/// <summary>Tags for categorization and search</summary>
|
|
public List<string> Tags { get; set; } = new();
|
|
}
|
|
```
|
|
|
|
### PreviousDecision
|
|
|
|
```csharp
|
|
public class PreviousDecision
|
|
{
|
|
/// <summary>Unique identifier for the decision</summary>
|
|
public string Id { get; set; } = string.Empty;
|
|
|
|
/// <summary>Full content of the decision</summary>
|
|
public string Content { get; set; } = string.Empty;
|
|
|
|
/// <summary>Brief summary of the decision</summary>
|
|
public string Summary { get; set; } = string.Empty;
|
|
|
|
/// <summary>Relevance score (0.0 to 1.0)</summary>
|
|
public double Relevance { get; set; }
|
|
|
|
/// <summary>When this decision was made</summary>
|
|
public DateTime Timestamp { get; set; }
|
|
|
|
/// <summary>Whether the decision was successful</summary>
|
|
public bool Successful { get; set; }
|
|
|
|
/// <summary>Tags for categorization and search</summary>
|
|
public List<string> Tags { get; set; } = new();
|
|
}
|
|
```
|
|
|
|
### ComprehensiveLearningSession
|
|
|
|
```csharp
|
|
public class ComprehensiveLearningSession
|
|
{
|
|
/// <summary>Unique session identifier</summary>
|
|
public Guid SessionId { get; set; }
|
|
|
|
/// <summary>Path to the solution file</summary>
|
|
public string SolutionPath { get; set; } = string.Empty;
|
|
|
|
/// <summary>Directory for generated reports</summary>
|
|
public string ReportsDirectory { get; set; } = "Reports";
|
|
|
|
/// <summary>Learning mode: conservative, moderate, aggressive</summary>
|
|
public string LearningMode { get; set; } = "conservative";
|
|
|
|
/// <summary>Maximum iterations for this session</summary>
|
|
public int MaxIterations { get; set; } = 20;
|
|
|
|
/// <summary>Maximum attempts per file before giving up</summary>
|
|
public int MaxAttemptsPerFile { get; set; } = 3;
|
|
|
|
/// <summary>Session timeout in minutes</summary>
|
|
public int SessionTimeoutMinutes { get; set; } = 60;
|
|
|
|
/// <summary>Enable verbose reporting</summary>
|
|
public bool VerboseReporting { get; set; } = false;
|
|
|
|
/// <summary>Skip warnings analysis phase</summary>
|
|
public bool SkipWarningsAnalysis { get; set; } = false;
|
|
|
|
/// <summary>Enable AI embeddings and semantic search</summary>
|
|
public bool EnableSemanticSearch { get; set; } = false;
|
|
|
|
/// <summary>OpenAI API key for embeddings (optional)</summary>
|
|
public string? OpenAIApiKey { get; set; }
|
|
|
|
/// <summary>Session start time</summary>
|
|
public DateTime StartTime { get; set; }
|
|
}
|
|
```
|
|
|
|
### ComprehensiveLearningResult
|
|
|
|
```csharp
|
|
public class ComprehensiveLearningResult
|
|
{
|
|
/// <summary>Session identifier</summary>
|
|
public Guid SessionId { get; set; }
|
|
|
|
/// <summary>Session start time</summary>
|
|
public DateTime StartTime { get; set; }
|
|
|
|
/// <summary>Session end time</summary>
|
|
public DateTime EndTime { get; set; }
|
|
|
|
/// <summary>Total session duration</summary>
|
|
public TimeSpan TotalDuration { get; set; }
|
|
|
|
/// <summary>Project name being analyzed</summary>
|
|
public string ProjectName { get; set; } = string.Empty;
|
|
|
|
/// <summary>Whether the session completed successfully</summary>
|
|
public bool Success { get; set; }
|
|
|
|
/// <summary>Whether a critical error occurred</summary>
|
|
public bool CriticalError { get; set; }
|
|
|
|
/// <summary>Error message if session failed</summary>
|
|
public string? ErrorMessage { get; set; }
|
|
|
|
/// <summary>All learning iterations performed</summary>
|
|
public List<LearningIteration> Iterations { get; set; } = new();
|
|
|
|
/// <summary>Failed attempts across all iterations</summary>
|
|
public List<FailedAttempt> FailedAttempts { get; set; } = new();
|
|
|
|
/// <summary>Git branch information</summary>
|
|
public GitBranchInfo GitInfo { get; set; } = new();
|
|
|
|
/// <summary>Baseline compilation results</summary>
|
|
public CompilationResult? BaselineCompilation { get; set; }
|
|
|
|
/// <summary>Final compilation results</summary>
|
|
public CompilationResult? FinalCompilation { get; set; }
|
|
|
|
/// <summary>Initial RefactorIQ analysis results</summary>
|
|
public RefactorIQAnalysisResult? InitialRefactorIQAnalysis { get; set; }
|
|
|
|
/// <summary>Whether AI features were enabled and used</summary>
|
|
public bool AIFeaturesEnabled { get; set; }
|
|
|
|
/// <summary>Semantic search results from AI analysis</summary>
|
|
public List<LearningVectorSearchResult>? SemanticSearchResults { get; set; }
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## Configuration Classes
|
|
|
|
### LearningConfiguration
|
|
|
|
```csharp
|
|
[ConfigurationSection("Learning")]
|
|
public class LearningConfiguration
|
|
{
|
|
public const string SectionName = "Learning";
|
|
|
|
/// <summary>Git-related configuration</summary>
|
|
[Required]
|
|
public GitConfiguration Git { get; set; } = new();
|
|
|
|
/// <summary>Security and validation settings</summary>
|
|
[Required]
|
|
public SecurityConfiguration Security { get; set; } = new();
|
|
|
|
/// <summary>Performance tuning parameters</summary>
|
|
[Required]
|
|
public PerformanceConfiguration Performance { get; set; } = new();
|
|
|
|
/// <summary>AI service configuration</summary>
|
|
[Required]
|
|
public AIConfiguration AI { get; set; } = new();
|
|
|
|
/// <summary>Learning mode configurations</summary>
|
|
[Required]
|
|
public LearningModeConfiguration LearningModes { get; set; } = new();
|
|
}
|
|
```
|
|
|
|
### GitConfiguration
|
|
|
|
```csharp
|
|
public class GitConfiguration
|
|
{
|
|
/// <summary>Prefix for AI-generated branches</summary>
|
|
[Required]
|
|
public string BranchPrefix { get; set; } = "ai-refactoring";
|
|
|
|
/// <summary>Name for git commits</summary>
|
|
[Required]
|
|
public string CommitterName { get; set; } = "AI Learning System";
|
|
|
|
/// <summary>Email for git commits</summary>
|
|
[Required]
|
|
[EmailAddress]
|
|
public string CommitterEmail { get; set; } = "ai@learning.system";
|
|
|
|
/// <summary>Whether to create safety branches</summary>
|
|
public bool CreateSafetyBranches { get; set; } = true;
|
|
|
|
/// <summary>Whether to automatically merge successful iterations</summary>
|
|
public bool AutoMergeSuccessful { get; set; } = true;
|
|
|
|
/// <summary>Maximum depth for git operations</summary>
|
|
[Range(1, 100)]
|
|
public int MaxDepth { get; set; } = 10;
|
|
}
|
|
```
|
|
|
|
### SecurityConfiguration
|
|
|
|
```csharp
|
|
public class SecurityConfiguration
|
|
{
|
|
/// <summary>Directories that are forbidden from access</summary>
|
|
[Required]
|
|
public List<string> ForbiddenDirectories { get; set; } = new()
|
|
{
|
|
"bin", "obj", ".git", "node_modules", ".vs", "packages"
|
|
};
|
|
|
|
/// <summary>File extensions that are allowed for processing</summary>
|
|
[Required]
|
|
public List<string> AllowedFileExtensions { get; set; } = new()
|
|
{
|
|
".cs", ".csproj", ".sln", ".json", ".xml"
|
|
};
|
|
|
|
/// <summary>Maximum file size in bytes</summary>
|
|
[Range(1024, int.MaxValue)]
|
|
public long MaxFileSize { get; set; } = 10 * 1024 * 1024; // 10MB
|
|
|
|
/// <summary>Maximum path length</summary>
|
|
[Range(10, 32767)]
|
|
public int MaxPathLength { get; set; } = 260;
|
|
|
|
/// <summary>Whether to validate file contents for malicious patterns</summary>
|
|
public bool ValidateFileContents { get; set; } = true;
|
|
|
|
/// <summary>Patterns that are considered unsafe in file paths</summary>
|
|
public List<string> UnsafePathPatterns { get; set; } = new()
|
|
{
|
|
"..", "~", "%", "$"
|
|
};
|
|
}
|
|
```
|
|
|
|
### AIConfiguration
|
|
|
|
```csharp
|
|
public class AIConfiguration
|
|
{
|
|
/// <summary>Whether to enable semantic search features</summary>
|
|
public bool EnableSemanticSearch { get; set; } = false;
|
|
|
|
/// <summary>Maximum number of search results to return</summary>
|
|
[Range(1, 100)]
|
|
public int MaxSearchResults { get; set; } = 10;
|
|
|
|
/// <summary>Minimum similarity score for search results</summary>
|
|
[Range(0.0, 1.0)]
|
|
public double MinSimilarityScore { get; set; } = 0.7;
|
|
|
|
/// <summary>Maximum tokens for LLM context</summary>
|
|
[Range(100, 32000)]
|
|
public int MaxContextTokens { get; set; } = 8000;
|
|
|
|
/// <summary>Whether to enable context caching</summary>
|
|
public bool EnableContextCaching { get; set; } = true;
|
|
|
|
/// <summary>Cache expiration time in minutes</summary>
|
|
[Range(1, 1440)]
|
|
public int CacheExpirationMinutes { get; set; } = 60;
|
|
|
|
/// <summary>OpenAI API configuration</summary>
|
|
public OpenAIConfiguration OpenAI { get; set; } = new();
|
|
}
|
|
```
|
|
|
|
### LearningModeConfiguration
|
|
|
|
```csharp
|
|
public class LearningModeConfiguration
|
|
{
|
|
/// <summary>Conservative learning mode settings</summary>
|
|
[Required]
|
|
public LearningModeSettings Conservative { get; set; } = new()
|
|
{
|
|
MaxIterations = 10,
|
|
MaxAttemptsPerFile = 2,
|
|
EnableRiskyRefactorings = false,
|
|
RequireCompilationSuccess = true
|
|
};
|
|
|
|
/// <summary>Moderate learning mode settings</summary>
|
|
[Required]
|
|
public LearningModeSettings Moderate { get; set; } = new()
|
|
{
|
|
MaxIterations = 20,
|
|
MaxAttemptsPerFile = 3,
|
|
EnableRiskyRefactorings = true,
|
|
RequireCompilationSuccess = true
|
|
};
|
|
|
|
/// <summary>Aggressive learning mode settings</summary>
|
|
[Required]
|
|
public LearningModeSettings Aggressive { get; set; } = new()
|
|
{
|
|
MaxIterations = 50,
|
|
MaxAttemptsPerFile = 5,
|
|
EnableRiskyRefactorings = true,
|
|
RequireCompilationSuccess = false
|
|
};
|
|
}
|
|
|
|
public class LearningModeSettings
|
|
{
|
|
/// <summary>Maximum iterations for this mode</summary>
|
|
[Range(1, 100)]
|
|
public int MaxIterations { get; set; }
|
|
|
|
/// <summary>Maximum attempts per file</summary>
|
|
[Range(1, 10)]
|
|
public int MaxAttemptsPerFile { get; set; }
|
|
|
|
/// <summary>Whether to enable risky refactorings</summary>
|
|
public bool EnableRiskyRefactorings { get; set; }
|
|
|
|
/// <summary>Whether compilation must succeed to continue</summary>
|
|
public bool RequireCompilationSuccess { get; set; }
|
|
|
|
/// <summary>Timeout per iteration in minutes</summary>
|
|
[Range(1, 60)]
|
|
public int IterationTimeoutMinutes { get; set; } = 5;
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## Exception Types
|
|
|
|
### Base Exception
|
|
|
|
```csharp
|
|
/// <summary>
|
|
/// Base exception for all learning-related errors
|
|
/// </summary>
|
|
public abstract class LearningException : Exception
|
|
{
|
|
/// <summary>Operation context where the error occurred</summary>
|
|
public string OperationContext { get; }
|
|
|
|
/// <summary>Correlation ID for tracing</summary>
|
|
public string CorrelationId { get; }
|
|
|
|
protected LearningException(string operationContext, string message)
|
|
: base(message)
|
|
{
|
|
OperationContext = operationContext;
|
|
CorrelationId = Guid.NewGuid().ToString("N")[..8];
|
|
}
|
|
|
|
protected LearningException(string operationContext, string message, Exception innerException)
|
|
: base(message, innerException)
|
|
{
|
|
OperationContext = operationContext;
|
|
CorrelationId = Guid.NewGuid().ToString("N")[..8];
|
|
}
|
|
}
|
|
```
|
|
|
|
### Specific Exception Types
|
|
|
|
```csharp
|
|
/// <summary>Compilation-related errors with detailed metrics</summary>
|
|
public class CompilationException : LearningException
|
|
{
|
|
public int ErrorCount { get; }
|
|
public int WarningCount { get; }
|
|
public IReadOnlyList<string> Errors { get; }
|
|
|
|
public CompilationException(int errorCount, int warningCount, IEnumerable<string> errors)
|
|
: base("Compilation", $"Compilation failed with {errorCount} errors and {warningCount} warnings")
|
|
{
|
|
ErrorCount = errorCount;
|
|
WarningCount = warningCount;
|
|
Errors = errors.ToList().AsReadOnly();
|
|
}
|
|
}
|
|
|
|
/// <summary>RefactorIQ operation failures</summary>
|
|
public class RefactorIQException : LearningException
|
|
{
|
|
public string? ConfigPath { get; }
|
|
|
|
public RefactorIQException(string operation, string? configPath, string message, Exception? innerException = null)
|
|
: base($"RefactorIQ.{operation}", message, innerException ?? new InvalidOperationException())
|
|
{
|
|
ConfigPath = configPath;
|
|
}
|
|
}
|
|
|
|
/// <summary>Security validation failures</summary>
|
|
public class SecurityException : LearningException
|
|
{
|
|
public string ValidationType { get; }
|
|
public string? ViolatingValue { get; }
|
|
|
|
public SecurityException(string validationType, string? violatingValue, string message)
|
|
: base($"Security.{validationType}", message)
|
|
{
|
|
ValidationType = validationType;
|
|
ViolatingValue = violatingValue;
|
|
}
|
|
}
|
|
|
|
/// <summary>Configuration validation errors</summary>
|
|
public class ConfigurationException : LearningException
|
|
{
|
|
public string ConfigurationKey { get; }
|
|
|
|
public ConfigurationException(string configurationKey, string message)
|
|
: base("Configuration", message)
|
|
{
|
|
ConfigurationKey = configurationKey;
|
|
}
|
|
}
|
|
|
|
/// <summary>Git operation failures</summary>
|
|
public class GitOperationException : LearningException
|
|
{
|
|
public string GitOperation { get; }
|
|
public string? RepositoryPath { get; }
|
|
|
|
public GitOperationException(string gitOperation, string? repositoryPath, string message)
|
|
: base($"Git.{gitOperation}", message)
|
|
{
|
|
GitOperation = gitOperation;
|
|
RepositoryPath = repositoryPath;
|
|
}
|
|
}
|
|
|
|
/// <summary>AI service operation failures</summary>
|
|
public class AIServiceException : LearningException
|
|
{
|
|
public string ServiceName { get; }
|
|
public bool IsRetryable { get; }
|
|
|
|
public AIServiceException(string serviceName, string message, Exception? innerException = null, bool isRetryable = false)
|
|
: base($"AIService.{serviceName}", message, innerException ?? new InvalidOperationException())
|
|
{
|
|
ServiceName = serviceName;
|
|
IsRetryable = isRetryable;
|
|
}
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## Plugin Interfaces
|
|
|
|
### ComprehensiveLearningRefactorPlugin
|
|
|
|
```csharp
|
|
[AIPlugin("ComprehensiveLearningRefactor",
|
|
"Complete self-learning refactoring system with unified context intelligence")]
|
|
public class ComprehensiveLearningRefactorPlugin : IAIPlugin, IDisposable
|
|
{
|
|
// Plugin parameters
|
|
[AIParameter("Solution path to analyze and improve", required: true)]
|
|
public string SolutionPath { get; set; }
|
|
|
|
[AIParameter("Learning mode: conservative, moderate, aggressive", required: false)]
|
|
public string LearningMode { get; set; } = "conservative";
|
|
|
|
[AIParameter("Enable semantic code search", required: false)]
|
|
public bool EnableSemanticSearch { get; set; } = false;
|
|
|
|
[AIParameter("OpenAI API key for embeddings", required: false)]
|
|
public string OpenAIApiKey { get; set; }
|
|
|
|
// Main execution method
|
|
public async Task<AIPluginResult> ExecuteAsync(IReadOnlyDictionary<string, object> parameters);
|
|
|
|
// Supported parameters definition
|
|
public IReadOnlyDictionary<string, Type> SupportedParameters { get; }
|
|
|
|
// Resource cleanup
|
|
public void Dispose();
|
|
}
|
|
```
|
|
|
|
### UnifiedContextPlugin
|
|
|
|
```csharp
|
|
[AIPlugin("UnifiedContext",
|
|
"Unified context service combining real-time code analysis with historical memory")]
|
|
public class UnifiedContextPlugin : IAIPlugin, IDisposable
|
|
{
|
|
// Supported actions
|
|
public static class Actions
|
|
{
|
|
public const string PrepareContext = "prepare-context";
|
|
public const string InitializeSession = "initialize-session";
|
|
public const string StoreInsight = "store-insight";
|
|
public const string FindSimilar = "find-similar";
|
|
public const string GetDecisions = "get-decisions";
|
|
public const string StoreDecision = "store-decision";
|
|
public const string FinalizeSession = "finalize-session";
|
|
}
|
|
|
|
// Action-specific parameter validation
|
|
private readonly Dictionary<string, HashSet<string>> _requiredParametersByAction = new()
|
|
{
|
|
[Actions.PrepareContext] = new() { "query" },
|
|
[Actions.InitializeSession] = new() { "projectPath", "topic" },
|
|
[Actions.StoreInsight] = new() { "insight", "category" },
|
|
[Actions.FindSimilar] = new() { "currentIssue" },
|
|
[Actions.GetDecisions] = new() { "symbolName" },
|
|
[Actions.StoreDecision] = new() { "decision", "reasoning", "filePath", "successful" },
|
|
[Actions.FinalizeSession] = new() { "sessionSummary", "metrics" }
|
|
};
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## Usage Examples
|
|
|
|
### Basic Learning Session
|
|
|
|
```csharp
|
|
// Setup dependency injection
|
|
var services = new ServiceCollection();
|
|
services.AddSingleton<IUnifiedContextService, UnifiedContextService>();
|
|
services.AddSingleton<ILLMContextService, LLMContextService>();
|
|
services.AddSingleton<ISecurityService, SecurityService>();
|
|
services.AddTransient<ILearningOrchestrator, LearningOrchestrator>();
|
|
|
|
var serviceProvider = services.BuildServiceProvider();
|
|
|
|
// Create and execute learning session
|
|
var session = new ComprehensiveLearningSession
|
|
{
|
|
SessionId = Guid.NewGuid(),
|
|
SolutionPath = @"C:\MyProject\Solution.sln",
|
|
LearningMode = "moderate",
|
|
EnableSemanticSearch = true,
|
|
MaxIterations = 25,
|
|
SessionTimeoutMinutes = 90
|
|
};
|
|
|
|
using var orchestrator = serviceProvider.GetRequiredService<ILearningOrchestrator>();
|
|
var result = await orchestrator.ExecuteCompleteLearningSessionAsync(session);
|
|
|
|
// Process results
|
|
Console.WriteLine($"Session completed: {result.Success}");
|
|
Console.WriteLine($"Duration: {result.TotalDuration.TotalMinutes:F1} minutes");
|
|
Console.WriteLine($"Iterations: {result.Iterations.Count}");
|
|
Console.WriteLine($"Successful: {result.Iterations.Count(i => i.Success)}");
|
|
```
|
|
|
|
### Advanced Context Preparation
|
|
|
|
```csharp
|
|
var contextService = serviceProvider.GetRequiredService<IUnifiedContextService>();
|
|
|
|
// Initialize learning session
|
|
var sessionContext = await contextService.InitializeLearningSessionAsync(
|
|
projectPath: @"C:\MyProject",
|
|
topic: "Performance optimization and code cleanup"
|
|
);
|
|
|
|
// Prepare comprehensive context for specific task
|
|
var context = await contextService.PrepareFullContextAsync(
|
|
query: "optimize database access patterns in UserService",
|
|
filePath: @"C:\MyProject\Services\UserService.cs",
|
|
maxTokens: 12000
|
|
);
|
|
|
|
// Analyze the context
|
|
Console.WriteLine($"Current code analysis tokens: {context.CurrentCodeAnalysis?.EstimatedTokens}");
|
|
Console.WriteLine($"Historical insights: {context.HistoricalInsights.Count}");
|
|
Console.WriteLine($"Related decisions: {context.RelatedDecisions.Count}");
|
|
|
|
// Check for successful patterns from history
|
|
var successfulDecisions = context.RelatedDecisions.Where(d => d.Successful).ToList();
|
|
if (successfulDecisions.Any())
|
|
{
|
|
Console.WriteLine("Found successful patterns:");
|
|
foreach (var decision in successfulDecisions.Take(3))
|
|
{
|
|
Console.WriteLine($" - {decision.Summary} (Relevance: {decision.Relevance:P})");
|
|
}
|
|
}
|
|
|
|
// Store insight about this analysis
|
|
await contextService.StoreLearningInsightAsync(
|
|
insight: "UserService has complex database access patterns that could benefit from caching",
|
|
category: "performance-analysis",
|
|
filePath: @"C:\MyProject\Services\UserService.cs",
|
|
metadata: new Dictionary<string, object>
|
|
{
|
|
["analysisTimestamp"] = DateTime.UtcNow,
|
|
["complexityScore"] = 0.85,
|
|
["recommendedPattern"] = "cache-aside"
|
|
}
|
|
);
|
|
```
|
|
|
|
### Security Validation
|
|
|
|
```csharp
|
|
var securityService = serviceProvider.GetRequiredService<ISecurityService>();
|
|
|
|
// Validate file access
|
|
string filePath = @"C:\MyProject\Services\UserService.cs";
|
|
if (!securityService.IsPathSafe(filePath))
|
|
{
|
|
throw new SecurityException("PathValidation", filePath, "File path is not safe");
|
|
}
|
|
|
|
if (!securityService.IsFileAllowed(filePath))
|
|
{
|
|
throw new SecurityException("FileAccess", filePath, "File access not allowed");
|
|
}
|
|
|
|
// Sanitize user input
|
|
string userQuery = securityService.SanitizeInput(rawUserInput);
|
|
|
|
// Validate configuration
|
|
var config = serviceProvider.GetRequiredService<IOptions<LearningConfiguration>>().Value;
|
|
var validationResult = securityService.ValidateConfiguration(config);
|
|
|
|
if (!validationResult.IsValid)
|
|
{
|
|
foreach (var error in validationResult.Errors)
|
|
{
|
|
Console.WriteLine($"Configuration error: {error}");
|
|
}
|
|
}
|
|
```
|
|
|
|
### Error Handling
|
|
|
|
```csharp
|
|
try
|
|
{
|
|
var result = await orchestrator.ExecuteCompleteLearningSessionAsync(session);
|
|
}
|
|
catch (CompilationException ex)
|
|
{
|
|
Console.WriteLine($"Compilation failed: {ex.ErrorCount} errors, {ex.WarningCount} warnings");
|
|
foreach (var error in ex.Errors.Take(5))
|
|
{
|
|
Console.WriteLine($" - {error}");
|
|
}
|
|
}
|
|
catch (SecurityException ex)
|
|
{
|
|
Console.WriteLine($"Security violation in {ex.ValidationType}: {ex.Message}");
|
|
// Log security incident
|
|
}
|
|
catch (AIServiceException ex)
|
|
{
|
|
Console.WriteLine($"AI service {ex.ServiceName} failed: {ex.Message}");
|
|
if (ex.IsRetryable)
|
|
{
|
|
Console.WriteLine("This operation can be retried");
|
|
}
|
|
}
|
|
catch (LearningException ex)
|
|
{
|
|
Console.WriteLine($"Learning operation failed in {ex.OperationContext}: {ex.Message}");
|
|
Console.WriteLine($"Correlation ID: {ex.CorrelationId}");
|
|
}
|
|
```
|
|
|
|
### Plugin Usage
|
|
|
|
```csharp
|
|
// Using the main learning plugin
|
|
var plugin = new ComprehensiveLearningRefactorPlugin();
|
|
|
|
var parameters = new Dictionary<string, object>
|
|
{
|
|
["solutionPath"] = @"C:\MyProject\Solution.sln",
|
|
["learningMode"] = "aggressive",
|
|
["enableSemanticSearch"] = true,
|
|
["openAIApiKey"] = Environment.GetEnvironmentVariable("OPENAI_API_KEY"),
|
|
["maxIterations"] = 30,
|
|
["sessionTimeoutMinutes"] = 120,
|
|
["verboseReporting"] = true
|
|
};
|
|
|
|
var result = await plugin.ExecuteAsync(parameters);
|
|
|
|
if (result.Success)
|
|
{
|
|
var learningResult = (ComprehensiveLearningResult)result.Data;
|
|
Console.WriteLine($"Learning session completed successfully");
|
|
Console.WriteLine($"Project: {learningResult.ProjectName}");
|
|
Console.WriteLine($"Duration: {learningResult.TotalDuration}");
|
|
}
|
|
else
|
|
{
|
|
Console.WriteLine($"Learning session failed: {result.Message}");
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
**Generated on 2025-06-25 by Claude Code**
|
|
**Version**: 1.0.0
|
|
**Last Updated**: After revolutionary unified context integration |