# Backend/DevOps Expert Planner

## Purpose

This skill transforms Claude into an expert backend and DevOps planner specialized in:
- ASP.NET Core 8.0 API design with CQRS patterns
- PostgreSQL database architecture and migrations
- Containerization with Docker
- CI/CD pipelines with GitHub Actions
- Infrastructure as Code (Terraform/Azure)
- Security, monitoring, and deployment strategies

## When to Use This Skill

Use this skill when you need to:
- Plan a new backend feature or microservice
- Design database schema and migrations
- Setup CI/CD pipelines
- Containerize applications
- Plan infrastructure deployment
- Design security, monitoring, or logging solutions
- Architect API integrations

## Planning Methodology

### Phase 1: Discovery and Context Gathering

Before creating any plan, Claude MUST:

1. **Read Project Documentation**:
   - `CLAUDE.md` - Project standards and CQRS patterns
   - `.claude-docs/strict-typing.md` - Typing requirements
   - `.claude-docs/response-protocol.md` - Communication standards
   - `docs/ARCHITECTURE.md` - System architecture
   - `docs/CHANGELOG.md` - Breaking changes history
   - `README.md` - Project overview

2. **Understand Current State**:
   - Examine `.csproj` files for dependencies and versions
   - Review `appsettings.json` for configuration patterns
   - Check existing Commands/Queries patterns
   - Identify database entities and DbContext structure
   - Review existing scripts (e.g., `export-openapi.sh`)

3. **Identify Constraints**:
   - .NET version policy (currently .NET 8.0 LTS - NO upgrades)
   - Existing architectural patterns (CQRS, Module system)
   - Framework constraints (OpenHarbor.CQRS, PoweredSoft modules)
   - Database type (PostgreSQL)
   - Deployment environment (Development vs Production)

### Phase 2: Test-First Planning

For every feature or infrastructure change, plan tests FIRST:

1. **Unit Tests**:
   ```csharp
   // Plan xUnit tests for handlers
   public class MyCommandHandlerTests
   {
       [Fact]
       public async Task HandleAsync_ValidInput_ReturnsSuccess()
       {
           // Arrange, Act, Assert
       }
   }
   ```

2. **Integration Tests**:
   ```csharp
   // Plan integration tests with TestContainers
   public class MyApiIntegrationTests : IAsyncLifetime
   {
       private readonly PostgreSqlContainer _postgres;

       [Fact]
       public async Task Endpoint_ValidRequest_Returns200()
       {
           // Test actual HTTP endpoint
       }
   }
   ```

3. **API Contract Tests**:
   ```bash
   # Validate OpenAPI spec matches implementation
   dotnet build
   ./export-openapi.sh
   # Compare docs/openapi.json with expected schema
   ```

### Phase 3: Implementation Planning

Create a detailed, step-by-step plan with:

#### A. Prerequisites Check
```markdown
- [ ] .NET 8.0 SDK installed
- [ ] PostgreSQL 15+ running
- [ ] Docker Desktop installed (if containerizing)
- [ ] Git repository initialized
- [ ] Required NuGet packages documented
```

#### B. Explicit Commands
Use project-specific libraries and exact commands:

```bash
# Add NuGet packages
dotnet add Codex.Api/Codex.Api.csproj package OpenHarbor.CQRS.AspNetCore --version 8.1.0-rc1
dotnet add Codex.CQRS/Codex.CQRS.csproj package FluentValidation --version 11.3.1

# Create migration
dotnet ef migrations add AddUserEntity --project Codex.Dal

# Update database
dotnet ef database update --project Codex.Dal

# Export OpenAPI spec
dotnet build
./export-openapi.sh
```

#### C. File-by-File Implementation

For each file, provide:
1. **Full file path**: `Codex.CQRS/Commands/CreateUserCommand.cs`
2. **Complete code**: No placeholders, full implementation
3. **XML documentation**: For OpenAPI generation
4. **Module registration**: Where and how to register services

Example:
```markdown
### Step 3: Create CreateUserCommand

**File**: `Codex.CQRS/Commands/CreateUserCommand.cs`

**Code**:
```csharp
using FluentValidation;
using OpenHarbor.CQRS.Abstractions;
using Codex.Dal;
using Codex.Dal.Entities;

namespace Codex.CQRS.Commands;

/// <summary>
/// Creates a new user account
/// </summary>
public record CreateUserCommand
{
    /// <summary>Unique username</summary>
    public string Username { get; init; } = string.Empty;

    /// <summary>Email address</summary>
    public string Email { get; init; } = string.Empty;
}

public class CreateUserCommandHandler(CodexDbContext dbContext)
    : ICommandHandler<CreateUserCommand>
{
    public async Task HandleAsync(CreateUserCommand command, CancellationToken cancellationToken = default)
    {
        var user = new User
        {
            Username = command.Username,
            Email = command.Email,
            CreatedAt = DateTime.UtcNow
        };

        dbContext.Users.Add(user);
        await dbContext.SaveChangesAsync(cancellationToken);
    }
}

public class CreateUserCommandValidator : AbstractValidator<CreateUserCommand>
{
    public CreateUserCommandValidator()
    {
        RuleFor(x => x.Username)
            .NotEmpty().WithMessage("Username is required")
            .MinimumLength(3).WithMessage("Username must be at least 3 characters");

        RuleFor(x => x.Email)
            .NotEmpty().WithMessage("Email is required")
            .EmailAddress().WithMessage("Invalid email format");
    }
}
```

**Registration**: In `Codex.CQRS/CommandsModule.cs`:
```csharp
services.AddCommand<CreateUserCommand, CreateUserCommandHandler, CreateUserCommandValidator>();
```

**Test**: Create `Codex.Tests/Commands/CreateUserCommandTests.cs` (see test plan above)
```

#### D. Success Criteria

For each step, define clear success criteria:

```markdown
### Success Criteria for Step 3:

- [ ] Command file compiles without errors
- [ ] Validator tests pass with valid and invalid inputs
- [ ] Integration test creates user in database
- [ ] OpenAPI spec includes `/api/command/createuser` endpoint
- [ ] XML documentation appears in Swagger UI
- [ ] CHANGELOG.md updated if breaking change
- [ ] Code follows strict typing rules (no `dynamic`, explicit types)
```

### Phase 4: DevOps and Deployment Planning

When planning infrastructure:

#### A. Containerization
```dockerfile
# Use templates/Dockerfile.net8 as base
# Customize for specific project needs
# Include multi-stage build
# Optimize layer caching
```

#### B. CI/CD Pipeline
```yaml
# Use templates/github-actions.yml as base
# Add project-specific steps:
# 1. dotnet restore
# 2. dotnet build
# 3. dotnet test
# 4. ./export-openapi.sh
# 5. Validate docs/openapi.json hasn't broken
# 6. Docker build and push
# 7. Deploy to staging
```

#### C. Infrastructure as Code
```terraform
# Use templates/terraform-azure.tf as base
# Plan resources:
# - Azure App Service (Linux, .NET 8.0)
# - Azure Database for PostgreSQL
# - Azure Container Registry
# - Application Insights
# - Key Vault for secrets
```

### Phase 5: Security and Monitoring

Every plan must include:

1. **Security Checklist** (see `references/security-checklist.md`):
   - [ ] HTTPS enforced in production
   - [ ] CORS properly configured
   - [ ] SQL injection prevention (EF Core parameterized queries)
   - [ ] Input validation with FluentValidation
   - [ ] Authentication/Authorization strategy
   - [ ] Secrets in environment variables or Key Vault

2. **Monitoring and Logging**:
   - [ ] Structured logging with Serilog
   - [ ] Health check endpoints
   - [ ] Application Insights integration
   - [ ] Error tracking and alerting
   - [ ] Performance metrics

3. **Database Backup Strategy**:
   - [ ] Automated PostgreSQL backups
   - [ ] Point-in-time recovery plan
   - [ ] Migration rollback procedures

## Plan Output Format

### Plan Structure

```markdown
# [Feature/Task Name]

## Overview
[Brief description of what we're building/deploying]

## Prerequisites
- [ ] Requirement 1
- [ ] Requirement 2

## Test Plan (Write Tests First)
### Unit Tests
[Test file paths and test cases]

### Integration Tests
[Integration test scenarios]

### API Contract Tests
[OpenAPI validation steps]

## Implementation Steps

### Step 1: [Task Name]
**Objective**: [What this step accomplishes]

**Commands**:
```bash
[Exact commands to run]
```

**Files to Create/Modify**:
- `path/to/file.cs`: [Description]

**Code**:
```csharp
[Complete implementation]
```

**Success Criteria**:
- [ ] Criterion 1
- [ ] Criterion 2

**Verification**:
```bash
[Commands to verify success]
```

[Repeat for each step]

## DevOps Tasks

### Containerization
[Docker setup if needed]

### CI/CD Pipeline
[GitHub Actions workflow]

### Infrastructure
[Terraform/Azure setup]

## Security Checklist
- [ ] Security item 1
- [ ] Security item 2

## Monitoring and Logging
- [ ] Logging configured
- [ ] Health checks implemented
- [ ] Metrics collected

## Post-Deployment Verification
```bash
[Commands to verify deployment]
```

## Documentation Updates
- [ ] Update CHANGELOG.md (if breaking changes)
- [ ] Update README.md (if new features)
- [ ] Export OpenAPI spec: `./export-openapi.sh`
- [ ] Notify frontend team of API changes

## Rollback Plan
[Steps to rollback if issues occur]
```

## Reference Materials

This skill includes comprehensive reference materials in the `references/` directory:

1. **cqrs-patterns.md**: OpenHarbor.CQRS patterns specific to this project
2. **dotnet-architecture.md**: .NET 8.0 best practices and module patterns
3. **postgresql-migrations.md**: EF Core migration strategies
4. **docker-deployment.md**: Container best practices for .NET 8.0
5. **cicd-pipelines.md**: GitHub Actions templates and patterns
6. **security-checklist.md**: Security requirements for APIs
7. **templates/**: Reusable code and configuration templates

## Key Principles

1. **Never Assume Context**: Always read project documentation first
2. **Test-First**: Plan tests before implementation
3. **Explicit Commands**: Use exact commands with project-specific libraries
4. **Clear Success Criteria**: Define measurable success for each step
5. **Reference Project Docs**: Link to CLAUDE.md, docs/, .claude-docs/
6. **Follow Project Standards**: Respect .NET version policy, typing rules, response protocol
7. **No Placeholders**: Provide complete, working code
8. **Security by Default**: Include security considerations in every plan
9. **Idempotent Operations**: Ensure operations can be safely repeated
10. **Document Everything**: Update docs and notify stakeholders

## Example Usage

**User**: "Plan a new feature to add user authentication with JWT tokens"

**Claude with Skill**:
1. Reads CLAUDE.md, ARCHITECTURE.md, current codebase
2. Identifies current state (no auth implemented)
3. Plans unit tests for token generation/validation
4. Plans integration tests for protected endpoints
5. Creates step-by-step implementation:
   - Add JWT NuGet packages
   - Create JwtService
   - Add authentication middleware to Program.cs
   - Create LoginCommand with validator
   - Update OpenAPI spec with Bearer scheme
   - Add [Authorize] attributes to protected commands/queries
   - Create Dockerfile with secret management
   - Update GitHub Actions to test auth flows
6. Includes security checklist
7. Plans monitoring for failed auth attempts
8. Provides rollback plan

## Skill Activation

When this skill is activated, Claude will:
1. Immediately read project documentation
2. Ask clarifying questions about requirements
3. Create a comprehensive plan following the methodology above
4. Present the plan for user approval before execution
5. Track progress using todo lists
6. Verify success criteria after each step

## Notes

- This skill is for **planning**, not execution (unless user approves)
- Always use the project's actual file paths, packages, and patterns
- Respect the project's .NET 8.0 LTS policy
- Follow strict typing rules and response protocol
- Reference templates but customize for specific needs
- Keep plans detailed but concise
- Include verification steps throughout
