Usecase: Clean Architecture + TDD: Lessons Learned Building InsightLoop with AI Assistance
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:
- Initial setup (BEFORE any repository tests)
- After domain changes
- 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
- AI works best with micro-tasks, not macro-instructions
- Document decisions locally - AI loses context after compression
- Task lists > Comprehensive guides for AI execution
- Progress tracking prevents "drift" in long sessions
- 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!
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:
- Initial Setup: After creating Prisma schema (before any tests)
- Schema Changes: After domain changes require new fields/tables
- Pre-Integration: Before running integration tests
- 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)
- Function Complexity: Max 20 lines, cyclomatic complexity < 5
- Class Size: Max 200 lines, single responsibility
- File Organization: One class/interface per file
- Naming: Self-documenting, no comments needed
- Nesting: Max 3 levels of indentation
Duplication Detection (DRY)
- 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:
- Current Need: What problem exists TODAY?
- User Request: Link to issue/ticket
- Alternative: Simpler solution considered?
- 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
-
Domain Layer: 1 commit per file (no TDD phase)
feat(domain): add UserModel typefeat(domain): add AddAccount interface
-
Test Doubles: 1 commit for mocks/spies
test(domain): add account mocks and spies
-
Data Protocols: 1 commit for protocols
feat(data): add repository and cryptography protocols
-
Each Test File: 2-3 commits minimum
test(data): add DbAddAccount test - RED phasefeat(data): implement DbAddAccount - GREEN phaserefactor(data): improve DbAddAccount - REFACTOR phase(optional)
-
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
- Feature branch from
developfollowing git-flow - Pre-commit hooks run automatically (lint, format, type-check)
- All tests must pass locally before push
- PR requires: 2 approvals, passing CI, updated documentation
- 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:
- Start by reviewing incomplete tasks in tasks.md
- Execute tasks in order (no skipping)
- Mark each task complete immediately after execution
- Commit progress updates at least every 5 tasks
- 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:
- Document current behavior with tests
- Refactor in small steps
- Run tests after each change
- Commit working state frequently
- 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
- Proposed amendments require RFC (Request for Comments) document
- Minimum 2-week discussion period with team input
- Requires 2/3 majority approval from technical leads
- Includes migration plan for existing code
- 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
- Team Lead for day-to-day interpretations
- Architecture Committee for principle clarifications
- CTO for constitutional amendments
- 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.
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 IDsmcp__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 contentsmcp__serena__find_file- Find files by patternmcp__serena__search_for_pattern- Search code patternsmcp__serena__get_symbols_overview- Understand code structuremcp__serena__find_symbol- Find specific code symbolsmcp__serena__find_referencing_symbols- Find referencesmcp__serena__replace_symbol_body- Replace code symbolsmcp__serena__insert_*_symbol- Insert code before/after symbolsmcp__serena__*_memory- Project memory managementmcp__serena__think_about_*- Reflection toolsmcp__serena__onboarding- Project onboarding
MCP Usage Guidelines:
- Prefer MCP tools over basic commands when available
- Use context7 for library documentation instead of guessing
- Use serena for code navigation instead of grep/find
- Use sequential-thinking for planning and complex decisions
- Use playwright for UI testing and web scraping
CRITICAL: Task Execution Rules
MANDATORY: When implementing features:
- ALWAYS use ULTRA THINK before starting implementation
- ALWAYS follow tasks.md file task-by-task in EXACT order
- NEVER skip tasks or implement multiple tasks without marking previous ones complete
- ALWAYS update tasks.md marking [x] after EACH task completion
- ALWAYS run specified tests/commands exactly as written in tasks
- NEVER proceed to next task if current task fails
- ALWAYS commit when task specifies to commit
TASK TRACKING:
- Use
mcp__sequential-thinking__sequentialthinkingbefore 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__sequentialthinkingto 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]
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
-
Validate Clean Architecture requirements:
- Domain purity (no external deps)
- Protocol definitions needed
- Adapter patterns required
- Factory patterns for DI
-
Research tasks for stack:
- Prisma + pgVector best practices - KeyCloak integration patterns - MinIO with Node.js setup - Vault secrets management - MCP server implementation -
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)
-
Domain Layer Design โ
data-model.md:- Pure domain models (types)
- Use case interfaces
- Domain errors
- NO implementations
-
Data Layer Protocols:
- Repository interfaces
- External service interfaces
- Cache interfaces
- All in
data/protocols/
-
API Contracts โ
/contracts/:- OpenAPI for REST
- Input/Output DTOs
- Error responses
- Status codes
-
Database Schema โ
prisma/schema.prisma:- Entities from domain
- Relations
- Indexes for performance
- Vector fields for AI
-
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):
- Project setup + initial migration
- Domain layer (models, interfaces)
- Domain mocks/spies
- Data protocols
- Data tests (RED) โ implementation (GREEN)
- Check if infra exists, if not:
- Infra tests (RED) โ implementation (GREEN)
- Presentation tests (RED) โ implementation (GREEN)
- Main layer composition (no tests)
- Integration tests
- 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)
-
Initial Setup (Phase 3.2 in tasks):
- Create schema from data-model.md
- Run initial migration
- Generate Prisma client
-
After Domain Changes (Phase 3.8 in tasks):
- If entities modified
- Generate new migration
- Update client
-
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
This is Gold
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
- Load this template and parse all YAML tasks
- Research business requirements first (T001-T005)
- Implement entities, value objects, use cases, errors
- Test everything with TDD approach
- Validate domain purity and quality gates
- Track progress using TodoWrite
- 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!
awesome. thank you!
Our Constitution v2.1.0
@thiagobutignon the link in this issue does not work
@JaysonAlbert, from the footnote, I believe this is the constitution:
https://github.com/github/spec-kit/issues/206#issuecomment-3285755837
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.
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.