From 6c64a17e86a1d1e244a9527e356fc411c1522ce5 Mon Sep 17 00:00:00 2001 From: Eric Gullickson <16152721+ericgullickson@users.noreply.github.com> Date: Wed, 6 Aug 2025 20:59:45 -0500 Subject: [PATCH] Greenfield --- AI_IMPLEMENTATION_GUIDE.md | 1266 ++++++++++++++++++++++++++++++++++++ AI_STRUCTURE.md | 591 +++++++++++++++++ MOTOVAULTPRO.md | 138 ++++ 3 files changed, 1995 insertions(+) create mode 100644 AI_IMPLEMENTATION_GUIDE.md create mode 100644 AI_STRUCTURE.md create mode 100644 MOTOVAULTPRO.md diff --git a/AI_IMPLEMENTATION_GUIDE.md b/AI_IMPLEMENTATION_GUIDE.md new file mode 100644 index 0000000..f29691c --- /dev/null +++ b/AI_IMPLEMENTATION_GUIDE.md @@ -0,0 +1,1266 @@ +# 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 " + 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 { + // 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 { + 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. \ No newline at end of file diff --git a/AI_STRUCTURE.md b/AI_STRUCTURE.md new file mode 100644 index 0000000..0d53b3b --- /dev/null +++ b/AI_STRUCTURE.md @@ -0,0 +1,591 @@ +You are tasked with creating a new project that follows AI-optimized documentation and structure patterns designed for efficient AI-to-AI code maintenance. This project should be self-describing, context-efficient, and progressively discoverable. +Core Setup Instructions + +1. Initialize Project Structure +Create this exact directory structure: +project-root/ +├── AI_README.md # 200-token complete system overview +├── PROJECT_MAP.md # Navigation and quick reference +├── CONVENTIONS.md # Project patterns and standards +├── CLAUDE.md # This file - AI interaction guide +├── CHANGELOG_AI.md # AI-focused change tracking +├── src/ +│ ├── core/ # Stable, critical functionality +│ │ └── README.md # Core module descriptions +│ ├── features/ # Business logic modules +│ │ └── README.md # Feature development guide +│ ├── shared/ # Reusable utilities +│ │ └── README.md # Utility usage patterns +│ └── index.{ts|py} # Main entry point +├── docs/ +│ ├── ARCHITECTURE.md # System design decisions +│ ├── TROUBLESHOOTING.md # Common issues and solutions +│ ├── dependencies.md # External dependency documentation +│ └── diagrams/ # Visual architecture representations +├── tests/ +│ ├── README.md # Testing strategy +│ ├── fixtures/ # Shared test data +│ └── examples/ # Usage examples +├── templates/ # Code generation templates +│ └── README.md # Template usage guide +├── .ai/ # AI-specific metadata +│ ├── context.json # Context navigation for AI +│ ├── dependencies.yaml # Module dependency graph +│ └── shortcuts.md # Quick command reference +└── scripts/ + └── setup.{sh|py} # Project initialization scripts +2. Create Foundation Files +AI_README.md +markdown# Project Name + +## AI Quick Start (50 tokens) +[One paragraph describing what this system does, its primary purpose, and key technologies] + +## Navigation Guide +- Start here: PROJECT_MAP.md +- Conventions: CONVENTIONS.md +- Architecture: docs/ARCHITECTURE.md +- AI Metadata: .ai/context.json + +## Critical Context +- [List 3-5 things an AI must always know when working on this codebase] + +## Primary Entry Points +- Main application: src/index.{ts|py} +- Core modules: src/core/README.md +- Feature modules: src/features/*/index.{ts|py} +PROJECT_MAP.md +markdown# Project Navigation Map + +## System Overview +[2-3 sentences about the system architecture] + +## Quick Navigation + +### By Task +- **Adding a feature**: Start with templates/ → src/features/ +- **Fixing bugs**: TROUBLESHOOTING.md → tests/ → src/ +- **Modifying core**: Read CONVENTIONS.md first → src/core/ +- **Adding tests**: tests/README.md → tests/examples/ + +### By Frequency +- **Most changed**: [List top 3 most frequently modified paths] +- **Most critical**: src/core/* +- **Most complex**: [List complex modules needing extra context] + +## Module Map +\`\`\` +src/ +├── core/ +│ ├── config/ # Environment and app configuration +│ ├── database/ # Data layer abstractions +│ ├── logging/ # Centralized logging +│ └── security/ # Auth and security primitives +├── features/ +│ └── [feature]/ # Each feature is self-contained +│ ├── index # Public API +│ ├── service # Business logic +│ ├── types # Type definitions +│ └── tests # Feature tests +└── shared/ + ├── utils/ # Pure utility functions + └── types/ # Shared type definitions +\`\`\` + +## AI Interaction Guide +- **Before modifying**: Read .ai/context.json for the area you're working in +- **When debugging**: Start with src/core/logging +- **When adding features**: Use templates/ for consistent patterns +- **After changes**: Update CHANGELOG_AI.md and .ai/dependencies.yaml +CONVENTIONS.md +markdown# Project Conventions + +## Code Style + +### Naming Conventions +- **Files**: kebab-case.ts or snake_case.py +- **Classes**: PascalCase with descriptive names +- **Functions**: camelCase (JS/TS) or snake_case (Python), verb_noun pattern +- **Constants**: UPPER_SNAKE_CASE +- **Interfaces/Types**: PascalCase with 'I' prefix for interfaces (optional) + +### Self-Documenting Code Principles +1. **Prefer clear naming over comments** + \`\`\`typescript + // Bad + const d = new Date(); // Gets current date + + // Good + const currentDate = new Date(); + \`\`\` + +2. **Use type hints as documentation** + \`\`\`python + def process_order( + order_data: OrderDict, + validate: bool = True + ) -> Result[Order, OrderError]: + """Process order. See OrderDict for structure.""" + pass + \`\`\` + +3. **Function names should describe complete behavior** + \`\`\`typescript + // Bad: validate(data) + // Good: validateOrThrow(data) + // Good: validateAndReturnErrors(data) + \`\`\` + +## Documentation Standards + +### Progressive Disclosure Pattern +\`\`\`javascript +/** + * @ai-summary Handles payment processing + * @ai-details docs/payments/PROCESSING.md + * @ai-examples tests/examples/payment-processing.test.js + * @critical-context PCI compliance required, no card storage + */ +\`\`\` + +### Required Annotations +- **Services/Classes**: @ai-summary (one line) +- **Complex functions**: HANDLES, THROWS, SIDE_EFFECTS +- **Security-sensitive code**: SAFETY comment +- **External dependencies**: DEPENDS comment + +### When to Comment +ONLY add inline comments for: +- Regulatory/compliance requirements +- Non-obvious business logic +- Performance optimizations (with metrics) +- Security considerations +- Workarounds with issue references + +## Structure Patterns + +### Feature Module Structure +\`\`\` +features/[feature-name]/ +├── index.{ts|py} # Public API (exports only) +├── service.{ts|py} # Business logic +├── repository.{ts|py} # Data access +├── types.{ts|py} # Type definitions +├── validators.{ts|py} # Input validation +├── README.md # Feature documentation +└── __tests__/ # Feature tests +\`\`\` + +### Service Class Pattern +\`\`\`typescript +export class FeatureService { + constructor( + private repository: FeatureRepository, + private logger: Logger + ) {} + + // Public methods first, prefixed with action verb + async createFeature(data: FeatureInput): Promise> { + const validated = this.validateOrFail(data); + return this.repository.create(validated); + } + + // Private helpers last, prefixed with underscore + private validateOrFail(data: unknown): FeatureInput { + // Validation logic + } +} +\`\`\` + +## Testing Standards + +### Test Naming +- Test files: [module].test.{ts|py} or test_[module].py +- Test names: test_should_[expected_behavior]_when_[condition] +- Use @ai-coverage to link tests to code + +### Test Organization +\`\`\`python +class TestFeatureService: + """ + @ai-coverage FeatureService + @ai-fixtures tests/fixtures/features/ + """ + + def test_should_create_feature_when_data_valid(self): + # Arrange → Act → Assert pattern + pass + + def test_should_reject_when_missing_required_fields(self): + pass +\`\`\` + +## Git Commit Standards +- Format: "type(scope): description" +- Types: feat, fix, docs, refactor, test, chore +- Include "AI-CONTEXT:" line for significant changes + +## Error Handling +- Use Result pattern or explicit error types +- Never catch and ignore errors silently +- Log errors with context at catch point +- Throw early, catch late + +## Performance Guidelines +- Document Big-O complexity for algorithms +- Add benchmarks for critical paths +- Use caching for expensive computations +- Profile before optimizing +.ai/context.json +json{ + "version": "1.0.0", + "project_type": "[web-api|cli-tool|library|full-stack-app]", + "language": "[typescript|python|javascript]", + "context_budget": { + "always_load": [ + "AI_README.md", + "CONVENTIONS.md" + ], + "essential_paths": [ + "src/core/", + "src/index.{ts|py}" + ], + "conditional": { + "if_modifying_auth": [ + "src/features/auth/", + "docs/auth/", + "src/core/security/" + ], + "if_debugging": [ + "src/core/logging/", + "TROUBLESHOOTING.md", + "tests/" + ], + "if_adding_feature": [ + "templates/feature/", + "src/features/README.md", + "CONVENTIONS.md#structure-patterns" + ], + "if_modifying_database": [ + "src/core/database/", + "migrations/", + "docs/database/" + ] + } + }, + "common_tasks": { + "add_endpoint": { + "template": "templates/endpoint.template", + "checklist": [ + "Define route in router", + "Add request/response types", + "Implement handler", + "Add validation", + "Write tests", + "Update API documentation" + ], + "examples": "tests/examples/endpoints/" + }, + "add_feature": { + "template": "templates/feature/", + "checklist": [ + "Create feature folder", + "Define types", + "Implement service", + "Add repository if needed", + "Write tests", + "Update dependencies.yaml", + "Add to feature index" + ] + }, + "debug_issue": { + "start_with": [ + "Check TROUBLESHOOTING.md", + "Review recent CHANGELOG_AI.md", + "Check logs in src/core/logging", + "Run relevant tests" + ] + } + }, + "danger_zones": { + "src/core/security/": { + "warning": "Security-critical code", + "required_review": true, + "checklist": [ + "Run security tests", + "Check for credential exposure", + "Verify input validation" + ] + }, + "migrations/": { + "warning": "Database schema changes", + "required_review": true, + "checklist": [ + "Test rollback procedure", + "Verify data preservation", + "Check migration order" + ] + }, + "src/core/config/": { + "warning": "System configuration", + "checklist": [ + "Update .env.example", + "Check all environments", + "Verify defaults are safe" + ] + } + }, + "dependencies": { + "external": { + "critical": ["framework", "database", "auth-library"], + "optional": ["monitoring", "analytics"] + }, + "internal": { + "most_imported": ["src/core/logger", "src/shared/types"], + "most_dependent": ["src/core/database", "src/core/config"] + } + }, + "testing": { + "test_command": "npm test | pytest", + "coverage_threshold": 80, + "critical_paths": [ + "src/core/security", + "src/core/database", + "src/features/auth" + ] + }, + "performance": { + "bottlenecks": [], + "optimization_notes": [], + "benchmarks": "tests/benchmarks/" + } +} +.ai/dependencies.yaml +yaml# Module Dependency Graph +# Format: module -> depends_on, consumed_by, impact_level + +version: 1.0.0 +last_updated: [DATE] + +modules: + core/config: + depends_on: [] + consumed_by: ["*"] # Everything depends on config + critical: true + modification_impact: "high - requires full system test" + test_command: "npm test core/config" + + core/database: + depends_on: ["core/config", "core/logging"] + consumed_by: ["features/*", "migrations"] + critical: true + modification_impact: "high - affects all data operations" + test_command: "npm test core/database" + + core/logging: + depends_on: ["core/config"] + consumed_by: ["*"] + critical: true + modification_impact: "medium - affects debugging capability" + test_command: "npm test core/logging" + + core/security: + depends_on: ["core/config", "core/database", "core/logging"] + consumed_by: ["features/auth", "api/middleware"] + critical: true + modification_impact: "critical - security review required" + test_command: "npm test core/security" + + features/[example]: + depends_on: ["core/*", "shared/utils"] + consumed_by: ["api/routes/[example]"] + critical: false + modification_impact: "low - isolated feature" + test_command: "npm test features/[example]" + +# Dependency rules +rules: + - "Features cannot depend on other features" + - "Core modules cannot depend on features" + - "Shared utilities cannot depend on core or features" + - "All modules must depend on core/config" + +# Import cycles to avoid +forbidden_cycles: + - ["core/database", "core/security", "core/database"] + +# High-risk modification paths +high_risk_paths: + - description: "Authentication flow" + modules: ["core/security", "features/auth", "api/middleware/auth"] + test_suite: "npm test:auth:full" + + - description: "Data persistence layer" + modules: ["core/database", "migrations", "features/*/repository"] + test_suite: "npm test:database:full" +3. Create Template Files +templates/feature/index.template +typescript/** + * @ai-summary [Feature description in one line] + * @ai-details docs/features/[feature-name].md + * @critical-context [Any critical information] + */ + +export * from './types'; +export * from './service'; +export { [FeatureName]Repository } from './repository'; +templates/feature/service.template +typescript/** + * @ai-summary Handles [feature] business logic + * @ai-examples tests/examples/[feature]/ + */ +export class [FeatureName]Service { + constructor( + private repository: [FeatureName]Repository, + private logger: Logger + ) {} + + /** + * HANDLES: [What it processes] + * THROWS: [Error types] + * SIDE_EFFECTS: [External changes] + */ + async create[FeatureName]( + data: [FeatureName]Input + ): Promise> { + // Validate -> Process -> Persist -> Return + const validated = this.validateOrFail(data); + const processed = this.processBusinessRules(validated); + return this.repository.create(processed); + } + + private validateOrFail(data: unknown): [FeatureName]Input { + // Validation logic + throw new Error('Not implemented'); + } + + private processBusinessRules(data: [FeatureName]Input): [FeatureName]Data { + // Business logic transformations + throw new Error('Not implemented'); + } +} +4. Project-Specific Setup Commands +Based on the project type, run these initialization commands: +bash# For TypeScript projects +npm init -y +npm install --save-dev typescript @types/node prettier eslint +npx tsc --init + +# For Python projects +python -m venv venv +pip install black pytest mypy pylint + +# Initialize git with proper ignores +git init +echo "node_modules/\nvenv/\n.env\n*.log\n.DS_Store" > .gitignore + +# Create initial environment file +echo "# Development Environment Variables\nNODE_ENV=development\nLOG_LEVEL=debug" > .env.example +5. Initial CHANGELOG_AI.md Entry +markdown# AI-Focused Changelog + +## [Date] - Project Initialization +**Created**: Initial project structure +**Architecture**: [Chosen architecture pattern] +**Key Technologies**: [List main technologies] +**AI Context**: +- Project follows AI-optimized documentation patterns +- Self-describing code structure implemented +- Progressive disclosure documentation in place +**Entry Points**: +- Start with AI_README.md +- Conventions in CONVENTIONS.md +- Navigation via PROJECT_MAP.md +Instructions for Claude Code +When creating a new project with these standards: + +Start by asking the user: + +Project type (API, CLI tool, web app, library) +Primary language (TypeScript, Python, JavaScript) +Key features needed initially +Any specific frameworks or libraries required + + +Then systematically: + +Create the complete directory structure +Generate all foundation files with project-specific content +Set up the .ai/ metadata directory +Create initial templates based on project type +Initialize version control and package management +Write the first entry in CHANGELOG_AI.md + + +Customize based on project type: + +API: Add OpenAPI specs, route templates, middleware patterns +CLI: Add command templates, argument parsing patterns +Library: Add export patterns, public API documentation +Full-stack: Add frontend/backend separation, API contracts + + +For each file you create: + +Ensure it follows the self-documenting principles +Add appropriate @ai-* annotations +Include type hints/interfaces +Create corresponding test file structure +Update .ai/context.json with new paths + + +Before completing setup: + +Verify all imports resolve correctly +Ensure templates have clear replacement markers +Check that navigation paths in documentation are accurate +Confirm .ai/dependencies.yaml reflects actual structure +Test that the project runs with minimal setup + + +Final output should include: + +Complete file structure +All content for foundation files +Setup instructions in a setup.md +Initial test file examples +A "Getting Started for AI" section in AI_README.md + + + +Remember: The goal is to create a codebase that another AI can understand and modify efficiently with minimal context loading. Every decision should optimize for clarity and discoverability. +Example First Response +When you run this setup, respond with: +I'll create an AI-optimized project structure for your [project type]. This setup will follow AI-to-AI communication patterns for maximum clarity and minimal context usage. + +## Project Configuration +- Type: [selected type] +- Language: [selected language] +- Architecture: [chosen pattern] + +## Creating Structure... +[Show the directory tree being created] + +## Generating Foundation Files... +[List each file as it's created] + +## Project Ready! + +### Next Steps for AI Interaction: +1. Read AI_README.md for system overview +2. Check CONVENTIONS.md before making changes +3. Use PROJECT_MAP.md for navigation +4. Refer to .ai/context.json for task-specific guidance + +### For Human Developers: +1. Run: [setup command] +2. Configure: Copy .env.example to .env +3. Install: [package manager] install +4. Test: [test command] + +The project is now optimized for AI maintenance and collaboration! \ No newline at end of file diff --git a/MOTOVAULTPRO.md b/MOTOVAULTPRO.md new file mode 100644 index 0000000..b4fc5b6 --- /dev/null +++ b/MOTOVAULTPRO.md @@ -0,0 +1,138 @@ +Technology Stack + +Frontend: React 18 with TypeScript +Backend: Node.js 20 + Express + TypeScript +Database: PostgreSQL 15 +Cache: Redis 7 +File Storage: MinIO (S3-compatible) +Authentication: Auth0 +Container Runtime: Docker +Orchestration: Kubernetes (Nutanix NKP) +GitOps: FluxCD + Kustomize +APIs: NHTSA vPIC (free), Google Maps Platform + +Project Structure +motovaultpro/ +├── docker-compose.yml # Local development environment +├── .env.example # Environment variables template +├── README.md # Project documentation +├── Makefile # Common commands +│ +├── backend/ +│ ├── package.json +│ ├── tsconfig.json +│ ├── Dockerfile +│ ├── src/ +│ │ ├── index.ts # Express server entry point +│ │ ├── app.ts # Express app configuration +│ │ ├── config/ +│ │ │ ├── database.ts # PostgreSQL connection +│ │ │ ├── redis.ts # Redis connection +│ │ │ ├── auth0.ts # Auth0 middleware +│ │ │ └── minio.ts # MinIO client setup +│ │ ├── routes/ +│ │ │ ├── index.ts # Route aggregator +│ │ │ ├── auth.routes.ts # Authentication endpoints +│ │ │ ├── vehicles.routes.ts # Vehicle CRUD + VIN decode +│ │ │ ├── fuel.routes.ts # Fuel log endpoints +│ │ │ ├── maintenance.routes.ts +│ │ │ └── stations.routes.ts # Google Maps integration +│ │ ├── controllers/ +│ │ │ ├── vehicles.controller.ts +│ │ │ ├── fuel.controller.ts +│ │ │ ├── maintenance.controller.ts +│ │ │ └── stations.controller.ts +│ │ ├── services/ +│ │ │ ├── vpic.service.ts # NHTSA vPIC integration +│ │ │ ├── googlemaps.service.ts +│ │ │ ├── cache.service.ts # Redis caching logic +│ │ │ └── storage.service.ts # MinIO operations +│ │ ├── models/ +│ │ │ ├── user.model.ts +│ │ │ ├── vehicle.model.ts +│ │ │ ├── fuel-log.model.ts +│ │ │ └── maintenance-log.model.ts +│ │ ├── middleware/ +│ │ │ ├── auth.middleware.ts +│ │ │ ├── validation.middleware.ts +│ │ │ └── error.middleware.ts +│ │ ├── utils/ +│ │ │ ├── logger.ts # Structured logging +│ │ │ └── validators.ts # Input validation schemas +│ │ └── migrations/ +│ │ ├── 001_initial_schema.sql +│ │ ├── 002_vin_cache.sql +│ │ └── 003_stored_procedures.sql +│ +├── frontend/ +│ ├── package.json +│ ├── tsconfig.json +│ ├── Dockerfile +│ ├── vite.config.ts +│ ├── index.html +│ ├── src/ +│ │ ├── main.tsx +│ │ ├── App.tsx +│ │ ├── api/ +│ │ │ ├── client.ts # Axios instance +│ │ │ ├── vehicles.api.ts +│ │ │ ├── fuel.api.ts +│ │ │ └── stations.api.ts +│ │ ├── components/ +│ │ │ ├── Layout/ +│ │ │ ├── VehicleForm/ +│ │ │ ├── VINDecoder/ +│ │ │ ├── FuelLogForm/ +│ │ │ ├── StationPicker/ # Google Maps component +│ │ │ └── common/ +│ │ ├── pages/ +│ │ │ ├── Dashboard.tsx +│ │ │ ├── Vehicles.tsx +│ │ │ ├── FuelLogs.tsx +│ │ │ └── Maintenance.tsx +│ │ ├── hooks/ +│ │ │ ├── useAuth.ts +│ │ │ ├── useVehicles.ts +│ │ │ └── useGoogleMaps.ts +│ │ ├── store/ +│ │ │ └── index.ts # Zustand or Redux +│ │ └── types/ +│ │ └── index.ts +│ +├── k8s/ # GitOps configurations +│ ├── base/ +│ │ ├── namespace.yaml +│ │ ├── backend/ +│ │ │ ├── deployment.yaml +│ │ │ ├── service.yaml +│ │ │ └── configmap.yaml +│ │ ├── frontend/ +│ │ │ ├── deployment.yaml +│ │ │ └── service.yaml +│ │ ├── postgres/ +│ │ │ ├── statefulset.yaml +│ │ │ ├── service.yaml +│ │ │ ├── pvc.yaml +│ │ │ └── init-scripts.yaml +│ │ ├── redis/ +│ │ │ ├── statefulset.yaml +│ │ │ └── service.yaml +│ │ ├── minio/ +│ │ │ ├── statefulset.yaml +│ │ │ ├── service.yaml +│ │ │ └── pvc.yaml +│ │ └── ingress.yaml +│ │ +│ └── overlays/ +│ ├── development/ +│ │ ├── kustomization.yaml +│ │ └── patches/ +│ └── production/ +│ ├── kustomization.yaml +│ ├── sealed-secrets/ +│ └── patches/ +│ +└── .github/ + └── workflows/ + ├── ci.yml # Test and build + └── cd.yml # Deploy via GitOps \ No newline at end of file