core

package
v0.0.0-...-6a3e998 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 23, 2025 License: MIT Imports: 26 Imported by: 0

README

Core Package

Overview

The core package implements the central engine for the DevOps MCP platform. It orchestrates context management, GitHub integration, embedding processing, and adapter coordination. The package provides the foundation for AI-powered DevOps automation with conversation context awareness and comprehensive GitHub content analysis.

Architecture

core/
├── engine.go                      # Main orchestration engine
├── context_manager.go            # Context management wrapper
├── context/                      # Full context implementation
│   └── manager.go               # Context manager with S3 support
├── github_content.go            # GitHub content storage
├── github_relationship_manager.go # Entity relationship tracking
├── embedding_manager.go         # Embedding generation interface
├── adapter_context_bridge.go    # Tool-context integration
├── system.go                    # Event bus implementation
└── fallback_service.go          # Degraded mode operations

Core Engine

The engine orchestrates all MCP functionality:

// Initialize engine
engine := core.NewEngine(
    adapters,           // Tool adapters
    contextManager,     // Context management
    metricsClient,      // Metrics collection
    systemEventBus,     // Event system
    logger,            // Structured logging
)

// Execute tool action with context
result, err := engine.ExecuteWithContext(ctx, &ExecuteRequest{
    Tool:   "github",
    Action: "create_issue",
    Params: map[string]interface{}{
        "title": "Fix memory leak",
        "body":  "Description...",
    },
    ContextID: contextID,
})

// Process GitHub content
err = engine.ProcessGitHubContent(ctx, &GitHubContent{
    Type:       "issue",
    Owner:      "S-Corkum",
    Repo:       "devops-mcp",
    Number:     123,
    Content:    issueData,
})

Context Management

Context Manager

Manages conversation contexts with persistence:

// Create context
context, err := contextManager.CreateContext(ctx, &CreateContextRequest{
    Name:    "deployment-planning",
    Content: "Planning production deployment...",
    Type:    "conversation",
    Metadata: map[string]interface{}{
        "project": "devops-mcp",
        "phase":   "planning",
    },
})

// Update context with new messages
updated, err := contextManager.UpdateContext(ctx, &UpdateContextRequest{
    ID: context.ID,
    Messages: []Message{
        {
            Role:    "user",
            Content: "What are the deployment steps?",
        },
        {
            Role:    "assistant",
            Content: "Here are the deployment steps...",
        },
    },
})

// Retrieve context
context, err := contextManager.GetContext(ctx, contextID)

// Search contexts
results, err := contextManager.SearchContexts(ctx, &SearchRequest{
    Query:  "deployment",
    Limit:  10,
    Offset: 0,
})
S3 Persistence

Contexts are persisted to S3 for durability:

// S3 storage structure
s3://bucket/contexts/{context_id}/
├── metadata.json    # Context metadata
├── messages.json    # Conversation messages
└── embeddings.json  # Generated embeddings

// Automatic S3 sync
// Contexts are automatically synced to S3 on updates
// Large contexts are offloaded to S3 to save database space
Token Management

Automatic token counting and truncation:

// Token limits
const (
    MaxTokensPerContext = 128000  // Claude's context window
    WarningThreshold    = 100000  // Warning at 78% capacity
)

// Truncation strategies
type TruncationStrategy string

const (
    // Remove oldest messages first
    TruncationOldestFirst TruncationStrategy = "oldest_first"
    
    // Keep user messages, truncate assistant
    TruncationPreserveUser TruncationStrategy = "preserve_user"
    
    // Keep most relevant messages
    TruncationRelevanceBased TruncationStrategy = "relevance_based"
)

// Configure truncation
manager := NewContextManager(
    db,
    WithTruncationStrategy(TruncationRelevanceBased),
    WithMaxTokens(100000),
)

GitHub Integration

Content Storage

Store and index GitHub content:

// Store GitHub issue
err = engine.StoreGitHubContent(ctx, &GitHubIssue{
    Owner:     "S-Corkum",
    Repo:      "devops-mcp",
    Number:    123,
    Title:     "Memory leak in worker",
    Body:      "Description...",
    State:     "open",
    Labels:    []string{"bug", "performance"},
    CreatedAt: time.Now(),
})

// Store pull request
err = engine.StoreGitHubPR(ctx, &GitHubPullRequest{
    Owner:      "S-Corkum",
    Repo:       "devops-mcp",
    Number:     456,
    Title:      "Fix memory leak",
    Body:       "This PR fixes...",
    State:      "open",
    BaseRef:    "main",
    HeadRef:    "fix/memory-leak",
    Commits:    3,
    Additions:  45,
    Deletions:  12,
})

// Query stored content
issues, err := engine.GetGitHubIssues(ctx, &IssueQuery{
    Owner:  "S-Corkum",
    Repo:   "devops-mcp",
    State:  "open",
    Labels: []string{"bug"},
})
Relationship Management

Track relationships between GitHub entities:

// Relationship types
const (
    RelationshipReferences = "references"    // Issue references another
    RelationshipMentions   = "mentions"      // User mentions
    RelationshipLinked     = "linked"        // Linked issues/PRs
    RelationshipDuplicate  = "duplicate"     // Duplicate issues
    RelationshipBlocks     = "blocks"        // Blocking issues
    RelationshipImplements = "implements"    // PR implements issue
)

// Process relationships
relationships := engine.ProcessRelationships(ctx, &GitHubContent{
    Type:    "pull_request",
    Content: prData,
})

// Query relationships
related, err := engine.GetRelatedEntities(ctx, &EntityQuery{
    EntityType: "issue",
    EntityID:   "123",
    RelationType: RelationshipLinked,
})
Content Processing Pipeline
// Full processing pipeline
err = engine.ProcessGitHubContent(ctx, content)
// 1. Store in S3
// 2. Index in database
// 3. Extract relationships
// 4. Generate embeddings
// 5. Update search index
// 6. Publish events

Embedding Management

Embedding Interface
type EmbeddingManager interface {
    // Generate embedding for text
    GenerateEmbedding(ctx context.Context, text string, model string) ([]float32, error)
    
    // Batch generate embeddings
    BatchGenerateEmbeddings(ctx context.Context, texts []string, model string) ([][]float32, error)
    
    // Store embedding
    StoreEmbedding(ctx context.Context, embedding *Embedding) error
    
    // Search similar embeddings
    SearchSimilar(ctx context.Context, query []float32, limit int) ([]*Embedding, error)
}
Content Processing

Process different content types:

// Process code chunks
embeddings, err := embeddingManager.ProcessCodeChunks(ctx, &CodeChunkRequest{
    FilePath: "pkg/core/engine.go",
    Language: "go",
    ChunkSize: 500,
    Overlap: 50,
})

// Process GitHub issues
embeddings, err := embeddingManager.ProcessIssue(ctx, &IssueRequest{
    Owner:  "S-Corkum",
    Repo:   "devops-mcp",
    Number: 123,
})

// Process pull request discussions
embeddings, err := embeddingManager.ProcessDiscussion(ctx, &DiscussionRequest{
    PRID:     456,
    Comments: prComments,
})

Adapter Context Bridge

Integrates tools with context awareness:

// Execute tool with context recording
bridge := NewAdapterContextBridge(adapters, contextManager)

result, err := bridge.ExecuteWithContext(ctx, &ExecuteRequest{
    Tool:      "github",
    Action:    "create_issue",
    Params:    params,
    ContextID: contextID,
})

// Automatic context updates:
// 1. Records tool request in context
// 2. Executes tool action
// 3. Records tool response in context
// 4. Updates token count
// 5. Applies truncation if needed

Event System

Publish/subscribe for system events:

// Initialize event bus
eventBus := NewSystemEventBus()

// Subscribe to events
sub := eventBus.Subscribe("github.issue.created", func(event Event) error {
    issue := event.Data.(*GitHubIssue)
    // Process new issue
    return nil
})
defer sub.Unsubscribe()

// Publish events
err = eventBus.Publish(&Event{
    Type: "github.issue.created",
    Data: issue,
    Metadata: map[string]interface{}{
        "source": "webhook",
    },
})

// Event types
const (
    EventContextCreated    = "context.created"
    EventContextUpdated    = "context.updated"
    EventGitHubIssue       = "github.issue.*"
    EventGitHubPR          = "github.pr.*"
    EventEmbeddingCreated  = "embedding.created"
    EventToolExecuted      = "tool.executed"
)

Fallback Service

Ensures basic functionality during failures:

// Fallback service provides
fallback := NewFallbackService()

// Emergency health check
health := fallback.HealthCheck()

// Emergency ID generation
id := fallback.GenerateID()

// Emergency event logging
fallback.LogEvent("Service degraded", map[string]interface{}{
    "reason": "Database unavailable",
    "time":   time.Now(),
})

// Use in engine
engine := NewEngine(
    adapters,
    contextManager,
    WithFallbackService(fallback),
)

Database Adapter

Compatibility layer for migration:

// Wrap pkg/database with internal/database interface
adapter := NewDatabaseAdapter(pkgDB)

// Use adapter with legacy code
legacyService := NewLegacyService(adapter)

// Gradual migration path:
// 1. Wrap new implementation
// 2. Update services one by one
// 3. Remove adapter when complete

Error Handling

Comprehensive error types:

// Context errors
var (
    ErrContextNotFound = errors.New("context not found")
    ErrContextTooLarge = errors.New("context exceeds token limit")
    ErrInvalidContext  = errors.New("invalid context format")
)

// GitHub errors
var (
    ErrGitHubRateLimit = errors.New("GitHub rate limit exceeded")
    ErrGitHubNotFound  = errors.New("GitHub resource not found")
    ErrGitHubAuth      = errors.New("GitHub authentication failed")
)

// Engine errors
var (
    ErrAdapterNotFound = errors.New("adapter not found")
    ErrActionFailed    = errors.New("action execution failed")
    ErrInvalidParams   = errors.New("invalid parameters")
)

Metrics and Monitoring

Built-in metrics collection:

// Automatic metrics
- engine_operations_total
- engine_operation_duration_seconds
- context_tokens_total
- github_content_processed_total
- embedding_generations_total
- event_published_total
- adapter_executions_total

Testing

Unit Tests
// Mock dependencies
mockDB := NewMockDatabase()
mockS3 := NewMockS3Client()
mockAdapters := NewMockAdapterRegistry()

engine := NewEngine(
    mockAdapters,
    NewContextManager(mockDB, mockS3),
    NewMockMetricsClient(),
    NewMockEventBus(),
)

// Test operations
result, err := engine.ExecuteWithContext(ctx, request)
assert.NoError(t, err)
Integration Tests
// Test with real services
func TestEngineIntegration(t *testing.T) {
    if testing.Short() {
        t.Skip("Skipping integration test")
    }
    
    // Setup real dependencies
    db := setupTestDB(t)
    s3 := setupTestS3(t)
    
    // Test full workflow
    engine := NewEngine(...)
    
    // Create context
    // Execute tools
    // Verify results
}

Best Practices

  1. Always use context: Pass context for cancellation and tracing
  2. Handle token limits: Monitor context size and truncate appropriately
  3. Cache embeddings: Reuse embeddings to reduce costs
  4. Batch operations: Process multiple items together
  5. Monitor events: Subscribe to relevant events
  6. Test fallbacks: Ensure degraded mode works
  7. Version content: Track content versions in S3

Performance Optimization

  • S3 Caching: Cache frequently accessed contexts
  • Embedding Cache: Cache generated embeddings
  • Batch Processing: Process GitHub content in batches
  • Async Events: Handle events asynchronously
  • Connection Pooling: Reuse database connections

Migration Guide

When migrating from internal to pkg:

  1. Use database adapter for compatibility
  2. Update imports gradually
  3. Test thoroughly at each step
  4. Remove adapters when complete

Future Enhancements

  • GraphQL support for GitHub
  • Real-time context sync
  • Advanced relationship analysis
  • Context versioning
  • Distributed context management
  • ML-powered truncation

References

Documentation

Index

Constants

View Source
const (
	// TruncateOldestFirst truncates the oldest items first
	TruncateOldestFirst = "oldest_first"

	// TruncatePreservingUser truncates by removing assistant responses while preserving user messages
	TruncatePreservingUser = "preserving_user"

	// TruncateRelevanceBased truncates based on relevance to the current conversation
	TruncateRelevanceBased = "relevance_based"
)

Constants for truncation strategies

View Source
const (
	// ModelTypeOpenAI represents OpenAI embedding models
	ModelTypeOpenAI EmbeddingModelType = "openai"
	// ModelTypeHuggingFace represents HuggingFace embedding models
	ModelTypeHuggingFace EmbeddingModelType = "huggingface"
	// ModelTypeCustom represents custom embedding models
	ModelTypeCustom EmbeddingModelType = "custom"

	// Content types for embedding generation
	ContentTypeCodeChunk  = "code_chunk"
	ContentTypeIssue      = "issue"
	ContentTypeComment    = "comment"
	ContentTypeDiscussion = "discussion"
)

Variables

View Source
var ErrContextNotFound = errors.New("context not found")

ErrContextNotFound is returned when a context is not found

Functions

This section is empty.

Types

type AdapterContextBridge

type AdapterContextBridge struct {
	// contains filtered or unexported fields
}

AdapterContextBridge connects adapters with the context manager for managing context-aware tool interactions

func NewAdapterContextBridge

func NewAdapterContextBridge(contextManager interfaces.ContextManager, adapters map[string]interfaces.Adapter) *AdapterContextBridge

NewAdapterContextBridge creates a new adapter-context bridge

func (*AdapterContextBridge) ExecuteToolAction

func (b *AdapterContextBridge) ExecuteToolAction(ctx context.Context, contextID string, tool string, action string, params map[string]interface{}) (interface{}, error)

ExecuteToolAction executes a tool action with context awareness

func (*AdapterContextBridge) GetToolData

func (b *AdapterContextBridge) GetToolData(ctx context.Context, contextID string, tool string, query interface{}) (interface{}, error)

GetToolData gets data from a tool with context awareness

func (*AdapterContextBridge) HandleToolWebhook

func (b *AdapterContextBridge) HandleToolWebhook(ctx context.Context, tool string, eventType string, payload []byte) error

HandleToolWebhook handles a webhook from a tool

type ContextManager

type ContextManager struct {
	// contains filtered or unexported fields
}

ContextManager is a wrapper around the internal context manager This allows us to test core functionality without directly exposing internal implementations

func NewContextManager

func NewContextManager(db interface{}, cache cache.Cache) *ContextManager

NewContextManager creates a new context manager

func (*ContextManager) CreateContext

func (cm *ContextManager) CreateContext(ctx context.Context, contextData *models.Context) (*models.Context, error)

CreateContext creates a new context

func (*ContextManager) DeleteContext

func (cm *ContextManager) DeleteContext(ctx context.Context, contextID string) error

DeleteContext deletes a context

func (*ContextManager) GetContext

func (cm *ContextManager) GetContext(ctx context.Context, contextID string) (*models.Context, error)

GetContext retrieves a context by ID

func (*ContextManager) ListContexts

func (cm *ContextManager) ListContexts(ctx context.Context, agentID string, sessionID string, options map[string]interface{}) ([]*models.Context, error)

ListContexts lists contexts for an agent

func (*ContextManager) SearchInContext

func (cm *ContextManager) SearchInContext(ctx context.Context, contextID string, query string) ([]models.ContextItem, error)

SearchInContext searches for text within a context

func (*ContextManager) Subscribe

func (cm *ContextManager) Subscribe(eventType string, handler func(models.Event))

Subscribe subscribes to context events

func (*ContextManager) SummarizeContext

func (cm *ContextManager) SummarizeContext(ctx context.Context, contextID string) (string, error)

SummarizeContext generates a summary of a context

func (*ContextManager) UpdateContext

func (cm *ContextManager) UpdateContext(ctx context.Context, contextID string, updateData *models.Context, options *models.ContextUpdateOptions) (*models.Context, error)

UpdateContext updates an existing context

type DatabaseAdapter

type DatabaseAdapter struct {
	// contains filtered or unexported fields
}

DatabaseAdapter provides compatibility between internal/database and pkg/database This adapter allows us to migrate code incrementally without breaking existing functionality

func NewDatabaseAdapter

func NewDatabaseAdapter(db *sqlx.DB, logger observability.Logger) (*DatabaseAdapter, error)

NewDatabaseAdapter creates a new adapter that wraps a pkg/database.Database instance but exposes it with the same interface as internal/database.Database

func (*DatabaseAdapter) DeleteGitHubContent

func (a *DatabaseAdapter) DeleteGitHubContent(ctx context.Context, owner, repo, contentType, contentID string) error

DeleteGitHubContent deletes GitHub content metadata from the database

func (*DatabaseAdapter) GetDB

func (a *DatabaseAdapter) GetDB() *sqlx.DB

GetDB returns the underlying sqlx.DB instance

func (*DatabaseAdapter) GetGitHubContent

func (a *DatabaseAdapter) GetGitHubContent(ctx context.Context, owner, repo, contentType, contentID string) (*storage.ContentMetadata, error)

GetGitHubContent retrieves GitHub content metadata from the database

func (*DatabaseAdapter) GetGitHubContentByChecksum

func (a *DatabaseAdapter) GetGitHubContentByChecksum(ctx context.Context, checksum string) (*storage.ContentMetadata, error)

GetGitHubContentByChecksum retrieves GitHub content metadata by checksum

func (*DatabaseAdapter) ListGitHubContent

func (a *DatabaseAdapter) ListGitHubContent(ctx context.Context, owner, repo, contentType string, limit int) ([]*storage.ContentMetadata, error)

ListGitHubContent lists GitHub content metadata from the database

func (*DatabaseAdapter) StoreGitHubContent

func (a *DatabaseAdapter) StoreGitHubContent(ctx context.Context, metadata *storage.ContentMetadata) error

StoreGitHubContent stores GitHub content metadata in the database This method adapts the pkg/database implementation to match the internal/database interface

type EmbeddingManager

type EmbeddingManager struct {
	// contains filtered or unexported fields
}

EmbeddingManager manages the embedding pipeline

func NewEmbeddingManager

func NewEmbeddingManager(db *sql.DB, chunkingService *chunking.ChunkingService, pipeline EmbeddingPipeline) (*EmbeddingManager, error)

NewEmbeddingManager creates a new embedding manager

func (*EmbeddingManager) CreateEmbeddingFromContent

func (m *EmbeddingManager) CreateEmbeddingFromContent(ctx context.Context, content string, contentType string, contentID string) error

CreateEmbeddingFromContent generates and stores an embedding for a content string

func (*EmbeddingManager) CreateEmbeddingsFromCodeFile

func (m *EmbeddingManager) CreateEmbeddingsFromCodeFile(ctx context.Context, owner string, repo string, path string, content []byte) error

CreateEmbeddingsFromCodeFile processes a code file to generate and store embeddings

func (*EmbeddingManager) CreateEmbeddingsFromDiscussion

func (m *EmbeddingManager) CreateEmbeddingsFromDiscussion(ctx context.Context, owner string, repo string, discussionID string) error

CreateEmbeddingsFromDiscussion processes a GitHub discussion to generate and store embeddings

func (*EmbeddingManager) CreateEmbeddingsFromDiscussions

func (m *EmbeddingManager) CreateEmbeddingsFromDiscussions(ctx context.Context, owner string, repo string, discussionIDs []string) error

CreateEmbeddingsFromDiscussions processes multiple GitHub discussions to generate and store embeddings

func (*EmbeddingManager) CreateEmbeddingsFromIssue

func (m *EmbeddingManager) CreateEmbeddingsFromIssue(ctx context.Context, owner string, repo string, issueNumber int) error

CreateEmbeddingsFromIssue processes a GitHub issue to generate and store embeddings

func (*EmbeddingManager) CreateEmbeddingsFromIssues

func (m *EmbeddingManager) CreateEmbeddingsFromIssues(ctx context.Context, owner string, repo string, issueNumbers []int) error

CreateEmbeddingsFromIssues processes multiple GitHub issues to generate and store embeddings

func (*EmbeddingManager) ProcessRepository

func (m *EmbeddingManager) ProcessRepository(ctx context.Context, owner string, repo string) error

ProcessRepository processes an entire repository to generate and store embeddings

func (*EmbeddingManager) SearchSimilarContent

func (m *EmbeddingManager) SearchSimilarContent(
	ctx context.Context,
	text string,
	modelType EmbeddingModelType,
	modelName string,
	limit int,
	threshold float32,
) ([]map[string]interface{}, error)

SearchSimilarContent searches for content similar to the provided text

type EmbeddingModelType

type EmbeddingModelType string

EmbeddingModelType represents the type of embedding model

type EmbeddingPipeline

type EmbeddingPipeline interface {
	// ProcessContent processes content to generate and store embeddings
	ProcessContent(ctx context.Context, content string, contentType string, contentID string) error
	// BatchProcessContent processes multiple content items in a batch
	BatchProcessContent(ctx context.Context, contents []string, contentType string, contentIDs []string) error
	// ProcessCodeChunks processes code chunks to generate and store embeddings
	ProcessCodeChunks(ctx context.Context, contentType string, contentID string, chunkIDs []string) error
	// ProcessIssues processes GitHub issues to generate and store embeddings
	ProcessIssues(ctx context.Context, ownerRepo string, issueNumbers []int) error
	// ProcessDiscussions processes GitHub discussions to generate and store embeddings
	ProcessDiscussions(ctx context.Context, ownerRepo string, discussionIDs []string) error
}

EmbeddingPipeline coordinates the embedding generation and storage process

type EmbeddingService

type EmbeddingService interface {
	// GenerateEmbedding creates an embedding for a single text
	GenerateEmbedding(ctx context.Context, text string, contentType string, contentID string) (*EmbeddingVector, error)
	// BatchGenerateEmbeddings creates embeddings for multiple texts
	BatchGenerateEmbeddings(ctx context.Context, texts []string, contentType string, contentIDs []string) ([]*EmbeddingVector, error)
}

EmbeddingService defines the interface for generating embeddings

type EmbeddingStorage

type EmbeddingStorage interface {
	// StoreEmbedding stores a single embedding
	StoreEmbedding(ctx context.Context, embedding *EmbeddingVector) error
	// BatchStoreEmbeddings stores multiple embeddings in a batch
	BatchStoreEmbeddings(ctx context.Context, embeddings []*EmbeddingVector) error
	// FindSimilarEmbeddings finds embeddings similar to the provided one
	FindSimilarEmbeddings(ctx context.Context, embedding *EmbeddingVector, limit int, threshold float32) ([]*EmbeddingVector, error)
}

EmbeddingStorage defines the interface for storing and retrieving embeddings

type EmbeddingVector

type EmbeddingVector struct {
	// The actual embedding vector values
	Vector []float32 `json:"vector"`
	// Dimensions of the vector
	Dimensions int `json:"dimensions"`
	// Model ID used to generate this embedding
	ModelID string `json:"model_id"`
	// ContentType indicates what type of content this is an embedding for
	ContentType string `json:"content_type"`
	// ContentID is a unique identifier for the content
	ContentID string `json:"content_id"`
	// Metadata about the embedding and content
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

EmbeddingVector represents a vector embedding with metadata

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine is the core engine of the MCP server

func NewEngine

func NewEngine(
	ctx context.Context,
	config interface{},
	db *database.Database,
	cacheClient cache.Cache,
	metricsClient observability.MetricsClient,
) (*Engine, error)

NewEngine creates a new engine

func (*Engine) Close

func (e *Engine) Close()

Close releases all engine resources

func (*Engine) ExecuteAdapterAction

func (e *Engine) ExecuteAdapterAction(ctx context.Context, contextID string, adapterType string, action string, params map[string]interface{}) (interface{}, error)

ExecuteAdapterAction executes an action using the appropriate adapter

func (*Engine) GetAdapter

func (e *Engine) GetAdapter(adapterType string) (interface{}, error)

GetAdapter gets an adapter by type

func (*Engine) GetContextManager

func (e *Engine) GetContextManager() *contextManager.Manager

GetContextManager returns the context manager

func (*Engine) GetGitHubContentManager

func (e *Engine) GetGitHubContentManager() *GitHubContentManager

GetGitHubContentManager returns the GitHub content manager

func (*Engine) HandleAdapterWebhook

func (e *Engine) HandleAdapterWebhook(ctx context.Context, adapterType string, eventType string, payload []byte) error

HandleAdapterWebhook handles a webhook event using the appropriate adapter

func (*Engine) Health

func (e *Engine) Health() map[string]string

Health returns the health status of all components

func (*Engine) RecordWebhookInContext

func (e *Engine) RecordWebhookInContext(ctx context.Context, agentID string, adapterType string, eventType string, payload interface{}) (string, error)

RecordWebhookInContext records a webhook event in a context

func (*Engine) Shutdown

func (e *Engine) Shutdown(ctx context.Context) error

Shutdown performs a graceful shutdown of the engine

type FallbackService

type FallbackService struct {
	// contains filtered or unexported fields
}

FallbackService provides degraded service when primary services fail

func NewFallbackService

func NewFallbackService() *FallbackService

NewFallbackService creates a new fallback service

func (*FallbackService) EmergencyHealthCheck

func (s *FallbackService) EmergencyHealthCheck() map[string]string

EmergencyHealthCheck provides a minimal health check

func (*FallbackService) GenerateEmergencyID

func (s *FallbackService) GenerateEmergencyID() string

GenerateEmergencyID generates a unique ID for emergency use

func (*FallbackService) LogEmergencyEvent

func (s *FallbackService) LogEmergencyEvent(ctx context.Context, eventType, details string) error

LogEmergencyEvent logs an emergency event

type GitHubContentManager

type GitHubContentManager struct {
	// contains filtered or unexported fields
}

GitHubContentManager manages GitHub content storage and retrieval

func NewGitHubContentManager

func NewGitHubContentManager(
	db *database.Database,
	s3Client *storage.S3Client,
	metricsClient observability.MetricsClient,
	relationshipService relationship.Service,
) (*GitHubContentManager, error)

NewGitHubContentManager creates a new GitHub content manager

func (*GitHubContentManager) DeleteContent

func (m *GitHubContentManager) DeleteContent(
	ctx context.Context,
	owner string,
	repo string,
	contentType storage.ContentType,
	contentID string,
) error

DeleteContent deletes GitHub content

func (*GitHubContentManager) GetContent

func (m *GitHubContentManager) GetContent(
	ctx context.Context,
	owner string,
	repo string,
	contentType storage.ContentType,
	contentID string,
) ([]byte, *storage.ContentMetadata, error)

GetContent retrieves GitHub content by owner, repo, type, and ID

func (*GitHubContentManager) GetContentByChecksum

func (m *GitHubContentManager) GetContentByChecksum(
	ctx context.Context,
	checksum string,
) ([]byte, *storage.ContentMetadata, error)

GetContentByChecksum retrieves GitHub content by its checksum

func (*GitHubContentManager) ListContent

func (m *GitHubContentManager) ListContent(
	ctx context.Context,
	owner string,
	repo string,
	contentType storage.ContentType,
	limit int,
) ([]*storage.ContentMetadata, error)

ListContent lists GitHub content for a repository

func (*GitHubContentManager) StoreContent

func (m *GitHubContentManager) StoreContent(
	ctx context.Context,
	owner string,
	repo string,
	contentType storage.ContentType,
	contentID string,
	data []byte,
	metadata map[string]interface{},
) (*storage.ContentMetadata, error)

StoreContent stores GitHub content in S3 and indexes it in the database

type GitHubRelationshipManager

type GitHubRelationshipManager struct {
	// contains filtered or unexported fields
}

GitHubRelationshipManager manages relationships between GitHub entities

func NewGitHubRelationshipManager

func NewGitHubRelationshipManager(relationshipService relationship.Service, contentManager *GitHubContentManager) *GitHubRelationshipManager

NewGitHubRelationshipManager creates a new relationship manager for GitHub content

func (*GitHubRelationshipManager) ProcessContentRelationships

func (m *GitHubRelationshipManager) ProcessContentRelationships(
	ctx context.Context,
	metadata *storage.ContentMetadata,
	content []byte,
) error

ProcessContentRelationships processes relationships for stored content

type MockCache

type MockCache struct {
	mock.Mock
}

MockCache is a mock implementation of the cache.Cache for testing

func (*MockCache) Close

func (m *MockCache) Close() error

Close mocks the cache.Cache.Close method

func (*MockCache) Delete

func (m *MockCache) Delete(ctx context.Context, key string) error

Delete mocks the cache.Cache.Delete method

func (*MockCache) Exists

func (m *MockCache) Exists(ctx context.Context, key string) (bool, error)

Exists mocks the cache.Cache.Exists method

func (*MockCache) Flush

func (m *MockCache) Flush(ctx context.Context) error

Flush mocks the cache.Cache.Flush method

func (*MockCache) Get

func (m *MockCache) Get(ctx context.Context, key string, value interface{}) error

Get mocks the cache.Cache.Get method

func (*MockCache) Set

func (m *MockCache) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

Set mocks the cache.Cache.Set method

type MockDB

type MockDB struct {
	mock.Mock
}

MockDB is a mock implementation for database operations in tests

func (*MockDB) CreateContext

func (m *MockDB) CreateContext(ctx context.Context, contextData *models.Context) error

CreateContext mocks creating a context in the database

func (*MockDB) DeleteContext

func (m *MockDB) DeleteContext(ctx context.Context, contextID string) error

DeleteContext mocks deleting a context from the database

func (*MockDB) GetContext

func (m *MockDB) GetContext(ctx context.Context, contextID string) (*models.Context, error)

GetContext mocks retrieving a context from the database

func (*MockDB) GetDB

func (m *MockDB) GetDB() interface{}

GetDB mocks getting the underlying database connection

func (*MockDB) ListContexts

func (m *MockDB) ListContexts(ctx context.Context, agentID, sessionID string, options map[string]interface{}) ([]*models.Context, error)

ListContexts mocks listing contexts from the database

func (*MockDB) UpdateContext

func (m *MockDB) UpdateContext(ctx context.Context, contextData *models.Context) error

UpdateContext mocks updating a context in the database

type MockMetricsClient

type MockMetricsClient struct{}

MockMetricsClient is a mock implementation of observability.MetricsClient

func (*MockMetricsClient) Close

func (m *MockMetricsClient) Close() error

Close is a no-op implementation

func (*MockMetricsClient) RecordCacheOperation

func (m *MockMetricsClient) RecordCacheOperation(operation string, success bool, durationSeconds float64)

RecordCacheOperation is a no-op implementation

func (*MockMetricsClient) RecordCounter

func (m *MockMetricsClient) RecordCounter(name string, value float64, labels map[string]string)

RecordCounter is a no-op implementation

func (*MockMetricsClient) RecordGauge

func (m *MockMetricsClient) RecordGauge(name string, value float64, labels map[string]string)

RecordGauge is a no-op implementation

func (*MockMetricsClient) RecordHistogram

func (m *MockMetricsClient) RecordHistogram(name string, value float64, labels map[string]string)

RecordHistogram is a no-op implementation

func (*MockMetricsClient) RecordOperation

func (m *MockMetricsClient) RecordOperation(component string, operation string, success bool, durationSeconds float64, labels map[string]string)

RecordOperation is a no-op implementation

func (*MockMetricsClient) RecordTimer

func (m *MockMetricsClient) RecordTimer(name string, duration time.Duration, labels map[string]string)

RecordTimer is a no-op implementation

func (*MockMetricsClient) StartTimer

func (m *MockMetricsClient) StartTimer(name string, labels map[string]string) func()

StartTimer is a no-op implementation

type MockSystemEventBus

type MockSystemEventBus struct{}

MockSystemEventBus is a mock implementation of system.EventBus

func (*MockSystemEventBus) Publish

func (b *MockSystemEventBus) Publish(ctx context.Context, event system.Event) error

Publish is a no-op implementation

func (*MockSystemEventBus) Subscribe

func (b *MockSystemEventBus) Subscribe(eventType system.EventType, handler func(ctx context.Context, event system.Event) error)

Subscribe is a no-op implementation

func (*MockSystemEventBus) Unsubscribe

func (b *MockSystemEventBus) Unsubscribe(eventType system.EventType, handler func(ctx context.Context, event system.Event) error)

Unsubscribe is a no-op implementation

type SystemEventBus

type SystemEventBus struct {
	// contains filtered or unexported fields
}

SystemEventBus implements the system.EventBus interface

func NewSystemEventBus

func NewSystemEventBus() *SystemEventBus

NewSystemEventBus creates a new system event bus

func (*SystemEventBus) Publish

func (b *SystemEventBus) Publish(ctx context.Context, event system.Event) error

Publish publishes an event to all subscribers

func (*SystemEventBus) Subscribe

func (b *SystemEventBus) Subscribe(eventType system.EventType, handler func(context.Context, system.Event) error)

Subscribe subscribes to events of a specific type

func (*SystemEventBus) Unsubscribe

func (b *SystemEventBus) Unsubscribe(eventType system.EventType, handler func(context.Context, system.Event) error)

Unsubscribe unsubscribes from events of a specific type

type TestMockEngine

type TestMockEngine struct {
	ContextManager interface{} // Added to satisfy tests
	// contains filtered or unexported fields
}

TestMockEngine is a mock implementation of the Engine for testing

func NewTestMockEngine

func NewTestMockEngine() *TestMockEngine

NewTestMockEngine creates a new mock engine for testing

func (*TestMockEngine) GetAdapter

func (m *TestMockEngine) GetAdapter(name string) (interface{}, error)

GetAdapter returns an adapter by name

func (*TestMockEngine) Health

func (m *TestMockEngine) Health() map[string]string

Health returns a map of component health statuses

func (*TestMockEngine) ProcessEvent

func (m *TestMockEngine) ProcessEvent(event interface{}) error

ProcessEvent processes an event

func (*TestMockEngine) RegisterAdapter

func (m *TestMockEngine) RegisterAdapter(name string, adapter interface{})

RegisterAdapter registers an adapter with the mock engine

type TruncateStrategy

type TruncateStrategy string

TruncateStrategy defines the strategy for truncating a context

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL