Files
motovaultpro/AI_IMPLEMENTATION_GUIDE.md
Eric Gullickson 6c64a17e86 Greenfield
2025-08-06 20:59:45 -05:00

1266 lines
46 KiB
Markdown

# MotoVaultPro Greenfield AI-First Implementation Guide
## Executive Summary
This guide provides a comprehensive approach to build MotoVaultPro from the ground up using AI-optimized patterns designed for maximum efficiency in AI-to-AI collaboration and maintenance.
**Project Status**: Greenfield - Building from scratch with AI-first architecture
**Target State**: Self-documenting, progressively discoverable codebase with AI-friendly navigation, context-aware documentation, and feature-based modular architecture optimized for AI development from day one.
**Key Advantage**: No legacy constraints - we can implement the optimal AI structure immediately.
---
## AI-First Project Architecture
### Optimal Directory Structure
```
motovaultpro-v2/
├── AI_README.md # 200-token complete system overview
├── PROJECT_MAP.md # Navigation and quick reference
├── CONVENTIONS.md # Project patterns and standards
├── CLAUDE.md # AI interaction guide (existing)
├── CHANGELOG_AI.md # AI-focused change tracking
├──
├── .ai/ # AI-specific metadata
│ ├── context.json # Context navigation for AI
│ ├── dependencies.yaml # Module dependency graph
│ └── shortcuts.md # Quick command reference
├──
├── backend/
│ ├── src/
│ │ ├── index.ts # Application entry point
│ │ ├── app.ts # Express app configuration
│ │ ├──
│ │ ├── core/ # Stable, critical functionality
│ │ │ ├── config/ # Environment & app configuration
│ │ │ │ ├── database.ts # PostgreSQL connection
│ │ │ │ ├── redis.ts # Redis connection
│ │ │ │ ├── auth0.ts # Auth0 middleware
│ │ │ │ └── minio.ts # MinIO client setup
│ │ │ ├── security/ # Auth and security primitives
│ │ │ │ └── auth.middleware.ts
│ │ │ └── logging/ # Centralized logging
│ │ │ └── logger.ts
│ │ ├──
│ │ ├── features/ # Business logic modules
│ │ │ ├── vehicles/ # Vehicle management feature
│ │ │ │ ├── index.ts # Public API exports
│ │ │ │ ├── vehicle.service.ts # Business logic
│ │ │ │ ├── vehicle.controller.ts # HTTP handlers
│ │ │ │ ├── vehicle.repository.ts # Data access
│ │ │ │ ├── vehicle.types.ts # Type definitions
│ │ │ │ ├── vehicle.validators.ts # Input validation
│ │ │ │ ├── vehicle.routes.ts # Route definitions
│ │ │ │ └── __tests__/ # Feature tests
│ │ │ ├── fuel-logs/ # Fuel tracking feature
│ │ │ │ └── [same structure as vehicles]
│ │ │ ├── maintenance/ # Maintenance tracking feature
│ │ │ │ └── [same structure as vehicles]
│ │ │ └── stations/ # Gas station discovery feature
│ │ │ └── [same structure as vehicles]
│ │ ├──
│ │ ├── shared/ # Reusable utilities
│ │ │ ├── types/ # Shared type definitions
│ │ │ │ ├── common.ts # Common types
│ │ │ │ └── api.ts # API response types
│ │ │ └── utils/ # Pure utility functions
│ │ │ ├── validation.ts
│ │ │ └── formatters.ts
│ │ ├──
│ │ ├── external/ # External API integrations
│ │ │ ├── vpic/ # NHTSA vPIC service
│ │ │ │ ├── vpic.service.ts
│ │ │ │ ├── vpic.types.ts
│ │ │ │ └── __tests__/
│ │ │ └── google-maps/ # Google Maps integration
│ │ │ ├── maps.service.ts
│ │ │ ├── maps.types.ts
│ │ │ └── __tests__/
│ │ └──
│ │ └── database/ # Database layer
│ │ ├── migrations/ # Schema migrations
│ │ │ ├── 001_initial_schema.sql
│ │ │ ├── 002_vin_cache.sql
│ │ │ └── 003_stored_procedures.sql
│ │ └── seeds/ # Test/dev data
│ ├──
│ ├── package.json
│ ├── tsconfig.json
│ ├── Dockerfile
│ └── jest.config.js
├──
├── frontend/
│ ├── src/
│ │ ├── main.tsx # React entry point
│ │ ├── App.tsx # Root component
│ │ ├──
│ │ ├── features/ # Feature-based organization
│ │ │ ├── vehicles/ # Vehicle management UI
│ │ │ │ ├── components/
│ │ │ │ │ ├── VehicleForm/
│ │ │ │ │ ├── VehicleList/
│ │ │ │ │ └── VINDecoder/
│ │ │ │ ├── pages/
│ │ │ │ │ ├── VehiclesPage.tsx
│ │ │ │ │ └── VehicleDetailPage.tsx
│ │ │ │ ├── hooks/
│ │ │ │ │ └── useVehicles.ts
│ │ │ │ ├── api/
│ │ │ │ │ └── vehicles.api.ts
│ │ │ │ └── types/
│ │ │ │ └── vehicle.types.ts
│ │ │ └── [fuel-logs, maintenance, stations with same structure]
│ │ ├──
│ │ ├── shared/ # Shared UI components & utilities
│ │ │ ├── components/ # Reusable UI components
│ │ │ │ ├── common/ # Basic UI elements
│ │ │ │ └── layout/ # Layout components
│ │ │ ├── hooks/ # Shared React hooks
│ │ │ │ ├── useAuth.ts
│ │ │ │ └── useApi.ts
│ │ │ ├── utils/ # Utility functions
│ │ │ └── types/ # Shared TypeScript types
│ │ ├──
│ │ └── core/ # Core application setup
│ │ ├── api/ # API client configuration
│ │ │ └── client.ts # Axios instance
│ │ ├── auth/ # Authentication setup
│ │ │ └── auth0.config.ts
│ │ └── store/ # State management
│ │ └── index.ts # Zustand/Redux store
│ ├──
│ ├── package.json
│ ├── tsconfig.json
│ ├── vite.config.ts
│ ├── Dockerfile
│ └── index.html
├──
├── templates/ # Code generation templates
│ ├── feature/ # Feature module template
│ │ ├── backend/
│ │ │ ├── [feature].service.ts
│ │ │ ├── [feature].controller.ts
│ │ │ ├── [feature].repository.ts
│ │ │ ├── [feature].types.ts
│ │ │ ├── [feature].validators.ts
│ │ │ └── [feature].routes.ts
│ │ └── frontend/
│ │ ├── [Feature]Page.tsx
│ │ ├── [Feature]Form.tsx
│ │ ├── [Feature]List.tsx
│ │ ├── use[Feature].ts
│ │ └── [feature].api.ts
│ ├── external-service/ # External API integration template
│ └── database-migration/ # Database migration template
├──
├── docs/ # Comprehensive documentation
│ ├── ARCHITECTURE.md # System design decisions
│ ├── API.md # API documentation
│ ├── DEPLOYMENT.md # Deployment guide
│ ├── TROUBLESHOOTING.md # Common issues and solutions
│ ├── external-apis/ # External API documentation
│ │ ├── nhtsa-vpic.md
│ │ └── google-maps.md
│ └── diagrams/ # Architecture diagrams
├──
├── k8s/ # Kubernetes configurations
│ └── [existing k8s structure from MOTOVAULTPRO.md]
├──
├── scripts/ # Development & deployment scripts
│ ├── setup.sh # Initial project setup
│ ├── generate-feature.sh # Generate new feature from template
│ └── migrate-db.sh # Database migration runner
├──
├── tests/ # Cross-cutting tests
│ ├── integration/ # API integration tests
│ ├── e2e/ # End-to-end tests
│ └── fixtures/ # Shared test data
├──
├── docker-compose.yml # Local development environment
├── .env.example # Environment variables template
├── Makefile # Common commands
└── README.md # Traditional project documentation
```
---
## Implementation Phases
### Phase 1: Project Foundation Setup (Day 1-2)
**Objective**: Create the complete AI-optimized project structure with foundation files.
#### 1.1 Initialize Project Structure
**Create complete directory tree** (all folders from structure above)
**Initialize package management**:
```bash
# Backend setup
cd backend && npm init -y
npm install express typescript @types/node @types/express
npm install --save-dev jest @types/jest ts-jest nodemon
npm install pg redis ioredis minio axios joi
npm install express-jwt jwks-rsa # Auth0 integration
# Frontend setup
cd ../frontend && npm create vite@latest . -- --template react-ts
npm install @auth0/auth0-react axios zustand
npm install --save-dev @testing-library/react @testing-library/jest-dom vitest
```
#### 1.2 Create Foundation Files
**AI_README.md** (Essential 200-token overview)
```markdown
# MotoVaultPro - AI-First Vehicle Management Platform
## AI Quick Start (50 tokens)
Full-stack vehicle management platform built with React/TypeScript frontend, Node.js/Express backend, PostgreSQL database. Integrates NHTSA vPIC for VIN decoding and Google Maps for fuel station discovery. Features Auth0 authentication, Redis caching, MinIO storage. AI-optimized architecture with feature-based modules.
## Navigation Guide
- Start here: PROJECT_MAP.md
- Conventions: CONVENTIONS.md
- Architecture: docs/ARCHITECTURE.md
- AI Context: .ai/context.json
## Critical Context
- Feature-based architecture: backend/src/features/ & frontend/src/features/
- External APIs: NHTSA vPIC (VIN decode), Google Maps (stations)
- Auth0 handles authentication (JWT tokens)
- All external calls use caching (Redis TTL-based)
- Database migrations in backend/src/database/migrations/
## Primary Entry Points
- Backend: backend/src/index.ts → backend/src/app.ts
- Frontend: frontend/src/main.tsx → frontend/src/App.tsx
- Features: backend/src/features/[feature]/index.ts
- Templates: templates/feature/ for new features
```
**PROJECT_MAP.md** (AI Navigation Guide)
```markdown
# MotoVaultPro AI Navigation Map
## System Overview
AI-first vehicle management platform with React frontend and Node.js backend. Features organized into self-contained modules with clear dependencies. External integrations cached via Redis. PostgreSQL for persistence, MinIO for file storage.
## Quick Navigation by Task
### Adding New Feature
1. **Use template**: `scripts/generate-feature.sh [feature-name]`
2. **Backend path**: `backend/src/features/[feature]/`
3. **Frontend path**: `frontend/src/features/[feature]/`
4. **Update dependencies**: `.ai/dependencies.yaml`
5. **Add tests**: Follow existing `__tests__/` patterns
### Debugging Issues
1. **Check logs**: `backend/src/core/logging/logger.ts` output
2. **API issues**: `backend/src/features/[feature]/[feature].controller.ts`
3. **External APIs**: `backend/src/external/[service]/`
4. **Database**: `backend/src/database/migrations/` for schema
5. **Frontend**: `frontend/src/features/[feature]/components/`
### Modifying External APIs
1. **Service layer**: `backend/src/external/[service]/[service].service.ts`
2. **Cache strategy**: Check TTL settings and invalidation logic
3. **Error handling**: Implement circuit breaker patterns
4. **Rate limiting**: Monitor API usage and implement backoff
5. **Types**: Update `[service].types.ts` for API changes
### Database Changes
1. **New migration**: `backend/src/database/migrations/`
2. **Follow naming**: `001_descriptive_name.sql`
3. **Update models**: `backend/src/features/[feature]/[feature].types.ts`
4. **Test migration**: Up AND down migrations
5. **Update seeds**: `backend/src/database/seeds/` if needed
## Feature Module Map
Each feature follows identical structure:
```
features/[feature]/
├── index.ts # Public API (exports only)
├── [feature].service.ts # Business logic & external calls
├── [feature].controller.ts # HTTP request/response handling
├── [feature].repository.ts # Database operations
├── [feature].types.ts # TypeScript type definitions
├── [feature].validators.ts # Input validation schemas
├── [feature].routes.ts # Express route definitions
└── __tests__/ # Feature-specific tests
├── unit/ # Service & utility tests
├── integration/ # API endpoint tests
└── fixtures/ # Test data
```
## AI Context Loading Guide
### Always Load (Essential Context)
- `AI_README.md` - System understanding
- `CONVENTIONS.md` - Coding standards
- `backend/src/core/` - Core functionality
- `.ai/context.json` - Task-specific routing
### Conditional Loading (Task-Specific)
- **Vehicle operations**: `backend/src/features/vehicles/`, `backend/src/external/vpic/`
- **Fuel tracking**: `backend/src/features/fuel-logs/`
- **Authentication issues**: `backend/src/core/security/`, Auth0 config
- **Database problems**: `backend/src/database/`, core config
- **Frontend bugs**: `frontend/src/features/[relevant-feature]/`
- **External API issues**: `backend/src/external/[service]/`
## Critical Paths (High-Risk Areas)
### Security-Critical
- `backend/src/core/security/auth.middleware.ts` - JWT validation
- `backend/src/core/config/auth0.ts` - Auth0 configuration
- All `.env` handling in config files
### Performance-Critical
- `backend/src/external/` - External API integrations
- Redis caching logic in all services
- Database queries in repositories
### Business-Critical
- `backend/src/features/vehicles/vehicle.service.ts` - Core vehicle operations
- VIN decoding pipeline (NHTSA integration)
- Fuel cost calculations and tracking
```
#### 1.3 Create AI Context System
**.ai/context.json**
```json
{
"version": "1.0.0",
"project_type": "full-stack-app",
"language": "typescript",
"ai_optimized": true,
"context_budget": {
"always_load": [
"AI_README.md",
"CONVENTIONS.md",
"backend/src/core/",
"backend/src/shared/types/"
],
"essential_paths": [
"backend/src/index.ts",
"backend/src/app.ts",
"frontend/src/main.tsx",
"frontend/src/App.tsx"
],
"conditional": {
"if_adding_feature": [
"templates/feature/",
".ai/dependencies.yaml",
"scripts/generate-feature.sh"
],
"if_modifying_vehicles": [
"backend/src/features/vehicles/",
"backend/src/external/vpic/",
"frontend/src/features/vehicles/"
],
"if_modifying_fuel": [
"backend/src/features/fuel-logs/",
"frontend/src/features/fuel-logs/"
],
"if_debugging_auth": [
"backend/src/core/security/",
"backend/src/core/config/auth0.ts",
"frontend/src/core/auth/"
],
"if_external_api_issues": [
"backend/src/external/",
"docs/external-apis/",
"backend/src/core/logging/"
],
"if_database_issues": [
"backend/src/database/",
"backend/src/core/config/database.ts",
"backend/src/features/*/[feature].repository.ts"
],
"if_frontend_issues": [
"frontend/src/features/",
"frontend/src/shared/components/",
"frontend/src/core/"
]
}
},
"common_tasks": {
"add_feature": {
"command": "./scripts/generate-feature.sh [feature-name]",
"template": "templates/feature/",
"checklist": [
"Run feature generation script",
"Implement business logic in service",
"Add database operations to repository",
"Create API endpoints in controller",
"Add route definitions",
"Implement frontend components",
"Write comprehensive tests",
"Update .ai/dependencies.yaml",
"Add feature to main app routes"
],
"auto_created": [
"backend/src/features/[feature]/",
"frontend/src/features/[feature]/",
"Complete test structure"
]
},
"add_external_api": {
"template": "templates/external-service/",
"checklist": [
"Create service in backend/src/external/[service]/",
"Implement caching strategy",
"Add comprehensive error handling",
"Implement rate limiting/backoff",
"Create TypeScript types",
"Write integration tests",
"Document in docs/external-apis/",
"Add environment variables",
"Update .ai/dependencies.yaml"
]
},
"debug_issue": {
"start_with": [
"Check backend/src/core/logging/ output",
"Review TROUBLESHOOTING.md",
"Check recent CHANGELOG_AI.md",
"Run relevant test suite",
"Check external API status if applicable"
],
"common_paths": [
"logs → controllers → services → external APIs",
"frontend errors → API calls → backend logs",
"database issues → migrations → repositories"
]
}
},
"danger_zones": {
"backend/src/core/security/": {
"warning": "Authentication & authorization critical path",
"required_review": true,
"test_command": "npm test:security",
"checklist": [
"Test with valid/invalid JWT tokens",
"Verify Auth0 configuration",
"Check token expiration handling",
"Validate error responses",
"Test rate limiting"
]
},
"backend/src/database/migrations/": {
"warning": "Database schema changes",
"required_review": true,
"test_command": "npm run migrate:test",
"checklist": [
"Test migration UP and DOWN",
"Verify data preservation",
"Check foreign key constraints",
"Test on copy of production data",
"Update repository classes"
]
},
"backend/src/external/": {
"warning": "External API integrations",
"test_command": "npm test:integration",
"checklist": [
"Test with API mocks",
"Verify caching behavior",
"Check error handling",
"Test rate limiting",
"Monitor API usage quotas"
]
}
},
"performance_monitoring": {
"critical_paths": [
"VIN decoding pipeline",
"Fuel station discovery",
"Vehicle data queries",
"Authentication flow"
],
"caching_strategy": {
"vin_decodes": "30 days (rarely change)",
"fuel_stations": "1 hour (prices change)",
"user_vehicles": "5 minutes (frequent updates)",
"auth_tokens": "Follow JWT expiration"
}
}
}
```
**.ai/dependencies.yaml**
```yaml
version: 1.0.0
last_updated: [DATE]
project_status: greenfield
# Module dependency graph for AI understanding
modules:
# Core Infrastructure
backend/src/core/config/:
depends_on: []
consumed_by: ["*"]
critical: true
modification_impact: "critical - full system restart required"
test_command: "npm test:config"
backend/src/core/logging/:
depends_on: ["backend/src/core/config/"]
consumed_by: ["*"]
critical: true
modification_impact: "medium - affects debugging capability"
test_command: "npm test:logging"
backend/src/core/security/:
depends_on: ["backend/src/core/config/", "backend/src/core/logging/"]
consumed_by: ["backend/src/features/*/[feature].controller.ts"]
critical: true
modification_impact: "critical - authentication affects all endpoints"
test_command: "npm test:security"
# Feature Modules (following identical patterns)
backend/src/features/vehicles/:
depends_on: ["backend/src/core/*", "backend/src/external/vpic/", "backend/src/shared/"]
consumed_by: ["backend/src/app.ts", "frontend/src/features/vehicles/"]
critical: true
modification_impact: "high - core business functionality"
test_command: "npm test:features:vehicles"
backend/src/features/fuel-logs/:
depends_on: ["backend/src/core/*", "backend/src/features/vehicles/", "backend/src/shared/"]
consumed_by: ["backend/src/app.ts", "frontend/src/features/fuel-logs/"]
critical: false
modification_impact: "medium - isolated feature"
test_command: "npm test:features:fuel-logs"
# External Integrations
backend/src/external/vpic/:
depends_on: ["backend/src/core/config/", "backend/src/core/logging/"]
consumed_by: ["backend/src/features/vehicles/"]
critical: false
modification_impact: "medium - affects VIN decoding only"
test_command: "npm test:external:vpic"
backend/src/external/google-maps/:
depends_on: ["backend/src/core/config/", "backend/src/core/logging/"]
consumed_by: ["backend/src/features/stations/"]
critical: false
modification_impact: "low - affects fuel station discovery only"
test_command: "npm test:external:maps"
# Frontend Features (mirror backend structure)
frontend/src/features/vehicles/:
depends_on: ["frontend/src/core/", "frontend/src/shared/"]
consumed_by: ["frontend/src/App.tsx"]
critical: true
modification_impact: "medium - user-facing functionality"
test_command: "npm test:frontend:vehicles"
# Architectural rules enforced by AI
rules:
- "Features cannot depend on other features (except vehicles as base)"
- "Core modules cannot depend on features"
- "External services must use caching"
- "All modules must depend on core/config for environment"
- "Frontend features mirror backend structure"
- "No direct database access outside repositories"
# Import cycles to prevent
forbidden_cycles:
- ["core/security", "features/*", "core/security"]
- ["features/vehicles", "features/fuel-logs", "features/vehicles"]
# High-risk modification paths requiring extra validation
high_risk_paths:
- description: "Authentication flow"
modules: ["core/security", "core/config/auth0.ts", "frontend/src/core/auth/"]
test_suite: "npm test:auth:full"
- description: "VIN decoding pipeline"
modules: ["external/vpic", "features/vehicles", "frontend/src/features/vehicles/components/VINDecoder"]
test_suite: "npm test:integration:vin"
- description: "Database operations"
modules: ["database/migrations", "features/*/[feature].repository.ts", "core/config/database.ts"]
test_suite: "npm test:database:full"
```
### Phase 2: Feature Templates & Code Generation (Day 3-4)
**Objective**: Create comprehensive templates that generate consistent, AI-friendly code.
#### 2.1 Feature Generation Script
**scripts/generate-feature.sh**
```bash
#!/bin/bash
set -e
FEATURE_NAME=$1
if [ -z "$FEATURE_NAME" ]; then
echo "Usage: $0 <feature-name>"
echo "Example: $0 maintenance-logs"
exit 1
fi
FEATURE_PASCAL=$(echo $FEATURE_NAME | sed -r 's/(^|-)([a-z])/\U\2/g')
FEATURE_CAMEL=$(echo $FEATURE_PASCAL | sed 's/^./\l&/')
echo "Generating feature: $FEATURE_NAME"
echo "Pascal case: $FEATURE_PASCAL"
echo "Camel case: $FEATURE_CAMEL"
# Create backend feature structure
BACKEND_DIR="backend/src/features/$FEATURE_NAME"
mkdir -p "$BACKEND_DIR/__tests__/unit"
mkdir -p "$BACKEND_DIR/__tests__/integration"
mkdir -p "$BACKEND_DIR/__tests__/fixtures"
# Generate backend files from templates
sed "s/\[FEATURE_NAME\]/$FEATURE_NAME/g; s/\[FEATURE_PASCAL\]/$FEATURE_PASCAL/g; s/\[FEATURE_CAMEL\]/$FEATURE_CAMEL/g" \
templates/feature/backend/index.template > "$BACKEND_DIR/index.ts"
sed "s/\[FEATURE_NAME\]/$FEATURE_NAME/g; s/\[FEATURE_PASCAL\]/$FEATURE_PASCAL/g; s/\[FEATURE_CAMEL\]/$FEATURE_CAMEL/g" \
templates/feature/backend/service.template > "$BACKEND_DIR/$FEATURE_CAMEL.service.ts"
sed "s/\[FEATURE_NAME\]/$FEATURE_NAME/g; s/\[FEATURE_PASCAL\]/$FEATURE_PASCAL/g; s/\[FEATURE_CAMEL\]/$FEATURE_CAMEL/g" \
templates/feature/backend/controller.template > "$BACKEND_DIR/$FEATURE_CAMEL.controller.ts"
sed "s/\[FEATURE_NAME\]/$FEATURE_NAME/g; s/\[FEATURE_PASCAL\]/$FEATURE_PASCAL/g; s/\[FEATURE_CAMEL\]/$FEATURE_CAMEL/g" \
templates/feature/backend/repository.template > "$BACKEND_DIR/$FEATURE_CAMEL.repository.ts"
sed "s/\[FEATURE_NAME\]/$FEATURE_NAME/g; s/\[FEATURE_PASCAL\]/$FEATURE_PASCAL/g; s/\[FEATURE_CAMEL\]/$FEATURE_CAMEL/g" \
templates/feature/backend/types.template > "$BACKEND_DIR/$FEATURE_CAMEL.types.ts"
sed "s/\[FEATURE_NAME\]/$FEATURE_NAME/g; s/\[FEATURE_PASCAL\]/$FEATURE_PASCAL/g; s/\[FEATURE_CAMEL\]/$FEATURE_CAMEL/g" \
templates/feature/backend/validators.template > "$BACKEND_DIR/$FEATURE_CAMEL.validators.ts"
sed "s/\[FEATURE_NAME\]/$FEATURE_NAME/g; s/\[FEATURE_PASCAL\]/$FEATURE_PASCAL/g; s/\[FEATURE_CAMEL\]/$FEATURE_CAMEL/g" \
templates/feature/backend/routes.template > "$BACKEND_DIR/$FEATURE_CAMEL.routes.ts"
# Create frontend feature structure
FRONTEND_DIR="frontend/src/features/$FEATURE_NAME"
mkdir -p "$FRONTEND_DIR/components"
mkdir -p "$FRONTEND_DIR/pages"
mkdir -p "$FRONTEND_DIR/hooks"
mkdir -p "$FRONTEND_DIR/api"
mkdir -p "$FRONTEND_DIR/types"
mkdir -p "$FRONTEND_DIR/__tests__"
# Generate frontend files from templates
sed "s/\[FEATURE_NAME\]/$FEATURE_NAME/g; s/\[FEATURE_PASCAL\]/$FEATURE_PASCAL/g; s/\[FEATURE_CAMEL\]/$FEATURE_CAMEL/g" \
templates/feature/frontend/Page.template > "$FRONTEND_DIR/pages/${FEATURE_PASCAL}Page.tsx"
sed "s/\[FEATURE_NAME\]/$FEATURE_NAME/g; s/\[FEATURE_PASCAL\]/$FEATURE_PASCAL/g; s/\[FEATURE_CAMEL\]/$FEATURE_CAMEL/g" \
templates/feature/frontend/Form.template > "$FRONTEND_DIR/components/${FEATURE_PASCAL}Form.tsx"
sed "s/\[FEATURE_NAME\]/$FEATURE_NAME/g; s/\[FEATURE_PASCAL\]/$FEATURE_PASCAL/g; s/\[FEATURE_CAMEL\]/$FEATURE_CAMEL/g" \
templates/feature/frontend/List.template > "$FRONTEND_DIR/components/${FEATURE_PASCAL}List.tsx"
sed "s/\[FEATURE_NAME\]/$FEATURE_NAME/g; s/\[FEATURE_PASCAL\]/$FEATURE_PASCAL/g; s/\[FEATURE_CAMEL\]/$FEATURE_CAMEL/g" \
templates/feature/frontend/hook.template > "$FRONTEND_DIR/hooks/use${FEATURE_PASCAL}.ts"
sed "s/\[FEATURE_NAME\]/$FEATURE_NAME/g; s/\[FEATURE_PASCAL\]/$FEATURE_PASCAL/g; s/\[FEATURE_CAMEL\]/$FEATURE_CAMEL/g" \
templates/feature/frontend/api.template > "$FRONTEND_DIR/api/$FEATURE_CAMEL.api.ts"
sed "s/\[FEATURE_NAME\]/$FEATURE_NAME/g; s/\[FEATURE_PASCAL\]/$FEATURE_PASCAL/g; s/\[FEATURE_CAMEL\]/$FEATURE_CAMEL/g" \
templates/feature/frontend/types.template > "$FRONTEND_DIR/types/$FEATURE_CAMEL.types.ts"
echo "✅ Feature $FEATURE_NAME generated successfully!"
echo ""
echo "Next steps:"
echo "1. Implement business logic in backend/src/features/$FEATURE_NAME/$FEATURE_CAMEL.service.ts"
echo "2. Add database operations in $FEATURE_CAMEL.repository.ts"
echo "3. Customize React components in frontend/src/features/$FEATURE_NAME/components/"
echo "4. Add feature routes to backend/src/app.ts and frontend/src/App.tsx"
echo "5. Write tests and update .ai/dependencies.yaml"
```
#### 2.2 Comprehensive Templates
**templates/feature/backend/service.template** (AI-optimized service pattern)
```typescript
/**
* @ai-summary Handles [FEATURE_NAME] business logic and external integrations
* @ai-examples backend/src/features/[FEATURE_NAME]/__tests__/fixtures/
* @critical-context Requires authentication, uses caching for external calls
*/
import { [FEATURE_PASCAL]Repository } from './[FEATURE_CAMEL].repository';
import {
[FEATURE_PASCAL]Input,
[FEATURE_PASCAL]Output,
[FEATURE_PASCAL]Error,
Create[FEATURE_PASCAL]Request,
Update[FEATURE_PASCAL]Request
} from './[FEATURE_CAMEL].types';
import { logger } from '../../core/logging/logger';
import { CacheService } from '../../shared/utils/cache.service';
export class [FEATURE_PASCAL]Service {
private readonly cachePrefix = '[FEATURE_NAME]';
private readonly cacheTTL = 300; // 5 minutes
constructor(
private repository: [FEATURE_PASCAL]Repository,
private cacheService: CacheService
) {}
/**
* HANDLES: Creates new [FEATURE_NAME] record with validation
* THROWS: ValidationError, DuplicateError, DatabaseError
* SIDE_EFFECTS: Database insert, cache invalidation
* AUTH_REQUIRED: true
*/
async create[FEATURE_PASCAL](
data: Create[FEATURE_PASCAL]Request,
userId: string
): Promise<[FEATURE_PASCAL]Output> {
try {
logger.info('[FEATURE_PASCAL]Service.create[FEATURE_PASCAL] started', {
userId,
dataKeys: Object.keys(data)
});
// 1. Validate business rules
await this.validateCreate[FEATURE_PASCAL](data, userId);
// 2. Transform input to domain model
const [FEATURE_CAMEL]Data = this.transformCreate[FEATURE_PASCAL](data, userId);
// 3. Persist to database
const created[FEATURE_PASCAL] = await this.repository.create(
[FEATURE_CAMEL]Data
);
// 4. Invalidate relevant cache entries
await this.invalidate[FEATURE_PASCAL]Cache(userId);
// 5. Transform to output format
const result = this.transformTo[FEATURE_PASCAL]Output(created[FEATURE_PASCAL]);
logger.info('[FEATURE_PASCAL]Service.create[FEATURE_PASCAL] completed', {
userId,
[FEATURE_CAMEL]Id: result.id
});
return result;
} catch (error) {
logger.error('[FEATURE_PASCAL]Service.create[FEATURE_PASCAL] failed', {
error: error.message,
userId,
data
});
if (error instanceof ValidationError) {
throw error;
}
throw new [FEATURE_PASCAL]Error(`Failed to create [FEATURE_NAME]: ${error.message}`);
}
}
/**
* HANDLES: Retrieves [FEATURE_NAME] records for user with caching
* THROWS: DatabaseError, NotFoundError
* SIDE_EFFECTS: Cache read/write
* AUTH_REQUIRED: true
*/
async get[FEATURE_PASCAL]sByUser(userId: string): Promise<[FEATURE_PASCAL]Output[]> {
const cacheKey = `${this.cachePrefix}:user:${userId}`;
try {
// 1. Check cache first
const cached = await this.cacheService.get<[FEATURE_PASCAL]Output[]>(cacheKey);
if (cached) {
logger.debug('[FEATURE_PASCAL]Service cache hit', { userId, cacheKey });
return cached;
}
// 2. Query database
const [FEATURE_CAMEL]s = await this.repository.findByUserId(userId);
// 3. Transform to output format
const result = [FEATURE_CAMEL]s.map(item =>
this.transformTo[FEATURE_PASCAL]Output(item)
);
// 4. Cache successful result
await this.cacheService.set(cacheKey, result, this.cacheTTL);
logger.info('[FEATURE_PASCAL]Service.get[FEATURE_PASCAL]sByUser completed', {
userId,
count: result.length
});
return result;
} catch (error) {
logger.error('[FEATURE_PASCAL]Service.get[FEATURE_PASCAL]sByUser failed', {
error: error.message,
userId
});
throw new [FEATURE_PASCAL]Error(`Failed to get [FEATURE_NAME]s: ${error.message}`);
}
}
// Private helper methods following AI-friendly patterns
private async validateCreate[FEATURE_PASCAL](
data: Create[FEATURE_PASCAL]Request,
userId: string
): Promise<void> {
// Implement validation logic
// Check business rules
// Verify user permissions
// Validate foreign key relationships
}
private transformCreate[FEATURE_PASCAL](
data: Create[FEATURE_PASCAL]Request,
userId: string
): [FEATURE_PASCAL]Input {
return {
...data,
userId,
createdAt: new Date(),
updatedAt: new Date()
} as [FEATURE_PASCAL]Input;
}
private transformTo[FEATURE_PASCAL]Output(item: [FEATURE_PASCAL]): [FEATURE_PASCAL]Output {
return {
id: item.id,
userId: item.userId,
createdAt: item.createdAt,
updatedAt: item.updatedAt,
// Add other fields as needed
} as [FEATURE_PASCAL]Output;
}
private async invalidate[FEATURE_PASCAL]Cache(userId: string): Promise<void> {
const cacheKey = `${this.cachePrefix}:user:${userId}`;
await this.cacheService.del(cacheKey);
}
}
// Custom error class
export class [FEATURE_PASCAL]Error extends Error {
constructor(message: string) {
super(message);
this.name = '[FEATURE_PASCAL]Error';
}
}
```
### Phase 3: Core Infrastructure Implementation (Day 5-7)
**Objective**: Implement the core system components using AI-optimized patterns.
#### 3.1 Backend Core Setup
**backend/src/core/config/database.ts**
```typescript
/**
* @ai-summary PostgreSQL connection setup with connection pooling
* @ai-details docs/database/CONNECTION_MANAGEMENT.md
* @critical-context Connection pooling, automatic reconnection, query logging
*/
import { Pool, PoolConfig } from 'pg';
import { logger } from '../logging/logger';
const poolConfig: PoolConfig = {
host: process.env.DB_HOST || 'localhost',
port: parseInt(process.env.DB_PORT || '5432'),
database: process.env.DB_NAME || 'motovaultpro',
user: process.env.DB_USER || 'postgres',
password: process.env.DB_PASSWORD || '',
ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false,
max: parseInt(process.env.DB_POOL_MAX || '10'),
min: parseInt(process.env.DB_POOL_MIN || '2'),
idleTimeoutMillis: parseInt(process.env.DB_IDLE_TIMEOUT || '30000'),
connectionTimeoutMillis: parseInt(process.env.DB_CONNECTION_TIMEOUT || '10000'),
};
export const pool = new Pool(poolConfig);
// Connection event handlers for monitoring
pool.on('connect', (client) => {
logger.info('Database client connected', {
totalCount: pool.totalCount,
idleCount: pool.idleCount
});
});
pool.on('error', (err) => {
logger.error('Database pool error', { error: err.message });
});
pool.on('remove', () => {
logger.info('Database client removed', {
totalCount: pool.totalCount,
idleCount: pool.idleCount
});
});
// Graceful shutdown handler
process.on('SIGTERM', async () => {
logger.info('SIGTERM received, closing database pool');
await pool.end();
process.exit(0);
});
export default pool;
```
**backend/src/core/logging/logger.ts**
```typescript
/**
* @ai-summary Structured logging with correlation IDs and log levels
* @ai-details docs/logging/STRUCTURED_LOGGING.md
* @critical-context All logs include correlation ID, user context, performance metrics
*/
import winston from 'winston';
const isDevelopment = process.env.NODE_ENV === 'development';
export const logger = winston.createLogger({
level: process.env.LOG_LEVEL || (isDevelopment ? 'debug' : 'info'),
format: winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: true }),
winston.format.json(),
winston.format.printf(({ timestamp, level, message, ...meta }) => {
const logEntry = {
timestamp,
level,
message,
service: 'motovaultpro-backend',
environment: process.env.NODE_ENV,
version: process.env.APP_VERSION,
...meta
};
return JSON.stringify(logEntry);
})
),
defaultMeta: {
service: 'motovaultpro-backend'
},
transports: [
new winston.transports.Console({
format: isDevelopment
? winston.format.combine(
winston.format.colorize(),
winston.format.simple()
)
: winston.format.json()
})
]
});
// Add file transport for production
if (process.env.NODE_ENV === 'production') {
logger.add(new winston.transports.File({
filename: 'logs/error.log',
level: 'error',
maxsize: 10485760, // 10MB
maxFiles: 5
}));
logger.add(new winston.transports.File({
filename: 'logs/combined.log',
maxsize: 10485760, // 10MB
maxFiles: 5
}));
}
export default logger;
```
#### 3.2 Frontend Core Setup
**frontend/src/core/api/client.ts**
```typescript
/**
* @ai-summary Axios client with Auth0 integration and error handling
* @ai-details docs/api/CLIENT_CONFIGURATION.md
* @critical-context Automatic token refresh, request/response logging, error transformation
*/
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { useAuth0 } from '@auth0/auth0-react';
const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3001/api';
// Create axios instance
export const apiClient: AxiosInstance = axios.create({
baseURL,
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
// Request interceptor for adding auth token
apiClient.interceptors.request.use(
async (config: AxiosRequestConfig) => {
// Note: In actual implementation, you'd get token from Auth0 context
// This is a placeholder for the pattern
const token = localStorage.getItem('access_token');
if (token) {
config.headers = {
...config.headers,
Authorization: `Bearer ${token}`,
};
}
// Add correlation ID for request tracking
config.headers['X-Correlation-ID'] = crypto.randomUUID();
console.log(`API Request: ${config.method?.toUpperCase()} ${config.url}`, {
correlationId: config.headers['X-Correlation-ID'],
params: config.params,
});
return config;
},
(error) => {
console.error('API Request Error:', error);
return Promise.reject(error);
}
);
// Response interceptor for error handling
apiClient.interceptors.response.use(
(response: AxiosResponse) => {
console.log(`API Response: ${response.status} ${response.config.url}`, {
correlationId: response.config.headers['X-Correlation-ID'],
duration: Date.now() - (response.config as any).startTime,
});
return response;
},
async (error) => {
const { response, config } = error;
console.error('API Response Error:', {
status: response?.status,
url: config?.url,
correlationId: config?.headers['X-Correlation-ID'],
error: response?.data?.error || error.message,
});
// Handle specific error cases
if (response?.status === 401) {
// Token expired or invalid
localStorage.removeItem('access_token');
window.location.href = '/login';
}
// Transform error to consistent format
const apiError = {
status: response?.status || 500,
message: response?.data?.error || error.message || 'An unexpected error occurred',
correlationId: config?.headers['X-Correlation-ID'],
};
return Promise.reject(apiError);
}
);
export default apiClient;
```
### Phase 4: Feature Implementation (Day 8-12)
**Objective**: Implement each feature using the generated templates and AI-optimized patterns.
#### 4.1 Implementation Order & Dependencies
1. **Vehicles Feature** (Days 8-9) - Foundation feature
2. **External APIs** (Day 10) - NHTSA vPIC and Google Maps
3. **Fuel Logs Feature** (Day 11) - Depends on vehicles
4. **Maintenance Feature** (Day 12) - Depends on vehicles
5. **Stations Feature** (Day 12) - Independent feature
#### 4.2 Success Criteria for Each Feature
**Per Feature Checklist:**
- [ ] Backend service, controller, repository implemented
- [ ] Frontend components, hooks, API client implemented
- [ ] Comprehensive test coverage (unit + integration)
- [ ] External API integrations cached appropriately
- [ ] Database migrations created and tested
- [ ] Documentation updated in feature README
- [ ] Added to main application routing
- [ ] Error handling follows established patterns
### Phase 5: Testing & Documentation (Day 13-14)
**Objective**: Comprehensive testing and AI-optimized documentation.
#### 5.1 Testing Strategy
**Test Structure** (mirrors feature structure)
```
__tests__/
├── unit/ # Individual function/method tests
│ ├── services/
│ ├── controllers/
│ └── utils/
├── integration/ # API endpoint tests with database
│ ├── vehicles.test.ts
│ ├── fuel-logs.test.ts
│ └── auth.test.ts
├── external/ # External API integration tests (mocked)
│ ├── vpic.test.ts
│ └── google-maps.test.ts
└── e2e/ # End-to-end user flow tests
├── vehicle-management.test.ts
└── fuel-tracking.test.ts
```
#### 5.2 AI-Optimized Documentation
**docs/ARCHITECTURE.md**
```markdown
# MotoVaultPro Architecture Overview
## System Design Philosophy
AI-first architecture prioritizing:
- **Self-documenting code** through naming and structure
- **Progressive disclosure** of complexity
- **Feature isolation** with clear dependencies
- **Consistent patterns** across all modules
- **Context-efficient navigation** for AI agents
## Core Architectural Patterns
### Feature-Based Organization
Each feature is completely self-contained:
- Business logic in service layer
- Data access in repository layer
- HTTP handling in controller layer
- Type definitions co-located with feature
- Tests mirror implementation structure
### External API Integration Pattern
All external APIs follow identical structure:
- Service class with caching
- Error handling with circuit breakers
- Rate limiting and backoff
- Comprehensive logging
- Mock-friendly for testing
### Security Architecture
- Auth0 handles all authentication
- JWT tokens validated on every request
- User context available throughout request lifecycle
- No sensitive data in logs or cache
- Environment-based configuration
## Database Design
### Schema Organization
- Core entities: users, vehicles, fuel_logs, maintenance_logs
- Audit fields on all tables (created_at, updated_at, created_by)
- Foreign key constraints enforced
- Indexes on frequently queried columns
- Migration-based schema evolution
### Caching Strategy
- External API responses: Appropriate TTL based on data volatility
- User data: Short TTL (5 minutes) for consistency
- Static data: Long TTL (30 days) for performance
- Cache invalidation on data mutations
## Frontend Architecture
### Component Organization
- Feature-based component grouping
- Shared components for common UI patterns
- Custom hooks for business logic
- API clients co-located with features
- Type definitions shared between frontend and backend
### State Management
- Local state for UI-only concerns
- Global state for cross-feature data
- Server state managed by API clients
- Authentication state managed by Auth0
```
---
## Implementation Timeline
### Week 1: Foundation (Days 1-7)
- **Days 1-2**: Project structure setup, foundation files
- **Days 3-4**: Templates and code generation scripts
- **Days 5-7**: Core infrastructure implementation
### Week 2: Feature Development (Days 8-14)
- **Days 8-9**: Vehicles feature (backend + frontend)
- **Day 10**: External API integrations (vPIC, Google Maps)
- **Day 11**: Fuel logs feature
- **Day 12**: Maintenance and stations features
- **Days 13-14**: Testing, documentation, refinement
---
## Success Metrics
### Quantitative Goals
- [ ] AI can understand system architecture in under 200 tokens
- [ ] Feature generation script creates working code in under 2 minutes
- [ ] AI requires 70% fewer file reads for common tasks vs traditional structure
- [ ] New feature implementation follows consistent patterns automatically
- [ ] Test coverage above 85% for all business logic
### Qualitative Goals
- [ ] AI can navigate codebase without human guidance
- [ ] Code review focuses on business logic vs structure
- [ ] New developers understand patterns intuitively
- [ ] Feature development velocity increases over time
- [ ] Technical debt accumulates slower due to consistent patterns
---
## Long-term Benefits
### For AI Collaboration
- **Context Efficiency**: AI loads only relevant code for each task
- **Pattern Recognition**: Consistent structure enables better code generation
- **Self-Documenting**: Code explains itself through naming and organization
- **Progressive Discovery**: AI can start with overview and dive deeper as needed
### For Human Developers
- **Reduced Cognitive Load**: Clear structure reduces context switching
- **Faster Onboarding**: New developers can follow established patterns
- **Better Maintainability**: Consistent patterns make changes predictable
- **Enhanced Productivity**: Templates and scripts automate repetitive tasks
### For System Evolution
- **Scalable Architecture**: Feature isolation supports team scaling
- **Technology Migration**: Clear boundaries enable gradual technology updates
- **Performance Optimization**: Well-defined layers enable targeted optimizations
- **Quality Assurance**: Consistent patterns enable automated quality checks
---
## Next Steps
1. **Begin Phase 1**: Create project structure and foundation files
2. **Setup Development Environment**: Docker Compose for local development
3. **Configure CI/CD**: GitHub Actions for testing and deployment
4. **Team Training**: Onboard development team to AI-first patterns
5. **Iterative Refinement**: Improve templates and patterns based on usage
This greenfield approach gives us the unique opportunity to build the ideal AI-collaborative codebase from day one, setting the foundation for efficient AI-to-AI development throughout the project lifecycle.