# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

Clinic is a TiDB cluster monitoring and diagnostics platform. It receives runtime data from TiDB clusters and rebuilds monitoring information for oncall issue investigation.

## Common Commands

```bash
# Full check, test, and build (run before submitting code)
make

# Quick lint check only (for fast local development)
make check

# Run tests
make test

# Run a single test
go test -v ./pkg/path/to/package -run TestName

# Build all binaries
make build

# Build specific components
make build-clinic-server    # Main clinic server
make ngm_api                # NGM API server
make build-task-manager     # Task manager
make build-internal-server  # Internal server

# Generate swagger docs
make generate-swagger

# Generate goqueryset (for db models with gen:qs comment)
make genearte-goqueryset
```

## Running Locally

```bash
# Clinic server
bin/server -c=pkg/config/config_example.yaml

# NGM API server (requires TiDB playground and port-forward to dbaas)
bin/ngm_api -c=pkg/ngm/config/config_example.yaml
```

## Architecture

### Main Services (cmd/)

- **server**: Main Clinic API server - handles file uploads, reports, metrics proxy, authentication
- **ngm_api**: Next-gen monitoring API - TopSQL, slow queries, continuous profiling, statements, key visualization
- **task_manager**: Background task processing
- **internal_server**: Internal APIs
- **importer/uploader**: Data import/upload utilities

### Key Packages (pkg/)

- **api/**: REST API handlers using Gin, organized by domain (login, org, upload, report, etc.). Uses `uber-go/fx` for dependency injection - each subdomain exposes a `Module` variable
- **ngm/**: Next-gen monitoring features (topsql, slowquery, conprof, statements, keyviz, performance_insight)
- **db/**: Database layer using GORM with MySQL/TiDB
- **auth/**: Authentication (OAuth, session, API keys)
- **rbac/**: Role-based access control using Casbin
- **storage/**: File storage abstraction (AWS S3)
- **proxy/**: Metric and o11y proxy handlers

### Database Migrations

Migrations are in `pkg/db/migrate.go`. To add a new migration:

```go
var _ = AddMigrateRecord(VERSION_NUMBER,
    func(db *gorm.DB) error {
        return db.AutoMigrate(&YourModel{})
    },
)
```

- Use a unique version number (check existing records for the latest)
- Models registered in `pkg/db/schema.go` `Models` slice are auto-created on fresh deployments
- Migrations run on startup for existing databases

### API Module Pattern

API handlers follow an fx module pattern:

```go
// pkg/api/yourfeature/register.go
var Module = fx.Options(
    fx.Provide(NewYourService),
    fx.Invoke(registerRouter),
)

func registerRouter(r *gin.RouterGroup, s *YourService) {
    r.GET("/endpoint", s.Handler)
}
```

### cloud_server/

Separate Go module (`cloud_server/go.mod`) for cloud-specific functionality with its own Makefile.
