💡 前置阅读推荐:如果你还不了解Claude Code子代理的基础概念,强烈建议先阅读我的上一篇文章《Claude Code子代理完全指南:从0到1构建你的AI编程军团》,它会帮你理解子代理的核心机制和配置方法。
今天要分享的是我精心优化的文档编写子代理——这个配置能让Claude Code像一个专业的技术文档工程师,从API文档到代码注释,从用户手册到架构设计,帮你构建清晰、完整、易维护的文档体系。
写文档不是简单的"描述功能",而是需要系统化的信息架构:
# 场景对比:为一个API编写文档
## ❌ 通用Claude可能给你的文档
### getUserInfo
获取用户信息
参数:id
返回:用户数据
## ✅ 文档子代理会给你的专业文档
/**
* @api {get} /api/v1/users/:id 获取用户详细信息
* @apiVersion 1.0.0
* @apiName GetUserInfo
* @apiGroup User
* @apiDescription 根据用户ID获取完整的用户信息,包含个人资料、权限和偏好设置
*
* @apiPermission authenticated
* @apiHeader {String} Authorization Bearer token (Required)
* @apiHeader {String} [Accept-Language=en] 响应语言偏好
*
* @apiParam {String{uuid}} id 用户唯一标识符
*
* @apiQuery {String="basic","detailed","full"} [fields=basic] 返回字段级别
* @apiQuery {Boolean} [include_metadata=false] 是否包含元数据
*
* @apiSuccess {Object} user 用户对象
* @apiSuccess {String} user.id 用户ID
* @apiSuccess {String} user.email 邮箱地址
* @apiSuccess {String} user.name 用户名称
* @apiSuccess {String} user.role 用户角色
* @apiSuccess {String} user.avatar 头像URL
* @apiSuccess {Object} user.profile 用户资料
* @apiSuccess {String} user.profile.bio 个人简介
* @apiSuccess {String} user.profile.location 所在地
* @apiSuccess {Date} user.createdAt 创建时间
* @apiSuccess {Date} user.updatedAt 更新时间
*
* @apiSuccessExample {json} Success-Response (200):
* HTTP/1.1 200 OK
* {
* "user": {
* "id": "550e8400-e29b-41d4-a716-446655440000",
* "email": "john@example.com",
* "name": "John Doe",
* "role": "admin",
* "avatar": "https://api.example.com/avatars/550e8400.jpg",
* "profile": {
* "bio": "Full-stack developer",
* "location": "San Francisco, CA"
* },
* "createdAt": "2024-01-15T08:00:00Z",
* "updatedAt": "2024-03-20T14:30:00Z"
* }
* }
*
* @apiError UserNotFound 用户不存在
* @apiError Unauthorized 未授权访问
* @apiError InvalidParameter 参数格式错误
*
* @apiErrorExample {json} Error-Response (404):
* HTTP/1.1 404 Not Found
* {
* "error": {
* "code": "USER_NOT_FOUND",
* "message": "The requested user does not exist",
* "details": {
* "id": "550e8400-e29b-41d4-a716-446655440000"
* }
* }
* }
*
* @apiExample {curl} 示例请求:
* curl -X GET "https://api.example.com/api/v1/users/550e8400-e29b-41d4-a716-446655440000" \
* -H "Authorization: Bearer your-token-here" \
* -H "Accept-Language: zh-CN"
*
* @apiExample {javascript} JavaScript:
* const response = await fetch('/api/v1/users/550e8400-e29b-41d4-a716-446655440000', {
* headers: {
* 'Authorization': 'Bearer ' + token
* }
* });
* const data = await response.json();
*
* @apiExample {python} Python:
* import requests
*
* response = requests.get(
* 'https://api.example.com/api/v1/users/550e8400-e29b-41d4-a716-446655440000',
* headers={'Authorization': f'Bearer {token}'}
* )
* user = response.json()
*
* @apiNote 注意事项:
* - 用户ID必须是有效的UUID格式
* - 普通用户只能查询自己的信息,管理员可查询所有用户
* - 响应会根据用户权限自动过滤敏感字段
* - 建议使用缓存,该接口有5分钟的CDN缓存
*
* @apiDeprecated 从v2.0.0开始,请使用 GET /api/v2/users/:id
*
* @apiSampleRequest https://api.example.com/api/v1/users
*/
痛点类型 | 具体问题 | 子代理解决方案 |
---|---|---|
信息缺失 | 文档不完整 | 系统化文档模板 |
更新滞后 | 代码改了文档没改 | 自动同步机制 |
难以理解 | 专业术语太多 | 分层次写作 |
缺少示例 | 不知道怎么用 | 丰富的代码示例 |
格式混乱 | 没有统一标准 | 规范化模板 |
文档就像产品说明书:
文档子代理就像一个专业的技术写作专家,知道如何让复杂的技术变得易懂。
---
name: code-documenter
description: Create comprehensive technical documentation, API docs, and inline code comments. Specializes in documentation generation, maintenance, and accessibility. Use PROACTIVELY for documentation tasks and knowledge management.
model: sonnet
---
You are a technical documentation specialist focused on creating clear, comprehensive, and maintainable documentation for software projects.
## Documentation Expertise
- API documentation with OpenAPI/Swagger specifications
- Code comment standards and inline documentation
- Technical architecture documentation and diagrams
- User guides and developer onboarding materials
- README files with clear setup and usage instructions
- Changelog maintenance and release documentation
- Knowledge base articles and troubleshooting guides
- Video documentation and interactive tutorials
## Documentation Standards
1. Clear, concise writing with consistent terminology
2. Comprehensive examples with working code snippets
3. Version-controlled documentation with change tracking
4. Accessibility compliance for diverse audiences
5. Multi-format output (HTML, PDF, mobile-friendly)
6. Search-friendly structure with proper indexing
7. Regular updates synchronized with code changes
8. Feedback collection and continuous improvement
## Content Strategy
- Audience analysis and persona-based content creation
- Information architecture with logical navigation
- Progressive disclosure for complex topics
- Visual aids integration (diagrams, screenshots, videos)
- Code example validation and testing automation
- Localization support for international audiences
- SEO optimization for discoverability
- Analytics tracking for usage patterns and improvements
## Automation and Tooling
- Documentation generation from code annotations
- Automated testing of code examples in documentation
- Style guide enforcement with linting tools
- Dead link detection and broken reference monitoring
- Documentation deployment pipelines and versioning
- Integration with development workflows and CI/CD
- Collaborative editing workflows and review processes
- Metrics collection for documentation effectiveness
Create documentation that serves as the single source of truth for projects. Focus on clarity, completeness, and maintaining synchronization with codebase evolution while ensuring accessibility for all users.
---
name: code-documenter
description: 创建全面的技术文档、API文档和内联代码注释。专精文档生成、维护和可访问性。在文档任务和知识管理时主动使用。
model: sonnet
---
你是一位技术文档专家,专注于为软件项目创建清晰、全面、可维护的文档。
## 文档专业技能 / Documentation Expertise
- 使用OpenAPI/Swagger规范的API文档
- 代码注释标准和内联文档
- 技术架构文档和图表
- 用户指南和开发者入门材料
- 包含清晰设置和使用说明的README文件
- 变更日志维护和发布文档
- 知识库文章和故障排除指南
- 视频文档和交互式教程
## 文档标准 / Documentation Standards
1. 清晰简洁的写作,术语一致
2. 包含可运行代码片段的全面示例
3. 带变更跟踪的版本控制文档
4. 面向多样化受众的可访问性合规
5. 多格式输出(HTML、PDF、移动友好)
6. 搜索友好的结构和正确的索引
7. 与代码变更同步的定期更新
8. 反馈收集和持续改进
## 内容策略 / Content Strategy
- 受众分析和基于角色的内容创建
- 具有逻辑导航的信息架构
- 复杂主题的渐进式披露
- 视觉辅助集成(图表、截图、视频)
- 代码示例验证和测试自动化
- 国际受众的本地化支持
- 可发现性的SEO优化
- 使用模式和改进的分析跟踪
## 自动化和工具 / Automation and Tooling
- 从代码注释生成文档
- 文档中代码示例的自动测试
- 使用检查工具强制执行样式指南
- 死链接检测和损坏引用监控
- 文档部署管道和版本控制
- 与开发工作流和CI/CD集成
- 协作编辑工作流和审查流程
- 文档有效性的指标收集
创建作为项目唯一真实来源的文档。
专注于清晰性、完整性,并保持与代码库演化的同步,同时确保所有用户的可访问性。
// 1. 什么是API文档?
// 就像餐厅菜单,告诉你有什么菜(接口)和怎么点(调用)
/**
* @api {post} /order 点餐
* @apiParam {String} dish 菜品名称
* @apiParam {Number} quantity 数量
* @apiSuccess {String} orderId 订单号
*/
// 2. 什么是README?
// 就像产品快速入门指南
/*
# 项目名称
## 快速开始
1. 安装:npm install
2. 运行:npm start
3. 访问:http://localhost:3000
*/
// 3. 什么是代码注释?
// 就像给代码加的说明标签
function calculatePrice(items) {
// 遍历所有商品
return items.reduce((total, item) => {
// 价格 = 单价 × 数量 × (1 - 折扣)
return total + item.price * item.quantity * (1 - item.discount);
}, 0);
}
// 4. 什么是架构文档?
// 就像建筑图纸,展示系统是如何搭建的
# 在Claude Code中输入
/agents
选择上面的英文版或中文版配置,完整粘贴
文档编写需要的权限:
建议选择 📘 蓝色(代表知识和文档),保存配置
输入指令:
为我的电商项目生成一个专业的README文档
文档子代理输出:
# 🛍️ E-Commerce Platform
<p align="center">
<img src="docs/images/logo.png" alt="Logo" width="200"/>
</p>
<p align="center">
<a href="https://github.com/yourname/ecommerce/actions">
<img src="https://github.com/yourname/ecommerce/workflows/CI/badge.svg" alt="CI Status">
</a>
<a href="https://codecov.io/gh/yourname/ecommerce">
<img src="https://codecov.io/gh/yourname/ecommerce/branch/main/graph/badge.svg" alt="Coverage">
</a>
<a href="LICENSE">
<img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="License">
</a>
<a href="https://github.com/yourname/ecommerce/releases">
<img src="https://img.shields.io/github/v/release/yourname/ecommerce" alt="Version">
</a>
</p>
<p align="center">
<a href="#features">Features</a> •
<a href="#quick-start">Quick Start</a> •
<a href="#documentation">Documentation</a> •
<a href="#contributing">Contributing</a> •
<a href="#license">License</a>
</p>
## 📋 Table of Contents
- [About](#about)
- [Features](#features)
- [Tech Stack](#tech-stack)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Configuration](#configuration)
- [Usage](#usage)
- [API Documentation](#api-documentation)
- [Testing](#testing)
- [Deployment](#deployment)
- [Contributing](#contributing)
- [License](#license)
- [Contact](#contact)
## 📖 About
A modern, scalable e-commerce platform built with Node.js and React. This platform provides a complete solution for online retail, including product management, shopping cart, payment processing, and order fulfillment.
### 🎯 Key Objectives
- **Performance**: Sub-second page loads with optimized caching
- **Scalability**: Horizontal scaling support for millions of users
- **Security**: PCI DSS compliant payment processing
- **User Experience**: Intuitive interface with mobile-first design
## ✨ Features
### For Customers
- 🛒 **Shopping Cart** - Persistent cart with real-time updates
- 💳 **Secure Checkout** - Multiple payment methods (Credit Card, PayPal, Apple Pay)
- 📦 **Order Tracking** - Real-time shipment tracking
- 👤 **User Profiles** - Order history and saved addresses
- 🔍 **Advanced Search** - Full-text search with filters
- ⭐ **Reviews & Ratings** - Verified purchase reviews
### For Administrators
- 📊 **Analytics Dashboard** - Sales metrics and customer insights
- 📦 **Inventory Management** - Stock tracking and alerts
- 💰 **Payment Processing** - Automated payment reconciliation
- 📧 **Email Automation** - Order confirmations and marketing
- 🎯 **Marketing Tools** - Discount codes and promotions
- 📈 **Reporting** - Customizable business reports
## 🛠️ Tech Stack
### Frontend
- **Framework**: React 18 with TypeScript
- **State Management**: Redux Toolkit
- **Styling**: Tailwind CSS
- **Build Tool**: Vite
- **Testing**: Jest + React Testing Library
### Backend
- **Runtime**: Node.js 20 LTS
- **Framework**: Express.js
- **Database**: PostgreSQL 15 + Redis
- **ORM**: Prisma
- **Authentication**: JWT + OAuth2
### Infrastructure
- **Container**: Docker
- **Orchestration**: Kubernetes
- **CI/CD**: GitHub Actions
- **Monitoring**: Prometheus + Grafana
- **Cloud**: AWS/GCP/Azure
## 📋 Prerequisites
Before you begin, ensure you have the following installed:
- **Node.js** (v20.0.0 or higher) - [Download](https://nodejs.org/)
- **PostgreSQL** (v15.0 or higher) - [Download](https://www.postgresql.org/)
- **Redis** (v7.0 or higher) - [Download](https://redis.io/)
- **Docker** (optional, for containerized deployment) - [Download](https://www.docker.com/)
## 🚀 Installation
### 1. Clone the Repository
\`\`\`bash
git clone https://github.com/yourname/ecommerce.git
cd ecommerce
\`\`\`
### 2. Install Dependencies
\`\`\`bash
# Install backend dependencies
cd backend
npm install
# Install frontend dependencies
cd ../frontend
npm install
\`\`\`
### 3. Set Up Environment Variables
\`\`\`bash
# Copy example environment files
cp backend/.env.example backend/.env
cp frontend/.env.example frontend/.env
# Edit the .env files with your configuration
# See Configuration section for details
\`\`\`
### 4. Initialize Database
\`\`\`bash
cd backend
npm run db:migrate
npm run db:seed # Optional: Load sample data
\`\`\`
### 5. Start Development Servers
\`\`\`bash
# In one terminal - Start backend
cd backend
npm run dev
# In another terminal - Start frontend
cd frontend
npm run dev
\`\`\`
The application will be available at:
- Frontend: http://localhost:3000
- Backend API: http://localhost:8000
- API Documentation: http://localhost:8000/api-docs
## ⚙️ Configuration
### Environment Variables
#### Backend (.env)
\`\`\`env
# Server
NODE_ENV=development
PORT=8000
# Database
DATABASE_URL=postgresql://user:password@localhost:5432/ecommerce
REDIS_URL=redis://localhost:6379
# Authentication
JWT_SECRET=your-secret-key
JWT_EXPIRE=7d
# Payment
STRIPE_SECRET_KEY=sk_test_...
PAYPAL_CLIENT_ID=...
# Email
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASS=your-password
# Storage
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...
AWS_BUCKET_NAME=...
\`\`\`
## 📚 API Documentation
Complete API documentation is available at `/api-docs` when running the server.
### Quick API Examples
#### Authentication
\`\`\`bash
# Register
curl -X POST http://localhost:8000/api/auth/register \\
-H "Content-Type: application/json" \\
-d '{"email":"user@example.com","password":"secure123"}'
# Login
curl -X POST http://localhost:8000/api/auth/login \\
-H "Content-Type: application/json" \\
-d '{"email":"user@example.com","password":"secure123"}'
\`\`\`
#### Products
\`\`\`bash
# Get all products
curl http://localhost:8000/api/products
# Get product by ID
curl http://localhost:8000/api/products/123
\`\`\`
## 🧪 Testing
### Run Tests
\`\`\`bash
# Backend tests
cd backend
npm test # Run all tests
npm run test:unit # Unit tests only
npm run test:e2e # E2E tests only
npm run test:coverage # With coverage
# Frontend tests
cd frontend
npm test
npm run test:coverage
\`\`\`
## 🚢 Deployment
### Docker Deployment
\`\`\`bash
# Build and run with Docker Compose
docker-compose up --build
# Or build individually
docker build -t ecommerce-backend ./backend
docker build -t ecommerce-frontend ./frontend
\`\`\`
### Production Deployment
See [DEPLOYMENT.md](docs/DEPLOYMENT.md) for detailed production deployment instructions.
## 🤝 Contributing
We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.
### Development Process
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
## 📄 License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## 📞 Contact
- **Project Lead**: Your Name - [@yourtwitter](https://twitter.com/yourtwitter)
- **Email**: your.email@example.com
- **Project Link**: [https://github.com/yourname/ecommerce](https://github.com/yourname/ecommerce)
## 🙏 Acknowledgments
- Thanks to all contributors
- Special thanks to [OpenSource Library](https://github.com/library) for inspiration
- Icons from [Font Awesome](https://fontawesome.com)
---
<p align="center">Made with ❤️ by the E-Commerce Team</p>
输入:
为用户管理模块生成Swagger API文档
文档子代理输出:
openapi: 3.0.3
info:
title:UserManagementAPI
description:|
用户管理模块API文档
## 认证方式
所有API使用BearerToken认证,在请求头中添加:
`Authorization:Bearer<token>`
## 错误处理
所有错误响应遵循统一格式
version:1.0.0
contact:
name:APISupport
email:api@example.com
license:
name:MIT
url:https://opensource.org/licenses/MIT
servers:
-url:https://api.example.com/v1
description:ProductionServer
-url:https://staging-api.example.com/v1
description:StagingServer
-url:http://localhost:8000/v1
description:DevelopmentServer
tags:
-name:Authentication
description:用户认证相关接口
-name:Users
description:用户管理接口
-name:Profile
description:用户资料接口
paths:
/auth/register:
post:
summary:用户注册
tags:
-Authentication
requestBody:
required:true
content:
application/json:
schema:
$ref:'#/components/schemas/RegisterRequest'
responses:
'201':
description:注册成功
content:
application/json:
schema:
$ref:'#/components/schemas/AuthResponse'
'400':
$ref:'#/components/responses/BadRequest'
'409':
$ref:'#/components/responses/Conflict'
components:
schemas:
User:
type:object
required:
-id
-email
-name
properties:
id:
type:string
format:uuid
example:"550e8400-e29b-41d4-a716-446655440000"
email:
type:string
format:email
example:"user@example.com"
name:
type:string
minLength:2
maxLength:100
example:"John Doe"
API文档版:
## Documentation Expertise
- OpenAPI 3.0规范
- GraphQL Schema文档
- Postman Collection
- API版本管理
- 示例代码生成
用户手册版:
## Documentation Expertise
- 用户故事编写
- 操作步骤图解
- FAQ整理
- 视频教程脚本
- 快速入门指南
## Team Standards
-文档语言:中英双语
-格式规范:Markdown+AsciiDoc
-图表工具:PlantUML+Mermaid
-版本控制:Git+语义化版本
-审查流程:PRReview必需
触发关键词:
子代理会建议自动化方案:
// 1. 从代码生成文档
// JSDoc -> HTML文档
npm run docs:generate
// 2. 文档测试
// 确保示例代码可运行
npm run docs:test
// 3. CI/CD集成
// 代码变更时自动更新文档
子代理遵循的原则:
评估指标 | 通用Claude | 文档子代理 | 提升幅度 |
---|---|---|---|
完整性 | 60% | 95% | +58% |
可读性 | 65% | 92% | +42% |
示例丰富度 | 40% | 90% | +125% |
更新及时性 | 30% | 85% | +183% |
用户满意度 | 50% | 88% | +76% |
这个文档专家子代理带来的价值:
记住:好的文档是项目成功的一半。代码是写给机器看的,文档是写给人看的。
/agents
创建代理现在就配置你的文档专家子代理,让每份文档都成为知识传承的典范!📚✨
#子代理 #ClaudeCode #AI #程序员 #前端达人