Revert "feat(ecc): prune plugin 43→12 items, promote 7 rules to .claude/rules/ (#245)"

This reverts commit 1bd68ff534.
This commit is contained in:
Affaan Mustafa
2026-02-20 01:11:30 -08:00
parent 1bd68ff534
commit 0e9f613fd1
536 changed files with 111479 additions and 253 deletions

View File

@@ -0,0 +1,29 @@
# 构建与修复
逐步修复 TypeScript 和构建错误:
1. 运行构建npm run build 或 pnpm build
2. 解析错误输出:
* 按文件分组
* 按严重性排序
3. 对于每个错误:
* 显示错误上下文(前后 5 行)
* 解释问题
* 提出修复方案
* 应用修复
* 重新运行构建
* 验证错误是否已解决
4. 在以下情况停止:
* 修复引入了新的错误
* 同一错误在 3 次尝试后仍然存在
* 用户请求暂停
5. 显示摘要:
* 已修复的错误
* 剩余的错误
* 新引入的错误
为了安全起见,一次只修复一个错误!

View File

@@ -0,0 +1,78 @@
# 检查点命令
在你的工作流中创建或验证一个检查点。
## 用法
`/checkpoint [create|verify|list] [name]`
## 创建检查点
创建检查点时:
1. 运行 `/verify quick` 以确保当前状态是干净的
2. 使用检查点名称创建一个 git stash 或提交
3. 将检查点记录到 `.claude/checkpoints.log`
```bash
echo "$(date +%Y-%m-%d-%H:%M) | $CHECKPOINT_NAME | $(git rev-parse --short HEAD)" >> .claude/checkpoints.log
```
4. 报告检查点已创建
## 验证检查点
根据检查点进行验证时:
1. 从日志中读取检查点
2. 将当前状态与检查点进行比较:
* 自检查点以来新增的文件
* 自检查点以来修改的文件
* 现在的测试通过率与当时对比
* 现在的覆盖率与当时对比
3. 报告:
```
CHECKPOINT COMPARISON: $NAME
============================
Files changed: X
Tests: +Y passed / -Z failed
Coverage: +X% / -Y%
Build: [PASS/FAIL]
```
## 列出检查点
显示所有检查点,包含:
* 名称
* 时间戳
* Git SHA
* 状态(当前、落后、超前)
## 工作流
典型的检查点流程:
```
[Start] --> /checkpoint create "feature-start"
|
[Implement] --> /checkpoint create "core-done"
|
[Test] --> /checkpoint verify "core-done"
|
[Refactor] --> /checkpoint create "refactor-done"
|
[PR] --> /checkpoint verify "feature-start"
```
## 参数
$ARGUMENTS:
* `create <name>` - 创建指定名称的检查点
* `verify <name>` - 根据指定名称的检查点进行验证
* `list` - 显示所有检查点
* `clear` - 删除旧的检查点保留最后5个

View File

@@ -0,0 +1,43 @@
# 代码审查
对未提交的更改进行全面的安全性和质量审查:
1. 获取更改的文件:`git diff --name-only HEAD`
2. 对每个更改的文件,检查:
**安全问题(严重):**
* 硬编码的凭据、API 密钥、令牌
* SQL 注入漏洞
* XSS 漏洞
* 缺少输入验证
* 不安全的依赖项
* 路径遍历风险
**代码质量(高):**
* 函数长度超过 50 行
* 文件长度超过 800 行
* 嵌套深度超过 4 层
* 缺少错误处理
* `console.log` 语句
* `TODO`/`FIXME` 注释
* 公共 API 缺少 JSDoc
**最佳实践(中):**
* 可变模式(应使用不可变模式)
* 代码/注释中使用表情符号
* 新代码缺少测试
* 无障碍性问题a11y
3. 生成报告,包含:
* 严重性:严重、高、中、低
* 文件位置和行号
* 问题描述
* 建议的修复方法
4. 如果发现严重或高优先级问题,则阻止提交
绝不允许包含安全漏洞的代码!

370
docs/zh-CN/commands/e2e.md Normal file
View File

@@ -0,0 +1,370 @@
---
description: 使用 Playwright 生成并运行端到端测试。创建测试旅程、运行测试、捕获截图/视频/跟踪,并上传工件。
---
# E2E 命令
此命令调用 **e2e-runner** 代理来使用 Playwright 生成、维护和执行端到端测试。
## 此命令的作用
1. **生成测试旅程** - 为用户流程创建 Playwright 测试
2. **运行 E2E 测试** - 跨浏览器执行测试
3. **捕获工件** - 失败时的截图、视频、跟踪
4. **上传结果** - HTML 报告和 JUnit XML
5. **识别不稳定测试** - 隔离不稳定的测试
## 何时使用
在以下情况使用 `/e2e`
* 测试关键用户旅程(登录、交易、支付)
* 验证多步骤流程端到端工作
* 测试 UI 交互和导航
* 验证前端和后端之间的集成
* 为生产部署做准备
## 工作原理
e2e-runner 代理将:
1. **分析用户流程**并识别测试场景
2. **使用页面对象模型模式生成 Playwright 测试**
3. **跨多个浏览器Chrome、Firefox、Safari运行测试**
4. **捕获失败**,包括截图、视频和跟踪
5. **生成包含结果和工件的报告**
6. **识别不稳定测试**并推荐修复方法
## 使用示例
````
User: /e2e Test the market search and view flow
Agent (e2e-runner):
# E2E Test Generation: Market Search and View Flow
## 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
## Generated Test Code
```typescript
// tests/e2e/markets/search-and-view.spec.ts
import { test, expect } from '@playwright/test'
import { MarketsPage } from '../../pages/MarketsPage'
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
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
await marketsPage.searchMarkets('election')
// Wait for API response
await page.waitForResponse(resp =>
resp.url().includes('/api/markets/search') && resp.status() === 200
)
// 3. Verify search results
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
const firstMarketTitle = await marketCards.first().textContent()
await marketCards.first().click()
// 5. Verify market details page loads
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
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' })
})
test('search with no results shows empty state', async ({ page }) => {
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
)
const marketCount = await marketsPage.marketCards.count()
expect(marketCount).toBe(0)
})
test('can clear search and see all markets again', async ({ page }) => {
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)
})
})
````
## 运行测试
```bash
# Run the generated test
npx playwright test tests/e2e/markets/search-and-view.spec.ts
Running 3 tests using 3 workers
✓ [chromium] search-and-view.spec.ts:5:3 user can search markets and view details (4.2s)
✓ [chromium] search-and-view.spec.ts:52:3 search with no results shows empty state (1.8s)
✓ [chromium] search-and-view.spec.ts:67:3 can clear search and see all markets again (2.9s)
3 passed (9.1s)
Artifacts generated:
- artifacts/search-results.png
- artifacts/market-details.png
- playwright-report/index.html
```
## 测试报告
```
╔══════════════════════════════════════════════════════════════╗
║ E2E Test Results ║
╠══════════════════════════════════════════════════════════════╣
║ Status: ✅ ALL TESTS PASSED ║
║ Total: 3 tests ║
║ Passed: 3 (100%) ║
║ Failed: 0 ║
║ Flaky: 0 ║
║ Duration: 9.1s ║
╚══════════════════════════════════════════════════════════════╝
Artifacts:
📸 Screenshots: 2 files
📹 Videos: 0 files (only on failure)
🔍 Traces: 0 files (only on failure)
📊 HTML Report: playwright-report/index.html
View report: npx playwright show-report
```
✅ E2E 测试套件已准备好进行 CI/CD 集成!
````
## Test Artifacts
When tests run, the following artifacts are captured:
**On All Tests:**
- HTML Report with timeline and results
- JUnit XML for CI integration
**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
npx playwright show-report
# View specific trace file
npx playwright show-trace artifacts/trace-abc123.zip
# Screenshots are saved in artifacts/ directory
open artifacts/search-results.png
````
## 不稳定测试检测
如果测试间歇性失败:
```
⚠️ FLAKY TEST DETECTED: tests/e2e/markets/trade.spec.ts
Test passed 7/10 runs (70% pass rate)
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
Quarantine recommendation: Mark as test.fixme() until fixed
```
## 浏览器配置
默认情况下,测试在多个浏览器上运行:
* ✅ Chromium桌面版 Chrome
* ✅ Firefox桌面版
* ✅ WebKit桌面版 Safari
* ✅ 移动版 Chrome可选
在 `playwright.config.ts` 中配置以调整浏览器。
## CI/CD 集成
添加到您的 CI 流水线:
```yaml
# .github/workflows/e2e.yml
- name: Install Playwright
run: npx playwright install --with-deps
- name: Run E2E tests
run: npx playwright test
- name: Upload artifacts
if: always()
uses: actions/upload-artifact@v3
with:
name: playwright-report
path: playwright-report/
```
## PMX 特定的关键流程
对于 PMX请优先考虑以下 E2E 测试:
**🔴 关键(必须始终通过):**
1. 用户可以连接钱包
2. 用户可以浏览市场
3. 用户可以搜索市场(语义搜索)
4. 用户可以查看市场详情
5. 用户可以下交易单(使用测试资金)
6. 市场正确结算
7. 用户可以提取资金
**🟡 重要:**
1. 市场创建流程
2. 用户资料更新
3. 实时价格更新
4. 图表渲染
5. 过滤和排序市场
6. 移动端响应式布局
## 最佳实践
**应该:**
* ✅ 使用页面对象模型以提高可维护性
* ✅ 使用 data-testid 属性作为选择器
* ✅ 等待 API 响应,而不是使用任意超时
* ✅ 测试关键用户旅程的端到端
* ✅ 在合并到主分支前运行测试
* ✅ 在测试失败时审查工件
**不应该:**
* ❌ 使用不稳定的选择器CSS 类可能会改变)
* ❌ 测试实现细节
* ❌ 针对生产环境运行测试
* ❌ 忽略不稳定测试
* ❌ 在失败时跳过工件审查
* ❌ 使用 E2E 测试每个边缘情况(使用单元测试)
## 重要注意事项
**对 PMX 至关重要:**
* 涉及真实资金的 E2E 测试**必须**仅在测试网/暂存环境中运行
* 切勿针对生产环境运行交易测试
* 为金融测试设置 `test.skip(process.env.NODE_ENV === 'production')`
* 仅使用带有少量测试资金的测试钱包
## 与其他命令的集成
* 使用 `/plan` 来识别要测试的关键旅程
* 使用 `/tdd` 进行单元测试(更快、更细粒度)
* 使用 `/e2e` 进行集成和用户旅程测试
* 使用 `/code-review` 来验证测试质量
## 相关代理
此命令调用位于 `~/.claude/agents/e2e-runner.md` 的 `e2e-runner` 代理。
## 快速命令
```bash
# Run all E2E tests
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
```

122
docs/zh-CN/commands/eval.md Normal file
View File

@@ -0,0 +1,122 @@
# Eval 命令
管理基于评估的开发工作流。
## 用法
`/eval [define|check|report|list] [feature-name]`
## 定义评估
`/eval define feature-name`
创建新的评估定义:
1. 使用模板创建 `.claude/evals/feature-name.md`
```markdown
## EVAL: 功能名称
创建于: $(date)
### 能力评估
- [ ] [能力 1 的描述]
- [ ] [能力 2 的描述]
### 回归评估
- [ ] [现有行为 1 仍然有效]
- [ ] [现有行为 2 仍然有效]
### 成功标准
- 能力评估的 pass@3 > 90%
- 回归评估的 pass^3 = 100%
```
2. 提示用户填写具体标准
## 检查评估
`/eval check feature-name`
为功能运行评估:
1.`.claude/evals/feature-name.md` 读取评估定义
2. 对于每个能力评估:
* 尝试验证标准
* 记录 通过/失败
*`.claude/evals/feature-name.log` 中记录尝试
3. 对于每个回归评估:
* 运行相关测试
* 与基线比较
* 记录 通过/失败
4. 报告当前状态:
```
EVAL CHECK: feature-name
========================
Capability: X/Y passing
Regression: X/Y passing
Status: IN PROGRESS / READY
```
## 报告评估
`/eval report feature-name`
生成全面的评估报告:
```
EVAL REPORT: feature-name
=========================
Generated: $(date)
CAPABILITY EVALS
----------------
[eval-1]: PASS (pass@1)
[eval-2]: PASS (pass@2) - required retry
[eval-3]: FAIL - see notes
REGRESSION EVALS
----------------
[test-1]: PASS
[test-2]: PASS
[test-3]: PASS
METRICS
-------
Capability pass@1: 67%
Capability pass@3: 100%
Regression pass^3: 100%
NOTES
-----
[Any issues, edge cases, or observations]
RECOMMENDATION
--------------
[SHIP / NEEDS WORK / BLOCKED]
```
## 列出评估
`/eval list`
显示所有评估定义:
```
EVAL DEFINITIONS
================
feature-auth [3/5 passing] IN PROGRESS
feature-search [5/5 passing] READY
feature-export [0/4 passing] NOT STARTED
```
## 参数
$ARGUMENTS:
* `define <name>` - 创建新的评估定义
* `check <name>` - 运行并检查评估
* `report <name>` - 生成完整报告
* `list` - 显示所有评估
* `clean` - 删除旧的评估日志(保留最近 10 次运行)

View File

@@ -0,0 +1,209 @@
---
name: evolve
description: 将相关本能聚类为技能、命令或代理
command: true
---
# Evolve 命令
## 实现方式
使用插件根路径运行 instinct CLI
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/skills/continuous-learning-v2/scripts/instinct-cli.py" evolve [--generate]
```
或者如果 `CLAUDE_PLUGIN_ROOT` 未设置(手动安装):
```bash
python3 ~/.claude/skills/continuous-learning-v2/scripts/instinct-cli.py evolve [--generate]
```
分析本能并将相关的本能聚合成更高层次的结构:
* **命令**:当本能描述用户调用的操作时
* **技能**:当本能描述自动触发的行为时
* **代理**:当本能描述复杂的、多步骤的流程时
## 使用方法
```
/evolve # Analyze all instincts and suggest evolutions
/evolve --domain testing # Only evolve instincts in testing domain
/evolve --dry-run # Show what would be created without creating
/evolve --threshold 5 # Require 5+ related instincts to cluster
```
## 演化规则
### → 命令(用户调用)
当本能描述用户会明确请求的操作时:
* 多个关于“当用户要求...”的本能
* 触发器类似“当创建新的 X 时”的本能
* 遵循可重复序列的本能
示例:
* `new-table-step1`: "当添加数据库表时,创建迁移"
* `new-table-step2`: "当添加数据库表时,更新模式"
* `new-table-step3`: "当添加数据库表时,重新生成类型"
→ 创建:`/new-table` 命令
### → 技能(自动触发)
当本能描述应该自动发生的行为时:
* 模式匹配触发器
* 错误处理响应
* 代码风格强制执行
示例:
* `prefer-functional`: "当编写函数时,优先使用函数式风格"
* `use-immutable`: "当修改状态时,使用不可变模式"
* `avoid-classes`: "当设计模块时,避免基于类的设计"
→ 创建:`functional-patterns` 技能
### → 代理(需要深度/隔离)
当本能描述复杂的、多步骤的、受益于隔离的流程时:
* 调试工作流
* 重构序列
* 研究任务
示例:
* `debug-step1`: "当调试时,首先检查日志"
* `debug-step2`: "当调试时,隔离故障组件"
* `debug-step3`: "当调试时,创建最小复现"
* `debug-step4`: "当调试时,用测试验证修复"
→ 创建:`debugger` 代理
## 操作步骤
1.`~/.claude/homunculus/instincts/` 读取所有本能
2. 按以下方式对本能进行分组:
* 领域相似性
* 触发器模式重叠
* 操作序列关联性
3. 对于每个包含 3 个以上相关本能的集群:
* 确定演化类型(命令/技能/代理)
* 生成相应的文件
* 保存到 `~/.claude/homunculus/evolved/{commands,skills,agents}/`
4. 将演化后的结构链接回源本能
## 输出格式
```
🧬 Evolve Analysis
==================
Found 3 clusters ready for evolution:
## Cluster 1: Database Migration Workflow
Instincts: new-table-migration, update-schema, regenerate-types
Type: Command
Confidence: 85% (based on 12 observations)
Would create: /new-table command
Files:
- ~/.claude/homunculus/evolved/commands/new-table.md
## Cluster 2: Functional Code Style
Instincts: prefer-functional, use-immutable, avoid-classes, pure-functions
Type: Skill
Confidence: 78% (based on 8 observations)
Would create: functional-patterns skill
Files:
- ~/.claude/homunculus/evolved/skills/functional-patterns.md
## Cluster 3: Debugging Process
Instincts: debug-check-logs, debug-isolate, debug-reproduce, debug-verify
Type: Agent
Confidence: 72% (based on 6 observations)
Would create: debugger agent
Files:
- ~/.claude/homunculus/evolved/agents/debugger.md
---
Run `/evolve --execute` to create these files.
```
## 标志
* `--execute`: 实际创建演化后的结构(默认为预览)
* `--dry-run`: 仅预览而不创建
* `--domain <name>`: 仅演化指定领域的本能
* `--threshold <n>`: 形成集群所需的最小本能数默认3
* `--type <command|skill|agent>`: 仅创建指定类型
## 生成的文件格式
### 命令
```markdown
---
name: new-table
description: Create a new database table with migration, schema update, and type generation
command: /new-table
evolved_from:
- new-table-migration
- update-schema
- regenerate-types
---
# 新建数据表命令
[基于集群本能生成的内容]
## 步骤
1. ...
2. ...
```
### 技能
```markdown
---
name: functional-patterns
description: 强制执行函数式编程模式
evolved_from:
- prefer-functional
- use-immutable
- avoid-classes
---
# 函数式模式技能
[基于聚类本能生成的内容]
```
### 代理
```markdown
---
name: debugger
description: 系统性调试代理
model: sonnet
evolved_from:
- debug-check-logs
- debug-isolate
- debug-reproduce
---
# 调试器代理
[基于聚类本能生成的内容]
```

View File

@@ -0,0 +1,187 @@
---
description: 逐步修复Go构建错误、go vet警告和linter问题。调用go-build-resolver代理进行最小化、精确的修复。
---
# Go 构建与修复
此命令调用 **go-build-resolver** 代理,以最小的更改增量修复 Go 构建错误。
## 此命令的作用
1. **运行诊断**:执行 `go build``go vet``staticcheck`
2. **解析错误**:按文件分组并按严重性排序
3. **增量修复**:一次修复一个错误
4. **验证每次修复**:每次更改后重新运行构建
5. **报告摘要**:显示已修复的内容和剩余问题
## 何时使用
在以下情况使用 `/go-build`
* `go build ./...` 因错误而失败
* `go vet ./...` 报告问题
* `golangci-lint run` 显示警告
* 模块依赖关系损坏
* 拉取更改后导致构建失败
## 运行的诊断命令
```bash
# Primary build check
go build ./...
# Static analysis
go vet ./...
# Extended linting (if available)
staticcheck ./...
golangci-lint run
# Module issues
go mod verify
go mod tidy -v
```
## 示例会话
````text
User: /go-build
Agent:
# Go Build Resolution
## Initial Diagnostics
```bash
$ go build ./...
internal/service/user.go:25:15: undefined: UserRepository
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
````
发现错误3
## 修复 1未定义的标识符
文件internal/service/user.go:25
错误undefined: UserRepository
原因:缺少导入
```go
// Added import
import "project/internal/repository"
// Changed
var repo UserRepository
// To
var repo repository.UserRepository
```
```bash
$ go build ./...
# 2 errors remaining
```
## 修复 2类型不匹配
文件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
```
## 修复 3缺少返回
文件internal/handler/api.go:58
错误missing return at end of function
```go
func GetUser(id string) (*User, error) {
if id == "" {
return nil, ErrInvalidID
}
user := findUser(id)
// Added missing return
return user, nil
}
```
```bash
$ go build ./...
# Build successful!
```
## 最终验证
```bash
$ go vet ./...
# No issues
$ go test ./...
ok project/internal/service 0.015s
ok project/internal/handler 0.023s
```
## 摘要
| 指标 | 数量 |
|--------|-------|
| 已修复的构建错误 | 3 |
| 已修复的 Vet 警告 | 0 |
| 已修改的文件 | 2 |
| 剩余问题 | 0 |
构建状态:✅ 成功
```
## 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` |
## 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
## 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
## Related Commands
- `/go-test` - Run tests after build succeeds
- `/go-review` - Review code quality
- `/verify` - Full verification loop
## Related
- Agent: `agents/go-build-resolver.md`
- Skill: `skills/golang-patterns/`
```

View File

@@ -0,0 +1,161 @@
---
description: 全面的Go代码审查涵盖惯用模式、并发安全性、错误处理和安全性。调用go-reviewer代理。
---
# Go 代码审查
此命令调用 **go-reviewer** 代理进行全面的 Go 语言特定代码审查。
## 此命令的作用
1. **识别 Go 变更**:通过 `git diff` 查找修改过的 `.go` 文件
2. **运行静态分析**:执行 `go vet``staticcheck``golangci-lint`
3. **安全扫描**:检查 SQL 注入、命令注入、竞态条件
4. **并发性审查**:分析 goroutine 安全性、通道使用、互斥锁模式
5. **惯用 Go 检查**:验证代码是否遵循 Go 约定和最佳实践
6. **生成报告**:按严重程度分类问题
## 使用时机
在以下情况使用 `/go-review`
* 编写或修改 Go 代码之后
* 提交 Go 变更之前
* 审查包含 Go 代码的拉取请求时
* 接手新的 Go 代码库时
* 学习惯用 Go 模式时
## 审查类别
### 严重(必须修复)
* SQL/命令注入漏洞
* 无同步的竞态条件
* Goroutine 泄漏
* 硬编码凭证
* 不安全的指针使用
* 关键路径中忽略的错误
### 高(应该修复)
* 缺少带上下文的错误包装
* 使用 panic 而非返回错误
* 上下文未传播
* 无缓冲通道导致死锁
* 接口未满足错误
* 缺少互斥锁保护
### 中(考虑修复)
* 非惯用代码模式
* 导出项缺少 godoc 注释
* 低效的字符串拼接
* 切片未预分配
* 未使用表格驱动测试
## 运行的自动化检查
```bash
# Static analysis
go vet ./...
# Advanced checks (if installed)
staticcheck ./...
golangci-lint run
# Race detection
go build -race ./...
# Security vulnerabilities
govulncheck ./...
```
## 使用示例
````text
User: /go-review
Agent:
# Go Code Review Report
## Files Reviewed
- internal/handler/user.go (modified)
- internal/service/auth.go (modified)
## Static Analysis Results
✓ go vet: No issues
✓ staticcheck: No issues
## Issues Found
[CRITICAL] Race Condition
File: internal/service/auth.go:45
Issue: Shared map accessed without synchronization
```go
var cache = map[string]*Session{} // Concurrent access!
func GetSession(id string) *Session {
return cache[id] // Race condition
}
````
修复:使用 sync.RWMutex 或 sync.Map
```go
var (
cache = map[string]*Session{}
cacheMu sync.RWMutex
)
func GetSession(id string) *Session {
cacheMu.RLock()
defer cacheMu.RUnlock()
return cache[id]
}
```
\[高] 缺少错误上下文
文件internal/handler/user.go:28
问题:返回的错误缺少上下文
```go
return err // No context
```
修复:使用上下文包装
```go
return fmt.Errorf("get user %s: %w", userID, err)
```
## 摘要
* 严重1
* 高1
* 中0
建议:❌ 在严重问题修复前阻止合并
```
## Approval Criteria
| Status | Condition |
|--------|-----------|
| ✅ Approve | No CRITICAL or HIGH issues |
| ⚠️ Warning | Only MEDIUM issues (merge with caution) |
| ❌ Block | CRITICAL or HIGH issues found |
## 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
## Related
- Agent: `agents/go-reviewer.md`
- Skills: `skills/golang-patterns/`, `skills/golang-testing/`
```

View File

@@ -0,0 +1,274 @@
---
description: 为Go强制执行TDD工作流程。首先编写表驱动测试然后实现。使用go test -cover验证80%以上的覆盖率。
---
# Go TDD 命令
此命令使用惯用的 Go 测试模式,为 Go 代码强制执行测试驱动开发方法。
## 此命令的作用
1. **定义类型/接口**:首先搭建函数签名
2. **编写表驱动测试**创建全面的测试用例RED 阶段)
3. **运行测试**:验证测试因正确原因而失败
4. **实现代码**编写最少的代码以通过测试GREEN 阶段)
5. **重构**:改进代码,同时保持测试通过
6. **检查覆盖率**:确保 80% 以上的覆盖率
## 何时使用
在以下情况下使用 `/go-test`
* 实现新的 Go 函数时
* 为现有代码添加测试覆盖率时
* 修复 bug 时(先编写失败的测试)
* 构建关键业务逻辑时
* 学习 Go 中的 TDD 工作流程时
## TDD 循环
```
RED → Write failing table-driven test
GREEN → Implement minimal code to pass
REFACTOR → Improve code, tests stay green
REPEAT → Next test case
```
## 示例会话
````
User: /go-test I need a function to validate email addresses
Agent:
# TDD Session: Email Validator
## Step 1: Define Interface
```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.
func ValidateEmail(email string) error {
panic("not implemented")
}
```
## Step 2: Write Table-Driven Tests (RED)
```go
// validator/email_test.go
package validator
import (
"testing"
)
func TestValidateEmail(t *testing.T) {
tests := []struct {
name string
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},
{"no local part", "@example.com", true},
{"double at", "user@@example.com", true},
{"spaces", "user @example.com", true},
{"no tld", "user@example", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateEmail(tt.email)
if tt.wantErr && err == nil {
t.Errorf("ValidateEmail(%q) = nil; want error", tt.email)
}
if !tt.wantErr && err != nil {
t.Errorf("ValidateEmail(%q) = %v; want nil", tt.email, err)
}
})
}
}
```
## Step 3: Run Tests - Verify FAIL
```bash
$ go test ./validator/...
--- FAIL: TestValidateEmail (0.00s)
--- FAIL: TestValidateEmail/simple_email (0.00s)
panic: not implemented
FAIL
```
✓ Tests fail as expected (panic).
## Step 4: Implement Minimal Code (GREEN)
```go
// validator/email.go
package validator
import (
"errors"
"regexp"
)
var emailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
var (
ErrEmailEmpty = errors.New("email cannot be empty")
ErrEmailInvalid = errors.New("email format is invalid")
)
func ValidateEmail(email string) error {
if email == "" {
return ErrEmailEmpty
}
if !emailRegex.MatchString(email) {
return ErrEmailInvalid
}
return nil
}
```
## Step 5: Run Tests - Verify PASS
```bash
$ go test ./validator/...
PASS
ok project/validator 0.003s
```
✓ All tests passing!
## Step 6: Check Coverage
```bash
$ go test -cover ./validator/...
PASS
coverage: 100.0% of statements
ok project/validator 0.003s
```
✓ Coverage: 100%
## TDD Complete!
````
## 测试模式
### 表驱动测试
```go
tests := []struct {
name string
input InputType
want OutputType
wantErr bool
}{
{"case 1", input1, want1, false},
{"case 2", input2, want2, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Function(tt.input)
// assertions
})
}
```
### 并行测试
```go
for _, tt := range tests {
tt := tt // Capture
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
// test body
})
}
```
### 测试辅助函数
```go
func setupTestDB(t *testing.T) *sql.DB {
t.Helper()
db := createDB()
t.Cleanup(func() { db.Close() })
return db
}
```
## 覆盖率命令
```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 ./...
```
## 覆盖率目标
| 代码类型 | 目标 |
|-----------|--------|
| 关键业务逻辑 | 100% |
| 公共 API | 90%+ |
| 通用代码 | 80%+ |
| 生成的代码 | 排除 |
## TDD 最佳实践
**应该做:**
* 先编写测试,再编写任何实现
* 每次更改后运行测试
* 使用表驱动测试以获得全面的覆盖率
* 测试行为,而非实现细节
* 包含边界情况空值、nil、最大值
**不应该做:**
* 在编写测试之前编写实现
* 跳过 RED 阶段
* 直接测试私有函数
* 在测试中使用 `time.Sleep`
* 忽略不稳定的测试
## 相关命令
* `/go-build` - 修复构建错误
* `/go-review` - 在实现后审查代码
* `/verify` - 运行完整的验证循环
## 相关
* 技能:`skills/golang-testing/`
* 技能:`skills/tdd-workflow/`

View File

@@ -0,0 +1,94 @@
---
name: instinct-export
description: 导出本能,与团队成员或其他项目共享
command: /instinct-export
---
# 本能导出命令
将本能导出为可共享的格式。非常适合:
* 与团队成员分享
* 转移到新机器
* 贡献给项目约定
## 用法
```
/instinct-export # Export all personal instincts
/instinct-export --domain testing # Export only testing instincts
/instinct-export --min-confidence 0.7 # Only export high-confidence instincts
/instinct-export --output team-instincts.yaml
```
## 操作步骤
1.`~/.claude/homunculus/instincts/personal/` 读取本能
2. 根据标志进行筛选
3. 剥离敏感信息:
* 移除会话 ID
* 移除文件路径(仅保留模式)
* 移除早于“上周”的时间戳
4. 生成导出文件
## 输出格式
创建一个 YAML 文件:
```yaml
# Instincts Export
# Generated: 2025-01-22
# Source: personal
# Count: 12 instincts
version: "2.0"
exported_by: "continuous-learning-v2"
export_date: "2025-01-22T10:30:00Z"
instincts:
- id: prefer-functional-style
trigger: "when writing new functions"
action: "Use functional patterns over classes"
confidence: 0.8
domain: code-style
observations: 8
- id: test-first-workflow
trigger: "when adding new functionality"
action: "Write test first, then implementation"
confidence: 0.9
domain: testing
observations: 12
- id: grep-before-edit
trigger: "when modifying code"
action: "Search with Grep, confirm with Read, then Edit"
confidence: 0.7
domain: workflow
observations: 6
```
## 隐私考虑
导出内容包括:
* ✅ 触发模式
* ✅ 操作
* ✅ 置信度分数
* ✅ 领域
* ✅ 观察计数
导出内容不包括:
* ❌ 实际代码片段
* ❌ 文件路径
* ❌ 会话记录
* ❌ 个人标识符
## 标志
* `--domain <name>`:仅导出指定领域
* `--min-confidence <n>`最低置信度阈值默认0.3
* `--output <file>`输出文件路径默认instincts-export-YYYYMMDD.yaml
* `--format <yaml|json|md>`输出格式默认yaml
* `--include-evidence`:包含证据文本(默认:排除)

View File

@@ -0,0 +1,150 @@
---
name: instinct-import
description: 从队友、技能创建者或其他来源导入本能
command: true
---
# 本能导入命令
## 实现
使用插件根路径运行本能 CLI
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/skills/continuous-learning-v2/scripts/instinct-cli.py" import <file-or-url> [--dry-run] [--force] [--min-confidence 0.7]
```
或者,如果 `CLAUDE_PLUGIN_ROOT` 未设置(手动安装):
```bash
python3 ~/.claude/skills/continuous-learning-v2/scripts/instinct-cli.py import <file-or-url>
```
从以下来源导入本能:
* 队友的导出
* 技能创建器(仓库分析)
* 社区集合
* 之前的机器备份
## 用法
```
/instinct-import team-instincts.yaml
/instinct-import https://github.com/org/repo/instincts.yaml
/instinct-import --from-skill-creator acme/webapp
```
## 执行步骤
1. 获取本能文件(本地路径或 URL
2. 解析并验证格式
3. 检查与现有本能的重复项
4. 合并或添加新本能
5. 保存到 `~/.claude/homunculus/instincts/inherited/`
## 导入过程
```
📥 Importing instincts from: team-instincts.yaml
================================================
Found 12 instincts to import.
Analyzing conflicts...
## New Instincts (8)
These will be added:
✓ use-zod-validation (confidence: 0.7)
✓ prefer-named-exports (confidence: 0.65)
✓ test-async-functions (confidence: 0.8)
...
## Duplicate Instincts (3)
Already have similar instincts:
⚠️ prefer-functional-style
Local: 0.8 confidence, 12 observations
Import: 0.7 confidence
→ Keep local (higher confidence)
⚠️ test-first-workflow
Local: 0.75 confidence
Import: 0.9 confidence
→ Update to import (higher confidence)
## Conflicting Instincts (1)
These contradict local instincts:
❌ use-classes-for-services
Conflicts with: avoid-classes
→ Skip (requires manual resolution)
---
Import 8 new, update 1, skip 3?
```
## 合并策略
### 针对重复项
当导入一个与现有本能匹配的本能时:
* **置信度高的胜出**:保留置信度更高的那个
* **合并证据**:合并观察计数
* **更新时间戳**:标记为最近已验证
### 针对冲突
当导入一个与现有本能相矛盾的本能时:
* **默认跳过**:不导入冲突的本能
* **标记待审**:将两者都标记为需要注意
* **手动解决**:由用户决定保留哪个
## 来源追踪
导入的本能被标记为:
```yaml
source: "inherited"
imported_from: "team-instincts.yaml"
imported_at: "2025-01-22T10:30:00Z"
original_source: "session-observation" # or "repo-analysis"
```
## 技能创建器集成
从技能创建器导入时:
```
/instinct-import --from-skill-creator acme/webapp
```
这会获取从仓库分析生成的本能:
* 来源:`repo-analysis`
* 更高的初始置信度0.7+
* 链接到源仓库
## 标志
* `--dry-run`:预览而不导入
* `--force`:即使存在冲突也导入
* `--merge-strategy <higher|local|import>`:如何处理重复项
* `--from-skill-creator <owner/repo>`:从技能创建器分析导入
* `--min-confidence <n>`:仅导入高于阈值的本能
## 输出
导入后:
```
✅ Import complete!
Added: 8 instincts
Updated: 1 instinct
Skipped: 3 instincts (2 duplicates, 1 conflict)
New instincts saved to: ~/.claude/homunculus/instincts/inherited/
Run /instinct-status to see all instincts.
```

View File

@@ -0,0 +1,86 @@
---
name: instinct-status
description: 显示所有已学习的本能及其置信水平
command: true
---
# 本能状态命令
显示所有已学习的本能及其置信度分数,按领域分组。
## 实现
使用插件根路径运行本能 CLI
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/skills/continuous-learning-v2/scripts/instinct-cli.py" status
```
或者,如果未设置 `CLAUDE_PLUGIN_ROOT`(手动安装),则使用:
```bash
python3 ~/.claude/skills/continuous-learning-v2/scripts/instinct-cli.py status
```
## 用法
```
/instinct-status
/instinct-status --domain code-style
/instinct-status --low-confidence
```
## 操作步骤
1.`~/.claude/homunculus/instincts/personal/` 读取所有本能文件
2.`~/.claude/homunculus/instincts/inherited/` 读取继承的本能
3. 按领域分组显示它们,并带有置信度条
## 输出格式
```
📊 Instinct Status
==================
## Code Style (4 instincts)
### prefer-functional-style
Trigger: when writing new functions
Action: Use functional patterns over classes
Confidence: ████████░░ 80%
Source: session-observation | Last updated: 2025-01-22
### use-path-aliases
Trigger: when importing modules
Action: Use @/ path aliases instead of relative imports
Confidence: ██████░░░░ 60%
Source: repo-analysis (github.com/acme/webapp)
## Testing (2 instincts)
### test-first-workflow
Trigger: when adding new functionality
Action: Write test first, then implementation
Confidence: █████████░ 90%
Source: session-observation
## Workflow (3 instincts)
### grep-before-edit
Trigger: when modifying code
Action: Search with Grep, confirm with Read, then Edit
Confidence: ███████░░░ 70%
Source: session-observation
---
Total: 9 instincts (4 personal, 5 inherited)
Observer: Running (last analysis: 5 min ago)
```
## 标志
* `--domain <name>`按领域过滤code-style、testing、git 等)
* `--low-confidence`:仅显示置信度 < 0.5 的本能
* `--high-confidence`:仅显示置信度 >= 0.7 的本能
* `--source <type>`按来源过滤session-observation、repo-analysis、inherited
* `--json`:以 JSON 格式输出,供编程使用

View File

@@ -0,0 +1,70 @@
# /learn - 提取可重用模式
分析当前会话,提取值得保存为技能的任何模式。
## 触发时机
在会话期间的任何时刻,当你解决了一个非平凡问题时,运行 `/learn`
## 提取内容
寻找:
1. **错误解决模式**
* 出现了什么错误?
* 根本原因是什么?
* 什么方法修复了它?
* 这对解决类似错误是否可重用?
2. **调试技术**
* 不明显的调试步骤
* 有效的工具组合
* 诊断模式
3. **变通方法**
* 库的怪癖
* API 限制
* 特定版本的修复
4. **项目特定模式**
* 发现的代码库约定
* 做出的架构决策
* 集成模式
## 输出格式
`~/.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]
```
## 流程
1. 回顾会话,寻找可提取的模式
2. 识别最有价值/可重用的见解
3. 起草技能文件
4. 在保存前请用户确认
5. 保存到 `~/.claude/skills/learned/`
## 注意事项
* 不要提取琐碎的修复(拼写错误、简单的语法错误)
* 不要提取一次性问题(特定的 API 中断等)
* 专注于那些将在未来会话中节省时间的模式
* 保持技能的专注性 - 一个技能对应一个模式

View File

@@ -0,0 +1,162 @@
# 后端 - 后端导向开发
后端导向的工作流程(研究 → 构思 → 规划 → 执行 → 优化 → 评审),由 Codex 主导。
## 使用方法
```bash
/backend <backend task description>
```
## 上下文
* 后端任务:$ARGUMENTS
* Codex 主导Gemini 作为辅助参考
* 适用场景API 设计、算法实现、数据库优化、业务逻辑
## 你的角色
你是 **后端协调者**,为服务器端任务协调多模型协作(研究 → 构思 → 规划 → 执行 → 优化 → 评审)。
**协作模型**
* **Codex** 后端逻辑、算法(**后端权威,可信赖**
* **Gemini** 前端视角(**后端意见仅供参考**
* **Claude (自身)** 协调、规划、执行、交付
***
## 多模型调用规范
**调用语法**
```
# New session call
Bash({
command: "~/.claude/bin/codeagent-wrapper {{LITE_MODE_FLAG}}--backend codex - \"$PWD\" <<'EOF'
ROLE_FILE: <role prompt path>
<TASK>
Requirement: <enhanced requirement (or $ARGUMENTS if not enhanced)>
Context: <project context and analysis from previous phases>
</TASK>
OUTPUT: Expected output format
EOF",
run_in_background: false,
timeout: 3600000,
description: "Brief description"
})
# Resume session call
Bash({
command: "~/.claude/bin/codeagent-wrapper {{LITE_MODE_FLAG}}--backend codex resume <SESSION_ID> - \"$PWD\" <<'EOF'
ROLE_FILE: <role prompt path>
<TASK>
Requirement: <enhanced requirement (or $ARGUMENTS if not enhanced)>
Context: <project context and analysis from previous phases>
</TASK>
OUTPUT: Expected output format
EOF",
run_in_background: false,
timeout: 3600000,
description: "Brief description"
})
```
**角色提示词**
| 阶段 | Codex |
|-------|-------|
| 分析 | `~/.claude/.ccg/prompts/codex/analyzer.md` |
| 规划 | `~/.claude/.ccg/prompts/codex/architect.md` |
| 评审 | `~/.claude/.ccg/prompts/codex/reviewer.md` |
**会话复用**:每次调用返回 `SESSION_ID: xxx`,在后续阶段使用 `resume xxx`。在第 2 阶段保存 `CODEX_SESSION`,在第 3 和第 5 阶段使用 `resume`
***
## 沟通准则
1. 在回复开头使用模式标签 `[Mode: X]`,初始值为 `[Mode: Research]`
2. 遵循严格序列:`Research → Ideation → Plan → Execute → Optimize → Review`
3. 需要时(例如确认/选择/批准)使用 `AskUserQuestion` 工具进行用户交互
***
## 核心工作流程
### 阶段 0提示词增强可选
`[Mode: Prepare]` - 如果 ace-tool MCP 可用,调用 `mcp__ace-tool__enhance_prompt`**用增强后的结果替换原始的 $ARGUMENTS用于后续的 Codex 调用**
### 阶段 1研究
`[Mode: Research]` - 理解需求并收集上下文
1. **代码检索**(如果 ace-tool MCP 可用):调用 `mcp__ace-tool__search_context` 以检索现有的 API、数据模型、服务架构
2. 需求完整性评分0-10>=7 继续,<7 停止并补充
### 阶段 2构思
`[Mode: Ideation]` - Codex 主导的分析
**必须调用 Codex**(遵循上述调用规范):
* ROLE\_FILE`~/.claude/.ccg/prompts/codex/analyzer.md`
* 需求:增强后的需求(或未增强时的 $ARGUMENTS
* 上下文:来自阶段 1 的项目上下文
* 输出:技术可行性分析、推荐解决方案(至少 2 个)、风险评估
**保存 SESSION\_ID**`CODEX_SESSION`)以供后续阶段复用。
输出解决方案(至少 2 个),等待用户选择。
### 阶段 3规划
`[Mode: Plan]` - Codex 主导的规划
**必须调用 Codex**(使用 `resume <CODEX_SESSION>` 以复用会话):
* ROLE\_FILE`~/.claude/.ccg/prompts/codex/architect.md`
* 需求:用户选择的解决方案
* 上下文:阶段 2 的分析结果
* 输出:文件结构、函数/类设计、依赖关系
Claude 综合规划,在用户批准后保存到 `.claude/plan/task-name.md`
### 阶段 4实施
`[Mode: Execute]` - 代码开发
* 严格遵循已批准的规划
* 遵循现有项目的代码规范
* 确保错误处理、安全性、性能优化
### 阶段 5优化
`[Mode: Optimize]` - Codex 主导的评审
**必须调用 Codex**(遵循上述调用规范):
* ROLE\_FILE`~/.claude/.ccg/prompts/codex/reviewer.md`
* 需求:评审以下后端代码变更
* 上下文git diff 或代码内容
* 输出安全性、性能、错误处理、API 合规性问题列表
整合评审反馈,在用户确认后执行优化。
### 阶段 6质量评审
`[Mode: Review]` - 最终评估
* 对照规划检查完成情况
* 运行测试以验证功能
* 报告问题和建议
***
## 关键规则
1. **Codex 的后端意见是可信赖的**
2. **Gemini 的后端意见仅供参考**
3. 外部模型**对文件系统零写入权限**
4. Claude 处理所有代码写入和文件操作

View File

@@ -0,0 +1,315 @@
# 执行 - 多模型协同执行
多模型协同执行 - 从计划获取原型 → Claude 重构并实施 → 多模型审计与交付。
$ARGUMENTS
***
## 核心协议
* **语言协议**:与工具/模型交互时使用**英语**,与用户沟通时使用用户的语言
* **代码主权**:外部模型**零文件系统写入权限**,所有修改由 Claude 执行
* **脏原型重构**:将 Codex/Gemini 统一差异视为“脏原型”,必须重构为生产级代码
* **止损机制**:当前阶段输出未经验证前,不得进入下一阶段
* **前提条件**仅在用户明确回复“Y”到 `/ccg:plan` 输出后执行(如果缺失,必须先确认)
***
## 多模型调用规范
**调用语法**(并行:使用 `run_in_background: true`
```
# Resume session call (recommended) - Implementation Prototype
Bash({
command: "~/.claude/bin/codeagent-wrapper {{LITE_MODE_FLAG}}--backend <codex|gemini> {{GEMINI_MODEL_FLAG}}resume <SESSION_ID> - \"$PWD\" <<'EOF'
ROLE_FILE: <role prompt path>
<TASK>
Requirement: <task description>
Context: <plan content + target files>
</TASK>
OUTPUT: Unified Diff Patch ONLY. Strictly prohibit any actual modifications.
EOF",
run_in_background: true,
timeout: 3600000,
description: "Brief description"
})
# New session call - Implementation Prototype
Bash({
command: "~/.claude/bin/codeagent-wrapper {{LITE_MODE_FLAG}}--backend <codex|gemini> {{GEMINI_MODEL_FLAG}}- \"$PWD\" <<'EOF'
ROLE_FILE: <role prompt path>
<TASK>
Requirement: <task description>
Context: <plan content + target files>
</TASK>
OUTPUT: Unified Diff Patch ONLY. Strictly prohibit any actual modifications.
EOF",
run_in_background: true,
timeout: 3600000,
description: "Brief description"
})
```
**审计调用语法**(代码审查 / 审计):
```
Bash({
command: "~/.claude/bin/codeagent-wrapper {{LITE_MODE_FLAG}}--backend <codex|gemini> {{GEMINI_MODEL_FLAG}}resume <SESSION_ID> - \"$PWD\" <<'EOF'
ROLE_FILE: <role prompt path>
<TASK>
Scope: Audit the final code changes.
Inputs:
- The applied patch (git diff / final unified diff)
- The touched files (relevant excerpts if needed)
Constraints:
- Do NOT modify any files.
- Do NOT output tool commands that assume filesystem access.
</TASK>
OUTPUT:
1) A prioritized list of issues (severity, file, rationale)
2) Concrete fixes; if code changes are needed, include a Unified Diff Patch in a fenced code block.
EOF",
run_in_background: true,
timeout: 3600000,
description: "Brief description"
})
```
**模型参数说明**
* `{{GEMINI_MODEL_FLAG}}`:当使用 `--backend gemini` 时,替换为 `--gemini-model gemini-3-pro-preview`(注意尾随空格);对于 codex 使用空字符串
**角色提示**
| 阶段 | Codex | Gemini |
|-------|-------|--------|
| 实施 | `~/.claude/.ccg/prompts/codex/architect.md` | `~/.claude/.ccg/prompts/gemini/frontend.md` |
| 审查 | `~/.claude/.ccg/prompts/codex/reviewer.md` | `~/.claude/.ccg/prompts/gemini/reviewer.md` |
**会话重用**:如果 `/ccg:plan` 提供了 SESSION\_ID使用 `resume <SESSION_ID>` 来重用上下文。
**等待后台任务**(最大超时 600000ms = 10 分钟):
```
TaskOutput({ task_id: "<task_id>", block: true, timeout: 600000 })
```
**重要**
* 必须指定 `timeout: 600000`,否则默认 30 秒会导致过早超时
* 如果 10 分钟后仍未完成,继续使用 `TaskOutput` 轮询,**切勿终止进程**
* 如果因超时而跳过等待,**必须调用 `AskUserQuestion` 询问用户是继续等待还是终止任务**
***
## 执行工作流
**执行任务**$ARGUMENTS
### 阶段 0读取计划
`[Mode: Prepare]`
1. **识别输入类型**
* 计划文件路径(例如 `.claude/plan/xxx.md`
* 直接任务描述
2. **读取计划内容**
* 如果提供了计划文件路径,读取并解析
* 提取任务类型、实施步骤、关键文件、SESSION\_ID
3. **执行前确认**
* 如果输入是“直接任务描述”或计划缺少 `SESSION_ID` / 关键文件:先与用户确认
* 如果无法确认用户已回复“Y”到计划在继续前必须再次确认
4. **任务类型路由**
| 任务类型 | 检测 | 路由 |
|-----------|-----------|-------|
| **前端** | 页面、组件、UI、样式、布局 | Gemini |
| **后端** | API、接口、数据库、逻辑、算法 | Codex |
| **全栈** | 包含前端和后端 | Codex ∥ Gemini 并行 |
***
### 阶段 1快速上下文检索
`[Mode: Retrieval]`
**必须使用 MCP 工具进行快速上下文检索,切勿手动逐个读取文件**
基于计划中的“关键文件”列表,调用 `mcp__ace-tool__search_context`
```
mcp__ace-tool__search_context({
query: "<semantic query based on plan content, including key files, modules, function names>",
project_root_path: "$PWD"
})
```
**检索策略**
* 从计划的“关键文件”表中提取目标路径
* 构建语义查询覆盖:入口文件、依赖模块、相关类型定义
* 如果结果不足,添加 1-2 次递归检索
* **切勿**使用 Bash + find/ls 手动探索项目结构
**检索后**
* 组织检索到的代码片段
* 确认实施所需的完整上下文
* 进入阶段 3
***
### 阶段 3原型获取
`[Mode: Prototype]`
**基于任务类型路由**
#### 路由 A前端/UI/样式 → Gemini
**限制**:上下文 < 32k 令牌
1. 调用 Gemini使用 `~/.claude/.ccg/prompts/gemini/frontend.md`
2. 输入:计划内容 + 检索到的上下文 + 目标文件
3. 输出:`Unified Diff Patch ONLY. Strictly prohibit any actual modifications.`
4. **Gemini 是前端设计权威,其 CSS/React/Vue 原型是最终的视觉基线**
5. **警告**:忽略 Gemini 的后端逻辑建议
6. 如果计划包含 `GEMINI_SESSION`:优先使用 `resume <GEMINI_SESSION>`
#### 路由 B后端/逻辑/算法 → Codex
1. 调用 Codex使用 `~/.claude/.ccg/prompts/codex/architect.md`
2. 输入:计划内容 + 检索到的上下文 + 目标文件
3. 输出:`Unified Diff Patch ONLY. Strictly prohibit any actual modifications.`
4. **Codex 是后端逻辑权威,利用其逻辑推理和调试能力**
5. 如果计划包含 `CODEX_SESSION`:优先使用 `resume <CODEX_SESSION>`
#### 路由 C全栈 → 并行调用
1. **并行调用**`run_in_background: true`
* Gemini处理前端部分
* Codex处理后端部分
2. 使用 `TaskOutput` 等待两个模型的完整结果
3. 每个模型使用计划中相应的 `SESSION_ID` 作为 `resume`(如果缺失则创建新会话)
**遵循上面 `IMPORTANT` 中的 `Multi-Model Call Specification` 指令**
***
### 阶段 4代码实施
`[Mode: Implement]`
**Claude 作为代码主权执行以下步骤**
1. **读取差异**:解析 Codex/Gemini 返回的统一差异补丁
2. **心智沙盒**
* 模拟将差异应用到目标文件
* 检查逻辑一致性
* 识别潜在冲突或副作用
3. **重构与清理**
* 将“脏原型”重构为**高度可读、可维护、企业级代码**
* 移除冗余代码
* 确保符合项目现有代码标准
* **除非必要,不要生成注释/文档**,代码应具有自解释性
4. **最小范围**
* 更改仅限于需求范围
* **强制审查**副作用
* 进行针对性修正
5. **应用更改**
* 使用编辑/写入工具执行实际修改
* **仅修改必要代码**,绝不影响用户的其他现有功能
6. **自验证**(强烈推荐):
* 运行项目现有的 lint / 类型检查 / 测试(优先考虑最小相关范围)
* 如果失败:先修复回归问题,然后进入阶段 5
***
### 阶段 5审计与交付
`[Mode: Audit]`
#### 5.1 自动审计
**更改生效后,必须立即并行调用** Codex 和 Gemini 进行代码审查:
1. **Codex 审查**`run_in_background: true`
* ROLE\_FILE`~/.claude/.ccg/prompts/codex/reviewer.md`
* 输入:更改的差异 + 目标文件
* 重点:安全性、性能、错误处理、逻辑正确性
2. **Gemini 审查**`run_in_background: true`
* ROLE\_FILE`~/.claude/.ccg/prompts/gemini/reviewer.md`
* 输入:更改的差异 + 目标文件
* 重点:可访问性、设计一致性、用户体验
使用 `TaskOutput` 等待两个模型的完整审查结果。优先重用阶段 3 的会话(`resume <SESSION_ID>`)以确保上下文一致性。
#### 5.2 整合与修复
1. 综合 Codex + Gemini 的审查反馈
2. 按信任规则权衡:后端遵循 Codex前端遵循 Gemini
3. 执行必要的修复
4. 根据需要重复阶段 5.1(直到风险可接受)
#### 5.3 交付确认
审计通过后,向用户报告:
```markdown
## 执行完成
### 变更摘要
| 文件 | 操作 | 描述 |
|------|-----------|-------------|
| path/to/file.ts | 已修改 | 描述 |
### 审计结果
- Codex: <通过/发现 N 个问题>
- Gemini: <通过/发现 N 个问题>
### 建议
1. [ ] <建议的测试步骤>
2. [ ] <建议的验证步骤>
```
***
## 关键规则
1. **代码主权** 所有文件修改由 Claude 执行,外部模型零写入权限
2. **脏原型重构** Codex/Gemini 输出视为草稿,必须重构
3. **信任规则** 后端遵循 Codex前端遵循 Gemini
4. **最小更改** 仅修改必要代码,无副作用
5. **强制审计** 更改后必须执行多模型代码审查
***
## 使用方法
```bash
# Execute plan file
/ccg:execute .claude/plan/feature-name.md
# Execute task directly (for plans already discussed in context)
/ccg:execute implement user authentication based on previous plan
```
***
## 与 /ccg:plan 的关系
1. `/ccg:plan` 生成计划 + SESSION\_ID
2. 用户用“Y”确认
3. `/ccg:execute` 读取计划,重用 SESSION\_ID执行实施

View File

@@ -0,0 +1,162 @@
# 前端 - 前端聚焦开发
前端聚焦的工作流(研究 → 构思 → 规划 → 执行 → 优化 → 评审),由 Gemini 主导。
## 使用方法
```bash
/frontend <UI task description>
```
## 上下文
* 前端任务: $ARGUMENTS
* Gemini 主导Codex 作为辅助参考
* 适用场景: 组件设计、响应式布局、UI 动画、样式优化
## 您的角色
您是 **前端协调器**,为 UI/UX 任务协调多模型协作(研究 → 构思 → 规划 → 执行 → 优化 → 评审)。
**协作模型**:
* **Gemini** 前端 UI/UX**前端权威,可信赖**
* **Codex** 后端视角(**前端意见仅供参考**
* **Claude自身** 协调、规划、执行、交付
***
## 多模型调用规范
**调用语法**:
```
# New session call
Bash({
command: "~/.claude/bin/codeagent-wrapper {{LITE_MODE_FLAG}}--backend gemini --gemini-model gemini-3-pro-preview - \"$PWD\" <<'EOF'
ROLE_FILE: <role prompt path>
<TASK>
Requirement: <enhanced requirement (or $ARGUMENTS if not enhanced)>
Context: <project context and analysis from previous phases>
</TASK>
OUTPUT: Expected output format
EOF",
run_in_background: false,
timeout: 3600000,
description: "Brief description"
})
# Resume session call
Bash({
command: "~/.claude/bin/codeagent-wrapper {{LITE_MODE_FLAG}}--backend gemini --gemini-model gemini-3-pro-preview resume <SESSION_ID> - \"$PWD\" <<'EOF'
ROLE_FILE: <role prompt path>
<TASK>
Requirement: <enhanced requirement (or $ARGUMENTS if not enhanced)>
Context: <project context and analysis from previous phases>
</TASK>
OUTPUT: Expected output format
EOF",
run_in_background: false,
timeout: 3600000,
description: "Brief description"
})
```
**角色提示词**:
| 阶段 | Gemini |
|-------|--------|
| 分析 | `~/.claude/.ccg/prompts/gemini/analyzer.md` |
| 规划 | `~/.claude/.ccg/prompts/gemini/architect.md` |
| 评审 | `~/.claude/.ccg/prompts/gemini/reviewer.md` |
**会话重用**: 每次调用返回 `SESSION_ID: xxx`,在后续阶段使用 `resume xxx`。在阶段 2 保存 `GEMINI_SESSION`,在阶段 3 和 5 使用 `resume`
***
## 沟通指南
1. 以模式标签 `[Mode: X]` 开始响应,初始为 `[Mode: Research]`
2. 遵循严格顺序: `Research → Ideation → Plan → Execute → Optimize → Review`
3. 需要时(例如确认/选择/批准)使用 `AskUserQuestion` 工具进行用户交互
***
## 核心工作流
### 阶段 0: 提示词增强(可选)
`[Mode: Prepare]` - 如果 ace-tool MCP 可用,调用 `mcp__ace-tool__enhance_prompt`**将原始的 $ARGUMENTS 替换为增强后的结果,用于后续的 Gemini 调用**
### 阶段 1: 研究
`[Mode: Research]` - 理解需求并收集上下文
1. **代码检索**(如果 ace-tool MCP 可用): 调用 `mcp__ace-tool__search_context` 来检索现有的组件、样式、设计系统
2. 需求完整性评分0-10: >=7 继续,<7 停止并补充
### 阶段 2: 构思
`[Mode: Ideation]` - Gemini 主导的分析
**必须调用 Gemini**(遵循上述调用规范):
* ROLE\_FILE: `~/.claude/.ccg/prompts/gemini/analyzer.md`
* 需求: 增强后的需求(或未经增强的 $ARGUMENTS
* 上下文: 来自阶段 1 的项目上下文
* 输出: UI 可行性分析、推荐解决方案(至少 2 个、UX 评估
**保存 SESSION\_ID**`GEMINI_SESSION`)以供后续阶段重用。
输出解决方案(至少 2 个),等待用户选择。
### 阶段 3: 规划
`[Mode: Plan]` - Gemini 主导的规划
**必须调用 Gemini**(使用 `resume <GEMINI_SESSION>` 来重用会话):
* ROLE\_FILE: `~/.claude/.ccg/prompts/gemini/architect.md`
* 需求: 用户选择的解决方案
* 上下文: 阶段 2 的分析结果
* 输出: 组件结构、UI 流程、样式方案
Claude 综合规划,在用户批准后保存到 `.claude/plan/task-name.md`
### 阶段 4: 实现
`[Mode: Execute]` - 代码开发
* 严格遵循批准的规划
* 遵循现有项目设计系统和代码标准
* 确保响应式设计、可访问性
### 阶段 5: 优化
`[Mode: Optimize]` - Gemini 主导的评审
**必须调用 Gemini**(遵循上述调用规范):
* ROLE\_FILE: `~/.claude/.ccg/prompts/gemini/reviewer.md`
* 需求: 评审以下前端代码变更
* 上下文: git diff 或代码内容
* 输出: 可访问性、响应式设计、性能、设计一致性等问题列表
整合评审反馈,在用户确认后执行优化。
### 阶段 6: 质量评审
`[Mode: Review]` - 最终评估
* 对照规划检查完成情况
* 验证响应式设计和可访问性
* 报告问题与建议
***
## 关键规则
1. **Gemini 的前端意见是可信赖的**
2. **Codex 的前端意见仅供参考**
3. 外部模型**没有文件系统写入权限**
4. Claude 处理所有代码写入和文件操作

View File

@@ -0,0 +1,270 @@
# 计划 - 多模型协同规划
多模型协同规划 - 上下文检索 + 双模型分析 → 生成分步实施计划。
$ARGUMENTS
***
## 核心协议
* **语言协议**:与工具/模型交互时使用 **英语**,与用户沟通时使用其语言
* **强制并行**Codex/Gemini 调用 **必须** 使用 `run_in_background: true`(包括单模型调用,以避免阻塞主线程)
* **代码主权**:外部模型 **零文件系统写入权限**,所有修改由 Claude 执行
* **止损机制**:在当前阶段输出验证完成前,不进入下一阶段
* **仅限规划**:此命令允许读取上下文并写入 `.claude/plan/*` 计划文件,但 **绝不修改生产代码**
***
## 多模型调用规范
**调用语法**(并行:使用 `run_in_background: true`
```
Bash({
command: "~/.claude/bin/codeagent-wrapper {{LITE_MODE_FLAG}}--backend <codex|gemini> {{GEMINI_MODEL_FLAG}}- \"$PWD\" <<'EOF'
ROLE_FILE: <role prompt path>
<TASK>
Requirement: <enhanced requirement>
Context: <retrieved project context>
</TASK>
OUTPUT: Step-by-step implementation plan with pseudo-code. DO NOT modify any files.
EOF",
run_in_background: true,
timeout: 3600000,
description: "Brief description"
})
```
**模型参数说明**
* `{{GEMINI_MODEL_FLAG}}`: 当使用 `--backend gemini` 时,替换为 `--gemini-model gemini-3-pro-preview`(注意尾随空格);对于 codex 使用空字符串
**角色提示**
| 阶段 | Codex | Gemini |
|-------|-------|--------|
| 分析 | `~/.claude/.ccg/prompts/codex/analyzer.md` | `~/.claude/.ccg/prompts/gemini/analyzer.md` |
| 规划 | `~/.claude/.ccg/prompts/codex/architect.md` | `~/.claude/.ccg/prompts/gemini/architect.md` |
**会话复用**:每次调用返回 `SESSION_ID: xxx`(通常由包装器输出),**必须保存** 供后续 `/ccg:execute` 使用。
**等待后台任务**(最大超时 600000ms = 10 分钟):
```
TaskOutput({ task_id: "<task_id>", block: true, timeout: 600000 })
```
**重要提示**
* 必须指定 `timeout: 600000`,否则默认 30 秒会导致过早超时
* 如果 10 分钟后仍未完成,继续使用 `TaskOutput` 轮询,**绝不终止进程**
* 如果因超时而跳过等待,**必须调用 `AskUserQuestion` 询问用户是继续等待还是终止任务**
***
## 执行流程
**规划任务**$ARGUMENTS
### 阶段 1完整上下文检索
`[Mode: Research]`
#### 1.1 提示增强(必须先执行)
**必须调用 `mcp__ace-tool__enhance_prompt` 工具**
```
mcp__ace-tool__enhance_prompt({
prompt: "$ARGUMENTS",
conversation_history: "<last 5-10 conversation turns>",
project_root_path: "$PWD"
})
```
等待增强后的提示,**将所有后续阶段的原始 $ARGUMENTS 替换为增强结果**。
#### 1.2 上下文检索
**调用 `mcp__ace-tool__search_context` 工具**
```
mcp__ace-tool__search_context({
query: "<semantic query based on enhanced requirement>",
project_root_path: "$PWD"
})
```
* 使用自然语言构建语义查询Where/What/How
* **绝不基于假设回答**
* 如果 MCP 不可用:回退到 Glob + Grep 进行文件发现和关键符号定位
#### 1.3 完整性检查
* 必须获取相关类、函数、变量的 **完整定义和签名**
* 如果上下文不足,触发 **递归检索**
* 输出优先级:入口文件 + 行号 + 关键符号名称;仅在必要时添加最小代码片段以消除歧义
#### 1.4 需求对齐
* 如果需求仍有歧义,**必须** 输出引导性问题给用户
* 直到需求边界清晰(无遗漏,无冗余)
### 阶段 2多模型协同分析
`[Mode: Analysis]`
#### 2.1 分发输入
**并行调用** Codex 和 Gemini`run_in_background: true`
**原始需求**(不预设观点)分发给两个模型:
1. **Codex 后端分析**
* ROLE\_FILE`~/.claude/.ccg/prompts/codex/analyzer.md`
* 重点:技术可行性、架构影响、性能考虑、潜在风险
* 输出:多视角解决方案 + 优缺点分析
2. **Gemini 前端分析**
* ROLE\_FILE`~/.claude/.ccg/prompts/gemini/analyzer.md`
* 重点UI/UX 影响、用户体验、视觉设计
* 输出:多视角解决方案 + 优缺点分析
使用 `TaskOutput` 等待两个模型的完整结果。**保存 SESSION\_ID**`CODEX_SESSION``GEMINI_SESSION`)。
#### 2.2 交叉验证
整合视角并迭代优化:
1. **识别共识**(强信号)
2. **识别分歧**(需要权衡)
3. **互补优势**:后端逻辑遵循 Codex前端设计遵循 Gemini
4. **逻辑推理**:消除解决方案中的逻辑漏洞
#### 2.3(可选但推荐)双模型计划草案
为减少 Claude 综合计划中的遗漏风险,可以并行让两个模型输出“计划草案”(仍然 **不允许** 修改文件):
1. **Codex 计划草案**(后端权威):
* ROLE\_FILE`~/.claude/.ccg/prompts/codex/architect.md`
* 输出:分步计划 + 伪代码(重点:数据流/边缘情况/错误处理/测试策略)
2. **Gemini 计划草案**(前端权威):
* ROLE\_FILE`~/.claude/.ccg/prompts/gemini/architect.md`
* 输出:分步计划 + 伪代码(重点:信息架构/交互/可访问性/视觉一致性)
使用 `TaskOutput` 等待两个模型的完整结果,记录它们建议的关键差异。
#### 2.4 生成实施计划Claude 最终版本)
综合两个分析,生成 **分步实施计划**
```markdown
## 实施计划:<任务名称>
### 任务类型
- [ ] 前端 (→ Gemini)
- [ ] 后端 (→ Codex)
- [ ] 全栈 (→ 并行)
### 技术解决方案
<基于 Codex + Gemini 分析得出的最优解决方案>
### 实施步骤
1. <步骤 1> - 预期交付物
2. <步骤 2> - 预期交付物
...
### 关键文件
| 文件 | 操作 | 描述 |
|------|-----------|-------------|
| path/to/file.ts:L10-L50 | 修改 | 描述 |
### 风险与缓解措施
| 风险 | 缓解措施 |
|------|------------|
### SESSION_ID (供 /ccg:execute 使用)
- CODEX_SESSION: <session_id>
- GEMINI_SESSION: <session_id>
```
### 阶段 2 结束:计划交付(非执行)
**`/ccg:plan` 的职责到此结束,必须执行以下操作**
1. 向用户呈现完整的实施计划(包括伪代码)
2. 将计划保存到 `.claude/plan/<feature-name>.md`(从需求中提取功能名称,例如 `user-auth``payment-module`
3.**粗体文本** 输出提示(必须使用实际保存的文件路径):
***
**计划已生成并保存至 `.claude/plan/actual-feature-name.md`**
**请审阅以上计划。您可以:**
* **修改计划**:告诉我需要调整的内容,我会更新计划
* **执行计划**:复制以下命令到新会话
```
/ccg:execute .claude/plan/actual-feature-name.md
```
***
**注意**:上面的 `actual-feature-name.md` 必须替换为实际保存的文件名!
4. **立即终止当前响应**(在此停止。不再进行工具调用。)
**绝对禁止**
* 询问用户“是/否”然后自动执行(执行是 `/ccg:execute` 的职责)
* 任何对生产代码的写入操作
* 自动调用 `/ccg:execute` 或任何实施操作
* 当用户未明确请求修改时继续触发模型调用
***
## 计划保存
规划完成后,将计划保存至:
* **首次规划**`.claude/plan/<feature-name>.md`
* **迭代版本**`.claude/plan/<feature-name>-v2.md``.claude/plan/<feature-name>-v3.md`...
计划文件写入应在向用户呈现计划前完成。
***
## 计划修改流程
如果用户请求修改计划:
1. 根据用户反馈调整计划内容
2. 更新 `.claude/plan/<feature-name>.md` 文件
3. 重新呈现修改后的计划
4. 提示用户再次审阅或执行
***
## 后续步骤
用户批准后,**手动** 执行:
```bash
/ccg:execute .claude/plan/<feature-name>.md
```
***
## 关键规则
1. **仅规划,不实施** 此命令不执行任何代码更改
2. **无是/否提示** 仅呈现计划,让用户决定后续步骤
3. **信任规则** 后端遵循 Codex前端遵循 Gemini
4. 外部模型 **零文件系统写入权限**
5. **SESSION\_ID 交接** 计划末尾必须包含 `CODEX_SESSION` / `GEMINI_SESSION`(供 `/ccg:execute resume <SESSION_ID>` 使用)

View File

@@ -0,0 +1,189 @@
# 工作流程 - 多模型协同开发
多模型协同开发工作流程(研究 → 构思 → 规划 → 执行 → 优化 → 审查),带有智能路由:前端 → Gemini后端 → Codex。
结构化开发工作流程包含质量门控、MCP 服务和多模型协作。
## 使用方法
```bash
/workflow <task description>
```
## 上下文
* 待开发任务:$ARGUMENTS
* 结构化的 6 阶段工作流程,包含质量门控
* 多模型协作Codex后端 + Gemini前端 + Claude编排
* MCP 服务集成ace-tool以增强能力
## 你的角色
你是**编排者**,协调一个多模型协作系统(研究 → 构思 → 规划 → 执行 → 优化 → 审查)。为有经验的开发者进行简洁、专业的沟通。
**协作模型**
* **ace-tool MCP** 代码检索 + 提示词增强
* **Codex** 后端逻辑、算法、调试(**后端权威,可信赖**
* **Gemini** 前端 UI/UX、视觉设计**前端专家,后端意见仅供参考**
* **Claude自身** 编排、规划、执行、交付
***
## 多模型调用规范
**调用语法**(并行:`run_in_background: true`,串行:`false`
```
# New session call
Bash({
command: "~/.claude/bin/codeagent-wrapper {{LITE_MODE_FLAG}}--backend <codex|gemini> {{GEMINI_MODEL_FLAG}}- \"$PWD\" <<'EOF'
ROLE_FILE: <role prompt path>
<TASK>
Requirement: <enhanced requirement (or $ARGUMENTS if not enhanced)>
Context: <project context and analysis from previous phases>
</TASK>
OUTPUT: Expected output format
EOF",
run_in_background: true,
timeout: 3600000,
description: "Brief description"
})
# Resume session call
Bash({
command: "~/.claude/bin/codeagent-wrapper {{LITE_MODE_FLAG}}--backend <codex|gemini> {{GEMINI_MODEL_FLAG}}resume <SESSION_ID> - \"$PWD\" <<'EOF'
ROLE_FILE: <role prompt path>
<TASK>
Requirement: <enhanced requirement (or $ARGUMENTS if not enhanced)>
Context: <project context and analysis from previous phases>
</TASK>
OUTPUT: Expected output format
EOF",
run_in_background: true,
timeout: 3600000,
description: "Brief description"
})
```
**模型参数说明**
* `{{GEMINI_MODEL_FLAG}}`: 当使用 `--backend gemini` 时,替换为 `--gemini-model gemini-3-pro-preview`(注意末尾空格);对于 codex 使用空字符串
**角色提示词**
| 阶段 | Codex | Gemini |
|-------|-------|--------|
| 分析 | `~/.claude/.ccg/prompts/codex/analyzer.md` | `~/.claude/.ccg/prompts/gemini/analyzer.md` |
| 规划 | `~/.claude/.ccg/prompts/codex/architect.md` | `~/.claude/.ccg/prompts/gemini/architect.md` |
| 审查 | `~/.claude/.ccg/prompts/codex/reviewer.md` | `~/.claude/.ccg/prompts/gemini/reviewer.md` |
**会话复用**:每次调用返回 `SESSION_ID: xxx`,在后续阶段使用 `resume xxx` 子命令(注意:`resume`,而非 `--resume`)。
**并行调用**:使用 `run_in_background: true` 启动,使用 `TaskOutput` 等待结果。**必须等待所有模型返回后才能进入下一阶段**。
**等待后台任务**(使用最大超时 600000ms = 10 分钟):
```
TaskOutput({ task_id: "<task_id>", block: true, timeout: 600000 })
```
**重要**
* 必须指定 `timeout: 600000`,否则默认 30 秒会导致过早超时。
* 如果 10 分钟后仍未完成,继续使用 `TaskOutput` 轮询,**切勿终止进程**。
* 如果因超时而跳过等待,**必须调用 `AskUserQuestion` 询问用户是继续等待还是终止任务。切勿直接终止。**
***
## 沟通指南
1. 回复以模式标签 `[Mode: X]` 开头,初始为 `[Mode: Research]`
2. 遵循严格顺序:`Research → Ideation → Plan → Execute → Optimize → Review`
3. 每个阶段完成后请求用户确认。
4. 当评分 < 7 或用户不批准时强制停止。
5. 需要时(例如确认/选择/批准)使用 `AskUserQuestion` 工具进行用户交互。
***
## 执行工作流程
**任务描述**$ARGUMENTS
### 阶段 1研究与分析
`[Mode: Research]` - 理解需求并收集上下文:
1. **提示词增强**:调用 `mcp__ace-tool__enhance_prompt`**将所有后续对 Codex/Gemini 的调用中的原始 $ARGUMENTS 替换为增强后的结果**
2. **上下文检索**:调用 `mcp__ace-tool__search_context`
3. **需求完整性评分** (0-10)
* 目标清晰度 (0-3),预期成果 (0-3),范围边界 (0-2),约束条件 (0-2)
* ≥7继续 | <7停止询问澄清问题
### 阶段 2解决方案构思
`[Mode: Ideation]` - 多模型并行分析:
**并行调用** (`run_in_background: true`)
* Codex使用分析器提示词输出技术可行性、解决方案、风险
* Gemini使用分析器提示词输出 UI 可行性、解决方案、UX 评估
使用 `TaskOutput` 等待结果。**保存 SESSION\_ID** (`CODEX_SESSION``GEMINI_SESSION`)。
**遵循上方 `Multi-Model Call Specification` 中的 `IMPORTANT` 说明**
综合两项分析,输出解决方案比较(至少 2 个选项),等待用户选择。
### 阶段 3详细规划
`[Mode: Plan]` - 多模型协作规划:
**并行调用**(使用 `resume <SESSION_ID>` 恢复会话):
* Codex使用架构师提示词 + `resume $CODEX_SESSION`,输出后端架构
* Gemini使用架构师提示词 + `resume $GEMINI_SESSION`,输出前端架构
使用 `TaskOutput` 等待结果。
**遵循上方 `Multi-Model Call Specification` 中的 `IMPORTANT` 说明**
**Claude 综合**:采纳 Codex 后端计划 + Gemini 前端计划,在用户批准后保存到 `.claude/plan/task-name.md`
### 阶段 4实施
`[Mode: Execute]` - 代码开发:
* 严格遵循批准的计划
* 遵循现有项目代码标准
* 在关键里程碑请求反馈
### 阶段 5代码优化
`[Mode: Optimize]` - 多模型并行审查:
**并行调用**
* Codex使用审查者提示词关注安全性、性能、错误处理
* Gemini使用审查者提示词关注可访问性、设计一致性
使用 `TaskOutput` 等待结果。整合审查反馈,在用户确认后执行优化。
**遵循上方 `Multi-Model Call Specification` 中的 `IMPORTANT` 说明**
### 阶段 6质量审查
`[Mode: Review]` - 最终评估:
* 对照计划检查完成情况
* 运行测试以验证功能
* 报告问题和建议
* 请求最终用户确认
***
## 关键规则
1. 阶段顺序不可跳过(除非用户明确指示)
2. 外部模型**对文件系统零写入权限**,所有修改由 Claude 执行
3. 当评分 < 7 或用户不批准时**强制停止**

View File

@@ -0,0 +1,183 @@
# 编排命令
用于复杂任务的顺序代理工作流。
## 使用
`/orchestrate [workflow-type] [task-description]`
## 工作流类型
### feature
完整功能实现工作流:
```
planner -> tdd-guide -> code-reviewer -> security-reviewer
```
### bugfix
错误调查与修复工作流:
```
planner -> tdd-guide -> code-reviewer
```
### refactor
安全重构工作流:
```
architect -> code-reviewer -> tdd-guide
```
### security
安全审查工作流:
```
security-reviewer -> code-reviewer -> architect
```
## 执行模式
针对工作流中的每个代理:
1. 使用来自上一个代理的上下文**调用代理**
2. 将输出收集为结构化的交接文档
3. 将文档**传递给链中的下一个代理**
4. 将结果**汇总**到最终报告中
## 交接文档格式
在代理之间,创建交接文档:
```markdown
## 交接:[前一位代理人] -> [下一位代理人]
### 背景
[已完成工作的总结]
### 发现
[关键发现或决定]
### 已修改的文件
[已触及的文件列表]
### 待解决的问题
[留给下一位代理人的未决事项]
### 建议
[建议的后续步骤]
```
## 示例:功能工作流
```
/orchestrate feature "Add user authentication"
```
执行:
1. **规划代理**
* 分析需求
* 创建实施计划
* 识别依赖项
* 输出:`HANDOFF: planner -> tdd-guide`
2. **TDD 指导代理**
* 读取规划交接文档
* 先编写测试
* 实施代码以通过测试
* 输出:`HANDOFF: tdd-guide -> code-reviewer`
3. **代码审查代理**
* 审查实现
* 检查问题
* 提出改进建议
* 输出:`HANDOFF: code-reviewer -> security-reviewer`
4. **安全审查代理**
* 安全审计
* 漏洞检查
* 最终批准
* 输出:最终报告
## 最终报告格式
```
ORCHESTRATION REPORT
====================
Workflow: feature
Task: Add user authentication
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]
FILES CHANGED
-------------
[List all files modified]
TEST RESULTS
------------
[Test pass/fail summary]
SECURITY STATUS
---------------
[Security findings]
RECOMMENDATION
--------------
[SHIP / NEEDS WORK / BLOCKED]
```
## 并行执行
对于独立的检查,并行运行代理:
```markdown
### 并行阶段
同时运行:
- code-reviewer质量
- security-reviewer安全
- architect设计
### 合并结果
将输出合并为单一报告
```
## 参数
$ARGUMENTS:
* `feature <description>` - 完整功能工作流
* `bugfix <description>` - 错误修复工作流
* `refactor <description>` - 重构工作流
* `security <description>` - 安全审查工作流
* `custom <agents> <description>` - 自定义代理序列
## 自定义工作流示例
```
/orchestrate custom "architect,tdd-guide,code-reviewer" "Redesign caching layer"
```
## 提示
1. **从规划代理开始**处理复杂功能
2. **始终在合并前包含代码审查代理**
3. 处理认证/支付/个人身份信息时**使用安全审查代理**
4. **保持交接文档简洁** - 关注下一个代理需要什么
5. 如有需要,**在代理之间运行验证**

115
docs/zh-CN/commands/plan.md Normal file
View File

@@ -0,0 +1,115 @@
---
description: 重新阐述需求、评估风险并创建分步实施计划。在接触任何代码之前,等待用户确认。
---
# 计划命令
此命令调用 **planner** 代理,在编写任何代码之前创建一个全面的实施计划。
## 此命令的作用
1. **重新阐述需求** - 明确需要构建什么
2. **识别风险** - 揭示潜在问题和阻碍
3. **创建分步计划** - 将实施分解为多个阶段
4. **等待确认** - 必须获得用户批准才能继续
## 何时使用
在以下情况下使用 `/plan`
* 开始新功能时
* 进行重大架构变更时
* 处理复杂重构时
* 多个文件/组件将受到影响时
* 需求不明确或存在歧义时
## 工作原理
planner 代理将:
1. **分析请求** 并用清晰的术语重新阐述需求
2. **分解为多个阶段**,每个阶段包含具体、可操作的步骤
3. **识别组件之间的依赖关系**
4. **评估风险和潜在阻碍**
5. **估算复杂度**(高/中/低)
6. **展示计划**并等待您明确的确认
## 使用示例
```
User: /plan I need to add real-time notifications when markets resolve
Agent (planner):
# Implementation Plan: Real-Time Market Resolution Notifications
## 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
## 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
### 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
### 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
### Phase 4: Frontend Components
- Create NotificationBell component in header
- Add NotificationList modal
- Implement real-time updates via Supabase subscriptions
- Add notification preferences page
## Dependencies
- Redis (for queue)
- Email service (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
## Estimated Complexity: MEDIUM
- Backend: 4-6 hours
- Frontend: 3-4 hours
- Testing: 2-3 hours
- Total: 9-13 hours
**WAITING FOR CONFIRMATION**: Proceed with this plan? (yes/no/modify)
```
## 重要说明
**关键**planner 代理在您明确用“是”、“继续”或类似的肯定性答复确认计划之前,**不会**编写任何代码。
如果您希望修改,请回复:
* "修改:\[您的修改内容]"
* "不同方法:\[替代方案]"
* "跳过阶段 2先执行阶段 3"
## 与其他命令的集成
计划之后:
* 使用 `/tdd` 以测试驱动开发的方式实施
* 如果出现构建错误,使用 `/build-fix`
* 使用 `/code-review` 审查已完成的实施
## 相关代理
此命令调用位于 `~/.claude/agents/planner.md``planner` 代理。

283
docs/zh-CN/commands/pm2.md Normal file
View File

@@ -0,0 +1,283 @@
# PM2 初始化
自动分析项目并生成 PM2 服务命令。
**命令**: `$ARGUMENTS`
***
## 工作流程
1. 检查 PM2如果缺失通过 `npm install -g pm2` 安装)
2. 扫描项目以识别服务(前端/后端/数据库)
3. 生成配置文件和各命令文件
***
## 服务检测
| 类型 | 检测方式 | 默认端口 |
|------|-----------|--------------|
| Vite | vite.config.\* | 5173 |
| Next.js | next.config.\* | 3000 |
| Nuxt | nuxt.config.\* | 3000 |
| CRA | package.json 中的 react-scripts | 3000 |
| Express/Node | server/backend/api 目录 + package.json | 3000 |
| FastAPI/Flask | requirements.txt / pyproject.toml | 8000 |
| Go | go.mod / main.go | 8080 |
**端口检测优先级**: 用户指定 > .env 文件 > 配置文件 > 脚本参数 > 默认端口
***
## 生成的文件
```
project/
├── ecosystem.config.cjs # PM2 config
├── {backend}/start.cjs # Python wrapper (if applicable)
└── .claude/
├── commands/
│ ├── pm2-all.md # Start all + monit
│ ├── pm2-all-stop.md # Stop all
│ ├── pm2-all-restart.md # Restart all
│ ├── pm2-{port}.md # Start single + logs
│ ├── pm2-{port}-stop.md # Stop single
│ ├── pm2-{port}-restart.md # Restart single
│ ├── pm2-logs.md # View all logs
│ └── pm2-status.md # View status
└── scripts/
├── pm2-logs-{port}.ps1 # Single service logs
└── pm2-monit.ps1 # PM2 monitor
```
***
## Windows 配置(重要)
### ecosystem.config.cjs
**必须使用 `.cjs` 扩展名**
```javascript
module.exports = {
apps: [
// Node.js (Vite/Next/Nuxt)
{
name: 'project-3000',
cwd: './packages/web',
script: 'node_modules/vite/bin/vite.js',
args: '--port 3000',
interpreter: 'C:/Program Files/nodejs/node.exe',
env: { NODE_ENV: 'development' }
},
// Python
{
name: 'project-8000',
cwd: './backend',
script: 'start.cjs',
interpreter: 'C:/Program Files/nodejs/node.exe',
env: { PYTHONUNBUFFERED: '1' }
}
]
}
```
**框架脚本路径:**
| 框架 | script | args |
|-----------|--------|------|
| Vite | `node_modules/vite/bin/vite.js` | `--port {port}` |
| Next.js | `node_modules/next/dist/bin/next` | `dev -p {port}` |
| Nuxt | `node_modules/nuxt/bin/nuxt.mjs` | `dev --port {port}` |
| Express | `src/index.js``server.js` | - |
### Python 包装脚本 (start.cjs)
```javascript
const { spawn } = require('child_process');
const proc = spawn('python', ['-m', 'uvicorn', 'app.main:app', '--host', '0.0.0.0', '--port', '8000', '--reload'], {
cwd: __dirname, stdio: 'inherit', windowsHide: true
});
proc.on('close', (code) => process.exit(code));
```
***
## 命令文件模板(最简内容)
### pm2-all.md (启动所有 + 监控)
````markdown
启动所有服务并打开 PM2 监控器。
```bash
cd "{PROJECT_ROOT}" && pm2 start ecosystem.config.cjs && start wt.exe -d "{PROJECT_ROOT}" pwsh -NoExit -c "pm2 monit"
```
````
### pm2-all-stop.md
````markdown
停止所有服务。
```bash
cd "{PROJECT_ROOT}" && pm2 stop all
```
````
### pm2-all-restart.md
````markdown
重启所有服务。
```bash
cd "{PROJECT_ROOT}" && pm2 restart all
```
````
### pm2-{port}.md (启动单个 + 日志)
````markdown
启动 {name} ({port}) 并打开日志。
```bash
cd "{PROJECT_ROOT}" && pm2 start ecosystem.config.cjs --only {name} && start wt.exe -d "{PROJECT_ROOT}" pwsh -NoExit -c "pm2 logs {name}"
```
````
### pm2-{port}-stop.md
````markdown
停止 {name} ({port})。
```bash
cd "{PROJECT_ROOT}" && pm2 stop {name}
```
````
### pm2-{port}-restart.md
````markdown
重启 {name} ({port})。
```bash
cd "{PROJECT_ROOT}" && pm2 restart {name}
```
````
### pm2-logs.md
````markdown
查看所有 PM2 日志。
```bash
cd "{PROJECT_ROOT}" && pm2 logs
```
````
### pm2-status.md
````markdown
查看 PM2 状态。
```bash
cd "{PROJECT_ROOT}" && pm2 status
```
````
### PowerShell 脚本 (pm2-logs-{port}.ps1)
```powershell
Set-Location "{PROJECT_ROOT}"
pm2 logs {name}
```
### PowerShell 脚本 (pm2-monit.ps1)
```powershell
Set-Location "{PROJECT_ROOT}"
pm2 monit
```
***
## 关键规则
1. **配置文件**: `ecosystem.config.cjs` (不是 .js)
2. **Node.js**: 直接指定 bin 路径 + 解释器
3. **Python**: Node.js 包装脚本 + `windowsHide: true`
4. **打开新窗口**: `start wt.exe -d "{path}" pwsh -NoExit -c "command"`
5. **最简内容**: 每个命令文件只有 1-2 行描述 + bash 代码块
6. **直接执行**: 无需 AI 解析,直接运行 bash 命令
***
## 执行
基于 `$ARGUMENTS`,执行初始化:
1. 扫描项目服务
2. 生成 `ecosystem.config.cjs`
3. 为 Python 服务生成 `{backend}/start.cjs`(如果适用)
4. 在 `.claude/commands/` 中生成命令文件
5. 在 `.claude/scripts/` 中生成脚本文件
6. **更新项目 CLAUDE.md**,添加 PM2 信息(见下文)
7. **显示完成摘要**,包含终端命令
***
## 初始化后:更新 CLAUDE.md
生成文件后,将 PM2 部分追加到项目的 `CLAUDE.md`(如果不存在则创建):
````markdown
## PM2 服务
| 端口 | 名称 | 类型 |
|------|------|------|
| {port} | {name} | {type} |
**终端命令:**
```bash
pm2 start ecosystem.config.cjs # First time
pm2 start all # After first time
pm2 stop all / pm2 restart all
pm2 start {name} / pm2 stop {name}
pm2 logs / pm2 status / pm2 monit
pm2 save # Save process list
pm2 resurrect # Restore saved list
```
````
**更新 CLAUDE.md 的规则:**
* 如果存在 PM2 部分,替换它
* 如果不存在,追加到末尾
* 保持内容精简且必要
***
## 初始化后:显示摘要
所有文件生成后,输出:
```
## PM2 Init Complete
**Services:**
| Port | Name | Type |
|------|------|------|
| {port} | {name} | {type} |
**Claude Commands:** /pm2-all, /pm2-all-stop, /pm2-{port}, /pm2-{port}-stop, /pm2-logs, /pm2-status
**Terminal Commands:**
## First time (with config file)
pm2 start ecosystem.config.cjs && pm2 save
## After first time (simplified)
pm2 start all # Start all
pm2 stop all # Stop all
pm2 restart all # Restart all
pm2 start {name} # Start single
pm2 stop {name} # Stop single
pm2 logs # View logs
pm2 monit # Monitor panel
pm2 resurrect # Restore saved processes
**Tip:** Run `pm2 save` after first start to enable simplified commands.
```

View File

@@ -0,0 +1,320 @@
---
description: 全面的Python代码审查确保符合PEP 8标准、类型提示、安全性以及Pythonic惯用法。调用python-reviewer代理。
---
# Python 代码审查
此命令调用 **python-reviewer** 代理进行全面的 Python 专项代码审查。
## 此命令的功能
1. **识别 Python 变更**:通过 `git diff` 查找修改过的 `.py` 文件
2. **运行静态分析**:执行 `ruff``mypy``pylint``black --check`
3. **安全扫描**:检查 SQL 注入、命令注入、不安全的反序列化
4. **类型安全审查**:分析类型提示和 mypy 错误
5. **Pythonic 代码检查**:验证代码是否遵循 PEP 8 和 Python 最佳实践
6. **生成报告**:按严重程度对问题进行归类
## 使用时机
在以下情况使用 `/python-review`
* 编写或修改 Python 代码后
* 提交 Python 变更前
* 审查包含 Python 代码的拉取请求时
* 接手新的 Python 代码库时
* 学习 Pythonic 模式和惯用法时
## 审查类别
### 关键 (必须修复)
* SQL/命令注入漏洞
* 不安全的 eval/exec 使用
* Pickle 不安全反序列化
* 硬编码的凭证
* YAML 不安全加载
* 隐藏错误的裸 except 子句
### 高 (应该修复)
* 公共函数缺少类型提示
* 可变默认参数
* 静默吞掉异常
* 未对资源使用上下文管理器
* 使用 C 风格循环而非推导式
* 使用 type() 而非 isinstance()
* 无锁的竞态条件
### 中 (考虑)
* 违反 PEP 8 格式规范
* 公共函数缺少文档字符串
* 使用 print 语句而非 logging
* 低效的字符串操作
* 未使用命名常量的魔法数字
* 未使用 f-strings 进行格式化
* 不必要的列表创建
## 运行的自动化检查
```bash
# Type checking
mypy .
# Linting and formatting
ruff check .
black --check .
isort --check-only .
# Security scanning
bandit -r .
# Dependency audit
pip-audit
safety check
# Testing
pytest --cov=app --cov-report=term-missing
```
## 使用示例
````text
User: /python-review
Agent:
# Python Code Review Report
## Files Reviewed
- app/routes/user.py (modified)
- app/services/auth.py (modified)
## Static Analysis Results
✓ ruff: No issues
✓ mypy: No errors
⚠️ black: 2 files need reformatting
✓ bandit: No security issues
## Issues Found
[CRITICAL] SQL Injection vulnerability
File: app/routes/user.py:42
Issue: User input directly interpolated into SQL query
```python
query = f"SELECT * FROM users WHERE id = {user_id}" # Bad
````
修复:使用参数化查询
```python
query = "SELECT * FROM users WHERE id = %s" # Good
cursor.execute(query, (user_id,))
```
\[高] 可变默认参数
文件app/services/auth.py:18
问题:可变默认参数导致共享状态
```python
def process_items(items=[]): # Bad
items.append("new")
return items
```
修复:使用 None 作为默认值
```python
def process_items(items=None): # Good
if items is None:
items = []
items.append("new")
return items
```
\[中] 缺少类型提示
文件app/services/auth.py:25
问题:公共函数缺少类型注解
```python
def get_user(user_id): # Bad
return db.find(user_id)
```
修复:添加类型提示
```python
def get_user(user_id: str) -> Optional[User]: # Good
return db.find(user_id)
```
\[中] 未使用上下文管理器
文件app/routes/user.py:55
问题:异常时文件未关闭
```python
f = open("config.json") # Bad
data = f.read()
f.close()
```
修复:使用上下文管理器
```python
with open("config.json") as f: # Good
data = f.read()
```
## 摘要
* 关键1
* 高1
* 中2
建议:❌ 在关键问题修复前阻止合并
## 所需的格式化
运行:`black app/routes/user.py app/services/auth.py`
````
## Approval Criteria
| Status | Condition |
|--------|-----------|
| ✅ Approve | No CRITICAL or HIGH issues |
| ⚠️ Warning | Only MEDIUM issues (merge with caution) |
| ❌ Block | CRITICAL or HIGH issues found |
## Integration with Other Commands
- Use `/tdd` first to ensure tests pass
- Use `/code-review` for non-Python specific concerns
- Use `/python-review` before committing
- Use `/build-fix` if static analysis tools fail
## Framework-Specific Reviews
### Django Projects
The reviewer checks for:
- N+1 query issues (use `select_related` and `prefetch_related`)
- Missing migrations for model changes
- Raw SQL usage when ORM could work
- Missing `transaction.atomic()` for multi-step operations
### FastAPI Projects
The reviewer checks for:
- CORS misconfiguration
- Pydantic models for request validation
- Response models correctness
- Proper async/await usage
- Dependency injection patterns
### Flask Projects
The reviewer checks for:
- Context management (app context, request context)
- Proper error handling
- Blueprint organization
- Configuration management
## Related
- Agent: `agents/python-reviewer.md`
- Skills: `skills/python-patterns/`, `skills/python-testing/`
## Common Fixes
### Add Type Hints
```python
# Before
def calculate(x, y):
return x + y
# After
from typing import Union
def calculate(x: Union[int, float], y: Union[int, float]) -> Union[int, float]:
return x + y
````
### 使用上下文管理器
```python
# Before
f = open("file.txt")
data = f.read()
f.close()
# After
with open("file.txt") as f:
data = f.read()
```
### 使用列表推导式
```python
# Before
result = []
for item in items:
if item.active:
result.append(item.name)
# After
result = [item.name for item in items if item.active]
```
### 修复可变默认参数
```python
# Before
def append(value, items=[]):
items.append(value)
return items
# After
def append(value, items=None):
if items is None:
items = []
items.append(value)
return items
```
### 使用 f-strings (Python 3.6+)
```python
# Before
name = "Alice"
greeting = "Hello, " + name + "!"
greeting2 = "Hello, {}".format(name)
# After
greeting = f"Hello, {name}!"
```
### 修复循环中的字符串连接
```python
# Before
result = ""
for item in items:
result += str(item)
# After
result = "".join(str(item) for item in items)
```
## Python 版本兼容性
审查者会指出代码何时使用了新 Python 版本的功能:
| 功能 | 最低 Python 版本 |
|---------|----------------|
| 类型提示 | 3.5+ |
| f-strings | 3.6+ |
| 海象运算符 (`:=`) | 3.8+ |
| 仅限位置参数 | 3.8+ |
| Match 语句 | 3.10+ |
| 类型联合 (\`x | None\`) | 3.10+ |
确保你的项目 `pyproject.toml``setup.py` 指定了正确的最低 Python 版本。

View File

@@ -0,0 +1,28 @@
# 重构清理
通过测试验证安全识别并删除无用代码:
1. 运行无用代码分析工具:
* knip查找未使用的导出和文件
* depcheck查找未使用的依赖项
* ts-prune查找未使用的 TypeScript 导出
2. 在 .reports/dead-code-analysis.md 中生成综合报告
3. 按严重程度对发现进行分类:
* 安全:测试文件、未使用的工具函数
* 注意API 路由、组件
* 危险:配置文件、主要入口点
4. 仅建议安全的删除操作
5. 每次删除前:
* 运行完整的测试套件
* 验证测试通过
* 应用更改
* 重新运行测试
* 如果测试失败则回滚
6. 显示已清理项目的摘要
切勿在不首先运行测试的情况下删除代码!

View File

@@ -0,0 +1,312 @@
# Sessions 命令
管理 Claude Code 会话历史 - 列出、加载、设置别名和编辑存储在 `~/.claude/sessions/` 中的会话。
## 用法
`/sessions [list|load|alias|info|help] [options]`
## 操作
### 列出会话
显示所有会话及其元数据,支持筛选和分页。
```bash
/sessions # List all sessions (default)
/sessions list # Same as above
/sessions list --limit 10 # Show 10 sessions
/sessions list --date 2026-02-01 # Filter by date
/sessions list --search abc # Search by session ID
```
**脚本:**
```bash
node -e "
const sm = require((process.env.CLAUDE_PLUGIN_ROOT||require('path').join(require('os').homedir(),'.claude'))+'/scripts/lib/session-manager');
const aa = require((process.env.CLAUDE_PLUGIN_ROOT||require('path').join(require('os').homedir(),'.claude'))+'/scripts/lib/session-aliases');
const result = sm.getAllSessions({ limit: 20 });
const aliases = aa.listAliases();
const aliasMap = {};
for (const a of aliases) aliasMap[a.sessionPath] = a.name;
console.log('Sessions (showing ' + result.sessions.length + ' of ' + result.total + '):');
console.log('');
console.log('ID Date Time Size Lines Alias');
console.log('────────────────────────────────────────────────────');
for (const s of result.sessions) {
const alias = aliasMap[s.filename] || '';
const size = sm.getSessionSize(s.sessionPath);
const stats = sm.getSessionStats(s.sessionPath);
const id = s.shortId === 'no-id' ? '(none)' : s.shortId.slice(0, 8);
const time = s.modifiedTime.toTimeString().slice(0, 5);
console.log(id.padEnd(8) + ' ' + s.date + ' ' + time + ' ' + size.padEnd(7) + ' ' + String(stats.lineCount).padEnd(5) + ' ' + alias);
}
"
```
### 加载会话
加载并显示会话内容(通过 ID 或别名)。
```bash
/sessions load <id|alias> # Load session
/sessions load 2026-02-01 # By date (for no-id sessions)
/sessions load a1b2c3d4 # By short ID
/sessions load my-alias # By alias name
```
**脚本:**
```bash
node -e "
const sm = require((process.env.CLAUDE_PLUGIN_ROOT||require('path').join(require('os').homedir(),'.claude'))+'/scripts/lib/session-manager');
const aa = require((process.env.CLAUDE_PLUGIN_ROOT||require('path').join(require('os').homedir(),'.claude'))+'/scripts/lib/session-aliases');
const id = process.argv[1];
// First try to resolve as alias
const resolved = aa.resolveAlias(id);
const sessionId = resolved ? resolved.sessionPath : id;
const session = sm.getSessionById(sessionId, true);
if (!session) {
console.log('Session not found: ' + id);
process.exit(1);
}
const stats = sm.getSessionStats(session.sessionPath);
const size = sm.getSessionSize(session.sessionPath);
const aliases = aa.getAliasesForSession(session.filename);
console.log('Session: ' + session.filename);
console.log('Path: ~/.claude/sessions/' + session.filename);
console.log('');
console.log('Statistics:');
console.log(' Lines: ' + stats.lineCount);
console.log(' Total items: ' + stats.totalItems);
console.log(' Completed: ' + stats.completedItems);
console.log(' In progress: ' + stats.inProgressItems);
console.log(' Size: ' + size);
console.log('');
if (aliases.length > 0) {
console.log('Aliases: ' + aliases.map(a => a.name).join(', '));
console.log('');
}
if (session.metadata.title) {
console.log('Title: ' + session.metadata.title);
console.log('');
}
if (session.metadata.started) {
console.log('Started: ' + session.metadata.started);
}
if (session.metadata.lastUpdated) {
console.log('Last Updated: ' + session.metadata.lastUpdated);
}
" "$ARGUMENTS"
```
### 创建别名
为会话创建一个易记的别名。
```bash
/sessions alias <id> <name> # Create alias
/sessions alias 2026-02-01 today-work # Create alias named "today-work"
```
**脚本:**
```bash
node -e "
const sm = require((process.env.CLAUDE_PLUGIN_ROOT||require('path').join(require('os').homedir(),'.claude'))+'/scripts/lib/session-manager');
const aa = require((process.env.CLAUDE_PLUGIN_ROOT||require('path').join(require('os').homedir(),'.claude'))+'/scripts/lib/session-aliases');
const sessionId = process.argv[1];
const aliasName = process.argv[2];
if (!sessionId || !aliasName) {
console.log('Usage: /sessions alias <id> <name>');
process.exit(1);
}
// Get session filename
const session = sm.getSessionById(sessionId);
if (!session) {
console.log('Session not found: ' + sessionId);
process.exit(1);
}
const result = aa.setAlias(aliasName, session.filename);
if (result.success) {
console.log('✓ Alias created: ' + aliasName + ' → ' + session.filename);
} else {
console.log('✗ Error: ' + result.error);
process.exit(1);
}
" "$ARGUMENTS"
```
### 移除别名
删除现有的别名。
```bash
/sessions alias --remove <name> # Remove alias
/sessions unalias <name> # Same as above
```
**脚本:**
```bash
node -e "
const aa = require((process.env.CLAUDE_PLUGIN_ROOT||require('path').join(require('os').homedir(),'.claude'))+'/scripts/lib/session-aliases');
const aliasName = process.argv[1];
if (!aliasName) {
console.log('Usage: /sessions alias --remove <name>');
process.exit(1);
}
const result = aa.deleteAlias(aliasName);
if (result.success) {
console.log('✓ Alias removed: ' + aliasName);
} else {
console.log('✗ Error: ' + result.error);
process.exit(1);
}
" "$ARGUMENTS"
```
### 会话信息
显示会话的详细信息。
```bash
/sessions info <id|alias> # Show session details
```
**脚本:**
```bash
node -e "
const sm = require((process.env.CLAUDE_PLUGIN_ROOT||require('path').join(require('os').homedir(),'.claude'))+'/scripts/lib/session-manager');
const aa = require((process.env.CLAUDE_PLUGIN_ROOT||require('path').join(require('os').homedir(),'.claude'))+'/scripts/lib/session-aliases');
const id = process.argv[1];
const resolved = aa.resolveAlias(id);
const sessionId = resolved ? resolved.sessionPath : id;
const session = sm.getSessionById(sessionId, true);
if (!session) {
console.log('Session not found: ' + id);
process.exit(1);
}
const stats = sm.getSessionStats(session.sessionPath);
const size = sm.getSessionSize(session.sessionPath);
const aliases = aa.getAliasesForSession(session.filename);
console.log('Session Information');
console.log('════════════════════');
console.log('ID: ' + (session.shortId === 'no-id' ? '(none)' : session.shortId));
console.log('Filename: ' + session.filename);
console.log('Date: ' + session.date);
console.log('Modified: ' + session.modifiedTime.toISOString().slice(0, 19).replace('T', ' '));
console.log('');
console.log('Content:');
console.log(' Lines: ' + stats.lineCount);
console.log(' Total items: ' + stats.totalItems);
console.log(' Completed: ' + stats.completedItems);
console.log(' In progress: ' + stats.inProgressItems);
console.log(' Size: ' + size);
if (aliases.length > 0) {
console.log('Aliases: ' + aliases.map(a => a.name).join(', '));
}
" "$ARGUMENTS"
```
### 列出别名
显示所有会话别名。
```bash
/sessions aliases # List all aliases
```
**脚本:**
```bash
node -e "
const aa = require((process.env.CLAUDE_PLUGIN_ROOT||require('path').join(require('os').homedir(),'.claude'))+'/scripts/lib/session-aliases');
const aliases = aa.listAliases();
console.log('Session Aliases (' + aliases.length + '):');
console.log('');
if (aliases.length === 0) {
console.log('No aliases found.');
} else {
console.log('Name Session File Title');
console.log('─────────────────────────────────────────────────────────────');
for (const a of aliases) {
const name = a.name.padEnd(12);
const file = (a.sessionPath.length > 30 ? a.sessionPath.slice(0, 27) + '...' : a.sessionPath).padEnd(30);
const title = a.title || '';
console.log(name + ' ' + file + ' ' + title);
}
}
"
```
## 参数
$ARGUMENTS:
* `list [options]` - 列出会话
* `--limit <n>` - 最大显示会话数默认50
* `--date <YYYY-MM-DD>` - 按日期筛选
* `--search <pattern>` - 在会话 ID 中搜索
* `load <id|alias>` - 加载会话内容
* `alias <id> <name>` - 为会话创建别名
* `alias --remove <name>` - 移除别名
* `unalias <name>` - 与 `--remove` 相同
* `info <id|alias>` - 显示会话统计信息
* `aliases` - 列出所有别名
* `help` - 显示此帮助信息
## 示例
```bash
# List all sessions
/sessions list
# Create an alias for today's session
/sessions alias 2026-02-01 today
# Load session by alias
/sessions load today
# Show session info
/sessions info today
# Remove alias
/sessions alias --remove today
# List all aliases
/sessions aliases
```
## 备注
* 会话以 Markdown 文件形式存储在 `~/.claude/sessions/`
* 别名存储在 `~/.claude/session-aliases.json`
* 会话 ID 可以缩短(通常前 4-8 个字符就足够唯一)
* 为经常引用的会话使用别名

View File

@@ -0,0 +1,83 @@
---
description: 配置您首选的包管理器npm/pnpm/yarn/bun
disable-model-invocation: true
---
# 包管理器设置
配置您为此项目或全局偏好的包管理器。
## 使用方式
```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
```
## 检测优先级
在确定使用哪个包管理器时,会按以下顺序检查:
1. **环境变量**`CLAUDE_PACKAGE_MANAGER`
2. **项目配置**`.claude/package-manager.json`
3. **package.json**`packageManager` 字段
4. **锁文件**package-lock.json、yarn.lock、pnpm-lock.yaml 或 bun.lockb 的存在
5. **全局配置**`~/.claude/package-manager.json`
6. **回退方案**:第一个可用的包管理器 (pnpm > bun > yarn > npm)
## 配置文件
### 全局配置
```json
// ~/.claude/package-manager.json
{
"packageManager": "pnpm"
}
```
### 项目配置
```json
// .claude/package-manager.json
{
"packageManager": "bun"
}
```
### package.json
```json
{
"packageManager": "pnpm@8.6.0"
}
```
## 环境变量
设置 `CLAUDE_PACKAGE_MANAGER` 以覆盖所有其他检测方法:
```bash
# Windows (PowerShell)
$env:CLAUDE_PACKAGE_MANAGER = "pnpm"
# macOS/Linux
export CLAUDE_PACKAGE_MANAGER=pnpm
```
## 运行检测
要查看当前包管理器检测结果,请运行:
```bash
node scripts/setup-package-manager.js --detect
```

View File

@@ -0,0 +1,177 @@
---
name: skill-create
description: 分析本地Git历史以提取编码模式并生成SKILL.md文件。Skill Creator GitHub应用的本地版本。
allowed_tools: ["Bash", "Read", "Write", "Grep", "Glob"]
---
# /skill-create - 本地技能生成
分析你的仓库的 git 历史,以提取编码模式并生成 SKILL.md 文件,用于向 Claude 传授你团队的实践方法。
## 使用方法
```bash
/skill-create # Analyze current repo
/skill-create --commits 100 # Analyze last 100 commits
/skill-create --output ./skills # Custom output directory
/skill-create --instincts # Also generate instincts for continuous-learning-v2
```
## 功能说明
1. **解析 Git 历史** - 分析提交记录、文件更改和模式
2. **检测模式** - 识别重复出现的工作流程和约定
3. **生成 SKILL.md** - 创建有效的 Claude Code 技能文件
4. **可选创建 Instincts** - 用于 continuous-learning-v2 系统
## 分析步骤
### 步骤 1收集 Git 数据
```bash
# Get recent commits with file changes
git log --oneline -n ${COMMITS:-200} --name-only --pretty=format:"%H|%s|%ad" --date=short
# Get commit frequency by file
git log --oneline -n 200 --name-only | grep -v "^$" | grep -v "^[a-f0-9]" | sort | uniq -c | sort -rn | head -20
# Get commit message patterns
git log --oneline -n 200 | cut -d' ' -f2- | head -50
```
### 步骤 2检测模式
寻找以下模式类型:
| 模式 | 检测方法 |
|---------|-----------------|
| **提交约定** | 对提交消息进行正则匹配 (feat:, fix:, chore:) |
| **文件协同更改** | 总是同时更改的文件 |
| **工作流序列** | 重复的文件更改模式 |
| **架构** | 文件夹结构和命名约定 |
| **测试模式** | 测试文件位置、命名、覆盖率 |
### 步骤 3生成 SKILL.md
输出格式:
```markdown
---
name: {repo-name}-patterns
description: 从 {repo-name} 提取的编码模式
version: 1.0.0
source: local-git-analysis
analyzed_commits: {count}
---
# {Repo Name} 模式
## 提交规范
{detected commit message patterns}
## 代码架构
{detected folder structure and organization}
## 工作流
{detected repeating file change patterns}
## 测试模式
{detected test conventions}
```
### 步骤 4生成 Instincts如果使用 --instincts
用于 continuous-learning-v2 集成:
```yaml
---
id: {repo}-commit-convention
trigger: "when writing a commit message"
confidence: 0.8
domain: git
source: local-repo-analysis
---
# Use Conventional Commits
## Action
Prefix commits with: feat:, fix:, chore:, docs:, test:, refactor:
## Evidence
- Analyzed {n} commits
- {percentage}% follow conventional commit format
```
## 示例输出
在 TypeScript 项目上运行 `/skill-create` 可能会产生:
```markdown
---
name: my-app-patterns
description: Coding patterns from my-app repository
version: 1.0.0
source: local-git-analysis
analyzed_commits: 150
---
# My App 模式
## 提交约定
该项目使用 **约定式提交**
- `feat:` - 新功能
- `fix:` - 错误修复
- `chore:` - 维护任务
- `docs:` - 文档更新
## 代码架构
```
src/
├── components/ # React 组件 (PascalCase.tsx)
├── hooks/ # 自定义钩子 (use\*.ts)
├── utils/ # 工具函数
├── types/ # TypeScript 类型定义
└── services/ # API 和外部服务
```
## Workflows
### Adding a New Component
1. Create `src/components/ComponentName.tsx`
2. Add tests in `src/components/__tests__/ComponentName.test.tsx`
3. Export from `src/components/index.ts`
### Database Migration
1. Modify `src/db/schema.ts`
2. Run `pnpm db:generate`
3. Run `pnpm db:migrate`
## Testing Patterns
- Test files: `__tests__/` directories or `.test.ts` suffix
- Coverage target: 80%+
- Framework: Vitest
```
## GitHub 应用集成
对于高级功能10k+ 提交、团队共享、自动 PR请使用 [Skill Creator GitHub 应用](https://github.com/apps/skill-creator)
* 安装: [github.com/apps/skill-creator](https://github.com/apps/skill-creator)
* 在任何议题上评论 `/skill-creator analyze`
* 接收包含生成技能的 PR
## 相关命令
* `/instinct-import` - 导入生成的 instincts
* `/instinct-status` - 查看已学习的 instincts
* `/evolve` - 将 instincts 聚类为技能/代理
***
*属于 [Everything Claude Code](https://github.com/affaan-m/everything-claude-code)*

330
docs/zh-CN/commands/tdd.md Normal file
View File

@@ -0,0 +1,330 @@
---
description: 强制执行测试驱动开发工作流。首先搭建接口,生成测试,然后实现最小化代码以通过测试。确保 80%+ 覆盖率。
---
# TDD 命令
此命令调用 **tdd-guide** 代理来强制执行测试驱动开发方法。
## 此命令的作用
1. **搭建接口** - 首先定义类型/接口
2. **首先生成测试** - 编写失败的测试(红)
3. **实现最小化代码** - 编写刚好足够的代码以通过测试(绿)
4. **重构** - 改进代码,同时保持测试通过(重构)
5. **验证覆盖率** - 确保 80%+ 的测试覆盖率
## 何时使用
在以下情况下使用 `/tdd`
* 实现新功能时
* 添加新函数/组件时
* 修复错误时(首先编写重现错误的测试)
* 重构现有代码时
* 构建关键业务逻辑时
## 工作原理
tdd-guide 代理将:
1. 为输入/输出**定义接口**
2. **编写将会失败的测试**(因为代码尚不存在)
3. **运行测试**并验证它们因正确的原因而失败
4. **编写最小化实现**以使测试通过
5. **运行测试**并验证它们通过
6. **重构**代码,同时保持测试通过
7. **检查覆盖率**,如果低于 80% 则添加更多测试
## TDD 循环
```
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
```
## 使用示例
````
User: /tdd I need a function to calculate market liquidity score
Agent (tdd-guide):
# TDD Session: Market Liquidity Score Calculator
## Step 1: Define Interface (SCAFFOLD)
```typescript
// lib/liquidity.ts
export interface MarketData {
totalVolume: number
bidAskSpread: number
activeTraders: number
lastTradeTime: Date
}
export function calculateLiquidityScore(market: MarketData): number {
// TODO: Implementation
throw new Error('Not implemented')
}
````
## 步骤 2编写失败的测试
```typescript
// lib/liquidity.test.ts
import { calculateLiquidityScore } from './liquidity'
describe('calculateLiquidityScore', () => {
it('should return high score for liquid market', () => {
const market = {
totalVolume: 100000,
bidAskSpread: 0.01,
activeTraders: 500,
lastTradeTime: new Date()
}
const score = calculateLiquidityScore(market)
expect(score).toBeGreaterThan(80)
expect(score).toBeLessThanOrEqual(100)
})
it('should return low score for illiquid market', () => {
const market = {
totalVolume: 100,
bidAskSpread: 0.5,
activeTraders: 2,
lastTradeTime: new Date(Date.now() - 86400000) // 1 day ago
}
const score = calculateLiquidityScore(market)
expect(score).toBeLessThan(30)
expect(score).toBeGreaterThanOrEqual(0)
})
it('should handle edge case: zero volume', () => {
const market = {
totalVolume: 0,
bidAskSpread: 0,
activeTraders: 0,
lastTradeTime: new Date()
}
const score = calculateLiquidityScore(market)
expect(score).toBe(0)
})
})
```
## 步骤 3运行测试 - 验证失败
```bash
npm test lib/liquidity.test.ts
FAIL lib/liquidity.test.ts
✕ should return high score for liquid market (2 ms)
Error: Not implemented
1 test failed, 0 passed
```
✅ 测试按预期失败。准备实施。
## 步骤 4实现最小化代码绿
```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)
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 +
traderScore * 0.2 +
recencyScore * 0.1
)
return Math.min(Math.max(score, 0), 100) // Clamp to 0-100
}
```
## 步骤 5运行测试 - 验证通过
```bash
npm test lib/liquidity.test.ts
PASS lib/liquidity.test.ts
✓ should return high score for liquid market (3 ms)
✓ should return low score for illiquid market (2 ms)
✓ should handle edge case: zero volume (1 ms)
3 tests passed
```
✅ 所有测试通过!
## 步骤 6重构改进
```typescript
// lib/liquidity.ts - Refactored with constants and better readability
const WEIGHTS = {
VOLUME: 0.4,
SPREAD: 0.3,
TRADERS: 0.2,
RECENCY: 0.1,
} as const
const SCALE_FACTORS = {
VOLUME: 1000,
SPREAD: 1000,
TRADERS: 10,
RECENCY_PENALTY: 10,
} as const
function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max)
}
export function calculateLiquidityScore(market: MarketData): number {
if (market.totalVolume === 0) return 0
const volumeScore = Math.min(market.totalVolume / SCALE_FACTORS.VOLUME, 100)
const spreadScore = clamp(100 - (market.bidAskSpread * SCALE_FACTORS.SPREAD), 0, 100)
const traderScore = Math.min(market.activeTraders / SCALE_FACTORS.TRADERS, 100)
const hoursSinceLastTrade = (Date.now() - market.lastTradeTime.getTime()) / (1000 * 60 * 60)
const recencyScore = clamp(100 - (hoursSinceLastTrade * SCALE_FACTORS.RECENCY_PENALTY), 0, 100)
const weightedScore =
volumeScore * WEIGHTS.VOLUME +
spreadScore * WEIGHTS.SPREAD +
traderScore * WEIGHTS.TRADERS +
recencyScore * WEIGHTS.RECENCY
return clamp(weightedScore, 0, 100)
}
```
## 步骤 7验证测试仍然通过
```bash
npm test lib/liquidity.test.ts
PASS lib/liquidity.test.ts
✓ should return high score for liquid market (3 ms)
✓ should return low score for illiquid market (2 ms)
✓ should handle edge case: zero volume (1 ms)
3 tests passed
```
✅ 重构完成,测试仍然通过!
## 步骤 8检查覆盖率
```bash
npm test -- --coverage lib/liquidity.test.ts
File | % Stmts | % Branch | % Funcs | % Lines
---------------|---------|----------|---------|--------
liquidity.ts | 100 | 100 | 100 | 100
Coverage: 100% ✅ (Target: 80%)
```
✅ TDD 会话完成!
```
## TDD Best Practices
**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)
**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)
## Test Types to Include
**Unit Tests** (Function-level):
- Happy path scenarios
- Edge cases (empty, null, max values)
- Error conditions
- Boundary values
**Integration Tests** (Component-level):
- API endpoints
- Database operations
- External service calls
- React components with hooks
**E2E Tests** (use `/e2e` command):
- Critical user flows
- Multi-step processes
- Full stack integration
## Coverage Requirements
- **80% minimum** for all code
- **100% required** for:
- Financial calculations
- Authentication logic
- Security-critical code
- Core business logic
## Important Notes
**MANDATORY**: Tests must be written BEFORE implementation. The TDD cycle is:
1. **RED** - Write failing test
2. **GREEN** - Implement to pass
3. **REFACTOR** - Improve code
Never skip the RED phase. Never write code before tests.
## Integration with Other Commands
- Use `/plan` first to understand what to build
- Use `/tdd` to implement with tests
- Use `/build-fix` if build errors occur
- Use `/code-review` to review implementation
- Use `/test-coverage` to verify coverage
## Related Agents
This command invokes the `tdd-guide` agent located at:
`~/.claude/agents/tdd-guide.md`
And can reference the `tdd-workflow` skill at:
`~/.claude/skills/tdd-workflow/`
```

View File

@@ -0,0 +1,28 @@
# 测试覆盖率
分析测试覆盖率并生成缺失的测试:
1. 运行带有覆盖率的测试npm test --coverage 或 pnpm test --coverage
2. 分析覆盖率报告 (coverage/coverage-summary.json)
3. 识别覆盖率低于 80% 阈值的文件
4. 对于每个覆盖率不足的文件:
* 分析未测试的代码路径
* 为函数生成单元测试
* 为 API 生成集成测试
* 为关键流程生成端到端测试
5. 验证新测试通过
6. 显示覆盖率指标的前后对比
7. 确保项目整体覆盖率超过 80%
重点关注:
* 正常路径场景
* 错误处理
* 边界情况null、undefined、空值
* 边界条件

View File

@@ -0,0 +1,21 @@
# 更新代码地图
分析代码库结构并更新架构文档:
1. 扫描所有源文件的导入、导出和依赖关系
2. 以以下格式生成简洁的代码地图:
* codemaps/architecture.md - 整体架构
* codemaps/backend.md - 后端结构
* codemaps/frontend.md - 前端结构
* codemaps/data.md - 数据模型和模式
3. 计算与之前版本的差异百分比
4. 如果变更 > 30%,则在更新前请求用户批准
5. 为每个代码地图添加新鲜度时间戳
6. 将报告保存到 .reports/codemap-diff.txt
使用 TypeScript/Node.js 进行分析。专注于高层结构,而非实现细节。

View File

@@ -0,0 +1,31 @@
# 更新文档
从单一事实来源同步文档:
1. 读取 package.json 的 scripts 部分
* 生成脚本参考表
* 包含来自注释的描述
2. 读取 .env.example
* 提取所有环境变量
* 记录其用途和格式
3. 生成 docs/CONTRIB.md内容包含
* 开发工作流程
* 可用脚本
* 环境设置
* 测试流程
4. 生成 docs/RUNBOOK.md内容包含
* 部署流程
* 监控和警报
* 常见问题及修复
* 回滚流程
5. 识别过时的文档:
* 查找 90 天以上未修改的文档
* 列出以供人工审查
6. 显示差异摘要
单一事实来源package.json 和 .env.example

View File

@@ -0,0 +1,60 @@
# 验证命令
对当前代码库状态执行全面验证。
## 说明
请严格按照以下顺序执行验证:
1. **构建检查**
* 运行此项目的构建命令
* 如果失败,报告错误并**停止**
2. **类型检查**
* 运行 TypeScript/类型检查器
* 报告所有错误,包含文件:行号
3. **代码检查**
* 运行代码检查器
* 报告警告和错误
4. **测试套件**
* 运行所有测试
* 报告通过/失败数量
* 报告覆盖率百分比
5. **Console.log 审计**
* 在源文件中搜索 console.log
* 报告位置
6. **Git 状态**
* 显示未提交的更改
* 显示自上次提交以来修改的文件
## 输出
生成一份简洁的验证报告:
```
VERIFICATION: [PASS/FAIL]
Build: [OK/FAIL]
Types: [OK/X errors]
Lint: [OK/X issues]
Tests: [X/Y passed, Z% coverage]
Secrets: [OK/X found]
Logs: [OK/X console.logs]
Ready for PR: [YES/NO]
```
如果存在任何关键问题,列出它们并提供修复建议。
## 参数
$ARGUMENTS 可以是:
* `quick` - 仅构建 + 类型检查
* `full` - 所有检查(默认)
* `pre-commit` - 与提交相关的检查
* `pre-pr` - 完整检查加安全扫描