# AGENTS.md

This file provides guidance to AI agents working with code in this repository.

## Project Overview

Django-Ninja backend powering CodeFlash's AI-driven code optimization. Handles LLM interactions, test generation, and optimization workflows.

## Commands

```bash
# Install dependencies (NEVER use pip)
uv sync
uv sync --group dev

# Run development server
uv run uvicorn aiservice.asgi:application --reload

# Run all tests
uv run pytest

# Run a single test file
uv run pytest tests/optimizer/test_optimizer.py

# Run a specific test
uv run pytest tests/optimizer/test_optimizer.py::test_function_name -v

# Type checking
uv run mypy .
uv run ty check

# Linting (auto-fixes enabled)
uv run ruff check .
uv run ruff format .
```

## Architecture

### API Structure
All REST endpoints use Django-Ninja with type-safe Pydantic schemas. APIs are defined in `aiservice/urls.py`:
- `/ai/optimize` - Code optimization (optimizer/optimizer.py)
- `/ai/testgen` - Test generation (testgen/testgen.py)
- `/ai/refinement` - Iterative refinement (optimizer/refinement.py)
- `/ai/rank` - Optimization ranking (ranker/ranker.py)
- `/ai/explain` - Code explanations (explanations/explanations.py)
- `/ai/code_repair` - Code repair (code_repair/code_repair.py)
- `/ai/adaptive_optimize` - Adaptive optimization (adaptive_optimizer/adaptive_optimizer.py)

### LLM Module (`aiservice/llm.py`)
Unified interface for all LLM calls. Always use this instead of direct API calls:
```python
from aiservice.llm import call_llm, OPTIMIZE_MODEL, LLMResponse

response: LLMResponse = await call_llm(
    llm=OPTIMIZE_MODEL,
    messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}],
    call_type="optimization",
    trace_id=trace_id,
)
```

Model assignments are configured at the bottom of `llm.py`. Supports both OpenAI and Anthropic via Azure.

### Prompt Files
LLM prompts are stored as `.md` files alongside their modules:
- `optimizer/system_prompt.md`, `optimizer/user_prompt.md`
- `testgen/execute_system_prompt.md`, `testgen/execute_user_prompt.md`
- `code_repair/CODE_REPAIR_SYSTEM_PROMPT.md`

### Middleware Stack (`aiservice/middleware/`)
- `healthcheck.py` - Health check endpoint
- `auth_middleware.py` - API authentication
- `rate_limit.py` - Rate limiting
- `track_usage_middleware.py` - Usage tracking

### Observability (`aiservice/observability/`)
- `logger.py` - Logging utilities
- `database.py` - Records LLM calls for tracing
- Sentry integration for error tracking (production only)

## Key Patterns

### Use libcst for code manipulation
Always use `libcst` (not `ast`) to preserve formatting when modifying code.

### Use Pydantic for schemas
All request/response models use Pydantic BaseModel or ninja.Schema.

### Async endpoints
Most API endpoints are async. Use `asyncio.TaskGroup` for concurrent operations.

### Context classes
Optimizer and testgen use context classes (`BaseOptimizerContext`, `BaseTestGenContext`) to manage state and prompts.

## Code Style

- **Line length**: 120 characters
- **Python**: 3.12+ syntax
- **Tooling**: Ruff (linting/formatting), mypy (strict mode), ty (type checker)
- **Comments**: Minimal - explain "why", not "what"
- **Docstrings**: Don't add unless explicitly requested

## Git Commits

Use conventional commit format: `fix:`, `feat:`, `refactor:`, `docs:`, `test:`, `chore:`

# Agent Rules <!-- tessl-managed -->

@../../.tessl/RULES.md follow the [instructions](../../.tessl/RULES.md)
