---
name: Create Cursor Skills
overview: Create 5 comprehensive Cursor Skills (400-500 lines each, English only) covering testing, API design, database, observability, and Kubernetes deployment patterns based on existing codebase patterns.
todos:
  - id: create-testing-skill
    content: Create testing-patterns skill with Jest config, mocking strategies, and test examples
    status: completed
  - id: create-api-skill
    content: Create api-design skill with RESTful patterns, DTO validation, and OpenAPI docs
    status: completed
  - id: create-database-skill
    content: Create database-prisma skill with repository pattern, migrations, and query optimization
    status: completed
  - id: create-observability-skill
    content: Create observability-monitoring skill with metrics, logging, tracing, and health checks
    status: completed
  - id: create-kubernetes-skill
    content: Create deployment-kubernetes skill with K8s manifests, HPA, and deployment strategies
    status: completed
---

# Create Comprehensive Cursor Skills

## Overview

Create 5 detailed Cursor Skills (400-500 lines each, English only) to codify best practices and patterns from the GoodGo microservices platform. Each skill will be based on actual code patterns found in the codebase.

## Skills to Create

### 1. testing-patterns

**Location**: `.cursor/skills/testing-patterns/SKILL.md`

**Content Structure**:

- Jest configuration patterns (from [`services/_template/jest.config.ts`](services/_template/jest.config.ts))
- Test setup utilities (from [`services/_template/src/__tests__/setupTests.ts`](services/_template/src/__tests__/setupTests.ts))
- Unit testing patterns (from feature.service.test.ts, feature.repository.test.ts)
- Integration testing patterns (from health.controller.test.ts)
- E2E testing patterns (from feature.e2e.ts, health.e2e.ts)
- Mocking strategies:
                                                                - Prisma mocking
                                                                - Redis mocking
                                                                - Auth SDK mocking
                                                                - Logger mocking
- Test utilities (createMockReq, createMockRes, createMockNext)
- Coverage requirements (>70%)
- Common testing mistakes
- Debugging test failures

**Key Patterns to Document**:

```typescript
// Mock setup pattern
jest.mock('@goodgo/logger');
jest.mock('../feature.repository');

// Test structure pattern
describe('FeatureService', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });
  
  it('should create feature successfully', async () => {
    // Arrange
    const mockData = {...};
    (repository.create as jest.Mock).mockResolvedValue(mockData);
    
    // Act
    const result = await service.create(input);
    
    // Assert
    expect(repository.create).toHaveBeenCalledWith(input);
    expect(result).toEqual(mockData);
  });
});
```

### 2. api-design

**Location**: `.cursor/skills/api-design/SKILL.md`

**Content Structure**:

- RESTful conventions (resource naming, HTTP methods)
- Response format standards (from existing API responses)
- Error response structure (from [`services/_template/src/errors/`](services/_template/src/errors/))
- DTO validation with Zod (from [`services/_template/src/modules/feature/feature.dto.ts`](services/_template/src/modules/feature/feature.dto.ts))
- Controller patterns (from feature.controller.ts)
- Route organization (from feature.module.ts)
- OpenAPI/Swagger documentation (from [`services/_template/src/docs/swagger.ts`](services/_template/src/docs/swagger.ts))
- Pagination patterns
- Filtering and sorting
- API versioning (/api/v1/)
- Authentication headers
- Correlation ID propagation

**Key Patterns to Document**:

```typescript
// DTO with Zod
export const createFeatureDtoSchema = z.object({
  name: z.string().min(1).max(100),
  title: z.string().max(200).optional(),
});

// Controller pattern
export class FeatureController {
  async create(req: Request, res: Response, next: NextFunction) {
    const dto = createFeatureDtoSchema.parse(req.body);
    const result = await this.service.create(dto);
    res.status(201).json({ success: true, data: result });
  }
}

// Route with middleware
router.post('/', 
  authenticate(),
  authorize('admin'),
  validateDto(createFeatureDtoSchema),
  asyncHandler(controller.create)
);
```

### 3. database-prisma

**Location**: `.cursor/skills/database-prisma/SKILL.md`

**Content Structure**:

- Prisma schema conventions (from [`services/_template/prisma/schema.prisma`](services/_template/prisma/schema.prisma))
- Migration workflow (dev vs production)
- Seeding strategies (from [`services/_template/prisma/seed.ts`](services/_template/prisma/seed.ts))
- Repository pattern (from [`services/_template/src/modules/common/repository.ts`](services/_template/src/modules/common/repository.ts))
- BaseRepository implementation
- Feature-specific repositories (from feature.repository.ts)
- Connection pooling with Neon
- Transaction handling
- Query optimization
- Error handling (DatabaseError)
- Soft delete pattern
- Prisma Client generation

**Key Patterns to Document**:

```typescript
// BaseRepository pattern
export class BaseRepository<T, CreateInput, UpdateInput> {
  constructor(
    protected prisma: PrismaClient,
    protected modelName: string,
    protected delegate: any
  ) {}
  
  async findById(id: string): Promise<T | null> {
    try {
      return await this.delegate.findUnique({ where: { id } });
    } catch (error: any) {
      throw new DatabaseError(`Failed to find ${this.modelName}`, { id });
    }
  }
}

// Feature-specific repository
export class FeatureRepository extends BaseRepository<Feature, CreateFeatureInput, UpdateFeatureInput> {
  async findByName(name: string): Promise<Feature | null> {
    return this.findByUnique({ name });
  }
}
```

### 4. observability-monitoring

**Location**: `.cursor/skills/observability-monitoring/SKILL.md`

**Content Structure**:

- Prometheus metrics patterns (from [`services/_template/src/middlewares/metrics.middleware.ts`](services/_template/src/middlewares/metrics.middleware.ts))
- Metric types (Counter, Gauge, Histogram, Summary)
- Custom metrics creation
- Correlation ID middleware (from correlation.middleware.ts)
- Structured logging patterns (from logger.middleware.ts)
- Jaeger tracing integration
- Health check patterns (liveness vs readiness)
- Prometheus configuration (from [`infra/observability/prometheus/prometheus.yml`](infra/observability/prometheus/prometheus.yml))
- Grafana dashboard setup
- Loki log aggregation
- Alert rules
- Debugging with observability tools

**Key Patterns to Document**:

```typescript
// Metrics middleware pattern
const httpRequestDurationSeconds = new client.Histogram({
  name: 'http_request_duration_seconds',
  help: 'Duration of HTTP requests in seconds',
  labelNames: ['method', 'route', 'status_code', 'correlation_id'],
  buckets: [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 2, 5, 10],
});

// Correlation ID pattern
export const correlationMiddleware = () => {
  return (req: Request, res: Response, next: NextFunction) => {
    const correlationId = req.headers['x-correlation-id'] || generateCorrelationId();
    req.correlationId = correlationId;
    res.setHeader('X-Correlation-ID', correlationId);
    next();
  };
};

// Health check pattern
export class HealthController {
  async liveness(req: Request, res: Response) {
    res.json({ status: 'ok', timestamp: new Date().toISOString() });
  }
  
  async readiness(req: Request, res: Response) {
    const dbHealthy = await checkDatabaseConnection();
    const redisHealthy = await checkRedisConnection();
    res.json({ status: dbHealthy && redisHealthy ? 'ok' : 'degraded' });
  }
}
```

### 5. deployment-kubernetes

**Location**: `.cursor/skills/deployment-kubernetes/SKILL.md`

**Content Structure**:

- Kubernetes manifest structure (from [`deployments/production/kubernetes/`](deployments/production/kubernetes/))
- Deployment configuration
- Service types (ClusterIP, LoadBalancer)
- ConfigMap and Secrets management (from configmap.yaml, secrets.yaml.example)
- Ingress configuration (from ingress.yaml)
- HorizontalPodAutoscaler setup
- Resource limits and requests
- Health probes (liveness, readiness, startup)
- Rolling update strategy
- Environment variable management
- Multi-environment setup (staging vs production)
- Namespace organization
- Service discovery in K8s
- Troubleshooting K8s deployments

**Key Patterns to Document**:

```yaml
# Deployment with HPA
apiVersion: apps/v1
kind: Deployment
metadata:
  name: auth-service
  namespace: production
spec:
  replicas: 3
  template:
    spec:
      containers:
   - name: auth-service
        image: goodgo/auth-service:latest
        resources:
          requests:
            memory: "512Mi"
            cpu: "500m"
          limits:
            memory: "1Gi"
            cpu: "1000m"
        livenessProbe:
          httpGet:
            path: /health/live
            port: 5001
        readinessProbe:
          httpGet:
            path: /health/ready
            port: 5001

---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: auth-service-hpa
spec:
  scaleTargetRef:
    kind: Deployment
    name: auth-service
  minReplicas: 3
  maxReplicas: 10
  metrics:
 - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70
```

## Implementation Plan

### Skill Structure Template

Each skill will follow this structure:

```markdown
---
name: skill-name
description: Brief description of when to use this skill
---

# Skill Title

## When to Use This Skill

Clear description of scenarios where this skill applies.

## Core Concepts

Key concepts and terminology.

## Patterns and Best Practices

### Pattern 1: Name

**Purpose**: What this pattern solves
**When to Use**: Specific scenarios
**Implementation**: Code example
**Common Mistakes**: What to avoid

### Pattern 2: Name

[Same structure...]

## Code Examples

### Example 1: Scenario

Full working example with explanation.

### Example 2: Scenario

[More examples...]

## Common Mistakes

List of anti-patterns and how to fix them.

## Troubleshooting

Common issues and solutions.

## Checklist

- [ ] Item 1
- [ ] Item 2

## Resources

Links to related docs and code.
```

## Content Sources

Each skill will extract patterns from:

1. **testing-patterns**:

                                                                                                - `services/_template/jest.config.ts`
                                                                                                - `services/_template/src/__tests__/setupTests.ts`
                                                                                                - `services/_template/src/modules/feature/__tests__/*.test.ts`
                                                                                                - `services/_template/src/__tests__/*.e2e.ts`

2. **api-design**:

                                                                                                - `services/_template/src/modules/feature/feature.dto.ts`
                                                                                                - `services/_template/src/modules/feature/feature.controller.ts`
                                                                                                - `services/_template/src/modules/feature/feature.module.ts`
                                                                                                - `services/_template/src/docs/swagger.ts`
                                                                                                - `services/_template/src/errors/`

3. **database-prisma**:

                                                                                                - `services/_template/prisma/schema.prisma`
                                                                                                - `services/_template/prisma/seed.ts`
                                                                                                - `services/_template/src/modules/common/repository.ts`
                                                                                                - `services/_template/src/modules/feature/feature.repository.ts`
                                                                                                - `services/_template/src/config/database.config.ts`

4. **observability-monitoring**:

                                                                                                - `services/_template/src/middlewares/metrics.middleware.ts`
                                                                                                - `services/_template/src/middlewares/correlation.middleware.ts`
                                                                                                - `services/_template/src/middlewares/logger.middleware.ts`
                                                                                                - `services/_template/src/modules/health/health.controller.ts`
                                                                                                - `infra/observability/prometheus/prometheus.yml`

5. **deployment-kubernetes**:

                                                                                                - `deployments/production/kubernetes/auth-service.yaml`
                                                                                                - `deployments/production/kubernetes/configmap.yaml`
                                                                                                - `deployments/production/kubernetes/secrets.yaml.example`
                                                                                                - `deployments/production/kubernetes/ingress.yaml`
                                                                                                - `deployments/staging/kubernetes/` (for comparison)

## Skill Features

Each skill will include:

- Clear "When to Use" section
- Real code examples from the codebase
- Common mistakes and anti-patterns
- Troubleshooting guide
- Checklist for implementation
- Links to related documentation
- Cross-references to other skills

## Quality Standards

- Length: 400-500 lines per skill
- Language: English only (technical content)
- Code examples: Working, tested patterns from codebase
- Format: Markdown with code blocks
- Structure: Consistent across all skills
- Practical: Focus on actionable patterns, not theory

## Expected Outcomes

After creating these skills, developers will have:

1. Clear testing patterns for unit, integration, and E2E tests
2. Standardized API design with validation and documentation
3. Database best practices with Prisma and repository pattern
4. Observability setup for metrics, logging, and tracing
5. Kubernetes deployment patterns for production

These skills will complement existing skills:

- `project-rules`: General architecture and standards
- `documentation`: How to write docs
- `comment-code`: Bilingual code comments

## Implementation Order

1. `testing-patterns` - Most frequently used
2. `api-design` - Every new feature needs this
3. `database-prisma` - Database work is common
4. `observability-monitoring` - Important for debugging
5. `deployment-kubernetes` - Less frequent but critical

Each skill will be self-contained and can be used independently.