Codebase Onboarding
Tier: POWERFUL
Category: Engineering
Domain: Documentation / Developer Experience
Overview
Analyze a codebase and generate comprehensive onboarding documentation tailored to your audience. Produces architecture overviews, key file maps, local setup guides, common task runbooks, debugging guides, and contribution guidelines. Outputs to Markdown, Notion, or Confluence.
Core Capabilities
- - Architecture overview — tech stack, system boundaries, data flow diagrams
- Key file map — what's important and why, with annotations
- Local setup guide — step-by-step from clone to running tests
- Common developer tasks — how to add a route, run migrations, create a component
- Debugging guide — common errors, log locations, useful queries
- Contribution guidelines — branch strategy, PR process, code style
- Audience-aware output — junior, senior, or contractor mode
When to Use
- - Onboarding a new team member or contractor
- After a major refactor that made existing docs stale
- Before open-sourcing a project
- Creating a team wiki page for a service
- Self-documenting before a long vacation
Codebase Analysis Commands
Run these before generating docs to gather facts:
CODEBLOCK0
Generated Documentation Template
README.md — Full Template
CODEBLOCK1 bash
1. Clone
git clone https://github.com/org/repo
cd repo
2. Install dependencies
pnpm install
3. Start infrastructure
docker compose up -d # Starts Postgres, Redis
4. Environment
cp .env.example .env
Edit .env — ask a teammate for real values or see Vault
5. Database setup
pnpm db:migrate # Run migrations
pnpm db:seed # Optional: load test data
6. Start dev server
pnpm dev # → http://localhost:3000
7. Verify
pnpm test # Should be all green
### Verify it works
- [ ] `http://localhost:3000` loads the app
- [ ] `http://localhost:3000/api/health` returns `{"status":"ok"}`
- [ ] `pnpm test` passes
---
## Architecture
### System Overview
Browser / Mobile
│
▼
[Next.js App] ←──── [Auth: NextAuth]
│
├──→ [PostgreSQL] (primary data store)
├──→ [Redis] (sessions, job queue)
└──→ [S3] (file uploads)
Background:
[BullMQ workers] ←── Redis queue
└──→ [External APIs: Stripe, SendGrid]
### Tech Stack
| Layer | Technology | Why |
|-------|-----------|-----|
| Frontend | Next.js 14 (App Router) | SSR, file-based routing |
| Styling | Tailwind CSS + shadcn/ui | Rapid UI development |
| API | Next.js Route Handlers | Co-located with frontend |
| Database | PostgreSQL 16 | Relational, RLS for multi-tenancy |
| ORM | Drizzle ORM | Type-safe, lightweight |
| Auth | NextAuth v5 | OAuth + email/password |
| Queue | BullMQ + Redis | Background jobs |
| Storage | AWS S3 | File uploads |
| Email | SendGrid | Transactional email |
| Payments | Stripe | Subscriptions |
| Deployment | Vercel (app) + Railway (workers) | |
| Monitoring | Sentry + Datadog | |
---
## Key Files
| Path | Purpose |
|------|---------|
| `app/` | Next.js App Router — pages and API routes |
| `app/api/` | API route handlers |
| `app/(auth)/` | Auth pages (login, register, reset) |
| `app/(app)/` | Protected app pages |
| `src/db/` | Database schema, migrations, client |
| `src/db/schema.ts` | **Drizzle schema — single source of truth** |
| `src/lib/` | Shared utilities (auth, email, stripe) |
| `src/lib/auth.ts` | **Auth configuration — read this first** |
| `src/components/` | Reusable React components |
| `src/hooks/` | Custom React hooks |
| `src/types/` | Shared TypeScript types |
| `workers/` | BullMQ background job processors |
| `emails/` | React Email templates |
| `tests/` | Test helpers, factories, integration tests |
| `.env.example` | All env vars with descriptions |
| `docker-compose.yml` | Local infrastructure |
---
## Common Developer Tasks
### Add a new API endpoint
bash
1. Create route handler
touch app/api/my-resource/route.ts
typescript
// app/api/my-resource/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { db } from '@/db/client'
export async function GET(req: NextRequest) {
const session = await auth()
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const data = await db.query.myResource.findMany({
where: (r, { eq }) => eq(r.userId, session.user.id),
})
return NextResponse.json({ data })
}
bash
2. Add tests
touch tests/api/my-resource.test.ts
3. Add to OpenAPI spec (if applicable)
pnpm generate:openapi
### Run a database migration
bash
Create migration
pnpm db:generate # Generates SQL from schema changes
Review the generated SQL
cat drizzle/migrations/0001
mychange.sql
Apply
pnpm db:migrate
Roll back (manual — inspect generated SQL and revert)
psql $DATABASE
URL -f scripts/rollback0001.sql
### Add a new email template
bash
1. Create template
touch emails/my-email.tsx
2. Preview in browser
pnpm email:preview
3. Send in code
import { sendEmail } from '@/lib/email'
await sendEmail({
to: user.email,
subject: 'Subject line',
template: 'my-email',
props: { name: "username"
})
### Add a background job
typescript
// 1. Define job in workers/jobs/my-job.ts
import { Queue, Worker } from 'bullmq'
import { redis } from '@/lib/redis'
export const myJobQueue = new Queue('my-job', { connection: redis })
export const myJobWorker = new Worker('my-job', async (job) => {
const { userId, data } = job.data
// do work
}, { connection: redis })
// 2. Enqueue
await myJobQueue.add('process', { userId, data }, {
attempts: 3,
backoff: { type: 'exponential', delay: 1000 },
})
---
## Debugging Guide
### Common Errors
**`Error: DATABASE_URL is not set`**
bash
Check your .env file exists and has the var
cat .env | grep DATABASE_URL
Start Postgres if not running
docker compose up -d postgres
**`PrismaClientKnownRequestError: P2002 Unique constraint failed`**
User already exists with that email. Check: is this a duplicate registration?
Run: SELECT * FROM users WHERE email = 'test@example.com';
**`Error: JWT expired`**
bash
Dev: extend token TTL in .env
JWT
EXPIRESIN=30d
Check clock skew between server and client
date && docker exec postgres date
**`500 on /api/*` in local dev**
bash
1. Check terminal for stack trace
2. Check database connectivity
psql $DATABASE_URL -c "SELECT 1"
3. Check Redis
redis-cli ping
4. Check logs
pnpm dev 2>&1 | grep -E "error|Error|ERROR"
### Useful SQL Queries
sql
-- Find slow queries (requires pg
statstatements)
SELECT query, mean
exectime, calls, total
exectime
FROM pg
statstatements
ORDER BY mean
exectime DESC
LIMIT 20;
-- Check active connections
SELECT count(*), state FROM pgstatactivity GROUP BY state;
-- Find bloated tables
SELECT relname, ndeadtup, nlivetup,
round(ndeadtup::numeric/nullif(nlivetup,0)*100, 2) AS dead_pct
FROM pgstatuser_tables
ORDER BY ndeadtup DESC;
### Debug Authentication
bash
Decode a JWT (no secret needed for header/payload)
echo "YOUR_JWT" | cut -d. -f2 | base64 -d | jq .
Check session in DB
psql $DATABASE
URL -c "SELECT * FROM sessions WHERE userid = 'usr
...' ORDER BY expiresat DESC LIMIT 5;"
### Log Locations
| Environment | Logs |
|-------------|------|
| Local dev | Terminal running `pnpm dev` |
| Vercel production | Vercel dashboard → Logs |
| Workers (Railway) | Railway dashboard → Deployments → Logs |
| Database | `docker logs postgres` (local) |
| Background jobs | `pnpm worker:dev` terminal |
---
## Contribution Guidelines
### Branch Strategy
main → production (protected, requires PR + CI)
└── feature/PROJ-123-short-desc
└── fix/PROJ-456-bug-description
└── chore/update-dependencies
### PR Requirements
- [ ] Branch name includes ticket ID (e.g., `feature/PROJ-123-...`)
- [ ] PR description explains the why
- [ ] All CI checks pass
- [ ] Test coverage doesn't decrease
- [ ] Self-reviewed (read your own diff before requesting review)
- [ ] Screenshots/video for UI changes
### Commit Convention
feat(scope): short description → new feature
fix(scope): short description → bug fix
chore: update dependencies → maintenance
docs: update API reference → documentation
### Code Style
bash
Lint + format
pnpm lint
pnpm format
Type check
pnpm typecheck
All checks (run before pushing)
pnpm validate
``
---
## Audience-Specific Notes
### For Junior Developers
- Start with src/lib/auth.ts
to understand authentication
- Read existing tests in tests/api/
— they document expected behavior
- Ask before touching anything in src/db/schema.ts
— schema changes affect everyone
- Use pnpm db:seed
to get realistic local data
### For Senior Engineers / Tech Leads
- Architecture decisions are documented in docs/adr/
(Architecture Decision Records)
- Performance benchmarks: pnpm bench
— baseline is in tests/benchmarks/baseline.json
- Security model: RLS policies in src/db/rls.sql
, enforced at DB level
- Scaling notes: docs/scaling.md
### For Contractors
- Scope is limited to src/features/[your-feature]/
unless discussed
- Never push directly to main
- All external API calls go through src/lib/` wrappers (for mocking in tests)
- - Time estimates: log in Linear ticket comments daily
Output Formats
→ See references/output-format-templates.md for details
Common Pitfalls
- - Docs written once, never updated — add doc updates to PR checklist
- Missing local setup step — test setup instructions on a fresh machine quarterly
- No error troubleshooting — debugging section is the most valuable part for new hires
- Too much detail for contractors — they need task-specific, not architecture-deep docs
- No screenshots — UI flows need screenshots; they go stale but are still valuable
- Skipping the "why" — document why decisions were made, not just what was decided
Best Practices
- 1. Keep setup under 10 minutes — if it takes longer, fix the setup, not the docs
- Test the docs — have a new hire follow them literally, fix every gap they hit
- Link, don't repeat — link to ADRs, issues, and external docs instead of duplicating
- Update in the same PR — docs changes alongside code changes
- Version-specific notes — call out things that changed in recent versions
- Runbooks over theory — "run this command" beats "the system uses Redis for..."
代码库入职指南
层级: 强大
类别: 工程
领域: 文档 / 开发者体验
概述
分析代码库并生成针对目标受众的全面入职文档。生成架构概览、关键文件映射、本地设置指南、常见任务手册、调试指南和贡献指南。输出格式支持 Markdown、Notion 或 Confluence。
核心能力
- - 架构概览 — 技术栈、系统边界、数据流图
- 关键文件映射 — 哪些文件重要及其原因,附带注释
- 本地设置指南 — 从克隆到运行测试的逐步指导
- 常见开发者任务 — 如何添加路由、运行迁移、创建组件
- 调试指南 — 常见错误、日志位置、有用查询
- 贡献指南 — 分支策略、PR 流程、代码风格
- 受众感知输出 — 初级、高级或承包商模式
使用场景
- - 入职新团队成员或承包商
- 重大重构导致现有文档过时后
- 项目开源前
- 为服务创建团队维基页面
- 长假前进行自我文档化
代码库分析命令
在生成文档前运行这些命令以收集事实:
bash
项目概览
cat package.json | jq {name, version, scripts, dependencies: (.dependencies | keys), devDependencies: (.devDependencies | keys)}
目录结构(前2层)
find . -maxdepth 2 -not -path
/node_modules/ -not -path
/.git/ -not -path
/.next/ | sort | head -60
最大文件(通常是核心模块)
find src/ -name
.ts -not -path /test* -exec wc -l {} + | sort -rn | head -20
所有路由(Next.js App Router)
find app/ -name route.ts -o -name page.tsx | sort
所有路由(Express)
grep -rn router\.\(get\|post\|put\|patch\|delete\) src/routes/ --include=*.ts
近期重大变更
git log --oneline --since=90 days ago | grep -E feat|refactor|breaking
主要贡献者
git shortlog -sn --no-merges | head -10
测试覆盖率摘要
pnpm test:ci --coverage 2>&1 | tail -20
生成文档模板
README.md — 完整模板
markdown
[项目名称]
一句话描述该项目的功能及使用人群。


这是什么?
[2-3句话:解决的问题、使用人群、当前状态]
线上环境: https://myapp.com
预发布环境: https://staging.myapp.com
文档: https://docs.myapp.com
快速开始
前置条件
| 工具 | 版本 | 安装方式 |
|---|
| Node.js | 20+ | nvm install 20 |
| pnpm |
8+ | npm i -g pnpm |
| Docker | 24+ |
docker.com |
| PostgreSQL | 16+ | 通过 Docker(见下文) |
设置(5分钟)
bash
1. 克隆
git clone https://github.com/org/repo
cd repo
2. 安装依赖
pnpm install
3. 启动基础设施
docker compose up -d # 启动 Postgres、Redis
4. 环境变量
cp .env.example .env
编辑 .env — 向团队成员询问实际值或查看 Vault
5. 数据库设置
pnpm db:migrate # 运行迁移
pnpm db:seed # 可选:加载测试数据
6. 启动开发服务器
pnpm dev # → http://localhost:3000
7. 验证
pnpm test # 应全部通过
验证是否正常工作
- - [ ] http://localhost:3000 加载应用
- [ ] http://localhost:3000/api/health 返回 {status:ok}
- [ ] pnpm test 通过
架构
系统概览
浏览器 / 移动端
│
▼
[Next.js 应用] ←──── [认证: NextAuth]
│
├──→ [PostgreSQL](主数据存储)
├──→ [Redis](会话、任务队列)
└──→ [S3](文件上传)
后台:
[BullMQ 工作进程] ←── Redis 队列
└──→ [外部 API: Stripe, SendGrid]
技术栈
| 层 | 技术 | 原因 |
|---|
| 前端 | Next.js 14(App Router) | SSR、基于文件的路由 |
| 样式 |
Tailwind CSS + shadcn/ui | 快速 UI 开发 |
| API | Next.js 路由处理器 | 与前端共存 |
| 数据库 | PostgreSQL 16 | 关系型、支持多租户 RLS |
| ORM | Drizzle ORM | 类型安全、轻量级 |
| 认证 | NextAuth v5 | OAuth + 邮箱/密码 |
| 队列 | BullMQ + Redis | 后台任务 |
| 存储 | AWS S3 | 文件上传 |
| 邮件 | SendGrid | 事务性邮件 |
| 支付 | Stripe | 订阅 |
| 部署 | Vercel(应用)+ Railway(工作进程) | |
| 监控 | Sentry + Datadog | |
关键文件
| 路径 | 用途 |
|---|
| app/ | Next.js App Router — 页面和 API 路由 |
| app/api/ |
API 路由处理器 |
| app/(auth)/ | 认证页面(登录、注册、重置) |
| app/(app)/ | 受保护的应用页面 |
| src/db/ | 数据库模式、迁移、客户端 |
| src/db/schema.ts |
Drizzle 模式 — 单一事实来源 |
| src/lib/ | 共享工具(认证、邮件、Stripe) |
| src/lib/auth.ts |
认证配置 — 首先阅读此文件 |
| src/components/ | 可复用的 React 组件 |
| src/hooks/ | 自定义 React 钩子 |
| src/types/ | 共享 TypeScript 类型 |
| workers/ | BullMQ 后台任务处理器 |
| emails/ | React Email 模板 |
| tests/ | 测试辅助工具、工厂函数、集成测试 |
| .env.example | 所有环境变量及描述 |
| docker-compose.yml | 本地基础设施 |
常见开发者任务
添加新的 API 端点
bash
1. 创建路由处理器
touch app/api/my-resource/route.ts
typescript
// app/api/my-resource/route.ts
import { NextRequest, NextResponse } from next/server
import { auth } from @/lib/auth
import { db } from @/db/client
export async function GET(req: NextRequest) {
const session = await auth()
if (!session) {
return NextResponse.json({ error: 未授权 }, { status: 401 })
}
const data = await db.query.myResource.findMany({
where: (r, { eq }) => eq(r.userId, session.user.id),
})
return NextResponse.json({ data })
}
bash
2. 添加测试
touch tests/api/my-resource.test.ts
3. 添加到 OpenAPI 规范(如适用)
pnpm generate:openapi
运行数据库迁移
bash
创建迁移
pnpm db:generate # 从模式变更生成 SQL
审查生成的 SQL
cat drizzle/migrations/0001
mychange.sql
应用
pnpm db:migrate
回滚(手动 — 检查生成的 SQL 并还原)
psql $DATABASE
URL -f scripts/rollback0001.sql
添加新的邮件模板
bash
1. 创建模板
touch emails/my-email.tsx
2. 在浏览器中预览
pnpm email:preview
3. 在代码中发送
import { sendEmail } from @/lib/email
await sendEmail({