# Bun + Hono + SQLite (libSQL & Drizzle ORM) — AI Agent Guidelines & Architecture Rules

> Ultra-fast edge API architecture using Bun.serve(), Hono v4, Drizzle ORM with embedded SQLite / Turso libSQL, and Zod OpenAPI validation.
> Technologies: Bun, Hono, SQLite, Drizzle, TypeScript, Zod

---

## AGENTS.md
```markdown
# Project Architecture & Guidelines (Bun + Hono + SQLite / Drizzle)

## 1. System Architecture
- **Runtime**: Bun (Bun.serve() high-performance HTTP & WebSocket server).
- **Web Framework**: Hono v4 (`hono`, `@hono/zod-validator`).
- **Database & ORM**: SQLite (`bun:sqlite` or `@libsql/client` for Turso edge replication) via Drizzle ORM.
- **Type Validation**: Zod with `@hono/zod-openapi` for declarative request/response contracts and automatic Swagger documentation.

## 2. Monorepo & Modular File Layout
- `src/index.ts`: Application bootstrap and `export default app` for Bun.serve().
- `src/routes/`: Route modules using `new Hono()`, grouped by domain entity (e.g. `users.routes.ts`, `auth.routes.ts`).
- `src/db/`:
  - `schema.ts`: Drizzle table definitions using `sqliteTable()`.
  - `client.ts`: Singleton database connection pool.
- `src/middleware/`: Bearer token auth, CORS, logger, and global error boundaries.

## 3. Route Handlers & Zod Validation
- Validate query, params, and JSON bodies strictly with `zValidator('json', schema)` or `@hono/zod-openapi`.
- Never parse `c.req.json()` manually without prior schema validation.
- Return typed JSON responses via `c.json({ success: true, data })`.

## 4. Database & Transaction Rules
- Use Drizzle ORM prepared queries for hot paths.
- Enable Write-Ahead Logging (`PRAGMA journal_mode = WAL;`) and busy timeouts (`PRAGMA busy_timeout = 5000;`) on SQLite databases.
- Group multi-row mutations inside `db.transaction()` blocks to prevent partial writes.

## 5. Coding Standards & Error Handling
- Strict TypeScript: `strict: true`, zero `any` policy.
- Throw typed `HTTPException` from `hono/http-exception` with explicit HTTP status codes (400, 401, 404, 422).
- Register global `app.onError((err, c) => ...)` returning consistent JSON error envelopes `{ error: string, code?: string }`.

## 6. Testing Conventions
- Use Bun's native test runner (`bun test`) — no Jest/Vitest dependency needed.
- Test Hono routes with `app.request('/path', { method: 'POST', body })` against an in-memory SQLite database, never the production file.
- Cover Zod schema edge cases explicitly (missing fields, wrong types, boundary values) — validation bugs are the most common regression in this stack.
- Run `bun test --coverage` in CI; block merges that drop coverage on `src/routes/` or `src/db/`.

## 7. Git Workflow & PR Conventions
- Conventional Commits (`feat:`, `fix:`, `refactor:`) with the affected route/module in scope, e.g. `fix(auth): handle expired bearer tokens`.
- Every PR that changes `src/db/schema.ts` must include the generated Drizzle migration file in the same commit.
- Require `bun test` and `tsc --noEmit` to pass before merge; no exceptions for "just a typo fix" PRs touching schema files.
- Rebase onto `main` before merging; keep history linear for easy `bun run db:migrate` rollback tracing.
```

---

## CLAUDE.md
```markdown
# CLAUDE.md — Bun + Hono + SQLite Commands & Conventions

## Common Commands
- `bun run dev` - Start local development server with hot module reloading (`bun --watch src/index.ts`)
- `bun run build` - Compile standalone binary or bundle with `bun build`
- `bun test` - Run unit and integration tests using native Bun test runner
- `bun run db:generate` - Generate Drizzle SQLite migrations (`drizzle-kit generate`)
- `bun run db:migrate` - Apply pending SQLite migrations (`drizzle-kit migrate`)

## Code Style Guidelines
- Leverage Hono's chainable API (`app.get(...).post(...)`) for type-inferred RPC client generation.
- Keep route handlers thin; delegate data access to dedicated repository/service functions.
- Never use Node.js legacy polyfills when native Web Platform APIs (`fetch`, `Request`, `Response`, `crypto`) are built-in.
- Enforce Prettier formatting with 2-space indentation and trailing commas.
```

---

## .cursor/rules/stack.mdc
```markdown
---
description: Bun + Hono + SQLite/Drizzle edge API rules
globs: ["**/*.ts"]
alwaysApply: true
---

# Bun + Hono + SQLite (Drizzle)

- `Bun.serve()` runtime, Hono v4 router, Drizzle ORM over `bun:sqlite` or `@libsql/client`.
- Validate every request body/query/params with `zValidator` or `@hono/zod-openapi` — never call `c.req.json()` unvalidated.
- Enable WAL mode (`PRAGMA journal_mode = WAL;`) and a busy timeout on SQLite; wrap multi-row writes in `db.transaction()`.
- Strict TypeScript, zero `any`. Throw `HTTPException` with explicit status codes.
- Global `app.onError` returns `{ error: string, code?: string }` — never leak raw stack traces to clients.
- Prefer native Web Platform APIs (`fetch`, `crypto`, `Request`/`Response`) over Node polyfills; Bun implements them natively.
- Keep route handlers thin — delegate persistence to `src/db/` repository functions, not inline queries.
```

---

## Architecture Overview & Best Practices
## Architecture Overview

Production-ready architectural guidelines for **Bun**, **Hono v4**, **SQLite**, and **Drizzle ORM**.

### Key Advantages

- **Sub-Millisecond Response Times**: Bun's native C/Zig bindings combined with Hono's lightweight RegExpRouter deliver microsecond latency overhead.
- **Embedded & Edge Ready**: Zero-configuration embedded SQLite via `bun:sqlite` or distributed edge replication via Turso libSQL.
- **End-to-End Type Safety**: Hono RPC allows sharing backend route types directly with frontend clients without code generation.