TDD Implementer
Goal: Implement features using TDD cycle: RED (write tests) → GREEN (minimal code) → REFACTOR (clean up)
Description
Implements features following Test-Driven Development methodology. Verifies acceptance tests fail (RED), writes minimal code to pass tests (GREEN), then refactors for quality (REFACTOR). Follows secure coding patterns and commits atomically at each phase.
Usage
- •"Implement feature using TDD"
- •"Write code for these tests"
- •"RED-GREEN-REFACTOR cycle for [feature]"
When to Use
- •After acceptance-test-generator creates BDD tests
- •Implementing new features or components
- •Need to ensure test coverage from the start
Pipeline Contract (sdlc-tdd-full.lobster)
Inputs:
- •
test_files(JSON array): Test files from acceptance-test-generator - •
stories(JSON array): User stories for context - •
workspace(string): Path to workspace
Output: JSON with structure:
{
"status": "success",
"implementation_files": [
"/opt/nexus/v2/api/endpoints/profile.py",
"/opt/nexus/v2/api/models/profile.py",
"/opt/nexus/v2/tests/test_profile_endpoint.py"
],
"test_results": {
"acceptance": {"passed": 3, "failed": 0, "total": 3},
"unit": {"passed": 12, "failed": 0, "total": 12}
},
"tdd_phases": {
"red": "completed",
"green": "completed",
"refactor": "completed"
},
"coverage_percent": 82,
"commits": [
{"sha": "abc123", "message": "test: add acceptance tests for profile API"},
{"sha": "def456", "message": "feat(api): implement profile endpoint"},
{"sha": "ghi789", "message": "refactor(api): simplify profile logic"}
]
}
Implementation
Execute in order. Do not run Lobster or any pipeline. Follow TDD cycle strictly.
Phase 1: RED - Verify Acceptance Tests Fail
Step 1.1: Run Acceptance Tests
- •Navigate to workspace
- •Run acceptance tests (pytest features/ or npm test features/)
- •Verify tests FAIL as expected (no implementation yet)
- •Capture failure messages to understand requirements
Step 1.2: Analyze Test Failures
- •From failures, identify needed components (e.g., ProfileEndpoint, ProfileService, Database model)
- •Create implementation plan: which files/classes/functions needed
- •Note dependencies between components
Step 1.3: Write Unit Tests for Components
- •For each component identified, write unit tests
- •Example: If acceptance test needs ProfileEndpoint, write tests/test_profile_endpoint.py
- •Cover happy path + edge cases (auth failures, missing data, validation errors)
- •Run unit tests → expect failures (RED state for unit tests)
Example unit test:
# tests/test_profile_endpoint.py
import pytest
from api.endpoints.profile import get_profile
def test_get_profile_authenticated_user(test_client, auth_token):
"""Test authenticated user can retrieve their profile"""
response = test_client.get(
'/api/v1/profile',
headers={'Authorization': f'Bearer {auth_token}'}
)
assert response.status_code == 200
assert 'user_id' in response.json
assert 'email' in response.json
def test_get_profile_unauthenticated():
"""Test unauthenticated user receives 401"""
response = test_client.get('/api/v1/profile')
assert response.status_code == 401
Phase 2: GREEN - Write Minimal Implementation
Step 2.1: Implement Components (YAGNI)
- •Write ONLY what's needed to pass tests
- •No premature optimization
- •No extra features not in acceptance criteria
- •Use simple, straightforward solutions
Example implementation:
# api/endpoints/profile.py
from flask import g, jsonify
from .auth import require_auth
@require_auth
def get_profile():
"""Retrieve authenticated user's profile"""
user_id = g.user_id
profile = db.get_user(user_id)
if not profile:
return jsonify({"error": "Profile not found"}), 404
return jsonify({
"user_id": profile.id,
"name": profile.name,
"email": profile.email,
"avatar_url": profile.avatar_url
}), 200
Step 2.2: Follow Secure Coding Patterns Follow patterns from docs/SECURITY-HARDENING-AGENTIC.md:
- •
SQL Injection: Use parameterized queries (never f-strings in SQL)
python# ❌ VULNERABLE db.execute(f"SELECT * FROM users WHERE id={user_id}") # ✅ SECURE db.execute("SELECT * FROM users WHERE id=?", (user_id,)) - •
XSS: Sanitize user input before rendering
pythonfrom markupsafe import escape return jsonify({"name": escape(user_input)}) - •
Broken Auth: Use decorators, check ownership
python@require_auth def update_profile(user_id): if g.user_id != user_id: return jsonify({"error": "Forbidden"}), 403 - •
Secrets: Use environment variables
pythonimport os JWT_SECRET = os.getenv("JWT_SECRET") # ✅ JWT_SECRET = "hardcoded-secret-123" # ❌ - •
Command Injection: Avoid shell=True, validate inputs
python# ❌ VULNERABLE subprocess.run(f"convert {user_file}", shell=True) # ✅ SECURE subprocess.run(["convert", user_file], shell=False)
Step 2.3: Run Unit Tests
- •Run unit tests → fix until all GREEN
- •Iterate: write code → run tests → fix failures → repeat
Step 2.4: Run Acceptance Tests
- •Run acceptance tests → should now PASS
- •If failures remain, debug and fix implementation
- •Verify all scenarios pass
Step 2.5: Check Test Coverage
- •Run coverage tool (pytest --cov or npm test --coverage)
- •Target: ≥70% line coverage
- •Identify uncovered branches, add tests if critical
Phase 3: REFACTOR - Clean Up Code
Step 3.1: Remove Duplication (DRY)
- •Look for repeated code blocks
- •Extract into helper functions
- •Create shared utilities for common patterns
Step 3.2: Improve Naming
- •Rename unclear variables (e.g.,
d→user_data) - •Use descriptive function names (e.g.,
get→fetch_user_profile) - •Follow language conventions (snake_case for Python, camelCase for JS)
Step 3.3: Simplify Complex Logic
- •Break long functions into smaller ones
- •Reduce nesting (early returns, guard clauses)
- •Replace complex conditionals with helper functions
Step 3.4: Add Docstrings
- •Add docstrings to public functions
- •Include: purpose, parameters, return type, exceptions
- •Example:
python
def get_profile(user_id: int) -> dict: """ Retrieve user profile by ID. Args: user_id: The user's unique identifier Returns: dict: Profile data (user_id, name, email, avatar_url) Raises: NotFoundError: If user does not exist UnauthorizedError: If user is not authenticated """
Step 3.5: Verify Tests Still Pass
- •After EACH refactor, re-run all tests
- •Tests must stay GREEN throughout refactoring
- •If tests fail, revert refactor and try different approach
Phase 4: Commit Changes
Create atomic commits at each TDD phase:
Commit 1 - RED Phase:
git add features/ tests/ git commit -m "test: add acceptance tests for profile API - Add feature file for profile retrieval scenarios - Add step definitions for API requests - Add unit tests for ProfileEndpoint Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>"
Commit 2 - GREEN Phase:
git add api/endpoints/profile.py api/models/ api/routes.py git commit -m "feat(api): implement profile endpoint - Add GET /api/v1/profile endpoint - Add ProfileEndpoint class with authentication - Add database query for user profile - All acceptance tests passing Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>"
Commit 3 - REFACTOR Phase:
git add api/endpoints/profile.py api/utils/ git commit -m "refactor(api): simplify profile logic - Extract profile serialization to utility function - Improve error handling with custom exceptions - Add docstrings to public functions - Reduce cyclomatic complexity from 8 to 4 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>"
Step 5: Output Results
Generate JSON with:
- •implementation_files: List of created/modified files
- •test_results: Acceptance + unit test pass/fail counts
- •tdd_phases: Status of each phase (completed)
- •coverage_percent: Code coverage percentage
- •commits: Array of commit SHAs and messages
Output Format
Markdown summary + JSON block for pipeline consumption:
# TDD Implementation Complete
Feature: **User profile API**
## TDD Cycle
### 🔴 RED Phase
- Acceptance tests: 3 scenarios FAIL ✅
- Unit tests: 12 tests FAIL ✅
- Components identified: ProfileEndpoint, ProfileService, User model
### 🟢 GREEN Phase
- Implementation: api/endpoints/profile.py (85 lines)
- Unit tests: 12/12 PASS ✅
- Acceptance tests: 3/3 PASS ✅
- Coverage: 82% (target: ≥70%)
### 🔵 REFACTOR Phase
- Extracted: profile_serializer utility
- Complexity: Reduced from 8 → 4
- Docstrings: Added to 3 public functions
- Tests: 15/15 PASS ✅ (still green)
## Files Created/Modified
- api/endpoints/profile.py (new)
- api/models/profile.py (new)
- api/routes.py (modified)
- api/utils/serializers.py (new)
- tests/test_profile_endpoint.py (new)
- features/story_001_profile_api.feature (new)
- features/steps/profile_steps.py (new)
## Commits
1. abc123: test: add acceptance tests for profile API
2. def456: feat(api): implement profile endpoint
3. ghi789: refactor(api): simplify profile logic
## Security Checks
✅ No SQL injection (parameterized queries)
✅ No hardcoded secrets (environment variables)
✅ Authentication enforced (@require_auth)
✅ Authorization checks (user ownership)
```json
{
"status": "success",
"implementation_files": [
"/opt/nexus/v2/api/endpoints/profile.py",
"/opt/nexus/v2/api/models/profile.py",
"/opt/nexus/v2/tests/test_profile_endpoint.py"
],
"test_results": {
"acceptance": {"passed": 3, "failed": 0, "total": 3},
"unit": {"passed": 12, "failed": 0, "total": 12}
},
"tdd_phases": {
"red": "completed",
"green": "completed",
"refactor": "completed"
},
"coverage_percent": 82,
"commits": [
{"sha": "abc123", "message": "test: add acceptance tests for profile API"},
{"sha": "def456", "message": "feat(api): implement profile endpoint"},
{"sha": "ghi789", "message": "refactor(api): simplify profile logic"}
]
}
## Notes - ALWAYS verify RED state before implementation (tests must fail first) - GREEN phase: minimal code only (no gold-plating) - REFACTOR phase: tests must stay green after each change - Commit atomically at each phase for clear history - Follow security patterns from docs/SECURITY-HARDENING-AGENTIC.md - Target coverage ≥70% but don't chase 100% (diminishing returns)