# Coding Standards -- LLMHosts.com

## ALWAYS APPLY
These standards apply to all code written in this workspace.

## FUNDAMENTAL RULES
1. **Docker always**: Every service, tool, dependency runs in containers. Never install natively.
2. **Read all docs**: Before implementing, read relevant knowledge base docs in full. Follow all instructions. Skip nothing.
3. **Research first**: Before any implementation, do 3 varied web searches on best practices (current as of Feb 2026). Compare to your plan. Refactor if needed.
4. **Full implementation**: Never partial work or shortcuts. Break into smaller edits if needed, but complete the full intended scope.
5. **Stay focused**: Only do what is asked. No scope creep. No documentation before task is done and verified.

## BACKEND (Python / FastAPI)
- Python 3.12+
- FastAPI for all HTTP services
- Pydantic v2 for validation and serialization
- async/await everywhere (no blocking I/O)
- Type hints on all functions
- Docstrings on public functions (concise, AI-optimized)
- Tests: pytest with async support
- Linting: ruff
- Formatting: ruff format

## FRONTEND (Next.js / TypeScript)
- Next.js 15+ with App Router
- TypeScript strict mode
- TailwindCSS for styling
- shadcn/ui components (do not reinvent)
- Tanstack Query for server state
- Zustand for client state
- WebSocket (Socket.io or native) for real-time
- ESLint + Prettier

## FILE STRUCTURE (CLI-first package -- ADR-008)
```
/home/dev/projects/LLMHosts.com/
├── llmhost/                # Python package (pip install llmhost)
│   ├── proxy/              # FastAPI OpenAI + Anthropic proxy
│   ├── router/             # Three-tier router (rule, kNN, ModernBERT, Qwen)
│   ├── cache/              # vCache (exact hash, namespace, semantic)
│   ├── backend/            # LiteLLM adapter, model registry
│   ├── discovery/          # Ollama, hardware, tunnel detection
│   ├── keys/               # BYOK key management, encryption
│   ├── metrics/            # Cost tracking, aggregation, baseline
│   ├── dashboard/          # TUI (textual) + web dashboard bridge
│   ├── db/                 # SQLite engine, models, migrations
│   ├── cli.py              # Click CLI entrypoint
│   ├── config.py           # Config loading (~/.llmhost/config.toml)
│   └── constants.py        # Ports, paths, version constants
├── hive/                   # Hive.CEO embedded agent system (NOT Hive Mode)
│   ├── agents/             # 5 agents: base, ceo, analyst, watcher, builder, advisor
│   ├── admin/              # FastAPI routes for /admin/hive/ panel
│   ├── models/             # LLM provider abstraction (Ollama, OpenAI, etc.)
│   ├── github/             # GitHub API wrapper for PR creation
│   ├── memory/             # Institutional memory store
│   ├── health/             # Health monitoring and self-healing
│   ├── backlog/            # Improvement item management
│   └── utils/              # Sandbox execution, codebase indexing
├── .hive/                  # Hive.CEO identity and state (tracked in git)
│   ├── identity.md         # What this app is (versioned, evolves)
│   ├── soul.md             # Agent behavioral guidelines
│   ├── config.yaml         # Model providers, settings, approval rules
│   ├── memory/             # Institutional memory (patterns, incidents, decisions)
│   └── ...                 # See AGENTS.md for full structure
├── tests/                  # All test layers (unit, integration, e2e, spec)
├── frontend/               # Next.js web dashboard (Phase 3)
├── docs/                   # Architecture, specs, knowledge base, backlog
├── deferred/               # Blocked items tracking (human-in-the-loop)
├── .github/                # CI/CD, issue templates, CODEOWNERS
├── pyproject.toml          # Package metadata, deps, tool config
├── Dockerfile              # Production multi-stage image
├── Dockerfile.dev          # Development container
└── docker-compose.yml      # Dev stack orchestration
```

## HIVE.CEO CODING CONVENTIONS
- All Hive Python code lives in `hive/` package (separate from `llmhost/`)
- Hive agents inherit from `hive.agents.base.BaseAgent`
- Agent scope boundaries are enforced in code (Analyst reads-only, Builder modifies-only-via-git, etc.)
- Hive admin routes mount at `/admin/hive/` on the host FastAPI app
- Hive uses ONLY stdlib imports where possible (ast, json, pathlib, dataclasses) -- minimize dependencies
- All Hive file I/O goes through `.hive/` directory (never writes outside workspace root)
- Hive agent activity is logged via Python `logging` (hive.* namespace)
- Naming: `Hive.CEO` = embedded agent system. `Hive Mode` = Phase 3 GPU pooling feature. NEVER conflate these.

## DOCKER CONVENTIONS
- Every service has its own Dockerfile
- docker-compose.yml at project root for local development
- Multi-stage builds for production images
- .dockerignore in every service directory
- Environment variables via .env files (never committed)
- Health checks on all services

## API CONVENTIONS
- OpenAI-compatible: /v1/chat/completions, /v1/models, etc.
- JSON responses with consistent error format
- API versioning via URL path (/v1/)
- Rate limiting headers on all responses
- Request tracing (X-Request-ID) on all requests
- Cost metadata in response headers (X-LLMHosts-Cost, X-LLMHosts-Model)

## GIT & GITHUB CONVENTIONS (Masterclass Level)
- **Conventional commits**: `feat(scope):`, `fix(scope):`, `docs:`, `refactor:`, `test:`, `chore:`
- **Branch naming**: `feature/<backlog-id>-<desc>`, `fix/<backlog-id>-<desc>`, `docs/<desc>`, `chore/<desc>`
- **PR required** for develop and main branches (no direct push, ever)
- **No secrets in commits** (use .env, docs/secure/ is gitignored, push protection enabled)
- **Squash merge to main** (linear history)
- **All PRs must pass**: lint, test, build, security checks before merge
- **Issues = backlog items**: Every backlog item is a GitHub Issue with labels (priority, epic, phase)
- **GitHub Projects V2**: Kanban board with Board/Table/Roadmap/Sprint views
- **GHCR**: Docker images pushed to GitHub Container Registry on merge to main
- **Dependabot**: Auto-updates for pip, npm, Docker, GitHub Actions dependencies
- **Secret scanning + push protection**: Enabled, blocks secrets before they land
- **Releases**: Semantic versioning, auto-changelog from conventional commit PR titles
- **Full spec**: docs/knowledge-base/github-masterclass.md
