docs: 精简 AGENTS.md 文档结构并优化内容呈现

This commit is contained in:
2026-04-01 23:24:23 +08:00
parent b38d475b6f
commit 22363279c8
+66 -247
View File
@@ -1,300 +1,119 @@
# AGENTS.md - AI Coding Agent Guidelines # AGENTS.md - AI Coding Agent Guidelines
Guidelines for AI agents working in this project.
## Project Overview ## Project Overview
> **This project uses [Bun](https://bun.sh) exclusively as both the JavaScript runtime and package manager. Do NOT use Node.js / npm / yarn / pnpm. All commands start with `bun` — use `bun install` for dependencies and `bun run <script>` for scripts. Always prefer `bun run <script>` over `bun <script>` to avoid conflicts with Bun built-in subcommands (e.g. `bun build` invokes Bun's bundler, NOT your package.json script). Never use `npm`, `npx`, or `node`.** > **This project uses [Bun](https://bun.sh) exclusively. Do NOT use Node.js / npm / yarn / pnpm. Always use `bun run <script>` (not `bun <script>`) to avoid conflicts with Bun built-in subcommands.**
- **Framework**: TanStack Start (React 19 SSR, file-based routing) - **Framework**: TanStack Start (React 19 SSR, file-based routing)
- **Runtime**: Bun (see `mise.toml` for version) — **NOT Node.js** - **Runtime/PM**: Bun (see `mise.toml`) — **NOT Node.js / npm / yarn / pnpm**
- **Package Manager**: Bun — **NOT npm / yarn / pnpm** - **Language**: TypeScript (strict mode) | **Styling**: Tailwind CSS v4
- **Language**: TypeScript (strict mode)
- **Styling**: Tailwind CSS v4
- **Database**: PostgreSQL + Drizzle ORM v1 beta (`drizzle-orm/postgres-js`, RQBv2) - **Database**: PostgreSQL + Drizzle ORM v1 beta (`drizzle-orm/postgres-js`, RQBv2)
- **State**: TanStack Query v5 - **State**: TanStack Query v5 | **RPC**: ORPC (contract-first) | **Build**: Vite + Nitro
- **RPC**: ORPC (contract-first, type-safe)
- **Build**: Vite + Nitro
## Build / Lint / Test Commands ## Commands
```bash ```bash
# Development
bun run dev # Vite dev server (localhost:3000) bun run dev # Vite dev server (localhost:3000)
bun run db:studio # Drizzle Studio GUI
# Build
bun run build # Production build → .output/ bun run build # Production build → .output/
bun run compile # Compile to standalone binary (current platform, depends on build) bun run compile # Compile to standalone binary (current platform)
bun run compile:darwin # Compile for macOS (arm64 + x64) bun run fix # Biome auto-fix (lint + format)
bun run compile:darwin:arm64 # Compile for macOS arm64
bun run compile:darwin:x64 # Compile for macOS x64
bun run compile:linux # Compile for Linux (x64 + arm64)
bun run compile:linux:arm64 # Compile for Linux arm64
bun run compile:linux:x64 # Compile for Linux x64
bun run compile:windows # Compile for Windows (default: x64)
bun run compile:windows:x64 # Compile for Windows x64
# Code Quality
bun run fix # Biome auto-fix
bun run typecheck # TypeScript check bun run typecheck # TypeScript check
bun run db:push # Push schema to dev DB (dev only, fast iteration)
# Database (Drizzle) bun run db:generate # Generate migration SQL files (for production)
bun run db:generate # Generate migrations from schema bun run db:migrate # Apply migrations (production deployment)
bun run db:migrate # Run migrations bun run db:studio # Drizzle Studio GUI
bun run db:push # Push schema directly (dev only) bun test path/to/test.ts # Run single test (not yet configured)
# Testing (not yet configured)
bun test path/to/test.ts # Run single test
bun test -t "pattern" # Run tests matching pattern
``` ```
## Code Style (TypeScript) ## Code Style
### Formatting (Biome) **Formatting (Biome):** 2-space indent, LF, single quotes, no semicolons, always arrow parens `(x) => x`
- **Indent**: 2 spaces | **Line endings**: LF
- **Quotes**: Single `'` | **Semicolons**: Omit (ASI)
- **Arrow parentheses**: Always `(x) => x`
### Imports
Biome auto-organizes. Order: 1) External packages → 2) Internal `@/*` aliases → 3) Type imports (`import type { ... }`)
**Imports** — Biome auto-organizes: 1) External → 2) `@/*` aliases → 3) `import type`
```typescript ```typescript
import { createFileRoute } from '@tanstack/react-router' import { createFileRoute } from '@tanstack/react-router'
import { z } from 'zod'
import { db } from '@/server/db' import { db } from '@/server/db'
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
``` ```
### TypeScript Strictness **TypeScript:** `strict: true`, `noUncheckedIndexedAccess`, `verbatimModuleSyntax`. Use `@/*` path aliases (→ `src/*`).
- `strict: true`, `noUncheckedIndexedAccess: true`, `noImplicitOverride: true`, `verbatimModuleSyntax: true`
- Use `@/*` path aliases (maps to `src/*`)
### Naming Conventions **Naming:** Files (utils): `kebab-case.ts` | Files (components): `PascalCase.tsx` | Components: `const Button = () => {}` | Functions: `camelCase` | Constants: `UPPER_SNAKE` | Types: `PascalCase`
| Type | Convention | Example |
|------|------------|---------|
| Files (utils) | kebab-case | `auth-utils.ts` |
| Files (components) | PascalCase | `UserProfile.tsx` |
| Components | PascalCase arrow | `const Button = () => {}` |
| Functions | camelCase | `getUserById` |
| Constants | UPPER_SNAKE | `MAX_RETRIES` |
| Types/Interfaces | PascalCase | `UserProfile` |
### React Patterns **React:** Arrow function components (Biome enforced). Routes: `export const Route = createFileRoute(...)`. Data: `useSuspenseQuery(orpc.feature.list.queryOptions())`
- Components: arrow functions (enforced by Biome)
- Routes: TanStack Router file conventions (`export const Route = createFileRoute(...)`)
- Data fetching: `useSuspenseQuery(orpc.feature.list.queryOptions())`
### Error Handling **Errors:** `try-catch` for async; `ORPCError` with codes (`NOT_FOUND`, `INPUT_VALIDATION_FAILED`). Never empty catch blocks.
- Use `try-catch` for async operations; throw descriptive errors
- ORPC: Use `ORPCError` with proper codes (`NOT_FOUND`, `INPUT_VALIDATION_FAILED`)
- Never use empty catch blocks
## ORPC Pattern ## ORPC Pattern
### 1. Define Contract (`src/server/api/contracts/feature.contract.ts`) **1. Contract** (`src/server/api/contracts/feature.contract.ts`) — Zod schemas for input/output
```typescript **2. Router** (`src/server/api/routers/feature.router.ts`) — Handler implementations using `os.feature.list.use(db).handler(...)`
import { oc } from '@orpc/contract' **3. Register** — Export from `contracts/index.ts` and `routers/index.ts`
import { createSelectSchema } from 'drizzle-orm/zod' **4. Client**`useSuspenseQuery(orpc.feature.list.queryOptions())` / `useMutation(orpc.feature.create.mutationOptions())`
import { z } from 'zod'
import { featureTable } from '@/server/db/schema'
const selectSchema = createSelectSchema(featureTable) ## Database (Drizzle ORM v1 beta)
export const list = oc.input(z.void()).output(z.array(selectSchema)) - **Driver**: `drizzle-orm/postgres-js` (NOT `bun-sql`) | **Validation**: `drizzle-orm/zod` (NOT `drizzle-zod`)
export const create = oc.input(insertSchema).output(selectSchema) - **Relations**: `defineRelations()` in `src/server/db/relations.ts` (RQBv2 — `drizzle()` only needs `{ relations }`)
``` - **Query style**: RQBv2 object syntax — `orderBy: { createdAt: 'desc' }`, `where: { id: 1 }`
- **Schema**: All tables must include `id` (UUIDv7), `createdAt`, `updatedAt` (see `src/server/db/fields.ts`)
### 2. Implement Router (`src/server/api/routers/feature.router.ts`) ### Database Workflow
```typescript - **Local dev**: `db:push` — fast iteration, no migration files needed
import { ORPCError } from '@orpc/server' - **Production**: `db:generate` → review SQL → `db:migrate` — versioned, auditable
import { db } from '../middlewares' - **Never mix** `push` and `migrate` on the same database instance
import { os } from '../server' - `drizzle/` migration directory is committed to Git
export const list = os.feature.list.use(db).handler(async ({ context }) => { ### ⚠️ drizzle.config.ts Caveat
return await context.db.query.featureTable.findMany({ `drizzle.config.ts` runs outside Vite — **`@/*` path aliases do not work**. Use relative imports (`./src/env`).
orderBy: { createdAt: 'desc' },
})
})
```
### 3. Register in Index Files
```typescript
// src/server/api/contracts/index.ts
import * as feature from './feature.contract'
export const contract = { feature }
// src/server/api/routers/index.ts
import * as feature from './feature.router'
export const router = os.router({ feature })
```
### 4. Use in Components
```typescript
import { useSuspenseQuery, useMutation } from '@tanstack/react-query'
import { orpc } from '@/client/orpc'
const { data } = useSuspenseQuery(orpc.feature.list.queryOptions())
const mutation = useMutation(orpc.feature.create.mutationOptions())
```
## Database (Drizzle ORM v1 beta + postgres-js)
- **ORM**: Drizzle ORM `1.0.0-beta` (RQBv2)
- **Driver**: `drizzle-orm/postgres-js` (NOT `bun-sql`)
- **Validation**: `drizzle-orm/zod` (built-in, NOT separate `drizzle-zod` package)
- **Relations**: Defined via `defineRelations()` in `src/server/db/relations.ts` (contains schema info, so `drizzle()` only needs `{ relations }`)
- **Query style**: RQBv2 object syntax (`orderBy: { createdAt: 'desc' }`, `where: { id: 1 }`)
### Schema Definition
```typescript
import { pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core'
import { sql } from 'drizzle-orm'
export const myTable = pgTable('my_table', {
id: uuid().primaryKey().default(sql`uuidv7()`),
name: text().notNull(),
createdAt: timestamp({ withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp({ withTimezone: true }).notNull().defaultNow().$onUpdateFn(() => new Date()),
})
```
### Relations (RQBv2)
```typescript
// src/server/db/relations.ts
import { defineRelations } from 'drizzle-orm'
import * as schema from './schema'
export const relations = defineRelations(schema, (r) => ({
// Define relations here using r.one / r.many / r.through
}))
```
### DB Instance
```typescript
// src/server/db/index.ts
import { drizzle } from 'drizzle-orm/postgres-js'
import { relations } from '@/server/db/relations'
// In RQBv2, relations already contain schema info — no separate schema import needed
const db = drizzle({
connection: env.DATABASE_URL,
relations,
})
```
### RQBv2 Query Examples
```typescript
// Object-style orderBy (NOT callback style)
const todos = await db.query.todoTable.findMany({
orderBy: { createdAt: 'desc' },
})
// Object-style where
const todo = await db.query.todoTable.findFirst({
where: { id: someId },
})
```
## Environment Variables ## Environment Variables
- Use `@t3-oss/env-core` with Zod validation in `src/env.ts` - Validated via `@t3-oss/env-core` + Zod in `src/env.ts`
- Server vars: no prefix | Client vars: `VITE_` prefix required - Server vars: no prefix | Client vars: `VITE_` prefix required
- Never commit `.env` files - Never commit `.env` files
```typescript
// src/env.ts
import { createEnv } from '@t3-oss/env-core'
import { z } from 'zod'
export const env = createEnv({
server: {
DATABASE_URL: z.string().url(),
},
clientPrefix: 'VITE_',
client: {
VITE_API_URL: z.string().optional(),
},
})
```
## Development Principles ## Development Principles
> **These principles apply to ALL code changes. Agents MUST follow them on every task.** 1. **No backward compatibility** — Rapid iteration. Always use latest API/patterns. No deprecated fallbacks.
2. **Always sync documentation** — Code changes → immediately update `AGENTS.md` and related docs.
1. **No backward compatibility** — This project is in rapid iteration. Always use the latest API and patterns. Never keep deprecated code paths or old API fallbacks "just in case". 3. **Forward-only migration** — Fully adopt new APIs when upgrading. No mixing old/new patterns.
2. **Always sync documentation** — When code changes, immediately update all related documentation (`AGENTS.md`, `README.md`, inline code examples). Code and docs must never drift apart. This includes updating code snippets in docs when imports, APIs, or patterns change.
3. **Forward-only migration** — When upgrading dependencies, fully adopt the new API. Don't mix old and new patterns in the same codebase.
## Critical Rules ## Critical Rules
**DO:** **DO:** `bun run fix` before committing | `@/*` path aliases | `createdAt`/`updatedAt` on all tables | `ORPCError` with proper codes | `drizzle-orm/zod` for validation | RQBv2 object syntax | Update docs with code changes
- Run `bun run fix` before committing
- Use `@/*` path aliases (not relative imports)
- Include `createdAt`/`updatedAt` on all tables
- Use `ORPCError` with proper codes
- Use `drizzle-orm/zod` (NOT `drizzle-zod`) for schema validation
- Use RQBv2 object syntax for `orderBy` and `where`
- Update `AGENTS.md` and other docs whenever code patterns change
**DON'T:** **DON'T:** `npm`/`npx`/`node`/`yarn`/`pnpm` | Edit `routeTree.gen.ts` | `as any`/`@ts-ignore`/`@ts-expect-error` | Commit `.env` | Empty catch blocks | Import from `drizzle-zod` | RQBv1 callback-style API | `drizzle-orm/bun-sql` driver | Pass `schema` to `drizzle()` | Import `os` from `@orpc/server` in middleware (use `@/server/api/server`) | Leave docs out of sync
- Use `npm`, `npx`, `node`, `yarn`, `pnpm` — always use `bun` / `bunx`
- Edit `src/routeTree.gen.ts` (auto-generated)
- Use `as any`, `@ts-ignore`, `@ts-expect-error`
- Commit `.env` files
- Use empty catch blocks `catch(e) {}`
- Import from `drizzle-zod` (use `drizzle-orm/zod` instead)
- Use RQBv1 callback-style `orderBy` / old `relations()` API
- Use `drizzle-orm/bun-sql` driver (use `drizzle-orm/postgres-js`)
- Pass `schema` to `drizzle()` constructor (only `relations` is needed in RQBv2)
- Import `os` from `@orpc/server` in middleware — use `@/server/api/server` (the local typed instance)
- Leave docs out of sync with code changes
## Git Workflow ## Git Workflow
1. Make changes following style guide 1. Make changes → 2. `bun run fix` → 3. `bun run typecheck` → 4. `bun run dev` (test) → 5. Commit
2. `bun run fix` - auto-format and lint
3. `bun run typecheck` - verify types
4. `bun run dev` - test locally
5. Commit with descriptive message
## Directory Structure ## Directory Structure
``` ```
. src/
├── src/ ├── client/orpc.ts # ORPC client + TanStack Query utils
├── client/ # Client-side code ├── components/ # React components
│ │ └── orpc.ts # ORPC client + TanStack Query utils (single entry point) ├── routes/ # TanStack Router file routes
│ ├── components/ # React components │ ├── __root.tsx # Root layout
── routes/ # TanStack Router file routes ── api/ # API routes (OpenAPI, health, RPC)
│ │ ├── __root.tsx # Root layout ├── server/
│ ├── index.tsx # Home page │ ├── api/
│ │ ── api/ │ │ ── contracts/ # ORPC input/output schemas (Zod)
│ │ ├── $.ts # OpenAPI handler + Scalar docs │ │ ├── routers/ # ORPC handler implementations
│ │ ├── health.ts # Health check endpoint │ │ ├── middlewares/ # Middleware (db, auth)
│ │ └── rpc.$.ts # ORPC RPC handler │ │ ├── interceptors.ts # Shared error interceptors
│ ├── server/ # Server-side code │ ├── context.ts # Request context
│ │ ├── api/ # ORPC layer │ │ ├── server.ts # ORPC server instance
│ │ │ ├── contracts/ # Input/output schemas (Zod) │ │ └── types.ts # Type exports
│ │ ├── middlewares/ # Middleware (db provider, auth) └── db/
│ │ ├── routers/ # Handler implementations ├── schema/ # Drizzle table definitions
│ │ ├── interceptors.ts # Shared error interceptors ├── fields.ts # Shared field builders
│ │ ├── context.ts # Request context ├── relations.ts # Drizzle relations (RQBv2)
│ ├── server.ts # ORPC server instance └── index.ts # Database instance
│ │ │ └── types.ts # Type exports ├── env.ts # Environment variable validation
│ │ └── db/ ├── router.tsx # Router configuration
│ │ ├── schema/ # Drizzle table definitions ├── routeTree.gen.ts # Auto-generated (DO NOT EDIT)
│ │ ├── fields.ts # Shared field builders (id, createdAt, updatedAt) └── styles.css # Tailwind entry
│ │ ├── relations.ts # Drizzle relations (defineRelations, RQBv2)
│ │ └── index.ts # Database instance (postgres-js driver)
│ ├── env.ts # Environment variable validation
│ ├── router.tsx # Router configuration
│ ├── routeTree.gen.ts # Auto-generated (DO NOT EDIT)
│ └── styles.css # Tailwind entry
├── biome.json # Linting/formatting config
├── compile.ts # Cross-platform binary compilation script
├── drizzle.config.ts # Drizzle Kit config
├── vite.config.ts # Vite + TanStack Start + Nitro config
├── tsconfig.json # TypeScript config
└── package.json # Dependencies and scripts
``` ```