mirror of
https://github.com/sweetwisdom/everything-claude-code-zh.git
synced 2026-03-26 10:20:14 +00:00
docs: 完成所有文档的中文翻译并应用到项目
This commit is contained in:
@@ -1,29 +1,29 @@
|
||||
# Build and Fix
|
||||
# 构建与修复 (Build and Fix)
|
||||
|
||||
Incrementally fix TypeScript and build errors:
|
||||
增量式修复 TypeScript 与构建错误:
|
||||
|
||||
1. Run build: npm run build or pnpm build
|
||||
1. 运行构建:npm run build 或 pnpm build
|
||||
|
||||
2. Parse error output:
|
||||
- Group by file
|
||||
- Sort by severity
|
||||
2. 解析错误输出:
|
||||
- 按文件分组
|
||||
- 按严重程度排序
|
||||
|
||||
3. For each error:
|
||||
- Show error context (5 lines before/after)
|
||||
- Explain the issue
|
||||
- Propose fix
|
||||
- Apply fix
|
||||
- Re-run build
|
||||
- Verify error resolved
|
||||
3. 针对每个错误:
|
||||
- 显示错误上下文(前后 5 行)
|
||||
- 解释问题所在
|
||||
- 提出修复方案
|
||||
- 执行修复
|
||||
- 重新运行构建
|
||||
- 验证错误是否已解决
|
||||
|
||||
4. Stop if:
|
||||
- Fix introduces new errors
|
||||
- Same error persists after 3 attempts
|
||||
- User requests pause
|
||||
4. 停止条件:
|
||||
- 修复引入了新错误
|
||||
- 同一错误在 3 次尝试后依然存在
|
||||
- 用户请求暂停
|
||||
|
||||
5. Show summary:
|
||||
- Errors fixed
|
||||
- Errors remaining
|
||||
- New errors introduced
|
||||
5. 显示摘要:
|
||||
- 已修复的错误
|
||||
- 剩余的错误
|
||||
- 新引入的错误
|
||||
|
||||
Fix one error at a time for safety!
|
||||
为了安全起见,一次只修复一个错误!
|
||||
|
||||
@@ -1,37 +1,37 @@
|
||||
# Checkpoint Command
|
||||
# 检查点(Checkpoint)指令
|
||||
|
||||
Create or verify a checkpoint in your workflow.
|
||||
在工作流(Workflow)中创建或验证检查点。
|
||||
|
||||
## Usage
|
||||
## 用法
|
||||
|
||||
`/checkpoint [create|verify|list] [name]`
|
||||
|
||||
## Create Checkpoint
|
||||
## 创建检查点(Create Checkpoint)
|
||||
|
||||
When creating a checkpoint:
|
||||
创建检查点时:
|
||||
|
||||
1. Run `/verify quick` to ensure current state is clean
|
||||
2. Create a git stash or commit with checkpoint name
|
||||
3. Log checkpoint to `.claude/checkpoints.log`:
|
||||
1. 运行 `/verify quick` 以确保当前状态干净
|
||||
2. 使用检查点名称创建一个 git stash 或提交(Commit)
|
||||
3. 将检查点记录到 `.claude/checkpoints.log`:
|
||||
|
||||
```bash
|
||||
echo "$(date +%Y-%m-%d-%H:%M) | $CHECKPOINT_NAME | $(git rev-parse --short HEAD)" >> .claude/checkpoints.log
|
||||
```
|
||||
|
||||
4. Report checkpoint created
|
||||
4. 报告检查点已创建
|
||||
|
||||
## Verify Checkpoint
|
||||
## 验证检查点(Verify Checkpoint)
|
||||
|
||||
When verifying against a checkpoint:
|
||||
对比检查点进行验证时:
|
||||
|
||||
1. Read checkpoint from log
|
||||
2. Compare current state to checkpoint:
|
||||
- Files added since checkpoint
|
||||
- Files modified since checkpoint
|
||||
- Test pass rate now vs then
|
||||
- Coverage now vs then
|
||||
1. 从日志中读取检查点
|
||||
2. 将当前状态与检查点进行对比:
|
||||
- 自检查点以来新增的文件
|
||||
- 自检查点以来修改的文件
|
||||
- 当前与当时的测试通过率对比
|
||||
- 当前与当时的代码覆盖率对比
|
||||
|
||||
3. Report:
|
||||
3. 报告:
|
||||
```
|
||||
CHECKPOINT COMPARISON: $NAME
|
||||
============================
|
||||
@@ -41,17 +41,17 @@ Coverage: +X% / -Y%
|
||||
Build: [PASS/FAIL]
|
||||
```
|
||||
|
||||
## List Checkpoints
|
||||
## 列出检查点(List Checkpoints)
|
||||
|
||||
Show all checkpoints with:
|
||||
- Name
|
||||
- Timestamp
|
||||
显示所有检查点,包括:
|
||||
- 名称
|
||||
- 时间戳
|
||||
- Git SHA
|
||||
- Status (current, behind, ahead)
|
||||
- 状态(当前、落后、超前)
|
||||
|
||||
## Workflow
|
||||
## 工作流(Workflow)
|
||||
|
||||
Typical checkpoint flow:
|
||||
典型的检查点工作流:
|
||||
|
||||
```
|
||||
[Start] --> /checkpoint create "feature-start"
|
||||
@@ -65,10 +65,10 @@ Typical checkpoint flow:
|
||||
[PR] --> /checkpoint verify "feature-start"
|
||||
```
|
||||
|
||||
## Arguments
|
||||
## 参数(Arguments)
|
||||
|
||||
$ARGUMENTS:
|
||||
- `create <name>` - Create named checkpoint
|
||||
- `verify <name>` - Verify against named checkpoint
|
||||
- `list` - Show all checkpoints
|
||||
- `clear` - Remove old checkpoints (keeps last 5)
|
||||
- `create <name>` - 创建具名检查点
|
||||
- `verify <name>` - 对比指定的检查点进行验证
|
||||
- `list` - 显示所有检查点
|
||||
- `clear` - 移除旧检查点(保留最后 5 个)
|
||||
|
||||
@@ -1,40 +1,40 @@
|
||||
# Code Review
|
||||
# 代码审查 (Code Review)
|
||||
|
||||
Comprehensive security and quality review of uncommitted changes:
|
||||
对未提交的更改进行全面的安全和质量审查:
|
||||
|
||||
1. Get changed files: git diff --name-only HEAD
|
||||
1. 获取已更改的文件:`git diff --name-only HEAD`
|
||||
|
||||
2. For each changed file, check for:
|
||||
2. 对每个更改的文件,检查以下项:
|
||||
|
||||
**Security Issues (CRITICAL):**
|
||||
- Hardcoded credentials, API keys, tokens
|
||||
- SQL injection vulnerabilities
|
||||
- XSS vulnerabilities
|
||||
- Missing input validation
|
||||
- Insecure dependencies
|
||||
- Path traversal risks
|
||||
**安全问题 (Security Issues) (严重 - CRITICAL):**
|
||||
- 硬编码的凭据、API 密钥、令牌 (Tokens)
|
||||
- SQL 注入漏洞
|
||||
- XSS 漏洞
|
||||
- 缺少输入验证
|
||||
- 不安全的依赖项
|
||||
- 路径遍历风险
|
||||
|
||||
**Code Quality (HIGH):**
|
||||
- Functions > 50 lines
|
||||
- Files > 800 lines
|
||||
- Nesting depth > 4 levels
|
||||
- Missing error handling
|
||||
- console.log statements
|
||||
- TODO/FIXME comments
|
||||
- Missing JSDoc for public APIs
|
||||
**代码质量 (Code Quality) (高 - HIGH):**
|
||||
- 函数长度 > 50 行
|
||||
- 文件长度 > 800 行
|
||||
- 嵌套深度 > 4 层
|
||||
- 缺少错误处理
|
||||
- `console.log` 语句
|
||||
- TODO/FIXME 注释
|
||||
- 公共 API 缺少 JSDoc
|
||||
|
||||
**Best Practices (MEDIUM):**
|
||||
- Mutation patterns (use immutable instead)
|
||||
- Emoji usage in code/comments
|
||||
- Missing tests for new code
|
||||
- Accessibility issues (a11y)
|
||||
**最佳实践 (Best Practices) (中 - MEDIUM):**
|
||||
- 变更模式 (Mutation patterns)(应改用不可变模式 (immutable))
|
||||
- 代码/注释中使用 Emoji
|
||||
- 新代码缺少测试
|
||||
- 无障碍访问问题 (a11y)
|
||||
|
||||
3. Generate report with:
|
||||
- Severity: CRITICAL, HIGH, MEDIUM, LOW
|
||||
- File location and line numbers
|
||||
- Issue description
|
||||
- Suggested fix
|
||||
3. 生成包含以下内容的报告:
|
||||
- 严重程度 (Severity):严重 (CRITICAL)、高 (HIGH)、中 (MEDIUM)、低 (LOW)
|
||||
- 文件位置和行号
|
||||
- 问题描述
|
||||
- 修复建议
|
||||
|
||||
4. Block commit if CRITICAL or HIGH issues found
|
||||
4. 如果发现“严重 (CRITICAL)”或“高 (HIGH)”级别的问题,则阻止提交 (Block commit)
|
||||
|
||||
Never approve code with security vulnerabilities!
|
||||
绝不要批准带有安全漏洞的代码!
|
||||
|
||||
322
commands/e2e.md
322
commands/e2e.md
@@ -1,60 +1,60 @@
|
||||
---
|
||||
description: Generate and run end-to-end tests with Playwright. Creates test journeys, runs tests, captures screenshots/videos/traces, and uploads artifacts.
|
||||
description: 使用 Playwright 生成并运行端到端测试。创建测试旅程、运行测试、捕获截图/视频/追踪,并上传产物。
|
||||
---
|
||||
|
||||
# E2E Command
|
||||
# E2E 命令
|
||||
|
||||
This command invokes the **e2e-runner** agent to generate, maintain, and execute end-to-end tests using Playwright.
|
||||
此命令调用 **e2e-runner** 智能体(Agent)来使用 Playwright 生成、维护和执行端到端测试(End-to-End Tests/E2E)。
|
||||
|
||||
## What This Command Does
|
||||
## 此命令的作用
|
||||
|
||||
1. **Generate Test Journeys** - Create Playwright tests for user flows
|
||||
2. **Run E2E Tests** - Execute tests across browsers
|
||||
3. **Capture Artifacts** - Screenshots, videos, traces on failures
|
||||
4. **Upload Results** - HTML reports and JUnit XML
|
||||
5. **Identify Flaky Tests** - Quarantine unstable tests
|
||||
1. **生成测试旅程(Test Journeys)** - 为用户流创建 Playwright 测试
|
||||
2. **运行 E2E 测试** - 在不同浏览器上执行测试
|
||||
3. **捕获产物(Artifacts)** - 在失败时捕获截图、视频和追踪(Traces)
|
||||
4. **上传结果** - 生成 HTML 报告和 JUnit XML
|
||||
5. **识别不稳定测试(Flaky Tests)** - 隔离不稳定的测试
|
||||
|
||||
## When to Use
|
||||
## 何时使用
|
||||
|
||||
Use `/e2e` when:
|
||||
- Testing critical user journeys (login, trading, payments)
|
||||
- Verifying multi-step flows work end-to-end
|
||||
- Testing UI interactions and navigation
|
||||
- Validating integration between frontend and backend
|
||||
- Preparing for production deployment
|
||||
在以下场景使用 `/e2e`:
|
||||
- 测试关键用户旅程(登录、交易、支付)
|
||||
- 验证多步骤流程的端到端运行情况
|
||||
- 测试 UI 交互和导航
|
||||
- 验证前端与后端之间的集成
|
||||
- 为生产环境部署做准备
|
||||
|
||||
## How It Works
|
||||
## 工作原理
|
||||
|
||||
The e2e-runner agent will:
|
||||
e2e-runner 智能体将执行以下操作:
|
||||
|
||||
1. **Analyze user flow** and identify test scenarios
|
||||
2. **Generate Playwright test** using Page Object Model pattern
|
||||
3. **Run tests** across multiple browsers (Chrome, Firefox, Safari)
|
||||
4. **Capture failures** with screenshots, videos, and traces
|
||||
5. **Generate report** with results and artifacts
|
||||
6. **Identify flaky tests** and recommend fixes
|
||||
1. **分析用户流**并识别测试场景
|
||||
2. 使用页面对象模型(Page Object Model/POM)模式**生成 Playwright 测试**
|
||||
3. 在多个浏览器(Chrome、Firefox、Safari)上**运行测试**
|
||||
4. 通过截图、视频和追踪**捕获失败信息**
|
||||
5. **生成报告**,包含结果和产物
|
||||
6. **识别不稳定测试**并推荐修复方案
|
||||
|
||||
## Example Usage
|
||||
## 使用示例
|
||||
|
||||
```
|
||||
User: /e2e Test the market search and view flow
|
||||
用户:/e2e 测试市场搜索和查看流程
|
||||
|
||||
Agent (e2e-runner):
|
||||
# E2E Test Generation: Market Search and View Flow
|
||||
智能体 (e2e-runner):
|
||||
# E2E 测试生成:市场搜索和查看流程
|
||||
|
||||
## Test Scenario Identified
|
||||
## 识别出的测试场景
|
||||
|
||||
**User Journey:** Market Search → View Results → Click Market → View Details
|
||||
**用户旅程:** 市场搜索 → 查看结果 → 点击市场 → 查看详情
|
||||
|
||||
**Test Coverage:**
|
||||
1. Navigate to markets page
|
||||
2. Perform semantic search
|
||||
3. Verify search results
|
||||
4. Click on first result
|
||||
5. Verify market details page loads
|
||||
6. Verify chart renders
|
||||
**测试覆盖范围:**
|
||||
1. 导航到市场页面
|
||||
2. 执行语义搜索
|
||||
3. 验证搜索结果
|
||||
4. 点击第一个结果
|
||||
5. 验证市场详情页面加载
|
||||
6. 验证图表渲染
|
||||
|
||||
## Generated Test Code
|
||||
## 生成的测试代码
|
||||
|
||||
```typescript
|
||||
// tests/e2e/markets/search-and-view.spec.ts
|
||||
@@ -64,52 +64,52 @@ import { MarketDetailsPage } from '../../pages/MarketDetailsPage'
|
||||
|
||||
test.describe('Market Search and View Flow', () => {
|
||||
test('user can search markets and view details', async ({ page }) => {
|
||||
// 1. Navigate to markets page
|
||||
// 1. 导航到市场页面
|
||||
const marketsPage = new MarketsPage(page)
|
||||
await marketsPage.goto()
|
||||
|
||||
// Verify page loaded
|
||||
// 验证页面加载
|
||||
await expect(page).toHaveTitle(/Markets/)
|
||||
await expect(page.locator('h1')).toContainText('Markets')
|
||||
|
||||
// 2. Perform semantic search
|
||||
// 2. 执行语义搜索
|
||||
await marketsPage.searchMarkets('election')
|
||||
|
||||
// Wait for API response
|
||||
// 等待 API 响应
|
||||
await page.waitForResponse(resp =>
|
||||
resp.url().includes('/api/markets/search') && resp.status() === 200
|
||||
)
|
||||
|
||||
// 3. Verify search results
|
||||
// 3. 验证搜索结果
|
||||
const marketCards = marketsPage.marketCards
|
||||
await expect(marketCards.first()).toBeVisible()
|
||||
const resultCount = await marketCards.count()
|
||||
expect(resultCount).toBeGreaterThan(0)
|
||||
|
||||
// Take screenshot of search results
|
||||
// 截取搜索结果截图
|
||||
await page.screenshot({ path: 'artifacts/search-results.png' })
|
||||
|
||||
// 4. Click on first result
|
||||
// 4. 点击第一个结果
|
||||
const firstMarketTitle = await marketCards.first().textContent()
|
||||
await marketCards.first().click()
|
||||
|
||||
// 5. Verify market details page loads
|
||||
// 5. 验证市场详情页面加载
|
||||
await expect(page).toHaveURL(/\/markets\/[a-z0-9-]+/)
|
||||
|
||||
const detailsPage = new MarketDetailsPage(page)
|
||||
await expect(detailsPage.marketName).toBeVisible()
|
||||
await expect(detailsPage.marketDescription).toBeVisible()
|
||||
|
||||
// 6. Verify chart renders
|
||||
// 6. 验证图表渲染
|
||||
await expect(detailsPage.priceChart).toBeVisible()
|
||||
|
||||
// Verify market name matches
|
||||
// 验证市场名称匹配
|
||||
const detailsTitle = await detailsPage.marketName.textContent()
|
||||
expect(detailsTitle?.toLowerCase()).toContain(
|
||||
firstMarketTitle?.toLowerCase().substring(0, 20) || ''
|
||||
)
|
||||
|
||||
// Take screenshot of market details
|
||||
// 截取市场详情截图
|
||||
await page.screenshot({ path: 'artifacts/market-details.png' })
|
||||
})
|
||||
|
||||
@@ -117,10 +117,10 @@ test.describe('Market Search and View Flow', () => {
|
||||
const marketsPage = new MarketsPage(page)
|
||||
await marketsPage.goto()
|
||||
|
||||
// Search for non-existent market
|
||||
// 搜索不存在的市场
|
||||
await marketsPage.searchMarkets('xyznonexistentmarket123456')
|
||||
|
||||
// Verify empty state
|
||||
// 验证空状态
|
||||
await expect(page.locator('[data-testid="no-results"]')).toBeVisible()
|
||||
await expect(page.locator('[data-testid="no-results"]')).toContainText(
|
||||
/no.*results|no.*markets/i
|
||||
@@ -134,32 +134,32 @@ test.describe('Market Search and View Flow', () => {
|
||||
const marketsPage = new MarketsPage(page)
|
||||
await marketsPage.goto()
|
||||
|
||||
// Initial market count
|
||||
// 初始市场数量
|
||||
const initialCount = await marketsPage.marketCards.count()
|
||||
|
||||
// Perform search
|
||||
// 执行搜索
|
||||
await marketsPage.searchMarkets('trump')
|
||||
await page.waitForLoadState('networkidle')
|
||||
|
||||
// Verify filtered results
|
||||
// 验证过滤后的结果
|
||||
const filteredCount = await marketsPage.marketCards.count()
|
||||
expect(filteredCount).toBeLessThan(initialCount)
|
||||
|
||||
// Clear search
|
||||
// 清除搜索
|
||||
await marketsPage.searchInput.clear()
|
||||
await page.waitForLoadState('networkidle')
|
||||
|
||||
// Verify all markets shown again
|
||||
// 验证再次显示所有市场
|
||||
const finalCount = await marketsPage.marketCards.count()
|
||||
expect(finalCount).toBe(initialCount)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## Running Tests
|
||||
## 运行测试
|
||||
|
||||
```bash
|
||||
# Run the generated test
|
||||
# 运行生成的测试
|
||||
npx playwright test tests/e2e/markets/search-and-view.spec.ts
|
||||
|
||||
Running 3 tests using 3 workers
|
||||
@@ -170,100 +170,100 @@ Running 3 tests using 3 workers
|
||||
|
||||
3 passed (9.1s)
|
||||
|
||||
Artifacts generated:
|
||||
生成的产物:
|
||||
- artifacts/search-results.png
|
||||
- artifacts/market-details.png
|
||||
- playwright-report/index.html
|
||||
```
|
||||
|
||||
## Test Report
|
||||
## 测试报告
|
||||
|
||||
```
|
||||
╔══════════════════════════════════════════════════════════════╗
|
||||
║ E2E Test Results ║
|
||||
║ E2E 测试结果 ║
|
||||
╠══════════════════════════════════════════════════════════════╣
|
||||
║ Status: ✅ ALL TESTS PASSED ║
|
||||
║ Total: 3 tests ║
|
||||
║ Passed: 3 (100%) ║
|
||||
║ Failed: 0 ║
|
||||
║ Flaky: 0 ║
|
||||
║ Duration: 9.1s ║
|
||||
║ 状态: ✅ 所有测试通过 ║
|
||||
║ 总计: 3 个测试 ║
|
||||
║ 通过: 3 (100%) ║
|
||||
║ 失败: 0 ║
|
||||
║ 不稳定: 0 ║
|
||||
║ 耗时: 9.1s ║
|
||||
╚══════════════════════════════════════════════════════════════╝
|
||||
|
||||
Artifacts:
|
||||
📸 Screenshots: 2 files
|
||||
📹 Videos: 0 files (only on failure)
|
||||
🔍 Traces: 0 files (only on failure)
|
||||
📊 HTML Report: playwright-report/index.html
|
||||
产物:
|
||||
📸 截图: 2 个文件
|
||||
📹 视频: 0 个文件 (仅在失败时生成)
|
||||
🔍 追踪: 0 个文件 (仅在失败时生成)
|
||||
📊 HTML 报告: playwright-report/index.html
|
||||
|
||||
View report: npx playwright show-report
|
||||
查看报告: npx playwright show-report
|
||||
```
|
||||
|
||||
✅ E2E test suite ready for CI/CD integration!
|
||||
✅ E2E 测试套件已就绪,可进行 CI/CD 集成!
|
||||
```
|
||||
|
||||
## Test Artifacts
|
||||
## 测试产物(Artifacts)
|
||||
|
||||
When tests run, the following artifacts are captured:
|
||||
测试运行时,会捕获以下产物:
|
||||
|
||||
**On All Tests:**
|
||||
- HTML Report with timeline and results
|
||||
- JUnit XML for CI integration
|
||||
**所有测试均会捕获:**
|
||||
- 包含时间线和结果的 HTML 报告
|
||||
- 用于 CI 集成的 JUnit XML
|
||||
|
||||
**On Failure Only:**
|
||||
- Screenshot of the failing state
|
||||
- Video recording of the test
|
||||
- Trace file for debugging (step-by-step replay)
|
||||
- Network logs
|
||||
- Console logs
|
||||
**仅在失败时捕获:**
|
||||
- 失败状态的截图
|
||||
- 测试过程的录屏视频
|
||||
- 用于调试的追踪文件(单步回放)
|
||||
- 网络日志
|
||||
- 控制台日志
|
||||
|
||||
## Viewing Artifacts
|
||||
## 查看产物
|
||||
|
||||
```bash
|
||||
# View HTML report in browser
|
||||
# 在浏览器中查看 HTML 报告
|
||||
npx playwright show-report
|
||||
|
||||
# View specific trace file
|
||||
# 查看特定的追踪文件
|
||||
npx playwright show-trace artifacts/trace-abc123.zip
|
||||
|
||||
# Screenshots are saved in artifacts/ directory
|
||||
# 截图保存在 artifacts/ 目录下
|
||||
open artifacts/search-results.png
|
||||
```
|
||||
|
||||
## Flaky Test Detection
|
||||
## 不稳定测试检测
|
||||
|
||||
If a test fails intermittently:
|
||||
如果测试间歇性失败:
|
||||
|
||||
```
|
||||
⚠️ FLAKY TEST DETECTED: tests/e2e/markets/trade.spec.ts
|
||||
⚠️ 检测到不稳定测试 (FLAKY TEST): tests/e2e/markets/trade.spec.ts
|
||||
|
||||
Test passed 7/10 runs (70% pass rate)
|
||||
测试在 10 次运行中通过了 7 次 (70% 通过率)
|
||||
|
||||
Common failure:
|
||||
常见失败原因:
|
||||
"Timeout waiting for element '[data-testid="confirm-btn"]'"
|
||||
|
||||
Recommended fixes:
|
||||
1. Add explicit wait: await page.waitForSelector('[data-testid="confirm-btn"]')
|
||||
2. Increase timeout: { timeout: 10000 }
|
||||
3. Check for race conditions in component
|
||||
4. Verify element is not hidden by animation
|
||||
推荐修复建议:
|
||||
1. 添加显式等待: await page.waitForSelector('[data-testid="confirm-btn"]')
|
||||
2. 增加超时时间: { timeout: 10000 }
|
||||
3. 检查组件中的竞态条件
|
||||
4. 验证元素未被动画隐藏
|
||||
|
||||
Quarantine recommendation: Mark as test.fixme() until fixed
|
||||
隔离建议: 在修复前标记为 test.fixme()
|
||||
```
|
||||
|
||||
## Browser Configuration
|
||||
## 浏览器配置
|
||||
|
||||
Tests run on multiple browsers by default:
|
||||
- ✅ Chromium (Desktop Chrome)
|
||||
- ✅ Firefox (Desktop)
|
||||
- ✅ WebKit (Desktop Safari)
|
||||
- ✅ Mobile Chrome (optional)
|
||||
测试默认在多个浏览器上运行:
|
||||
- ✅ Chromium (桌面版 Chrome)
|
||||
- ✅ Firefox (桌面版)
|
||||
- ✅ WebKit (桌面版 Safari)
|
||||
- ✅ 移动版 Chrome (可选)
|
||||
|
||||
Configure in `playwright.config.ts` to adjust browsers.
|
||||
在 `playwright.config.ts` 中进行浏览器配置调整。
|
||||
|
||||
## CI/CD Integration
|
||||
## CI/CD 集成
|
||||
|
||||
Add to your CI pipeline:
|
||||
添加到你的 CI 流水线中:
|
||||
|
||||
```yaml
|
||||
# .github/workflows/e2e.yml
|
||||
@@ -281,83 +281,83 @@ Add to your CI pipeline:
|
||||
path: playwright-report/
|
||||
```
|
||||
|
||||
## PMX-Specific Critical Flows
|
||||
## PMX 特有的关键流程
|
||||
|
||||
For PMX, prioritize these E2E tests:
|
||||
对于 PMX,请优先考虑这些 E2E 测试:
|
||||
|
||||
**🔴 CRITICAL (Must Always Pass):**
|
||||
1. User can connect wallet
|
||||
2. User can browse markets
|
||||
3. User can search markets (semantic search)
|
||||
4. User can view market details
|
||||
5. User can place trade (with test funds)
|
||||
6. Market resolves correctly
|
||||
7. User can withdraw funds
|
||||
**🔴 关键 (必须始终通过):**
|
||||
1. 用户可以连接钱包
|
||||
2. 用户可以浏览市场
|
||||
3. 用户可以搜索市场(语义搜索)
|
||||
4. 用户可以查看市场详情
|
||||
5. 用户可以下单交易(使用测试资金)
|
||||
6. 市场正确结算
|
||||
7. 用户可以提取资金
|
||||
|
||||
**🟡 IMPORTANT:**
|
||||
1. Market creation flow
|
||||
2. User profile updates
|
||||
3. Real-time price updates
|
||||
4. Chart rendering
|
||||
5. Filter and sort markets
|
||||
6. Mobile responsive layout
|
||||
**🟡 重要:**
|
||||
1. 市场创建流程
|
||||
2. 用户资料更新
|
||||
3. 实时价格更新
|
||||
4. 图表渲染
|
||||
5. 过滤和排序市场
|
||||
6. 移动端响应式布局
|
||||
|
||||
## Best Practices
|
||||
## 最佳实践
|
||||
|
||||
**DO:**
|
||||
- ✅ Use Page Object Model for maintainability
|
||||
- ✅ Use data-testid attributes for selectors
|
||||
- ✅ Wait for API responses, not arbitrary timeouts
|
||||
- ✅ Test critical user journeys end-to-end
|
||||
- ✅ Run tests before merging to main
|
||||
- ✅ Review artifacts when tests fail
|
||||
**建议 (DO):**
|
||||
- ✅ 使用页面对象模型(POM)以提高可维护性
|
||||
- ✅ 使用 data-testid 属性作为选择器
|
||||
- ✅ 等待 API 响应,而不是任意的超时时间
|
||||
- ✅ 对关键用户旅程进行端到端测试
|
||||
- ✅ 在合并到主分支前运行测试
|
||||
- ✅ 测试失败时查看产物
|
||||
|
||||
**DON'T:**
|
||||
- ❌ Use brittle selectors (CSS classes can change)
|
||||
- ❌ Test implementation details
|
||||
- ❌ Run tests against production
|
||||
- ❌ Ignore flaky tests
|
||||
- ❌ Skip artifact review on failures
|
||||
- ❌ Test every edge case with E2E (use unit tests)
|
||||
**禁忌 (DON'T):**
|
||||
- ❌ 使用脆弱的选择器(CSS 类可能会改变)
|
||||
- ❌ 测试实现细节
|
||||
- ❌ 针对生产环境运行测试
|
||||
- ❌ 忽视不稳定测试
|
||||
- ❌ 失败时跳过产物审查
|
||||
- ❌ 用 E2E 测试每个边缘情况(应使用单元测试)
|
||||
|
||||
## Important Notes
|
||||
## 重要注意事项
|
||||
|
||||
**CRITICAL for PMX:**
|
||||
- E2E tests involving real money MUST run on testnet/staging only
|
||||
- Never run trading tests against production
|
||||
- Set `test.skip(process.env.NODE_ENV === 'production')` for financial tests
|
||||
- Use test wallets with small test funds only
|
||||
**对于 PMX 的关键点:**
|
||||
- 涉及真钱的 E2E 测试必须仅在测试网 (testnet) 或预发布环境 (staging) 运行
|
||||
- 严禁针对生产环境运行交易测试
|
||||
- 为金融相关的测试设置 `test.skip(process.env.NODE_ENV === 'production')`
|
||||
- 仅使用带有少量测试资金的测试钱包
|
||||
|
||||
## Integration with Other Commands
|
||||
## 与其他命令的集成
|
||||
|
||||
- Use `/plan` to identify critical journeys to test
|
||||
- Use `/tdd` for unit tests (faster, more granular)
|
||||
- Use `/e2e` for integration and user journey tests
|
||||
- Use `/code-review` to verify test quality
|
||||
- 使用 `/plan` 识别需要测试的关键旅程
|
||||
- 使用 `/tdd` 进行单元测试(更快、更细粒度)
|
||||
- 使用 `/e2e` 进行集成和用户旅程测试
|
||||
- 使用 `/code-review` 验证测试质量
|
||||
|
||||
## Related Agents
|
||||
## 相关智能体
|
||||
|
||||
This command invokes the `e2e-runner` agent located at:
|
||||
此命令调用位于以下位置的 `e2e-runner` 智能体:
|
||||
`~/.claude/agents/e2e-runner.md`
|
||||
|
||||
## Quick Commands
|
||||
## 快捷命令
|
||||
|
||||
```bash
|
||||
# Run all E2E tests
|
||||
# 运行所有 E2E 测试
|
||||
npx playwright test
|
||||
|
||||
# Run specific test file
|
||||
# 运行特定的测试文件
|
||||
npx playwright test tests/e2e/markets/search.spec.ts
|
||||
|
||||
# Run in headed mode (see browser)
|
||||
# 在有头模式下运行(可看到浏览器)
|
||||
npx playwright test --headed
|
||||
|
||||
# Debug test
|
||||
# 调试测试
|
||||
npx playwright test --debug
|
||||
|
||||
# Generate test code
|
||||
# 生成测试代码
|
||||
npx playwright codegen http://localhost:3000
|
||||
|
||||
# View report
|
||||
# 查看报告
|
||||
npx playwright show-report
|
||||
```
|
||||
|
||||
116
commands/eval.md
116
commands/eval.md
@@ -1,120 +1,120 @@
|
||||
# Eval Command
|
||||
# 评测命令(Eval Command)
|
||||
|
||||
Manage eval-driven development workflow.
|
||||
管理评测驱动开发(eval-driven development)工作流。
|
||||
|
||||
## Usage
|
||||
## 用法(Usage)
|
||||
|
||||
`/eval [define|check|report|list] [feature-name]`
|
||||
|
||||
## Define Evals
|
||||
## 定义评测(Define Evals)
|
||||
|
||||
`/eval define feature-name`
|
||||
|
||||
Create a new eval definition:
|
||||
创建一个新的评测定义:
|
||||
|
||||
1. Create `.claude/evals/feature-name.md` with template:
|
||||
1. 创建 `.claude/evals/feature-name.md` 文件,使用以下模板:
|
||||
|
||||
```markdown
|
||||
## EVAL: feature-name
|
||||
Created: $(date)
|
||||
创建时间:$(date)
|
||||
|
||||
### Capability Evals
|
||||
- [ ] [Description of capability 1]
|
||||
- [ ] [Description of capability 2]
|
||||
### 能力评测(Capability Evals)
|
||||
- [ ] [能力描述 1]
|
||||
- [ ] [能力描述 2]
|
||||
|
||||
### Regression Evals
|
||||
- [ ] [Existing behavior 1 still works]
|
||||
- [ ] [Existing behavior 2 still works]
|
||||
### 回归评测(Regression Evals)
|
||||
- [ ] [现有行为 1 仍然正常工作]
|
||||
- [ ] [现有行为 2 仍然正常工作]
|
||||
|
||||
### Success Criteria
|
||||
- pass@3 > 90% for capability evals
|
||||
- pass^3 = 100% for regression evals
|
||||
### 通过准则(Success Criteria)
|
||||
- 能力评测(capability evals)的 pass@3 > 90%
|
||||
- 回归评测(regression evals)的 pass^3 = 100%
|
||||
```
|
||||
|
||||
2. Prompt user to fill in specific criteria
|
||||
2. 提示用户填写具体准则。
|
||||
|
||||
## Check Evals
|
||||
## 检查评测(Check Evals)
|
||||
|
||||
`/eval check feature-name`
|
||||
|
||||
Run evals for a feature:
|
||||
运行特定功能的评测:
|
||||
|
||||
1. Read eval definition from `.claude/evals/feature-name.md`
|
||||
2. For each capability eval:
|
||||
- Attempt to verify criterion
|
||||
- Record PASS/FAIL
|
||||
- Log attempt in `.claude/evals/feature-name.log`
|
||||
3. For each regression eval:
|
||||
- Run relevant tests
|
||||
- Compare against baseline
|
||||
- Record PASS/FAIL
|
||||
4. Report current status:
|
||||
1. 从 `.claude/evals/feature-name.md` 读取评测定义。
|
||||
2. 对于每一项能力评测:
|
||||
- 尝试验证准则。
|
||||
- 记录 PASS/FAIL。
|
||||
- 在 `.claude/evals/feature-name.log` 中记录尝试日志。
|
||||
3. 对于每一项回归评测:
|
||||
- 运行相关测试。
|
||||
- 与基准(baseline)进行对比。
|
||||
- 记录 PASS/FAIL。
|
||||
4. 报告当前状态:
|
||||
|
||||
```
|
||||
EVAL CHECK: feature-name
|
||||
========================
|
||||
Capability: X/Y passing
|
||||
Regression: X/Y passing
|
||||
Status: IN PROGRESS / READY
|
||||
能力(Capability): X/Y 通过
|
||||
回归(Regression): X/Y 通过
|
||||
状态(Status): 进行中(IN PROGRESS)/ 已就绪(READY)
|
||||
```
|
||||
|
||||
## Report Evals
|
||||
## 生成报告(Report Evals)
|
||||
|
||||
`/eval report feature-name`
|
||||
|
||||
Generate comprehensive eval report:
|
||||
生成完整的评测报告:
|
||||
|
||||
```
|
||||
EVAL REPORT: feature-name
|
||||
=========================
|
||||
Generated: $(date)
|
||||
生成时间:$(date)
|
||||
|
||||
CAPABILITY EVALS
|
||||
能力评测(CAPABILITY EVALS)
|
||||
----------------
|
||||
[eval-1]: PASS (pass@1)
|
||||
[eval-2]: PASS (pass@2) - required retry
|
||||
[eval-3]: FAIL - see notes
|
||||
[eval-2]: PASS (pass@2) - 需重试
|
||||
[eval-3]: FAIL - 见备注
|
||||
|
||||
REGRESSION EVALS
|
||||
回归评测(REGRESSION EVALS)
|
||||
----------------
|
||||
[test-1]: PASS
|
||||
[test-2]: PASS
|
||||
[test-3]: PASS
|
||||
|
||||
METRICS
|
||||
指标(METRICS)
|
||||
-------
|
||||
Capability pass@1: 67%
|
||||
Capability pass@3: 100%
|
||||
Regression pass^3: 100%
|
||||
能力 pass@1: 67%
|
||||
能力 pass@3: 100%
|
||||
回归 pass^3: 100%
|
||||
|
||||
NOTES
|
||||
备注(NOTES)
|
||||
-----
|
||||
[Any issues, edge cases, or observations]
|
||||
[任何问题、边界情况或观察结果]
|
||||
|
||||
RECOMMENDATION
|
||||
建议(RECOMMENDATION)
|
||||
--------------
|
||||
[SHIP / NEEDS WORK / BLOCKED]
|
||||
[可发布(SHIP)/ 需改进(NEEDS WORK)/ 阻塞(BLOCKED)]
|
||||
```
|
||||
|
||||
## List Evals
|
||||
## 列出评测(List Evals)
|
||||
|
||||
`/eval list`
|
||||
|
||||
Show all eval definitions:
|
||||
显示所有评测定义:
|
||||
|
||||
```
|
||||
EVAL DEFINITIONS
|
||||
================
|
||||
feature-auth [3/5 passing] IN PROGRESS
|
||||
feature-search [5/5 passing] READY
|
||||
feature-export [0/4 passing] NOT STARTED
|
||||
feature-auth [3/5 通过] 进行中(IN PROGRESS)
|
||||
feature-search [5/5 通过] 已就绪(READY)
|
||||
feature-export [0/4 通过] 未开始(NOT STARTED)
|
||||
```
|
||||
|
||||
## Arguments
|
||||
## 参数(Arguments)
|
||||
|
||||
$ARGUMENTS:
|
||||
- `define <name>` - Create new eval definition
|
||||
- `check <name>` - Run and check evals
|
||||
- `report <name>` - Generate full report
|
||||
- `list` - Show all evals
|
||||
- `clean` - Remove old eval logs (keeps last 10 runs)
|
||||
- `define <name>` - 创建新的评测定义。
|
||||
- `check <name>` - 运行并检查评测。
|
||||
- `report <name>` - 生成完整报告。
|
||||
- `list` - 显示所有评测。
|
||||
- `clean` - 清除旧的评测日志(保留最近 10 次运行记录)。
|
||||
|
||||
@@ -1,55 +1,55 @@
|
||||
---
|
||||
description: Fix Go build errors, go vet warnings, and linter issues incrementally. Invokes the go-build-resolver agent for minimal, surgical fixes.
|
||||
description: 增量修复 Go 构建错误、go vet 警告和 linter 问题。调用 go-build-resolver 智能体(Agent)进行最小化、外科手术式的修复。
|
||||
---
|
||||
|
||||
# Go Build and Fix
|
||||
# Go 构建与修复 (Go Build and Fix)
|
||||
|
||||
This command invokes the **go-build-resolver** agent to incrementally fix Go build errors with minimal changes.
|
||||
此命令会调用 **go-build-resolver** 智能体(Agent),以最小的改动增量修复 Go 构建错误。
|
||||
|
||||
## What This Command Does
|
||||
## 此命令的作用
|
||||
|
||||
1. **Run Diagnostics**: Execute `go build`, `go vet`, `staticcheck`
|
||||
2. **Parse Errors**: Group by file and sort by severity
|
||||
3. **Fix Incrementally**: One error at a time
|
||||
4. **Verify Each Fix**: Re-run build after each change
|
||||
5. **Report Summary**: Show what was fixed and what remains
|
||||
1. **运行诊断**:执行 `go build`、`go vet`、`staticcheck`
|
||||
2. **解析错误**:按文件分组并按严重程度排序
|
||||
3. **增量修复**:一次修复一个错误
|
||||
4. **验证每次修复**:每次更改后重新运行构建
|
||||
5. **报告摘要**:显示已修复的内容和剩余的问题
|
||||
|
||||
## When to Use
|
||||
## 何时使用
|
||||
|
||||
Use `/go-build` when:
|
||||
- `go build ./...` fails with errors
|
||||
- `go vet ./...` reports issues
|
||||
- `golangci-lint run` shows warnings
|
||||
- Module dependencies are broken
|
||||
- After pulling changes that break the build
|
||||
在以下情况下使用 `/go-build`:
|
||||
- `go build ./...` 失败并报错
|
||||
- `go vet ./...` 报告问题
|
||||
- `golangci-lint run` 显示警告
|
||||
- 模块依赖关系损坏
|
||||
- 拉取了破坏构建的更改后
|
||||
|
||||
## Diagnostic Commands Run
|
||||
## 运行的诊断命令
|
||||
|
||||
```bash
|
||||
# Primary build check
|
||||
# 主要构建检查
|
||||
go build ./...
|
||||
|
||||
# Static analysis
|
||||
# 静态分析
|
||||
go vet ./...
|
||||
|
||||
# Extended linting (if available)
|
||||
# 扩展 lint 检查(如果可用)
|
||||
staticcheck ./...
|
||||
golangci-lint run
|
||||
|
||||
# Module issues
|
||||
# 模块问题
|
||||
go mod verify
|
||||
go mod tidy -v
|
||||
```
|
||||
|
||||
## Example Session
|
||||
## 会话示例
|
||||
|
||||
```text
|
||||
User: /go-build
|
||||
|
||||
Agent:
|
||||
# Go Build Resolution
|
||||
# Go 构建修复 (Go Build Resolution)
|
||||
|
||||
## Initial Diagnostics
|
||||
## 初始诊断
|
||||
|
||||
```bash
|
||||
$ go build ./...
|
||||
@@ -58,51 +58,51 @@ internal/handler/api.go:42:9: cannot use x (type string) as type int
|
||||
internal/handler/api.go:58:2: missing return at end of function
|
||||
```
|
||||
|
||||
Errors found: 3
|
||||
发现错误:3
|
||||
|
||||
## Fix 1: Undefined Identifier
|
||||
## 修复 1:未定义标识符 (Undefined Identifier)
|
||||
|
||||
File: internal/service/user.go:25
|
||||
Error: undefined: UserRepository
|
||||
Cause: Missing import
|
||||
文件:internal/service/user.go:25
|
||||
错误:undefined: UserRepository
|
||||
原因:缺少导入 (Missing import)
|
||||
|
||||
```go
|
||||
// Added import
|
||||
// 添加了导入
|
||||
import "project/internal/repository"
|
||||
|
||||
// Changed
|
||||
// 更改了
|
||||
var repo UserRepository
|
||||
// To
|
||||
// 为
|
||||
var repo repository.UserRepository
|
||||
```
|
||||
|
||||
```bash
|
||||
$ go build ./...
|
||||
# 2 errors remaining
|
||||
# 剩余 2 个错误
|
||||
```
|
||||
|
||||
## Fix 2: Type Mismatch
|
||||
## 修复 2:类型不匹配 (Type Mismatch)
|
||||
|
||||
File: internal/handler/api.go:42
|
||||
Error: cannot use x (type string) as type int
|
||||
文件:internal/handler/api.go:42
|
||||
错误:cannot use x (type string) as type int
|
||||
|
||||
```go
|
||||
// Changed
|
||||
// 更改了
|
||||
count := params.Get("count")
|
||||
// To
|
||||
// 为
|
||||
countStr := params.Get("count")
|
||||
count, _ := strconv.Atoi(countStr)
|
||||
```
|
||||
|
||||
```bash
|
||||
$ go build ./...
|
||||
# 1 error remaining
|
||||
# 剩余 1 个错误
|
||||
```
|
||||
|
||||
## Fix 3: Missing Return
|
||||
## 修复 3:缺少返回 (Missing Return)
|
||||
|
||||
File: internal/handler/api.go:58
|
||||
Error: missing return at end of function
|
||||
文件:internal/handler/api.go:58
|
||||
错误:missing return at end of function
|
||||
|
||||
```go
|
||||
func GetUser(id string) (*User, error) {
|
||||
@@ -110,74 +110,74 @@ func GetUser(id string) (*User, error) {
|
||||
return nil, ErrInvalidID
|
||||
}
|
||||
user := findUser(id)
|
||||
// Added missing return
|
||||
// 添加了缺少的 return
|
||||
return user, nil
|
||||
}
|
||||
```
|
||||
|
||||
```bash
|
||||
$ go build ./...
|
||||
# Build successful!
|
||||
# 构建成功!
|
||||
```
|
||||
|
||||
## Final Verification
|
||||
## 最终验证
|
||||
|
||||
```bash
|
||||
$ go vet ./...
|
||||
# No issues
|
||||
# 无问题
|
||||
|
||||
$ go test ./...
|
||||
ok project/internal/service 0.015s
|
||||
ok project/internal/handler 0.023s
|
||||
```
|
||||
|
||||
## Summary
|
||||
## 摘要
|
||||
|
||||
| Metric | Count |
|
||||
|--------|-------|
|
||||
| Build errors fixed | 3 |
|
||||
| Vet warnings fixed | 0 |
|
||||
| Files modified | 2 |
|
||||
| Remaining issues | 0 |
|
||||
| 指标 | 计数 |
|
||||
|------|------|
|
||||
| 已修复构建错误 | 3 |
|
||||
| 已修复 Vet 警告 | 0 |
|
||||
| 修改的文件 | 2 |
|
||||
| 剩余问题 | 0 |
|
||||
|
||||
Build Status: ✅ SUCCESS
|
||||
构建状态:✅ 成功 (SUCCESS)
|
||||
```
|
||||
|
||||
## Common Errors Fixed
|
||||
## 常见修复错误
|
||||
|
||||
| Error | Typical Fix |
|
||||
|-------|-------------|
|
||||
| `undefined: X` | Add import or fix typo |
|
||||
| `cannot use X as Y` | Type conversion or fix assignment |
|
||||
| `missing return` | Add return statement |
|
||||
| `X does not implement Y` | Add missing method |
|
||||
| `import cycle` | Restructure packages |
|
||||
| `declared but not used` | Remove or use variable |
|
||||
| `cannot find package` | `go get` or `go mod tidy` |
|
||||
| 错误 | 典型修复方案 |
|
||||
|------|--------------|
|
||||
| `undefined: X` | 添加导入或修复拼写错误 |
|
||||
| `cannot use X as Y` | 类型转换或修复赋值 |
|
||||
| `missing return` | 添加 return 语句 |
|
||||
| `X does not implement Y` | 添加缺失的方法 |
|
||||
| `import cycle` | 重构包结构 |
|
||||
| `declared but not used` | 删除或使用该变量 |
|
||||
| `cannot find package` | 执行 `go get` 或 `go mod tidy` |
|
||||
|
||||
## Fix Strategy
|
||||
## 修复策略
|
||||
|
||||
1. **Build errors first** - Code must compile
|
||||
2. **Vet warnings second** - Fix suspicious constructs
|
||||
3. **Lint warnings third** - Style and best practices
|
||||
4. **One fix at a time** - Verify each change
|
||||
5. **Minimal changes** - Don't refactor, just fix
|
||||
1. **构建错误优先** - 代码必须能编译
|
||||
2. **Vet 警告次之** - 修复可疑结构
|
||||
3. **Lint 警告第三** - 样式和最佳实践
|
||||
4. **一次一个修复** - 验证每次更改
|
||||
5. **最小化更改** - 不要重构,只管修复
|
||||
|
||||
## Stop Conditions
|
||||
## 停止条件
|
||||
|
||||
The agent will stop and report if:
|
||||
- Same error persists after 3 attempts
|
||||
- Fix introduces more errors
|
||||
- Requires architectural changes
|
||||
- Missing external dependencies
|
||||
如果出现以下情况,智能体(Agent)将停止并报告:
|
||||
- 尝试 3 次后同一错误仍然存在
|
||||
- 修复引入了更多错误
|
||||
- 需要架构调整
|
||||
- 缺少外部依赖项
|
||||
|
||||
## Related Commands
|
||||
## 相关命令
|
||||
|
||||
- `/go-test` - Run tests after build succeeds
|
||||
- `/go-review` - Review code quality
|
||||
- `/verify` - Full verification loop
|
||||
- `/go-test` - 构建成功后运行测试
|
||||
- `/go-review` - 审查代码质量
|
||||
- `/verify` - 完整的验证循环
|
||||
|
||||
## Related
|
||||
## 相关
|
||||
|
||||
- Agent: `agents/go-build-resolver.md`
|
||||
- Skill: `skills/golang-patterns/`
|
||||
- 智能体 (Agent):`agents/go-build-resolver.md`
|
||||
- 技能 (Skill):`skills/golang-patterns/`
|
||||
|
||||
@@ -1,100 +1,100 @@
|
||||
---
|
||||
description: Comprehensive Go code review for idiomatic patterns, concurrency safety, error handling, and security. Invokes the go-reviewer agent.
|
||||
description: 针对地道模式、并发安全、错误处理和安全性的全面 Go 代码审查。调用 go-reviewer 智能体 (Agent)。
|
||||
---
|
||||
|
||||
# Go Code Review
|
||||
# Go 代码审查 (Go Code Review)
|
||||
|
||||
This command invokes the **go-reviewer** agent for comprehensive Go-specific code review.
|
||||
此命令调用 **go-reviewer** 智能体 (Agent) 进行针对 Go 语言特性的全面代码审查。
|
||||
|
||||
## What This Command Does
|
||||
## 此命令的作用
|
||||
|
||||
1. **Identify Go Changes**: Find modified `.go` files via `git diff`
|
||||
2. **Run Static Analysis**: Execute `go vet`, `staticcheck`, and `golangci-lint`
|
||||
3. **Security Scan**: Check for SQL injection, command injection, race conditions
|
||||
4. **Concurrency Review**: Analyze goroutine safety, channel usage, mutex patterns
|
||||
5. **Idiomatic Go Check**: Verify code follows Go conventions and best practices
|
||||
6. **Generate Report**: Categorize issues by severity
|
||||
1. **识别 Go 代码变更**:通过 `git diff` 查找已修改的 `.go` 文件
|
||||
2. **运行静态分析**:执行 `go vet`、`staticcheck` 和 `golangci-lint`
|
||||
3. **安全扫描**:检查 SQL 注入、命令注入、竞态条件等安全隐患
|
||||
4. **并发审查**:分析 Goroutine 安全、通道 (Channel) 使用、互斥锁 (Mutex) 模式
|
||||
5. **地道 Go 检查**:验证代码是否遵循 Go 惯例和最佳实践
|
||||
6. **生成报告**:按严重程度对问题进行分类
|
||||
|
||||
## When to Use
|
||||
## 适用场景
|
||||
|
||||
Use `/go-review` when:
|
||||
- After writing or modifying Go code
|
||||
- Before committing Go changes
|
||||
- Reviewing pull requests with Go code
|
||||
- Onboarding to a new Go codebase
|
||||
- Learning idiomatic Go patterns
|
||||
在以下情况下使用 `/go-review`:
|
||||
- 编写或修改 Go 代码后
|
||||
- 提交 Go 代码变更前
|
||||
- 审查包含 Go 代码的拉取请求 (Pull Request)
|
||||
- 熟悉新的 Go 代码库
|
||||
- 学习地道的 Go 模式
|
||||
|
||||
## Review Categories
|
||||
## 审查类别
|
||||
|
||||
### CRITICAL (Must Fix)
|
||||
- SQL/Command injection vulnerabilities
|
||||
- Race conditions without synchronization
|
||||
- Goroutine leaks
|
||||
- Hardcoded credentials
|
||||
- Unsafe pointer usage
|
||||
- Ignored errors in critical paths
|
||||
### 致命 (CRITICAL) - 必须修复
|
||||
- SQL/命令注入漏洞
|
||||
- 未经同步的并发访问(竞态条件)
|
||||
- Goroutine 泄露
|
||||
- 硬编码的凭据
|
||||
- 不安全的指针 (Unsafe Pointer) 使用
|
||||
- 关键路径中被忽略的错误
|
||||
|
||||
### HIGH (Should Fix)
|
||||
- Missing error wrapping with context
|
||||
- Panic instead of error returns
|
||||
- Context not propagated
|
||||
- Unbuffered channels causing deadlocks
|
||||
- Interface not satisfied errors
|
||||
- Missing mutex protection
|
||||
### 高危 (HIGH) - 建议修复
|
||||
- 缺失包含上下文 (Context) 的错误包装
|
||||
- 使用 Panic 代替错误返回
|
||||
- 上下文 (Context) 未透传
|
||||
- 导致死锁的无缓冲通道
|
||||
- 接口未实现错误
|
||||
- 缺失互斥锁保护
|
||||
|
||||
### MEDIUM (Consider)
|
||||
- Non-idiomatic code patterns
|
||||
- Missing godoc comments on exports
|
||||
- Inefficient string concatenation
|
||||
- Slice not preallocated
|
||||
- Table-driven tests not used
|
||||
### 中等 (MEDIUM) - 酌情考虑
|
||||
- 非地道的代码模式
|
||||
- 导出的标识符缺失 Godoc 注释
|
||||
- 低效的字符串拼接
|
||||
- 切片 (Slice) 未预分配容量
|
||||
- 未使用表驱动测试 (Table-driven tests)
|
||||
|
||||
## Automated Checks Run
|
||||
## 运行的自动化检查
|
||||
|
||||
```bash
|
||||
# Static analysis
|
||||
# 静态分析
|
||||
go vet ./...
|
||||
|
||||
# Advanced checks (if installed)
|
||||
# 高级检查(如果已安装)
|
||||
staticcheck ./...
|
||||
golangci-lint run
|
||||
|
||||
# Race detection
|
||||
# 竞态检测
|
||||
go build -race ./...
|
||||
|
||||
# Security vulnerabilities
|
||||
# 安全漏洞
|
||||
govulncheck ./...
|
||||
```
|
||||
|
||||
## Example Usage
|
||||
## 使用示例
|
||||
|
||||
```text
|
||||
User: /go-review
|
||||
用户: /go-review
|
||||
|
||||
Agent:
|
||||
# Go Code Review Report
|
||||
智能体 (Agent):
|
||||
# Go 代码审查报告 (Go Code Review Report)
|
||||
|
||||
## Files Reviewed
|
||||
- internal/handler/user.go (modified)
|
||||
- internal/service/auth.go (modified)
|
||||
## 已审查的文件
|
||||
- internal/handler/user.go (已修改)
|
||||
- internal/service/auth.go (已修改)
|
||||
|
||||
## Static Analysis Results
|
||||
✓ go vet: No issues
|
||||
✓ staticcheck: No issues
|
||||
## 静态分析结果
|
||||
✓ go vet: 无问题
|
||||
✓ staticcheck: 无问题
|
||||
|
||||
## Issues Found
|
||||
## 发现的问题
|
||||
|
||||
[CRITICAL] Race Condition
|
||||
File: internal/service/auth.go:45
|
||||
Issue: Shared map accessed without synchronization
|
||||
[致命] 竞态条件 (Race Condition)
|
||||
文件: internal/service/auth.go:45
|
||||
问题: 未经同步访问共享 Map
|
||||
```go
|
||||
var cache = map[string]*Session{} // Concurrent access!
|
||||
var cache = map[string]*Session{} // 并发访问!
|
||||
|
||||
func GetSession(id string) *Session {
|
||||
return cache[id] // Race condition
|
||||
return cache[id] // 竞态条件
|
||||
}
|
||||
```
|
||||
Fix: Use sync.RWMutex or sync.Map
|
||||
修复: 使用 sync.RWMutex 或 sync.Map
|
||||
```go
|
||||
var (
|
||||
cache = map[string]*Session{}
|
||||
@@ -108,41 +108,41 @@ func GetSession(id string) *Session {
|
||||
}
|
||||
```
|
||||
|
||||
[HIGH] Missing Error Context
|
||||
File: internal/handler/user.go:28
|
||||
Issue: Error returned without context
|
||||
[高危] 缺失错误上下文
|
||||
文件: internal/handler/user.go:28
|
||||
问题: 返回错误时未包含上下文信息
|
||||
```go
|
||||
return err // No context
|
||||
return err // 缺失上下文
|
||||
```
|
||||
Fix: Wrap with context
|
||||
修复: 包装上下文信息
|
||||
```go
|
||||
return fmt.Errorf("get user %s: %w", userID, err)
|
||||
```
|
||||
|
||||
## Summary
|
||||
- CRITICAL: 1
|
||||
- HIGH: 1
|
||||
- MEDIUM: 0
|
||||
## 总结
|
||||
- 致命 (CRITICAL): 1
|
||||
- 高危 (HIGH): 1
|
||||
- 中等 (MEDIUM): 0
|
||||
|
||||
Recommendation: ❌ Block merge until CRITICAL issue is fixed
|
||||
建议: ❌ 在修复“致命”问题前禁止合并
|
||||
```
|
||||
|
||||
## Approval Criteria
|
||||
## 批准标准
|
||||
|
||||
| Status | Condition |
|
||||
| 状态 | 条件 |
|
||||
|--------|-----------|
|
||||
| ✅ Approve | No CRITICAL or HIGH issues |
|
||||
| ⚠️ Warning | Only MEDIUM issues (merge with caution) |
|
||||
| ❌ Block | CRITICAL or HIGH issues found |
|
||||
| ✅ 批准 (Approve) | 无致命 (CRITICAL) 或高危 (HIGH) 问题 |
|
||||
| ⚠️ 警告 (Warning) | 仅存在中等 (MEDIUM) 问题(谨慎合并) |
|
||||
| ❌ 阻断 (Block) | 发现致命 (CRITICAL) 或高危 (HIGH) 问题 |
|
||||
|
||||
## Integration with Other Commands
|
||||
## 与其他命令的集成
|
||||
|
||||
- Use `/go-test` first to ensure tests pass
|
||||
- Use `/go-build` if build errors occur
|
||||
- Use `/go-review` before committing
|
||||
- Use `/code-review` for non-Go specific concerns
|
||||
- 先使用 `/go-test` 确保测试通过
|
||||
- 如果出现构建错误,使用 `/go-build`
|
||||
- 在提交代码前使用 `/go-review`
|
||||
- 针对非 Go 特定的问题,使用 `/code-review`
|
||||
|
||||
## Related
|
||||
## 相关内容
|
||||
|
||||
- Agent: `agents/go-reviewer.md`
|
||||
- Skills: `skills/golang-patterns/`, `skills/golang-testing/`
|
||||
- 智能体 (Agent): `agents/go-reviewer.md`
|
||||
- 技能 (Skills): `skills/golang-patterns/`, `skills/golang-testing/`
|
||||
|
||||
@@ -1,60 +1,60 @@
|
||||
---
|
||||
description: Enforce TDD workflow for Go. Write table-driven tests first, then implement. Verify 80%+ coverage with go test -cover.
|
||||
description: 强制执行 Go 的测试驱动开发(TDD)工作流。先编写表驱动测试(Table-Driven Tests),然后进行实现。使用 go test -cover 验证 80% 以上的覆盖率。
|
||||
---
|
||||
|
||||
# Go TDD Command
|
||||
# Go TDD 命令
|
||||
|
||||
This command enforces test-driven development methodology for Go code using idiomatic Go testing patterns.
|
||||
此命令使用地道的 Go 测试模式为 Go 代码强制执行测试驱动开发(Test-Driven Development,TDD)方法论。
|
||||
|
||||
## What This Command Does
|
||||
## 此命令的作用
|
||||
|
||||
1. **Define Types/Interfaces**: Scaffold function signatures first
|
||||
2. **Write Table-Driven Tests**: Create comprehensive test cases (RED)
|
||||
3. **Run Tests**: Verify tests fail for the right reason
|
||||
4. **Implement Code**: Write minimal code to pass (GREEN)
|
||||
5. **Refactor**: Improve while keeping tests green
|
||||
6. **Check Coverage**: Ensure 80%+ coverage
|
||||
1. **定义类型/接口**:首先搭建函数签名的支架
|
||||
2. **编写表驱动测试(Table-Driven Tests)**:创建全面的测试用例(RED/红灯)
|
||||
3. **运行测试**:验证测试因预期的原因失败
|
||||
4. **实现代码**:编写通过测试所需的最少代码(GREEN/绿灯)
|
||||
5. **重构(Refactor)**:在保持测试通过的同时优化代码
|
||||
6. **检查覆盖率**:确保 80% 以上的覆盖率
|
||||
|
||||
## When to Use
|
||||
## 何时使用
|
||||
|
||||
Use `/go-test` when:
|
||||
- Implementing new Go functions
|
||||
- Adding test coverage to existing code
|
||||
- Fixing bugs (write failing test first)
|
||||
- Building critical business logic
|
||||
- Learning TDD workflow in Go
|
||||
在以下场景使用 `/go-test`:
|
||||
- 实现新的 Go 函数
|
||||
- 为现有代码增加测试覆盖率
|
||||
- 修复 Bug(先编写失败的测试)
|
||||
- 构建核心业务逻辑
|
||||
- 在 Go 中学习 TDD 工作流(Workflow)
|
||||
|
||||
## TDD Cycle
|
||||
## TDD 周期
|
||||
|
||||
```
|
||||
RED → Write failing table-driven test
|
||||
GREEN → Implement minimal code to pass
|
||||
REFACTOR → Improve code, tests stay green
|
||||
REPEAT → Next test case
|
||||
RED(红灯) → 编写失败的表驱动测试
|
||||
GREEN(绿灯) → 实现通过测试所需的最少代码
|
||||
REFACTOR(重构) → 优化代码,保持测试通过
|
||||
REPEAT(循环) → 下一个测试用例
|
||||
```
|
||||
|
||||
## Example Session
|
||||
## 会话示例
|
||||
|
||||
```text
|
||||
User: /go-test I need a function to validate email addresses
|
||||
User: /go-test 我需要一个验证电子邮件地址的函数
|
||||
|
||||
Agent:
|
||||
# TDD Session: Email Validator
|
||||
# TDD 会话:电子邮件验证器
|
||||
|
||||
## Step 1: Define Interface
|
||||
## 第 1 步:定义接口
|
||||
|
||||
```go
|
||||
// validator/email.go
|
||||
package validator
|
||||
|
||||
// ValidateEmail checks if the given string is a valid email address.
|
||||
// Returns nil if valid, error describing the issue otherwise.
|
||||
// ValidateEmail 检查给定的字符串是否为有效的电子邮件地址。
|
||||
// 如果有效返回 nil,否则返回描述问题的错误。
|
||||
func ValidateEmail(email string) error {
|
||||
panic("not implemented")
|
||||
}
|
||||
```
|
||||
|
||||
## Step 2: Write Table-Driven Tests (RED)
|
||||
## 第 2 步:编写表驱动测试 (RED)
|
||||
|
||||
```go
|
||||
// validator/email_test.go
|
||||
@@ -70,13 +70,13 @@ func TestValidateEmail(t *testing.T) {
|
||||
email string
|
||||
wantErr bool
|
||||
}{
|
||||
// Valid emails
|
||||
// 有效邮箱
|
||||
{"simple email", "user@example.com", false},
|
||||
{"with subdomain", "user@mail.example.com", false},
|
||||
{"with plus", "user+tag@example.com", false},
|
||||
{"with dots", "first.last@example.com", false},
|
||||
|
||||
// Invalid emails
|
||||
// 无效邮箱
|
||||
{"empty string", "", true},
|
||||
{"no at sign", "userexample.com", true},
|
||||
{"no domain", "user@", true},
|
||||
@@ -100,7 +100,7 @@ func TestValidateEmail(t *testing.T) {
|
||||
}
|
||||
```
|
||||
|
||||
## Step 3: Run Tests - Verify FAIL
|
||||
## 第 3 步:运行测试 - 验证失败
|
||||
|
||||
```bash
|
||||
$ go test ./validator/...
|
||||
@@ -112,9 +112,9 @@ $ go test ./validator/...
|
||||
FAIL
|
||||
```
|
||||
|
||||
✓ Tests fail as expected (panic).
|
||||
✓ 测试如预期般失败 (panic)。
|
||||
|
||||
## Step 4: Implement Minimal Code (GREEN)
|
||||
## 第 4 步:实现最少代码 (GREEN)
|
||||
|
||||
```go
|
||||
// validator/email.go
|
||||
@@ -143,7 +143,7 @@ func ValidateEmail(email string) error {
|
||||
}
|
||||
```
|
||||
|
||||
## Step 5: Run Tests - Verify PASS
|
||||
## 第 5 步:运行测试 - 验证通过
|
||||
|
||||
```bash
|
||||
$ go test ./validator/...
|
||||
@@ -152,9 +152,9 @@ PASS
|
||||
ok project/validator 0.003s
|
||||
```
|
||||
|
||||
✓ All tests passing!
|
||||
✓ 所有测试通过!
|
||||
|
||||
## Step 6: Check Coverage
|
||||
## 第 6 步:检查覆盖率
|
||||
|
||||
```bash
|
||||
$ go test -cover ./validator/...
|
||||
@@ -164,14 +164,14 @@ coverage: 100.0% of statements
|
||||
ok project/validator 0.003s
|
||||
```
|
||||
|
||||
✓ Coverage: 100%
|
||||
✓ 覆盖率:100%
|
||||
|
||||
## TDD Complete!
|
||||
## TDD 完成!
|
||||
```
|
||||
|
||||
## Test Patterns
|
||||
## 测试模式
|
||||
|
||||
### Table-Driven Tests
|
||||
### 表驱动测试(Table-Driven Tests)
|
||||
```go
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -186,23 +186,23 @@ tests := []struct {
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := Function(tt.input)
|
||||
// assertions
|
||||
// 断言逻辑
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
### Parallel Tests
|
||||
### 并行测试(Parallel Tests)
|
||||
```go
|
||||
for _, tt := range tests {
|
||||
tt := tt // Capture
|
||||
tt := tt // 闭包捕获变量
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
// test body
|
||||
// 测试主体
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
### Test Helpers
|
||||
### 测试助手(Test Helpers)
|
||||
```go
|
||||
func setupTestDB(t *testing.T) *sql.DB {
|
||||
t.Helper()
|
||||
@@ -212,57 +212,57 @@ func setupTestDB(t *testing.T) *sql.DB {
|
||||
}
|
||||
```
|
||||
|
||||
## Coverage Commands
|
||||
## 覆盖率命令
|
||||
|
||||
```bash
|
||||
# Basic coverage
|
||||
# 基础覆盖率
|
||||
go test -cover ./...
|
||||
|
||||
# Coverage profile
|
||||
# 生成覆盖率分析文件
|
||||
go test -coverprofile=coverage.out ./...
|
||||
|
||||
# View in browser
|
||||
# 在浏览器中查看结果
|
||||
go tool cover -html=coverage.out
|
||||
|
||||
# Coverage by function
|
||||
# 按函数查看覆盖率
|
||||
go tool cover -func=coverage.out
|
||||
|
||||
# With race detection
|
||||
# 配合竞态检测运行
|
||||
go test -race -cover ./...
|
||||
```
|
||||
|
||||
## Coverage Targets
|
||||
## 覆盖率目标
|
||||
|
||||
| Code Type | Target |
|
||||
| 代码类型 | 目标 |
|
||||
|-----------|--------|
|
||||
| Critical business logic | 100% |
|
||||
| Public APIs | 90%+ |
|
||||
| General code | 80%+ |
|
||||
| Generated code | Exclude |
|
||||
| 核心业务逻辑 | 100% |
|
||||
| 公共 API | 90%+ |
|
||||
| 通用代码 | 80%+ |
|
||||
| 生成的代码 | 排除 |
|
||||
|
||||
## TDD Best Practices
|
||||
## TDD 最佳实践
|
||||
|
||||
**DO:**
|
||||
- Write test FIRST, before any implementation
|
||||
- Run tests after each change
|
||||
- Use table-driven tests for comprehensive coverage
|
||||
- Test behavior, not implementation details
|
||||
- Include edge cases (empty, nil, max values)
|
||||
**建议这样做:**
|
||||
- **先**写测试,在进行任何实现之前
|
||||
- 每次修改后都运行测试
|
||||
- 使用表驱动测试以实现全面的覆盖
|
||||
- 测试行为,而不是实现细节
|
||||
- 包含边界情况(空值、nil、最大值)
|
||||
|
||||
**DON'T:**
|
||||
- Write implementation before tests
|
||||
- Skip the RED phase
|
||||
- Test private functions directly
|
||||
- Use `time.Sleep` in tests
|
||||
- Ignore flaky tests
|
||||
**不要这样做:**
|
||||
- 在测试之前编写实现代码
|
||||
- 跳过 RED(红灯)阶段
|
||||
- 直接测试私有函数
|
||||
- 在测试中使用 `time.Sleep`
|
||||
- 忽略不稳定的测试(Flaky tests)
|
||||
|
||||
## Related Commands
|
||||
## 相关命令
|
||||
|
||||
- `/go-build` - Fix build errors
|
||||
- `/go-review` - Review code after implementation
|
||||
- `/verify` - Run full verification loop
|
||||
- `/go-build` - 修复构建错误
|
||||
- `/go-review` - 实现后评审代码
|
||||
- `/verify` - 运行完整验证循环
|
||||
|
||||
## Related
|
||||
## 相关内容
|
||||
|
||||
- Skill: `skills/golang-testing/`
|
||||
- Skill: `skills/tdd-workflow/`
|
||||
- 技能(Skill):`skills/golang-testing/`
|
||||
- 技能(Skill):`skills/tdd-workflow/`
|
||||
|
||||
@@ -1,70 +1,70 @@
|
||||
# /learn - Extract Reusable Patterns
|
||||
# /learn - 提取可复用模式(Patterns)
|
||||
|
||||
Analyze the current session and extract any patterns worth saving as skills.
|
||||
分析当前会话(Session)并提取任何值得作为技能(Skills)保存的模式。
|
||||
|
||||
## Trigger
|
||||
## 触发(Trigger)
|
||||
|
||||
Run `/learn` at any point during a session when you've solved a non-trivial problem.
|
||||
在会话期间解决了一个非琐碎的问题后,可以随时运行 `/learn`。
|
||||
|
||||
## What to Extract
|
||||
## 提取内容
|
||||
|
||||
Look for:
|
||||
关注以下方面:
|
||||
|
||||
1. **Error Resolution Patterns**
|
||||
- What error occurred?
|
||||
- What was the root cause?
|
||||
- What fixed it?
|
||||
- Is this reusable for similar errors?
|
||||
1. **错误解决模式(Error Resolution Patterns)**
|
||||
- 发生了什么错误?
|
||||
- 根本原因是什么?
|
||||
- 如何修复的?
|
||||
- 是否可用于解决类似的错误?
|
||||
|
||||
2. **Debugging Techniques**
|
||||
- Non-obvious debugging steps
|
||||
- Tool combinations that worked
|
||||
- Diagnostic patterns
|
||||
2. **调试技巧(Debugging Techniques)**
|
||||
- 非显而易见的调试步骤
|
||||
- 行之有效的工具组合
|
||||
- 诊断模式
|
||||
|
||||
3. **Workarounds**
|
||||
- Library quirks
|
||||
- API limitations
|
||||
- Version-specific fixes
|
||||
3. **变通方法(Workarounds)**
|
||||
- 库的奇特特性(Quirks)
|
||||
- API 限制
|
||||
- 特定版本的修复补丁
|
||||
|
||||
4. **Project-Specific Patterns**
|
||||
- Codebase conventions discovered
|
||||
- Architecture decisions made
|
||||
- Integration patterns
|
||||
4. **项目特定模式(Project-Specific Patterns)**
|
||||
- 发现的代码库规范
|
||||
- 做出的架构决策
|
||||
- 集成模式
|
||||
|
||||
## Output Format
|
||||
## 输出格式
|
||||
|
||||
Create a skill file at `~/.claude/skills/learned/[pattern-name].md`:
|
||||
在 `~/.claude/skills/learned/[pattern-name].md` 路径下创建一个技能文件:
|
||||
|
||||
```markdown
|
||||
# [Descriptive Pattern Name]
|
||||
# [描述性的模式名称]
|
||||
|
||||
**Extracted:** [Date]
|
||||
**Context:** [Brief description of when this applies]
|
||||
**提取日期:** [日期]
|
||||
**上下文:** [适用场景的简要描述]
|
||||
|
||||
## Problem
|
||||
[What problem this solves - be specific]
|
||||
## 问题
|
||||
[该模式解决的问题 - 请具体描述]
|
||||
|
||||
## Solution
|
||||
[The pattern/technique/workaround]
|
||||
## 解决方案
|
||||
[模式/技术/变通方法]
|
||||
|
||||
## Example
|
||||
[Code example if applicable]
|
||||
## 示例
|
||||
[如果适用,请提供代码示例]
|
||||
|
||||
## When to Use
|
||||
[Trigger conditions - what should activate this skill]
|
||||
## 何时使用
|
||||
[触发条件 - 什么情况下应激活此技能]
|
||||
```
|
||||
|
||||
## Process
|
||||
## 流程
|
||||
|
||||
1. Review the session for extractable patterns
|
||||
2. Identify the most valuable/reusable insight
|
||||
3. Draft the skill file
|
||||
4. Ask user to confirm before saving
|
||||
5. Save to `~/.claude/skills/learned/`
|
||||
1. 回顾会话以寻找可提取的模式
|
||||
2. 识别最有价值/可复用的见解
|
||||
3. 起草技能文件
|
||||
4. 保存前请求用户确认
|
||||
5. 保存至 `~/.claude/skills/learned/`
|
||||
|
||||
## Notes
|
||||
## 注意事项
|
||||
|
||||
- Don't extract trivial fixes (typos, simple syntax errors)
|
||||
- Don't extract one-time issues (specific API outages, etc.)
|
||||
- Focus on patterns that will save time in future sessions
|
||||
- Keep skills focused - one pattern per skill
|
||||
- 不要提取琐碎的修复(如拼写错误、简单的语法错误)
|
||||
- 不要提取一次性问题(如特定的 API 故障等)
|
||||
- 专注于能在未来会话中节省时间的模式
|
||||
- 保持技能聚焦 —— 每个技能只包含一个模式
|
||||
|
||||
@@ -1,172 +1,172 @@
|
||||
# Orchestrate Command
|
||||
# 编排(Orchestrate)命令
|
||||
|
||||
Sequential agent workflow for complex tasks.
|
||||
用于复杂任务的顺序智能体(Agent)工作流。
|
||||
|
||||
## Usage
|
||||
## 用法
|
||||
|
||||
`/orchestrate [workflow-type] [task-description]`
|
||||
|
||||
## Workflow Types
|
||||
## 工作流类型
|
||||
|
||||
### feature
|
||||
Full feature implementation workflow:
|
||||
完整功能实现工作流:
|
||||
```
|
||||
planner -> tdd-guide -> code-reviewer -> security-reviewer
|
||||
```
|
||||
|
||||
### bugfix
|
||||
Bug investigation and fix workflow:
|
||||
Bug 调查与修复工作流:
|
||||
```
|
||||
explorer -> tdd-guide -> code-reviewer
|
||||
```
|
||||
|
||||
### refactor
|
||||
Safe refactoring workflow:
|
||||
安全重构工作流:
|
||||
```
|
||||
architect -> code-reviewer -> tdd-guide
|
||||
```
|
||||
|
||||
### security
|
||||
Security-focused review:
|
||||
侧重安全的评审:
|
||||
```
|
||||
security-reviewer -> code-reviewer -> architect
|
||||
```
|
||||
|
||||
## Execution Pattern
|
||||
## 执行模式
|
||||
|
||||
For each agent in the workflow:
|
||||
对于工作流中的每个智能体(Agent):
|
||||
|
||||
1. **Invoke agent** with context from previous agent
|
||||
2. **Collect output** as structured handoff document
|
||||
3. **Pass to next agent** in chain
|
||||
4. **Aggregate results** into final report
|
||||
1. **调用智能体**:携带来自上一个智能体的上下文。
|
||||
2. **收集输出**:将其作为结构化的交接(Handoff)文档。
|
||||
3. **传递**:交给链条中的下一个智能体。
|
||||
4. **汇总结果**:生成最终报告。
|
||||
|
||||
## Handoff Document Format
|
||||
## 交接(Handoff)文档格式
|
||||
|
||||
Between agents, create handoff document:
|
||||
在智能体之间创建交接文档:
|
||||
|
||||
```markdown
|
||||
## HANDOFF: [previous-agent] -> [next-agent]
|
||||
|
||||
### Context
|
||||
[Summary of what was done]
|
||||
[工作总结]
|
||||
|
||||
### Findings
|
||||
[Key discoveries or decisions]
|
||||
[关键发现或决策]
|
||||
|
||||
### Files Modified
|
||||
[List of files touched]
|
||||
[涉及的文件列表]
|
||||
|
||||
### Open Questions
|
||||
[Unresolved items for next agent]
|
||||
[留给下一个智能体的未解决事项]
|
||||
|
||||
### Recommendations
|
||||
[Suggested next steps]
|
||||
[建议的后续步骤]
|
||||
```
|
||||
|
||||
## Example: Feature Workflow
|
||||
## 示例:功能开发工作流(Feature Workflow)
|
||||
|
||||
```
|
||||
/orchestrate feature "Add user authentication"
|
||||
/orchestrate feature "添加用户认证功能"
|
||||
```
|
||||
|
||||
Executes:
|
||||
执行流程:
|
||||
|
||||
1. **Planner Agent**
|
||||
- Analyzes requirements
|
||||
- Creates implementation plan
|
||||
- Identifies dependencies
|
||||
- Output: `HANDOFF: planner -> tdd-guide`
|
||||
1. **规划智能体(Planner Agent)**
|
||||
- 分析需求
|
||||
- 创建实现计划
|
||||
- 识别依赖项
|
||||
- 输出:`HANDOFF: planner -> tdd-guide`
|
||||
|
||||
2. **TDD Guide Agent**
|
||||
- Reads planner handoff
|
||||
- Writes tests first
|
||||
- Implements to pass tests
|
||||
- Output: `HANDOFF: tdd-guide -> code-reviewer`
|
||||
2. **TDD 指导智能体(TDD Guide Agent)**
|
||||
- 读取规划智能体(Planner)的交接文档
|
||||
- 测试先行(先编写测试)
|
||||
- 编写实现代码以通过测试
|
||||
- 输出:`HANDOFF: tdd-guide -> code-reviewer`
|
||||
|
||||
3. **Code Reviewer Agent**
|
||||
- Reviews implementation
|
||||
- Checks for issues
|
||||
- Suggests improvements
|
||||
- Output: `HANDOFF: code-reviewer -> security-reviewer`
|
||||
3. **代码评审智能体(Code Reviewer Agent)**
|
||||
- 评审实现代码
|
||||
- 检查潜在问题
|
||||
- 提出改进建议
|
||||
- 输出:`HANDOFF: code-reviewer -> security-reviewer`
|
||||
|
||||
4. **Security Reviewer Agent**
|
||||
- Security audit
|
||||
- Vulnerability check
|
||||
- Final approval
|
||||
- Output: Final Report
|
||||
4. **安全评审智能体(Security Reviewer Agent)**
|
||||
- 安全审计
|
||||
- 漏洞检查
|
||||
- 最终批准
|
||||
- 输出:最终报告
|
||||
|
||||
## Final Report Format
|
||||
## 最终报告格式
|
||||
|
||||
```
|
||||
ORCHESTRATION REPORT
|
||||
====================
|
||||
Workflow: feature
|
||||
Task: Add user authentication
|
||||
Task: 添加用户认证功能
|
||||
Agents: planner -> tdd-guide -> code-reviewer -> security-reviewer
|
||||
|
||||
SUMMARY
|
||||
-------
|
||||
[One paragraph summary]
|
||||
[一段话总结]
|
||||
|
||||
AGENT OUTPUTS
|
||||
-------------
|
||||
Planner: [summary]
|
||||
TDD Guide: [summary]
|
||||
Code Reviewer: [summary]
|
||||
Security Reviewer: [summary]
|
||||
Planner: [摘要]
|
||||
TDD Guide: [摘要]
|
||||
Code Reviewer: [摘要]
|
||||
Security Reviewer: [摘要]
|
||||
|
||||
FILES CHANGED
|
||||
-------------
|
||||
[List all files modified]
|
||||
[列出所有修改的文件]
|
||||
|
||||
TEST RESULTS
|
||||
------------
|
||||
[Test pass/fail summary]
|
||||
[测试通过/失败摘要]
|
||||
|
||||
SECURITY STATUS
|
||||
---------------
|
||||
[Security findings]
|
||||
[安全发现项]
|
||||
|
||||
RECOMMENDATION
|
||||
--------------
|
||||
[SHIP / NEEDS WORK / BLOCKED]
|
||||
```
|
||||
|
||||
## Parallel Execution
|
||||
## 并行执行
|
||||
|
||||
For independent checks, run agents in parallel:
|
||||
对于独立的检查项,可以并行运行智能体:
|
||||
|
||||
```markdown
|
||||
### Parallel Phase
|
||||
Run simultaneously:
|
||||
- code-reviewer (quality)
|
||||
- security-reviewer (security)
|
||||
- architect (design)
|
||||
同时运行:
|
||||
- code-reviewer (质量评审)
|
||||
- security-reviewer (安全评审)
|
||||
- architect (设计评审)
|
||||
|
||||
### Merge Results
|
||||
Combine outputs into single report
|
||||
将所有输出汇总到单个报告中
|
||||
```
|
||||
|
||||
## Arguments
|
||||
## 参数
|
||||
|
||||
$ARGUMENTS:
|
||||
- `feature <description>` - Full feature workflow
|
||||
- `bugfix <description>` - Bug fix workflow
|
||||
- `refactor <description>` - Refactoring workflow
|
||||
- `security <description>` - Security review workflow
|
||||
- `custom <agents> <description>` - Custom agent sequence
|
||||
- `feature <description>` - 完整功能实现工作流
|
||||
- `bugfix <description>` - Bug 修复工作流
|
||||
- `refactor <description>` - 重构工作流
|
||||
- `security <description>` - 安全评审工作流
|
||||
- `custom <agents> <description>` - 自定义智能体序列
|
||||
|
||||
## Custom Workflow Example
|
||||
## 自定义工作流示例
|
||||
|
||||
```
|
||||
/orchestrate custom "architect,tdd-guide,code-reviewer" "Redesign caching layer"
|
||||
/orchestrate custom "architect,tdd-guide,code-reviewer" "重构缓存层"
|
||||
```
|
||||
|
||||
## Tips
|
||||
## 技巧
|
||||
|
||||
1. **Start with planner** for complex features
|
||||
2. **Always include code-reviewer** before merge
|
||||
3. **Use security-reviewer** for auth/payment/PII
|
||||
4. **Keep handoffs concise** - focus on what next agent needs
|
||||
5. **Run verification** between agents if needed
|
||||
1. **从规划开始**:对于复杂功能,优先使用规划智能体(Planner)。
|
||||
2. **始终包含代码评审**:在合并前,务必包含代码评审智能体(Code Reviewer)。
|
||||
3. **涉及敏感操作使用安全评审**:在处理鉴权、支付或敏感信息(PII)时,请使用安全评审智能体(Security Reviewer)。
|
||||
4. **保持交接文档简洁**:专注于下一个智能体所需的信息。
|
||||
5. **在环节间运行验证**:如有必要,在智能体交接间运行验证(Verification)。
|
||||
|
||||
158
commands/plan.md
158
commands/plan.md
@@ -1,113 +1,113 @@
|
||||
---
|
||||
description: Restate requirements, assess risks, and create step-by-step implementation plan. WAIT for user CONFIRM before touching any code.
|
||||
description: 重述需求、评估风险并创建分步实施计划。在修改任何代码之前,必须等待用户确认(CONFIRM)。
|
||||
---
|
||||
|
||||
# Plan Command
|
||||
# 计划命令(Plan Command)
|
||||
|
||||
This command invokes the **planner** agent to create a comprehensive implementation plan before writing any code.
|
||||
此命令调用 **计划智能体(planner agent)**,在编写任何代码之前创建一个全面的实施计划。
|
||||
|
||||
## What This Command Does
|
||||
## 此命令的作用
|
||||
|
||||
1. **Restate Requirements** - Clarify what needs to be built
|
||||
2. **Identify Risks** - Surface potential issues and blockers
|
||||
3. **Create Step Plan** - Break down implementation into phases
|
||||
4. **Wait for Confirmation** - MUST receive user approval before proceeding
|
||||
1. **重述需求** - 澄清需要构建的内容
|
||||
2. **识别风险** - 发现潜在问题和阻碍因素
|
||||
3. **创建分步计划** - 将实施分解为不同阶段(Phases)
|
||||
4. **等待确认** - 在继续操作之前**必须**获得用户批准
|
||||
|
||||
## When to Use
|
||||
## 何时使用
|
||||
|
||||
Use `/plan` when:
|
||||
- Starting a new feature
|
||||
- Making significant architectural changes
|
||||
- Working on complex refactoring
|
||||
- Multiple files/components will be affected
|
||||
- Requirements are unclear or ambiguous
|
||||
在以下情况使用 `/plan`:
|
||||
- 开始一个新功能(new feature)
|
||||
- 进行重大架构变更(architectural changes)
|
||||
- 进行复杂的重构(refactoring)
|
||||
- 涉及多个文件或组件时
|
||||
- 需求不明确或存在歧义时
|
||||
|
||||
## How It Works
|
||||
## 工作原理
|
||||
|
||||
The planner agent will:
|
||||
计划智能体(planner agent)将:
|
||||
|
||||
1. **Analyze the request** and restate requirements in clear terms
|
||||
2. **Break down into phases** with specific, actionable steps
|
||||
3. **Identify dependencies** between components
|
||||
4. **Assess risks** and potential blockers
|
||||
5. **Estimate complexity** (High/Medium/Low)
|
||||
6. **Present the plan** and WAIT for your explicit confirmation
|
||||
1. **分析请求**并以清晰的术语重述需求
|
||||
2. **分解为阶段(Phases)**,并附带具体、可操作的步骤
|
||||
3. **识别组件之间的依赖关系(Dependencies)**
|
||||
4. **评估风险**和潜在阻碍因素
|
||||
5. **预估复杂度(Complexity)**(高/中/低)
|
||||
6. **展示计划**并**等待**您的明确确认
|
||||
|
||||
## Example Usage
|
||||
## 使用示例
|
||||
|
||||
```
|
||||
User: /plan I need to add real-time notifications when markets resolve
|
||||
用户:/plan 我需要在市场结算时添加实时通知
|
||||
|
||||
Agent (planner):
|
||||
# Implementation Plan: Real-Time Market Resolution Notifications
|
||||
智能体 (planner):
|
||||
# 实施计划:实时市场结算通知
|
||||
|
||||
## Requirements Restatement
|
||||
- Send notifications to users when markets they're watching resolve
|
||||
- Support multiple notification channels (in-app, email, webhook)
|
||||
- Ensure notifications are delivered reliably
|
||||
- Include market outcome and user's position result
|
||||
## 需求重述
|
||||
- 当用户关注的市场结算时,向其发送通知
|
||||
- 支持多个通知渠道(应用内、电子邮件、webhook)
|
||||
- 确保通知能够可靠交付
|
||||
- 包含市场结果和用户的持仓结算结果
|
||||
|
||||
## Implementation Phases
|
||||
## 实施阶段
|
||||
|
||||
### Phase 1: Database Schema
|
||||
- Add notifications table with columns: id, user_id, market_id, type, status, created_at
|
||||
- Add user_notification_preferences table for channel preferences
|
||||
- Create indexes on user_id and market_id for performance
|
||||
### 第 1 阶段:数据库 Schema
|
||||
- 添加 notifications 表,包含列:id, user_id, market_id, type, status, created_at
|
||||
- 添加 user_notification_preferences 表用于渠道偏好设置
|
||||
- 在 user_id 和 market_id 上创建索引以提高性能
|
||||
|
||||
### Phase 2: Notification Service
|
||||
- Create notification service in lib/notifications.ts
|
||||
- Implement notification queue using BullMQ/Redis
|
||||
- Add retry logic for failed deliveries
|
||||
- Create notification templates
|
||||
### 第 2 阶段:通知服务
|
||||
- 在 lib/notifications.ts 中创建通知服务
|
||||
- 使用 BullMQ/Redis 实施通知队列
|
||||
- 为投递失败添加重试逻辑
|
||||
- 创建通知模板
|
||||
|
||||
### Phase 3: Integration Points
|
||||
- Hook into market resolution logic (when status changes to "resolved")
|
||||
- Query all users with positions in market
|
||||
- Enqueue notifications for each user
|
||||
### 第 3 阶段:集成点
|
||||
- 挂钩(Hook)到市场结算逻辑(当状态变为 "resolved" 时)
|
||||
- 查询在该市场有持仓的所有用户
|
||||
- 为每个用户将通知加入队列
|
||||
|
||||
### Phase 4: Frontend Components
|
||||
- Create NotificationBell component in header
|
||||
- Add NotificationList modal
|
||||
- Implement real-time updates via Supabase subscriptions
|
||||
- Add notification preferences page
|
||||
### 第 4 阶段:前端组件
|
||||
- 在页眉创建 NotificationBell 组件
|
||||
- 添加 NotificationList 模态框
|
||||
- 通过 Supabase subscriptions 实施实时更新
|
||||
- 添加通知偏好设置页面
|
||||
|
||||
## Dependencies
|
||||
- Redis (for queue)
|
||||
- Email service (SendGrid/Resend)
|
||||
- Supabase real-time subscriptions
|
||||
## 依赖关系 (Dependencies)
|
||||
- Redis(用于队列)
|
||||
- 电子邮件服务 (SendGrid/Resend)
|
||||
- Supabase 实时订阅 (real-time subscriptions)
|
||||
|
||||
## Risks
|
||||
- HIGH: Email deliverability (SPF/DKIM required)
|
||||
- MEDIUM: Performance with 1000+ users per market
|
||||
- MEDIUM: Notification spam if markets resolve frequently
|
||||
- LOW: Real-time subscription overhead
|
||||
## 风险
|
||||
- 高 (HIGH):电子邮件可达性(需要 SPF/DKIM)
|
||||
- 中 (MEDIUM):每个市场超过 1000 名用户时的性能问题
|
||||
- 中 (MEDIUM):如果市场结算频繁,可能会产生通知垃圾
|
||||
- 低 (LOW):实时订阅的开销
|
||||
|
||||
## Estimated Complexity: MEDIUM
|
||||
- Backend: 4-6 hours
|
||||
- Frontend: 3-4 hours
|
||||
- Testing: 2-3 hours
|
||||
- Total: 9-13 hours
|
||||
## 预估复杂度:中 (MEDIUM)
|
||||
- 后端:4-6 小时
|
||||
- 前端:3-4 小时
|
||||
- 测试:2-3 小时
|
||||
- 总计:9-13 小时
|
||||
|
||||
**WAITING FOR CONFIRMATION**: Proceed with this plan? (yes/no/modify)
|
||||
**等待确认**:是否继续执行此计划?(yes/no/modify)
|
||||
```
|
||||
|
||||
## Important Notes
|
||||
## 重要提示
|
||||
|
||||
**CRITICAL**: The planner agent will **NOT** write any code until you explicitly confirm the plan with "yes" or "proceed" or similar affirmative response.
|
||||
**关键 (CRITICAL)**:在您明确确认计划(如回答 "yes" 或 "proceed" 或类似的肯定回复)之前,计划智能体(planner agent)**不会**编写任何代码。
|
||||
|
||||
If you want changes, respond with:
|
||||
- "modify: [your changes]"
|
||||
- "different approach: [alternative]"
|
||||
- "skip phase 2 and do phase 3 first"
|
||||
如果您想修改计划,请回复:
|
||||
- "modify: [您的修改意见]"
|
||||
- "different approach: [替代方案]"
|
||||
- "skip phase 2 and do phase 3 first"(跳过第 2 阶段,先做第 3 阶段)
|
||||
|
||||
## Integration with Other Commands
|
||||
## 与其他命令的集成
|
||||
|
||||
After planning:
|
||||
- Use `/tdd` to implement with test-driven development
|
||||
- Use `/build-and-fix` if build errors occur
|
||||
- Use `/code-review` to review completed implementation
|
||||
计划完成后:
|
||||
- 使用 `/tdd` 通过测试驱动开发(test-driven development)进行实施
|
||||
- 如果出现构建错误,使用 `/build-and-fix`
|
||||
- 使用 `/code-review` 评审已完成的实施
|
||||
|
||||
## Related Agents
|
||||
## 相关智能体
|
||||
|
||||
This command invokes the `planner` agent located at:
|
||||
此命令调用位于以下路径的 `planner` 智能体:
|
||||
`~/.claude/agents/planner.md`
|
||||
|
||||
@@ -1,28 +1,28 @@
|
||||
# Refactor Clean
|
||||
# 重构清理 (Refactor Clean)
|
||||
|
||||
Safely identify and remove dead code with test verification:
|
||||
安全地识别并通过测试验证移除死代码(Dead Code):
|
||||
|
||||
1. Run dead code analysis tools:
|
||||
- knip: Find unused exports and files
|
||||
- depcheck: Find unused dependencies
|
||||
- ts-prune: Find unused TypeScript exports
|
||||
1. 运行死代码分析工具:
|
||||
- knip:查找未使用的导出和文件
|
||||
- depcheck:查找未使用的依赖
|
||||
- ts-prune:查找未使用的 TypeScript 导出
|
||||
|
||||
2. Generate comprehensive report in .reports/dead-code-analysis.md
|
||||
2. 在 `.reports/dead-code-analysis.md` 中生成详细报告
|
||||
|
||||
3. Categorize findings by severity:
|
||||
- SAFE: Test files, unused utilities
|
||||
- CAUTION: API routes, components
|
||||
- DANGER: Config files, main entry points
|
||||
3. 按严重程度对结果进行分类:
|
||||
- 安全(SAFE):测试文件、未使用的工具类
|
||||
- 谨慎(CAUTION):API 路由、组件
|
||||
- 危险(DANGER):配置文件、主入口点
|
||||
|
||||
4. Propose safe deletions only
|
||||
4. 仅建议进行安全的删除
|
||||
|
||||
5. Before each deletion:
|
||||
- Run full test suite
|
||||
- Verify tests pass
|
||||
- Apply change
|
||||
- Re-run tests
|
||||
- Rollback if tests fail
|
||||
5. 在每次删除之前:
|
||||
- 运行完整的测试套件
|
||||
- 验证测试通过
|
||||
- 应用更改
|
||||
- 重新运行测试
|
||||
- 如果测试失败则回滚
|
||||
|
||||
6. Show summary of cleaned items
|
||||
6. 显示已清理项的摘要
|
||||
|
||||
Never delete code without running tests first!
|
||||
严禁在未运行测试的情况下删除代码!
|
||||
|
||||
@@ -1,42 +1,42 @@
|
||||
---
|
||||
description: Configure your preferred package manager (npm/pnpm/yarn/bun)
|
||||
description: 配置你偏好的包管理器 (npm/pnpm/yarn/bun)
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
# Package Manager Setup
|
||||
# 包管理器设置 (Package Manager Setup)
|
||||
|
||||
Configure your preferred package manager for this project or globally.
|
||||
为本项目或全局配置你偏好的包管理器。
|
||||
|
||||
## Usage
|
||||
## 用法 (Usage)
|
||||
|
||||
```bash
|
||||
# Detect current package manager
|
||||
# 检测当前包管理器
|
||||
node scripts/setup-package-manager.js --detect
|
||||
|
||||
# Set global preference
|
||||
# 设置全局偏好
|
||||
node scripts/setup-package-manager.js --global pnpm
|
||||
|
||||
# Set project preference
|
||||
# 设置项目偏好
|
||||
node scripts/setup-package-manager.js --project bun
|
||||
|
||||
# List available package managers
|
||||
# 列出可用的包管理器
|
||||
node scripts/setup-package-manager.js --list
|
||||
```
|
||||
|
||||
## Detection Priority
|
||||
## 检测优先级 (Detection Priority)
|
||||
|
||||
When determining which package manager to use, the following order is checked:
|
||||
在确定使用哪个包管理器时,将按以下顺序进行检查:
|
||||
|
||||
1. **Environment variable**: `CLAUDE_PACKAGE_MANAGER`
|
||||
2. **Project config**: `.claude/package-manager.json`
|
||||
3. **package.json**: `packageManager` field
|
||||
4. **Lock file**: Presence of package-lock.json, yarn.lock, pnpm-lock.yaml, or bun.lockb
|
||||
5. **Global config**: `~/.claude/package-manager.json`
|
||||
6. **Fallback**: First available package manager (pnpm > bun > yarn > npm)
|
||||
1. **环境变量 (Environment variable)**: `CLAUDE_PACKAGE_MANAGER`
|
||||
2. **项目配置 (Project config)**: `.claude/package-manager.json`
|
||||
3. **package.json**: `packageManager` 字段
|
||||
4. **锁定文件 (Lock file)**: 是否存在 package-lock.json、yarn.lock、pnpm-lock.yaml 或 bun.lockb
|
||||
5. **全局配置 (Global config)**: `~/.claude/package-manager.json`
|
||||
6. **后备方案 (Fallback)**: 第一个可用的包管理器 (pnpm > bun > yarn > npm)
|
||||
|
||||
## Configuration Files
|
||||
## 配置文件 (Configuration Files)
|
||||
|
||||
### Global Configuration
|
||||
### 全局配置
|
||||
```json
|
||||
// ~/.claude/package-manager.json
|
||||
{
|
||||
@@ -44,7 +44,7 @@ When determining which package manager to use, the following order is checked:
|
||||
}
|
||||
```
|
||||
|
||||
### Project Configuration
|
||||
### 项目配置
|
||||
```json
|
||||
// .claude/package-manager.json
|
||||
{
|
||||
@@ -59,9 +59,9 @@ When determining which package manager to use, the following order is checked:
|
||||
}
|
||||
```
|
||||
|
||||
## Environment Variable
|
||||
## 环境变量 (Environment Variable)
|
||||
|
||||
Set `CLAUDE_PACKAGE_MANAGER` to override all other detection methods:
|
||||
设置 `CLAUDE_PACKAGE_MANAGER` 以覆盖所有其他检测方法:
|
||||
|
||||
```bash
|
||||
# Windows (PowerShell)
|
||||
@@ -71,9 +71,9 @@ $env:CLAUDE_PACKAGE_MANAGER = "pnpm"
|
||||
export CLAUDE_PACKAGE_MANAGER=pnpm
|
||||
```
|
||||
|
||||
## Run the Detection
|
||||
## 运行检测 (Run the Detection)
|
||||
|
||||
To see current package manager detection results, run:
|
||||
若要查看当前的包管理器检测结果,请运行:
|
||||
|
||||
```bash
|
||||
node scripts/setup-package-manager.js --detect
|
||||
|
||||
212
commands/tdd.md
212
commands/tdd.md
@@ -2,59 +2,59 @@
|
||||
description: Enforce test-driven development workflow. Scaffold interfaces, generate tests FIRST, then implement minimal code to pass. Ensure 80%+ coverage.
|
||||
---
|
||||
|
||||
# TDD Command
|
||||
# TDD 命令
|
||||
|
||||
This command invokes the **tdd-guide** agent to enforce test-driven development methodology.
|
||||
此命令调用 **tdd-guide** 智能体(Agent)来强制执行测试驱动开发(TDD)方法论。
|
||||
|
||||
## What This Command Does
|
||||
## 此命令的作用
|
||||
|
||||
1. **Scaffold Interfaces** - Define types/interfaces first
|
||||
2. **Generate Tests First** - Write failing tests (RED)
|
||||
3. **Implement Minimal Code** - Write just enough to pass (GREEN)
|
||||
4. **Refactor** - Improve code while keeping tests green (REFACTOR)
|
||||
5. **Verify Coverage** - Ensure 80%+ test coverage
|
||||
1. **搭建接口(Scaffold Interfaces)** - 首先定义类型/接口
|
||||
2. **先生成测试** - 编写失败的测试(红/RED)
|
||||
3. **编写最小化实现代码** - 只编写刚好能通过测试的代码(绿/GREEN)
|
||||
4. **重构(Refactor)** - 在保持测试通过的前提下优化代码(重构/REFACTOR)
|
||||
5. **验证覆盖率** - 确保测试覆盖率达到 80% 以上
|
||||
|
||||
## When to Use
|
||||
## 适用场景
|
||||
|
||||
Use `/tdd` when:
|
||||
- Implementing new features
|
||||
- Adding new functions/components
|
||||
- Fixing bugs (write test that reproduces bug first)
|
||||
- Refactoring existing code
|
||||
- Building critical business logic
|
||||
在以下情况下使用 `/tdd`:
|
||||
- 实现新功能
|
||||
- 添加新的函数/组件
|
||||
- 修复 Bug(先编写重现该 Bug 的测试)
|
||||
- 重构现有代码
|
||||
- 构建核心业务逻辑
|
||||
|
||||
## How It Works
|
||||
## 工作原理
|
||||
|
||||
The tdd-guide agent will:
|
||||
tdd-guide 智能体将:
|
||||
|
||||
1. **Define interfaces** for inputs/outputs
|
||||
2. **Write tests that will FAIL** (because code doesn't exist yet)
|
||||
3. **Run tests** and verify they fail for the right reason
|
||||
4. **Write minimal implementation** to make tests pass
|
||||
5. **Run tests** and verify they pass
|
||||
6. **Refactor** code while keeping tests green
|
||||
7. **Check coverage** and add more tests if below 80%
|
||||
1. 为输入/输出**定义接口**
|
||||
2. **编写会失败(FAIL)的测试**(因为代码尚未存在)
|
||||
3. **运行测试**并验证它们因预期的原因而失败
|
||||
4. **编写最小化实现**以使测试通过
|
||||
5. **运行测试**并验证它们通过
|
||||
6. 在保持测试通过的前提下**重构**代码
|
||||
7. **检查覆盖率**,如果低于 80% 则添加更多测试
|
||||
|
||||
## TDD Cycle
|
||||
## TDD 循环
|
||||
|
||||
```
|
||||
RED → GREEN → REFACTOR → REPEAT
|
||||
红 (RED) → 绿 (GREEN) → 重构 (REFACTOR) → 重复 (REPEAT)
|
||||
|
||||
RED: Write a failing test
|
||||
GREEN: Write minimal code to pass
|
||||
REFACTOR: Improve code, keep tests passing
|
||||
REPEAT: Next feature/scenario
|
||||
红 (RED): 编写一个失败的测试
|
||||
绿 (GREEN): 编写最小化代码以通过测试
|
||||
重构 (REFACTOR): 改进代码,保持测试通过
|
||||
重复 (REPEAT): 下一个功能/场景
|
||||
```
|
||||
|
||||
## Example Usage
|
||||
## 使用示例
|
||||
|
||||
```
|
||||
User: /tdd I need a function to calculate market liquidity score
|
||||
User: /tdd 我需要一个计算市场流动性评分(market liquidity score)的函数
|
||||
|
||||
Agent (tdd-guide):
|
||||
# TDD Session: Market Liquidity Score Calculator
|
||||
# TDD 会话:市场流动性评分计算器
|
||||
|
||||
## Step 1: Define Interface (SCAFFOLD)
|
||||
## 步骤 1:定义接口 (SCAFFOLD)
|
||||
|
||||
```typescript
|
||||
// lib/liquidity.ts
|
||||
@@ -66,12 +66,12 @@ export interface MarketData {
|
||||
}
|
||||
|
||||
export function calculateLiquidityScore(market: MarketData): number {
|
||||
// TODO: Implementation
|
||||
// TODO: 待实现
|
||||
throw new Error('Not implemented')
|
||||
}
|
||||
```
|
||||
|
||||
## Step 2: Write Failing Test (RED)
|
||||
## 步骤 2:编写失败的测试 (RED)
|
||||
|
||||
```typescript
|
||||
// lib/liquidity.test.ts
|
||||
@@ -97,7 +97,7 @@ describe('calculateLiquidityScore', () => {
|
||||
totalVolume: 100,
|
||||
bidAskSpread: 0.5,
|
||||
activeTraders: 2,
|
||||
lastTradeTime: new Date(Date.now() - 86400000) // 1 day ago
|
||||
lastTradeTime: new Date(Date.now() - 86400000) // 1 天前
|
||||
}
|
||||
|
||||
const score = calculateLiquidityScore(market)
|
||||
@@ -121,7 +121,7 @@ describe('calculateLiquidityScore', () => {
|
||||
})
|
||||
```
|
||||
|
||||
## Step 3: Run Tests - Verify FAIL
|
||||
## 步骤 3:运行测试 - 验证失败 (FAIL)
|
||||
|
||||
```bash
|
||||
npm test lib/liquidity.test.ts
|
||||
@@ -133,28 +133,28 @@ FAIL lib/liquidity.test.ts
|
||||
1 test failed, 0 passed
|
||||
```
|
||||
|
||||
✅ Tests fail as expected. Ready to implement.
|
||||
✅ 测试如预期般失败。准备开始实现。
|
||||
|
||||
## Step 4: Implement Minimal Code (GREEN)
|
||||
## 步骤 4:编写最小化实现代码 (GREEN)
|
||||
|
||||
```typescript
|
||||
// lib/liquidity.ts
|
||||
export function calculateLiquidityScore(market: MarketData): number {
|
||||
// Handle zero volume edge case
|
||||
// 处理零交易量的边缘情况
|
||||
if (market.totalVolume === 0) {
|
||||
return 0
|
||||
}
|
||||
|
||||
// Calculate component scores (0-100 scale)
|
||||
// 计算各项评分(0-100 刻度)
|
||||
const volumeScore = Math.min(market.totalVolume / 1000, 100)
|
||||
const spreadScore = Math.max(100 - (market.bidAskSpread * 1000), 0)
|
||||
const traderScore = Math.min(market.activeTraders / 10, 100)
|
||||
|
||||
// Recent activity bonus
|
||||
// 最近活跃度奖励
|
||||
const hoursSinceLastTrade = (Date.now() - market.lastTradeTime.getTime()) / (1000 * 60 * 60)
|
||||
const recencyScore = Math.max(100 - (hoursSinceLastTrade * 10), 0)
|
||||
|
||||
// Weighted average
|
||||
// 加权平均
|
||||
const score = (
|
||||
volumeScore * 0.4 +
|
||||
spreadScore * 0.3 +
|
||||
@@ -162,11 +162,11 @@ export function calculateLiquidityScore(market: MarketData): number {
|
||||
recencyScore * 0.1
|
||||
)
|
||||
|
||||
return Math.min(Math.max(score, 0), 100) // Clamp to 0-100
|
||||
return Math.min(Math.max(score, 0), 100) // 限制在 0-100 之间
|
||||
}
|
||||
```
|
||||
|
||||
## Step 5: Run Tests - Verify PASS
|
||||
## 步骤 5:运行测试 - 验证通过 (PASS)
|
||||
|
||||
```bash
|
||||
npm test lib/liquidity.test.ts
|
||||
@@ -179,12 +179,12 @@ PASS lib/liquidity.test.ts
|
||||
3 tests passed
|
||||
```
|
||||
|
||||
✅ All tests passing!
|
||||
✅ 所有测试均已通过!
|
||||
|
||||
## Step 6: Refactor (IMPROVE)
|
||||
## 步骤 6:重构 (IMPROVE)
|
||||
|
||||
```typescript
|
||||
// lib/liquidity.ts - Refactored with constants and better readability
|
||||
// lib/liquidity.ts - 使用常量重构以提高可读性
|
||||
const WEIGHTS = {
|
||||
VOLUME: 0.4,
|
||||
SPREAD: 0.3,
|
||||
@@ -223,7 +223,7 @@ export function calculateLiquidityScore(market: MarketData): number {
|
||||
}
|
||||
```
|
||||
|
||||
## Step 7: Verify Tests Still Pass
|
||||
## 步骤 7:验证测试依然通过
|
||||
|
||||
```bash
|
||||
npm test lib/liquidity.test.ts
|
||||
@@ -236,9 +236,9 @@ PASS lib/liquidity.test.ts
|
||||
3 tests passed
|
||||
```
|
||||
|
||||
✅ Refactoring complete, tests still passing!
|
||||
✅ 重构完成,测试依然通过!
|
||||
|
||||
## Step 8: Check Coverage
|
||||
## 步骤 8:检查覆盖率
|
||||
|
||||
```bash
|
||||
npm test -- --coverage lib/liquidity.test.ts
|
||||
@@ -247,80 +247,80 @@ File | % Stmts | % Branch | % Funcs | % Lines
|
||||
---------------|---------|----------|---------|--------
|
||||
liquidity.ts | 100 | 100 | 100 | 100
|
||||
|
||||
Coverage: 100% ✅ (Target: 80%)
|
||||
Coverage: 100% ✅ (目标: 80%)
|
||||
```
|
||||
|
||||
✅ TDD session complete!
|
||||
✅ TDD 会话完成!
|
||||
```
|
||||
|
||||
## TDD Best Practices
|
||||
## TDD 最佳实践
|
||||
|
||||
**DO:**
|
||||
- ✅ Write the test FIRST, before any implementation
|
||||
- ✅ Run tests and verify they FAIL before implementing
|
||||
- ✅ Write minimal code to make tests pass
|
||||
- ✅ Refactor only after tests are green
|
||||
- ✅ Add edge cases and error scenarios
|
||||
- ✅ Aim for 80%+ coverage (100% for critical code)
|
||||
**建议做法:**
|
||||
- ✅ **先**编写测试,在进行任何实现之前
|
||||
- ✅ 在编写实现之前,先运行测试并验证它们**失败**
|
||||
- ✅ 编写最小化代码以使测试通过
|
||||
- ✅ 仅在测试通过(绿色)后才进行重构
|
||||
- ✅ 涵盖边缘情况和错误场景
|
||||
- ✅ 目标是 80% 以上的覆盖率(核心代码要求 100%)
|
||||
|
||||
**DON'T:**
|
||||
- ❌ Write implementation before tests
|
||||
- ❌ Skip running tests after each change
|
||||
- ❌ Write too much code at once
|
||||
- ❌ Ignore failing tests
|
||||
- ❌ Test implementation details (test behavior)
|
||||
- ❌ Mock everything (prefer integration tests)
|
||||
**避免做法:**
|
||||
- ❌ 在测试之前编写实现
|
||||
- ❌ 每次更改后跳过运行测试
|
||||
- ❌ 一次性编写过多代码
|
||||
- ❌ 忽略失败的测试
|
||||
- ❌ 测试实现细节(应测试行为)
|
||||
- ❌ 模拟(Mock)一切(更推荐集成测试)
|
||||
|
||||
## Test Types to Include
|
||||
## 应包含的测试类型
|
||||
|
||||
**Unit Tests** (Function-level):
|
||||
- Happy path scenarios
|
||||
- Edge cases (empty, null, max values)
|
||||
- Error conditions
|
||||
- Boundary values
|
||||
**单元测试** (函数级别):
|
||||
- 核心流程(Happy path)场景
|
||||
- 边缘情况(空值、null、最大值)
|
||||
- 错误条件
|
||||
- 边界值
|
||||
|
||||
**Integration Tests** (Component-level):
|
||||
- API endpoints
|
||||
- Database operations
|
||||
- External service calls
|
||||
- React components with hooks
|
||||
**集成测试** (组件级别):
|
||||
- API 端点
|
||||
- 数据库操作
|
||||
- 外部服务调用
|
||||
- 带有 Hooks 的 React 组件
|
||||
|
||||
**E2E Tests** (use `/e2e` command):
|
||||
- Critical user flows
|
||||
- Multi-step processes
|
||||
- Full stack integration
|
||||
**E2E 测试** (使用 `/e2e` 命令):
|
||||
- 关键用户流程
|
||||
- 多步骤流程
|
||||
- 全栈集成
|
||||
|
||||
## Coverage Requirements
|
||||
## 覆盖率要求
|
||||
|
||||
- **80% minimum** for all code
|
||||
- **100% required** for:
|
||||
- Financial calculations
|
||||
- Authentication logic
|
||||
- Security-critical code
|
||||
- Core business logic
|
||||
- 所有代码**最低 80%**
|
||||
- 以下内容**要求 100%**:
|
||||
- 财务计算
|
||||
- 身份验证逻辑
|
||||
- 关键安全代码
|
||||
- 核心业务逻辑
|
||||
|
||||
## Important Notes
|
||||
## 重要提示
|
||||
|
||||
**MANDATORY**: Tests must be written BEFORE implementation. The TDD cycle is:
|
||||
**强制性**:必须在实现之前编写测试。TDD 循环是:
|
||||
|
||||
1. **RED** - Write failing test
|
||||
2. **GREEN** - Implement to pass
|
||||
3. **REFACTOR** - Improve code
|
||||
1. **红 (RED)** - 编写失败的测试
|
||||
2. **绿 (GREEN)** - 实现代码以通过测试
|
||||
3. **重构 (REFACTOR)** - 优化代码
|
||||
|
||||
Never skip the RED phase. Never write code before tests.
|
||||
切勿跳过红色(RED)阶段。切勿在测试之前编写代码。
|
||||
|
||||
## Integration with Other Commands
|
||||
## 与其他命令的集成
|
||||
|
||||
- Use `/plan` first to understand what to build
|
||||
- Use `/tdd` to implement with tests
|
||||
- Use `/build-and-fix` if build errors occur
|
||||
- Use `/code-review` to review implementation
|
||||
- Use `/test-coverage` to verify coverage
|
||||
- 首先使用 `/plan` 了解要构建的内容
|
||||
- 使用 `/tdd` 进行带测试的实现
|
||||
- 如果出现构建错误,使用 `/build-and-fix`
|
||||
- 使用 `/code-review` 审查实现
|
||||
- 使用 `/test-coverage` 验证覆盖率
|
||||
|
||||
## Related Agents
|
||||
## 相关智能体(Agents)
|
||||
|
||||
This command invokes the `tdd-guide` agent located at:
|
||||
此命令调用位于以下位置的 `tdd-guide` 智能体:
|
||||
`~/.claude/agents/tdd-guide.md`
|
||||
|
||||
And can reference the `tdd-workflow` skill at:
|
||||
并可以参考位于以下位置的 `tdd-workflow` 技能(Skill):
|
||||
`~/.claude/skills/tdd-workflow/`
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
# Test Coverage
|
||||
# 测试覆盖率 (Test Coverage)
|
||||
|
||||
Analyze test coverage and generate missing tests:
|
||||
分析测试覆盖率并生成缺失的测试用例:
|
||||
|
||||
1. Run tests with coverage: npm test --coverage or pnpm test --coverage
|
||||
1. 运行带覆盖率报告的测试:npm test --coverage 或 pnpm test --coverage
|
||||
|
||||
2. Analyze coverage report (coverage/coverage-summary.json)
|
||||
2. 分析覆盖率报告 (coverage/coverage-summary.json)
|
||||
|
||||
3. Identify files below 80% coverage threshold
|
||||
3. 识别覆盖率低于 80% 阈值的文件
|
||||
|
||||
4. For each under-covered file:
|
||||
- Analyze untested code paths
|
||||
- Generate unit tests for functions
|
||||
- Generate integration tests for APIs
|
||||
- Generate E2E tests for critical flows
|
||||
4. 针对每个覆盖率不足的文件:
|
||||
- 分析未测试的代码路径
|
||||
- 为函数生成单元测试 (Unit Tests)
|
||||
- 为 API 生成集成测试 (Integration Tests)
|
||||
- 为关键流程生成端到端测试 (E2E Tests)
|
||||
|
||||
5. Verify new tests pass
|
||||
5. 验证新测试已通过
|
||||
|
||||
6. Show before/after coverage metrics
|
||||
6. 展示覆盖率指标的前后对比
|
||||
|
||||
7. Ensure project reaches 80%+ overall coverage
|
||||
7. 确保项目整体覆盖率达到 80% 以上
|
||||
|
||||
Focus on:
|
||||
- Happy path scenarios
|
||||
- Error handling
|
||||
- Edge cases (null, undefined, empty)
|
||||
- Boundary conditions
|
||||
重点关注:
|
||||
- 正常路径 (Happy path) 场景
|
||||
- 错误处理 (Error handling)
|
||||
- 边缘情况 (Edge cases) (null, undefined, empty)
|
||||
- 边界条件 (Boundary conditions)
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
# Update Codemaps
|
||||
# 更新代码映射表(Update Codemaps)
|
||||
|
||||
Analyze the codebase structure and update architecture documentation:
|
||||
分析代码库结构并更新架构文档:
|
||||
|
||||
1. Scan all source files for imports, exports, and dependencies
|
||||
2. Generate token-lean codemaps in the following format:
|
||||
- codemaps/architecture.md - Overall architecture
|
||||
- codemaps/backend.md - Backend structure
|
||||
- codemaps/frontend.md - Frontend structure
|
||||
- codemaps/data.md - Data models and schemas
|
||||
1. 扫描所有源文件中的导入(imports)、导出(exports)和依赖关系
|
||||
2. 生成符合以下格式的 Token 精简版代码映射表(Codemaps):
|
||||
- `codemaps/architecture.md` - 整体架构
|
||||
- `codemaps/backend.md` - 后端结构
|
||||
- `codemaps/frontend.md` - 前端结构
|
||||
- `codemaps/data.md` - 数据模型与模式(Schemas)
|
||||
|
||||
3. Calculate diff percentage from previous version
|
||||
4. If changes > 30%, request user approval before updating
|
||||
5. Add freshness timestamp to each codemap
|
||||
6. Save reports to .reports/codemap-diff.txt
|
||||
3. 计算与上一版本的差异百分比
|
||||
4. 如果变更超过 30%,在更新前请求用户批准
|
||||
5. 为每个代码映射表(Codemap)添加更新时间戳
|
||||
6. 将报告保存至 `.reports/codemap-diff.txt`
|
||||
|
||||
Use TypeScript/Node.js for analysis. Focus on high-level structure, not implementation details.
|
||||
使用 TypeScript/Node.js 进行分析。侧重于高层级结构,而非实现细节。
|
||||
|
||||
@@ -1,31 +1,31 @@
|
||||
# Update Documentation
|
||||
# 更新文档 (Update Documentation)
|
||||
|
||||
Sync documentation from source-of-truth:
|
||||
从单一事实来源(Source-of-truth)同步文档:
|
||||
|
||||
1. Read package.json scripts section
|
||||
- Generate scripts reference table
|
||||
- Include descriptions from comments
|
||||
1. 读取 `package.json` 中的 `scripts` 章节
|
||||
- 生成脚本参考表
|
||||
- 包含来自注释的说明描述
|
||||
|
||||
2. Read .env.example
|
||||
- Extract all environment variables
|
||||
- Document purpose and format
|
||||
2. 读取 `.env.example`
|
||||
- 提取所有环境变量
|
||||
- 记录变量用途与格式
|
||||
|
||||
3. Generate docs/CONTRIB.md with:
|
||||
- Development workflow
|
||||
- Available scripts
|
||||
- Environment setup
|
||||
- Testing procedures
|
||||
3. 生成 `docs/CONTRIB.md`,内容包含:
|
||||
- 开发工作流(Development workflow)
|
||||
- 可用脚本
|
||||
- 环境搭建
|
||||
- 测试流程
|
||||
|
||||
4. Generate docs/RUNBOOK.md with:
|
||||
- Deployment procedures
|
||||
- Monitoring and alerts
|
||||
- Common issues and fixes
|
||||
- Rollback procedures
|
||||
4. 生成 `docs/RUNBOOK.md`,内容包含:
|
||||
- 部署流程
|
||||
- 监控与告警
|
||||
- 常见问题与修复
|
||||
- 回滚流程
|
||||
|
||||
5. Identify obsolete documentation:
|
||||
- Find docs not modified in 90+ days
|
||||
- List for manual review
|
||||
5. 识别过时文档:
|
||||
- 查找 90 天以上未修改的文档
|
||||
- 列出清单以供人工核查
|
||||
|
||||
6. Show diff summary
|
||||
6. 显示差异(diff)摘要
|
||||
|
||||
Single source of truth: package.json and .env.example
|
||||
单一事实来源(Single source of truth):`package.json` 和 `.env.example`
|
||||
|
||||
@@ -1,39 +1,39 @@
|
||||
# Verification Command
|
||||
# 验证(Verification)命令
|
||||
|
||||
Run comprehensive verification on current codebase state.
|
||||
对当前代码库状态进行全面验证。
|
||||
|
||||
## Instructions
|
||||
## 指令(Instructions)
|
||||
|
||||
Execute verification in this exact order:
|
||||
请按以下确切顺序执行验证:
|
||||
|
||||
1. **Build Check**
|
||||
- Run the build command for this project
|
||||
- If it fails, report errors and STOP
|
||||
1. **构建检查(Build Check)**
|
||||
- 运行此项目的构建命令
|
||||
- 如果构建失败,报告错误并停止(STOP)
|
||||
|
||||
2. **Type Check**
|
||||
- Run TypeScript/type checker
|
||||
- Report all errors with file:line
|
||||
2. **类型检查(Type Check)**
|
||||
- 运行 TypeScript/类型检查器
|
||||
- 报告所有错误及其对应的 `file:line`(文件:行号)
|
||||
|
||||
3. **Lint Check**
|
||||
- Run linter
|
||||
- Report warnings and errors
|
||||
3. **代码规范检查(Lint Check)**
|
||||
- 运行 Linter
|
||||
- 报告警告与错误
|
||||
|
||||
4. **Test Suite**
|
||||
- Run all tests
|
||||
- Report pass/fail count
|
||||
- Report coverage percentage
|
||||
4. **测试套件(Test Suite)**
|
||||
- 运行所有测试
|
||||
- 报告通过/失败的数量
|
||||
- 报告覆盖率百分比
|
||||
|
||||
5. **Console.log Audit**
|
||||
- Search for console.log in source files
|
||||
- Report locations
|
||||
5. **Console.log 审计**
|
||||
- 在源文件中搜索 `console.log`
|
||||
- 报告其所在位置
|
||||
|
||||
6. **Git Status**
|
||||
- Show uncommitted changes
|
||||
- Show files modified since last commit
|
||||
6. **Git 状态(Git Status)**
|
||||
- 显示未提交的更改
|
||||
- 显示自上次提交以来修改的文件
|
||||
|
||||
## Output
|
||||
## 输出(Output)
|
||||
|
||||
Produce a concise verification report:
|
||||
生成一份简洁的验证报告:
|
||||
|
||||
```
|
||||
VERIFICATION: [PASS/FAIL]
|
||||
@@ -48,12 +48,12 @@ Logs: [OK/X console.logs]
|
||||
Ready for PR: [YES/NO]
|
||||
```
|
||||
|
||||
If any critical issues, list them with fix suggestions.
|
||||
如果存在任何关键问题,请列出这些问题并给出修复建议。
|
||||
|
||||
## Arguments
|
||||
## 参数(Arguments)
|
||||
|
||||
$ARGUMENTS can be:
|
||||
- `quick` - Only build + types
|
||||
- `full` - All checks (default)
|
||||
- `pre-commit` - Checks relevant for commits
|
||||
- `pre-pr` - Full checks plus security scan
|
||||
`$ARGUMENTS` 可以是:
|
||||
- `quick` - 仅执行构建 + 类型检查
|
||||
- `full` - 执行所有检查(默认)
|
||||
- `pre-commit` - 执行与提交相关的检查
|
||||
- `pre-pr` - 执行完整检查以及安全扫描
|
||||
|
||||
Reference in New Issue
Block a user