专题:Claude Code 工作流系统学习
关键词:Claude Code, 文档生成, API文档, Swagger, OpenAPI, Sphinx, TypeDoc, JSDoc, README, ADR, C4模型, MkDocs, Confluence, 文档质量
二、API 文档生成
API 文档是开发团队最常需要维护的文档类型之一。Claude Code 支持从多个维度生成 API 文档,包括注释解析、OpenAPI/Swagger 规范生成,以及端点描述与请求响应示例的自动编写。
2.1 注释解析与 OpenAPI 规范生成
Claude Code 可以读取代码中的注释信息,自动生成符合 OpenAPI 3.0 标准的规范文件。以下是一个典型的 Express.js 路由处理器的注释解析示例:
// 提示 Claude Code:为以下 Express 路由生成 OpenAPI 3.0 规范
//
// GET /api/v1/users?page=1&limit=20
// 返回分页用户列表,支持按角色筛选
// 需要 Bearer Token 认证
// 响应格式:{ data: User[], total: number, page: number, limit: number }
app.get('/api/v1/users', authenticate, async (req, res) => {
const { page = 1, limit = 20, role } = req.query;
const filter = role ? { role } : {};
const [data, total] = await Promise.all([
User.find(filter).skip((page - 1) * limit).limit(limit),
User.countDocuments(filter)
]);
res.json({ data, total, page: Number(page), limit: Number(limit) });
});
Claude Code 收到上述提示后,会生成如下的 OpenAPI 规范片段:
openapi: 3.0.3
info:
title: 用户服务 API
version: 1.0.0
description: 提供用户管理与认证功能
paths:
/api/v1/users:
get:
summary: 获取分页用户列表
description: 支持按角色筛选的分页用户查询接口
security:
- bearerAuth: []
parameters:
- name: page
in: query
schema: { type: integer, default: 1 }
description: 页码,从 1 开始
- name: limit
in: query
schema: { type: integer, default: 20 }
description: 每页条数
- name: role
in: query
schema: { type: string, enum: [admin, user, guest] }
description: 按角色筛选用户
responses:
'200':
description: 成功返回用户列表
content:
application/json:
schema:
type: object
properties:
data: { type: array, items: { $ref: '#/components/schemas/User' } }
total: { type: integer }
page: { type: integer }
limit: { type: integer }
2.2 端点描述与请求响应示例
生成规范文件后,Claude Code 还可以为每个端点编写更详细的描述文档,包括请求示例、响应示例和错误码说明。这在团队协作和第三方集成时极为重要。
# 提示 Claude Code:为 POST /api/v1/orders 端点编写详细文档
#
# 请求体:
# { userId: string, items: Array<{ productId: string, quantity: number }>, coupon?: string }
# 响应体:
# 201: { orderId: string, total: number, status: 'pending', createdAt: string }
# 400: { error: string, details: string[] }
# 401: { error: 'Unauthorized' }
# 业务规则:
# - 订单总额超过 500 元自动包邮
# - 优惠券每人限用一张
# - 库存不足时返回 409
Claude Code 会自动生成包含各种场景的完整文档:
## 创建订单
### 功能描述
创建新订单并锁定对应商品库存。支持优惠券抵扣,
订单总额满 500 元自动享受包邮服务。
### 请求示例
```bash
curl -X POST https://api.example.com/api/v1/orders \
-H "Authorization: Bearer <token>" \
-H "Content-Type: application/json" \
-d '{
"userId": "usr_abc123",
"items": [
{ "productId": "prod_001", "quantity": 2 },
{ "productId": "prod_002", "quantity": 1 }
],
"coupon": "SPRING2026"
}'
```
### 成功响应 (201 Created)
```json
{
"orderId": "ord_xyz789",
"total": 458.00,
"shipping": 15.00,
"status": "pending",
"createdAt": "2026-05-08T12:00:00Z",
"estimatedDelivery": "2026-05-12T12:00:00Z"
}
```
### 错误响应
| 状态码 | 错误场景 | 说明 |
|--------|----------|------|
| 400 | 库存不足 | body.items 中列出库存不足的商品 ID |
| 400 | 优惠券无效 | 优惠券已过期或不符合使用条件 |
| 401 | 未认证 | 缺少或 Bearer Token 无效 |
| 409 | 重复请求 | 相同幂等键已存在订单 |
最佳实践:建议在代码仓库中维护一个 prompts/ 目录,存放常用的文档生成提示模板。这样团队成员可以复用标准化的提示,确保生成的文档风格一致。同时,结合 CI/CD 流水线,在每次 API 变更时自动触发文档重新生成。
三、代码文档生成
代码文档(docstring/注释)是开发者最常接触的文档形式。Claude Code 能够分析代码结构,自动生成符合行业标准的文档注释,支持 Python(Sphinx/reST/Google/Numpy 风格)、TypeScript/JavaScript(TypeDoc/JSDoc)、Java(Javadoc)等多种格式。
3.1 Python Docstring 生成(Sphinx/Google 风格)
以下是一个 Python 机器学习工具函数,Claude Code 可为其生成完整的 Google 风格 docstring:
# 原始代码(无注释)
def train_ensemble_model(models, X_train, y_train, X_val, y_val,
weights=None, stacking_meta=None):
results = {}
for name, model in models.items():
model.fit(X_train, y_train)
preds = model.predict(X_val)
score = accuracy_score(y_val, preds)
results[name] = {'model': model, 'score': score, 'predictions': preds}
if stacking_meta:
stack_preds = np.column_stack([r['predictions'] for r in results.values()])
meta_model = stacking_meta.fit(stack_preds, y_val)
results['stacking'] = {'model': meta_model, 'score': accuracy_score(
y_val, meta_model.predict(stack_preds))}
if weights:
weighted_preds = np.average(
[r['predictions'] for r in results.values()],
weights=weights, axis=0)
final_score = accuracy_score(y_val, weighted_preds)
results['weighted_ensemble'] = {'predictions': weighted_preds, 'score': final_score}
return results
Claude Code 生成的 Google 风格 docstring:
def train_ensemble_model(models, X_train, y_train, X_val, y_val,
weights=None, stacking_meta=None):
"""训练集成模型并评估各基学习器与集成策略的性能。
遍历所有基模型进行独立训练与验证集评估。可选地执行 stacking
元学习器训练或加权集成,返回各模型的评估结果。
Args:
models (dict[str, BaseEstimator]): 基学习器字典,
键为模型名称,值为未训练的 scikit-learn 估计器实例。
X_train (np.ndarray): 训练集特征矩阵,形状 (n_samples, n_features)。
y_train (np.ndarray): 训练集标签向量,形状 (n_samples,)。
X_val (np.ndarray): 验证集特征矩阵,形状 (n_val_samples, n_features)。
y_val (np.ndarray): 验证集标签向量,形状 (n_val_samples,)。
weights (list[float] | None): 各基模型的加权集成权重。
长度必须与 models 中模型数量一致,且和为 1.0。
stacking_meta (BaseEstimator | None): Stacking 元学习器实例。
如提供,则使用基模型在验证集上的预测作为特征训练元模型。
Returns:
dict[str, dict]: 包含各模型评估结果的字典,每个条目的结构为:
- 'model': 已训练的模型实例
- 'score': 验证集准确率 (float)
- 'predictions': 验证集预测值 (np.ndarray)
当启用 stacking 时增加 'stacking' 键;
当启用加权集成时增加 'weighted_ensemble' 键。
Raises:
ValueError: 当 weights 长度与 models 数量不一致时抛出。
ValueError: 当 weights 之和不为 1.0 时抛出(容差 1e-6)。
"""
# ... 函数体保持不变 ...
3.2 TypeScript/JSDoc 与 TypeDoc
对于 TypeScript 项目,Claude Code 可以生成兼容 TypeDoc 的 JSDoc 注释,并自动推断泛型类型参数:
// 提示 Claude Code:为以下 TypeScript 函数添加 JSDoc 注释,
// 兼容 TypeDoc 生成,需包含类型参数说明、泛型约束、以及复杂返回类型的文档
interface PaginatedResult<T> {
data: T[];
total: number;
page: number;
limit: number;
hasMore: boolean;
}
async function paginatedQuery<T extends Document>(
model: Model<T>,
filter: FilterQuery<T>,
options: { page?: number; limit?: number; sort?: Record<string, 1 | -1>; populate?: string[] }
): Promise<PaginatedResult<T>> {
const page = options.page ?? 1;
const limit = Math.min(options.limit ?? 20, 100);
const skip = (page - 1) * limit;
const query = model.find(filter).skip(skip).limit(limit);
if (options.sort) query.sort(options.sort);
if (options.populate) options.populate.forEach(f => query.populate(f));
const [data, total] = await Promise.all([query.exec(), model.countDocuments(filter)]);
return { data, total, page, limit, hasMore: skip + limit < total };
}
Claude Code 生成的 TypeDoc 兼容注释:
/**
* 执行分页数据库查询,返回标准化分页结果。
*
* 自动处理页码越界、限制最大返回条数(100),
* 并支持关联表填充(populate)与排序。
*
* @typeParam T - Mongoose 文档类型,需继承自 Document 接口。
* @param model - Mongoose 模型类,用于构建查询。
* @param filter - MongoDB 查询筛选条件(FilterQuery<T>)。
* @param options - 查询选项对象。
* @param options.page - 页码,从 1 开始,默认为 1。
* @param options.limit - 每页条数,最大 100,默认为 20。
* @param options.sort - 排序规则,如 `{ createdAt: -1 }`。
* @param options.populate - 需要填充的关联字段名称数组。
*
* @returns 标准化分页结果,包含数据数组、总数、当前页、每页条数及是否有更多页。
*
* @throws 当 model.find 或 model.countDocuments 抛出数据库连接异常时向上传播。
*
* @example
* ```typescript
* const result = await paginatedQuery(UserModel, { role: 'admin' }, {
* page: 1, limit: 10, sort: { createdAt: -1 }, populate: ['profile']
* });
* console.log(result.data); // User[]
* ```
*/
Sphinx/TypeDoc 集成提示:Claude Code 生成的注释遵守各工具的严格语法要求。对于 Sphinx,使用 reStructuredText 格式时可添加 `:param:`、`:type:`、`:returns:`、`:raises:` 等字段指令。对于 TypeDoc,确保 `@param`、`@returns` 等标签后跟标准类型表达式,以保证生成的 HTML 文档类型链接正确。
四、README 生成
README 是项目的门面,直接影响开发者的第一印象和采用意愿。Claude Code 可以根据项目结构、依赖配置和代码特征,自动生成结构完整、内容详实的中英文 README 文件。
4.1 从项目结构推断 README 内容
向 Claude Code 提供项目的目录结构和关键配置文件,即可生成针对性的 README:
项目结构:
my-fastapi-service/
├── app/
│ ├── main.py # FastAPI 应用入口,包含路由注册与生命周期
│ ├── routers/
│ │ ├── users.py # 用户 CRUD 路由
│ │ └── orders.py # 订单路由
│ ├── models/
│ │ ├── user.py # SQLAlchemy User 模型
│ │ └── order.py # SQLAlchemy Order 模型
│ ├── schemas/
│ │ ├── user.py # Pydantic 请求/响应模式
│ │ └── order.py # Pydantic 订单模式
│ ├── services/
│ │ ├── auth.py # JWT 认证逻辑
│ │ └── payment.py # 支付网关集成
│ └── core/
│ ├── config.py # 环境变量配置(pydantic-settings)
│ └── database.py # 数据库会话管理
├─ tests/
├─ Dockerfile
├─ docker-compose.yml
├─ pyproject.toml # 依赖管理(Poetry)
└─ alembic/ # 数据库迁移
# 提示 Claude Code:基于以上项目结构,
# 生成完整的英文 README.md,包含:
# - 项目描述与徽章
# - 快速开始(Docker / Poetry)
# - API 文档链接
# - 环境变量说明表
# - 测试与贡献指南
Claude Code 生成的 README 核心部分:
# My FastAPI Service
[](https://github.com/user/my-fastapi-service/actions)
[](https://www.python.org/downloads/)
[](https://fastapi.tiangolo.com)
[](https://github.com/astral-sh/ruff)
Production-ready order management API built with FastAPI,
featuring JWT authentication, SQLAlchemy async ORM, and
Stripe payment integration.
## Quick Start
### Docker (Recommended)
```bash
docker compose up -d
# Service available at http://localhost:8000
# API docs at http://localhost:8000/docs
```
### Local Development
```bash
# Install dependencies
poetry install
# Copy environment variables
cp .env.example .env
# Run database migrations
poetry run alembic upgrade head
# Start development server
poetry run uvicorn app.main:app --reload --port 8000
```
## Environment Variables
| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `DATABASE_URL` | Yes | - | PostgreSQL connection string |
| `JWT_SECRET` | Yes | - | HMAC key for JWT signing |
| `STRIPE_API_KEY` | No | - | Stripe secret key (required for payments) |
| `REDIS_URL` | No | `redis://localhost:6379` | Redis cache connection |
| `LOG_LEVEL` | No | `INFO` | Python logging level |
## Project Structure
```
app/
├── routers/ # HTTP route handlers
├── models/ # SQLAlchemy ORM models
├── schemas/ # Pydantic request/response models
├── services/ # Business logic layer
└── core/ # Configuration & infrastructure
```
## API Documentation
Once the service is running, interactive API documentation is
available at `/docs` (Swagger UI) and `/redoc` (ReDoc).
Auto-generated OpenAPI spec at `/openapi.json`.
## Testing
```bash
# Run all tests
poetry run pytest
# Run with coverage
poetry run pytest --cov=app --cov-report=term-missing
# Run specific test file
poetry run pytest tests/test_orders.py -v
```
4.2 许可证选择与贡献指南
Claude Code 可以根据项目类型和用户需求推荐合适的开源许可证,并自动生成贡献指南(CONTRIBUTING.md),包括提交信息规范、PR 流程、编码风格要求等。
# 提示 Claude Code:
# 为我的开源项目生成 CONTRIBUTING.md
#
# 项目信息:
# - 语言: Go
# - 类型: CLI 工具(类似 kubectl 的数据库管理工具)
# - 许可证: Apache 2.0
# - 构建工具: Makefile
# - 测试框架: Go built-in testing + testify
# - CI: GitHub Actions
#
# 要求包含:
# - PR 流程(fork 工作流)
# - Commit 消息规范(Conventional Commits)
# - 代码风格(gofumpt + golangci-lint)
# - 本地开发环境搭建
# - 测试要求
生成的贡献指南片段:
# Contributing to dbctl
## Development Setup
```bash
# Fork and clone the repository
git clone https://github.com/YOUR_USERNAME/dbctl.git
cd dbctl
# Install dependencies
go mod download
# Install development tools
make install-tools # gofumpt, golangci-lint, gotestsum
# Build from source
make build
```
## Commit Message Convention
We follow [Conventional Commits](https://www.conventionalcommits.org/):
```
<type>(<scope>): <description>
[optional body]
[optional footer]
```
Types: `feat` | `fix` | `docs` | `style` | `refactor` | `test` | `chore`
Examples:
```
feat(executor): add PostgreSQL connection pool
fix(parser): handle trailing semicolons in multi-line SQL
docs(readme): update installation instructions
```
## Pull Request Process
1. Create a feature branch from `main`: `git checkout -b feat/my-feature`
2. Make changes and ensure all tests pass: `make test`
3. Run linter: `make lint`
4. Update documentation if needed
5. Open a PR with a clear title and description
6. Ensure CI checks pass before requesting review
提示:生成 README 时,建议先运行项目的测试套件,将测试输出提供给 Claude Code。这样生成的 README 可以在"示例"部分包含真实可验证的运行输出,而非手写的伪代码。
五、架构文档生成
架构文档记录了系统设计决策与组件关系,是大型项目的必备资产。Claude Code 可以帮助生成架构决策记录(ADR)、系统架构图描述(C4 模型),以及组件依赖与数据流图。
5.1 ADR 架构决策记录
ARD(Architecture Decision Record)是一种轻量级的架构决策文档化方法。Claude Code 可以根据团队讨论或问题描述生成结构化的 ADR:
# 提示 Claude Code:为我生成 ADR 文档
#
# 背景:我们的电商平台目前使用单体 MySQL 数据库,
# 随着订单量增长(日均 5 万笔),读负载成为瓶颈。
# 团队讨论了两个方案:
#
# 方案 A:MySQL 读写分离(主从复制)
# - 优点:变更小,MySQL 原生支持
# - 缺点:只能扩展读,写仍然是单点
#
# 方案 B:引入 CQRS + 事件溯源
# - 命令端:写入 PostgreSQL(保持不变)
# - 查询端:写入 Elasticsearch,支持复杂搜索
# - 事件总线:RabbitMQ
# - 优点:读写独立扩展、支持复杂查询
# - 缺点:架构复杂度增加、需要处理最终一致性
#
# 决定选择方案 B,请生成完整的 ADR-0003
Claude Code 生成的 ADR:
# ADR-0003: 采用 CQRS 模式分离读写模型
## 状态
已接受 · 2026-04-15
## 上下文
电商平台订单表日均写入约 5 万行,但查询量超过 100 万次。
大量查询涉及跨表聚合、全文搜索和复杂过滤条件,
导致 MySQL 单库的读负载持续升高(CPU 使用率 > 75%)。
当前 MySQL 主从读写分离方案(ADR-0001)已无法满足搜索需求。
## 决策
采用 CQRS(Command Query Responsibility Segregation)模式,
将写入路径与查询路径分离:
- 命令端(Command Side):保留 PostgreSQL 作为写入存储,
确保事务完整性(ACID)。
- 查询端(Query Side):引入 Elasticsearch 作为查询存储,
支持全文搜索与复杂聚合。
- 数据同步:通过 RabbitMQ 事件总线将写入事件异步同步到查询端。
- 最终一致性:接受写入后短时(< 500ms)的查询不一致,
通过前端乐观 UI 更新补偿。
## 后果
### 正面
- 读写负载可独立水平扩展
- 支持订单全文搜索、多维度聚合分析
- 查询性能预计提升 10-20 倍
### 负面
- 引入最终一致性,部分查询场景需处理延迟
- 团队需要学习 Elasticsearch 查询语法
- 运维复杂度增加(新增 RabbitMQ、ES 集群)
### 风险
- 事件丢失风险:通过 RabbitMQ 的 publisher confirm +
消费者手动 ack 机制保证至少一次投递
- 数据不一致风险:通过定时对账任务(每 15 分钟)检测
并修复写端与读端的数据差异
5.2 C4 模型与系统架构图
C4 模型(Context / Container / Component / Code)是描述软件架构的分层方法。Claude Code 可以生成 C4 模型的文本描述,再配合工具(如 Structurizr、PlantUML)生成可视化图表。
// 提示 Claude Code:为以下微服务系统生成 C4 模型描述
//
// 系统:在线支付平台
// 包含以下容器:
// 1. Web App (React + TypeScript)
// 2. API Gateway (Kong)
// 3. Payment Service (Go, gRPC)
// 4. Account Service (Go, gRPC)
// 5. Notification Service (Node.js, Kafka consumer)
// 6. PostgreSQL (主数据库)
// 7. Redis (会话缓存)
// 8. Kafka (事件总线)
//
// 外部系统:银行网关、短信服务商(Twilio)
Claude Code 会生成如下结构化描述:
## System Context (C1)
[系统] 在线支付平台 --[使用]--> [外部] 银行网关
[系统] 在线支付平台 --[通知]--> [外部] 短信服务 (Twilio)
[用户] 商户 --[操作]--> [系统] 在线支付平台
[用户] 消费者 --[支付]--> [系统] 在线支付平台
## Container Diagram (C2)
[Web App] React SPA (TypeScript)
- 提供商家后台与消费者支付页面
- 通过 HTTPS/REST 调用 API Gateway
[API Gateway] Kong Gateway
- 路由分发、限流、认证鉴权
- 上游指向 gRPC 服务
[Payment Service] Go gRPC Server
- 处理支付创建、确认、退款
- 调用银行网关完成资金交易
- 写入 PostgreSQL (orders 表)
- 发布 PaymentEvents 到 Kafka
[Account Service] Go gRPC Server
- 管理商户账户余额、结算
- 写入 PostgreSQL (accounts 表)
- 消费 Kafka 中的 PaymentEvents
[Notification Service] Node.js Kafka Consumer
- 消费 PaymentEvents 发送短信/邮件通知
- 调用 Twilio API
[PostgreSQL] 主数据库
- 存储订单、账户、交易记录
[Redis] 会话缓存
- 存储登录 session、分布式锁
[Kafka] 事件总线
- PaymentEvents topic: payment.created, payment.confirmed, payment.refunded
5.3 组件依赖与数据流图
对于单个服务内部,Claude Code 可以分析代码依赖关系,生成组件级文档和数据流说明:
# 提示 Claude Code:分析以下 Go 代码的依赖关系,
# 生成 data flow 文档
// payment/service.go
type Service struct {
repo Repository
bankGW BankGateway
publisher EventPublisher
cache Cache
}
func (s *Service) ProcessPayment(ctx context.Context, req PaymentRequest) (*PaymentResult, error) {
// 1. 幂等性检查
existing, err := s.cache.Get(ctx, idempotencyKey(req.IdempotencyKey))
if existing != nil { return existing, nil }
// 2. 锁账户
lock, err := s.cache.Lock(ctx, "account:"+req.AccountID, 5*time.Second)
defer lock.Release()
// 3. 验证余额
account, err := s.repo.GetAccount(ctx, req.AccountID)
if account.Balance < req.Amount { return nil, ErrInsufficientBalance }
// 4. 调用银行网关
result, err := s.bankGW.Charge(ctx, req.CardToken, req.Amount, req.Currency)
// 5. 更新数据库
payment := &Payment{AccountID: req.AccountID, Amount: req.Amount, Status: "completed"}
s.repo.Save(ctx, payment)
// 6. 发布事件
s.publisher.Publish(ctx, "payment.completed", payment)
// 7. 设置幂等缓存
s.cache.Set(ctx, idempotencyKey(req.IdempotencyKey), result, 24*time.Hour)
return result, nil
}
生成的数据流文档:
## ProcessPayment 数据流
### 输入
- PaymentRequest { IdempotencyKey, AccountID, CardToken, Amount, Currency }
### 步骤与数据流向
```
┌──────────────────────────────────────────────────┐
│ Service.ProcessPayment │
│ │
Request ──→ ① Read Cache ──→ ② Lock ──→ ③ Read DB ──→ ④ Bank ──→ ⑤ Write DB ──→ ⑥ Pub Event ──→ ⑦ Set Cache ──→ Result
│
└── Account.Balance ≥ Amount?
否 ──→ ErrInsufficientBalance
```
### 依赖组件
| 组件 | 用途 | 失败影响 | 重试策略 |
|-------------|----------------------|---------------------|------------------|
| Cache | 幂等性 + 分布式锁 | 重复支付风险 | 立即重试 × 3 |
| Repository | 账户余额 + 订单持久化 | 支付失败 | 指数退避 × 5 |
| BankGateway | 外部银行扣款 | 支付失败,用户需重试 | 无(业务决定) |
| Publisher | 事件通知 | 下游服务状态不一致 | 持久化重试队列 |
六、Wiki 与内部文档
除代码仓库内的文档外,团队通常还需要维护 Wiki(GitHub Wiki / Confluence)或静态站点(MkDocs / Docusaurus)。Claude Code 可以在这些平台上批量创建、更新文档,并保持与代码的同步。
6.1 GitHub Wiki 批量创建与更新
GitHub Wiki 本质上是 Git 仓库(项目名.wiki.git),Claude Code 可以直接操作 Wiki 仓库,批量创建和更新页面:
# 提示 Claude Code:为我的项目创建 GitHub Wiki
#
# 项目:https://github.com/myuser/data-pipeline
# 技术栈:Apache Spark, Airflow, Delta Lake, dbt
#
# 需要创建以下 Wiki 页面:
# 1. Home - 项目概述与架构
# 2. Pipeline-Architecture - 各 pipeline 的 DAG 说明
# 3. Data-Models - 数据模型定义与血缘关系
# 4. Deployment - 部署步骤与环境配置
# 5. Troubleshooting - 常见问题与排查方法
#
# 可以从代码仓库的 README、docstrings、Dockerfile、
# Airflow DAG 文件中提取信息
Claude Code 会读取已有的代码文件,提取关键信息,然后依次创建 Wiki 页面。以下是 Pipeline-Architecture 页面的生成示例:
# Pipeline Architecture
## Overview
We run 4 main data pipelines orchestrated by Apache Airflow
on a daily schedule. All pipelines write to Delta Lake tables
in the Bronze → Silver → Gold medallion architecture.
## Pipeline 1: Ingestion (Bronze)
**DAG:** `ingestion_dag` | **Schedule:** Daily 02:00 UTC | **Duration:** ~45 min
Reads raw data from source APIs (Stripe, Google Analytics, PostgreSQL CDC)
and writes to `bronze.*` Delta tables with minimal transformation.
```python
# dags/ingestion_dag.py (key structure)
with DAG("ingestion_dag", schedule="0 2 * * *"):
for source in ["stripe", "ga4", "cdc"]:
ingest = PythonOperator(task_id=f"ingest_{source}", ...)
validate = PythonOperator(task_id=f"validate_{source}", ...)
ingest >> validate
```
## Pipeline 2: Transformation (Silver)
**DAG:** `transformation_dag` | **Schedule:** Daily 04:00 UTC | **Duration:** ~2 h
Applies data cleansing, deduplication, and type casting.
Uses Spark Structured Streaming for near-real-time paths.
## Pipeline 3: Aggregation (Gold)
**DAG:** `aggregation_dag` | **Schedule:** Daily 07:00 UTC | **Duration:** ~1.5 h
Computes business metrics (DAU, MRR, churn rate, LTV) using
dbt models running on Spark. Models defined in `/dbt/models/gold/`.
## Pipeline 4: Data Quality
**DAG:** `data_quality_dag` | **Schedule:** Daily 09:00 UTC | **Duration:** ~20 min
Runs Great Expectations suites against Gold tables and sends
Slack alerts on quality check failures.
6.2 Confluence 与 MkDocs 站点生成
对于使用 Confluence 的企业团队,Claude Code 可以通过 Confluence REST API 批量创建和更新页面。对于更倾向于 Docs as Code 的团队,Claude Code 能够生成 MkDocs 或 Docusaurus 格式的 Markdown 文件:
# 提示 Claude Code:为我的微服务项目生成 MkDocs 站点
#
# 项目包含 6 个微服务,每个在 /services/ 目录下
# 每个服务包含:
# - README.md
# - openapi.yaml
# - CHANGELOG.md
# - docs/ 目录(含架构说明、配置说明)
#
# 需要:
# 1. 生成 mkdocs.yml 配置文件
# 2. 创建 docs/index.md 作为站点首页
# 3. 为每个服务生成独立的文档页面
# 4. 自动从各服务的 README 提取核心内容
# 5. 配置导航结构(嵌套目录)
# 6. 启用 mermaid 插件支持图表渲染
Claude Code 生成的 mkdocs.yml:
site_name: 微服务平台文档
site_description: 微服务平台技术文档 - 架构、API、部署指南
repo_url: https://github.com/myorg/microservice-platform
edit_uri: edit/main/docs/
theme:
name: material
language: zh
features:
- navigation.tabs
- navigation.sections
- navigation.expand
- content.code.copy
plugins:
- search
- mermaid2
- macros
markdown_extensions:
- pymdownx.highlight
- pymdownx.superfences:
custom_fences:
- name: mermaid
class: mermaid
format: !!python/name:mermaid2.fence_mermaid
- pymdownx.tabbed
- admonition
- toc:
permalink: true
nav:
- 首页: index.md
- 架构概览: architecture/overview.md
- 服务文档:
- 用户服务 (users): services/users.md
- 订单服务 (orders): services/orders.md
- 支付服务 (payments): services/payments.md
- 通知服务 (notifications): services/notifications.md
- 库存服务 (inventory): services/inventory.md
- 分析服务 (analytics): services/analytics.md
- 部署指南: deployment/guide.md
- API 参考: api/overview.md
- 常见问题: troubleshooting/faq.md
6.3 知识库自动更新
Claude Code 可以监听代码仓库的变更事件,在 PR 合并后自动更新相关 Wiki 或 MkDocs 页面。这保证了文档与代码始终同步,避免"文档过期"这个最常见的问题。
# .github/workflows/docs-auto-update.yml
name: Auto Update Documentation
on:
pull_request:
types: [closed]
branches: [main]
jobs:
update-docs:
if: github.event.pull_request.merged == true
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Analyze PR changes
id: analyze
run: |
echo "Changed services:" >> $GITHUB_OUTPUT
# 检测变更涉及的服务目录
git diff --name-only ${{ github.event.before }}..${{ github.event.after }} \
| grep '^services/' | cut -d'/' -f2 | sort -u
- name: Generate updated docs
run: |
# Claude Code 自动分析变更并更新对应文档
claude --prompt "
PR #${{ github.event.number }} 已合并到 main。
变更文件:$(git diff --name-only ${{ github.event.before }}..${{ github.event.after }})
请更新 mkdocs 站点中对应服务的文档页面。
"
- name: Build and deploy MkDocs
run: |
mkdocs build
mkdocs gh-deploy --force
七、文档质量检查
生成文档后,质量检查是不可或缺的环节。Claude Code 可以执行拼写检查、链接验证、术语一致性检查、版本同步检查以及内容过时检测等任务,确保文档的专业性和准确性。
7.1 拼写检查与术语一致性
对于中英文混合的技术文档,Claude Code 可以识别拼写错误,并检查术语使用是否符合项目规范:
# 提示 Claude Code:检查以下文档中的拼写错误和术语一致性
#
# 项目术语表:
# - "用户" 不应写成 "使用者"
# - "部署" 不应写成 "部属"
# - "Kubernetes" 不应写成 "k8s" 或 "kubernates"
# - "微服务" 统一使用,不用 "微型服务"
# - "API" 统一大写,不用 "api"(代码块除外)
# - "前端" / "后端" 统一使用,不用 "前台" / "后台"
#
# 需要检查的文档:docs/**, wiki/**, README.md
Claude Code 会逐文件扫描并报告发现的问题:
## 拼写与术语检查报告
### 拼写错误
| 文件 | 位置 | 原文 | 建议 |
|------|------|------|------|
| docs/deploy.md:45 | 第3段 | Kubernates | Kubernetes |
| README.md:12 | 标题 | 微型服务架构 | 微服务架构 |
| services/users/README.md:78 | - | 使用者认证流程 | 用户认证流程 |
### 术语不一致
| 文件 | 术语 | 出现 | 应统一为 |
|------|------|------|----------|
| docs/architecture/overview.md:120 | api网关 | 3次 | API网关 |
| docs/architecture/overview.md:201 | API 网关 | 2次 | API网关 |
| wiki/Troubleshooting.md:34 | 前台应用 | 1次 | 前端应用 |
### 建议修复命令
```bash
# 批量替换
sed -i 's/Kubernates/Kubernetes/g' docs/deploy.md
sed -i 's/微型服务/微服务/g' README.md
sed -i 's/\bapi网关\b/API网关/g' docs/architecture/overview.md
sed -i 's/前台应用/前端应用/g' wiki/Troubleshooting.md
```
7.2 链接检查与版本同步
文档中的链接失效或引用版本与实际不符是常见问题。Claude Code 可以递归扫描文档目录,验证所有内部链接和外部链接的有效性,并检查代码示例中的版本号是否与当前项目一致:
# 提示 Claude Code:检查 docs/ 目录下所有文档的
# 1. 内部链接有效性(指向同一仓库内其他 .md 文件的链接)
# 2. 代码示例中的版本号是否与当前项目一致
# 3. API 端点与 openapi.yaml 定义是否匹配
#
# 当前项目版本:v2.5.1(记录在 pyproject.toml 中)
# 可用的 API 定义:openapi/openapi.yaml
生成的检查报告:
## 文档质量检查报告
### 1. 链接检查
| 状态 | 链接 | 文件 |
|------|------|------|
| ❌ 404 | `../api/v1/orders.md` | docs/guides/quickstart.md:42 |
| ❌ 404 | `https://example.com/deprecated` | docs/deployment/guide.md:88 |
| ✅ 有效 | `../architecture/overview.md` | docs/guides/quickstart.md:15 |
| ✅ 有效 | `https://fastapi.tiangolo.com/` | README.md:30 |
### 2. 版本同步
| 文件 | 引用版本 | 当前版本 | 状态 |
|------|----------|----------|------|
| README.md:5 | v2.4.0 | v2.5.1 | ❌ 过期 |
| docs/deploy.md:12 | 2.5.x | 2.5.1 | ✅ 一致 |
| docs/changelog.md | 包含 v2.5.1 | v2.5.1 | ✅ 一致 |
### 3. API 一致性
| 端点 | 文档 | openapi.yaml | 状态 |
|------|------|-------------|------|
| POST /api/v1/orders | 已描述 | 已定义 | ✅ 匹配 |
| GET /api/v1/users | 已描述 | 已定义 | ✅ 匹配 |
| PATCH /api/v1/orders/{id} | 已描述 | 未定义 | ❌ 缺少定义 |
| DELETE /api/v1/users/{id} | 未描述 | 已定义 | ⚠️ 缺少文档 |
7.3 过时检测与自动修复
Claude Code 可以比较代码库的最新状态与文档内容,自动标注过时的描述、示例或截图,并提出修复建议。这是保持文档长期可用的关键能力:
# 提示 Claude Code:检测 docs/ 目录下的文档是否过时
#
# 检测规则:
# 1. 文档中的代码示例与源码中对应函数的签名是否一致
# 2. 文档中引用的配置字段是否在当前默认配置中存在
# 3. 文档中描述的 CLI 命令参数是否与当前 --help 输出一致
# 4. 文档中引用的环境变量名是否在 .env.example 中存在
过时检测报告示例:
## 过时检测报告
### 1. 代码签名变更
| 文档 | 行 | 文档中的签名 | 实际签名 |
|------|----|-------------|----------|
| docs/api/users.md:55 | `get_user(id)` | `get_user(user_id: UUID)` | |
| docs/examples/batch.py:12 | `process(data, config)` | `process(data, config, timeout=30)` | |
### 2. 配置变更
| 文档 | 已移除的配置 | 新增的配置(未文档化) |
|------|-------------|----------------------|
| docs/config.md | `debug_mode` (v2.4 移除) | `log_format` |
| docs/config.md | `db_pool_size` (已弃用) | `db.max_connections` |
### 3. CLI 命令变更
| 文档 | 命令 | 状态 |
|------|------|------|
| docs/cli.md:22 | `dbctl deploy --env` | ❌ 参数已改为 `--environment` |
| docs/cli.md:45 | `dbctl rollback --version` | ✅ 完全匹配 |
### 自动修复建议
```bash
# 修复 README 中的 API 示例
sed -i 's/get_user(id)/get_user(user_id: UUID)/g' docs/api/users.md
sed -i 's/process(data, config)/process(data, config, timeout=30)/g' docs/examples/batch.py
```
注意:过时检测不能完全自动化地进行全局替换。每个变更点都需要人工确认,特别是当文档中的描述与代码行为的差异是有意为之(如描述了设计变更的过渡期)时。建议将过时检测报告作为工单(issue)提交,由文档负责人逐条确认后修改。
八、最佳实践总结
综合以上六大文档生成场景,以下是在实际项目中应用 Claude Code 文档工作流的最佳实践总结:
1. 模板先行:为每类文档准备标准化的提示模板(prompt template),存储在项目仓的 .claude/prompts/ 目录中。团队成员使用统一模板,保证生成风格一致。
2. 迭代生成:不要期望一次生成完美文档。先生成大綱(outline),再逐节填充,最后做质量检查。Claude Code 支持多轮对话式修改。
3. 上下文充分:提供充分的上下文信息:项目结构、关键代码片段、已有文档样例、术语表。上下文越充分,生成结果越准确。
4. CI/CD 集成:将文档生成与质量检查集成到 CI/CD 流水线。PR 合并时自动更新 API 文档,定时运行过时检测。
5. 人工审核:所有自动生成的文档必须经过人工审核。特别是 ADR 等架构决策文档,需要架构师确认技术准确性。
6. 版本管理:文档和代码同源管理(monorepo 或同步分支),确保文档变更和代码变更绑定,方便回溯。
7. 渐进式采纳:从 README 生成和 docstring 补全这两个收益最高的场景开始,逐步扩展到 ADR、Wiki 等场景。
推荐学习路径
| 阶段 | 场景 | 工具/格式 | 预期收益 |
| 第一阶段 | README 生成 | Markdown | 项目入口文档标准化 |
| 第二阶段 | Docstring 补全 | Sphinx/TypeDoc/JSDoc | 代码可读性提升 |
| 第三阶段 | API 文档生成 | OpenAPI/Swagger | 前后端协作效率提升 |
| 第四阶段 | 架构文档 | ADR / C4 模型 | 架构决策可追溯 |
| 第五阶段 | Wiki 与内部文档 | MkDocs / Confluence | 团队知识库完善 |
| 第六阶段 | 质量自动化 | CI/CD 集成 | 文档可持续维护 |
"写文档不是写一次就完事,而是一个持续的过程。好的文档工作流,应该让写文档像写代码一样自然,让文档与代码同寿。"
通过 Claude Code 的文档生成工作流,团队可以将文档维护的工作量降低 60% 以上,同时显著提升文档质量。关键在于建立正确的流程规范,充分发挥 AI 在信息提取、格式转换和一致性检查方面的优势,同时保留人类在技术判断、架构决策和内容审核中的核心角色。