implement-repository-pattern
Creates repository following Clean Architecture with Protocol in domain layer and Implementation in infrastructure layer. Use when adding new data access layer, creating database interaction, implementing persistence, or need to store/retrieve domain models. Enforces Protocol/ABC pattern with ServiceResult, ManagedResource lifecycle, and proper layer separation. Triggers on "create repository for X", "implement data access for Y", "add persistence layer", or "store/retrieve domain model".
What this skill does
Works with Python files in domain/repositories/ and infrastructure/ directories.
# Implement Repository Pattern
## Table of Contents
### Core Sections
- [Purpose](#purpose)
- Core responsibility: Create repositories with Protocol/Implementation separation
- [Quick Start](#quick-start)
- Fastest path: Create repository from user request to working implementation
- [Instructions](#instructions)
- [Step 1: Create Domain Protocol (Interface)](#step-1-create-domain-protocol-interface)
- [Step 2: Create Infrastructure Implementation](#step-2-create-infrastructure-implementation)
- [Step 3: Add Cypher Queries](#step-3-add-cypher-queries)
- [Step 4: Register in Container](#step-4-register-in-container)
- [Step 5: Create Tests](#step-5-create-tests)
- [Examples](#examples)
- [Example 1: Simple CRUD Repository](#example-1-simple-crud-repository)
- [Example 2: Repository with Complex Domain Model](#example-2-repository-with-complex-domain-model)
- [Example 3: Repository with Pagination](#example-3-repository-with-pagination)
### Patterns & Best Practices
- [Common Patterns](#common-patterns)
- [Pattern 1: Query Parameter Validation](#pattern-1-query-parameter-validation)
- [Pattern 2: ServiceResult Propagation](#pattern-2-serviceresult-propagation)
- [Pattern 3: Resource Lifecycle](#pattern-3-resource-lifecycle)
- [Red Flags - STOP](#red-flags---stop)
- Critical issues to watch for in repository implementation
- [Success Checklist](#success-checklist)
- Complete validation before marking repository done
### Supporting Resources
- [Requirements](#requirements)
- Dependencies, project structure, and setup requirements
- [See Also](#see-also)
- [templates/protocol-template.py](./templates/protocol-template.py) - Repository protocol skeleton
- [templates/implementation-template.py](./templates/implementation-template.py) - Neo4j implementation skeleton
- [templates/test-template.py](./templates/test-template.py) - Test suite skeleton
- [references/pattern-guide.md](./references/pattern-guide.md) - Complete pattern catalog
- [references/troubleshooting.md](./references/troubleshooting.md) - Common issues and solutions
- [scripts/analyze_queries.py](./scripts/analyze_queries.py) - Analyze Cypher queries in repository implementations
- [scripts/generate_repository.py](./scripts/generate_repository.py) - Generate repository pattern files with domain protocol and implementation
- [scripts/validate_repository_patterns.py](./scripts/validate_repository_patterns.py) - Validate repository pattern compliance across the codebase
## Purpose
Create repositories following Clean Architecture principles with Protocol (domain layer) and Implementation (infrastructure layer) separation. Ensures proper dependency inversion, ServiceResult return types, and resource lifecycle management.
## When to Use
Use this skill when:
- **Adding new data access layer** - Creating persistence for domain models
- **Creating database interaction** - Implementing queries and commands against data stores
- **Implementing persistence** - Storing and retrieving domain entities
- **Need to store/retrieve domain models** - Data access abstraction required
**Trigger phrases:**
- "Create a repository for X"
- "Implement data access for Y"
- "Add persistence layer for Z"
- "Store/retrieve domain model X"
## Quick Start
**User:** "Create a repository for storing search history"
**What happens:**
1. Create Protocol interface in `domain/repositories/search_history_repository.py`
2. Create Neo4j implementation in `infrastructure/neo4j/search_history_repository.py`
3. Implement ManagedResource for lifecycle
4. Use ServiceResult for all operations
5. Add required Cypher queries
**Result:** ✅ Repository with Protocol + Implementation ready for dependency injection
## Instructions
### Step 1: Create Domain Protocol (Interface)
**Location:** `src/project_watch_mcp/domain/repositories/{name}_repository.py`
**Pattern:**
```python
from abc import ABC, abstractmethod
from project_watch_mcp.domain.common import ServiceResult
class {Name}Repository(ABC):
"""Port for {purpose} storage and retrieval.
This interface defines the contract for {operations}.
Concrete implementations will be provided in the infrastructure layer.
"""
@abstractmethod
async def {operation}(self, param: Type) -> ServiceResult[ReturnType]:
"""Brief description of operation.
Args:
param: Description
Returns:
ServiceResult[ReturnType]: Success with data or Failure on errors
"""
pass
```
**Key Requirements:**
- Inherit from `ABC`
- Use `@abstractmethod` decorator
- Return `ServiceResult[T]` for all operations
- Document expected behavior in docstrings
- No implementation details (pure interface)
### Step 2: Create Infrastructure Implementation
**Location:** `src/project_watch_mcp/infrastructure/neo4j/{name}_repository.py`
**Pattern:**
```python
from neo4j import AsyncDriver, RoutingControl
from project_watch_mcp.config.settings import Settings
from project_watch_mcp.domain.common import ServiceResult
from project_watch_mcp.domain.repositories.{name}_repository import {Name}Repository
from project_watch_mcp.domain.services.resource_manager import ManagedResource
class Neo4j{Name}Repository({Name}Repository, ManagedResource):
"""Neo4j adapter implementing {Name}Repository interface."""
def __init__(self, driver: AsyncDriver, settings: Settings):
if not driver:
raise ValueError("Neo4j driver is required")
if not settings:
raise ValueError("Settings is required")
self.driver = driver
self.settings = settings
self.database = settings.neo4j.database_name
async def _execute_with_retry(
self,
query: str,
parameters: dict[str, Any] | None = None,
routing: RoutingControl = RoutingControl.WRITE,
) -> ServiceResult[list[dict]]:
"""Execute query with parameter validation and retry logic."""
# Validate before executing
validation_result = validate_and_build_query(query, parameters, strict=True)
if validation_result.is_failure:
return ServiceResult.fail(f"Validation failed: {validation_result.error}")
validated_query = validation_result.data
try:
records, _, _ = await self.driver.execute_query(
cast(LiteralString, validated_query.query),
validated_query.parameters,
database_=self.database,
routing_=routing,
)
return ServiceResult.ok([dict(record) for record in records])
except Neo4jError as e:
return ServiceResult.fail(f"Database error: {str(e)}")
async def close(self) -> None:
"""Close and cleanup resources (ManagedResource protocol)."""
# Repository-specific cleanup if needed
pass
```
**Key Requirements:**
- Implement Protocol interface
- Inherit from `ManagedResource`
- Required constructor params: `driver: AsyncDriver, settings: Settings`
- Validate parameters in constructor (`if not driver: raise ValueError`)
- Use `_execute_with_retry()` for all database operations
- Implement `close()` for resource cleanup
- All operations return `ServiceResult[T]`
### Step 3: Add Cypher Queries
**Location:** `src/project_watch_mcp/infrastructure/neo4j/queries.py`
**Pattern:**
```python
class CypherQueries:
# Existing queries...
# {Name}Repository Queries
GET_{ENTITY} = """
MATCH (e:{Label} {project_name: $project_name, id: $id})
RETURN e
"""
SAVE_{ENTITY} = """
MERGE (e:{Label} {project_name: $project_name, id: $id})
SET e += $properties
SET e.updated_at = datetime()
RETURN e
"""
```
**Key Requirements:**
- Group queries by repository
- Use parameterized queries (prevent injection)
- Use MERGE for upsert operations
- Include timestamp managRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.