Pattern-016: Repository Context Enrichment Pattern

Status

Proven

Context

Workflow systems that integrate with external services like GitHub require repository context for operations like ticket creation, but requiring users to explicitly provide repository information every time creates friction and reduces usability. Without automatic context enrichment, workflows either fail due to missing information or force users to repeatedly provide the same contextual data. The Repository Context Enrichment Pattern addresses:

Pattern Description

The Repository Context Enrichment Pattern automatically enriches workflow context with repository information and other required contextual data, enabling seamless integration workflows. The pattern intercepts workflow creation, identifies workflows that require specific context (like repository information), attempts to enrich the context from available sources, and gracefully handles enrichment failures to maintain workflow reliability.

Implementation

Structure

# Repository context enrichment framework
class ContextEnrichmentEngine:
    def __init__(self, project_context: ProjectContext):
        self.project_context = project_context
        self.enrichers = []

    def register_enricher(self, enricher: ContextEnricher):
        """Register context enricher for specific workflow types"""
        self.enrichers.append(enricher)

    async def enrich_workflow_context(self, intent: Intent) -> Dict[str, Any]:
        """Apply context enrichment based on workflow type"""
        pass

    def get_repository_context(self) -> Optional[RepositoryInfo]:
        """Extract repository context from project"""
        pass

Example (GitHub Repository Enrichment)

from typing import Dict, Any, Optional
import structlog

logger = structlog.get_logger()

class GitHubRepositoryEnricher:
    """Enriches workflow context with GitHub repository information"""

    def __init__(self, project_context: ProjectContext):
        self.project_context = project_context

    def can_enrich(self, intent: Intent) -> bool:
        """Check if this enricher applies to the given intent"""
        return intent.type in [
            WorkflowType.CREATE_TICKET,
            WorkflowType.CREATE_ISSUE,
            WorkflowType.ANALYZE_REPOSITORY
        ]

    async def enrich_context(self, intent: Intent) -> Dict[str, Any]:
        """Enrich context with repository information"""
        context = dict(intent.context)

        if not self.can_enrich(intent):
            return context

        try:
            # Attempt to get repository from project context
            repo = await self.project_context.get_github_repository()
            if repo:
                context["repository"] = {
                    "owner": repo.owner,
                    "name": repo.name,
                    "full_name": repo.full_name,
                    "url": repo.url
                }
                logger.info(
                    "Repository context enriched",
                    workflow_type=intent.type,
                    repository=repo.full_name
                )
            else:
                logger.warning(
                    "No GitHub repository found for project",
                    project_id=self.project_context.id,
                    workflow_type=intent.type
                )
        except Exception as e:
            logger.error(
                "Failed to enrich context with repository",
                error=str(e),
                workflow_type=intent.type,
                project_id=self.project_context.id
            )
            # Don't fail the workflow - proceed without enrichment

        return context

def create_workflow_from_intent(intent: Intent, project_context: ProjectContext):
    """
    Create workflow with enriched context for seamless integrations.
    This pattern ensures downstream handlers have necessary context.
    """
    # Initialize enrichment engine
    enricher = GitHubRepositoryEnricher(project_context)

    # Enrich context based on workflow type
    enriched_context = await enricher.enrich_context(intent)

    # Create workflow with enriched context
    workflow = Workflow(
        type=intent.type,
        context=enriched_context,
        metadata={
            "enrichment_applied": True,
            "enrichment_timestamp": datetime.utcnow().isoformat()
        }
    )

    logger.info(
        "Workflow created with context enrichment",
        workflow_type=intent.type,
        context_keys=list(enriched_context.keys())
    )

    return workflow

Example (Multi-Integration Enrichment)

class MultiIntegrationEnricher:
    """Supports multiple integration types through extensible enrichment"""

    def __init__(self, project_context: ProjectContext):
        self.project_context = project_context
        self.enrichers = {
            'github': GitHubRepositoryEnricher(project_context),
            'notion': NotionWorkspaceEnricher(project_context),
            'slack': SlackChannelEnricher(project_context)
        }

    async def enrich_workflow_context(self, intent: Intent) -> Dict[str, Any]:
        """Apply all applicable enrichers to workflow context"""
        context = dict(intent.context)

        for enricher_name, enricher in self.enrichers.items():
            try:
                if enricher.can_enrich(intent):
                    enriched = await enricher.enrich_context(intent)
                    context.update(enriched)
                    logger.debug(
                        "Applied context enricher",
                        enricher=enricher_name,
                        workflow_type=intent.type
                    )
            except Exception as e:
                logger.error(
                    "Context enricher failed",
                    enricher=enricher_name,
                    error=str(e),
                    workflow_type=intent.type
                )
                # Continue with other enrichers

        return context

# Centralized workflow factory with enrichment
class EnrichedWorkflowFactory:
    def __init__(self, project_context: ProjectContext):
        self.enricher = MultiIntegrationEnricher(project_context)

    async def create_workflow(self, intent: Intent) -> Workflow:
        """Create workflow with automatic context enrichment"""
        enriched_context = await self.enricher.enrich_workflow_context(intent)

        return Workflow(
            type=intent.type,
            context=enriched_context,
            created_at=datetime.utcnow()
        )

Usage Guidelines

When to Use Repository Context Enrichment

Enrichment Strategy Best Practices

Error Handling Best Practices

Anti-Patterns to Avoid

Benefits

Trade-offs

Migration Notes (for consolidation from legacy systems)

Quality Assurance Checklist

Agent Coordination Notes

References

Last updated: September 15, 2025