v1.0:gudaspec正式版,不再依赖于openspec

This commit is contained in:
GuDaStudio
2026-02-06 11:11:39 +08:00
parent 32d5902088
commit 34b2c931b6
8 changed files with 3669 additions and 196 deletions

View File

@@ -0,0 +1,577 @@
---
name: GudaSpec: Deep Research Review
description: Interactive review of external research - guided technology decisions and synthesis.
category: GudaSpec
tags: [gudaspec, research, review, external, synthesis, interactive]
argument-hint: [requirement-id]
---
<!-- GUDASPEC:DEEP-RESEARCH-REVIEW:START -->
## Purpose
以用户友好的方式审查外部研究发现,引导技术决策,综合内外部约束生成最终需求文档。
## Core Principles
1. **决策导向**:聚焦于帮助用户做决定,而非展示信息
2. **对比清晰**:用表格和可视化展示选项差异
3. **风险透明**:明确说明每个选择的潜在风险
4. **关联内部**:始终与内部约束对照验证
5. **渐进收敛**:从大方向到具体细节
## Guardrails
- **MUST** use `AskUserQuestions` for all decisions
- **MUST** relate external findings to internal constraints
- **MUST** explain trade-offs in business terms
- **NEVER** make technology decisions without user confirmation
- **NEVER** present options without recommendation and rationale
---
## Steps
### Step 0: Load Both Documents
```bash
cat gudaspec/research/<requirement-id>/internal.md
cat gudaspec/research/<requirement-id>/external.md
```
Prepare synthesis by:
- Mapping external options to internal constraints
- Identifying potential conflicts
- Preparing comparison matrices
### Step 1: Welcome and Context Recap
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 外部调研审查: <Requirement Description>
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
需求ID: <requirement-id>
【回顾:您之前的关键决策】
• 登录安全: 复用现有机制
• 同步频率: 每5分钟
• 实施边界: <范围描述>
【本次调研解答了】
• Microsoft Graph API vs EWS 选型
• OAuth 2.0 集成方案
• 邮件数据存储策略
接下来我会引导您完成技术选型决策。
📊 决策概览:
┌─────────────────────────────────────┐
│ 核心技术选型 ████████░░ 2 个 │
│ 实施策略确认 ██████░░░░ 2 个 │
│ 风险确认 ████░░░░░░ 1 个 │
└─────────────────────────────────────┘
预计用时: 5-10 分钟
```
---
### Step 2: Core Technology Decision (核心技术决策)
**Strategy**: Present as a product comparison, highlight what matters most for this specific use case.
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🎯 技术选型 1/2: 邮件API选择
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
经过调研,有两个主要方案可以实现 Outlook 邮件集成:
┌─────────────────────────────────────────────────────────────┐
│ Microsoft Graph API │
├─────────────────────────────────────────────────────────────┤
│ 🌟 推荐理由: 微软官方推荐的现代API │
│ │
│ ✅ 优势 │ ⚠️ 注意事项 │
│ • 统一的API可扩展到日历等 │ • 需要Azure AD应用注册 │
│ • 活跃维护,文档完善 │ • 学习曲线略高 │
│ • 支持增量同步(省流量) │ • 某些高级功能需付费许可 │
│ • 与现代OAuth 2.0完全兼容 │ │
│ │ │
│ 📊 与您项目的兼容性: 95% │ │
│ • ✅ 可复用现有OAuth基础设施 │ │
│ • ✅ 符合项目REST风格 │ │
│ • ⚠️ 需要新增 msgraph-sdk │ │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ Exchange Web Services (EWS) │
├─────────────────────────────────────────────────────────────┤
备选方案: 传统但稳定 │
│ │
│ ✅ 优势 │ ⚠️ 注意事项 │
│ • 成熟稳定,案例多 │ • 微软已停止新功能开发 │
│ • 本地Exchange服务器支持好 │ • 未来可能被废弃 │
│ │ • 文档逐渐过时 │
│ │ • 某些新邮箱功能不支持 │
│ │ │
│ 📊 与您项目的兼容性: 70% │ │
│ • ⚠️ 认证方式与现有不兼容 │ │
│ • ⚠️ XML格式与项目JSON风格冲突│ │
└─────────────────────────────────────────────────────────────┘
【我的建议】
选择 **Microsoft Graph API**
原因与您项目的现有技术栈OAuth、REST、JSON高度兼容
且是微软未来重点发展方向,长期维护成本更低。
```
Use `AskUserQuestions`:
```
question: "邮件API您选择哪个方案"
options: [
"Microsoft Graph API推荐",
"Exchange Web Services",
"需要更多对比信息",
"我有其他考虑,想讨论一下"
]
```
**If user wants more info or discussion**, provide:
```
我来补充一些细节:
【成本对比】
• Graph API: 免费额度较大,超出后按调用计费
• EWS: 通常包含在Microsoft 365订阅中
【开发时间对比】
• Graph API: 预计 3-4 天有官方SDK
• EWS: 预计 5-7 天(需要更多手动处理)
【您的顾虑是什么?】
```
---
### Step 3: Implementation Strategy Decision (实施策略决策)
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🎯 技术选型 2/2: OAuth认证流程
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
基于您选择的 Graph API需要确定 OAuth 认证流程:
【您的场景】
用户在您的应用中点击"连接Outlook" → 跳转微软登录 →
授权后返回您的应用 → 开始同步邮件
【推荐方案: Authorization Code Flow】
```
用户 您的应用 微软
│ │ │
│──点击连接────▶│ │
│ │──重定向──────▶│
│ │ │
│◀──────────────────登录页面────│
│ │ │
│───────────输入账号密码───────▶│
│ │ │
│ │◀──授权码──────│
│ │ │
│ │──换取Token───▶│
│ │ │
│ │◀──Access Token│
│◀──连接成功───│ │
```
【此方案的优点】
• 最安全的OAuth流程PKCE增强
• 与您现有的Google OAuth流程一致
• 可复用现有的Token刷新机制
【需要您确认】
Token存储位置
┌────────────────────────────────────────────┐
│ A. 数据库存储(推荐) │
│ • 服务器可定时刷新 │
│ • 用户关闭浏览器后仍可后台同步 │
│ • 需要加密存储 │
├────────────────────────────────────────────┤
│ B. 仅Session存储 │
│ • 更简单,无需额外存储 │
│ • 用户关闭浏览器后需重新授权 │
│ • 不支持后台同步 │
└────────────────────────────────────────────┘
```
Use `AskUserQuestions`:
```
question: "Token存储方案选择"
options: [
"A. 数据库存储(推荐:支持后台同步)",
"B. Session存储简单但功能受限",
"这个决定需要更多技术背景,请解释"
]
```
---
### Step 4: Best Practices Adoption (最佳实践采纳)
**Strategy**: Present best practices as "lessons learned from others", let user decide what to adopt.
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📚 最佳实践: 他人踩过的坑
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
调研中发现了一些值得借鉴的经验:
【实践1: 增量同步】
┌────────────────────────────────────────────┐
│ 💡 经验: 不要每次全量拉取邮件 │
│ │
│ 问题: 全量拉取会很慢且浪费API配额 │
│ 解决: 使用 deltaLink 只获取变化的邮件 │
│ 效果: API调用减少 80%,同步速度提升 5x │
│ │
│ 采纳成本: 低Graph API原生支持
└────────────────────────────────────────────┘
建议: ✅ 强烈推荐采纳
【实践2: 错误重试策略】
┌────────────────────────────────────────────┐
│ 💡 经验: API调用失败时要智能重试 │
│ │
│ 问题: 网络波动导致同步中断 │
│ 解决: 指数退避重试 (1s, 2s, 4s, 8s...) │
│ 效果: 同步成功率从 95% 提升到 99.9% │
│ │
│ 采纳成本: 低约2小时开发
└────────────────────────────────────────────┘
建议: ✅ 推荐采纳
【实践3: 邮件内容缓存】
┌────────────────────────────────────────────┐
│ 💡 经验: 缓存邮件正文减少重复请求 │
│ │
│ 问题: 用户反复查看同一邮件消耗API │
│ 解决: 本地缓存已读邮件内容 │
│ 效果: 响应速度提升API成本降低 │
│ │
│ 采纳成本: 中(需要设计缓存策略) │
└────────────────────────────────────────────┘
建议: ⚠️ 可选(根据使用频率决定)
```
Use `AskUserQuestions`:
```
question: "以上最佳实践,您希望采纳哪些?"
options: [
"全部采纳(推荐)",
"仅采纳强烈推荐的实践1和2",
"最小实现,后续再优化",
"我想逐个讨论"
]
```
---
### Step 5: Risk Acknowledgment (风险确认)
**Strategy**: Be transparent about potential issues, get user's acknowledgment.
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠️ 风险提示: 实施前须知
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
基于调研,以下风险需要您了解:
【风险1: API速率限制】
┌────────────────────────────────────────────┐
│ 🚨 严重程度: 中 │
│ │
│ 情况: Graph API 有调用频率限制 │
│ • 每应用: 2000次/秒 │
│ • 每用户: 10000次/10分钟 │
│ │
│ 触发场景: 大量用户同时首次同步 │
│ │
│ 缓解措施: │
│ ✅ 已计划: 增量同步减少调用 │
│ ✅ 已计划: 错误重试策略 │
│ 📋 建议: 首次同步限制为最近30天邮件 │
└────────────────────────────────────────────┘
【风险2: Token过期处理】
┌────────────────────────────────────────────┐
│ 🚨 严重程度: 低 │
│ │
│ 情况: Access Token 1小时过期 │
│ Refresh Token 90天过期 │
│ │
│ 触发场景: 用户90天未使用需重新授权 │
│ │
│ 缓解措施: │
│ ✅ 已计划: 自动刷新机制 │
│ 📋 建议: 过期前邮件提醒用户重新授权 │
└────────────────────────────────────────────┘
【总体风险评估】
以上风险在正确实施后均可控。
无阻塞性风险,可以继续推进。
```
Use `AskUserQuestions`:
```
question: "您是否了解并接受以上风险?"
options: [
"了解,可以接受",
"风险1我有顾虑想讨论一下",
"风险2我有顾虑想讨论一下",
"需要更详细的风险分析"
]
```
---
### Step 6: Constraint Conflict Resolution (约束冲突解决)
**Strategy**: If there are conflicts between internal and external constraints, present clearly and get resolution.
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚡ 约束冲突: 需要您做决定
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
在综合内外部研究时,发现一个需要协调的点:
【冲突描述】
┌────────────────────────────────────────────┐
│ 内部约束: │
│ 现有认证模块使用 HS256 算法签名 JWT │
│ │
│ 外部推荐: │
│ Microsoft 最佳实践建议使用 RS256 算法 │
│ │
│ 冲突点: │
│ 算法不同,无法直接复用现有 Token 验证逻辑 │
└────────────────────────────────────────────┘
【解决方案】
方案A: 统一升级到 RS256
┌────────────────────────────────────────────┐
│ 做法: 整体迁移现有认证到 RS256 │
│ 优点: 安全性更高,架构统一 │
│ 代价: 需要修改现有代码,所有用户重新登录 │
│ 工作量: +2天 │
└────────────────────────────────────────────┘
方案B: 双算法共存
┌────────────────────────────────────────────┐
│ 做法: 现有保持 HS256Outlook 用 RS256 │
│ 优点: 不影响现有功能 │
│ 代价: 代码复杂度增加,维护两套逻辑 │
│ 工作量: +0.5天 │
└────────────────────────────────────────────┘
方案C: Outlook也用 HS256
┌────────────────────────────────────────────┐
│ 做法: 忽略微软建议,统一用 HS256 │
│ 优点: 最简单,完全复用现有逻辑 │
│ 代价: 安全性略低于推荐标准 │
│ 工作量: +0天 │
└────────────────────────────────────────────┘
【我的建议】
选择 **方案B: 双算法共存**
原因平衡了安全性和改动范围Outlook模块使用推荐算法
不影响现有用户,未来可渐进式迁移。
```
Use `AskUserQuestions`:
```
question: "对于JWT算法冲突您选择哪个方案"
options: [
"方案A: 统一升级(更安全,改动大)",
"方案B: 双算法共存(推荐:平衡)",
"方案C: 统一HS256最简单",
"需要更多信息来决定"
]
```
---
### Step 7: Final Decision Summary (最终决策总结)
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ 决策总结
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
经过完整的研究和审查,以下是您的所有决策:
┌─────────────────────────────────────────────────────────────┐
│ 📋 需求: <Requirement Description> │
│ 🆔 ID: <requirement-id> │
├─────────────────────────────────────────────────────────────┤
│ │
│ 【内部研究决策】 │
│ ├─ 登录安全: 复用现有机制 │
│ ├─ 项目规范: 完全遵循 │
│ ├─ 集成方案: 3个对接点 │
│ └─ 同步频率: 每5分钟 │
│ │
│ 【外部研究决策】 │
│ ├─ 邮件API: Microsoft Graph API │
│ ├─ 认证流程: Authorization Code Flow + PKCE │
│ ├─ Token存储: 数据库加密存储 │
│ ├─ 最佳实践: 采纳增量同步 + 错误重试 │
│ └─ JWT算法: 双算法共存 │
│ │
│ 【风险确认】 │
│ ├─ API限速: 已了解,通过增量同步缓解 │
│ └─ Token过期: 已了解,通过自动刷新处理 │
│ │
├─────────────────────────────────────────────────────────────┤
│ 📊 实施预估 │
│ ├─ 涉及文件: 12-15 个 │
│ ├─ 新增依赖: msgraph-sdk, msal │
│ ├─ 预计工时: 5-7 天 │
│ └─ 风险等级: 中低 │
└─────────────────────────────────────────────────────────────┘
```
Use `AskUserQuestions`:
```
question: "以上决策总结是否准确完整?"
options: [
"准确,生成最终需求文档",
"基本准确,有小的补充",
"需要修改某项决策"
]
```
---
### Step 8: Generate Final Requirement Document
Create comprehensive `requirement.md` incorporating all confirmed decisions.
**Key sections to include**:
- 所有内部约束(已确认)
- 所有外部约束(已确认)
- 技术决策及理由
- 采纳的最佳实践
- 风险及缓解措施
- 用户所有决策的完整记录
---
### Step 9: Completion Output
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🎉 Research 全部完成!
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
需求ID: <requirement-id>
📁 生成的文档:
├─ gudaspec/research/<requirement-id>/
│ ├─ internal.md (内部研究 - 已确认)
│ ├─ external.md (外部研究 - 已确认)
│ └─ requirement.md (最终需求文档) ⭐
📊 研究摘要:
┌─────────────────────────────────────────┐
│ 您做出了 8 项关键决策 │
│ 确认了 12 条约束 │
│ 采纳了 2 项最佳实践 │
│ 了解并接受了 2 项风险 │
└─────────────────────────────────────────┘
📋 下一步操作:
1. 输入 /clear 清空当前上下文
(释放空间,为规划阶段准备)
2. 输入以下命令开始规划:
/gudaspec:plan gudaspec/research/<requirement-id>/requirement.md
规划阶段将基于您确认的约束,生成详细的实施计划。
```
---
## Question Design Patterns for External Review
### Pattern 1: Product Comparison (产品对比)
```
【方案A】 vs 【方案B】
┌──────────────┐ ┌──────────────┐
│ 特点 │ │ 特点 │
│ 优势 │ │ 优势 │
│ 劣势 │ │ 劣势 │
│ 适用场景 │ │ 适用场景 │
└──────────────┘ └──────────────┘
我的建议: [方案X],因为 [与您需求的匹配点]
```
### Pattern 2: Trade-off Matrix (权衡矩阵)
```
┌─────────┬──────┬──────┬──────┐
│ 维度 │ A │ B │ C │
├─────────┼──────┼──────┼──────┤
│ 成本 │ ⭐⭐⭐ │ ⭐⭐ │ ⭐ │
│ 复杂度 │ ⭐ │ ⭐⭐ │ ⭐⭐⭐ │
│ 安全性 │ ⭐⭐⭐ │ ⭐⭐ │ ⭐ │
└─────────┴──────┴──────┴──────┘
您更看重哪个维度?
```
### Pattern 3: Impact Visualization (影响可视化)
```
如果选择 [方案X]:
现在 3个月后
──── ────────
[现状] ──────────────▶ [预期结果]
收益: [具体数字/效果]
代价: [具体工作量/风险]
```
### Pattern 4: Lesson Learned (经验借鉴)
```
【他人经验】
问题: 遇到了什么问题
原因: 为什么会这样
解决: 怎么解决的
效果: 解决后怎样
【对您的启示】
建议: 您应该/不应该...
```
---
## Exit Criteria
- [ ] All technology decisions confirmed with user rationale
- [ ] All best practices reviewed (adopted/skipped with reason)
- [ ] All risks acknowledged by user
- [ ] All constraint conflicts resolved
- [ ] Final decision summary confirmed by user
- [ ] requirement.md generated with complete documentation
- [ ] User directed to /gudaspec:plan
<!-- GUDASPEC:DEEP-RESEARCH-REVIEW:END -->

276
gudaspec/deepresearch.md Normal file
View File

@@ -0,0 +1,276 @@
---
name: GudaSpec: Deep Research
description: External problem domain research - analyze available technologies, patterns, and best practices.
category: GudaSpec
tags: [gudaspec, research, external, greenfield, technology]
argument-hint: [requirement-id]
---
<!-- GUDASPEC:DEEPRESEARCH:START -->
## CRITICAL: RESEARCH ONLY, NO IMPLEMENTATION
- **DO NOT** write any implementation code
- **DO NOT** make final technology decisions without user confirmation
- **ONLY** gather information, compare options, document constraints
- Present options objectively with pros/cons
## Purpose
执行问题域调研External Research研究外部技术、模式和最佳实践为需求实现提供技术选型依据。
## Guardrails
- **MUST** read internal.md first to understand existing constraints
- **MANDATORY**: Use `mcp__grok-search` for external research
- **MUST** verify external recommendations against internal constraints
- All findings must include source URLs
- Prefer recent sources (2024-2025)
---
## Steps
### Step 0: Load Internal Research
```bash
# Read internal research for context
cat gudaspec/research/<requirement-id>/internal.md
```
Extract:
- Hard constraints (compatibility requirements)
- Existing technology stack
- Integration points
- Open questions that need external research
### Step 1: Identify Research Topics
Based on internal research triggers, identify specific research topics:
```
📋 External Research 议题
需求ID: <requirement-id>
基于内部研究,需要调研以下议题:
| ID | 议题 | 调研目的 | 与内部约束关系 |
|----|------|----------|----------------|
| ER-1 | <topic> | <purpose> | <constraint compatibility> |
| ER-2 | <topic> | <purpose> | <constraint compatibility> |
确认开始调研?
```
### Step 2: Execute External Research
For each research topic, use `mcp__grok-search`:
**Search Patterns**:
| 调研类型 | 搜索模式 |
|----------|----------|
| 技术对比 | `"[Tech A] vs [Tech B] [use case] 2024 2025"` |
| 最佳实践 | `"[Domain] best practices production 2025"` |
| 实现参考 | `"[Framework] [feature] implementation example"` |
| API限制 | `"[Service] API rate limits pricing 2025"` |
| 安全考量 | `"[Technology] security vulnerabilities CVE 2024"` |
### Step 3: Analyze Each Topic
For each topic, gather:
- Multiple options/approaches
- Pros and cons of each
- Compatibility with internal constraints
- Community adoption and maintenance status
- License considerations
### Step 4: Generate External Document
Create:
```
gudaspec/research/<requirement-id>/external.md
```
**Document Template**:
```markdown
---
requirement_id: <requirement-id>
created: <ISO timestamp>
researcher: claude
status: pending-review
type: external
internal_ref: gudaspec/research/<requirement-id>/internal.md
---
# External Research: <Requirement Description>
## 调研背景
### 内部约束回顾
| 约束ID | 约束描述 | 对外部选型的影响 |
|--------|----------|------------------|
| HC-1 | <constraint> | <impact on selection> |
| ... | | |
### 现有技术栈
| 类型 | 技术 | 版本 |
|------|------|------|
| <type> | <tech> | <version> |
---
## 调研议题 1: <Topic Name>
### 调研问题
<What we need to find out>
### 选项分析
#### 选项 A: <Option Name>
| 维度 | 评估 |
|------|------|
| 描述 | |
| 官方文档 | [链接]() |
| GitHub Stars | |
| 最近更新 | |
| License | |
**优势**:
- [ ] <advantage 1> — 确认
- [ ] <advantage 2> — 确认
**劣势**:
- [ ] <disadvantage 1> — 确认
- [ ] <disadvantage 2> — 确认
**与内部约束兼容性**:
| 约束 | 兼容? | 说明 |
|------|-------|------|
| HC-1 | ✅/❌/⚠️ | <explanation> |
**参考实现**:
- [项目名](URL) — <what to learn>
**来源**: [URL1](), [URL2]()
---
#### 选项 B: <Option Name>
<Same structure as Option A>
---
#### 选项对比
| 维度 | 选项 A | 选项 B | 选项 C |
|------|--------|--------|--------|
| 学习曲线 | | | |
| 性能 | | | |
| 社区支持 | | | |
| 与现有栈兼容 | | | |
| 维护成本 | | | |
**初步推荐**: <Option X>
**推荐理由**: <reasoning based on internal constraints>
**确认**: [ ]
---
## 调研议题 2: <Topic Name>
<Same structure as Topic 1>
---
## 最佳实践发现
| ID | 实践 | 来源 | 适用性 | 确认 |
|----|------|------|--------|------|
| BP-1 | <practice> | [URL]() | <applicability> | [ ] |
| BP-2 | <practice> | [URL]() | <applicability> | [ ] |
---
## 外部服务约束
| 服务 | 约束类型 | 限制值 | 对设计影响 | 确认 |
|------|----------|--------|------------|------|
| <service> | Rate Limit | <value> | <impact> | [ ] |
| <service> | Pricing | <value> | <impact> | [ ] |
---
## 安全考量
| ID | 考量 | 风险级别 | 缓解措施 | 确认 |
|----|------|----------|----------|------|
| SEC-1 | <consideration> | 高/中/低 | <mitigation> | [ ] |
---
## 开放问题
| ID | 问题 | 上下文 | 您的回答 |
|----|------|--------|----------|
| OQ-E-1 | | | __________ |
| OQ-E-2 | | | __________ |
---
## 外部约束汇总
### 硬约束 (来自外部研究)
| ID | 约束 | 来源 | 确认 |
|----|------|------|------|
| HC-E-1 | | [URL]() | [ ] |
### 软约束 (来自外部研究)
| ID | 约束 | 来源 | 确认 |
|----|------|------|------|
| SC-E-1 | | [URL]() | [ ] |
---
## 下一步
文档已生成,请执行以下操作:
1. **清空上下文**: 输入 `/clear`
2. **开始审查**: 输入 `/gudaspec:deep-research-review <requirement-id>`
```
### Step 5: Final Output
```
✅ External Research 完成
需求ID: <requirement-id>
文档位置: gudaspec/research/<requirement-id>/external.md
调研摘要:
- 调研议题: [X] 个
- 技术选项: [Y] 个
- 最佳实践: [Z] 条
- 外部约束: [N] 条
- 开放问题: [M] 个
📋 下一步操作:
1. 输入 /clear 清空当前上下文
2. 输入 /gudaspec:deep-research-review <requirement-id> 开始审查
```
---
## Exit Criteria
- [ ] Internal constraints reviewed for compatibility checking
- [ ] All research topics investigated
- [ ] Multiple options compared for each topic
- [ ] Compatibility with internal constraints verified
- [ ] External document saved
- [ ] User reminded to `/clear` and proceed to review
<!-- GUDASPEC:DEEPRESEARCH:END -->

View File

@@ -1,24 +1,917 @@
---
name: GudaSpec: Implementation
description: Execute approved OpenSpec changes via multi-model collaboration with Codex/Gemini.
description: Execute approved plan phase by phase with TDD cycle and multi-model collaboration.
category: GudaSpec
tags: [openspec, implementation, multi-model, codex, gemini]
tags: [gudaspec, implementation, tdd, multi-model, codex, gemini]
argument-hint: [plan.md path] [optional: Phase N]
---
<!-- GUDASPEC:START -->
**Guardrails**
- If the project is detected to lack `./openspec/` dir, prompt the user to initialize the project using `/gudaspec:init`.
- Never apply external model prototypes directly—all Codex/Gemini outputs serve as reference only and must be rewritten into readable, maintainable, production-grade code.
- Keep changes tightly scoped to the requested outcome; enforce side-effect review before applying any modification.
- Minimize documentation—avoid unnecessary comments; prefer self-explanatory code.
**Steps**
1. Run `openspec view` to inspect current project status and review `Active Changes`; Use `AskUserQuestions` tool ask the user to confirm which proposal ID they want to implement and wait for explicit confirmation before proceeding.
2. Run `/opsx:apply <proposal_id>` and then follow it.
3. When performing a specific coding task, refer to the code prototype provided by an effective model:
- **Route A: Gemini Kernel** — `mcp__gemini__gemini` tool for frontend/UI/styling tasks (CSS, React, Vue, HTML, component design).
- **Route B: Codex Kernel** — `mcp__codex__codex` tool for backend/logic/algorithm tasks (API, data processing, business logic, debugging).
- **Mandatory constraint**: When communicating with Codex/Gemini, the prompt **must explicitly require** returning a `Unified Diff Patch` only; external models are strictly forbidden from making any real file modifications.
4. Upon receiving the diff patch from Codex/Gemini, **NEVER apply it directly**; rewrite the prototype by removing redundancy, ensuring clear naming and simple structure, aligning with project style, and eliminating unnecessary comments.
5. For each completed task, conduct multi-model reviews using Codex`mcp__codex__codex` / Gemini`mcp__gemini__gemini`, requiring iterative reviews until receiving dual-model **LGTM approval**.
6. MUST follow the `/opsx:apply <proposal_id>`.
<!-- GUDASPEC:END -->
<!-- GUDASPEC:IMPLEMENTATION:START -->
## Purpose
基于已批准的计划逐Phase执行TDD循环Red-Green-Refactor利用多模型协作实现并审查代码。
## Core Principles
1. **Plan is Law** — 严格按照计划规格实现,不擅自扩展范围
2. **Test First** — Level 1-2时先写测试确认RED状态后再实现
3. **AI Assists, Human Decides** — AI生成原型人工确认关键决策
4. **Dual Model LGTM** — 重要代码需Codex+Gemini双重审查
5. **Phase Isolation** — 每Phase完成后/clear保持上下文干净
6. **Fail Fast, Recover Easy** — 问题早发现支持从任意Phase恢复
## Guardrails
- **MUST** read plan.md completely before starting.
- **MUST** follow TDD cycle if test_level >= 1.
- **MUST** pause for human confirmation after each Phase.
- **MUST** stop and report if plan doesn't match reality.
- **NEVER** apply AI-generated code directly without review.
- **NEVER** skip tests to "save time".
- **NEVER** expand scope beyond what's specified in plan.
---
## Steps
### Step 0: Load Plan and Determine Starting Point
**With full path:**
```
/gudaspec:implementation gudaspec/plans/<requirement-id>/plan.md
```
**With Phase specified (for recovery):**
```
/gudaspec:implementation gudaspec/plans/<requirement-id>/plan.md Phase 2
```
**If no parameter:**
```
请提供计划文档路径:
/gudaspec:implementation gudaspec/plans/<requirement-id>/plan.md
如需从特定Phase继续:
/gudaspec:implementation gudaspec/plans/<requirement-id>/plan.md Phase N
```
### Step 1: Plan Verification
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 实施准备: <Requirement Title>
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
【计划概览】
需求ID: <requirement-id>
测试策略: Level <X>
计划状态: <approved>
批准时间: <timestamp>
【Phase结构】
┌─────────────────────────────────────────────┐
│ Phase 1: <name> [ ] │
│ Phase 2: <name> [ ] │
│ Phase 3: <name> [ ] │
└─────────────────────────────────────────────┘
【起始点】
从 Phase <N> 开始执行
【前置检查】
• 代码库状态: <clean/有未提交变更>
• 分支: <current branch>
• 上次commit: <hash>
```
**Pre-flight checks:**
```bash
# 检查工作区状态
git status
# 检查是否在正确分支
git branch --show-current
```
Use `AskUserQuestions`:
```
question: "准备开始实施?"
options: [
"开始 Phase <N>",
"需要先处理未提交的变更",
"需要切换分支",
"查看Plan详情"
]
```
---
### Step 2: Phase Execution Loop
**For each Phase, execute the following sub-steps:**
---
#### Step 2.1: Phase Overview
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🚀 Phase <N>: <Phase Name>
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
【目标】
<Phase goal from plan>
【变更范围】
• <file1.py> — <change type>
• <file2.py> — <change type>
【测试范围】
• <test1> — <scenario>
• <test2> — <scenario>
【执行流程】
1. 编写测试 (RED)
2. 实现代码 (GREEN)
3. 审查优化 (REFACTOR)
4. 验证确认 (VERIFY)
开始执行...
```
---
#### Step 2.2: RED — Write Tests First (Level 1-2)
**Skip this step if test_level == 0**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔴 RED: 编写测试
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
【测试规格】(来自Plan)
Test 1: <test_name>
• 场景: <scenario>
• 输入: <input>
• 期望: <expected>
Test 2: <test_name>
• 场景: <edge case>
• 输入: <input>
• 期望: <expected>
【生成测试代码】
```
**Claude writes test code based on test specifications:**
```python
# tests/test_<module>.py
import pytest
from src.auth.service import AuthService
from src.auth.exceptions import UserNotFoundError, TwoFactorNotEnabledError
class TestVerify2FA:
"""Phase 1: 双因素认证验证测试"""
@pytest.fixture
def auth_service(self):
return AuthService()
@pytest.fixture
def user_with_2fa(self, db_session):
"""创建已启用2FA的测试用户"""
user = create_test_user(email="test@example.com")
user.enable_2fa(secret="TESTSECRET123456")
db_session.add(user)
db_session.commit()
return user
def test_valid_code_should_pass(self, auth_service, user_with_2fa):
"""
场景: 用户输入正确的TOTP验证码
期望: 返回True
"""
# Arrange
valid_code = generate_totp_code(user_with_2fa.totp_secret)
# Act
result = auth_service.verify_2fa(user_with_2fa.id, valid_code)
# Assert
assert result is True
def test_invalid_code_should_fail(self, auth_service, user_with_2fa):
"""
场景: 用户输入错误的验证码
期望: 返回False
"""
# Arrange
invalid_code = "000000"
# Act
result = auth_service.verify_2fa(user_with_2fa.id, invalid_code)
# Assert
assert result is False
def test_user_not_found_should_raise(self, auth_service):
"""
场景: 用户不存在
期望: 抛出UserNotFoundError
"""
# Arrange
non_existent_id = uuid4()
# Act & Assert
with pytest.raises(UserNotFoundError):
auth_service.verify_2fa(non_existent_id, "123456")
def test_2fa_not_enabled_should_raise(self, auth_service, user_without_2fa):
"""
场景: 用户未启用2FA
期望: 抛出TwoFactorNotEnabledError
"""
# Act & Assert
with pytest.raises(TwoFactorNotEnabledError):
auth_service.verify_2fa(user_without_2fa.id, "123456")
```
**Write tests to file and run:**
```bash
# 创建/更新测试文件
# ... (write to tests/test_<module>.py)
# 运行测试确认RED状态
pytest tests/test_<module>.py -v
```
**Expected output:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔴 RED状态确认
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
测试结果:
• test_valid_code_should_pass FAILED ❌
• test_invalid_code_should_fail FAILED ❌
• test_user_not_found_should_raise FAILED ❌
• test_2fa_not_enabled_should_raise FAILED ❌
状态: 4 failed — RED确认 ✓
原因: verify_2fa() 方法尚未实现
继续进入GREEN阶段...
```
**If tests unexpectedly pass (implementation already exists):**
```
⚠️ 警告: 测试意外通过
这可能意味着:
1. 功能已经存在(计划过期)
2. 测试写得不正确
3. 测试在错误的条件下通过
请确认如何处理?
```
---
#### Step 2.3: GREEN — Implement Code
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🟢 GREEN: 实现代码
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
【实现规格】(来自Plan)
文件: src/auth/service.py
接口: verify_2fa(user_id: UUID, code: str) -> bool
行为规格:
• 用户不存在 → UserNotFoundError
• 未启用2FA → TwoFactorNotEnabledError
• 验证码正确 → True
• 验证码错误 → False
参考: authenticate() 方法模式
```
**Determine implementation approach based on task type:**
**For Backend Logic — Use Codex:**
```
【调用 Codex 生成实现原型】
```
Invoke `mcp__codex__codex`:
```
Based on this specification, implement the function:
File: src/auth/service.py
Class: AuthService
Interface:
```python
async def verify_2fa(self, user_id: UUID, code: str) -> bool:
"""
验证用户的双因素认证码
Args:
user_id: 用户唯一标识
code: 6位TOTP验证码
Returns:
验证成功True失败False
Raises:
UserNotFoundError: 用户不存在
TwoFactorNotEnabledError: 用户未启用2FA
"""
```
Behavior:
- User not found → raise UserNotFoundError
- 2FA not enabled → raise TwoFactorNotEnabledError
- Valid code → return True, reset failed attempts
- Invalid code → return False, increment failed attempts
- Validation window: ±1 period (30 seconds tolerance)
Reference pattern: authenticate() method at line 78-95
Existing service: TotpService.verify() at src/auth/totp.py:23
Constraints:
- Use existing TotpService, do not reimplement TOTP logic
- Follow error handling pattern from authenticate()
- Store failed attempts in user.failed_2fa_attempts
Return ONLY the implementation code, no explanations.
```
**For Frontend UI — Use Gemini:**
Invoke `mcp__gemini__gemini`:
```
Based on this specification, implement the component:
...
```
**Receive and Review AI Output:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📝 Codex 生成的原型
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```python
async def verify_2fa(self, user_id: UUID, code: str) -> bool:
# Get user
user = await self.user_repository.get_by_id(user_id)
if not user:
raise UserNotFoundError(f"User {user_id} not found")
# Check if 2FA is enabled
if not user.is_2fa_enabled:
raise TwoFactorNotEnabledError(
f"2FA is not enabled for user {user_id}"
)
# Verify TOTP code
totp_service = TotpService()
is_valid = totp_service.verify(
secret=user.totp_secret,
code=code,
valid_window=1 # ±30 seconds
)
# Update attempt counters
if is_valid:
await self._reset_failed_2fa_attempts(user_id)
return True
else:
await self._increment_failed_2fa_attempts(user_id)
return False
```
```
**Claude Reviews and Refines:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔍 Claude 审查与改写
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
【审查结果】
✅ 接口签名正确
✅ 异常处理符合规格
⚠️ TotpService应复用实例非每次创建
⚠️ 缺少日志记录参考authenticate模式
✅ 失败计数逻辑正确
【改写后的代码】
```python
async def verify_2fa(self, user_id: UUID, code: str) -> bool:
"""验证用户的双因素认证码"""
logger.debug(f"Verifying 2FA for user {user_id}")
# Get user
user = await self.user_repository.get_by_id(user_id)
if not user:
logger.warning(f"2FA verification failed: user {user_id} not found")
raise UserNotFoundError(f"User {user_id} not found")
# Check if 2FA is enabled
if not user.is_2fa_enabled:
logger.warning(f"2FA verification failed: not enabled for {user_id}")
raise TwoFactorNotEnabledError(
f"2FA is not enabled for user {user_id}"
)
# Verify TOTP code using existing service
is_valid = self.totp_service.verify(
secret=user.totp_secret,
code=code,
valid_window=1
)
# Update attempt counters
if is_valid:
logger.info(f"2FA verification successful for user {user_id}")
await self._reset_failed_2fa_attempts(user_id)
return True
else:
logger.warning(f"2FA verification failed: invalid code for {user_id}")
await self._increment_failed_2fa_attempts(user_id)
return False
```
【变更说明】
1. 添加日志记录符合authenticate模式
2. 复用self.totp_service而非创建新实例
3. 保持其他逻辑不变
```
**Apply code and run tests:**
```bash
# 应用代码变更
# ... (write to src/auth/service.py)
# 运行测试
pytest tests/test_<module>.py -v
```
**Check GREEN status:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🟢 GREEN状态检查
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
测试结果:
• test_valid_code_should_pass PASSED ✅
• test_invalid_code_should_fail PASSED ✅
• test_user_not_found_should_raise PASSED ✅
• test_2fa_not_enabled_should_raise PASSED ✅
状态: 4 passed — GREEN确认 ✓
继续进入REFACTOR阶段...
```
**If tests fail:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
❌ 测试失败
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
失败测试:
• test_valid_code_should_pass — AssertionError: expected True, got None
【请求 Codex 分析修复】
```
Invoke `mcp__codex__codex`:
```
This test is failing:
Test:
```python
def test_valid_code_should_pass(...):
...
```
Error:
```
AssertionError: expected True, got None
```
Implementation:
```python
async def verify_2fa(...):
...
```
Analyze the issue and provide a fix.
```
**Loop until GREEN.**
---
#### Step 2.4: REFACTOR — Multi-Model Review
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔄 REFACTOR: 多模型审查
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
测试已通过,现在进行代码质量审查。
```
**Cross-Model Review:**
**Gemini reviews backend code (different perspective):**
Invoke `mcp__gemini__gemini`:
```
Review this implementation for code quality issues:
```python
async def verify_2fa(self, user_id: UUID, code: str) -> bool:
...
```
Check for:
1. Error handling completeness
2. Edge cases not covered
3. Security concerns
4. Code readability
5. Naming clarity
Format: [ISSUE] <description> → [SUGGESTION] <fix>
If no issues: [LGTM] <brief comment>
```
**Codex reviews for logic issues:**
Invoke `mcp__codex__codex`:
```
Review this implementation for logic issues:
```python
async def verify_2fa(self, user_id: UUID, code: str) -> bool:
...
```
Check for:
1. Race conditions
2. Missing validation
3. Performance concerns
4. Consistency with codebase patterns
Format: [ISSUE] <description> → [SUGGESTION] <fix>
If no issues: [LGTM] <brief comment>
```
**Review Results:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 审查结果
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
【Gemini 审查】
[LGTM] 代码清晰,错误处理完整,日志记录规范。
【Codex 审查】
[ISSUE] 未检查code参数格式应为6位数字
→ [SUGGESTION] 添加输入验证:
if not code or not code.isdigit() or len(code) != 6:
raise InvalidCodeFormatError("Code must be 6 digits")
【审查总结】
• Gemini: LGTM ✅
• Codex: 1个建议
是否采纳Codex的建议
```
Use `AskUserQuestions`:
```
question: "Codex建议添加code格式验证是否采纳"
options: [
"采纳,添加验证",
"跳过TotpService已有验证",
"采纳,但调整实现方式"
]
```
**If adopting suggestions:**
1. Apply the fix
2. Run tests again
3. Confirm still GREEN
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ REFACTOR 完成
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
代码审查: 双模型LGTM ✅
测试状态: 4 passed ✅
代码质量: 已优化
继续进入VERIFY阶段...
```
---
#### Step 2.5: VERIFY — Automated + Manual Verification
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✓ VERIFY: 验证阶段
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
【自动化验证】
```
**Run all automated checks from plan:**
```bash
# 单元测试
pytest tests/test_auth.py -v
# 期望: All passed
# 类型检查
mypy src/auth/service.py
# 期望: Success
# Lint检查
ruff check src/auth/
# 期望: No issues
# 完整测试套件(检查回归)
pytest tests/ -v --tb=short
# 期望: No regressions
```
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 自动化验证结果
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
| 检查项 | 状态 | 详情 |
|--------|------|------|
| 单元测试 | ✅ PASS | 4/4 passed |
| 类型检查 | ✅ PASS | No errors |
| Lint检查 | ✅ PASS | No issues |
| 回归测试 | ✅ PASS | 26/26 passed |
自动化验证: 全部通过 ✅
```
**Manual Verification Checklist:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
👤 手动验证清单
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
请手动验证以下项目:
[ ] 1. 启动应用,使用测试账户登录
[ ] 2. 启用2FA扫描二维码
[ ] 3. 输入正确验证码,确认登录成功
[ ] 4. 输入错误验证码,确认被拒绝
[ ] 5. 连续输入5次错误确认账户锁定
[ ] 6. 检查日志输出格式正确
完成后请确认。
```
Use `AskUserQuestions`:
```
question: "手动验证结果?"
options: [
"全部通过继续下一Phase",
"发现问题,需要修复",
"需要跳过某些验证项(请说明原因)"
]
```
---
#### Step 2.6: Phase Completion & Pause
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ Phase <N> 完成
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
【Phase总结】
┌─────────────────────────────────────────────┐
│ 文件变更: │
│ • src/auth/service.py (修改) │
│ • tests/test_auth.py (新增) │
│ │
│ 测试: │
│ • 新增: 4个 │
│ • 通过: 4个 │
│ • 回归: 0个 │
│ │
│ 审查: │
│ • Codex: LGTM │
│ • Gemini: LGTM │
└─────────────────────────────────────────────┘
【进度更新】
┌─────────────────────────────────────────────┐
│ Phase 1: <name> [✅] │
│ Phase 2: <name> [ ] │
│ Phase 3: <name> [ ] │
└─────────────────────────────────────────────┘
【建议操作】
1. 提交当前变更:
git add -A && git commit -m "feat(auth): implement 2FA verification - Phase 1"
2. 如果需要继续Phase 2:
输入 /clear 清空上下文
然后输入 /gudaspec:implementation gudaspec/plans/<id>/plan.md Phase 2
3. 如果需要暂停:
进度已保存随时可以从Phase 2继续
```
**Update plan.md with progress:**
```markdown
## Phase 1: 双因素认证核心逻辑 ✅
Completed: <timestamp>
Commit: <hash>
```
---
### Step 3: Handle Plan-Reality Mismatch
**When implementation discovers plan doesn't match reality:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠️ 计划与实际不匹配
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
【发现】
计划中: 修改 src/auth/service.py 的 AuthService 类
实际上: AuthService 已被重构为 AuthenticationService
【影响】
• Phase 1 的变更目标需要调整
• 接口位置变化,但功能规格不变
【选项】
```
Use `AskUserQuestions`:
```
question: "如何处理这个不匹配?"
options: [
"适配:按新结构实现相同功能",
"暂停返回Plan阶段更新计划",
"询问:需要更多信息来决定"
]
```
---
### Step 4: Final Completion
**After all Phases complete:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🎉 实施完成
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
需求ID: <requirement-id>
【完成摘要】
┌─────────────────────────────────────────────┐
│ Phase 1: 双因素认证核心逻辑 [✅] │
│ Phase 2: API端点实现 [✅] │
│ Phase 3: 前端集成 [✅] │
└─────────────────────────────────────────────┘
【变更统计】
• 文件变更: 12个
• 新增代码: ~450行
• 新增测试: 18个
• 测试覆盖: 87%
【提交历史】
• <hash1> feat(auth): implement 2FA verification - Phase 1
• <hash2> feat(auth): add 2FA API endpoints - Phase 2
• <hash3> feat(ui): integrate 2FA flow - Phase 3
【最终验证】
• 所有测试通过: ✅
• 类型检查通过: ✅
• Lint检查通过: ✅
• 双模型LGTM: ✅
【下一步】
1. 创建Pull Request
2. 请求代码审查
3. 合并到主分支
📋 归档:
相关文档将移动到 gudaspec/archive/<date>-<requirement-id>/
```
**Archive documents:**
```bash
mkdir -p gudaspec/archive/$(date +%Y-%m-%d)-<requirement-id>
mv gudaspec/research/<requirement-id> gudaspec/archive/$(date +%Y-%m-%d)-<requirement-id>/research
mv gudaspec/plans/<requirement-id> gudaspec/archive/$(date +%Y-%m-%d)-<requirement-id>/plan
```
---
## Level 0: Standard Verification Mode
**When test_level == 0, skip TDD cycle:**
```
Phase执行流程 (Level 0):
1. READ SPEC — 读取变更规格
2. IMPLEMENT — Claude直接实现可借助Codex/Gemini
3. MULTI-MODEL REVIEW — 双模型审查
4. VERIFY — 运行现有测试 + 手动验证
5. PAUSE — 等待人工确认
```
---
## Error Recovery
### Recovering from Failed Phase
```
/gudaspec:implementation gudaspec/plans/<id>/plan.md Phase 2
```
The command will:
1. Read plan and detect Phase 1 is marked complete
2. Start from Phase 2
3. Verify Phase 1 changes are still intact
### Recovering from Test Failures
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
❌ 无法达到GREEN状态
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
经过3次尝试测试仍然失败:
• test_valid_code_should_pass — TypeError: ...
【选项】
1. 继续尝试提供更多上下文给Codex
2. 暂停并请求帮助
3. 跳过此测试(需说明原因)
4. 返回Plan阶段修改规格
```
---
## Exit Criteria
- [ ] All Phases completed and marked in plan.md
- [ ] All tests passing (TDD Level 1-2) or verification passing (Level 0)
- [ ] Dual-model LGTM obtained for each Phase
- [ ] All manual verification items confirmed
- [ ] Changes committed with proper messages
- [ ] Documents archived
---
## Reference
- Plan document: `gudaspec/plans/<requirement-id>/plan.md`
- Test specifications: `gudaspec/plans/<requirement-id>/tests/`
- Backend implementation: Use `mcp__codex__codex`
- Frontend implementation: Use `mcp__gemini__gemini`
- Cross-review: Opposite model reviews implementation
<!-- GUDASPEC:IMPLEMENTATION:END -->

View File

@@ -1,59 +1,376 @@
---
name: GudaSpec: Init
description: Initialize OpenSpec environment with MCP tools validation for the current project.
description: Initialize GudaSpec environment with directory structure and MCP tools validation.
category: GudaSpec
tags: [openspec, init, setup, mcp]
tags: [gudaspec, init, setup, mcp, rpi]
---
<!-- GUDASPEC:START -->
**Guardrails**
- Detect the current operating system (Linux, macOS, Windows) and adjust shell commands accordingly.
- All example commands below assume a Linux/Unix environment; adapt syntax for PowerShell on Windows if detected.
<!-- GUDASPEC:INIT:START -->
## Purpose
初始化GudaSpec环境创建目录结构验证MCP工具可用性输出GudaSpec简介。
## Guardrails
- Detect the current operating system and adapt commands accordingly.
- Do not proceed to the next step until the current step completes successfully.
- Provide clear, actionable error messages when a step fails.
- Respect user's existing configurations and avoid overwriting without confirmation.
**Steps**
1. **Detect Operating System**
- Identify the current OS using appropriate methods (`uname -s` on Unix-like systems, or environment variables on Windows).
- Inform the user which OS was detected and note any command adaptations that will be made.
---
2. **Check and Install OpenSpec**
- Verify if `openspec` CLI is installed by running `openspec --version` or `which openspec` (Linux/macOS) / `where openspec` (Windows).
- If not installed, install globally using:
```bash
npm install -g @fission-ai/openspec@latest
```
- On Windows, use the same npm command in PowerShell or Command Prompt.
- Confirm installation success by running `openspec --version` after installation.
## Steps
3. **Initialize OpenSpec for Current Project**
- Run the initialization command:
```bash
openspec init --tools claude
```
- Verify that `openspec/` directory structure is created successfully.
- Report any initialization errors and suggest remediation steps.
### Step 1: Detect Environment
4. **Validate MCP Tools Availability**
- Check if `mcp__codex__codex` tool is available and responsive.
- Check if `mcp__gemini__gemini` tool is available and responsive.
- For each unavailable tool, display a clear warning message with installation instructions:
- **Codex MCP**: "The `mcp__codex__codex` tool is not available. Please install it from: https://github.com/GuDaStudio/codexmcp"
- **Gemini MCP**: "The `mcp__gemini__gemini` tool is not available. Please install it from: https://github.com/GuDaStudio/geminimcp"
- Explain that these MCP tools will be required for subsequent GudaSpec workflows.
```bash
# 检测操作系统
uname -s 2>/dev/null || echo "Windows"
5. **Summary Report**
- Display a summary of the initialization status:
- OpenSpec installation: ✓/✗
- Project initialization: ✓/✗
- `mcp__codex__codex` availability: ✓/✗
- `mcp__gemini__gemini` availability: ✓/✗
- If any components are missing, list the required actions before proceeding with other GudaSpec commands.
# 检测当前目录
pwd
```
**Reference**
- OpenSpec CLI documentation: Run `openspec --help` for available commands.
- Codex MCP installation: https://github.com/GuDaStudio/codexmcp
- Gemini MCP installation: https://github.com/GuDaStudio/geminimcp
- For Node.js/npm issues, ensure Node.js >= 18.x is installed.
- On permission errors during global npm install, consider using `sudo` (Linux/macOS) or running terminal as Administrator (Windows), or configure npm to use a user-writable directory.
<!-- GUDASPEC:END -->
Report detected environment:
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔍 环境检测
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
| 项目 | 检测结果 |
|------|----------|
| 操作系统 | <OS> |
| 当前目录 | <path> |
| Git仓库 | <yes/no> |
```
---
### Step 2: Check Existing GudaSpec Installation
```bash
# 检查是否已存在gudaspec目录
if [ -d "gudaspec" ]; then
echo "GUDASPEC_EXISTS=true"
ls -la gudaspec/
else
echo "GUDASPEC_EXISTS=false"
fi
```
**If gudaspec/ exists:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠️ 检测到已有GudaSpec安装
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
现有目录结构:
gudaspec/
├── research/ (<N>个需求)
├── plans/ (<N>个计划)
└── archive/ (<N>个归档)
```
Use `AskUserQuestions`:
```
question: "如何处理现有安装?"
options: [
"保留现有数据仅验证MCP工具",
"重新初始化现有数据将移动到backup/",
"取消初始化"
]
```
---
### Step 3: Create GudaSpec Directory Structure
```bash
# 创建目录结构
mkdir -p gudaspec/{research,plans,archive}
# 创建初始化标记文件
cat > gudaspec/.gudaspec.json << 'EOF'
{
"version": "1.0.0",
"initialized_at": "<ISO timestamp>",
"initialized_by": "claude",
"test_level_default": 1
}
EOF
```
Verify creation:
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📁 目录结构创建
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
gudaspec/
├── .gudaspec.json ✅ 配置文件
├── research/ ✅ 研究文档目录
├── plans/ ✅ 计划文档目录
└── archive/ ✅ 归档目录
目录结构创建: ✅ 完成
```
---
### Step 4: Validate MCP Tools Availability
Check each required MCP tool:
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔧 MCP工具验证
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```
**Check Codex MCP:**
- Attempt to invoke `mcp__codex__codex` with a simple test query
- Record availability status
**Check Gemini MCP:**
- Attempt to invoke `mcp__gemini__gemini` with a simple test query
- Record availability status
**Check Grok Search MCP:**
- Attempt to invoke `mcp__grok-search` with a simple test query
- Record availability status
**Display results:**
```
| MCP工具 | 状态 | 用途 |
|---------|------|------|
| mcp__codex__codex | ✅ / ❌ | 后端逻辑实现与审查 |
| mcp__gemini__gemini | ✅ / ❌ | 前端UI实现与审查 |
| mcp__grok-search | ✅ / ❌ | 实时在线搜索 |
```
**For each unavailable tool, display installation instructions:**
```
【缺失工具安装指南】
❌ mcp__codex__codex 不可用
用途: GudaSpec使用Codex作为后端逻辑实现引擎和代码审查器
安装: https://github.com/GuDaStudio/codexmcp
❌ mcp__gemini__gemini 不可用
用途: GudaSpec使用Gemini作为前端UI设计引擎和代码审查器
安装: https://github.com/GuDaStudio/geminimcp
❌ mcp__grok-search 不可用
用途: GudaSpec使用Grok Search进行实时在线文档搜索
安装: https://github.com/GuDaStudio/GrokSearch
```
---
### Step 5: Summary Report
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 初始化总结
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
【环境状态】
| 项目 | 状态 |
|------|------|
| GudaSpec目录 | ✅ 已创建 |
| mcp__codex__codex | ✅ / ❌ |
| mcp__gemini__gemini | ✅ / ❌ |
| mcp__grok-search | ✅ / ❌ |
【功能可用性】
| 功能 | 状态 | 依赖 |
|------|------|------|
| 内部研究 (Research) | ✅ | - |
| 外部调研 (Deep Research) | ✅ / ⚠️ | Grok Search |
| 计划制定 (Plan) | ✅ | - |
| 后端实现 | ✅ / ⚠️ | Codex |
| 前端实现 | ✅ / ⚠️ | Gemini |
| 多模型审查 | ✅ / ⚠️ | Codex + Gemini |
⚠️ = 功能可用但体验受限缺少对应MCP工具
```
**If any tools missing:**
```
【待处理事项】
请安装缺失的MCP工具以获得完整功能
1. <missing tool> — <installation url>
2. ...
```
---
### Step 7: Output GudaSpec Introduction
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
GudaSpec 简介
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
GudaSpec 是基于 RPI (Research-Plan-Implementation) 编码理论的 Claude Code
自定义命令集融合多模型协作与TDD测试驱动开发专为复杂场景设计。
┌─────────────────────────────────────────────────────────────────────────────┐
│ 核心理念 │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ 📊 RPI工作流 │
│ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │
│ │ RESEARCH │───▶│ PLAN │───▶│ IMPLEMENT │ │
│ │ 需求研究 │ │ 计划制定 │ │ 代码实现 │ │
│ └───────────────┘ └───────────────┘ └───────────────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ 约束集文档 规格文档 可运行代码 │
│ │
│ 🎯 核心原则 │
│ • 有效上下文专注 — 通过阶段分离极致利用上下文窗口保持40-60%利用率) │
│ • 频繁意向压缩 — 每阶段产出紧凑文档,/clear后作为下阶段种子 │
│ • 高杠杆审查点 — 审查规格而非代码,一行错误规格=百行错误代码 │
│ │
│ 🔧 多模型协作 │
│ • Codex — 后端逻辑实现与审查 │
│ • Gemini — 前端UI实现与审查 │
│ • Grok — 实时在线搜索与文档查询 │
│ • 双模型LGTM — 交叉审查确保代码质量 │
│ │
│ 🧪 TDD测试驱动可选
│ • Level 0: 标准验证Success Criteria
│ • Level 1: TDD模式Red-Green-Refactor
│ • Level 2: TDD + Property Testing发现边界情况
│ │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐
│ 命令速查 │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ 【Research阶段】将需求转化为约束集 │
│ ┌─────────────────────────────────────────────────────────────────────────┐│
│ │ /gudaspec:research │ 内部研究:分析代码库约束 ││
│ │ /gudaspec:research-review <id> │ 内部审查:确认约束,判断是否需外部 ││
│ │ /gudaspec:deepresearch <id> │ 外部研究:调研技术选型与最佳实践 ││
│ │ /gudaspec:deep-research-review <id> │ 外部审查:确认选型,生成需求文档 ││
│ └─────────────────────────────────────────────────────────────────────────┘│
│ ↓ /clear │
│ 【Plan阶段】将需求转化为零决策规格 │
│ ┌─────────────────────────────────────────────────────────────────────────┐│
│ │ /gudaspec:plan <requirement.md> │ 结构设计Phase划分测试策略选择 ││
│ │ /gudaspec:plan-review <id> │ 详细规格:接口定义,测试规格,审批 ││
│ └─────────────────────────────────────────────────────────────────────────┘│
│ ↓ /clear │
│ 【Implementation阶段】执行规格产出代码 │
│ ┌─────────────────────────────────────────────────────────────────────────┐│
│ │ /gudaspec:implementation <plan.md> [Phase N] ││
│ │ • TDD循环RED写测试→ GREEN写实现→ REFACTOR审查优化 ││
│ │ • 多模型协作Codex实现后端Gemini实现前端交叉审查 ││
│ │ • 逐Phase执行每Phase后暂停等待人工确认 ││
│ └─────────────────────────────────────────────────────────────────────────┘│
│ │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐
│ 目录结构 │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ gudaspec/ │
│ ├── research/ # 研究文档 │
│ │ └── <requirement-id>/ │
│ │ ├── internal.md # 内部研究(代码库约束) │
│ │ ├── external.md # 外部研究(技术选型) │
│ │ └── requirement.md # 最终需求文档 │
│ ├── plans/ # 计划文档 │
│ │ └── <requirement-id>/ │
│ │ ├── structure.md # 计划结构 │
│ │ ├── plan.md # 详细计划 │
│ │ └── tests/ # 测试规格 │
│ └── archive/ # 已完成需求归档 │
│ └── <date>-<requirement-id>/ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐
│ 典型工作流 │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ 简单需求Bug修复、小改动: │
│ /gudaspec:research → 描述需求 │
│ /clear → /gudaspec:research-review <id> → 跳过外部 → requirement.md │
│ /clear → /gudaspec:plan <req.md> │
│ /clear → /gudaspec:plan-review <id> │
│ /clear → /gudaspec:implementation <plan.md> │
│ │
│ 复杂需求(新功能、新技术): │
│ /gudaspec:research → 描述需求 │
│ /clear → /gudaspec:research-review <id> → 需要外部 │
│ /clear → /gudaspec:deepresearch <id> │
│ /clear → /gudaspec:deep-research-review <id> → requirement.md │
│ /clear → /gudaspec:plan <req.md> │
│ /clear → /gudaspec:plan-review <id> │
│ /clear → /gudaspec:implementation <plan.md> │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
```
---
### Step 8: Next Steps
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ GudaSpec 初始化完成
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 下一步操作:
1. 输入 /clear 清空当前上下文
(初始化信息较多,清空后开始新任务更高效)
2. 开始您的第一个需求:
输入 /gudaspec:research
然后描述您的需求
💡 提示:
• 每个阶段完成后记得 /clear 保持上下文干净
• 简单需求可跳过外部研究阶段
• 使用 Level 1 TDD模式可获得更高代码质量
• 多模型审查会自动进行,无需手动触发
📚 参考资源:
• RPI理论: https://github.com/humanlayer/humanlayer
• GudaSpec命令集: https://github.com/GuDaStudio/commands
• Codex MCP: https://github.com/GuDaStudio/codexmcp
• Gemini MCP: https://github.com/GuDaStudio/geminimcp
• Grok Search: https://github.com/GuDaStudio/GrokSearch
```
---
## Exit Criteria
- [ ] Operating system detected
- [ ] gudaspec/ directory structure created
- [ ] .gudaspec.json configuration file created
- [ ] All MCP tools checked and status reported
- [ ] Summary report displayed
- [ ] GudaSpec introduction output
- [ ] User directed to /clear and /gudaspec:research
---
## Reference
- GudaSpec Commands: https://github.com/GuDaStudio/commands
- HumanLayer RPI: https://github.com/humanlayer/humanlayer
- Codex MCP: https://github.com/GuDaStudio/codexmcp
- Gemini MCP: https://github.com/GuDaStudio/geminimcp
- Grok Search: https://github.com/GuDaStudio/GrokSearch
<!-- GUDASPEC:INIT:END -->

405
gudaspec/plan-review.md Normal file
View File

@@ -0,0 +1,405 @@
---
name: GudaSpec: Plan Review
description: Review plan structure, write detailed implementation plan with test specifications, and approve.
category: GudaSpec
tags: [gudaspec, plan, review, detail, tdd, approval]
argument-hint: [requirement-id]
---
<!-- GUDASPEC:PLAN-REVIEW:START -->
## Purpose
基于已确认的计划结构,编写详细实施计划,生成测试规格(如适用),多模型审查,最终用户批准。
## Core Principles
1. **Structure First** — 结构已在plan阶段确认本阶段聚焦细节
2. **Test-First When TDD** — Level 1-2时测试规格先于实现细节
3. **Interactive Review** — 逐Phase与用户确认非一次性输出
4. **Multi-Model Verification** — 多模型审查计划完整性
5. **Explicit Approval** — 必须获得用户明确批准
## Guardrails
- **MUST** load both structure.md and requirement.md first.
- **MUST** confirm each Phase with user before moving to next.
- **MUST** generate test specifications if test_level >= 1.
- **MUST** run multi-model review before final approval.
- **NEVER** finalize plan with open questions.
- Keep context under 60K tokens.
---
## Steps
### Step 0: Load Documents
```bash
cat gudaspec/plans/<requirement-id>/structure.md
cat gudaspec/research/<requirement-id>/requirement.md
```
Extract:
- Phase结构
- 测试策略Level
- 约束集
- 技术决策
### Step 1: Structure Confirmation
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 计划详细化: <Requirement Title>
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
需求ID: <requirement-id>
测试策略: Level <X>
【计划结构回顾】
Phase 1: <name> — <goal>
Phase 2: <name> — <goal>
Phase 3: <name> — <goal>
接下来我将逐Phase编写详细内容。
每个Phase完成后会请您确认。
准备开始?
```
### Step 2: Detail Each Phase (Interactive Loop)
**For each Phase:**
#### 2.1 Generate Test Specifications (if Level >= 1)
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🧪 Phase 1 测试规格
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
【测试目标】
验证: <what this phase should achieve>
【测试用例】
┌─────────────────────────────────────────────────────────────┐
│ Test 1: <test_name> │
├─────────────────────────────────────────────────────────────┤
│ 场景: <scenario description> │
│ 输入: <input> │
│ 期望: <expected output> │
│ 验证: <how to verify> │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ Test 2: <test_name> │
├─────────────────────────────────────────────────────────────┤
│ 场景: <edge case> │
│ 输入: <input> │
│ 期望: <expected output> │
│ 验证: <how to verify> │
└─────────────────────────────────────────────────────────────┘
【测试代码骨架】
```python
# tests/test_<module>.py
class TestPhase1<Feature>:
"""Phase 1: <name> 测试"""
def test_<scenario_1>(self):
"""
场景: <description>
期望: <expected>
"""
# Arrange
<setup code hint>
# Act
<action code hint>
# Assert
assert <condition>, "<failure message>"
def test_<scenario_2>(self):
"""边界情况: <description>"""
# TODO: Implement
pass
```
【Property Tests】(if Level 2)
```python
from hypothesis import given, strategies as st
@given(st.text(min_size=1, max_size=100))
def test_<property_name>(input_value):
"""
Property: <invariant description>
"""
result = <function>(input_value)
assert <property_condition>
```
```
Use `AskUserQuestions`:
```
question: "Phase 1 测试规格是否完整?"
options: [
"完整,继续编写实现细节",
"需要添加更多测试场景",
"需要修改某个测试",
"测试粒度不合适"
]
```
### Step 2.2: Write Implementation Details
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📝 Phase 1 变更规格
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
【变更清单】
1⃣ 认证服务扩展
┌─────────────────────────────────────────────────────────────┐
│ 文件: `src/auth/service.py`
│ 类型: 修改现有类 │
├─────────────────────────────────────────────────────────────┤
│ 【接口定义】 │
│ ```python │
│ async def verify_2fa( │
│ self, │
│ user_id: UUID, │
│ code: str │
│ ) -> bool: │
│ """ │
│ 验证用户的双因素认证码 │
│ │
│ Args: │
│ user_id: 用户唯一标识 │
│ code: 6位TOTP验证码 │
│ │
│ Returns: │
│ 验证成功True失败False │
│ │
│ Raises: │
│ UserNotFoundError: 用户不存在 │
│ TwoFactorNotEnabledError: 用户未启用2FA │
│ """ │
│ ``` │
├─────────────────────────────────────────────────────────────┤
│ 【行为规格】 │
│ • 用户不存在 → 抛出 UserNotFoundError │
│ • 用户未启用2FA → 抛出 TwoFactorNotEnabledError │
│ • 验证码正确 → 返回 True重置失败计数 │
│ • 验证码错误 → 返回 False增加失败计数 │
│ • 验证窗口 → ±1周期允许30秒误差
├─────────────────────────────────────────────────────────────┤
│ 【实现要点】 │
│ • 使用现有 TotpService.verify() 方法 │
│ • 遵循 authenticate() 的错误处理模式 │
│ • 失败计数存储于 user.failed_2fa_attempts │
├─────────────────────────────────────────────────────────────┤
│ 【参考模式】 │
│ • src/auth/service.py:78-95 authenticate() 方法 │
│ • src/auth/totp.py:23 TotpService.verify() 方法 │
├─────────────────────────────────────────────────────────────┤
│ 关联约束: HC-I-1复用TotpService, SC-I-2错误处理模式
│ 关联测试: test_valid_code_passes, test_invalid_code_fails │
└─────────────────────────────────────────────────────────────┘
【注意】: 以上是规格说明,非完整实现代码。
Implementation阶段将基于此规格编写实际代码。
```
Use `AskUserQuestions`:
```
question: "Phase 1 实现细节是否清晰完整?"
options: [
"清晰继续Phase 2",
"代码变更需要调整",
"执行顺序需要修改",
"Success Criteria需要补充"
]
```
#### 2.3 Repeat for Each Phase
Continue until all Phases are detailed.
### Step 3: Multi-Model Review
**Invoke `mcp__codex__codex`:**
```
Review this implementation plan:
[paste complete plan]
Check for:
1. Missing files that should be modified
2. Incorrect dependency order
3. Incomplete success criteria
4. Edge cases not covered by tests
Format: [ISSUE] <description> → [SUGGESTION] <fix>
```
**Invoke `mcp__gemini__gemini`:**
```
Review this implementation plan:
[paste complete plan]
Check for:
1. UI/UX gaps
2. Accessibility issues
3. Component interaction problems
4. Missing manual verification steps
Format: [ISSUE] <description> → [SUGGESTION] <fix>
```
**Present review findings:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔍 多模型审查结果
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
【Codex 发现】
• ⚠️ <issue 1> → 建议: <fix>
• ✅ 依赖顺序正确
• ✅ 测试覆盖完整
【Gemini 发现】
• ⚠️ <issue 2> → 建议: <fix>
• ✅ UI变更合理
【已自动修正】
• <auto-fixed issue>
【需要您确认】
• <issue requiring user decision>
```
### Step 4: Final Summary & Approval
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 计划总结
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
【计划概览】
┌─────────────────────────────────────────────────────────────┐
│ 需求: <requirement title> │
│ ID: <requirement-id> │
│ 测试策略: Level <X> │
├─────────────────────────────────────────────────────────────┤
│ │
│ Phase 1: <name> │
│ ├─ 文件变更: <N>个 │
│ ├─ 测试用例: <M>个 │
│ └─ 验证点: 自动<A>个 + 手动<B>个 │
│ │
│ Phase 2: <name> │
│ ├─ 文件变更: <N>个 │
│ ├─ 测试用例: <M>个 │
│ └─ 验证点: 自动<A>个 + 手动<B>个 │
│ │
│ Phase 3: <name> │
│ ├─ 文件变更: <N>个 │
│ ├─ 测试用例: <M>个 │
│ └─ 验证点: 自动<A>个 + 手动<B>个 │
│ │
├─────────────────────────────────────────────────────────────┤
│ 总计: │
│ • 文件变更: <total>个 │
│ • 测试用例: <total>个 │
│ • 自动验证: <total>个 │
│ • 手动验证: <total>个 │
│ • 风险等级: 中 │
└─────────────────────────────────────────────────────────────┘
【执行流程预览】
Phase 1 → 自动验证 → ⏸️手动确认 → Phase 2 → 自动验证 → ⏸️手动确认 → ...
【回滚计划】
如果任何Phase失败: <rollback strategy>
```
Use `AskUserQuestions`:
```
question: "是否批准此计划?"
options: [
"批准,保存完整计划",
"需要修改某个Phase",
"需要调整整体结构",
"有问题需要讨论"
]
```
### Step 5: Save Complete Plan
Save to: `gudaspec/plans/<requirement-id>/plan.md`
Also save test skeletons (if Level >= 1):
```
gudaspec/plans/<requirement-id>/tests/
├── test_spec.md
└── skeletons/
├── test_phase1.py
├── test_phase2.py
└── ...
```
Update structure.md status: `status: plan-approved`
### Step 6: Completion Output
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ 计划已批准
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
需求ID: <requirement-id>
📁 生成的文件:
gudaspec/plans/<requirement-id>/
├── structure.md (已更新状态)
├── plan.md (完整计划) ⭐
└── tests/
├── test_spec.md (测试规格)
└── skeletons/ (测试骨架代码)
📊 计划摘要:
┌─────────────────────────────────────────┐
│ Phases: [N] │
│ 文件变更: [X] │
│ 测试用例: [Y] │
│ 测试策略: Level [Z] │
└─────────────────────────────────────────┘
📋 下一步操作:
1. 输入 /clear 清空当前上下文
2. 输入 /gudaspec:implementation gudaspec/plans/<requirement-id>/plan.md
⚠️ 实施阶段提示:
• 将逐Phase执行每Phase有明确的停止点
• 测试将在实现前/后运行取决于TDD Level
• 每个Phase自动验证通过后等待您的手动确认
```
---
## Exit Criteria
- [ ] Structure document loaded and confirmed
- [ ] All Phases detailed with implementation steps
- [ ] Test specifications generated (if Level >= 1)
- [ ] Multi-model review completed and issues addressed
- [ ] User explicitly approved the plan
- [ ] plan.md saved with all details
- [ ] Test skeletons saved (if applicable)
- [ ] User directed to /gudaspec:implementation
<!-- GUDASPEC:PLAN-REVIEW:END -->

View File

@@ -1,61 +1,351 @@
---
name: GudaSpec: Plan
description: Refine proposals into zero-decision executable task flows via multi-model analysis.
description: Analyze requirements and design implementation plan structure with test strategy selection.
category: GudaSpec
tags: [gudaspec, plan, multi-model, pbt]
allowed-tools: Bash(openspec:*), mcp__codex__codex, mcp__gemini__gemini
argument-hint: [proposal_id]
tags: [gudaspec, plan, structure, multi-model, tdd]
argument-hint: [requirement.md path]
---
<!-- GUDASPEC:START -->
**Guardrails**
- If the project is detected to lack `./openspec/` dir, prompt the user to initialize the project using `/gudaspec:init`.
- Strictly adhere to **OpenSpec** rules when writing **standardized spec-structured projects**.
- The goal of this phase is to eliminate ALL decision points from the task flow—implementation should be pure mechanical execution.
- Do not proceed to implementation until every ambiguity is resolved and every constraint is explicitly documented.
- Multi-model collaboration is mandatory: use both `mcp__codex__codex` and `mcp__gemini__gemini` to surface blind spots and conflicting assumptions.
- Every requirement must have Property-Based Testing (PBT) properties defined—focus on invariants, not just example-based tests.
- If constraints cannot be fully specified, escalate back to the user rather than making assumptions.
**Steps**
1. Run `openspec view` to display all **Active Changes**, then confirm with the user which proposal ID (`<proposal_id>`) they wish to refine into a zero-decision plan.
<!-- GUDASPEC:PLAN:START -->
2. Run `/opsx:continue <proposal_id>` then follow it to review the current specs and improve quality of specs.
## Purpose
3. During the review progress, invoke both MCP tools to detect remaining ambiguities:
- Use `mcp__codex__codex` tool, e.g. "Review proposal <proposal_id> for decision points that remain unspecified. List each as: [AMBIGUITY] <description> → [REQUIRED CONSTRAINT] <what must be decided>."
- Use `mcp__gemini__gemini` tool, e.g. "Identify implicit assumptions in proposal <proposal_id>. For each assumption, specify: [ASSUMPTION] <description> → [EXPLICIT CONSTRAINT NEEDED] <concrete specification>."
- **Anti-Pattern Detection** (flag and reject):
- Information collection without decision boundaries (e.g., "JWT vs OAuth2 vs session—all viable")
- Technical comparisons without selection criteria
- Deferred decisions marked as "to be determined during implementation"
- **Target Pattern** (required for approval):
- Explicit technology choices with parameters (e.g., "JWT with accessToken TTL=15min, refreshToken TTL=7days")
- Concrete algorithm selections with configurations (e.g., "bcrypt with cost factor=12")
- Precise behavioral rules (e.g., "Lock account for 30min after 5 failed login attempts")
- Use `AskUserQuestions` tool for ANY ambiguity, NEVER assume or guess.
- **Iterate** with user until ALL ambiguities are resolved into explicit constraints.
分析需求文档设计计划结构选择测试策略。产出计划结构草案供review阶段确认和细化。
4. After clarifying requirements, modify the spec documents. For each change, you MUST run the command `openspec validate <proposal_id> --strict` to ensure the correct format.
## Core Principles
5. When backend logic modification requirements are identified, Invoke both MCP tools to derive testable invariants:
- Use `mcp__codex__codex` tool, e.g. "Extract Property-Based Testing properties from proposal <proposal_id>. For each requirement, identify: [INVARIANT] <mathematical property that must always hold> → [FALSIFICATION STRATEGY] <how to generate test cases that attempt to break it>."
- Use `mcp__codex__codex` tool, e.g. "Analyze proposal <proposal_id> for system properties. Define: [PROPERTY] <name> | [DEFINITION] <formal description> | [BOUNDARY CONDITIONS] <edge cases to test> | [COUNTEREXAMPLE GENERATION] <approach>."
- **PBT Property Categories to Extract**:
- **Commutativity/Associativity**: Order-independent operations
- **Idempotency**: Repeated operations yield same result
- **Round-trip**: Encode→Decode returns original
- **Invariant Preservation**: State constraints maintained across operations
- **Monotonicity**: Ordering guarantees (e.g., timestamps always increase)
- **Bounds**: Value ranges, size limits, rate constraints
- After modify the spec documents with the PBT, MUST run the command `openspec validate <proposal_id> --strict` to ensure the correct format.
1. **Read Everything First** — 完整读取所有引用文件后再分析
2. **Verify Before Plan** — 验证约束仍然有效
3. **Structure Before Detail** — 先确认结构,再写细节
4. **Test Strategy Early** — 在结构阶段就决定测试策略
6. For complex proposals, consider running steps 2-4 iteratively on sub-components and remind the user rather than the entire proposal at once.
## Guardrails
**Exit Criteria**
A proposal is ready to exit the Plan phase only when:
- [ ] All multi-model analyses completed and synthesized
- [ ] Zero ambiguities remain (verified by step 3 audit)
- [ ] All PBT properties documented with falsification strategies
- [ ] `openspec validate <id> --strict` returns zero issues
- [ ] User has explicitly approved all constraint decisions
<!-- GUDASPEC:END -->
- If project lacks `gudaspec/` directory, prompt user to run `/gudaspec:init`.
- **MUST** read requirement.md and ALL referenced files completely.
- **MUST** verify constraints against current codebase.
- **MUST** get user confirmation on plan structure before proceeding.
- **NEVER** write detailed implementation steps in this phase.
- Keep context under 50K tokens.
---
## Steps
### Step 0: Load Requirement Document
**With parameter:**
```
/gudaspec:plan gudaspec/research/<requirement-id>/requirement.md
```
Read the file and all files mentioned in it.
**Without parameter:**
```
请提供需求文档路径:
/gudaspec:plan gudaspec/research/<requirement-id>/requirement.md
```
### Step 1: Context Gathering & Verification
1. **Extract from requirement.md:**
- 约束集(硬约束 + 软约束)
- 技术决策
- 集成点
- 成功标准
- 实施边界
2. **Read all referenced source files**
3. **Verify constraints still valid:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔍 约束验证
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
| 约束ID | 状态 | 说明 |
|--------|------|------|
| HC-I-1 | ✅ 有效 | 代码未变更 |
| HC-I-2 | ⚠️ 变化 | 文件已移动到新位置 |
| SC-E-1 | ✅ 有效 | 外部API仍适用 |
```
4. **Present understanding for confirmation**
Use `AskUserQuestions` to confirm understanding.
### Step 2: Multi-Model Analysis
**Invoke `mcp__codex__codex`:**
```
Analyze this requirement for implementation planning:
[paste key constraints and decisions]
Identify:
1. Implementation risks
2. Dependency order between components
3. Edge cases to address
4. Suggested phase boundaries
```
**Invoke `mcp__gemini__gemini`:**
```
Analyze this requirement for implementation planning:
[paste key constraints and decisions]
Identify:
1. UI/UX implementation considerations
2. Component structure recommendations
3. State management implications
4. Testing challenges for frontend
```
**Present synthesized findings:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔍 多模型分析结果
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
【风险识别】
• <risk 1>
• <risk 2>
【依赖顺序建议】
1. <first>
2. <second>
3. <third>
【建议的Phase边界】
• Phase 1 与 Phase 2 在 <component> 处分界
• 原因: <rationale>
```
### Step 3: Test Strategy Selection
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🧪 测试策略选择
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
请选择本次实施的测试策略:
┌─────────────────────────────────────────────────────────────┐
│ Level 0: 标准验证模式 │
├─────────────────────────────────────────────────────────────┤
│ • 使用Success Criteria命令验证 │
│ • 不生成测试代码 │
│ • 适合: 简单修复、配置变更、原型探索 │
│ • 验证方式: 运行现有测试 + 手动检查 │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ Level 1: TDD模式 ⭐推荐 │
├─────────────────────────────────────────────────────────────┤
│ • 先写测试,再写实现 (Red-Green-Refactor) │
│ • 生成测试骨架代码 │
│ • 适合: 标准功能开发、API开发、业务逻辑 │
│ • 验证方式: 测试从红变绿 + 手动检查 │
│ │
│ 【TDD如何帮助AI开发】 │
│ • 失败测试为AI提供精确的任务定义 │
│ • 防止AI"幻觉"——测试会立即暴露错误 │
│ • 每个小步骤都有验证,错误不会累积 │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ Level 2: TDD + Property Testing │
├─────────────────────────────────────────────────────────────┤
│ • 包含Level 1全部内容 │
│ • 额外定义Property不变量 │
│ • 随机输入发现边界情况 │
│ • 适合: 关键业务逻辑、安全功能、数据处理 │
│ • 验证方式: 测试通过 + Property验证 + 手动检查 │
│ │
│ 【Property Testing示例】 │
│ • "密码永不出现在日志中" — 随机测试1000种输入 │
│ • "加密后解密等于原文" — 验证往返一致性 │
└─────────────────────────────────────────────────────────────┘
基于您的需求特点,我建议: Level <X>
原因: <rationale>
```
Use `AskUserQuestions`:
```
question: "选择测试策略Level"
options: [
"Level 0: 标准验证(简单任务)",
"Level 1: TDD模式推荐",
"Level 2: TDD + Property Testing关键逻辑",
"不确定,请解释更多"
]
```
### Step 4: Design Plan Structure
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📐 计划结构设计
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
【实施策略概述】
<1-2句话描述整体策略>
【Phase划分】
┌─────────────────────────────────────────────────────────────┐
│ Phase 1: <名称> │
├─────────────────────────────────────────────────────────────┤
│ 目标: <完成什么> │
│ 涉及: <模块/文件范围> │
│ 依赖: 无 │
│ 预计: ~<N>个文件变更 │
│ 测试: <Level对应的验证方式> │
└─────────────────────────────────────────────────────────────┘
│ 完成 + 验证通过
┌─────────────────────────────────────────────────────────────┐
│ Phase 2: <名称> │
├─────────────────────────────────────────────────────────────┤
│ 目标: <完成什么> │
│ 涉及: <模块/文件范围> │
│ 依赖: Phase 1 │
│ 预计: ~<N>个文件变更 │
│ 测试: <Level对应的验证方式> │
└─────────────────────────────────────────────────────────────┘
│ 完成 + 验证通过
┌─────────────────────────────────────────────────────────────┐
│ Phase 3: <名称> │
├─────────────────────────────────────────────────────────────┤
│ 目标: <完成什么> │
│ 涉及: <模块/文件范围> │
│ 依赖: Phase 2 │
│ 预计: ~<N>个文件变更 │
│ 测试: <Level对应的验证方式> │
└─────────────────────────────────────────────────────────────┘
【明确不包含】
• ❌ <排除项1> — 原因: <reason>
• ❌ <排除项2> — 原因: <reason>
【风险预判】
| 风险 | 严重度 | 缓解策略 |
|------|--------|----------|
| <risk> | 高/中/低 | <mitigation> |
```
Use `AskUserQuestions`:
```
question: "计划结构是否合适?"
options: [
"合适,保存并继续",
"需要调整Phase划分",
"需要调整范围边界",
"风险评估需要修改"
]
```
### Step 5: Save Structure Document
Save to: `gudaspec/plans/<requirement-id>/structure.md`
```markdown
---
requirement_id: <requirement-id>
created: <ISO timestamp>
planner: claude
status: structure-approved
test_level: <0|1|2>
requirement_ref: gudaspec/research/<requirement-id>/requirement.md
git_commit: <current commit>
branch: <current branch>
---
# Plan Structure: <Requirement Title>
## 实施策略
<strategy overview>
## 约束验证结果
| 约束ID | 状态 | 说明 |
|--------|------|------|
...
## 多模型分析摘要
### 风险
...
### 依赖顺序
...
## 测试策略
Level: <0|1|2>
原因: <rationale>
## Phase结构
### Phase 1: <name>
- 目标:
- 涉及:
- 依赖:
- 预计变更:
### Phase 2: <name>
...
## 不包含
- ❌ ...
## 风险预判
| 风险 | 严重度 | 缓解策略 |
...
## 下一步
/clear → /gudaspec:plan-review <requirement-id>
```
### Step 6: Completion Output
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ 计划结构已保存
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
需求ID: <requirement-id>
结构文档: gudaspec/plans/<requirement-id>/structure.md
结构摘要:
┌─────────────────────────────────────────┐
│ Phase数量: [N] │
│ 测试策略: Level [X] │
│ 预计文件变更: [Y] 个 │
│ 风险等级: 高/中/低 │
└─────────────────────────────────────────┘
📋 下一步操作:
1. 输入 /clear 清空当前上下文
2. 输入 /gudaspec:plan-review <requirement-id>
plan-review阶段将:
• 确认每个Phase的详细内容
• 生成具体的代码变更说明
• 生成测试规格Level 1-2
• 最终批准计划
```
---
## Exit Criteria
- [ ] Requirement document fully read and understood
- [ ] All referenced files read
- [ ] Constraints verified against current code
- [ ] Multi-model analysis completed
- [ ] Test strategy level selected
- [ ] Plan structure designed and approved
- [ ] Structure document saved
- [ ] User directed to /gudaspec:plan-review
<!-- GUDASPEC:PLAN:END -->

516
gudaspec/research-review.md Normal file
View File

@@ -0,0 +1,516 @@
---
name: GudaSpec: Research Review
description: Interactive review of internal research - user-friendly confirmation through guided questions.
category: GudaSpec
tags: [gudaspec, research, review, internal, interactive]
argument-hint: [requirement-id]
---
<!-- GUDASPEC:RESEARCH-REVIEW:START -->
## Purpose
以用户友好的方式审查内部研究发现。通过场景化描述和引导式问题,帮助用户理解并确认约束,无需深入技术细节。
## Core Principles
1. **场景驱动**:将技术约束转化为用户场景
2. **选择优先**:尽量提供选项而非开放式问题
3. **关联解释**:说明每个决策对后续的影响
4. **渐进深入**:先确认大方向,再处理细节
5. **智能分组**:将相关约束串联成有意义的主题
## Guardrails
- **MUST** use `AskUserQuestions` tool for all confirmations
- **MUST** translate technical constraints into user-understandable language
- **MUST** explain WHY each confirmation matters
- **NEVER** dump raw technical details without context
- **NEVER** ask users to confirm things they cannot reasonably evaluate
---
## Steps
### Step 0: Load and Analyze Internal Document
```bash
cat gudaspec/research/<requirement-id>/internal.md
```
After loading, perform **Constraint Clustering**:
- Group related constraints by theme/scenario
- Identify dependencies between constraints
- Rank by importance (blocking vs nice-to-have)
- Prepare user-friendly translations
### Step 1: Welcome and Context Setting
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 需求审查: <Requirement Description>
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
需求ID: <requirement-id>
我已完成代码库分析,发现了一些需要您确认的关键点。
接下来我会通过几个简单的问题来确认这些发现。
📊 审查概览:
┌─────────────────────────────────────┐
│ 核心场景确认 ████████░░ 3 个 │
│ 技术适配确认 ██████░░░░ 2 个 │
│ 实施边界确认 ████░░░░░░ 1 个 │
│ 开放问题 ██░░░░░░░░ 2 个 │
└─────────────────────────────────────┘
预计用时: 5-10 分钟
准备好开始了吗?
```
Use `AskUserQuestions`:
```
options: ["开始审查", "先看一下完整的研究文档"]
```
---
### Step 2: Core Scenario Confirmation (场景化约束确认)
**Strategy**: Group related constraints into user scenarios, ask about the scenario rather than individual constraints.
**Example Transformation**:
| 原始约束 (技术) | 转化后 (场景) |
|-----------------|---------------|
| HC-1: 密码必须bcrypt, cost=12 | |
| HC-2: 登录失败5次锁定30分钟 | → "用户登录安全" 场景 |
| HC-3: JWT用HS256算法 | |
| SC-1: 错误响应用RFC 7807格式 | |
**Scenario Presentation Format**:
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔐 场景 1/3: 用户登录安全
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
我发现项目中已有一套完整的登录安全机制:
【当前实现方式】
• 密码存储:使用 bcrypt 加密(业界推荐的安全方案)
• 防暴力破解:连续失败 5 次后锁定账户 30 分钟
• 登录凭证:使用 JWT Token15分钟过期
【这意味着什么】
您的新功能需要 [复用/适配/绕开] 这套机制。
如果您的功能涉及用户身份验证,必须走这套流程。
【对您需求的影响】
<根据具体需求说明影响,例如>
- 如果需要新增登录方式,需要集成到现有的 AuthService
- 如果需要延长登录时间,需要调整 JWT 配置
```
Use `AskUserQuestions`:
```
question: "您的需求与用户登录安全的关系是?"
options: [
"需要复用现有登录机制新增OAuth登录方式",
"需要修改现有机制(如:调整锁定策略)",
"与登录无关,可以跳过",
"不确定,需要更多解释"
]
```
**If user selects "不确定"**, provide deeper explanation:
```
让我举个具体例子:
假设您要添加"Outlook邮件集成"功能:
- 如果用户需要登录才能使用邮件功能 → 复用现有机制
- 如果Outlook需要单独的OAuth认证 → 可能需要扩展机制
- 如果只是后台同步邮件,用户无感知 → 与登录无关
您的需求更接近哪种情况?
```
**Record Decision**: Update internal.md with user's choice and rationale.
---
### Step 3: Technical Adaptation Confirmation (技术适配确认)
**Strategy**: Present technical constraints as "project rules" that need to be followed, ask if there are special reasons to deviate.
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔧 技术适配: 项目规范
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
我发现项目遵循以下规范,新代码应保持一致:
【代码风格】
┌────────────────────────────────────────────┐
│ 📁 目录结构: src/<模块>/[router|service|models].py
│ 📝 命名规范: 函数用 snake_case, 类用 PascalCase
│ 🧪 测试要求: 每个模块需要对应的 tests/<模块>/ 目录
│ 📦 依赖管理: 使用 pyproject.toml + poetry
└────────────────────────────────────────────┘
【API规范】
┌────────────────────────────────────────────┐
│ 🔗 路由风格: RESTful (如 /users/{id}/emails)
│ 📄 响应格式: 统一的 JSON 结构
│ ❌ 错误处理: 使用项目自定义的 AppException
└────────────────────────────────────────────┘
【为什么这很重要】
遵循这些规范可以:
• 让代码更容易被团队其他成员理解
• 复用现有的工具函数和中间件
• 保持项目整体一致性
```
Use `AskUserQuestions`:
```
question: "关于项目规范,请确认:"
options: [
"遵循以上所有规范(推荐)",
"大部分遵循,但有特殊情况需要说明",
"这是一个独立模块,可能需要不同的规范"
]
```
**If user selects special case**, follow up:
```
请告诉我特殊情况:
• 哪些规范可能需要调整?
• 调整的原因是什么?
```
---
### Step 4: Integration Points Confirmation (集成点确认)
**Strategy**: Visualize where new code connects to existing code, confirm the connection points.
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔌 集成点: 新代码如何接入现有系统
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
根据您的需求,新功能需要在以下位置与现有代码对接:
```
现有系统 您的新功能
───────── ─────────
┌─────────────┐ ┌─────────────┐
│ 用户模块 │◄─────────────│ Outlook │
│ users/ │ 获取用户 │ 集成模块 │
└─────────────┘ 信息 └─────────────┘
│ │
│ │
▼ ▼
┌─────────────┐ ┌─────────────┐
│ 认证模块 │◄─────────────│ OAuth │
│ auth/ │ 复用认证 │ 处理 │
└─────────────┘ └─────────────┘
```
【具体对接点】
1⃣ 用户信息获取
位置: src/users/service.py → UserService.get_by_id()
用途: 获取用户邮箱配置
2⃣ 认证复用
位置: src/auth/deps.py → get_current_user()
用途: 验证用户身份
【这意味着什么】
• 您的代码需要导入并调用这些现有函数
• 如果这些函数不满足需求,可能需要扩展(而非重写)
```
Use `AskUserQuestions`:
```
question: "这些集成点是否符合您的预期?"
options: [
"符合,按此方案集成",
"基本符合,但可能还需要其他集成点",
"不太确定,能否解释一下替代方案?"
]
```
---
### Step 5: Scope Boundary Confirmation (边界确认)
**Strategy**: Clearly state what IS and IS NOT included, get explicit confirmation.
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📐 实施边界: 明确范围
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
根据我的分析,本次实施的范围建议如下:
【✅ 包含在内】
• <功能点1>
• <功能点2>
• <功能点3>
【❌ 不包含(建议后续处理)】
• <排除项1> — 原因: <简要说明>
• <排除项2> — 原因: <简要说明>
【⚠️ 需要您决定】
• <边界模糊项> — 包含它会增加约 X 天工作量
```
Use `AskUserQuestions`:
```
question: "关于实施边界:"
options: [
"同意以上边界划分",
"需要包含更多功能(请说明)",
"范围太大,需要进一步缩减"
]
```
---
### Step 6: Open Questions (开放问题 - 智能提问)
**Strategy**: Transform technical open questions into business decisions with clear options.
**Example Transformation**:
| 原始问题 (技术) | 转化后 (业务决策) |
|-----------------|-------------------|
| "JWT TTL 设置多少?" | "用户需要多久重新登录一次?" |
| "是否需要 rate limiting" | "如何防止用户过于频繁调用?" |
| "缓存策略用什么?" | "数据实时性要求高吗?" |
**Presentation Format**:
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
❓ 需要您决定: 邮件同步频率
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
【背景】
Outlook邮件集成需要定期从服务器获取新邮件。
同步频率会影响:
• 实时性:频率越高,用户越快看到新邮件
• 成本频率越高API调用次数越多
• 性能:频率越高,服务器负载越大
【选项对比】
┌─────────────────────────────────────────────┐
│ 选项 │ 延迟 │ API成本 │ 适用场景 │
├─────────────────────────────────────────────┤
│ A. 实时推送 │ < 1秒 │ 高 │ 即时通讯 │
│ B. 每5分钟 │ ≤ 5分钟│ 中 │ 一般办公 │
│ C. 每30分钟 │ ≤ 30分钟│ 低 │ 非紧急 │
│ D. 手动刷新 │ 用户控制│ 最低 │ 低频使用 │
└─────────────────────────────────────────────┘
```
Use `AskUserQuestions`:
```
question: "邮件同步频率选择哪个方案?"
options: ["A. 实时推送", "B. 每5分钟推荐", "C. 每30分钟", "D. 手动刷新", "需要更多信息来决定"]
```
---
### Step 7: External Research Determination (智能判断)
**Strategy**: Don't just ask "need external research?", explain what would be researched and why.
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔍 是否需要外部调研?
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
基于以上讨论,我识别到以下可能需要外部调研的点:
【需要调研的内容】
┌─────────────────────────────────────────────┐
│ 1. Microsoft Graph API vs EWS │
│ 原因: 项目中没有Outlook集成先例 │
│ 影响: 决定整体技术架构 │
│ 调研内容: API能力对比、认证方式、限制 │
├─────────────────────────────────────────────┤
│ 2. OAuth 2.0 最佳实践 │
│ 原因: 现有OAuth实现仅支持Google │
│ 影响: Token管理和刷新策略 │
│ 调研内容: Microsoft OAuth流程差异 │
└─────────────────────────────────────────────┘
【如果跳过外部调研】
• 我将基于通用知识进行实施
• 可能无法选择最优方案
• 后续可能需要返工
【如果进行外部调研】
• 预计额外需要 1 轮对话
• 将获得针对性的技术选型建议
• 降低实施风险
```
Use `AskUserQuestions`:
```
question: "是否进行外部调研?"
options: [
"是,进行调研(推荐:涉及新技术)",
"否,我对技术选型已有明确想法",
"否,这是简单需求,不需要调研"
]
```
**If user skips and has clear idea**, follow up:
```
您提到已有明确想法,请告诉我:
• 您倾向使用什么技术方案?
• 有什么特殊考虑因素吗?
```
---
### Step 8: Summary and Confirmation (总结确认)
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ 审查总结
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
感谢您的耐心确认!以下是本次审查的结果:
【您的关键决策】
┌─────────────────────────────────────────────┐
│ 1. 登录安全: 复用现有机制 │
│ 2. 项目规范: 完全遵循 │
│ 3. 集成方案: 按建议的3个点对接 │
│ 4. 实施边界: 同意建议范围 │
│ 5. 同步频率: 每5分钟 │
│ 6. 外部调研: 需要 │
└─────────────────────────────────────────────┘
【这些决策的影响】
• 实施复杂度: 中等
• 预计涉及文件: 8-12 个
• 需要新增依赖: 2 个 (msgraph-sdk, msal)
【下一步】
<根据是否需要外部调研显示不同内容>
```
Use `AskUserQuestions`:
```
question: "以上总结是否准确?"
options: [
"准确,继续下一步",
"需要修改某项决策",
"需要补充说明"
]
```
---
### Step 9: Output and Next Steps
**If External Research Needed**:
```
✅ Internal Research 审查完成
需求ID: <requirement-id>
审查状态: 已确认,待外部调研
📋 下一步操作:
1. 输入 /clear 清空当前上下文
2. 输入 /gudaspec:deepresearch <requirement-id> 开始外部调研
外部调研将解答:
• Microsoft Graph API 技术选型
• OAuth 2.0 集成方案
```
**If No External Research Needed**:
```
✅ Research 全部完成
需求ID: <requirement-id>
最终需求文档: gudaspec/research/<requirement-id>/requirement.md
📋 下一步操作:
1. 输入 /clear 清空当前上下文
2. 输入 /gudaspec:plan gudaspec/research/<requirement-id>/requirement.md
```
---
## Question Design Patterns (问题设计模式)
### Pattern 1: Scenario-Based (场景式)
```
【场景描述】
当用户执行 <动作> 时,系统当前会 <行为>。
【问题】
您的需求是否需要改变这个行为?
```
### Pattern 2: Impact-Driven (影响驱动)
```
【发现】
项目使用 <技术/模式>。
【如果遵循】<好处>
【如果偏离】<代价>
【问题】
您希望如何处理?
```
### Pattern 3: Trade-off (权衡式)
```
【权衡点】
<选项A> vs <选项B>
【A的特点】<优劣>
【B的特点】<优劣>
【问题】
哪个更符合您的需求?
```
### Pattern 4: Clarification (澄清式)
```
【我的理解】
您希望实现 <功能描述>
【确认点】
- <细节1>: 是这样吗?
- <细节2>: 还是这样?
【问题】
我的理解正确吗?
```
---
## Exit Criteria
- [ ] All scenarios confirmed via interactive questions
- [ ] All user decisions recorded with rationale
- [ ] External research need determined with clear reasoning
- [ ] User explicitly confirmed summary
- [ ] Document updated with confirmed decisions
- [ ] User directed to appropriate next step
<!-- GUDASPEC:RESEARCH-REVIEW:END -->

View File

@@ -1,97 +1,296 @@
---
name: GudaSpec Research
description: Transform user requirements into constraint sets through parallel exploration and analysis
name: GudaSpec: Research
description: Internal codebase research - analyze existing code constraints and generate requirement ID.
category: GudaSpec
tags: [gudaspec, research, constraints, exploration, subagents]
tags: [gudaspec, research, internal, brownfield, constraints]
---
<!-- GUDASPEC:RESEARCH:START -->
**Core Philosophy**
- If the project is detected to lack `./openspec/` dir, prompt the user to initialize the project using `/gudaspec:init`.
- Research produces **constraint sets**, not information dumps. Each constraint narrows the solution space.
- Constraints tell subsequent stages "don't consider this direction," enabling mechanical execution without decisions.
- The output is "約束集合 + 可验证的成功判据" (constraint sets + verifiable success criteria).
- Eliminate ambiguity through structured exploration and user interaction.
- Strictly adhere to **OpenSpec** rules when writing **standardized spec-structured projects**.
**Guardrails**
- **NEVER** divide subagent tasks by roles (e.g., "架构师agent", "安全专家agent").
- **ALWAYS** divide by context boundaries (e.g., "user-related code", "authentication logic", "infrastructure config").
- Each subagent context must be self-contained with independent output.
- **MANDATORY**: Use `mcp__auggie-mcp__codebase-retrieval` to minimize search/grep/find operations.
- All subagents must follow the same structured output template for aggregation.
- Do not make architectural decisions—surface constraints that guide decisions.
## CRITICAL: DOCUMENT ONLY, NO SUGGESTIONS
**Steps**
0. **Generate OpenSpec Proposal**
- Run `/opsx:explore <user question>` always first.
- **DO NOT** suggest improvements or changes
- **DO NOT** critique implementation or identify problems
- **DO NOT** recommend refactoring or optimizations
- **ONLY** describe: what exists, where it exists, how components interact
- You are creating a **technical map** of constraints, not a roadmap for changes
1. **Initial Codebase Assessment**
- Combine user requirements with quick codebase scan using `mcp__auggie-mcp__codebase-retrieval`.
- Determine project scale: single directory vs. multi-directory structure.
- **Decision point**: If code spans multiple subdirectories or modules → enable parallel Explore subagents.
- Document finding: "Single agent serial exploration is inefficient; parallel subagents required."
## Purpose
2. **Define Exploration Boundaries (Context-Based Division)**
- Identify natural context boundaries in the codebase (NOT functional roles).
- Example divisions:
* Subagent 1: User domain code (user models, user services, user UI)
* Subagent 2: Authentication & authorization code (auth middleware, session, tokens)
* Subagent 3: Configuration & infrastructure (configs, deployments, build scripts)
- Each boundary should be self-contained: no cross-communication needed between subagents.
- Define exploration scope and expected output for each subagent.
- The subagent takes forever to run, forcing you to wait—absolutely nothing else can be done until the subagent's results are fully obtained.
执行代码域调研Internal Research分析现有代码库约束生成需求ID和待审查的内部研究文档。
3. **Prepare Standardized Output Template**
- Define a unified JSON schema that all Explore subagents must follow:
```json
{
"module_name": "string - context boundary explored",
"existing_structures": ["list of key structures/patterns found"],
"existing_conventions": ["list of conventions/standards in use"],
"constraints_discovered": ["list of hard constraints that limit solution space"],
"open_questions": ["list of ambiguities requiring user input"],
"dependencies": ["list of dependencies on other modules/systems"],
"risks": ["list of potential risks or blockers"],
"success_criteria_hints": ["observable behaviors that indicate success"]
}
```
- Communicate template to all subagents for consistency.
## Guardrails
4. **Parallel Subagent Dispatch**
- For each defined context boundary, spawn an Explore subagent with:
* **Explicit instruction**: "You MUST use `mcp__auggie-mcp__codebase-retrieval` to reduce search operations."
* Defined scope and context boundary.
* Required output template (from Step 3).
* Clear success criteria: complete analysis of assigned boundary.
- Monitor subagent execution and collect structured reports.
- If project lacks `./openspec/` directory, prompt user to run `/gudaspec:init`.
- **MANDATORY**: Use `mcp__auggie-mcp__codebase-retrieval` to minimize grep/find operations.
- **NEVER** divide tasks by roles. **ALWAYS** divide by context boundaries.
- Base all judgments on code evidence. Speculation prohibited.
- All findings must include file:line references.
5. **Aggregate and Synthesize Reports**
- Collect all subagent JSON outputs.
- Merge findings into unified constraint sets:
* **Hard constraints**: Technical limitations, existing patterns that cannot be violated.
* **Soft constraints**: Conventions, preferences, style guides.
* **Dependencies**: Cross-module relationships that affect implementation order.
* **Risks**: Potential blockers that need mitigation.
- Identify **open questions** from all reports that require user clarification.
- Synthesize **success criteria** from scenario hints across all contexts.
---
6. **User Interaction for Ambiguity Resolution**
- Compile prioritized list of open questions from aggregated reports.
- Use `AskUserQuestions` tool to present questions systematically:
* Group related questions together.
* Provide context for each question.
* Suggest default answers when applicable.
- Capture user responses as additional constraints.
- Update constraint sets with confirmed decisions.
## Steps
7. **Generate OpenSpec Proposal**
- Run `/opsx:ff <requirement-description>` and follow it.
- When generate `proposal.md`, strictly prohibit abbreviating user requirements; only expansion is allowed. The generated document MUST NOT contain any ambiguous content. For example, specific project files mentioned by the user must be accurately referenced down to the file path, and should not be abbreviated in a way that misleads document readers into thinking it refers to an online-searched project rather than a local one.
### Step 0: Receive Requirement
When invoked, respond:
```
我已准备好进行代码域调研。请描述您的需求,我将:
1. 分析现有代码库中的相关约束
2. 生成需求ID便于后续管理
3. 输出待审查的内部研究文档
请描述您的需求:
```
Wait for user input.
### Step 1: Generate Requirement ID
Based on user's requirement description, generate a kebab-case ID:
**命名规范**参考OpenSpec
- 格式: `<action>-<target>[-<scope>]`
- 动作词: `add`, `fix`, `update`, `remove`, `refactor`, `migrate`
- 全小写,单词间用连字符
- 长度: 3-5个单词
- 避免缩写,保持可读性
**示例**
| 用户需求 | 生成的需求ID |
|----------|--------------|
| "添加Outlook邮件前端" | `add-outlook-email-frontend` |
| "修复用户登录超时问题" | `fix-user-login-timeout` |
| "重构支付模块" | `refactor-payment-module` |
| "添加双因素认证" | `add-two-factor-auth` |
| "迁移数据库到PostgreSQL" | `migrate-database-postgresql` |
Confirm with user:
```
需求ID: <generated-id>
确认此ID或提供修改建议
```
### Step 2: Read Mentioned Files
- If user mentions specific files, read them **FULLY** before proceeding
- This ensures complete context before decomposition
### Step 3: Codebase Assessment
Use `mcp__auggie-mcp__codebase-retrieval` to:
- Scan project structure
- Identify relevant modules/directories
- Determine context boundaries for parallel research
### Step 4: Define Context Boundaries
Divide by **context**, not roles:
| Correct (Context) | Incorrect (Role) |
|-------------------|------------------|
| User-related code | "架构师 agent" |
| Authentication layer | "安全专家 agent" |
| Data access layer | "DBA agent" |
| Target feature area | "领域专家 agent" |
### Step 5: Parallel Subagent Research
For each context boundary, spawn subagent:
```
You are a documentarian, NOT a critic.
Document what EXISTS, not what SHOULD BE.
Context: [boundary_name]
Scope: [directories/files]
Output JSON:
{
"context_boundary": "string",
"relevant_files": [{"path": "", "purpose": "", "key_exports": [], "lines": ""}],
"existing_patterns": ["pattern - location"],
"hard_constraints": ["constraint - file:line - reason"],
"soft_constraints": ["convention - where observed"],
"dependencies": {"internal": [], "external": []},
"information_flow": "description",
"integration_points": ["where new code must connect"],
"open_questions": ["question - context"]
}
```
### Step 6: Aggregate and Generate Internal Document
Create directory and file:
```
gudaspec/research/<requirement-id>/internal.md
```
**Document Template**:
````markdown
---
requirement_id: <requirement-id>
created: <ISO timestamp>
researcher: claude
git_commit: <current commit>
branch: <current branch>
status: pending-review
type: internal
---
# Internal Research: <Requirement Description>
## 需求概述
<用户原始需求描述 - 完整记录>
## 代码库概况
### 项目结构
```
<relevant directory tree>
```
### 技术栈
| 类型 | 技术 | 版本 | 配置位置 |
|------|------|------|----------|
| 框架 | | | |
| 数据库 | | | |
| ... | | | |
---
## 约束发现
### 硬约束 (CANNOT violate)
> 以下约束必须严格遵守,违反将导致系统故障或不兼容
| ID | 约束描述 | 来源 | 原因 | 确认 |
|----|----------|------|------|------|
| HC-1 | | `file:line` | | [ ] |
| HC-2 | | `file:line` | | [ ] |
| HC-3 | | `file:line` | | [ ] |
### 软约束 (SHOULD follow)
> 以下为项目惯例,建议遵循以保持一致性
| ID | 约束描述 | 观察位置 | 灵活度 | 确认 |
|----|----------|----------|--------|------|
| SC-1 | | | | [ ] |
| SC-2 | | | | [ ] |
---
## 相关文件分析
### 核心文件
| 文件路径 | 用途 | 关键导出 | 与需求关系 | 确认 |
|----------|------|----------|------------|------|
| | | | | [ ] |
| | | | | [ ] |
### 信息流
```
<ASCII diagram showing data flow relevant to requirement>
```
确认信息流准确: [ ]
---
## 集成点
> 新代码需要与以下位置对接
| ID | 集成位置 | 文件 | 对接方式 | 确认 |
|----|----------|------|----------|------|
| IP-1 | | | | [ ] |
| IP-2 | | | | [ ] |
---
## 依赖关系
### 内部依赖
| 模块 | 依赖 | 关系类型 | 确认 |
|------|------|----------|------|
| | | | [ ] |
### 外部依赖
| 包名 | 版本 | 用途 | 确认 |
|------|------|------|------|
| | | | [ ] |
---
## 现有测试
| 测试文件 | 覆盖范围 | 状态 | 与需求相关 | 确认 |
|----------|----------|------|------------|------|
| | | | | [ ] |
---
## 开放问题
> 以下问题需要您的确认
| ID | 问题 | 上下文 | 您的回答 |
|----|------|--------|----------|
| OQ-1 | | | __________ |
| OQ-2 | | | __________ |
| OQ-3 | | | __________ |
---
## External Research 初步判断
基于以上内部研究,以下情况可能需要外部调研:
| 触发条件 | 检测结果 | 说明 |
|----------|----------|------|
| 引入新技术/库 | ⬜ 是 / ⬜ 否 | |
| 代码库无相关参考 | ⬜ 是 / ⬜ 否 | |
| 新架构模式 | ⬜ 是 / ⬜ 否 | |
| 未知领域知识 | ⬜ 是 / ⬜ 否 | |
| 用户显式要求 | ⬜ 是 / ⬜ 否 | |
初步建议: [ ] 需要 External Research / [ ] 不需要
````
### Step 7: Final Output
```
✅ Internal Research 完成
需求ID: <requirement-id>
文档位置: gudaspec/research/<requirement-id>/internal.md
发现摘要:
- 硬约束: [X] 条
- 软约束: [Y] 条
- 集成点: [Z] 处
- 开放问题: [N] 个
📋 下一步操作:
1. 输入 /clear 清空当前上下文
2. 输入 /gudaspec:research-review <requirement-id> 开始审查
```
---
## Exit Criteria
- [ ] Requirement ID generated and confirmed
- [ ] All context boundaries explored
- [ ] Internal document saved to `gudaspec/research/<id>/internal.md`
- [ ] All checkboxes initialized as unchecked
- [ ] User reminded to `/clear` and proceed to review
**Reference**
- Inspect codebase structure: `ls -R` or `mcp__auggie-mcp__codebase-retrieval`
- Validate subagent outputs conform to template before aggregation.
- Use `AskUserQuestions` for ANY ambiguity—do not assume or guess.
- Always base judgments on project codes, strictly prohibiting the use of general knowledge for speculation. It is permissible to indicate uncertainty to users.
<!-- GUDASPEC:RESEARCH:END -->