# MotoVaultPro

Single-tenant vehicle management application with 9-container architecture (6 application: Traefik, Frontend, Backend, OCR, PostgreSQL, Redis + 3 logging: Loki, Alloy, Grafana).

## Files

| File | What | When to read |
| ---- | ---- | ------------ |
| `Makefile` | Build, test, deploy commands | Running any make command |
| `docker-compose.yml` | Development container orchestration | Local development setup |
| `docker-compose.staging.yml` | Staging container orchestration | Staging deployment |
| `docker-compose.prod.yml` | Production container orchestration | Production deployment |
| `docker-compose.blue-green.yml` | Blue-green deployment orchestration | Zero-downtime deploys |
| `package.json` | Root workspace dependencies | Dependency management |
| `README.md` | Project overview | First-time setup |

## Subdirectories

| Directory | What | When to read |
| --------- | ---- | ------------ |
| `backend/` | Fastify API server with feature capsules | Backend development |
| `frontend/` | React/Vite SPA with MUI | Frontend development |
| `ocr/` | Python OCR microservice (Tesseract) | OCR pipeline, receipt/VIN extraction |
| `docs/` | Project documentation hub | Architecture, APIs, testing |
| `config/` | Configuration files (Traefik, logging stack) | Infrastructure setup |
| `scripts/` | Utility scripts (backup, deploy, CI) | Automation tasks |
| `.ai/` | AI context and workflow contracts | AI-assisted development |
| `.claude/` | Claude Code agents and skills | Delegating to agents, using skills |
| `.gitea/` | Gitea workflows and templates | CI/CD, issue templates |
| `ansible/` | Ansible deployment playbooks | Server provisioning |
| `certs/` | TLS certificates | SSL/TLS configuration |
| `secrets/` | Docker secrets (Stripe keys, Traefik) | Secret management |
| `data/` | Persistent data volumes (backups, documents) | Storage paths, volume mounts |

## Build for staging and production. NOT FOR DEVELOPMENT

```bash
make setup    # First-time setup 
make rebuild  # Rebuild containers
```

## Test

```bash
npm test             # Run all tests
npm run lint         # Linting
npm run type-check   # TypeScript validation
```

---

# Development Partnership Guidelines

## Core Development Principles

### AI Context Efficiency
**CRITICAL**: All development practices and choices should be made taking into account the most context efficient interaction with another AI. Any AI should be able to understand this application with minimal prompting.

## Never Use Emojis
Maintain professional documentation standards without emoji usage.

## Mobile + Desktop Requirement
**ALL features MUST be implemented and tested on BOTH mobile and desktop.** This is a hard requirement that cannot be skipped. Every component, page, and feature needs responsive design and mobile-first considerations.

### Codebase Integrity Rules
- Justify every new file and folder as being needed for the final production application.
- Never make up things that aren't part of the actual project
- Never skip or ignore existing system architecture
- Be precise and respectful of the current codebase
- **Delete** old code when replacing it
- **Meaningful names**: `userID` not `id`

## Naming Conventions

### Case Standards
| Layer | Convention | Example |
|-------|------------|---------|
| Database columns | snake_case | `user_id`, `created_at`, `is_active` |
| Backend TypeScript types | camelCase | `userId`, `createdAt`, `isActive` |
| API responses | camelCase | `{ "userId": "...", "createdAt": "..." }` |
| Frontend TypeScript types | camelCase | `userId`, `createdAt`, `isActive` |

### Repository Pattern for Case Conversion
All repositories MUST implement private `mapRow()` or similar mapper functions to convert database snake_case to TypeScript camelCase:

```typescript
private mapRow(row: any): MyType {
  return {
    id: row.id,
    userId: row.user_id,      // snake_case -> camelCase
    createdAt: row.created_at,
    isActive: row.is_active,
  };
}
```

All methods returning data to the API must use these mappers - never return raw database rows.

## Development Workflow (Local + CI/CD)

### Local Development
```bash
npm install          # Install dependencies
npm run dev          # Start dev server
npm test             # Run tests
npm run lint         # Linting
npm run type-check   # TypeScript validation
```

### CI/CD Pipeline (on PR)
- Container builds and integration tests
- Mobile/desktop viewport validation
- Security scanning

**Flow**: Local dev -> Push to Gitea -> CI/CD runs -> PR review -> Merge


## Quality Standards

### Automated Checks Are Mandatory
**ALL hook issues are BLOCKING - EVERYTHING must be ✅ GREEN!**
- No errors. No formatting issues. No linting problems. Zero tolerance
- These are not suggestions. Fix ALL issues before continuing

### Code Completion Criteria
Our code is complete when:
- ✅ All linters pass with zero issues
- ✅ All tests pass  
- ✅ Feature works end-to-end
- ✅ Old code is deleted

## AI Collaboration Strategy

### Use Multiple Agents
Leverage subagents aggressively for better results:
- Spawn agents to explore different parts of the codebase in parallel
- Use one agent to write tests while another implements features
- Delegate research tasks: "I'll have an agent investigate the database schema while I analyze the API structure"
- For complex refactors: One agent identifies changes, another implements them

### Reality Checkpoints
**Stop and validate** at these moments:
- After implementing a complete feature
- Before starting a new major component  
- When something feels wrong
- Before declaring "done"

## Performance & Security Standards

### Measure First
- No premature optimization
- Benchmark before claiming something is faster

### Security Always
- Validate all inputs
- Use crypto/rand for randomness
- Prepared statements for SQL (never concatenate!)

## AI Loading Context Strategies

Canonical sources only - avoid duplication:
- Architecture and metadata: `.ai/context.json`
- Sprint workflow contract: `.ai/workflow-contract.json`
- Documentation hub: `docs/README.md`
- Feature work: `backend/src/features/{feature}/README.md`
- Platform architecture: `docs/PLATFORM-SERVICES.md`
- Testing workflow: `docs/TESTING.md`

## Sprint Workflow

Issues are the source of truth. See `.ai/workflow-contract.json` for complete workflow.

### Quick Reference
- Every PR must link to at least one issue
- Use Gitea MCP tools for issue/label/branch/PR operations
- Labels: `status/backlog` -> `status/ready` -> `status/in-progress` -> `status/review` -> `status/done`
- Branches: `issue-{parent_index}-{slug}` (e.g., `issue-42-add-fuel-report`)
- Commits: `{type}: {summary} (refs #{index})` (e.g., `feat: add fuel report (refs #42)`)

### Sub-Issue Decomposition
Multi-file features (3+ files) must be broken into sub-issues for smaller AI context windows:
- **Sub-issue title**: `{type}: {summary} (#{parent_index})` -- parent index in title
- **Sub-issue body**: First line `Relates to #{parent_index}`
- **ONE branch** per parent issue only. Never branch per sub-issue.
- **ONE PR** per parent issue. Body lists `Fixes #N` for parent and every sub-issue.
- **Commits** reference the specific sub-issue: `feat: add dashboard (refs #107)`
- **Status labels** tracked on parent only. Sub-issues stay `status/backlog`.
- **Plan milestones** map 1:1 to sub-issues.

## Architecture Context for AI

### 9-Container Architecture
**MotoVaultPro uses a unified architecture:** A single-tenant application with 9 containers - 6 application (Traefik, Frontend, Backend, OCR, PostgreSQL, Redis) + 3 logging (Loki, Alloy, Grafana). Application features in `backend/src/features/[name]/` are self-contained modules within the backend service, including the platform feature for vehicle data and VIN decoding. See `docs/LOGGING.md` for unified logging system documentation.

### Key Principles for AI Understanding
- **Feature Capsule Organization**: Application features are self-contained modules within the backend
- **Single-Tenant**: All data belongs to a single user/tenant
- **User-Scoped Data**: All application data isolated by user_id
- **Local Dev + CI/CD**: Development locally, container testing in CI/CD pipeline
- **Integrated Platform**: Platform capabilities integrated into main backend service

### Common AI Tasks
See `Makefile` for authoritative commands and `docs/README.md` for navigation.

## Agent System

| Directory | Contents | When to Read |
|-----------|----------|--------------|
| `.claude/role-agents/` | Developer, TW, QR, Debugger | Delegating execution |
| `.claude/role-agents/quality-reviewer.md` | RULE 0/1/2 definitions | Quality review |
| `.claude/skills/planner/` | Planning workflow | Complex features (3+ files) |
| `.claude/skills/problem-analysis/` | Problem decomposition | Uncertain approach |
| `.claude/agents/` | Domain agents | Feature/Frontend/Platform work |
| `.ai/workflow-contract.json` | Sprint process, skill integration | Issue workflow |

### Quality Rules (see quality-reviewer.md for full definitions)
- **RULE 0 (CRITICAL)**: Production reliability - unhandled errors, security, resource exhaustion
- **RULE 1 (HIGH)**: Project standards - mobile+desktop, naming, patterns, CI/CD pass
- **RULE 2 (SHOULD_FIX)**: Structural quality - god objects, duplication, dead code
