Skip to main content

TDDAI (Test-Driven Development AI) - Complete Documentation

🎯 Overview​

TDDAI is a comprehensive AI-Enhanced Test-Driven Development Framework designed for production-ready development with strict quality gates. It's a key component of the LLM Platform ecosystem, providing automated TDD enforcement, project analysis, and seamless integration with Claude Code and other development tools.

Version: 2.2.3 (Production Ready)
Package: @bluefly/tddai
License: MIT
Repository: Part of LLM Platform ecosystem

πŸš€ Quick Start​

Installation​

# Install globally for CLI access
npm install -g @bluefly/tddai

# Complete project setup with Claude Code integration
npx @bluefly/tddai setup-wizard

# Minimal Claude Code integration only
npx @bluefly/tddai claude-setup

First TDD Session​

# Initialize TDD session
/tdd-start

# Enter RED phase (write failing tests)
/tdd-red user-authentication

# Enter GREEN phase (minimal implementation)
/tdd-green user-authentication

# Enter REFACTOR phase (improve code quality)
/tdd-refactor user-authentication

# Check status and metrics
/tdd-status

πŸ—οΈ Architecture​

Core Components​

  1. TDD Workflow Engine: Manages RED-GREEN-REFACTOR cycles
  2. Project Analyzer: Provides 0-100 quality scoring
  3. AI Integration: Automated test generation and implementation
  4. Hook System: Claude Code and Cursor integration
  5. Quality Gates: Coverage, mutation testing, compliance checks
  6. Drupal Ultra-Strict: Custom code vs contrib analysis

Technology Stack​

  • Runtime: Node.js 20+
  • Language: TypeScript (strict mode)
  • CLI Framework: Commander.js
  • Testing: Jest, Vitest, PHPUnit (auto-detected)
  • AI Providers: Ollama (default), OpenAI, Anthropic
  • Vector DB: Qdrant for pattern matching

πŸ“‹ Features​

1. AI-Enhanced TDD Workflow​

Phase Management​

  • RED Phase: Write failing tests only
  • GREEN Phase: Minimal implementation to pass tests
  • REFACTOR Phase: Improve code while keeping tests green

Automatic Enforcement​

  • Prevents implementation during RED phase
  • Warns about test modifications during GREEN phase
  • Ensures tests remain passing during REFACTOR phase

2. Project Quality Assessment​

Scoring System (0-100)​

const qualityFactors = {
testCoverage: 40, // 95% target
testQuality: 20, // Mutation testing
configuration: 15, // Proper configs
dependencies: 15, // Up-to-date, secure
documentation: 10 // README, comments
};

Multi-Language Support​

  • TypeScript/JavaScript: Jest, Vitest, Mocha
  • PHP: PHPUnit, Pest
  • Python: PyTest, unittest
  • Drupal: PHPUnit with Drupal Test Traits

3. AI-Powered Development​

Test Generation​

# Generate tests for untested files
tddai improve generate-tests --coverage 95

# AI-powered test creation
tddai ai generate-test "user authentication with JWT"

# Generate tests for specific file
tddai ai test-file src/auth/AuthService.ts

Implementation Assistance​

# AI implementation from tests
tddai ai implement --test auth.test.ts

# Code completion suggestions
tddai ai complete --context "REST API endpoint"

# Refactoring suggestions
tddai ai refactor --file user.service.ts

4. Drupal Ultra-Strict Mode​

Zero-Tolerance Analysis​

# Ultra-strict module analysis
tddai drupal ultra-strict /path/to/module --zero-tolerance

# Detect unnecessary custom code
tddai drupal detect-custom /path/to/module --show-examples

# Suggest contrib alternatives
tddai drupal suggest-contrib /path/to/module

# Generate proper Drupal plugins
tddai drupal generate-plugins ai_model my_ai_module --full-stack

Custom Code Detection​

  • Identifies reinvented wheels
  • Suggests existing contrib modules
  • Calculates "custom code score"
  • Provides migration paths to contrib

πŸ”§ CLI Commands Reference​

Core Analysis Commands​

# Comprehensive project analysis
tddai analyze --detailed --fix

# Multi-project analysis
tddai improve analyze --all --detailed

# Automatic issue fixing
tddai improve fix --all

# Generate missing tests
tddai improve generate-tests --coverage 90

TDD Workflow Commands​

# Phase management
tddai tdd red [target] # Enter RED phase
tddai tdd green [target] # Enter GREEN phase
tddai tdd refactor [target] # Enter REFACTOR phase
tddai tdd status # Check current phase
tddai tdd validate # Comprehensive validation

AI Commands​

# Test generation
tddai ai generate-test "feature description"
tddai ai test-file path/to/file.ts

# Implementation
tddai ai implement --test test-file.ts
tddai ai complete --context "description"

# Analysis
tddai ai analyze-coverage ./
tddai ai suggest-improvements

Drupal Commands​

# Ultra-strict analysis
tddai drupal ultra-strict /path --zero-tolerance

# Custom code detection
tddai drupal detect-custom /path --score-threshold 50
tddai drupal suggest-contrib /path

# Code generation
tddai drupal generate-plugins entity_type module_name
tddai drupal create-recipe recipe_name --features

Utility Commands​

# Setup and configuration
tddai setup-wizard # Complete setup
tddai claude-setup # Claude Code integration
tddai cursor-setup # Cursor integration

# Quality and reporting
tddai report --format json # Generate quality report
tddai metrics --dashboard # Show metrics dashboard
tddai export --format csv # Export metrics

βš™οΈ Configuration​

Project Configuration (tddai.config.yml)​

# Project settings
project:
type: drupal # drupal, typescript, php, python
language: php # php, typescript, javascript, python
framework: phpunit # phpunit, jest, vitest, pytest

# Testing configuration
testing:
framework: phpunit # Test framework to use
coverageThreshold: 95 # Minimum coverage percentage
timeout: 30000 # Test timeout in milliseconds
mutationThreshold: 80 # Mutation testing threshold

# TDD workflow settings
tdd:
enforceWorkflow: true # Enforce RED-GREEN-REFACTOR
autoWatch: true # Auto-run tests on file changes
requireTestFirst: true # Block implementation without tests
phaseTimeout: 3600 # Phase timeout in seconds

# AI integration
ai:
enabled: true # Enable AI features
provider: ollama # ollama, openai, anthropic
model: llama3.2:7b # Model to use
temperature: 0.3 # Creativity level
maxTokens: 2000 # Response length limit

# Drupal-specific settings
drupal:
ultraStrict:
enabled: true # Enable ultra-strict mode
zeroTolerance: false # Zero tolerance for custom code
customCodeScoreThreshold: 50 # Custom code warning threshold
suggestContrib: true # Suggest contrib alternatives

codeGeneration:
useTraits: true # Use Drupal traits
followStandards: true # Follow Drupal coding standards
generateTests: true # Auto-generate test classes

# Quality gates
quality:
coverage:
minimum: 95 # Minimum code coverage
branches: 90 # Branch coverage minimum
functions: 95 # Function coverage minimum

complexity:
cyclomaticMax: 10 # Max cyclomatic complexity
cognitiveMax: 15 # Max cognitive complexity

dependencies:
checkOutdated: true # Check for outdated packages
checkSecurity: true # Security vulnerability scanning
autoUpdate: false # Auto-update dependencies

# Integration settings
integrations:
claudeCode:
contextInjection: true # Inject TDD context
complianceGuard: true # Prevent TDD violations
slashCommands: true # Enable slash commands

cursor:
enabled: false # Enable Cursor integration
dataSovereignty: true # Data sovereignty features
vectorDb: qdrant # Vector database choice

ci:
preCommitHooks: true # Git pre-commit hooks
qualityGates: true # CI/CD quality gates
reporting: junit # Test report format

Environment Variables​

# Core settings
TDDAI_AI_PROVIDER=ollama
TDDAI_COVERAGE_THRESHOLD=95
TDDAI_STRICT_MODE=true

# AI provider settings
TDDAI_OLLAMA_HOST=localhost:11434
TDDAI_OPENAI_API_KEY=sk-...
TDDAI_ANTHROPIC_API_KEY=sk-ant-...

# Drupal settings
TDDAI_DRUPAL_ULTRA_STRICT=true
TDDAI_DRUPAL_ZERO_TOLERANCE=false

# Database settings
TDDAI_QDRANT_URL=http://localhost:6333
TDDAI_VECTOR_COLLECTION=tddai_patterns

# Development settings
TDDAI_DEBUG=true
TDDAI_LOG_LEVEL=info
TDDAI_CACHE_DIR=~/.tddai/cache

πŸ”— Claude Code Integration​

Automatic Setup​

npx @bluefly/tddai claude-setup

This creates:

.claude/
β”œβ”€β”€ settings.json # Hook configuration
β”œβ”€β”€ hooks/
β”‚ β”œβ”€β”€ tdd-context-injector.js # Adds TDD status to prompts
β”‚ └── tdd-compliance-guardian.js # Prevents TDD violations
└── commands/tdd/
β”œβ”€β”€ start.md, status.md, validate.md
└── red.md, green.md, refactor.md

Available Slash Commands​

CommandDescriptionUsage Example
/tdd-startInitialize TDD session/tdd-start
/tdd-statusShow current metrics/tdd-status
/tdd-validateRun compliance check/tdd-validate
/tdd-red [target]Enter RED phase/tdd-red login-feature
/tdd-green [target]Enter GREEN phase/tdd-green login-feature
/tdd-refactor [target]Enter REFACTOR phase/tdd-refactor login-feature

Hook Behavior​

Context Injection Hook​

Automatically adds to every Claude prompt:

[TDD Status] Phase: RED, Coverage: 85% | [Project Context] 15 files tracked

Compliance Guardian Hook​

Prevents TDD violations:

TDD RED Phase Violation: Cannot modify implementation file 'src/auth.js' during RED phase. Write failing tests first.

🎯 Cursor Integration (Planned)​

Data Sovereignty Features​

  • Local AI processing with Ollama
  • Private vector database (Qdrant)
  • No data sent to external services
  • Configurable AI providers

Setup​

npx @bluefly/tddai cursor-setup --data-sovereignty

Features​

  • TDD workflow enforcement in Cursor
  • Local code analysis and suggestions
  • Private pattern learning
  • Multi-provider AI support

πŸ“Š Quality Metrics​

Project Scoring Algorithm​

const calculateProjectScore = (metrics) => {
const weights = {
coverage: 0.40, // Test coverage percentage
testQuality: 0.20, // Mutation testing score
codeQuality: 0.15, # Linting, complexity
configuration: 0.15, // Proper configs present
documentation: 0.10 // README, comments
};

return Object.entries(weights)
.reduce((score, [metric, weight]) =>
score + (metrics[metric] * weight), 0);
};

Coverage Thresholds​

  • Minimum: 95% line coverage
  • Branch: 90% branch coverage
  • Function: 95% function coverage
  • Mutation: 80% mutation score

Quality Gates​

  1. Test Coverage: Must meet minimum thresholds
  2. TDD Compliance: Must follow RED-GREEN-REFACTOR
  3. Code Quality: Linting and complexity checks
  4. Security: Dependency vulnerability scanning
  5. Documentation: README and code comments

πŸ”§ Development Workflows​

Standard TDD Workflow​

  1. Initialize: /tdd-start in Claude Code
  2. Red Phase: /tdd-red feature-name
    • Write failing tests
    • Guardian prevents implementation edits
  3. Green Phase: /tdd-green feature-name
    • Write minimal implementation
    • Guardian warns about test modifications
  4. Refactor Phase: /tdd-refactor feature-name
    • Improve code quality
    • Ensure tests remain green
  5. Validate: /tdd-status for final metrics

Team Onboarding Workflow​

# Team lead setup (one-time)
cd /team/project
npx @bluefly/tddai setup-wizard
git add .claude/ tddai.config.yml
git commit -m "Setup TDDAI workflow"
git push

# Team member setup (zero configuration)
git clone <team-repo>
npm install -g @bluefly/tddai
# All slash commands now available in Claude Code!

CI/CD Integration​

# .gitlab-ci.yml example
stages:
- quality-check
- test
- build

tdd-validation:
stage: quality-check
script:
- npm install -g @bluefly/tddai
- tddai validate --strict --junit-output
artifacts:
reports:
junit: tddai-report.xml

πŸ› Troubleshooting​

Common Issues​

Hook Not Working​

# Check hook configuration
cat .claude/settings.json

# Verify hook permissions
ls -la .claude/hooks/

# Test hook manually
./.claude/hooks/tdd-context-injector.js '{"event":"UserPromptSubmit","prompt":"test"}'

Coverage Issues​

# Check test framework detection
tddai analyze --debug

# Verify coverage configuration
cat jest.config.js # or phpunit.xml

# Run coverage manually
npm test -- --coverage

AI Provider Issues​

# Test Ollama connection
curl http://localhost:11434/api/version

# Check AI configuration
tddai config --show-ai

# Test AI functionality
tddai ai generate-test "simple test" --debug

Performance Optimization​

Cache Management​

# Clear caches
tddai cache clear

# Show cache stats
tddai cache stats

# Optimize cache
tddai cache optimize

Large Projects​

# Incremental analysis
tddai analyze --incremental

# Parallel processing
tddai analyze --parallel 4

# Exclude directories
tddai analyze --exclude node_modules,vendor

πŸ”’ Security​

Data Protection​

  • Local AI processing by default (Ollama)
  • No code sent to external services without explicit consent
  • Configurable AI providers with privacy controls
  • Vector embeddings stored locally (Qdrant)

Audit Trail​

  • All TDD phase changes logged
  • Quality metrics tracked over time
  • Hook executions recorded
  • CI/CD integration events

πŸ“ˆ Advanced Features​

Custom Hooks​

// .claude/hooks/custom-hook.js
const input = JSON.parse(process.argv[2] || '{}');

if (input.event === 'UserPromptSubmit') {
// Add custom context
console.log(JSON.stringify({
continue: true,
context: `[Custom] ${customAnalysis()}`
}));
}

Plugin Development​

# Create TDDAI plugin
tddai create-plugin my-plugin --template typescript

# Install plugin
tddai plugin install ./my-plugin

# List plugins
tddai plugin list

Vector Database Integration​

// Pattern learning from codebase
const patterns = await qdrant.search({
collection: 'tddai_patterns',
vector: embedCode(currentCode),
limit: 5
});

πŸš€ Roadmap​

Version 2.3 (Q1 2025)​

  • Cursor agent integration
  • Enhanced data sovereignty
  • Multi-provider AI support
  • Advanced vector pattern matching

Version 2.4 (Q2 2025)​

  • VS Code extension
  • JetBrains plugin
  • Enhanced Drupal ultra-strict mode
  • Team collaboration features

Version 3.0 (Q3 2025)​

  • Enterprise dashboard
  • Advanced analytics
  • Custom rule engine
  • Multi-language expansion

πŸ“š Resources​

Documentation​

Community​

Support​


TDDAI - Transforming development through AI-enhanced Test-Driven Development
Β© 2024 LLM Platform Team. Licensed under MIT.