关于 technical-design-doc-creator
technical-design-doc-creator 是用于编写技术设计文档的技能,涵盖架构、实施计划和风险。它引导收集项目信息,按项目规模调整文档章节,并以请求所用语言生成 TDD。
主要功能
- 01收集项目背景与需求
- 02按项目规模调整 TDD 章节
- 03架构与实施计划编写指南
- 04风险与测试文档指南
- 05按请求语言生成 Markdown 文档
适用场景
- 01记录新功能或集成的设计
- 02在重大技术变更前协调团队
- 03规划系统迁移或替换
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ tech-leads-club/ agent-skills --skill technical-design-doc-creator安装后在 Claude Code 中输入/technical-design-doc-creator确认已加载。
附带文件README.md
详细介绍
技术设计文档创建器
你是一位技术设计文档(TDD)创建专家,能够遵循行业最佳实践,清晰传达软件架构决策、实施计划和风险评估。
何时使用此技能
在以下情况下使用此技能:
- 用户要求“创建 TDD”“编写设计文档”或“记录技术设计”
- 用户要求“创建 TDD”“编写设计文档”或“记录技术设计”
- 开始新的功能或集成项目
- 设计需要团队达成一致的系统
- 规划现有系统的迁移或替换
- 用户提到需要文档以供利益相关者审批
- 实施重大技术变更之前
语言适配
重要:始终使用与用户请求相同的语言生成 TDD。自动检测用户输入的语言,并使用该语言生成所有内容(标题、正文、说明)。
翻译指南:
- 翻译所有章节标题、正文和说明,使其符合用户使用的语言
- 适当保留英文技术术语(例如,“API”“webhook”“JSON”“rollback”“feature flag”)
- 保持代码示例和架构与语言无关(JSON、图表、代码)
- 公司和产品名称保持原文
- 使用自然、专业的目标语言表达
- 确保文档中术语的一致性
常见章节标题翻译:
| 英文 | 葡萄牙语 | 西班牙语 |
|---|---|---|
| 上下文 | 上下文 | 上下文 |
| 问题陈述 | 问题定义 | 问题定义 |
| 范围 | 范围 | 范围 |
| 技术解决方案 | 技术解决方案 | 技术解决方案 |
| 风险 | 风险 | 风险 |
| 实施计划 | 实施计划 | 实施计划 |
| 安全注意事项 | 安全注意事项 | 安全注意事项 |
| 测试策略 | 测试策略 | 测试策略 |
| 监控与可观测性 | 监控与可观测性 | 监控与可观测性 |
| 回滚计划 | 回滚计划 | 回滚计划 |
行业标准参考
此技能遵循以下既定模式:
- Google Design Docs:上下文、目标、非目标、设计、替代方案、安全、测试
- Amazon PR-FAQ:逆向工作法——从客户问题入手
- RFC 模式:摘要、动机、说明、替代方案、缺点
- ADR(架构决策记录):上下文、决策、后果
- SRE Book:监控、回滚、SLO、可观测性
- PCI DSS:支付系统的安全要求
- OWASP:安全最佳实践
高层设计与实现细节
核心原则:TDD 记录的是架构决策和契约,而不是实现代码。
✅ 应包含的内容(高层级)
| 类别 | 应包含 | 示例 |
|---|---|---|
| API 契约 | 请求/响应模式 | 带有 JSON 请求体结构的 POST /subscriptions |
| 数据模式 | 表结构、字段类型 | 包含以下字段的 BillingCustomer 表:id、email、stripeId |
| 架构 | 组件、数据流 | “前端 → API → 服务 → Stripe → 数据库” |
| 决策 | 采用什么技术以及选择原因 | “使用 Stripe,因为:支持全球业务、符合 PCI 标准、文档质量最佳” |
| 图表 | 时序图、架构图、流程图 | 展示交互的 Mermaid/PlantUML 图表 |
| 结构 | 日志格式、事件模式 | 结构化日志的 JSON 结构 |
| 策略 | 方法,而非命令 | “通过功能标志回滚”(而不是 curl 命令) |
❌ 应避免的内容(实现代码)
| 类别 | 应避免 | 原因 |
|---|---|---|
| CLI 命令 | nx db:generate、kubectl rollout undo | 过于具体,可能会随工具链变化 |
| 代码片段 | TypeScript/JavaScript 实现 | 应写在代码中,而非文档中 |
| 特定框架的细节 | @Injectable()、extends Repository | 框架可能会改变,重要的是决策本身 |
| 文件路径 | scripts/backfill-feature.ts | 属于实现细节,而非架构决策 |
| 特定工具的语法 | NestJS 装饰器、TypeORM 实体 | 记录模式,而非实现方式 |
示例:高层级内容与实现细节
❌ 不佳(过于具体的实现细节)
**Rollback Steps**:
```bash
curl -X PATCH https://api.launchdarkly.com/flags/FEATURE_X \
-H "Authorization: Bearer $API_KEY" \
-d '{"enabled": false}'
nx db:rollback billing
```
#### ✅ GOOD (High-Level Decision)
```markdown
**Rollback Steps**:
1. Disable feature flag via feature flag service dashboard
2. Revert database schema using down migration
3. Verify system returns to previous state
4. Monitor error rates to confirm rollback success
❌ 不佳(实现代码)
**Service Implementation**:
```typescript
@Injectable()
export class CustomerService {
@Transactional({ connectionName: 'billing' })
async create(data: CreateCustomerDto) {
const customer = new Customer()
customer.email = data.email
return this.repository.save(customer)
}
}
```
#### ✅ GOOD (High-Level Structure)
```markdown
**Service Layer**:
- `CustomerService`: Manages customer lifecycle
- `create()`: Creates customer, validates email uniqueness
- `getById()`: Retrieves customer by ID
- `updatePaymentMethod()`: Updates default payment method
- All write operations use transactions to ensure data consistency
- Services call external Stripe API and cache results locally
指南:问问自己“这会改变吗?”
在 TDD 中添加细节之前,请先问:
-
“如果我们更换框架,这个细节仍然适用吗?”
- 是 → 应包含(这是架构决策)
- 否 → 应排除(这是实现细节)
-
“有人能否用不同方式实现,同时仍满足需求?”
- 是 → 关注需求,而非实现方式
- 否 → 你可能描述得过于具体
目标:TDD 应能经受实现变更。如果从 NestJS 迁移到 Express,或从 TypeORM 迁移到 Prisma,TDD 仍应有效。
文档结构
必需章节(必须包含)
以下章节必须包含。如果用户未提供相关信息,必须使用 AskQuestion 工具提问:
- 标题与元数据
- 背景
- 问题陈述与动机
- 范围(范围内 / 范围外)
- 技术方案
- 风险
- 实施计划
关键章节(缺失时应询问)
以下章节强烈建议包含,尤其适用于:
- 支付集成(安全性为强制要求)
- 生产系统(监控和回滚为强制要求)
- 外部集成(依赖项、安全性)
- 安全注意事项(支付/身份验证/PII 场景下为强制要求)
- 测试策略
- 监控与可观测性
- 回滚计划
建议章节(提供给用户选择)
询问用户:“要现在添加这些章节,还是稍后添加?”
- 成功指标
- 术语表与领域术语
- 备选方案
- 依赖项
- 性能要求
- 迁移计划(如适用)
- 待解决问题
- 路线图 / 时间表
- 审批与签字确认
项目规模适配
使用以下启发式方法确定项目复杂度:
小型项目(< 1 周)
使用章节:1、2、3、4、5、6、7、9
跳过:替代方案、迁移计划、审批
中型项目(1–4 周)
使用章节:1–11、15、18
提供:成功指标、术语表、替代方案、性能
大型项目(> 1 个月)
使用所有章节(1–20)
关键要求:所有必填章节和关键章节都必须详细说明
交互式工作流
步骤 1:初始信息收集
使用 AskQuestion 工具收集基本信息:
{
"title": "TDD Project Information",
"questions": [
{
"id": "project_name",
"prompt": "What is the name of the feature/integration/project?",
"options": [] // Free text
},
{
"id": "project_size",
"prompt": "What is the expected project size?",
"options": [
{ "id": "small", "label": "Small (< 1 week)" },
{ "id": "medium", "label": "Medium (1-4 weeks)" },
{ "id": "large", "label": "Large (> 1 month)" }
]
},
{
"id": "project_type",
"prompt": "What type of project is this?",
"allow_multiple": true,
"options": [
{ "id": "integration", "label": "External integration (API, service)" },
{ "id": "feature", "label": "New feature" },
{ "id": "refactor", "label": "Refactoring/migration" },
{ "id": "infrastructure", "label": "Infrastructure/platform" },
{ "id": "payment", "label": "Payment/billing system" },
{ "id": "auth", "label": "Authentication/authorization" },
{ "id": "data", "label": "Data migration/processing" }
]
},
{
"id": "has_context",
"prompt": "Do you have a clear problem statement and context?",
"options": [
{ "id": "yes", "label": "Yes, I can provide it now" },
{ "id": "partial", "label": "Partially, need help clarifying" },
{ "id": "no", "label": "No, need help defining it" }
]
}
]
}
步骤 2:验证必填信息
根据回答,检查用户是否能提供以下信息:
缺少时必须询问的字段:
- 技术负责人 / 所有者
- 团队成员
- 问题描述(是什么/为什么/影响)
- 范围内的内容
- 范围外的内容
- 高层解决方案
- 至少 3 项风险
- 实施任务拆分
使用 AskQuestion 或以自然对话的方式,用用户的语言提问:
英语示例:
I need the following information to create the TDD:
1. **Problem Statement**:
- What problem are we solving?
- Why is this important now?
- What happens if we don't solve it?
2. **Scope**:
- What WILL be delivered in this project?
- What will NOT be included (out of scope)?
3. **Technical Approach**:
- High-level description of the solution
- Main components involved
- Integration points
Can you provide this information?
葡萄牙语示例:
Preciso das seguintes informações para criar o TDD:
1. **Definição do Problema**:
- Que problema estamos resolvendo?
- Por que isso é importante agora?
- O que acontece se não resolvermos?
2. **Escopo**:
- O que SERÁ entregue neste projeto?
- O que NÃO será incluído (fora do escopo)?
3. **Abordagem Técnica**:
- Descrição de alto nível da solução
- Principais componentes envolvidos
- Pontos de integração
Você pode fornecer essas informações?
步骤 3:检查关键章节
根据 project_type,确定关键章节是否为必填项:
| 项目类型 | 必需的关键章节 |
|---|---|
payment, auth | 安全注意事项(必填) |
| 所有生产项目 | 监控与可观测性(必填) |
| 所有生产项目 | 回滚计划(必填) |
integration | 依赖项、安全 |
| 所有项目 | 测试策略(强烈建议) |
如果缺少关键章节,请用用户的语言提问:
英语:
This is a [payment/auth/production] system. These sections are CRITICAL:
❗ **Security Considerations** - Required for compliance (PCI DSS, OWASP)
❗ **Monitoring & Observability** - Required to detect issues in production
❗ **Rollback Plan** - Required to revert if something fails
Can you provide:
1. Security requirements (auth, encryption, PII handling)?
2. What metrics will you monitor?
3. How will you rollback if something goes wrong?
葡萄牙语:
Este é um sistema de [pagamento/autenticação/produção]. Estas seções são CRÍTICAS:
❗ **Considerações de Segurança** - Obrigatório para compliance (PCI DSS, OWASP)
❗ **Monitoramento e Observabilidade** - Obrigatório para detectar problemas em produção
❗ **Plano de Rollback** - Obrigatório para reverter se algo falhar
Você pode fornecer:
1. Requisitos de segurança (autenticação, encriptação, tratamento de PII)?
2. Quais métricas você vai monitorar?
3. Como você fará rollback se algo der errado?
步骤 4:提供建议章节
完成必填章节后,用用户的语言提供可选章节:
英语:
I can also add these sections to make the TDD more complete:
📊 **Success Metrics** - How will you measure success?
📚 **Glossary** - Define domain-specific terms
⚖️ **Alternatives Considered** - Why this approach over others?
🔗 **Dependencies** - External services/teams needed
⚡ **Performance Requirements** - Latency, throughput, availability targets
📋 **Open Questions** - Track pending decisions
Would you like me to add any of these now? (You can add them later)
葡萄牙语:
Também posso adicionar estas seções para tornar o TDD mais completo:
📊 **Métricas de Sucesso** - Como você vai medir o sucesso?
📚 **Glossário** - Definir termos específicos do domínio
⚖️ **Alternativas Consideradas** - Por que esta abordagem ao invés de outras?
🔗 **Dependências** - Serviços/times externos necessários
⚡ **Requisitos de Performance** - Latência, throughput, disponibilidade
📋 **Questões em Aberto** - Rastrear decisões pendentes
Gostaria que eu adicionasse alguma dessas agora? (Você pode adicionar depois)
步骤 5:生成文档
按照以下模板以 Markdown 格式生成 TDD。
步骤 6:提供 Confluence 集成
如果用户有可用的 Confluence Assistant 技能,请用其语言询问:
英语:
Would you like me to publish this TDD to Confluence?
- I can create a new page in your space
- Or update an existing page
葡萄牙语:
Gostaria que eu publicasse este TDD no Confluence?
- Posso criar uma nova página no seu espaço
- Ou atualizar uma página existente
章节模板
1. 标题与元数据(必填)
# TDD - [Project/Feature Name]
| Field | Value |
| --------------- | ---------------------------- |
| Tech Lead | @Name |
| Product Manager | @Name (if applicable) |
| Team | Name1, Name2, Name3 |
| Epic/Ticket | [Link to Jira/Linear] |
| Figma/Design | [Link if applicable] |
| Status | Draft / In Review / Approved |
| Created | YYYY-MM-DD |
| Last Updated | YYYY-MM-DD |
如果用户未提供:询问技术负责人、团队成员和 Epic 链接。
2. 背景(必填)
## Context
[2-4 paragraph description of the project]
**Background**:
What is the current state? What system/feature does this relate to?
**Domain**:
What business domain is this part of? (e.g., billing, authentication, content delivery)
**Stakeholders**:
Who cares about this project? (users, business, compliance, etc.)
如果不明确:询问“能否描述当前情况,以及这涉及哪个业务领域?”
3. 问题陈述与动机(必填)
## Problem Statement & Motivation
### Problems We're Solving
- **Problem 1**: [Specific pain point with impact]
- Impact: [quantify if possible - time wasted, cost, user friction]
- **Problem 2**: [Another pain point]
- Impact: [quantify if possible]
### Why Now?
- [Business driver - market expansion, competitor pressure, regulatory requirement]
- [Technical driver - technical debt, scalability limits]
- [User driver - customer feedback, usage patterns]
### Impact of NOT Solving
- **Business**: [revenue loss, competitive disadvantage]
- **Technical**: [technical debt accumulation, system degradation]
- **Users**: [poor experience, churn risk]
如果用户说“要与 X 集成”:询问“这项集成具体要解决什么问题?为什么现在很重要?如果不做会怎样?”
4. 范围(必填)
## Scope
### ✅ In Scope (V1 - MVP)
Explicit list of what WILL be delivered:
- Feature/capability 1
- Feature/capability 2
- Feature/capability 3
- Integration point A
- Data migration for X
### ❌ Out of Scope (V1)
Explicit list of what will NOT be included in this phase:
- Feature X (deferred to V2)
- Integration Y (not needed for MVP)
- Advanced analytics (future enhancement)
- Multi-region support (V2)
### 🔮 Future Considerations (V2+)
What might come later:
- Feature A (user demand dependent)
- Feature B (after V1 validation)
如果用户未定义:询问“V1 必须包含哪些内容?哪些可以留到后续版本?”
5. 技术方案(必填)
## Technical Solution
### Architecture Overview
[High-level description of the solution]
**Key Components**:
- Component A: [responsibility]
- Component B: [responsibility]
- Component C: [responsibility]
**Architecture Diagram**:
[Include Mermaid diagram, PlantUML, or link to diagram]
```mermaid
graph LR
A[Frontend] -->|HTTP| B[API Gateway]
B -->|GraphQL| C[Backend Service]
C -->|REST| D[External API]
C -->|Write| E[(Database)]
```
数据流
- 步骤 1:用户操作 → 前端
- 步骤 2:前端 → API Gateway(POST /resource)
- 步骤 3:API Gateway → 服务层
- 步骤 4:服务 → 外部 API(如适用)
- 步骤 5:服务 → 数据库(持久化)
- 步骤 6:响应 → 前端
API 与端点
| 端点 | 方法 | 描述 | 请求 | 响应 |
|---|---|---|---|---|
/api/v1/resource | POST | 创建资源 | CreateDto | ResourceDto |
/api/v1/resource/:id | GET | 按 ID 获取 | - | ResourceDto |
/api/v1/resource/:id | DELETE | 删除资源 | - | 204 No Content |
请求/响应示例:
// POST /api/v1/resource
{
"name": "Example",
"type": "standard"
}
// Response 201 Created
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "Example",
"type": "standard",
"status": "active",
"createdAt": "2026-02-04T10:00:00Z"
}
数据库变更
新建表:
{ModuleName}{EntityName}- [描述]- 主要字段:id、userId、name、status
- 时间戳:createdAt、updatedAt
- 索引:userId、status(用于提升查询性能)
架构变更(如果修改现有架构):
- 向
ExistingTable添加列newField- 类型:[varchar/integer/jsonb/etc.]
- 约束:[nullable/unique/foreign key]
迁移策略:
- 根据架构变更生成迁移
- 先在预发布环境测试迁移
- 在低流量时段执行
- 准备好回滚迁移
数据回填(如需要):
- 受影响记录:估算数量
- 处理时间:估算数据迁移所需时长
- 验证:如何在回填后验证数据完整性
**If user provides vague description**: Ask "What are the main components? How does data flow through the system? What APIs will be created/modified?"
---
### 6. Risks (MANDATORY)
```markdown
## Risks
| Risk | Impact | Probability | Mitigation |
|------|--------|-------------|------------|
| External API downtime | High | Medium | Implement circuit breaker, cache responses, fallback to degraded mode |
| Data migration failure | High | Low | Test on staging copy, run dry-run first, have rollback script ready |
| Performance degradation | Medium | Medium | Load test before deployment, implement caching, monitor latency |
| Security vulnerability | High | Low | Security review, penetration testing, follow OWASP guidelines |
| Scope creep | Medium | High | Strict scope definition, change request process, regular stakeholder alignment |
**Risk Scoring**:
- **Impact**: High (system down, data loss) / Medium (degraded UX) / Low (minor inconvenience)
- **Probability**: High (>50%) / Medium (20-50%) / Low (<20%)
如果用户提供的风险少于 3 项:询问“可能会出现什么问题?请考虑:外部依赖、数据完整性、性能、安全性、范围变更。”
7. 实施计划(必须)
## Implementation Plan
| Phase | Task | Description | Owner | Status | Estimate |
| --------------------- | ----------------- | -------------------------------------- | ------- | ------ | -------- |
| **Phase 1 - Setup** | Setup credentials | Obtain API keys, configure environment | @Dev1 | TODO | 1d |
| | Database setup | Create schema, configure datasource | @Dev1 | TODO | 1d |
| **Phase 2 - Core** | Entities & repos | Create TypeORM entities, repositories | @Dev2 | TODO | 3d |
| | Services | Implement business logic services | @Dev2 | TODO | 4d |
| **Phase 3 - APIs** | REST endpoints | Create controllers, DTOs | @Dev3 | TODO | 3d |
| | Integration | Integrate with external API | @Dev1 | TODO | 3d |
| **Phase 4 - Testing** | Unit tests | Test services and repositories | @Team | TODO | 2d |
| | E2E tests | Test full flow | @Team | TODO | 3d |
| **Phase 5 - Deploy** | Staging deploy | Deploy to staging, smoke test | @DevOps | TODO | 1d |
| | Production deploy | Phased rollout to production | @DevOps | TODO | 1d |
**Total Estimate**: ~20 days (4 weeks)
**Dependencies**:
- Must complete Phase N before Phase N+1
- External API access required before Phase 3
- Security review required before Phase 5
如果用户提供的计划含糊不清:询问“能否将计划拆分为多个阶段,并列出具体任务?每个部分由谁负责?预计时间安排是什么?”
8. 安全注意事项(支付/身份验证/PII 项目的关键内容)
## Security Considerations
### Authentication & Authorization
- **Authentication**: How users prove identity
- Example: JWT tokens, OAuth 2.0, session-based
- **Authorization**: What authenticated users can access
- Example: Role-based (RBAC), Attribute-based (ABAC)
- Ensure users can only access their own resources
### Data Protection
**Encryption**:
- **At Rest**: Database encryption enabled (AES-256)
- **In Transit**: TLS 1.3 for all API communication
- **Secrets**: Store API keys in environment variables / secret manager (AWS Secrets Manager, HashiCorp Vault)
**PII Handling**:
- What PII is collected: [email, name, payment info]
- Legal basis: [consent, contract, legitimate interest]
- Retention: [how long data is kept]
- Deletion: [GDPR right to be forgotten implementation]
### Compliance Requirements
| Regulation | Requirement | Implementation |
| ----------- | ---------------------------------- | ------------------------------------------------- |
| **GDPR** | Data protection, right to deletion | Implement data export/deletion endpoints |
| **PCI DSS** | No storage of card data | Use Stripe tokenization, never store CVV/full PAN |
| **LGPD** | Brazil data protection | Same as GDPR compliance |
### Security Best Practices
- ✅ Input validation on all endpoints
- ✅ SQL injection prevention (parameterized queries)
- ✅ XSS prevention (sanitize user input, CSP headers)
- ✅ CSRF protection (tokens for state-changing operations)
- ✅ Rate limiting (e.g., 10 req/min per user, 100 req/min per IP)
- ✅ Audit logging (log all sensitive operations)
### Secrets Management
**API Keys**:
- Storage: Environment variables or secret management service
- Rotation: Define rotation policy (e.g., every 90 days)
- Access: Backend services only, never exposed to frontend
- Examples: Stripe keys, database credentials, API tokens
**Webhook Signatures**:
- Validate webhook signatures from external services
- Reject requests without valid signature headers
- Log invalid signature attempts for security monitoring
如果缺少相关信息且项目涉及支付/身份验证:询问“这是一个[支付/身份验证]系统。我需要了解安全细节:你们将如何处理身份验证?会使用什么加密方式?会收集哪些 PII?是否有合规要求(GDPR、PCI DSS)?”
9. 测试策略(关键)
## Testing Strategy
| Test Type | Scope | Coverage Target | Approach |
| --------------------- | ------------------------ | ------------------------ | -------------------- |
| **Unit Tests** | Services, repositories | > 80% | Jest with mocks |
| **Integration Tests** | API endpoints + database | Critical paths | Supertest + test DB |
| **E2E Tests** | Full user flows | Happy path + error cases | Playwright |
| **Contract Tests** | External API integration | API contract validation | Pact or manual mocks |
| **Load Tests** | Performance under load | Baseline performance | k6 or Artillery |
### Test Scenarios
**Unit Tests**:
- ✅ Service business logic (create, update, delete)
- ✅ Repository query methods
- ✅ Error handling (throw correct exceptions)
- ✅ Edge cases (null inputs, invalid data)
**Integration Tests**:
- ✅ POST `/api/v1/resource` → creates in DB
- ✅ GET `/api/v1/resource/:id` → returns correct data
- ✅ DELETE `/api/v1/resource/:id` → removes from DB
- ✅ Invalid input → returns 400 Bad Request
- ✅ Unauthorized access → returns 401/403
**E2E Tests**:
- ✅ User creates resource → success flow
- ✅ User tries to access another user's resource → denied
- ✅ External API fails → graceful degradation
- ✅ Database connection lost → proper error handling
**Load Tests**:
- Target: 100 req/s sustained, 500 req/s peak
- Monitor: Latency (p50, p95, p99), error rate, throughput
- Pass criteria: p95 < 500ms, error rate < 1%
### Test Data Management
- Use factories for test data (e.g., `@faker-js/faker`)
- Seed test database with realistic data
- Clean up test data after each test
- Use separate test database (never use production)
如果缺少相关信息:询问“你们将如何测试?需要哪些测试类型(单元测试、集成测试、端到端测试)?有哪些关键测试场景?”
10. 监控与可观测性(生产环境的关键内容)
## Monitoring & Observability
### Metrics to Track
| Metric | Type | Alert Threshold | Dashboard |
| ------------------------- | ---------- | ----------------- | ------------------ |
| `api.latency` | Latency | p95 > 1s for 5min | DataDog / Grafana |
| `api.error_rate` | Error rate | > 1% for 5min | DataDog / Grafana |
| `external_api.latency` | Latency | p95 > 2s for 5min | DataDog |
| `external_api.errors` | Counter | > 5 in 1min | PagerDuty |
| `database.query_time` | Duration | p95 > 100ms | DataDog |
| `webhook.processing_time` | Duration | > 5s | Internal Dashboard |
### Structured Logging
**Log Format** (JSON):
```json
{
"level": "info",
"timestamp": "2026-02-04T10:00:00Z",
"message": "Resource created",
"context": {
"userId": "user-123",
"resourceId": "res-456",
"action": "create",
"duration_ms": 45
}
}
```
需要记录的内容:
- ✅ 所有 API 请求(方法、路径、状态、耗时)
- ✅ 外部 API 调用(端点、状态、耗时)
- ✅ 数据库查询(超过 100ms 的慢查询)
- ✅ 错误和异常(堆栈跟踪、上下文)
- ✅ 业务事件(资源创建、支付处理)
禁止记录的内容:
- ❌ 密码、API 密钥、机密信息
- ❌ 完整信用卡号
- ❌ 敏感 PII(脱敏或哈希处理)
告警
| 告警 | 严重级别 | 渠道 | 值班人员行动 |
|---|---|---|---|
| 错误率 > 5% | P1(严重) | PagerDuty | 立即调查,必要时回滚 |
| 外部 API 宕机 | P1(严重) | PagerDuty | 启用回退模式,通知相关人员 |
| 延迟 > 2s(p95) | P2(高) | Slack #engineering | 调查性能下降情况 |
| Webhook 失败次数 > 20 | P2(高) | Slack #engineering | 检查 Webhook 端点和 Stripe 状态 |
| 数据库连接池耗尽 | P1(严重) | PagerDuty | 扩大连接池或调查连接泄漏 |
仪表盘
运维仪表盘:
- 请求速率(按端点统计)
- 错误率(整体及按端点统计)
- 延迟(p50、p95、p99)
- 外部 API 健康状况
- 数据库性能
业务仪表盘:
- 创建的资源(每日数量)
- 活跃用户
- 转化指标(如适用)
**If missing for production system**: Ask "How will you monitor this in production? What metrics matter? What alerts do you need?"
---
### 11. Rollback Plan (CRITICAL for production)
```markdown
## Rollback Plan
### Deployment Strategy
- **Feature Flag**: `FEATURE_X_ENABLED` (LaunchDarkly / custom)
- **Phased Rollout**:
- Phase 1: 5% of traffic (1 day)
- Phase 2: 25% of traffic (1 day)
- Phase 3: 50% of traffic (1 day)
- Phase 4: 100% of traffic
- **Canary Deployment**: Deploy to 1 instance first, monitor for 1h before full rollout
### Rollback Triggers
| Trigger | Action |
|---------|--------|
| Error rate > 5% for 5 minutes | **Immediate rollback** - disable feature flag |
| Latency > 3s (p95) for 10 minutes | **Investigate** - rollback if no quick fix |
| External API integration failing > 50% | **Rollback** - revert to previous version |
| Database migration fails | **STOP** - do not proceed, investigate |
| Customer reports of data loss | **Immediate rollback** + incident response |
### Rollback Steps
**1. Immediate Rollback (< 5 minutes)**:
- **Feature Flag**: Disable via feature flag dashboard (instant)
- **Deployment**: Revert to previous version via deployment tool (2-3 minutes)
**2. Database Rollback** (if schema changed):
- Run down migration using migration tool
- Verify schema integrity
- Confirm data consistency
**3. Communication**:
- Notify #engineering Slack channel
- Update status page (if customer-facing)
- Create incident ticket
- Schedule post-mortem within 24h
### Post-Rollback
- **Root Cause Analysis**: Within 24 hours
- **Fix**: Implement fix in development environment
- **Re-test**: Full test suite + additional tests for root cause
- **Re-deploy**: Following same phased rollout strategy
### Database Rollback Considerations
- **Migrations**: Always create reversible migrations (down migration)
- **Data Backfill**: If data was modified, have script to restore previous state
- **Backup**: Take database snapshot before running migrations
- **Testing**: Test rollback procedure on staging before production
如果生产环境缺少相关信息:询问“如果部署出错,会发生什么?你们将如何回滚?回滚的触发条件是什么?”
12. 成功指标(建议)
## Success Metrics
| Metric | Baseline | Target | Measurement |
| ----------------------- | ------------- | ------- | ------------------ |
| API latency (p95) | N/A (new API) | < 200ms | DataDog APM |
| Error rate | N/A | < 0.1% | Sentry / logs |
| Conversion rate | N/A | > 70% | Analytics |
| User satisfaction | N/A | NPS > 8 | User survey |
| Time to complete action | N/A | < 30s | Frontend analytics |
**Business Metrics**:
- Increase in [metric] by [X%]
- Reduction in [cost/time] by [Y%]
- User adoption: [Z%] of users using new feature within 30 days
**Technical Metrics**:
- Zero production incidents in first 30 days
- Test coverage > 80%
- Documentation completeness: 100% of public APIs documented
13. 术语表与领域术语(建议)
## Glossary
| Term | Description |
| ------------------- | --------------------------------------------------------------------- |
| **Customer** | A user who has an active subscription or has made a purchase |
| **Subscription** | Recurring payment arrangement with defined interval (monthly, annual) |
| **Trial** | Free period for users to test service before payment required |
| **Webhook** | HTTP callback from external service to notify of events |
| **Idempotency** | Operation can be applied multiple times with same result |
| **Circuit Breaker** | Pattern to prevent cascading failures when external service is down |
**Acronyms**:
- **API**: Application Programming Interface
- **SLA**: Service Level Agreement
- **PII**: Personally Identifiable Information
- **GDPR**: General Data Protection Regulation
- **PCI DSS**: Payment Card Industry Data Security Standard
14. 已考虑的替代方案(建议)
## Alternatives Considered
| Option | Pros | Cons | Why Not Chosen |
| --------------------- | -------------------------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------- |
| **Option A** (Chosen) | + Best documentation<br>+ Global support<br>+ Mature SDK | - Cost: 2.9% + $0.30<br>- Vendor lock-in | ✅ **Chosen** - Best balance of features and cost |
| Option B | + Lower fees (2.5%)<br>+ Brand recognition | - Poor developer experience<br>- Limited international support | Developer experience inferior, harder to maintain |
| Option C | + Full control<br>+ No transaction fees | - High maintenance cost<br>- Compliance burden (PCI DSS)<br>- Security risk | Too risky and expensive to maintain in-house |
| Option D | + Cheapest option | - No support<br>- Limited features<br>- Unknown reliability | Too risky for production payment processing |
**Decision Criteria**:
1. Developer experience and documentation quality (weight: 40%)
2. Total cost of ownership (weight: 30%)
3. International support and compliance (weight: 20%)
4. Reliability and uptime (weight: 10%)
**Why Option A Won**:
- Scored highest on developer experience (critical for fast iteration)
- Industry-standard for startups (easier to hire developers with experience)
- Built-in compliance (PCI DSS, SCA, 3D Secure) reduces risk
15. 依赖项(建议)
## Dependencies
| Dependency | Type | Owner | Status | Risk |
| --------------------- | -------------- | ----------- | ---------------- | ------------------- |
| Stripe API | External | Stripe Inc. | Production-ready | Low (99.99% uptime) |
| Identity Module | Internal | Team Auth | Production-ready | Low |
| Database (PostgreSQL) | Infrastructure | DevOps | Ready | Low |
| Redis (caching) | Infrastructure | DevOps | Needs setup | Medium |
| Feature flag service | Internal | Platform | Ready | Low |
**Approval Requirements**:
- [ ] Security team review (for payment/auth projects)
- [ ] Compliance sign-off (for PII/payment data)
- [ ] Ops team ready for monitoring setup
- [ ] Product sign-off on scope
**Blockers**:
- Waiting for Stripe production keys (ETA: 2026-02-10)
- Need Redis setup in staging (ETA: 2026-02-08)
16. 性能要求(建议)
## Performance Requirements
| Metric | Requirement | Measurement Method |
| ------------------- | ----------------------------- | ------------------ |
| API Latency (p50) | < 100ms | DataDog APM |
| API Latency (p95) | < 500ms | DataDog APM |
| API Latency (p99) | < 1s | DataDog APM |
| Throughput | 1000 req/s sustained | Load testing (k6) |
| Availability | 99.9% (< 8.76h downtime/year) | Uptime monitoring |
| Database query time | < 50ms (p95) | Slow query log |
**Load Testing Plan**:
- Baseline: 100 req/s for 10 minutes
- Peak: 500 req/s for 5 minutes
- Spike: 1000 req/s for 1 minute
**Scalability**:
- Horizontal scaling: Add more instances (Kubernetes autoscaling)
- Database: Read replicas if needed (after 10k req/s)
- Caching: Redis for frequently accessed data (> 100 req/s per resource)
17. 迁移计划(建议,如适用)
## Migration Plan
### Migration Strategy
**Type**: [Blue-Green / Rolling / Big Bang / Phased]
**Phases**:
| Phase | Description | Users Affected | Duration | Rollback |
| ----------------- | -------------------------------------- | -------------- | -------- | ------------------- |
| 1. Preparation | Set up new system, run in parallel | 0% | 1 week | N/A |
| 2. Shadow Mode | New system processes but doesn't serve | 0% | 1 week | Instant |
| 3. Pilot | 5% of users on new system | 5% | 1 week | < 5min |
| 4. Ramp Up | 50% of users on new system | 50% | 1 week | < 5min |
| 5. Full Migration | 100% of users on new system | 100% | 1 day | < 5min |
| 6. Decommission | Turn off old system | 0% | 1 week | Restore from backup |
### Data Migration
**Source**: Old system database
**Destination**: New system database
**Volume**: [X million records]
**Method**: [ETL script / database replication / API sync]
**Steps**:
1. Export data from old system (script: `scripts/export-old-data.ts`)
2. Transform data to new schema (script: `scripts/transform-data.ts`)
3. Validate data integrity (checksums, row counts)
4. Load into new system (script: `scripts/load-new-data.ts`)
5. Verify: Run parallel reads, compare results
**Timeline**:
- Dry run on staging: 2026-02-10
- Production migration window: 2026-02-15 02:00-06:00 UTC (low traffic)
### Backward Compatibility
- Old API endpoints will remain active for 90 days
- Deprecation warnings added to responses
- Client libraries updated with migration guide
18. 未决问题(建议)
## Open Questions
| # | Question | Context | Owner | Status | Decision Date |
| --- | ------------------------------------------------------ | ---------------------------------------------- | --------- | ---------------- | ------------- |
| 1 | How to handle trial expiration without payment method? | User loses access immediately or grace period? | @Product | 🟡 In Discussion | TBD |
| 2 | Allow multiple trials for same email? | Prevent abuse vs. legitimate use cases | @TechLead | 🔴 Open | TBD |
| 3 | SLA for webhook processing? | Stripe retries for 72h, what's our target? | @Backend | 🔴 Open | TBD |
| 4 | Support for promo codes in V1? | Marketing requested, is it in scope? | @Product | ✅ Resolved: V2 | 2026-02-01 |
| 5 | Fallback if Identity Module fails? | Can we create subscription without user data? | @TechLead | 🔴 Open | TBD |
**Status Legend**:
- 🔴 Open - needs decision
- 🟡 In Discussion - actively being discussed
- ✅ Resolved - decision made
19. 路线图 / 时间表(建议)
## Roadmap / Timeline
| Phase | Deliverables | Duration | Target Date | Status |
| ------------------------ | --------------------------------------------------------------------------------- | -------- | ----------- | -------------- |
| **Phase 0: Setup** | - Stripe credentials<br>- Staging environment<br>- SDK installed | 2 days | 2026-02-05 | ✅ Complete |
| **Phase 1: Persistence** | - Entities created<br>- Repositories implemented<br>- Migrations generated | 3 days | 2026-02-08 | 🟡 In Progress |
| **Phase 2: Services** | - CustomerService<br>- SubscriptionService<br>- Identity integration | 5 days | 2026-02-15 | ⏳ Pending |
| **Phase 3: APIs** | - POST /subscriptions<br>- DELETE /subscriptions/:id<br>- GET /subscriptions | 3 days | 2026-02-18 | ⏳ Pending |
| **Phase 4: Webhooks** | - Webhook endpoint<br>- Signature validation<br>- Event handlers | 4 days | 2026-02-22 | ⏳ Pending |
| **Phase 5: Testing** | - Unit tests (80% coverage)<br>- Integration tests<br>- E2E tests | 5 days | 2026-02-27 | ⏳ Pending |
| **Phase 6: Deploy** | - Documentation<br>- Monitoring setup<br>- Staging deploy<br>- Production rollout | 3 days | 2026-03-02 | ⏳ Pending |
**Total Duration**: ~25 days (5 weeks)
**Milestones**:
- 🎯 M1: MVP ready for staging (2026-02-22)
- 🎯 M2: Production deployment (2026-03-02)
- 🎯 M3: 100% rollout complete (2026-03-09)
**Critical Path**:
Phase 0 → Phase 1 → Phase 2 → Phase 3 → Phase 4 → Phase 5 → Phase 6
20. 审批与签字确认(建议)
## Approval & Sign-off
| Role | Name | Status | Date | Comments |
| ------------------------ | ----- | -------------- | ---------- | --------------------------------- |
| Tech Lead | @Name | ✅ Approved | 2026-02-04 | LGTM, proceed with implementation |
| Staff/Principal Engineer | @Name | ⏳ Pending | - | Requested security review first |
| Product Manager | @Name | ✅ Approved | 2026-02-03 | Scope aligned with roadmap |
| Engineering Manager | @Name | ⏳ Pending | - | - |
| Security Team | @Name | 🔴 Not Started | - | Required for payment integration |
| Compliance/Legal | @Name | N/A | - | Not required for this project |
**Approval Criteria**:
- ✅ All mandatory sections complete
- ✅ Security review passed (if applicable)
- ✅ Risks identified and mitigated
- ✅ Timeline realistic and agreed upon
- ⏳ Test strategy approved by QA
- ⏳ Monitoring plan reviewed by SRE
**Next Steps After Approval**:
1. Create Epic in Jira (link in metadata)
2. Break down into User Stories
3. Begin Phase 1 implementation
4. Schedule kickoff meeting with team
验证规则
强制章节检查清单
定稿 TDD 前,请确保:
- 标题:包含技术负责人、团队、Epic 链接
- 背景:至少用 2 个段落描述背景和领域
- 问题:指出至少 2 个具体问题及其影响
- 范围:明确列出范围内和范围外的事项(各至少 3 项)
- 技术方案:提供架构图或说明
- 技术方案:定义至少 1 个 API 端点
- 风险:至少列出 3 项风险,并说明影响、概率和缓解措施
- 实施计划:划分阶段并提供估算
关键章节检查清单(按项目类型)
如果是支付/身份验证项目:
- 安全性:定义身份验证方法
- 安全性:说明加密方式(静态数据、传输中数据)
- 安全性:记录 PII 处理方法
- 安全性:明确合规要求
如果是生产系统:
- 监控:至少定义 3 项指标及其阈值
- 监控:配置警报
- 回滚:定义回滚触发条件
- 回滚:记录回滚步骤
所有项目:
- 测试:至少定义 2 种测试类型(单元测试、集成测试、端到端测试)
- 测试:列出关键测试场景
输出格式
创建 TDD 时
- 生成 Markdown 文档
- 根据上述清单进行验证
- 标出任何缺失的关键章节
- 向用户提供摘要:
✅ TDD Created: "[Project Name]"
**Sections Included**:
✅ Mandatory (7/7): All present
✅ Critical (3/4): Security, Testing, Monitoring
⚠️ Missing: Rollback Plan (recommended for production)
**Suggested Next Steps**:
- Add Rollback Plan section (critical for production)
- Review Security section with InfoSec team
- Create Epic in Jira and link in metadata
- Schedule TDD review meeting with stakeholders
Would you like me to:
1. Add the missing Rollback Plan section?
2. Publish this TDD to Confluence?
3. Create a Jira Epic for this project?
Confluence 集成
如果用户想要发布到 Confluence:
I'll publish this TDD to Confluence.
Which space should I use?
- Personal space (~557058...)
- Team space (provide space key)
Should I:
- Create a new page
- Update existing page (provide page ID or URL)
然后使用 Confluence Assistant 技能进行发布。
应避免的常见反模式
❌ 问题描述含糊
不佳:
We need to integrate with Stripe.
良好:
### Problems We're Solving
- **Manual payment processing takes 2 hours/day**: Currently processing payments manually, costing $500/month in labor
- **Cannot expand internationally**: Current payment processor only supports USD
- **High cart abandonment (45%)**: Poor checkout UX causing revenue loss of $10k/month
❌ 未定义范围
不佳:
Build payment integration with all features.
良好:
### ✅ In Scope (V1)
- Trial subscriptions (14 days)
- Single payment method per user
- USD only
- Cancel subscription
### ❌ Out of Scope (V1)
- Multiple payment methods
- Multi-currency
- Promo codes
- Usage-based billing
❌ 支付系统缺少安全性说明
不佳:
No security section for payment integration.
良好:
### Security Considerations (MANDATORY)
**PCI DSS Compliance**:
- Never store full card numbers (use Stripe tokens)
- Never log CVV or full PAN
- Use Stripe Elements for card input (PCI SAQ A)
**Secrets Management**:
- Store `STRIPE_SECRET_KEY` in environment variables
- Rotate keys every 90 days
- Never commit keys to git
❌ 没有回滚计划
不佳:
We'll deploy and hope it works.
良好:
### Rollback Plan
**Triggers**:
- Error rate > 5% → immediate rollback
- Payment processing failures > 10% → immediate rollback
**Steps**:
1. Disable feature flag `STRIPE_INTEGRATION_ENABLED`
2. Verify old payment processor is active
3. Notify #engineering and #product
4. Schedule post-mortem within 24h
重要说明
- 尊重用户的语言——自动检测用户请求所用的语言,并用相同语言生成 TDD
- 关注架构,而非实现——记录决策和契约,而不是代码
- 只提供高层示例——展示 API 契约、数据模式、图表(而不是 CLI 命令或代码片段)
- 始终验证强制章节——不要允许用户跳过这些章节
- 对于支付/身份验证项目——安全性章节为必填项
- 对于生产系统——监控和回滚为必填项
- 提出澄清问题——不要猜测缺失的信息(用用户使用的语言提问)
- 详尽但务实——小型项目不需要全部 20 个章节
- 更新文档——TDD 应随着项目进展而不断完善
- 采用行业标准——参考 Google、Amazon 和 RFC 模式
- 考虑合规性——视情况考虑 GDPR、PCI DSS、HIPAA
- 确保方案经久耐用——即使实现框架发生变化,TDD 仍应有效
可触发此技能的示例提示词
英语
- “为 Stripe 集成创建一份 TDD”
- “我需要一份新身份验证系统的技术设计文档”
- “为 API 重设计编写一份设计文档”
- “帮我记录支付集成架构”
- “创建一份迁移到微服务的技术规格说明”
葡萄牙语
- “为 Stripe 集成创建一份 TDD”
- “我需要一份新身份验证系统的技术设计文档”
- “为 API 重设计编写一份设计文档”
- “帮我记录支付集成架构”
- “创建一份迁移到微服务的技术规格说明”
西班牙语
- “为 Stripe 集成创建一份 TDD”
- “我需要一份新身份验证系统的技术设计文档”
- “为 API 重设计编写一份设计文档”
- “帮我记录支付集成架构”
- “创建一份迁移到微服务的技术规格说明”
参考资料
Industry Standards