spec-kit icon indicating copy to clipboard operation
spec-kit copied to clipboard

Usecase: Clean Architecture + TDD: Lessons Learned Building InsightLoop with AI Assistance

Open thiagobutignon opened this issue 1 year ago โ€ข 10 comments

Overview

This issue documents the journey of building InsightLoop, an AI platform following Clean Architecture principles with strict TDD methodology, and the challenges/solutions when using AI coding assistants (Claude Code, GitHub Copilot).

๐Ÿ—๏ธ Architecture Stack

  • Backend: TypeScript, Express.js, Prisma, PostgreSQL, Keycloak, Redis, MinIO
  • Frontend: React 18+, Shadcn/ui, TailwindCSS
  • MCP: Model Context Protocol servers (TypeScript/Python)
  • Testing: Jest, 100% coverage achieved
  • Methodology: Clean Architecture (Rodrigo Manguinho), TDD

๐Ÿ“š Key Learnings

1. Why AI Assistants Fail at Complex Instructions

Problem: When given comprehensive documents (like our 1000+ line Constitution), AI assistants lose context and violate principles.

Root Cause:

  • Attention dilution across too many rules
  • Context competition between instructions
  • Token distance degradation

Solution: Break down into atomic, sequential tasks

# Instead of: "Implement user registration following Clean Architecture"
# Use: Task-by-task approach
- [ ] T001: Create domain/models/user.ts
- [ ] T002: Add UserModel type
- [ ] T003: Commit "feat(domain): add UserModel"

### 2. TDD Implementation Order (Critical)
**The [@rmanguinho](https://github.com/rmanguinho) Method that ACTUALLY works:**
1. Domain Layer (NO TESTS - just contracts)
   โ””โ”€โ”€ Models & Interfaces
2. Domain Mocks/Spies
3. Data Layer Protocols
4. Data Tests (RED) โ†’ Implementation (GREEN)
5. Infra Tests (RED) โ†’ Implementation (GREEN)  
6. Presentation Tests (RED) โ†’ Implementation (GREEN)
7. Main Layer (composition, NO UNIT TESTS)
8. Integration Tests

## Git Evidence of Compliance:
```bash
72b250f test(data): add DbAddAccount tests - RED phase
32b1da8 feat(data): implement DbAddAccount - GREEN phase

3. Database Migration Timing

Critical Points:

  1. Initial setup (BEFORE any repository tests)
  2. After domain changes
  3. Before integration tests

Common Error: "Table does not exist" - happens when tests run before migrations

4. Progress Tracking is Mandatory

# After EVERY task:
sed -i 's/\[ \] T001/\[x\] T001/' specs/001-feature/tasks.md
git add specs/001-feature/tasks.md
git commit -m "chore: mark T001 complete"

๐Ÿ› ๏ธ Tools & Scripts That Helped

Task Helper Script

#!/bin/bash
# task-helper.sh
grep "^\- \[ \]" specs/*/tasks.md | head -1  # Next task
sed -i "s/\[ \] T001/\[x\] T001/" tasks.md   # Mark complete

Code Review Automation

#!/bin/bash
echo "=== TDD Compliance ==="
git log --oneline | grep -E "(RED|GREEN)" | head -10

echo "=== Coverage ==="
yarn test:coverage | grep "All files"

echo "=== Duplication ==="
npx jscpd src --min-tokens 30

๐Ÿšซ Anti-Patterns to Avoid

โŒ Creating all tests first

# WRONG: Batch test creation
tests/*.spec.ts (all at once)

โŒ Starting from Infrastructure

# WRONG: Bottom-up
1. Setup database
2. Create repositories  
3. Create use cases
4. Create domain (should be FIRST!)

โŒ Skipping RED phase

# WRONG: Test and implementation together
# RIGHT: Test first (must fail), then implement

๐Ÿ“ˆ Results

  • Coverage: 100% achieved
  • Architecture: Clean separation maintained
  • TDD: Full RED-GREEN-REFACTOR compliance
  • Commits: Atomic, traceable history

๐ŸŽ“ Key Takeaways

  1. AI works best with micro-tasks, not macro-instructions
  2. Document decisions locally - AI loses context after compression
  3. Task lists > Comprehensive guides for AI execution
  4. Progress tracking prevents "drift" in long sessions
  5. Mock external dependencies early to avoid test blockage

๐Ÿ“– Resources

Clean Architecture - Rodrigo Manguinho Model Context Protocol Our Constitution v2.1.0

๐Ÿค Contributing Feel free to add your experiences with AI-assisted Clean Architecture development in the comments!

thiagobutignon avatar Sep 12 '25 15:09 thiagobutignon

Setup

Adapt for your own needs.

// memory/constitution.md
# InsightLoop AI Platform Constitution

## Core Principles

### I. Clean Architecture & Domain-Driven Design

Every component follows Clean Architecture principles with clear separation of concerns. Domain logic remains pure and framework-agnostic. Dependencies flow inward: Domain โ†’ Data โ†’ Infrastructure โ†’ Presentation โ†’ Main. No domain code imports infrastructure code. Each bounded context maintains its own domain model. Domain layer contains only types, interfaces, and pure business logic without any external dependencies.

### II. SOLID, DRY, KISS, and YAGNI Principles

**SOLID Principles**: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion applied rigorously across all layers.
**DRY (Don't Repeat Yourself)**: Code duplication is unacceptable. Shared logic must be extracted to utilities, helpers, or base classes. If copying code, stop and refactor. Maximum 3 similar implementations before mandatory abstraction.
**KISS (Keep It Simple, Stupid)**: Simplest solution that works is the correct solution. No clever code. Readable over performant unless performance is proven bottleneck. If explanation takes >2 minutes, it's too complex.
**YAGNI (You Aren't Gonna Need It)**: Build only what's needed NOW. No future-proofing without documented requirement. No generic solutions for single use cases. Delete unused code immediately. Features on-demand, not on-speculation.

### III. Library-First Development

Every feature begins as a standalone, independently deployable library. Libraries must be self-contained with clear interfaces, comprehensive documentation (including llms.txt for AI consumption), and isolated testing. Libraries expose functionality through well-defined contracts: REST APIs, gRPC services, or MCP protocols. No feature bypasses library abstraction to directly access infrastructure.

### IV. Test-First Development (NON-NEGOTIABLE)

Strict TDD enforcement following Rodrigo Manguinho's Clean Architecture methodology. Development must follow this exact sequence:

#### TDD Development Order (MANDATORY):

1. **Domain Layer**:

   - Create models (types/interfaces)
   - Create use case interfaces
   - Commit each file individually
   - NO TESTS for domain (pure contracts)

2. **Domain Mocks & Test Doubles**:

   - Create mock implementations of domain models
   - Create spy implementations of domain use cases
   - Commit mocks/spies

3. **Data Layer Protocols**:

   - Create data/protocols interfaces (e.g., AddAccountRepository, Hasher)
   - These are contracts that data layer needs but don't belong in domain
   - Commit protocols

4. **Data Layer Test (Red Phase)**:

   - Write test file using Spies and Stubs
   - **RUN TEST - MUST FAIL** โŒ
   - Commit failing test

5. **Data Layer Implementation (Green Phase)**:

   - Implement use case classes injecting protocols
   - Use cases know Domain but Domain doesn't know Data
   - **RUN TEST - MUST PASS** โœ…
   - Commit working implementation

6. **Infra Layer Test (Red Phase)** [OPTIONAL]:

   - Only if infrastructure adapter doesn't exist
   - Write failing test for adapter
   - **RUN TEST - MUST FAIL** โŒ
   - Commit failing test

7. **Infra Layer Implementation (Green Phase)** [OPTIONAL]:

   - Implement concrete adapter (e.g., BcryptAdapter implements Hasher)
   - **RUN TEST - MUST PASS** โœ…
   - Commit working adapter

8. **Presentation Layer Test (Red Phase)**:

   - Write controller/handler tests
   - **RUN TEST - MUST FAIL** โŒ
   - Commit failing test

9. **Presentation Layer Implementation (Green Phase)**:

   - Implement controllers/handlers
   - **RUN TEST - MUST PASS** โœ…
   - Commit working controller

10. **Main Layer**:

    - Compose using Factories, Adapters, Middlewares
    - NO unit tests (covered by integration)
    - Commit compositions

11. **Integration Tests**:
    - Test complete flow from routes to database
    - **RUN ALL TESTS - MUST PASS** โœ…
    - Commit integration tests

#### Critical Rules:

- NEVER create all test files first then all production files
- Each layer must be completed (test โ†’ implementation) before moving to next
- Domain Layer has NO tests (pure interfaces/types/models)
- Test Doubles (mocks/stubs/spies) created AFTER domain, BEFORE data layer tests
- Minimum coverage: 80% unit, 70% integration, 100% critical paths

### V. Model Context Protocol Integration

All AI capabilities exposed through standardized MCP servers. TypeScript and Python implementations maintain protocol parity. Resources, Tools, and Prompts clearly defined and versioned. MCP servers follow single-responsibility principle. Transport layer supports both STDIO (local) and HTTP+SSE (remote).

### VI. Observability & Monitoring

Structured logging mandatory (JSON format with correlation IDs). OpenTelemetry for distributed tracing across services. Metrics exposed via Prometheus endpoints. Health checks at /health (liveness) and /ready (readiness). Error tracking with proper context and stack traces.

### VII. Security by Design

Zero-trust architecture with KeyCloak for authentication/authorization. Secrets managed exclusively through Vault Community - no hardcoded credentials. RBAC enforced at API gateway and service levels. Data encryption at rest (PostgreSQL) and in transit (TLS 1.3+). Regular security scanning in CI/CD pipeline.

### VIII. Containerization & Infrastructure as Code

All services containerized with multi-stage Docker builds. Development/production parity through consistent container usage. Infrastructure definitions in docker-compose for local, Kubernetes manifests for production. Makefile as single source of truth for all operations. No manual infrastructure changes - everything through code.

## Technology Standards

### Backend Services (Node.js/TypeScript)

- **Framework**: Express.js with typed middleware chain
- **ORM**: Prisma with migrations tracked in version control
- **Database**: PostgreSQL with pgVector for AI embeddings
- **Cache**: Redis for session management and temporary data
- **Storage**: MinIO for S3-compatible object storage
- **Documentation**: OpenAPI 3.0 via Swagger with auto-generation
- **Testing**: Jest with supertest for API testing
- **Code Quality**: ESLint (airbnb-typescript), Prettier, Husky pre-commit hooks

#### Test Structure (Following Clean Architecture):

tests/ โ”œโ”€โ”€ domain/ # NO TESTS HERE - only interfaces โ”œโ”€โ”€ data/ โ”‚ โ”œโ”€โ”€ mocks/ # Test doubles for domain interfaces โ”‚ โ””โ”€โ”€ usecases/ # Data layer use case tests โ”œโ”€โ”€ infra/ โ”‚ โ”œโ”€โ”€ mocks/ # External service mocks โ”‚ โ””โ”€โ”€ db/ # Repository implementation tests โ”œโ”€โ”€ presentation/ โ”‚ โ”œโ”€โ”€ controllers/ # Controller tests โ”‚ โ””โ”€โ”€ middlewares/ # Middleware tests โ”œโ”€โ”€ main/ # NO UNIT TESTS - only integration โ””โ”€โ”€ integration/ # Full flow tests


#### Test Doubles Patterns:

- **Stub**: Returns fixed values (for simple responses)
- **Spy**: Records calls and returns values (for verification)
- **Mock**: Pre-programmed expectations (for complex scenarios)
- **Fake**: Working implementation for tests (e.g., in-memory DB)

### Frontend Application (React/TypeScript)

- **Framework**: React 18+ with functional components only
- **UI Components**: Shadcn/ui with Tailwind CSS
- **State Management**: React Context + useReducer for complex state
- **Data Fetching**: TanStack Query with proper caching strategies
- **Forms**: React Hook Form with Zod validation
- **Testing**: Jest + React Testing Library
- **Build**: Vite for development, optimized production builds

### MCP Servers

- **TypeScript Server**: Using official @modelcontextprotocol/sdk
- **Python Server**: Using mcp package with FastAPI for HTTP transport
- **Protocol Version**: Latest stable MCP specification
- **Testing**: Integration tests for all exposed tools and resources
- **Python Quality**: Black formatter, pylint, mypy for type checking, pytest

### Infrastructure Requirements

- **Container Registry**: Local registry for development, ECR/GCR for production
- **Orchestration**: Docker Compose for local, Kubernetes for production
- **Service Mesh**: Optional Istio for advanced traffic management
- **Monitoring Stack**: Prometheus + Grafana + Loki
- **CI/CD**: GitHub Actions with matrix testing

## Task Generation Requirements

### Tasks Must Include Test Execution & Progress Tracking

Every implementation must include these task types:

```markdown
## Required Task Types

1. **Implementation Tasks**: Create file with specific content
2. **Test Execution Tasks** (๐Ÿงช): Run tests verifying RED/GREEN state
3. **Progress Update Tasks** (๐Ÿ“): Mark task complete in tasks.md
4. **Commit Tasks** (๐Ÿ’พ): Atomic commits with proper messages
5. **Migration Tasks** (๐Ÿ—„๏ธ): Database schema changes at correct points
6. **Verification Tasks**: Ensure coverage and quality metrics

Task Progress Tracking (MANDATORY)

# After EVERY task completion:
sed -i 's/\[ \] T001/\[x\] T001/' specs/[###-feature]/tasks.md
git add specs/[###-feature]/tasks.md
git commit -m "chore: mark T001 as completed"

Database Migration Points

Migrations MUST occur at these specific points:

  1. Initial Setup: After creating Prisma schema (before any tests)
  2. Schema Changes: After domain changes require new fields/tables
  3. Pre-Integration: Before running integration tests
  4. Pre-Deployment: Final migration check
# Migration sequence:
npx prisma migrate dev --name [description]  # Generate migration
npx prisma migrate deploy                     # Apply migration
npx prisma generate                           # Update client
npm test -- [affected_tests]                 # Verify tests still pass

Development Workflow

TDD Workflow Example (MUST FOLLOW)

For a new feature "Create User", the exact development sequence with commits:

// STEP 1: DOMAIN LAYER (no tests, just contracts)
// domain/models/user.ts
export type UserModel = { id: string; email: string; name: string };
// COMMIT: "feat(domain): add UserModel type"

// domain/usecases/add-account.ts
export interface AddAccount {
  add(account: AddAccountModel): Promise<AccountModel>;
}
// COMMIT: "feat(domain): add AddAccount interface"

// STEP 2: DOMAIN MOCKS
// tests/domain/mocks/mock-account.ts
export const mockAccountModel = (): AccountModel => ({
  id: "valid_id",
  name: "valid_name",
  email: "[email protected]",
});
// COMMIT: "test(domain): add account model mock"

// STEP 3: DATA PROTOCOLS
// data/protocols/criptography/hasher.ts
export interface Hasher {
  hash(value: string): Promise<string>;
}
// COMMIT: "feat(data): add Hasher protocol"

// STEP 4: DATA LAYER TEST (Red)
// tests/data/usecases/db-add-account.spec.ts
describe("DbAddAccount", () => {
  test("Should call Hasher with correct password", async () => {
    const { sut, hasherSpy } = makeSut();
    await sut.add(mockAddAccountModel());
    expect(hasherSpy.value).toBe("valid_password");
  });
});
// RUN: npm test -- --watch db-add-account.spec.ts
// VERIFY: Test FAILS โŒ
// COMMIT: "test(data): add DbAddAccount test - RED phase"

// STEP 5: DATA LAYER IMPLEMENTATION (Green)
// data/usecases/add-account/db-add-account.ts
export class DbAddAccount implements AddAccount {
  constructor(
    private readonly hasher: Hasher,
    private readonly addAccountRepository: AddAccountRepository
  ) {}

  async add(accountData: AddAccountModel): Promise<AccountModel> {
    const hashedPassword = await this.hasher.hash(accountData.password);
    const account = await this.addAccountRepository.add({
      ...accountData,
      password: hashedPassword,
    });
    return account;
  }
}
// RUN: npm test -- --watch db-add-account.spec.ts
// VERIFY: Test PASSES โœ…
// COMMIT: "feat(data): implement DbAddAccount - GREEN phase"

// Continue with INFRA, PRESENTATION, MAIN, INTEGRATION...

Code Simplicity Guidelines (KISS)

  1. Function Complexity: Max 20 lines, cyclomatic complexity < 5
  2. Class Size: Max 200 lines, single responsibility
  3. File Organization: One class/interface per file
  4. Naming: Self-documenting, no comments needed
  5. Nesting: Max 3 levels of indentation

Duplication Detection (DRY)

  1. Check for duplication before commit
npx jscpd src --min-tokens 30

If duplication > 3%: REFACTOR REQUIRED

Feature Justification (YAGNI)

Before adding ANY feature/abstraction, document:

  1. Current Need: What problem exists TODAY?
  2. User Request: Link to issue/ticket
  3. Alternative: Simpler solution considered?
  4. ROI: Implementation time vs value delivered

TDD Git Workflow (MANDATORY)

Each TDD phase requires specific commit patterns for traceability:

Commit Message Format

<type>(<layer>): <description> [- <TDD phase>]

Types: feat, test, refactor, fix, chore
Layers: domain, data, infra, presentation, main, integration
TDD Phases: RED phase, GREEN phase, REFACTOR phase

Required Commits per Layer

  1. Domain Layer: 1 commit per file (no TDD phase)

    • feat(domain): add UserModel type
    • feat(domain): add AddAccount interface
  2. Test Doubles: 1 commit for mocks/spies

    • test(domain): add account mocks and spies
  3. Data Protocols: 1 commit for protocols

    • feat(data): add repository and cryptography protocols
  4. Each Test File: 2-3 commits minimum

    • test(data): add DbAddAccount test - RED phase
    • feat(data): implement DbAddAccount - GREEN phase
    • refactor(data): improve DbAddAccount - REFACTOR phase (optional)
  5. Integration: Final validation

    • test(integration): add signup route tests

Git History Must Show

git log --oneline
# GOOD - Shows TDD flow:
a1b2c3d feat(domain): add UserModel type
d4e5f6g feat(domain): add AddAccount interface
h7i8j9k test(domain): add account mocks and spies
l0m1n2o feat(data): add repository protocols
p3q4r5s test(data): add DbAddAccount test - RED phase
t6u7v8w feat(data): implement DbAddAccount - GREEN phase
x9y0z1a test(infra): add BcryptAdapter test - RED phase
b2c3d4e feat(infra): implement BcryptAdapter - GREEN phase

# BAD - No TDD evidence:
a1b2c3d feat: add user feature
d4e5f6g test: add tests

Code Submission Process

  1. Feature branch from develop following git-flow
  2. Pre-commit hooks run automatically (lint, format, type-check)
  3. All tests must pass locally before push
  4. PR requires: 2 approvals, passing CI, updated documentation
  5. Squash merge to maintain clean history

API Development Standards

  • Version all APIs (v1, v2) with deprecation notices
  • Rate limiting on all public endpoints
  • Request/Response validation with detailed error messages
  • Correlation IDs for request tracing
  • Pagination for list endpoints (cursor-based preferred)

Database Migration Policy

  • All schema changes through Prisma migrations
  • Backward compatible changes only (add columns, never remove in same release)
  • Migration testing required in staging environment
  • Rollback plan documented for each migration
  • Vector indexes optimized for similarity search performance

MCP Server Development

  • Each server focuses on single domain capability
  • Comprehensive tool descriptions for LLM understanding
  • Resource URIs follow consistent naming convention
  • Prompt templates tested with multiple LLM providers
  • Integration tests with actual AI clients

Quality Gates

TDD Anti-Patterns (FORBIDDEN)

These practices violate our TDD principles and will result in PR rejection:

โŒ Over-Engineering Anti-Pattern (Violates KISS & YAGNI)

Adding unnecessary complexity or features:

WRONG:
- Generic repository for single entity
- Abstract factory for 2 implementations
- Strategy pattern for non-changing algorithm
- Microservices for <100 requests/minute
- Event sourcing for CRUD operations

โŒ Code Duplication Anti-Pattern (Violates DRY)

WRONG:
- Same validation in multiple controllers
- Duplicate error handling logic
- Copy-paste test setups
- Repeated database queries

โŒ Test-First Anti-Pattern

Creating all test files first, then all implementation files:

WRONG:
1. Create all *.spec.ts files
2. Create all production *.ts files
3. Make tests pass

โŒ Bottom-Up Anti-Pattern

Starting from infrastructure/database layer:

WRONG:
1. Create database schema
2. Create repositories
3. Create use cases
4. Create domain

โŒ Mock-Everything Anti-Pattern

Over-mocking leading to brittle tests:

WRONG:
- Mocking primitive values
- Mocking DTOs
- Mocking value objects
- Creating mocks before domain interfaces exist

โŒ Integration-Only Anti-Pattern

Skipping unit tests and only writing integration tests:

WRONG:
- No unit tests for use cases
- No unit tests for controllers
- Only testing through HTTP requests

Pre-Deployment Checklist

  • [ ] TDD sequence followed correctly (Domain โ†’ Data โ†’ Infra โ†’ Presentation โ†’ Main)
  • [ ] KISS: No over-engineered solutions (complexity justified?)
  • [ ] YAGNI: No speculative features (all features requested?)
  • [ ] DRY: Code duplication < 3% (jscpd report clean?)
  • [ ] All tests passing (unit, integration, e2e)
  • [ ] Task progress at 100% in tasks.md
  • [ ] Security scan completed (dependencies, containers)
  • [ ] Performance benchmarks within acceptable range
  • [ ] Documentation updated (API, README, CHANGELOG)
  • [ ] Database migrations tested and reversible
  • [ ] MCP server contracts validated
  • [ ] Monitoring dashboards configured

Performance Standards

  • API response time: p95 < 200ms, p99 < 500ms
  • Container startup: < 30 seconds
  • Database queries: Explain plan reviewed for N+1 issues
  • Vector similarity search: < 100ms for 1M embeddings
  • Frontend Core Web Vitals: LCP < 2.5s, FID < 100ms, CLS < 0.1

Security Requirements

  • Dependency updates within 30 days for critical vulnerabilities
  • Penetration testing quarterly
  • OWASP Top 10 compliance verified
  • Secrets rotation every 90 days
  • Audit logs retained for 1 year

CI/CD Task Verification

The CI/CD pipeline MUST verify task progress:

# .github/workflows/task-progress.yml
name: Verify Task Progress
on: [push, pull_request]

jobs:
  verify-progress:
    steps:
      - name: Check task completion
        run: |
          # Count incomplete tasks
          INCOMPLETE=$(grep -c "^\- \[ \]" specs/*/tasks.md || true)
          if [ $INCOMPLETE -gt 0 ]; then
            echo "โŒ Found $INCOMPLETE incomplete tasks"
            echo "All tasks must be marked complete before merge"
            exit 1
          fi

      - name: Verify migration status
        run: |
          npx prisma migrate status
          if [ $? -ne 0 ]; then
            echo "โŒ Pending migrations detected"
            exit 1
          fi

Task Execution Monitoring

Every development session MUST:

  1. Start by reviewing incomplete tasks in tasks.md
  2. Execute tasks in order (no skipping)
  3. Mark each task complete immediately after execution
  4. Commit progress updates at least every 5 tasks
  5. Never leave tasks.md out of sync with actual progress

Progress Verification Commands

# Check incomplete tasks
grep "^\- \[ \]" specs/*/tasks.md | wc -l

# Find last completed task
grep "^\- \[x\]" specs/*/tasks.md | tail -1

# Verify migrations are current
npx prisma migrate status

# Generate progress report
echo "Progress: $(grep -c "^\- \[x\]" tasks.md) / $(grep -c "^\- \[" tasks.md)"

Refactoring Triggers

Mandatory refactoring when:

  • Same code appears 3 times (DRY violation)
  • Function > 20 lines or complexity > 5 (KISS violation)
  • Unused code exists > 1 sprint (YAGNI violation)
  • Test coverage drops below 80%
  • Performance degrades > 20% from baseline

Refactoring Process:

  1. Document current behavior with tests
  2. Refactor in small steps
  3. Run tests after each change
  4. Commit working state frequently
  5. Update documentation

Architectural Decision Records (ADR)

ADR Format

All significant architectural decisions documented in docs/adr/ following:

# ADR-XXX: Title

Status: [Proposed|Accepted|Deprecated|Superseded]
Date: YYYY-MM-DD
Context: Why this decision is needed
Decision: What we're doing
Consequences: Trade-offs and impacts

Review Triggers

  • Introduction of new technology/framework
  • Significant performance optimization
  • Security architecture changes
  • Integration pattern modifications
  • Breaking API changes

Governance

Constitutional Authority

This constitution supersedes all other development practices and guidelines. In case of conflict, constitutional principles take precedence. Teams may add additional constraints but cannot override constitutional requirements.

Amendment Process

  1. Proposed amendments require RFC (Request for Comments) document
  2. Minimum 2-week discussion period with team input
  3. Requires 2/3 majority approval from technical leads
  4. Includes migration plan for existing code
  5. Grace period of 30 days for implementation

Compliance Verification

  • Automated checks in CI/CD pipeline for constitutional compliance
  • Quarterly architecture review against principles
  • Exception requests require written justification and expire after 90 days
  • Non-compliance blocks production deployment

Escalation Path

  1. Team Lead for day-to-day interpretations
  2. Architecture Committee for principle clarifications
  3. CTO for constitutional amendments
  4. External audit annually for compliance verification

Version: 2.1.0 | Ratified: 2025-01-15 | Last Amended: 2025-01-15

Changelog

  • v2.1.0: Added SOLID, DRY, KISS, YAGNI principles with enforcement rules
  • v2.0.0: Complete rewrite with TDD methodology, task tracking, and migration points
  • v1.3.0: Added mandatory task progress tracking and database migration timing
  • v1.2.0: Added precise TDD workflow with commits and test execution requirements
  • v1.1.0: Corrected TDD order following Manguinho's methodology
  • v1.0.0: Initial constitution

This constitution is a living document. Regular reviews ensure it evolves with our technical needs while maintaining core architectural integrity. For implementation guidance, refer to /docs/guides/constitutional-compliance.md.

TDD methodology based on Clean Architecture principles by Rodrigo Manguinho. Reference implementations available at github.com/rmanguinho/clean-ts-api.

thiagobutignon avatar Sep 12 '25 15:09 thiagobutignon

MCP's

You should install some MCP's servers for example:

  • Sequential Thinking
  • Context7 (This is helpful during the Research phase)
  • MCP Fetch (This is helpful during the Research phase)
  • Serena

templates/agent-file-template.ts

[PROJECT NAME] Development Guidelines

Auto-generated from all feature plans. Last updated: [DATE]

CRITICAL: ULTRA THINK Mode Required

MANDATORY: ALWAYS use the ULTRA THINK mode for:

  • Complex problem solving and planning
  • Architecture decisions
  • Code review and analysis
  • Debugging complex issues
  • Multi-step task implementation

Use the command: mcp__sequential-thinking__sequentialthinking to engage deep thinking before critical decisions.

Available MCP Servers

Your environment includes the following MCP (Model Context Protocol) servers:

1. fetch - Internet Access

  • mcp__fetch__fetch - Fetch URLs and extract content as markdown
  • Use for documentation, API references, and web resources

2. playwright - Browser Automation

  • mcp__playwright__browser_* - Full browser control
  • Navigate, click, fill forms, take screenshots
  • Test user interfaces and web applications

3. context7 - Library Documentation

  • mcp__context7__resolve-library-id - Find library IDs
  • mcp__context7__get-library-docs - Get up-to-date documentation
  • Essential for working with external libraries

4. sequential-thinking - Deep Analysis

  • mcp__sequential-thinking__sequentialthinking - ULTRA THINK mode
  • Use for complex problem solving and planning
  • Chain multiple thoughts for thorough analysis

5. serena - Code Intelligence

  • mcp__serena__list_dir - List directory contents
  • mcp__serena__find_file - Find files by pattern
  • mcp__serena__search_for_pattern - Search code patterns
  • mcp__serena__get_symbols_overview - Understand code structure
  • mcp__serena__find_symbol - Find specific code symbols
  • mcp__serena__find_referencing_symbols - Find references
  • mcp__serena__replace_symbol_body - Replace code symbols
  • mcp__serena__insert_*_symbol - Insert code before/after symbols
  • mcp__serena__*_memory - Project memory management
  • mcp__serena__think_about_* - Reflection tools
  • mcp__serena__onboarding - Project onboarding

MCP Usage Guidelines:

  1. Prefer MCP tools over basic commands when available
  2. Use context7 for library documentation instead of guessing
  3. Use serena for code navigation instead of grep/find
  4. Use sequential-thinking for planning and complex decisions
  5. Use playwright for UI testing and web scraping

CRITICAL: Task Execution Rules

MANDATORY: When implementing features:

  1. ALWAYS use ULTRA THINK before starting implementation
  2. ALWAYS follow tasks.md file task-by-task in EXACT order
  3. NEVER skip tasks or implement multiple tasks without marking previous ones complete
  4. ALWAYS update tasks.md marking [x] after EACH task completion
  5. ALWAYS run specified tests/commands exactly as written in tasks
  6. NEVER proceed to next task if current task fails
  7. ALWAYS commit when task specifies to commit

TASK TRACKING:

  • Use mcp__sequential-thinking__sequentialthinking before each major task
  • After EVERY task: Update tasks.md immediately
  • Use TodoWrite tool to track current progress
  • Never batch multiple task implementations

Active Technologies

[EXTRACTED FROM ALL PLAN.MD FILES]

Project Structure

[ACTUAL STRUCTURE FROM PLANS]

Commands

[ONLY COMMANDS FOR ACTIVE TECHNOLOGIES]

Code Style

[LANGUAGE-SPECIFIC, ONLY FOR LANGUAGES IN USE]

Testing Strategy

  • ALWAYS use TDD (Test-Driven Development)
  • Write tests BEFORE implementation
  • Use MCP servers for intelligent test generation
  • Target 100% coverage for critical paths
  • Mock all external dependencies

Security Guidelines

  • No hardcoded credentials (use environment variables)
  • No eval() or dynamic code execution
  • Input validation on all user inputs
  • Use MCP tools to scan for vulnerabilities
  • Follow OWASP best practices

Performance Optimization

  • Use mcp__sequential-thinking__sequentialthinking to analyze performance
  • Profile before optimizing
  • Consider caching strategies
  • Lazy loading for heavy resources
  • Code splitting for large applications

Recent Changes

[LAST 3 FEATURES AND WHAT THEY ADDED]

thiagobutignon avatar Sep 12 '25 15:09 thiagobutignon

Plan

templates/plan-template.md

Implementation Plan: [FEATURE]

Branch: [###-feature-name] | Date: [DATE] | Spec: [link] Input: Feature specification from /specs/[###-feature-name]/spec.md

Execution Flow (/plan command scope)

1. Load feature spec from Input path
   โ†’ If not found: ERROR "No feature spec at {path}"
2. Fill Technical Context (scan for NEEDS CLARIFICATION)
   โ†’ Verify Clean Architecture compliance
   โ†’ Set Structure Decision (always Clean Architecture)
3. Evaluate Constitution Check section below
   โ†’ Verify TDD workflow compliance
   โ†’ Check task progress tracking requirements
   โ†’ Update Progress Tracking: Initial Constitution Check
4. Execute Phase 0 โ†’ research.md
   โ†’ If NEEDS CLARIFICATION remain: ERROR "Resolve unknowns"
5. Execute Phase 1 โ†’ contracts, data-model.md, quickstart.md, CLAUDE.md
6. Re-evaluate Constitution Check section
   โ†’ If TDD violations: ERROR "Must follow Manguinho methodology"
   โ†’ Update Progress Tracking: Post-Design Constitution Check
7. Plan Phase 2 โ†’ Describe TDD task generation approach
8. STOP - Ready for /tasks command

Summary

[Extract from feature spec: primary requirement + Clean Architecture approach]

Technical Context (Clean Architecture Stack)

Backend:

  • Language: TypeScript 5.x / Node.js 22.x
  • Framework: Express.js (presentation layer only)
  • ORM: Prisma (infra layer only)
  • Database: PostgreSQL 17+ with pgVector
  • Cache: Redis (infra layer)
  • Storage: MinIO (infra layer)
  • Auth: KeyCloak (infra layer)
  • Secrets: Vault Community (infra layer)
  • Documentation: Swagger/OpenAPI 3.0

Frontend:

  • Framework: React 18+ (functional components) with NextJS 15+
  • UI: Shadcn/ui + Tailwind CSS
  • State: React Hooks + Context
  • Forms: React Hook Form + Zod
  • Data: TanStack Query

MCP Servers:

  • TypeScript: @modelcontextprotocol/sdk 1.18+
  • Python: fastmcp 2.12+ + FastAPI

Testing:

  • Backend: Jest + Supertest
  • Frontend: Jest + React Testing Library
  • MCP: Integration tests for tools/resources

Infrastructure:

  • Containers: Docker (multi-stage builds)
  • Orchestration: docker-compose (dev) / K8s (prod)
  • Build: Makefile
  • CI/CD: GitHub Actions

Project Type: web (backend + frontend + mcp) Performance Goals: p95 < 200ms, p99 < 500ms Scale: 10k concurrent users

Constitution Check v1.3.0

GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.

Clean Architecture Compliance:

  • Domain layer pure? (no framework dependencies)
  • Data layer protocols defined? (interfaces only)
  • Infra implements protocols? (concrete adapters)
  • Presentation uses domain interfaces? (no direct infra)
  • Main layer composition only? (factories, no logic)

TDD Methodology (Manguinho):

  • Domain โ†’ Mocks โ†’ Protocols โ†’ Test(RED) โ†’ Impl(GREEN)?
  • Each phase has progress tracking tasks?
  • Database migrations at correct points?
  • Test execution tasks included?
  • Commits follow feat/test pattern?

Task Generation Requirements:

  • Every task has progress update (๐Ÿ“)?
  • Test execution tasks (๐Ÿงช) present?
  • Migration tasks (๐Ÿ—„๏ธ) at right time?
  • Commit tasks (๐Ÿ’พ) after each phase?
  • No batch tasks or missing steps?

Testing Order:

  • Domain (no tests, only contracts)
  • Data tests BEFORE implementation
  • Infra tests BEFORE implementation
  • Presentation tests BEFORE implementation
  • Integration tests LAST

Observability:

  • Structured JSON logging?
  • OpenTelemetry tracing?
  • Prometheus metrics?
  • Health endpoints?

Project Structure (Clean Architecture)

Documentation (this feature)

specs/[###-feature]/
โ”œโ”€โ”€ plan.md              # This file (/plan command output)
โ”œโ”€โ”€ research.md          # Phase 0 output
โ”œโ”€โ”€ data-model.md        # Phase 1 output
โ”œโ”€โ”€ quickstart.md        # Phase 1 output
โ”œโ”€โ”€ contracts/           # Phase 1 output
โ”‚   โ”œโ”€โ”€ openapi.yaml    # REST contracts
โ”‚   โ””โ”€โ”€ graphql.schema  # If GraphQL used
โ”œโ”€โ”€ tasks.md            # Phase 2 output (/tasks command)
โ””โ”€โ”€ progress-report.md  # Ongoing progress tracking

Backend Structure (Clean Architecture)

backend/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ domain/           # Enterprise Business Rules
โ”‚   โ”‚   โ”œโ”€โ”€ models/       # Entities (types/interfaces)
โ”‚   โ”‚   โ”œโ”€โ”€ usecases/     # Use case interfaces
โ”‚   โ”‚   โ””โ”€โ”€ errors/       # Domain errors
โ”‚   โ”‚
โ”‚   โ”œโ”€โ”€ data/             # Application Business Rules
โ”‚   โ”‚   โ”œโ”€โ”€ protocols/    # Data layer interfaces
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ db/      # Repository interfaces
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ cache/   # Cache interfaces
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ criptography/ # Crypto interfaces
โ”‚   โ”‚   โ””โ”€โ”€ usecases/     # Use case implementations
โ”‚   โ”‚
โ”‚   โ”œโ”€โ”€ infra/            # Frameworks & Drivers
โ”‚   โ”‚   โ”œโ”€โ”€ db/          # Prisma repositories
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ prisma/
โ”‚   โ”‚   โ”œโ”€โ”€ cache/       # Redis adapters
โ”‚   โ”‚   โ”œโ”€โ”€ criptography/# Bcrypt, JWT adapters
โ”‚   โ”‚   โ”œโ”€โ”€ storage/     # MinIO adapters
โ”‚   โ”‚   โ”œโ”€โ”€ auth/        # KeyCloak adapters
โ”‚   โ”‚   โ””โ”€โ”€ vault/       # Vault adapters
โ”‚   โ”‚
โ”‚   โ”œโ”€โ”€ presentation/     # Interface Adapters
โ”‚   โ”‚   โ”œโ”€โ”€ controllers/  # HTTP controllers
โ”‚   โ”‚   โ”œโ”€โ”€ middlewares/  # Express middlewares
โ”‚   โ”‚   โ”œโ”€โ”€ validators/   # Request validation
โ”‚   โ”‚   โ””โ”€โ”€ helpers/      # HTTP helpers
โ”‚   โ”‚
โ”‚   โ””โ”€โ”€ main/             # Composition Root
โ”‚       โ”œโ”€โ”€ config/       # App configuration
โ”‚       โ”œโ”€โ”€ factories/    # Dependency injection
โ”‚       โ”‚   โ”œโ”€โ”€ usecases/
โ”‚       โ”‚   โ”œโ”€โ”€ controllers/
โ”‚       โ”‚   โ””โ”€โ”€ middlewares/
โ”‚       โ”œโ”€โ”€ routes/       # Route definitions
โ”‚       โ”œโ”€โ”€ adapters/     # Route adapters
โ”‚       โ””โ”€โ”€ server.ts     # Entry point
โ”‚
โ”œโ”€โ”€ tests/
โ”‚   โ”œโ”€โ”€ domain/
โ”‚   โ”‚   โ””โ”€โ”€ mocks/       # Domain mocks/spies
โ”‚   โ”œโ”€โ”€ data/
โ”‚   โ”‚   โ”œโ”€โ”€ mocks/       # Protocol mocks/spies
โ”‚   โ”‚   โ””โ”€โ”€ usecases/    # Use case tests
โ”‚   โ”œโ”€โ”€ infra/
โ”‚   โ”‚   โ”œโ”€โ”€ mocks/       # External service mocks
โ”‚   โ”‚   โ””โ”€โ”€ db/          # Repository tests
โ”‚   โ”œโ”€โ”€ presentation/
โ”‚   โ”‚   โ”œโ”€โ”€ mocks/       # Controller mocks
โ”‚   โ”‚   โ””โ”€โ”€ controllers/ # Controller tests
โ”‚   โ”œโ”€โ”€ main/            # NO UNIT TESTS
โ”‚   โ””โ”€โ”€ integration/     # Full flow tests
โ”‚
โ”œโ”€โ”€ prisma/
โ”‚   โ”œโ”€โ”€ schema.prisma    # Database schema
โ”‚   โ””โ”€โ”€ migrations/      # Migration files
โ”‚
โ””โ”€โ”€ package.json

Frontend Structure

frontend/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ domain/          # Business logic
โ”‚   โ”œโ”€โ”€ data/            # Data layer
โ”‚   โ”œโ”€โ”€ infra/           # External services
โ”‚   โ”œโ”€โ”€ presentation/    # UI components
โ”‚   โ”‚   โ”œโ”€โ”€ components/
โ”‚   โ”‚   โ”œโ”€โ”€ pages/
โ”‚   โ”‚   โ””โ”€โ”€ hooks/
โ”‚   โ””โ”€โ”€ main/            # App bootstrap
โ””โ”€โ”€ tests/

MCP Server Structure

mcp-typescript/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ domain/          # MCP business logic
โ”‚   โ”œโ”€โ”€ tools/           # Tool implementations
โ”‚   โ”œโ”€โ”€ resources/       # Resource providers
โ”‚   โ””โ”€โ”€ server.ts        # MCP server entry
โ””โ”€โ”€ tests/

mcp-python/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ domain/
โ”‚   โ”œโ”€โ”€ tools/
โ”‚   โ”œโ”€โ”€ resources/
โ”‚   โ””โ”€โ”€ server.py
โ””โ”€โ”€ tests/

Structure Decision: Clean Architecture for ALL components

Phase 0: Research & Architecture Validation

  1. Validate Clean Architecture requirements:

    • Domain purity (no external deps)
    • Protocol definitions needed
    • Adapter patterns required
    • Factory patterns for DI
  2. Research tasks for stack:

    - Prisma + pgVector best practices
    - KeyCloak integration patterns
    - MinIO with Node.js setup
    - Vault secrets management
    - MCP server implementation
    
  3. Document in research.md:

    • Architecture decisions (ADRs)
    • Technology choices rationale
    • Performance considerations
    • Security requirements

Output: research.md with Clean Architecture validation

Phase 1: Design & Contracts (Clean Architecture)

  1. Domain Layer Design โ†’ data-model.md:

    • Pure domain models (types)
    • Use case interfaces
    • Domain errors
    • NO implementations
  2. Data Layer Protocols:

    • Repository interfaces
    • External service interfaces
    • Cache interfaces
    • All in data/protocols/
  3. API Contracts โ†’ /contracts/:

    • OpenAPI for REST
    • Input/Output DTOs
    • Error responses
    • Status codes
  4. Database Schema โ†’ prisma/schema.prisma:

    • Entities from domain
    • Relations
    • Indexes for performance
    • Vector fields for AI
  5. MCP Server Contracts:

    • Tools definitions
    • Resources schemas
    • Prompt templates

Output: Complete design following Clean Architecture

Phase 2: TDD Task Generation Approach

Executed by /tasks command

Task Order (MANDATORY):

  1. Project setup + initial migration
  2. Domain layer (models, interfaces)
  3. Domain mocks/spies
  4. Data protocols
  5. Data tests (RED) โ†’ implementation (GREEN)
  6. Check if infra exists, if not:
    • Infra tests (RED) โ†’ implementation (GREEN)
  7. Presentation tests (RED) โ†’ implementation (GREEN)
  8. Main layer composition (no tests)
  9. Integration tests
  10. Final migrations and deployment prep

Task Types Required:

  • Implementation tasks
  • Test execution tasks (๐Ÿงช)
  • Progress tracking tasks (๐Ÿ“)
  • Commit tasks (๐Ÿ’พ)
  • Migration tasks (๐Ÿ—„๏ธ)

Estimated: 100-150 tasks following TDD rigorously

Migration Points (Critical)

  1. Initial Setup (Phase 3.2 in tasks):

    • Create schema from data-model.md
    • Run initial migration
    • Generate Prisma client
  2. After Domain Changes (Phase 3.8 in tasks):

    • If entities modified
    • Generate new migration
    • Update client
  3. Before Integration Tests (Phase 3.15 in tasks):

    • Verify all migrations applied
    • Seed test data
    • Check indexes

Complexity Tracking

Document any Constitution violations

Violation Justification Alternative Rejected
None expected Follow Clean Architecture N/A

Progress Tracking

Updated during execution

Phase Status:

  • [ ] Phase 0: Research complete
  • [ ] Phase 1: Design complete
  • [ ] Phase 2: Task approach defined
  • [ ] Phase 3: Tasks generated (/tasks)
  • [ ] Phase 4: Implementation complete
  • [ ] Phase 5: Validation passed

Constitution Gates:

  • [ ] Clean Architecture verified
  • [ ] TDD methodology confirmed
  • [ ] Task tracking requirements met
  • [ ] Migration points identified

Compliance Checklist:

  • [ ] Domain layer has NO dependencies
  • [ ] All protocols defined before implementation
  • [ ] TDD order will be followed
  • [ ] Progress tracking included
  • [ ] Migrations at correct points

Based on Constitution v1.3.0 - Clean Architecture & TDD Compliant

thiagobutignon avatar Sep 12 '25 15:09 thiagobutignon

This is Gold

chennakrishnaa avatar Sep 12 '25 19:09 chennakrishnaa

Well, after a extensive research and a lot of personal knowledge working in code generation in the last 2 years with ai and without AI. I achieve a very impressive result.


# Phase 2: Domain Layer - [FEATURE NAME]

## ๐Ÿ“– HOW TO READ THIS YAML TEMPLATE

This domain template follows the same YAML structure as the main orchestrator. Each task has complete metadata for intelligent execution by Claude Code.

### ๐ŸŽฏ Key Sections:
1. **PHASE METADATA** - Domain layer identity and dependencies
2. **OBJECTIVES** - What we're trying to achieve
3. **TASKS** - Detailed YAML task definitions with templates, validation, etc.
4. **VALIDATION GATES** - Quality checks before proceeding to Data layer
5. **AUTOMATION HINTS** - How Claude Code should execute these tasks

---

## ๐Ÿ“ TEMPLATE INSTRUCTIONS
**Replace these placeholders with your specific names:**
- `[Feature]` โ†’ Your feature name (e.g., Registration, Survey, Authentication)
- `[Model1]`, `[Model2]` โ†’ Your domain models (e.g., User, Survey, Account)
- `[UseCase1]`, `[UseCase2]` โ†’ Your use case names (e.g., AddSurvey, Authentication)

## ๐Ÿ“‹ PHASE METADATA

```yaml
# ๐ŸŽฏ DOMAIN LAYER IDENTITY - "Pure business logic with zero external dependencies"
phase:
  id: domain-layer
  name: "Domain Layer - Pure Business Logic"
  version: "1.0.0"
  dependencies:
    - phase: setup                                    # Must complete setup first
      status: required
      validation: "Check if src/ and tests/ directories exist"

  # ๐Ÿ“ WHAT THIS PHASE PRODUCES
  outputs:
    - models: "src/domain/models/"                   # TypeScript types for business models
    - usecases: "src/domain/usecases/"              # Interface definitions only
    - index: "src/domain/models/index.ts"           # Export all models

  # ๐Ÿ“Š EFFORT ESTIMATES
  estimated_tasks: 30-50                            # Typical number of tasks
  estimated_loc: 400-600                           # Lines of code expected

  # ๐Ÿ—๏ธ CLEAN ARCHITECTURE PRINCIPLES
  clean_architecture_principles:
    - "100% pure - no external dependencies"        # Zero imports from outside domain
    - "Express business rules clearly"              # Entities have business methods
    - "Use case interfaces only (no implementation)" # Data layer implements these

๐ŸŽฏ PHASE OBJECTIVES

# ๐ŸŽฏ WHAT WE'RE TRYING TO ACHIEVE - "Pure business logic foundation"
objectives:
  - id: research
    description: "Research existing domain and requirements"
    priority: 1                                     # Do this first

  - id: models
    description: "Define TypeScript types for business models"
    priority: 2                                     # Core business types

  - id: usecases
    description: "Define use case INTERFACES (not implementations)"
    priority: 3                                     # Contracts for Data layer

  - id: testing
    description: "Test all business logic with TDD"
    priority: continuous                            # Test everything immediately

PART 0: RESEARCH & ANALYSIS

# ๐Ÿ” RESEARCH TASKS - "Understand the business before coding"
tasks:
  - id: T001
    title: "Extract business rules from spec"
    description: "Analyze requirements to identify business rules"
    type: research
    category: analysis
    tdd_phase: "N/A"
    dependencies: []

    # ๐Ÿ“ฅ INPUTS NEEDED
    inputs:
      - file: "spec.md"                            # Requirements document
        required: true

    # ๐Ÿ“ค OUTPUTS PRODUCED
    outputs:
      - type: documentation
        content: "List of identified business rules"

    # ๐Ÿ”ง COMMANDS TO RUN
    commands:
      - type: bash
        command: 'cat spec.md | grep -E "must|should|cannot|required"'
        description: "Search for business rule indicators"

    # โœ… SUCCESS CRITERIA
    validation:
      - check: "business_rules_documented"
        expected: "Business rules documented"
      - check: "minimum_rules_identified"
        expected: "At least 3 rules identified"

    # โฑ๏ธ TIME ESTIMATES
    estimated_time: 10min
    mcp_servers: []                                 # No special servers needed
    design_patterns: []                             # No patterns applied yet
    status: pending                                 # Not started
    completed_at: null                              # Will be filled when done

  - id: T002
    title: "Identify models from requirements"
    description: "Extract core business models"
    type: research
    category: analysis
    tdd_phase: "N/A"
    dependencies: ["T001"]

    inputs:
      - file: "spec.md"
        required: true

    outputs:
      - type: documentation
        format: markdown
        template: |
          # Models identified:
          - [Model1]: Core business type for [purpose]
          - [Model2]: Represents [what]

          # Fields per model:
          - [Model1]: [field1], [field2]
          - [Model2]: [field1], [field2]

    validation:
      - check: "models_identified"
        expected: "At least 1 model identified"
      - check: "fields_mapped"
        expected: "Fields mapped to models"

    estimated_time: 10min
    mcp_servers: []
    design_patterns: ["TypeScript Types", "Domain Model"]      # Relevant patterns
    status: pending
    completed_at: null

  - id: T003
    title: "Identify value objects needed"
    description: "Determine complex types requiring validation"
    type: research
    category: analysis
    tdd_phase: "N/A"
    dependencies: ["T002"]

    outputs:
      - type: documentation
        format: markdown
        template: |
          # Value Objects needed:
          - [ValueObject1]: [validation rules] (e.g., Email with format validation)
          - [ValueObject2]: [validation rules] (e.g., Password with min length)

    validation:
      - check: "value_objects_identified"
        expected: "Value objects identified with validation rules"

    estimated_time: 5min
    mcp_servers: []
    design_patterns: ["Value Object"]
    status: pending
    completed_at: null

  - id: T004
    title: "Check existing domain structure"
    description: "Verify what already exists to avoid duplication"
    type: research
    category: validation
    tdd_phase: "N/A"
    dependencies: []

    commands:
      - type: bash
        command: "ls -la src/domain/ 2>/dev/null || echo 'Domain not created yet'"
      - type: bash
        command: "find src/domain -name '*.ts' 2>/dev/null | sort"

    validation:
      - check: "existing_code_checked"
        expected: "Existing code checked"
      - check: "no_duplication_planned"
        expected: "No duplication planned"

    estimated_time: 2min
    mcp_servers: []
    status: pending
    completed_at: null

  - id: T005
    title: "Create research summary and plan"
    description: "Document findings and create implementation plan"
    type: documentation
    category: planning
    tdd_phase: "N/A"
    dependencies: ["T001", "T002", "T003", "T004"]

    outputs:
      - file: "docs/domain-analysis.md"
        required: false                              # Optional documentation

    # ๐Ÿ”„ GIT WORKFLOW
    git:
      commit_message: "docs: analyze domain requirements and create plan"
      atomic: true                                   # Single commit

    validation:
      - check: "plan_documented"
        expected: "Plan documented"
      - check: "ready_to_implement"
        expected: "Ready to implement"

    estimated_time: 5min
    status: pending
    completed_at: null

PART 1: DOMAIN MODELS

# ๐Ÿ“Š MODEL TASKS - "TypeScript types for business data"
tasks:
  - id: T011
    title: "Create [Model1] type"
    description: "Define TypeScript type for business model"
    type: implementation
    category: model
    tdd_phase: "RED"
    dependencies: ["T005"]

    inputs:
      - analysis: "T002.outputs"                     # Use research results

    outputs:
      - file: "src/domain/models/[model1].ts"
        type: "typescript"

    # ๐Ÿ“„ CODE TEMPLATE - "What Claude Code should generate"
    template: |
      export type [Model1]Model = {
        id: string
        [field1]: string
        [field2]: number
        [field3]?: string                            # Optional fields with ?
        date: Date
      }

      // For nested types, use type aliases
      type [Model1][SubType]Model = {
        [nestedField]: string
        [anotherField]: boolean
      }

    # โœ… QUALITY CHECKS
    validation:
      - check: "typescript_type_defined"
        expected: "TypeScript type defined"
        description: "Uses export type syntax"
      - check: "no_external_dependencies"
        expected: "No external dependencies"
        description: "Pure TypeScript types"
      - check: "follows_naming_convention"
        expected: "Follows [Model]Model naming"
        description: "Consistent naming pattern"

    # ๐ŸŽจ DESIGN PATTERNS USED
    design_patterns: ["TypeScript Types", "Domain Model"]

    mcp_servers: []
    estimated_time: 5min
    status: pending
    completed_at: null

  - id: T012
    title: "Create mock for [Model1]"
    description: "Create test mock using faker"
    type: implementation                             # Creating mock
    category: mock
    dependencies: ["T011"]                           # Need model first
    tdd_phase: "GREEN"                              # Supporting test infrastructure

    inputs:
      - file: "src/domain/models/[model1].ts"

    outputs:
      - file: "tests/domain/mocks/mock-[model1].ts"
        type: "typescript"

    # ๐Ÿงช MOCK TEMPLATE - Following Manguinho pattern
    template: |
      import { [Model1]Model } from '@/domain/models'
      import faker from 'faker'

      export const mock[Model1]Model = (): [Model1]Model => ({
        id: faker.datatype.uuid(),
        [field1]: faker.random.words(),
        [field2]: faker.datatype.number(),
        [field3]: faker.random.word(),
        date: faker.date.recent()
      })

      export const mock[Model1]Models = (): [Model1]Model[] => [
        mock[Model1]Model(),
        mock[Model1]Model()
      ]

    # ๐Ÿ”ง COMMANDS TO RUN
    commands:
      - type: test
        command: "npx tsc --noEmit tests/domain/mocks/mock-[model1].ts"
        expected_result: "No compilation errors"
        description: "Verify mock compiles"

    validation:
      - check: "mock_compiles"
        command: "npx tsc --noEmit tests/domain/mocks/mock-[model1].ts"
        expected: "No errors"
        description: "TypeScript compilation passes"
      - check: "follows_manguinho_pattern"
        expected: "Follows faker pattern"
        description: "Uses faker for test data generation"

    mcp_servers: []
    estimated_time: 5min
    status: pending
    completed_at: null

  - id: T013
    title: "Commit [Model1] with mock"
    description: "Atomic commit of model and its mock"
    type: git
    category: version-control
    tdd_phase: "N/A"
    dependencies: ["T011", "T012"]

    # ๐Ÿ”„ GIT CONFIGURATION
    git:
      files:
        - "src/domain/models/[model1].ts"
        - "tests/domain/mocks/mock-[model1].ts"
      commit_message: "feat: add [Model1] model with mock"
      atomic: true                                   # Single commit for both files

      # ๐Ÿ” PRE-COMMIT CHECKS
      pre_commit_checks:
        - "npx tsc --noEmit src/domain/models/[model1].ts"     # Model must compile
        - "npx tsc --noEmit tests/domain/mocks/mock-[model1].ts"  # Mock must compile

    validation:
      - check: "clean_commit"
        expected: "Clean commit created"
      - check: "compilation_passes"
        command: "npx tsc --noEmit src/domain/models/[model1].ts"
        expected: "No errors"

    estimated_time: 1min
    status: pending
    completed_at: null

PART 2: USE CASE INTERFACES

# ๐Ÿ“‹ USE CASE INTERFACE TASKS - "Contracts for business operations"
tasks:
  - id: T021
    title: "Define [UseCase1] interface"
    description: "Create use case contract (interface only)"
    type: implementation
    category: usecase
    tdd_phase: "RED"
    dependencies: ["T013"]

    outputs:
      - file: "src/domain/usecases/[use-case-1].ts"
        type: "typescript"

    # ๐Ÿ“„ USE CASE INTERFACE TEMPLATE - Following Manguinho pattern
    template: |
      import { [Model1]Model } from '@/domain/models'

      export interface [UseCase1] {
        [methodName]: (data: [UseCase1].Params) => Promise<[UseCase1].Result>
      }

      export namespace [UseCase1] {
        export type Params = Omit<[Model1]Model, 'id'>
        export type Result = void  // or [Model1]Model | null for queries
      }

    design_patterns: ["Interface", "Namespace Pattern", "Omit Utility Type"]

    validation:
      - check: "interface_only"
        expected: "Interface only (no implementation)"
        description: "Data layer implements this"
      - check: "uses_namespace_pattern"
        expected: "Uses namespace for types"
        description: "Follows Manguinho pattern"
      - check: "imports_domain_models"
        expected: "Imports from @/domain/models"
        description: "References domain types correctly"

    estimated_time: 5min
    status: pending
    completed_at: null

  - id: T022
    title: "Create mock for [UseCase1] params"
    description: "Create test mock for use case parameters"
    type: implementation
    category: mock
    tdd_phase: "GREEN"
    dependencies: ["T021"]

    outputs:
      - file: "tests/domain/mocks/mock-[use-case-1].ts"
        type: "typescript"

    # ๐Ÿ“„ USE CASE MOCK TEMPLATE
    template: |
      import { [UseCase1] } from '@/domain/usecases'
      import faker from 'faker'

      export const mock[UseCase1]Params = (): [UseCase1].Params => ({
        [field1]: faker.random.words(),
        [field2]: faker.datatype.number(),
        [field3]: faker.random.word(),
        date: faker.date.recent()
      })

    validation:
      - check: "mock_compiles"
        command: "npx tsc --noEmit tests/domain/mocks/mock-[use-case-1].ts"
        expected: "No errors"
        description: "TypeScript compilation passes"

    estimated_time: 3min
    status: pending
    completed_at: null

  - id: T023
    title: "Commit [UseCase1] interface with mock"
    description: "Commit use case interface and mock"
    type: git
    category: version-control
    tdd_phase: "N/A"
    dependencies: ["T021", "T022"]

    git:
      files:
        - "src/domain/usecases/[use-case-1].ts"
        - "tests/domain/mocks/mock-[use-case-1].ts"
      commit_message: "feat: add [UseCase1] interface with mock"
      atomic: true

      # ๐Ÿ” PRE-COMMIT CHECKS
      pre_commit_checks:
        - "npx tsc --noEmit src/domain/usecases/[use-case-1].ts"
        - "npx tsc --noEmit tests/domain/mocks/mock-[use-case-1].ts"

    estimated_time: 1min
    status: pending
    completed_at: null

PART 3: MODELS INDEX AND FINAL VALIDATION

# ๐Ÿ“ฆ INDEX AND FINALIZATION TASKS
tasks:
  - id: T031
    title: "Create models index file"
    description: "Export all models from index.ts"
    type: implementation
    category: index
    tdd_phase: "GREEN"
    dependencies: ["T023"]

    outputs:
      - file: "src/domain/models/index.ts"
        type: "typescript"

    # ๐Ÿ“„ INDEX TEMPLATE - Following Manguinho pattern
    template: |
      export * from './[model1]'
      export * from './[model2]'
      // Add more model exports as needed

    validation:
      - check: "exports_all_models"
        expected: "All models exported"
        description: "Index exports all domain models"
      - check: "follows_manguinho_pattern"
        expected: "Follows export * pattern"
        description: "Uses export * from pattern"

    estimated_time: 2min
    status: pending
    completed_at: null

## PART 4: FINAL VALIDATION

```yaml
# โœ… VALIDATION TASKS - "Ensure domain quality"
tasks:
  - id: T041
    title: "Verify domain structure"
    description: "Ensure correct Manguinho-style structure"
    type: validation
    category: quality-check
    dependencies: ["T031"]

    # ๐Ÿ” STRUCTURE CHECKS - Following Manguinho pattern
    commands:
      - type: bash
        command: 'find src/domain -name "*.ts" -exec grep -l "@prisma\|express\|axios\|bcrypt" {} \;'
        expected_result: ""                         # Should find nothing
        description: "Should return nothing - domain must be pure"

      - type: bash
        command: 'ls src/domain/models/index.ts && echo "โœ… Models index exists"'
        expected_result: "โœ… Models index exists"

      - type: bash
        command: 'find src/domain -name "*.ts" -exec grep -l "export type.*Model" {} \; | wc -l'
        expected_result: "> 0"                      # Should have models

    validation:
      - check: "no_external_dependencies"
        expected: "No external dependencies found"
        description: "Domain layer is pure"
      - check: "models_index_exists"
        expected: "Models index exists"
        description: "Following Manguinho pattern"
      - check: "has_typescript_types"
        expected: "Has TypeScript types"
        description: "Uses export type syntax"

    mcp_servers: []
    estimated_time: 3min
    status: pending
    completed_at: null

  - id: T042
    title: "Verify compilation"
    description: "Ensure all TypeScript compiles correctly"
    type: test
    category: compilation
    dependencies: ["T041"]

    commands:
      - type: compilation
        command: "npx tsc --noEmit src/domain/**/*.ts"
        expected_result: "No compilation errors"

      - type: compilation
        command: "npx tsc --noEmit tests/domain/**/*.ts"
        expected_result: "No compilation errors"

    validation:
      - check: "domain_compiles"
        command: "npx tsc --noEmit src/domain/**/*.ts"
        expected: "No errors"
        description: "Domain layer compiles"
      - check: "mocks_compile"
        command: "npx tsc --noEmit tests/domain/**/*.ts"
        expected: "No errors"
        description: "Domain mocks compile"

    mcp_servers: []
    estimated_time: 2min
    status: pending
    completed_at: null

  - id: T043
    title: "Final commit and phase completion"
    description: "Mark domain layer as complete"
    type: git
    category: phase-completion
    dependencies: ["T042"]

    git:
      files:
        - "src/domain/models/index.ts"
      commit_message: "feat: complete domain layer with models index"
      atomic: true

      # ๐Ÿ” PRE-COMMIT CHECKS
      pre_commit_checks:
        - "npx tsc --noEmit src/domain/**/*.ts"      # All must compile
        - "npx tsc --noEmit tests/domain/**/*.ts"    # Mocks must compile

    validation:
      - check: "phase_complete"
        expected: "Domain phase complete"
        description: "Ready for data layer"

    estimated_time: 1min
    status: pending
    completed_at: null

๐Ÿ” VALIDATION GATES

# ๐Ÿšฆ QUALITY GATES - "Must pass before proceeding to Data layer"
validation_gates:
  - id: purity_check
    description: "Domain has no external dependencies"
    command: 'find src/domain -name "*.ts" -exec grep -l "@prisma\|express\|axios\|bcrypt" {} \; | wc -l'
    expected: 0                                     # Zero external dependencies
    critical: true                                  # MUST pass

  - id: typescript_types
    description: "Uses TypeScript types (not classes)"
    command: 'find src/domain/models -name "*.ts" -exec grep -l "export type.*Model" {} \; | wc -l'
    expected: "> 0"                                 # At least some models
    critical: true

  - id: use_case_interfaces
    description: "Use cases are just interfaces"
    command: 'find src/domain/usecases -name "*.ts" -exec grep -l "class.*implements" {} \; | wc -l'
    expected: 0                                     # No implementations
    critical: true

  - id: compilation_check
    description: "All TypeScript compiles without errors"
    command: "npx tsc --noEmit src/domain/**/*.ts"
    expected: "No errors"                           # Must compile
    critical: true

  - id: mocks_compilation
    description: "All mocks compile without errors"
    command: "npx tsc --noEmit tests/domain/**/*.ts"
    expected: "No errors"                           # Mocks must compile
    critical: true

  - id: models_index_exists
    description: "Models index file exists following Manguinho pattern"
    command: 'ls src/domain/models/index.ts'
    expected: "File exists"                         # Index must exist
    critical: true

๐Ÿ“Š SUCCESS METRICS

# ๐Ÿ† SUCCESS CRITERIA - "How to measure domain quality"
success_metrics:
  - metric: "Zero external dependencies"
    measurement: "dependency analysis"
    target: 0

  - metric: "TypeScript types only"
    measurement: "export type count"
    target: "> 0 models defined"

  - metric: "Use case interfaces"
    measurement: "interface count"
    target: "All use cases"

  - metric: "Compilation success"
    measurement: "TypeScript compilation"
    target: "No errors"

  - metric: "Mock compilation"
    measurement: "Test mock compilation"
    target: "No errors"

  - metric: "Manguinho pattern compliance"
    measurement: "structure analysis"
    target: "100% compliance"

๐Ÿ—๏ธ ARCHITECTURE STRUCTURE

# ๐Ÿ“ EXPECTED FILE STRUCTURE - Following Manguinho pattern
architecture:
  src_structure:
    domain:
      models:
        - "[model1].ts # TypeScript type definitions"
        - "[model2].ts # Additional models"
        - "index.ts # Export all models"
      usecases:
        - "[use-case-1].ts # Interface with namespace"
        - "[use-case-2].ts # Interface with namespace"

  test_structure:
    domain:
      mocks:
        - "mock-[model1].ts # Faker-based mocks"
        - "mock-[model2].ts # Additional mocks"
        - "mock-[use-case-1].ts # Use case parameter mocks"

๐Ÿš€ EXECUTION TRACKING

# ๐Ÿ“Š PROGRESS TRACKING - "Real-time status"
tracking:
  total_tasks: 12                                   # Total tasks in this phase
  completed_tasks: 0                                # How many done
  current_task: null                                # Currently executing
  started_at: null                                  # When phase started
  completed_at: null                                # When phase finished
  blockers: []                                      # What's blocking progress
  notes: []                                         # Any important notes
  execution_log: []                                 # History of actions

๐Ÿ’ก AUTOMATION HINTS

# ๐Ÿค– CLAUDE CODE AUTOMATION GUIDANCE
automation:
  claude_code_hints:
    - "Use TodoWrite to track progress automatically"
    - "Execute bash commands in parallel when possible"
    - "Use mcp__serena for code analysis"
    - "Use mcp__sequential-thinking for complex decisions"
    - "Commit atomically after each task group"

  # โšก PARALLEL EXECUTION OPPORTUNITIES
  parallel_execution:
    - ["T001", "T004"]                              # Research can run together
    - ["T011", "T021"]                              # Model and usecase can be parallel

  # ๐Ÿ›ค๏ธ CRITICAL PATH
  critical_path:
    - "T001 โ†’ T002 โ†’ T003 โ†’ T005"                   # Research sequence
    - "T005 โ†’ T011 โ†’ T012 โ†’ T013"                   # First model sequence
    - "T013 โ†’ T021 โ†’ T022 โ†’ T023"                   # Usecase sequence
    - "T023 โ†’ T031 โ†’ T041 โ†’ T042 โ†’ T043"            # Finalization sequence

  # ๐Ÿ”„ ROLLBACK POINTS
  rollback_points:
    - after: "T005"
      description: "Before implementation starts"
    - after: "T013"
      description: "After first model"
    - after: "T023"
      description: "After usecases"
    - after: "T031"
      description: "Before validation"

๐ŸŽ“ SUMMARY: DOMAIN LAYER EXECUTION

๐Ÿ‘ค For Users

  • "Execute domain layer" โ†’ Claude Code handles all tasks
  • "Show domain progress" โ†’ See completion status
  • "Validate domain" โ†’ Run quality gates

๐Ÿค– For Claude Code

  1. Load this template and parse all YAML tasks
  2. Research business requirements first (T001-T005)
  3. Implement entities, value objects, use cases, errors
  4. Test everything with TDD approach
  5. Validate domain purity and quality gates
  6. Track progress using TodoWrite
  7. Commit atomically after each component

๐ŸŽฏ Key Principles

  • Manguinho Pattern - TypeScript types for models, interfaces for use cases
  • Production Code - Write real production code, not examples
  • Compilation First - Ensure code compiles before commit
  • Mocks After Models - Create mocks using faker after each model
  • Pure TypeScript - No external dependencies, only TypeScript types

Remember: Follow Rodrigo Manguinho's clean-ts-api structure exactly. Domain layer is production code that must compile!

thiagobutignon avatar Sep 15 '25 07:09 thiagobutignon

awesome. thank you!

danieldekay avatar Sep 22 '25 16:09 danieldekay

Our Constitution v2.1.0

@thiagobutignon the link in this issue does not work

JaysonAlbert avatar Oct 13 '25 05:10 JaysonAlbert

@JaysonAlbert, from the footnote, I believe this is the constitution:

https://github.com/github/spec-kit/issues/206#issuecomment-3285755837

taqtiqa-mark avatar Oct 16 '25 06:10 taqtiqa-mark

This issue has been automatically marked as stale because it has not had any activity for 150 days. It will be closed in 30 days if no further activity occurs.

github-actions[bot] avatar Apr 03 '26 14:04 github-actions[bot]

This issue has been automatically closed due to inactivity (180 days total). If you believe this issue is still relevant, please reopen it or create a new issue.

github-actions[bot] avatar May 05 '26 00:05 github-actions[bot]