# AGENTS.md

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

## Project Overview

**TiInsight** is a data analysis service built with TiDB Cloud that provides natural language querying of databases with data visualization and exploration capabilities.

## Architecture

### Tech Stack

- **Framework**: Next.js 14 (React framework for SSR and static generation)
- **Language**: TypeScript
- **Database**: TiDB Cloud (via Drizzle ORM)
- **State Management**: Redux Toolkit + Redux Persist
- **API Layer**: tRPC (type-safe API calls)
- **UI Components**: Mantine UI + TiDB Cloud UI Kit
- **Data Fetching**: React Query (TanStack Query)
- **Authentication**: Lucia Auth + Arctic
- **Error Tracking**: Sentry
- **Code Quality**: Biome (linting/formatting)

### Key Architecture Components

1. **Frontend**: Next.js pages with React components in `/components`
2. **API Layer**: tRPC routers in `/server/api.ts` with procedures in `/server/`
3. **Database**: Drizzle ORM schema definitions in `/server/schema.ts`
4. **State Management**: Redux store configuration in `/store/`
5. **Authentication**: Lucia auth integration with TiDB Cloud OAuth

## Folder Structure

```
/
├── components/          # React components (App.tsx is main layout)
├── pages/               # Next.js pages and API routes
│   ├── api/             # API endpoints (tRPC gateway)
│   └── oauth/           # OAuth authentication flows
├── server/              # Server-side code
│   ├── api.ts           # Main tRPC router and procedures
│   ├── auth.ts          # Authentication logic
│   ├── schema.ts        # Database schema (Drizzle)
│   └── trpc.ts          # tRPC configuration
├── store/               # Redux store and slices
├── utils/               # Utility functions
├── drizzle/             # Drizzle migrations
└── public/              # Static assets
```

## Development Commands

### Build & Run

```bash
# Install dependencies
pnpm install

# Run development server (port 3000)
pnpm dev

# Build for production
pnpm build

# Start production server
pnpm start
```

### Database

```bash
# Generate Drizzle migrations
pnpm db:generate

# Push schema to database
pnpm db:push

# Drop database (careful!)
pnpm db:drop
```

### Testing & Quality

```bash
# Run tests (Vitest)
pnpm test

# Run single test file
pnpm test path/to/test.spec.ts

# Lint code (Next.js ESLint)
pnpm lint

# Format code (Biome)
npx biome check --apply
```

### Git Hooks

- **pre-commit**: Runs Biome formatting on staged files
- Uses Lefthook for git hook management

## Key Files

### Entry Points

- `pages/_app.tsx` - Main Next.js app component
- `components/App.tsx` - Main application layout
- `pages/api/gateway/[trpc].ts` - tRPC API handler

### Core Logic

- `server/api.ts` - Main tRPC router with all procedures
- `server/schema.ts` - Database schema definitions
- `server/trpc.ts` - tRPC configuration and middleware
- `server/auth.ts` - Authentication logic

### State Management

- `store/index.ts` - Redux store configuration
- `store/slices/` - Redux slices (account, session, etc.)

## Environment Variables

Required environment variables (see `.env.example`):

- `TIINSIGHT_DB_URI` - TiDB Cloud database connection
- `TIDBCLOUD_OAUTH_CLIENT_ID/SECRET` - OAuth credentials
- `TIDBCLOUD_DATA_APP_ENDPOINT_HOST` - Data API endpoint
- `MASTER_KEY_V0` - Application master key
- `SAMPLE_DB_*` - Sample database configuration

## Testing Strategy

- **Framework**: Vitest
- **Test files**: `*.spec.ts` or `*.test.ts`
- **Run tests**: `pnpm test`
- **Watch mode**: `pnpm test --watch`

## Code Quality

- **Linter/Formatter**: Biome (replaces ESLint/Prettier)
- **Config**: `biome.json`
- **Git hooks**: Auto-format on commit via Lefthook
- **Type Safety**: TypeScript with strict mode

## Deployment

- **Platform**: Vercel (configured in project)
- **Process**: Push to main branch triggers automatic deployment
- **Environment**: Configure Vercel environment variables

## Key Features

1. **Natural Language Querying**: Convert text to SQL queries
2. **Data Visualization**: ECharts integration for charts
3. **Canvas Mode**: Visual data relationship mapping
4. **Session Management**: Conversation history and bookmarks
5. **Authentication**: TiDB Cloud OAuth integration

## Important Patterns

1. **tRPC Procedures**: Type-safe API endpoints with `publicProcedure` and `protectedProcedure`
2. **Redux State**: Centralized state management with persistence
3. **React Query**: Server state management for data fetching
4. **Drizzle ORM**: Type-safe database access
5. **Error Boundaries**: Comprehensive error handling with Sentry

## Common Development Tasks

### Adding a new API endpoint

1. Add procedure to `server/api.ts`
2. Use `publicProcedure` or `protectedProcedure`
3. Define input/output schemas with Zod
4. Access via `trpcNextClient.yourProcedure.useQuery()`

### Adding a new component

1. Create in `/components/` directory
2. Use Mantine UI components for styling
3. Connect to Redux store if needed
4. Use React Query for data fetching

### Database changes

1. Update schema in `server/schema.ts`
2. Run `pnpm db:generate` to create migration
3. Run `pnpm db:push` to apply to database
