mirror of
https://github.com/catlog22/Claude-Code-Workflow.git
synced 2026-02-07 02:04:11 +08:00
Compare commits
91 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
04cd536da5 | ||
|
|
9a3608173a | ||
|
|
f5b6bb97bc | ||
|
|
2819f3597f | ||
|
|
c0c1a2eb92 | ||
|
|
012197a861 | ||
|
|
407b2e6930 | ||
|
|
6428febdf6 | ||
|
|
9f9ef1d054 | ||
|
|
ea04663035 | ||
|
|
f0954b3247 | ||
|
|
2fffe78dc9 | ||
|
|
02531c4d15 | ||
|
|
5fa7524ad7 | ||
|
|
21fbdbc55e | ||
|
|
1f1a078450 | ||
|
|
d3aeac4e9f | ||
|
|
e2e3d5a815 | ||
|
|
ddb7fb7d7a | ||
|
|
62d5ce3f34 | ||
|
|
15b3977e88 | ||
|
|
d70f02abed | ||
|
|
e11c4ba8ed | ||
|
|
60eab98782 | ||
|
|
d9f1d14d5e | ||
|
|
64e064e775 | ||
|
|
8c1d62208e | ||
|
|
c4960c3e84 | ||
|
|
82b8fcc608 | ||
|
|
a7c8ea04f1 | ||
|
|
2084ff3e21 | ||
|
|
890ca455b2 | ||
|
|
1dfabf6bda | ||
|
|
604405b2d6 | ||
|
|
190d2280fd | ||
|
|
4e66864cfd | ||
|
|
cac0566627 | ||
|
|
572c103fbf | ||
|
|
9d6bc92837 | ||
|
|
ffe9898fd3 | ||
|
|
a602a46985 | ||
|
|
f7dd3d23ff | ||
|
|
200812d204 | ||
|
|
261c98549d | ||
|
|
b85d9b9eb1 | ||
|
|
4610018193 | ||
|
|
9c9b1ad01c | ||
|
|
2f3a14e946 | ||
|
|
1376dc71d9 | ||
|
|
c1d12384c3 | ||
|
|
eea859dd6f | ||
|
|
3fe630f221 | ||
|
|
eeaefa7208 | ||
|
|
e58c33fb6e | ||
|
|
6716772e0a | ||
|
|
a8367bd4d7 | ||
|
|
ea13f9a575 | ||
|
|
7d152b7bf9 | ||
|
|
16c96229f9 | ||
|
|
40b003be68 | ||
|
|
46111b3987 | ||
|
|
f47726d43b | ||
|
|
502d088c98 | ||
|
|
f845e6e0ee | ||
|
|
e96eed817c | ||
|
|
6a6d1885d8 | ||
|
|
a34eeb63bf | ||
|
|
56acc4f19c | ||
|
|
fdf468ed99 | ||
|
|
680c2a0597 | ||
|
|
5b5dc85677 | ||
|
|
1e691fa751 | ||
|
|
1f87ca0be3 | ||
|
|
f14418603a | ||
|
|
1fae35c05d | ||
|
|
8523079a99 | ||
|
|
4daeb0eead | ||
|
|
86548af518 | ||
|
|
4e5eb6cd40 | ||
|
|
021ce619f0 | ||
|
|
63aaab596c | ||
|
|
bc52af540e | ||
|
|
8bbbdc61eb | ||
|
|
fd5f6c2c97 | ||
|
|
fd145c34cd | ||
|
|
10b3ace917 | ||
|
|
d6a2e0de59 | ||
|
|
35c6605681 | ||
|
|
ef2229b0bb | ||
|
|
b65977d8dc | ||
|
|
bc4176fda0 |
@@ -29,13 +29,18 @@ Available CLI endpoints are dynamically defined by the config file:
|
||||
```
|
||||
Bash({ command: "ccw cli -p '...' --tool gemini", run_in_background: true })
|
||||
```
|
||||
- **After CLI call**: Stop immediately - let CLI execute in background
|
||||
- **After CLI call**: Stop output immediately - let CLI execute in background. **DO NOT use TaskOutput polling** - wait for hook callback to receive results
|
||||
|
||||
### CLI Analysis Calls
|
||||
- **Wait for results**: MUST wait for CLI analysis to complete before taking any write action. Do NOT proceed with fixes while analysis is running
|
||||
- **Value every call**: Each CLI invocation is valuable and costly. NEVER waste analysis results:
|
||||
- Aggregate multiple analysis results before proposing solutions
|
||||
|
||||
### CLI Auto-Invoke Triggers
|
||||
- **Reference**: See `cli-tools-usage.md` → [Auto-Invoke Triggers](#auto-invoke-triggers) for full specification
|
||||
- **Key scenarios**: Self-repair fails, ambiguous requirements, architecture decisions, pattern uncertainty, critical code paths
|
||||
- **Principles**: Default `--mode analysis`, no confirmation needed, wait for completion, flexible rule selection
|
||||
|
||||
## Code Diagnostics
|
||||
|
||||
- **Prefer `mcp__ide__getDiagnostics`** for code error checking over shell-based TypeScript compilation
|
||||
|
||||
366
.claude/TYPESCRIPT_LSP_SETUP.md
Normal file
366
.claude/TYPESCRIPT_LSP_SETUP.md
Normal file
@@ -0,0 +1,366 @@
|
||||
# Claude Code TypeScript LSP 配置指南
|
||||
|
||||
> 更新日期: 2026-01-20
|
||||
> 适用版本: Claude Code v2.0.74+
|
||||
|
||||
---
|
||||
|
||||
## 目录
|
||||
|
||||
1. [方式一:插件市场(推荐)](#方式一插件市场推荐)
|
||||
2. [方式二:MCP Server (cclsp)](#方式二mcp-server-cclsp)
|
||||
3. [方式三:内置LSP工具](#方式三内置lsp工具)
|
||||
4. [配置验证](#配置验证)
|
||||
5. [故障排查](#故障排查)
|
||||
|
||||
---
|
||||
|
||||
## 方式一:插件市场(推荐)
|
||||
|
||||
### 步骤 1: 添加插件市场
|
||||
|
||||
在Claude Code中执行:
|
||||
|
||||
```bash
|
||||
/plugin marketplace add boostvolt/claude-code-lsps
|
||||
```
|
||||
|
||||
### 步骤 2: 安装TypeScript LSP插件
|
||||
|
||||
```bash
|
||||
# TypeScript/JavaScript支持(推荐vtsls)
|
||||
/plugin install vtsls@claude-code-lsps
|
||||
```
|
||||
|
||||
### 步骤 3: 验证安装
|
||||
|
||||
```bash
|
||||
/plugin list
|
||||
```
|
||||
|
||||
应该看到:
|
||||
```
|
||||
✓ vtsls@claude-code-lsps (enabled)
|
||||
✓ pyright-lsp@claude-plugins-official (enabled)
|
||||
```
|
||||
|
||||
### 配置文件自动更新
|
||||
|
||||
安装后,`~/.claude/settings.json` 会自动添加:
|
||||
|
||||
```json
|
||||
{
|
||||
"enabledPlugins": {
|
||||
"pyright-lsp@claude-plugins-official": true,
|
||||
"vtsls@claude-code-lsps": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 支持的操作
|
||||
|
||||
- `goToDefinition` - 跳转到定义
|
||||
- `findReferences` - 查找引用
|
||||
- `hover` - 显示类型信息
|
||||
- `documentSymbol` - 文档符号
|
||||
- `getDiagnostics` - 诊断信息
|
||||
|
||||
---
|
||||
|
||||
## 方式二:MCP Server (cclsp)
|
||||
|
||||
### 优势
|
||||
|
||||
- **位置容错**:自动修正AI生成的不精确行号
|
||||
- **更多功能**:支持重命名、完整诊断
|
||||
- **灵活配置**:完全自定义LSP服务器
|
||||
|
||||
### 安装步骤
|
||||
|
||||
#### 1. 安装TypeScript Language Server
|
||||
|
||||
```bash
|
||||
npm install -g typescript-language-server typescript
|
||||
```
|
||||
|
||||
验证安装:
|
||||
```bash
|
||||
typescript-language-server --version
|
||||
```
|
||||
|
||||
#### 2. 配置cclsp
|
||||
|
||||
运行自动配置:
|
||||
```bash
|
||||
npx cclsp@latest setup --user
|
||||
```
|
||||
|
||||
或手动创建配置文件:
|
||||
|
||||
**文件位置**: `~/.claude/cclsp.json` 或 `~/.config/claude/cclsp.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"servers": [
|
||||
{
|
||||
"extensions": ["ts", "tsx", "js", "jsx"],
|
||||
"command": ["typescript-language-server", "--stdio"],
|
||||
"rootDir": ".",
|
||||
"restartInterval": 5,
|
||||
"initializationOptions": {
|
||||
"preferences": {
|
||||
"includeInlayParameterNameHints": "all",
|
||||
"includeInlayPropertyDeclarationTypeHints": true,
|
||||
"includeInlayFunctionParameterTypeHints": true,
|
||||
"includeInlayVariableTypeHints": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"extensions": ["py", "pyi"],
|
||||
"command": ["pylsp"],
|
||||
"rootDir": ".",
|
||||
"restartInterval": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### 3. 在Claude Code中启用MCP Server
|
||||
|
||||
添加到Claude Code配置:
|
||||
|
||||
```bash
|
||||
# 查看当前MCP配置
|
||||
cat ~/.claude/.mcp.json
|
||||
|
||||
# 如果没有,创建新的
|
||||
```
|
||||
|
||||
**文件**: `~/.claude/.mcp.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"cclsp": {
|
||||
"command": "npx",
|
||||
"args": ["cclsp@latest"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### cclsp可用的MCP工具
|
||||
|
||||
使用时,Claude Code会自动调用这些工具:
|
||||
|
||||
- `find_definition` - 按名称查找定义(支持模糊匹配)
|
||||
- `find_references` - 查找所有引用
|
||||
- `rename_symbol` - 重命名符号(带备份)
|
||||
- `get_diagnostics` - 获取诊断信息
|
||||
- `restart_server` - 重启LSP服务器
|
||||
|
||||
---
|
||||
|
||||
## 方式三:内置LSP工具
|
||||
|
||||
### 启用方式
|
||||
|
||||
设置环境变量:
|
||||
|
||||
**Linux/Mac**:
|
||||
```bash
|
||||
export ENABLE_LSP_TOOL=1
|
||||
claude
|
||||
```
|
||||
|
||||
**Windows (PowerShell)**:
|
||||
```powershell
|
||||
$env:ENABLE_LSP_TOOL=1
|
||||
claude
|
||||
```
|
||||
|
||||
**永久启用** (添加到shell配置):
|
||||
```bash
|
||||
# Linux/Mac
|
||||
echo 'export ENABLE_LSP_TOOL=1' >> ~/.bashrc
|
||||
source ~/.bashrc
|
||||
|
||||
# Windows (PowerShell Profile)
|
||||
Add-Content $PROFILE '$env:ENABLE_LSP_TOOL=1'
|
||||
```
|
||||
|
||||
### 限制
|
||||
|
||||
- 需要先安装语言服务器插件(见方式一)
|
||||
- 不支持重命名等高级操作
|
||||
- 无位置容错功能
|
||||
|
||||
---
|
||||
|
||||
## 配置验证
|
||||
|
||||
### 1. 检查LSP服务器是否可用
|
||||
|
||||
```bash
|
||||
# 检查TypeScript Language Server
|
||||
which typescript-language-server # Linux/Mac
|
||||
where typescript-language-server # Windows
|
||||
|
||||
# 测试运行
|
||||
typescript-language-server --stdio
|
||||
```
|
||||
|
||||
### 2. 在Claude Code中测试
|
||||
|
||||
打开任意TypeScript文件,让Claude执行:
|
||||
|
||||
```typescript
|
||||
// 测试LSP功能
|
||||
LSP({
|
||||
operation: "hover",
|
||||
filePath: "path/to/your/file.ts",
|
||||
line: 10,
|
||||
character: 5
|
||||
})
|
||||
```
|
||||
|
||||
### 3. 检查插件状态
|
||||
|
||||
```bash
|
||||
/plugin list
|
||||
```
|
||||
|
||||
查看启用的插件:
|
||||
```bash
|
||||
cat ~/.claude/settings.json | grep enabledPlugins
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 故障排查
|
||||
|
||||
### 问题 1: "No LSP server available"
|
||||
|
||||
**原因**:TypeScript LSP插件未安装或未启用
|
||||
|
||||
**解决**:
|
||||
```bash
|
||||
# 重新安装插件
|
||||
/plugin install vtsls@claude-code-lsps
|
||||
|
||||
# 检查settings.json
|
||||
cat ~/.claude/settings.json
|
||||
```
|
||||
|
||||
### 问题 2: "typescript-language-server: command not found"
|
||||
|
||||
**原因**:未安装TypeScript Language Server
|
||||
|
||||
**解决**:
|
||||
```bash
|
||||
npm install -g typescript-language-server typescript
|
||||
|
||||
# 验证
|
||||
typescript-language-server --version
|
||||
```
|
||||
|
||||
### 问题 3: LSP响应慢或超时
|
||||
|
||||
**原因**:项目太大或配置不当
|
||||
|
||||
**解决**:
|
||||
```json
|
||||
// 在tsconfig.json中优化
|
||||
{
|
||||
"compilerOptions": {
|
||||
"incremental": true,
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
```
|
||||
|
||||
### 问题 4: 插件安装失败
|
||||
|
||||
**原因**:网络问题或插件市场未添加
|
||||
|
||||
**解决**:
|
||||
```bash
|
||||
# 确认插件市场已添加
|
||||
/plugin marketplace list
|
||||
|
||||
# 如果没有,重新添加
|
||||
/plugin marketplace add boostvolt/claude-code-lsps
|
||||
|
||||
# 重试安装
|
||||
/plugin install vtsls@claude-code-lsps
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 三种方式对比
|
||||
|
||||
| 特性 | 插件市场 | cclsp (MCP) | 内置LSP |
|
||||
|------|----------|-------------|---------|
|
||||
| 安装复杂度 | ⭐ 低 | ⭐⭐ 中 | ⭐ 低 |
|
||||
| 功能完整性 | ⭐⭐⭐ 完整 | ⭐⭐⭐ 完整+ | ⭐⭐ 基础 |
|
||||
| 位置容错 | ❌ 无 | ✅ 有 | ❌ 无 |
|
||||
| 重命名支持 | ✅ 有 | ✅ 有 | ❌ 无 |
|
||||
| 自定义配置 | ⚙️ 有限 | ⚙️ 完整 | ❌ 无 |
|
||||
| 生产稳定性 | ⭐⭐⭐ 高 | ⭐⭐ 中 | ⭐⭐⭐ 高 |
|
||||
|
||||
---
|
||||
|
||||
## 推荐配置
|
||||
|
||||
### 新手用户
|
||||
**推荐**: 方式一(插件市场)
|
||||
- 一条命令安装
|
||||
- 官方维护,稳定可靠
|
||||
- 满足日常使用需求
|
||||
|
||||
### 高级用户
|
||||
**推荐**: 方式二(cclsp)
|
||||
- 完整功能支持
|
||||
- 位置容错(AI友好)
|
||||
- 灵活配置
|
||||
- 支持重命名等高级操作
|
||||
|
||||
### 快速测试
|
||||
**推荐**: 方式三(内置LSP)+ 方式一(插件)
|
||||
- 设置环境变量
|
||||
- 安装插件
|
||||
- 立即可用
|
||||
|
||||
---
|
||||
|
||||
## 附录:支持的语言
|
||||
|
||||
通过插件市场可用的LSP:
|
||||
|
||||
| 语言 | 插件名 | 安装命令 |
|
||||
|------|--------|----------|
|
||||
| TypeScript/JavaScript | vtsls | `/plugin install vtsls@claude-code-lsps` |
|
||||
| Python | pyright | `/plugin install pyright@claude-code-lsps` |
|
||||
| Go | gopls | `/plugin install gopls@claude-code-lsps` |
|
||||
| Rust | rust-analyzer | `/plugin install rust-analyzer@claude-code-lsps` |
|
||||
| Java | jdtls | `/plugin install jdtls@claude-code-lsps` |
|
||||
| C/C++ | clangd | `/plugin install clangd@claude-code-lsps` |
|
||||
| C# | omnisharp | `/plugin install omnisharp@claude-code-lsps` |
|
||||
| PHP | intelephense | `/plugin install intelephense@claude-code-lsps` |
|
||||
| Kotlin | kotlin-ls | `/plugin install kotlin-language-server@claude-code-lsps` |
|
||||
| Ruby | solargraph | `/plugin install solargraph@claude-code-lsps` |
|
||||
|
||||
---
|
||||
|
||||
## 相关文档
|
||||
|
||||
- [Claude Code LSP 文档](https://docs.anthropic.com/claude-code/lsp)
|
||||
- [cclsp GitHub](https://github.com/ktnyt/cclsp)
|
||||
- [TypeScript Language Server](https://github.com/typescript-language-server/typescript-language-server)
|
||||
- [Plugin Marketplace](https://github.com/boostvolt/claude-code-lsps)
|
||||
|
||||
---
|
||||
|
||||
**配置完成后,重启Claude Code以应用更改**
|
||||
@@ -215,7 +215,7 @@ CONTEXT: @**/* | Memory: {ace_context_summary}
|
||||
|
||||
EXPECTED: JSON with feasibility_score, findings, implementation_approaches, technical_concerns, code_locations
|
||||
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md) |
|
||||
CONSTRAINTS:
|
||||
- Specific file:line references
|
||||
- Quantify effort estimates
|
||||
- Concrete pros/cons
|
||||
|
||||
@@ -61,6 +61,29 @@ Score = 0
|
||||
|
||||
**Extract Keywords**: domains (auth, api, database, ui), technologies (react, typescript, node), actions (implement, refactor, test)
|
||||
|
||||
**Plan Context Loading** (when executing from plan.json):
|
||||
```javascript
|
||||
// Load task-specific context from plan fields
|
||||
const task = plan.tasks.find(t => t.id === taskId)
|
||||
const context = {
|
||||
// Base context
|
||||
scope: task.scope,
|
||||
modification_points: task.modification_points,
|
||||
implementation: task.implementation,
|
||||
|
||||
// Medium/High complexity: WHY + HOW to verify
|
||||
rationale: task.rationale?.chosen_approach, // Why this approach
|
||||
verification: task.verification?.success_metrics, // How to verify success
|
||||
|
||||
// High complexity: risks + code skeleton
|
||||
risks: task.risks?.map(r => r.mitigation), // Risk mitigations to follow
|
||||
code_skeleton: task.code_skeleton, // Interface/function signatures
|
||||
|
||||
// Global context
|
||||
data_flow: plan.data_flow?.diagram // Data flow overview
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Context Discovery
|
||||
@@ -114,9 +137,10 @@ plan → planning/architecture-planning.txt | planning/task-breakdown.txt
|
||||
bug-fix → development/bug-diagnosis.txt
|
||||
```
|
||||
|
||||
**3. RULES Field**:
|
||||
- Use `$(cat ~/.claude/workflows/cli-templates/prompts/{path}.txt)` directly
|
||||
- NEVER escape: `\$`, `\"`, `\'` breaks command substitution
|
||||
**3. CONSTRAINTS Field**:
|
||||
- Use `--rule <template>` option to auto-load protocol + template (appended to prompt)
|
||||
- Template names: `category-function` format (e.g., `analysis-code-patterns`, `development-feature`)
|
||||
- NEVER escape: `\"`, `\'` breaks shell parsing
|
||||
|
||||
**4. Structured Prompt**:
|
||||
```bash
|
||||
@@ -125,7 +149,31 @@ TASK: {specific_task_with_details}
|
||||
MODE: {analysis|write|auto}
|
||||
CONTEXT: {structured_file_references}
|
||||
EXPECTED: {clear_output_expectations}
|
||||
RULES: $(cat {selected_template}) | {constraints}
|
||||
CONSTRAINTS: {constraints}
|
||||
```
|
||||
|
||||
**5. Plan-Aware Prompt Enhancement** (when executing from plan.json):
|
||||
```bash
|
||||
# Include rationale in PURPOSE (Medium/High)
|
||||
PURPOSE: {task.description}
|
||||
Approach: {task.rationale.chosen_approach}
|
||||
Decision factors: {task.rationale.decision_factors.join(', ')}
|
||||
|
||||
# Include code skeleton in TASK (High)
|
||||
TASK: {task.implementation.join('\n')}
|
||||
Key interfaces: {task.code_skeleton.interfaces.map(i => i.signature)}
|
||||
Key functions: {task.code_skeleton.key_functions.map(f => f.signature)}
|
||||
|
||||
# Include verification in EXPECTED
|
||||
EXPECTED: {task.acceptance.join(', ')}
|
||||
Success metrics: {task.verification.success_metrics.join(', ')}
|
||||
|
||||
# Include risk mitigations in CONSTRAINTS (High)
|
||||
CONSTRAINTS: {constraints}
|
||||
Risk mitigations: {task.risks.map(r => r.mitigation).join('; ')}
|
||||
|
||||
# Include data flow context (High)
|
||||
Memory: Data flow: {plan.data_flow.diagram}
|
||||
```
|
||||
|
||||
---
|
||||
@@ -156,8 +204,8 @@ TASK: {task}
|
||||
MODE: analysis
|
||||
CONTEXT: @**/*
|
||||
EXPECTED: {output}
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt)
|
||||
" --tool gemini --mode analysis --cd {dir}
|
||||
CONSTRAINTS: {constraints}
|
||||
" --tool gemini --mode analysis --rule analysis-code-patterns --cd {dir}
|
||||
|
||||
# Qwen fallback: Replace '--tool gemini' with '--tool qwen'
|
||||
```
|
||||
@@ -204,11 +252,25 @@ find .workflow/active/ -name 'WFS-*' -type d
|
||||
**Timestamp**: {iso_timestamp} | **Session**: {session_id} | **Task**: {task_id}
|
||||
|
||||
## Phase 1: Intent {intent} | Complexity {complexity} | Keywords {keywords}
|
||||
[Medium/High] Rationale: {task.rationale.chosen_approach}
|
||||
[High] Risks: {task.risks.map(r => `${r.description} → ${r.mitigation}`).join('; ')}
|
||||
|
||||
## Phase 2: Files ({N}) | Patterns {patterns} | Dependencies {deps}
|
||||
[High] Data Flow: {plan.data_flow.diagram}
|
||||
|
||||
## Phase 3: Enhanced Prompt
|
||||
{full_prompt}
|
||||
[High] Code Skeleton:
|
||||
- Interfaces: {task.code_skeleton.interfaces.map(i => i.name).join(', ')}
|
||||
- Functions: {task.code_skeleton.key_functions.map(f => f.signature).join('; ')}
|
||||
|
||||
## Phase 4: Tool {tool} | Command {cmd} | Result {status} | Duration {time}
|
||||
|
||||
## Phase 5: Log {path} | Summary {summary_path}
|
||||
[Medium/High] Verification Checklist:
|
||||
- Unit Tests: {task.verification.unit_tests.join(', ')}
|
||||
- Success Metrics: {task.verification.success_metrics.join(', ')}
|
||||
|
||||
## Next Steps: {actions}
|
||||
```
|
||||
|
||||
|
||||
@@ -77,6 +77,8 @@ Phase 4: planObject Generation
|
||||
|
||||
## CLI Command Template
|
||||
|
||||
### Base Template (All Complexity Levels)
|
||||
|
||||
```bash
|
||||
ccw cli -p "
|
||||
PURPOSE: Generate plan for {task_description}
|
||||
@@ -84,12 +86,18 @@ TASK:
|
||||
• Analyze task/bug description and context
|
||||
• Break down into tasks following schema structure
|
||||
• Identify dependencies and execution phases
|
||||
• Generate complexity-appropriate fields (rationale, verification, risks, code_skeleton, data_flow)
|
||||
MODE: analysis
|
||||
CONTEXT: @**/* | Memory: {context_summary}
|
||||
EXPECTED:
|
||||
## Summary
|
||||
[overview]
|
||||
|
||||
## Approach
|
||||
[high-level strategy]
|
||||
|
||||
## Complexity: {Low|Medium|High}
|
||||
|
||||
## Task Breakdown
|
||||
### T1: [Title] (or FIX1 for fix-plan)
|
||||
**Scope**: [module/feature path]
|
||||
@@ -97,17 +105,54 @@ EXPECTED:
|
||||
**Description**: [what]
|
||||
**Modification Points**: - [file]: [target] - [change]
|
||||
**Implementation**: 1. [step]
|
||||
**Acceptance/Verification**: - [quantified criterion]
|
||||
**Reference**: - Pattern: [pattern] - Files: [files] - Examples: [guidance]
|
||||
**Acceptance**: - [quantified criterion]
|
||||
**Depends On**: []
|
||||
|
||||
[MEDIUM/HIGH COMPLEXITY ONLY]
|
||||
**Rationale**:
|
||||
- Chosen Approach: [why this approach]
|
||||
- Alternatives Considered: [other options]
|
||||
- Decision Factors: [key factors]
|
||||
- Tradeoffs: [known tradeoffs]
|
||||
|
||||
**Verification**:
|
||||
- Unit Tests: [test names]
|
||||
- Integration Tests: [test names]
|
||||
- Manual Checks: [specific steps]
|
||||
- Success Metrics: [quantified metrics]
|
||||
|
||||
[HIGH COMPLEXITY ONLY]
|
||||
**Risks**:
|
||||
- Risk: [description] | Probability: [L/M/H] | Impact: [L/M/H] | Mitigation: [strategy] | Fallback: [alternative]
|
||||
|
||||
**Code Skeleton**:
|
||||
- Interfaces: [name]: [definition] - [purpose]
|
||||
- Functions: [signature] - [purpose] - returns [type]
|
||||
- Classes: [name] - [purpose] - methods: [list]
|
||||
|
||||
## Data Flow (HIGH COMPLEXITY ONLY)
|
||||
**Diagram**: [A → B → C]
|
||||
**Stages**:
|
||||
- Stage [name]: Input=[type] → Output=[type] | Component=[module] | Transforms=[list]
|
||||
**Dependencies**: [external deps]
|
||||
|
||||
## Design Decisions (MEDIUM/HIGH)
|
||||
- Decision: [what] | Rationale: [why] | Tradeoff: [what was traded]
|
||||
|
||||
## Flow Control
|
||||
**Execution Order**: - Phase parallel-1: [T1, T2] (independent)
|
||||
**Exit Conditions**: - Success: [condition] - Failure: [condition]
|
||||
|
||||
## Time Estimate
|
||||
**Total**: [time]
|
||||
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/planning/02-breakdown-task-steps.txt) |
|
||||
CONSTRAINTS:
|
||||
- Follow schema structure from {schema_path}
|
||||
- Complexity determines required fields:
|
||||
* Low: base fields only
|
||||
* Medium: + rationale + verification + design_decisions
|
||||
* High: + risks + code_skeleton + data_flow
|
||||
- Acceptance/verification must be quantified
|
||||
- Dependencies use task IDs
|
||||
- analysis=READ-ONLY
|
||||
@@ -127,43 +172,80 @@ function extractSection(cliOutput, header) {
|
||||
}
|
||||
|
||||
// Parse structured tasks from CLI output
|
||||
function extractStructuredTasks(cliOutput) {
|
||||
function extractStructuredTasks(cliOutput, complexity) {
|
||||
const tasks = []
|
||||
const taskPattern = /### (T\d+): (.+?)\n\*\*File\*\*: (.+?)\n\*\*Action\*\*: (.+?)\n\*\*Description\*\*: (.+?)\n\*\*Modification Points\*\*:\n((?:- .+?\n)*)\*\*Implementation\*\*:\n((?:\d+\. .+?\n)+)\*\*Reference\*\*:\n((?:- .+?\n)+)\*\*Acceptance\*\*:\n((?:- .+?\n)+)\*\*Depends On\*\*: (.+)/g
|
||||
// Split by task headers
|
||||
const taskBlocks = cliOutput.split(/### (T\d+):/).slice(1)
|
||||
|
||||
for (let i = 0; i < taskBlocks.length; i += 2) {
|
||||
const taskId = taskBlocks[i].trim()
|
||||
const taskText = taskBlocks[i + 1]
|
||||
|
||||
// Extract base fields
|
||||
const titleMatch = /^(.+?)(?=\n)/.exec(taskText)
|
||||
const scopeMatch = /\*\*Scope\*\*: (.+?)(?=\n)/.exec(taskText)
|
||||
const actionMatch = /\*\*Action\*\*: (.+?)(?=\n)/.exec(taskText)
|
||||
const descMatch = /\*\*Description\*\*: (.+?)(?=\n)/.exec(taskText)
|
||||
const depsMatch = /\*\*Depends On\*\*: (.+?)(?=\n|$)/.exec(taskText)
|
||||
|
||||
let match
|
||||
while ((match = taskPattern.exec(cliOutput)) !== null) {
|
||||
// Parse modification points
|
||||
const modPoints = match[6].trim().split('\n').filter(s => s.startsWith('-')).map(s => {
|
||||
const m = /- \[(.+?)\]: \[(.+?)\] - (.+)/.exec(s)
|
||||
return m ? { file: m[1], target: m[2], change: m[3] } : null
|
||||
}).filter(Boolean)
|
||||
|
||||
// Parse reference
|
||||
const refText = match[8].trim()
|
||||
const reference = {
|
||||
pattern: (/- Pattern: (.+)/m.exec(refText) || [])[1]?.trim() || "No pattern",
|
||||
files: ((/- Files: (.+)/m.exec(refText) || [])[1] || "").split(',').map(f => f.trim()).filter(Boolean),
|
||||
examples: (/- Examples: (.+)/m.exec(refText) || [])[1]?.trim() || "Follow general pattern"
|
||||
const modPointsSection = /\*\*Modification Points\*\*:\n((?:- .+?\n)*)/.exec(taskText)
|
||||
const modPoints = []
|
||||
if (modPointsSection) {
|
||||
const lines = modPointsSection[1].split('\n').filter(s => s.trim().startsWith('-'))
|
||||
lines.forEach(line => {
|
||||
const m = /- \[(.+?)\]: \[(.+?)\] - (.+)/.exec(line)
|
||||
if (m) modPoints.push({ file: m[1].trim(), target: m[2].trim(), change: m[3].trim() })
|
||||
})
|
||||
}
|
||||
|
||||
// Parse depends_on
|
||||
const depsText = match[10].trim()
|
||||
const depends_on = depsText === '[]' ? [] : depsText.replace(/[\[\]]/g, '').split(',').map(s => s.trim()).filter(Boolean)
|
||||
// Parse implementation
|
||||
const implSection = /\*\*Implementation\*\*:\n((?:\d+\. .+?\n)+)/.exec(taskText)
|
||||
const implementation = implSection
|
||||
? implSection[1].split('\n').map(s => s.replace(/^\d+\. /, '').trim()).filter(Boolean)
|
||||
: []
|
||||
|
||||
tasks.push({
|
||||
id: match[1].trim(),
|
||||
title: match[2].trim(),
|
||||
file: match[3].trim(),
|
||||
action: match[4].trim(),
|
||||
description: match[5].trim(),
|
||||
// Parse reference
|
||||
const refSection = /\*\*Reference\*\*:\n((?:- .+?\n)+)/.exec(taskText)
|
||||
const reference = refSection ? {
|
||||
pattern: (/- Pattern: (.+)/m.exec(refSection[1]) || [])[1]?.trim() || "No pattern",
|
||||
files: ((/- Files: (.+)/m.exec(refSection[1]) || [])[1] || "").split(',').map(f => f.trim()).filter(Boolean),
|
||||
examples: (/- Examples: (.+)/m.exec(refSection[1]) || [])[1]?.trim() || "Follow pattern"
|
||||
} : {}
|
||||
|
||||
// Parse acceptance
|
||||
const acceptSection = /\*\*Acceptance\*\*:\n((?:- .+?\n)+)/.exec(taskText)
|
||||
const acceptance = acceptSection
|
||||
? acceptSection[1].split('\n').map(s => s.replace(/^- /, '').trim()).filter(Boolean)
|
||||
: []
|
||||
|
||||
const task = {
|
||||
id: taskId,
|
||||
title: titleMatch?.[1].trim() || "Untitled",
|
||||
scope: scopeMatch?.[1].trim() || "",
|
||||
action: actionMatch?.[1].trim() || "Implement",
|
||||
description: descMatch?.[1].trim() || "",
|
||||
modification_points: modPoints,
|
||||
implementation: match[7].trim().split('\n').map(s => s.replace(/^\d+\. /, '')).filter(Boolean),
|
||||
implementation,
|
||||
reference,
|
||||
acceptance: match[9].trim().split('\n').map(s => s.replace(/^- /, '')).filter(Boolean),
|
||||
depends_on
|
||||
})
|
||||
acceptance,
|
||||
depends_on: depsMatch?.[1] === '[]' ? [] : (depsMatch?.[1] || "").replace(/[\[\]]/g, '').split(',').map(s => s.trim()).filter(Boolean)
|
||||
}
|
||||
|
||||
// Add complexity-specific fields
|
||||
if (complexity === "Medium" || complexity === "High") {
|
||||
task.rationale = extractRationale(taskText)
|
||||
task.verification = extractVerification(taskText)
|
||||
}
|
||||
|
||||
if (complexity === "High") {
|
||||
task.risks = extractRisks(taskText)
|
||||
task.code_skeleton = extractCodeSkeleton(taskText)
|
||||
}
|
||||
|
||||
tasks.push(task)
|
||||
}
|
||||
|
||||
return tasks
|
||||
}
|
||||
|
||||
@@ -186,14 +268,155 @@ function extractFlowControl(cliOutput) {
|
||||
}
|
||||
}
|
||||
|
||||
// Parse rationale section for a task
|
||||
function extractRationale(taskText) {
|
||||
const rationaleMatch = /\*\*Rationale\*\*:\n- Chosen Approach: (.+?)\n- Alternatives Considered: (.+?)\n- Decision Factors: (.+?)\n- Tradeoffs: (.+)/s.exec(taskText)
|
||||
if (!rationaleMatch) return null
|
||||
|
||||
return {
|
||||
chosen_approach: rationaleMatch[1].trim(),
|
||||
alternatives_considered: rationaleMatch[2].split(',').map(s => s.trim()).filter(Boolean),
|
||||
decision_factors: rationaleMatch[3].split(',').map(s => s.trim()).filter(Boolean),
|
||||
tradeoffs: rationaleMatch[4].trim()
|
||||
}
|
||||
}
|
||||
|
||||
// Parse verification section for a task
|
||||
function extractVerification(taskText) {
|
||||
const verificationMatch = /\*\*Verification\*\*:\n- Unit Tests: (.+?)\n- Integration Tests: (.+?)\n- Manual Checks: (.+?)\n- Success Metrics: (.+)/s.exec(taskText)
|
||||
if (!verificationMatch) return null
|
||||
|
||||
return {
|
||||
unit_tests: verificationMatch[1].split(',').map(s => s.trim()).filter(Boolean),
|
||||
integration_tests: verificationMatch[2].split(',').map(s => s.trim()).filter(Boolean),
|
||||
manual_checks: verificationMatch[3].split(',').map(s => s.trim()).filter(Boolean),
|
||||
success_metrics: verificationMatch[4].split(',').map(s => s.trim()).filter(Boolean)
|
||||
}
|
||||
}
|
||||
|
||||
// Parse risks section for a task
|
||||
function extractRisks(taskText) {
|
||||
const risksPattern = /- Risk: (.+?) \| Probability: ([LMH]) \| Impact: ([LMH]) \| Mitigation: (.+?)(?: \| Fallback: (.+?))?(?=\n|$)/g
|
||||
const risks = []
|
||||
let match
|
||||
|
||||
while ((match = risksPattern.exec(taskText)) !== null) {
|
||||
risks.push({
|
||||
description: match[1].trim(),
|
||||
probability: match[2] === 'L' ? 'Low' : match[2] === 'M' ? 'Medium' : 'High',
|
||||
impact: match[3] === 'L' ? 'Low' : match[3] === 'M' ? 'Medium' : 'High',
|
||||
mitigation: match[4].trim(),
|
||||
fallback: match[5]?.trim() || undefined
|
||||
})
|
||||
}
|
||||
|
||||
return risks.length > 0 ? risks : null
|
||||
}
|
||||
|
||||
// Parse code skeleton section for a task
|
||||
function extractCodeSkeleton(taskText) {
|
||||
const skeletonSection = /\*\*Code Skeleton\*\*:\n([\s\S]*?)(?=\n\*\*|$)/.exec(taskText)
|
||||
if (!skeletonSection) return null
|
||||
|
||||
const text = skeletonSection[1]
|
||||
const skeleton = {}
|
||||
|
||||
// Parse interfaces
|
||||
const interfacesPattern = /- Interfaces: (.+?): (.+?) - (.+?)(?=\n|$)/g
|
||||
const interfaces = []
|
||||
let match
|
||||
while ((match = interfacesPattern.exec(text)) !== null) {
|
||||
interfaces.push({ name: match[1].trim(), definition: match[2].trim(), purpose: match[3].trim() })
|
||||
}
|
||||
if (interfaces.length > 0) skeleton.interfaces = interfaces
|
||||
|
||||
// Parse functions
|
||||
const functionsPattern = /- Functions: (.+?) - (.+?) - returns (.+?)(?=\n|$)/g
|
||||
const functions = []
|
||||
while ((match = functionsPattern.exec(text)) !== null) {
|
||||
functions.push({ signature: match[1].trim(), purpose: match[2].trim(), returns: match[3].trim() })
|
||||
}
|
||||
if (functions.length > 0) skeleton.key_functions = functions
|
||||
|
||||
// Parse classes
|
||||
const classesPattern = /- Classes: (.+?) - (.+?) - methods: (.+?)(?=\n|$)/g
|
||||
const classes = []
|
||||
while ((match = classesPattern.exec(text)) !== null) {
|
||||
classes.push({
|
||||
name: match[1].trim(),
|
||||
purpose: match[2].trim(),
|
||||
methods: match[3].split(',').map(s => s.trim()).filter(Boolean)
|
||||
})
|
||||
}
|
||||
if (classes.length > 0) skeleton.classes = classes
|
||||
|
||||
return Object.keys(skeleton).length > 0 ? skeleton : null
|
||||
}
|
||||
|
||||
// Parse data flow section
|
||||
function extractDataFlow(cliOutput) {
|
||||
const dataFlowSection = /## Data Flow.*?\n([\s\S]*?)(?=\n## |$)/.exec(cliOutput)
|
||||
if (!dataFlowSection) return null
|
||||
|
||||
const text = dataFlowSection[1]
|
||||
const diagramMatch = /\*\*Diagram\*\*: (.+?)(?=\n|$)/.exec(text)
|
||||
const depsMatch = /\*\*Dependencies\*\*: (.+?)(?=\n|$)/.exec(text)
|
||||
|
||||
// Parse stages
|
||||
const stagesPattern = /- Stage (.+?): Input=(.+?) → Output=(.+?) \| Component=(.+?)(?: \| Transforms=(.+?))?(?=\n|$)/g
|
||||
const stages = []
|
||||
let match
|
||||
while ((match = stagesPattern.exec(text)) !== null) {
|
||||
stages.push({
|
||||
stage: match[1].trim(),
|
||||
input: match[2].trim(),
|
||||
output: match[3].trim(),
|
||||
component: match[4].trim(),
|
||||
transformations: match[5] ? match[5].split(',').map(s => s.trim()).filter(Boolean) : undefined
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
diagram: diagramMatch?.[1].trim() || null,
|
||||
stages: stages.length > 0 ? stages : undefined,
|
||||
dependencies: depsMatch ? depsMatch[1].split(',').map(s => s.trim()).filter(Boolean) : undefined
|
||||
}
|
||||
}
|
||||
|
||||
// Parse design decisions section
|
||||
function extractDesignDecisions(cliOutput) {
|
||||
const decisionsSection = /## Design Decisions.*?\n([\s\S]*?)(?=\n## |$)/.exec(cliOutput)
|
||||
if (!decisionsSection) return null
|
||||
|
||||
const decisionsPattern = /- Decision: (.+?) \| Rationale: (.+?)(?: \| Tradeoff: (.+?))?(?=\n|$)/g
|
||||
const decisions = []
|
||||
let match
|
||||
|
||||
while ((match = decisionsPattern.exec(decisionsSection[1])) !== null) {
|
||||
decisions.push({
|
||||
decision: match[1].trim(),
|
||||
rationale: match[2].trim(),
|
||||
tradeoff: match[3]?.trim() || undefined
|
||||
})
|
||||
}
|
||||
|
||||
return decisions.length > 0 ? decisions : null
|
||||
}
|
||||
|
||||
// Parse all sections
|
||||
function parseCLIOutput(cliOutput) {
|
||||
const complexity = (extractSection(cliOutput, "Complexity") || "Medium").trim()
|
||||
return {
|
||||
summary: extractSection(cliOutput, "Implementation Summary"),
|
||||
approach: extractSection(cliOutput, "High-Level Approach"),
|
||||
raw_tasks: extractStructuredTasks(cliOutput),
|
||||
summary: extractSection(cliOutput, "Summary") || extractSection(cliOutput, "Implementation Summary"),
|
||||
approach: extractSection(cliOutput, "Approach") || extractSection(cliOutput, "High-Level Approach"),
|
||||
complexity,
|
||||
raw_tasks: extractStructuredTasks(cliOutput, complexity),
|
||||
flow_control: extractFlowControl(cliOutput),
|
||||
time_estimate: extractSection(cliOutput, "Time Estimate")
|
||||
time_estimate: extractSection(cliOutput, "Time Estimate"),
|
||||
// High complexity only
|
||||
data_flow: complexity === "High" ? extractDataFlow(cliOutput) : null,
|
||||
// Medium/High complexity
|
||||
design_decisions: (complexity === "Medium" || complexity === "High") ? extractDesignDecisions(cliOutput) : null
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -326,7 +549,8 @@ function inferFlowControl(tasks) {
|
||||
|
||||
```javascript
|
||||
function generatePlanObject(parsed, enrichedContext, input, schemaType) {
|
||||
const tasks = validateAndEnhanceTasks(parsed.raw_tasks, enrichedContext)
|
||||
const complexity = parsed.complexity || input.complexity || "Medium"
|
||||
const tasks = validateAndEnhanceTasks(parsed.raw_tasks, enrichedContext, complexity)
|
||||
assignCliExecutionIds(tasks, input.session.id) // MANDATORY: Assign CLI execution IDs
|
||||
const flow_control = parsed.flow_control?.execution_order?.length > 0 ? parsed.flow_control : inferFlowControl(tasks)
|
||||
const focus_paths = [...new Set(tasks.flatMap(t => [t.file || t.scope, ...t.modification_points.map(m => m.file)]).filter(Boolean))]
|
||||
@@ -338,7 +562,7 @@ function generatePlanObject(parsed, enrichedContext, input, schemaType) {
|
||||
flow_control,
|
||||
focus_paths,
|
||||
estimated_time: parsed.time_estimate || `${tasks.length * 30} minutes`,
|
||||
recommended_execution: (input.complexity === "Low" || input.severity === "Low") ? "Agent" : "Codex",
|
||||
recommended_execution: (complexity === "Low" || input.severity === "Low") ? "Agent" : "Codex",
|
||||
_metadata: {
|
||||
timestamp: new Date().toISOString(),
|
||||
source: "cli-lite-planning-agent",
|
||||
@@ -348,6 +572,15 @@ function generatePlanObject(parsed, enrichedContext, input, schemaType) {
|
||||
}
|
||||
}
|
||||
|
||||
// Add complexity-specific top-level fields
|
||||
if (complexity === "Medium" || complexity === "High") {
|
||||
base.design_decisions = parsed.design_decisions || []
|
||||
}
|
||||
|
||||
if (complexity === "High") {
|
||||
base.data_flow = parsed.data_flow || null
|
||||
}
|
||||
|
||||
// Schema-specific fields
|
||||
if (schemaType === 'fix-plan') {
|
||||
return {
|
||||
@@ -361,10 +594,63 @@ function generatePlanObject(parsed, enrichedContext, input, schemaType) {
|
||||
return {
|
||||
...base,
|
||||
approach: parsed.approach || "Step-by-step implementation",
|
||||
complexity: input.complexity || "Medium"
|
||||
complexity
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Enhanced task validation with complexity-specific fields
|
||||
function validateAndEnhanceTasks(rawTasks, enrichedContext, complexity) {
|
||||
return rawTasks.map((task, idx) => {
|
||||
const enhanced = {
|
||||
id: task.id || `T${idx + 1}`,
|
||||
title: task.title || "Unnamed task",
|
||||
scope: task.scope || task.file || inferFile(task, enrichedContext),
|
||||
action: task.action || inferAction(task.title),
|
||||
description: task.description || task.title,
|
||||
modification_points: task.modification_points?.length > 0
|
||||
? task.modification_points
|
||||
: [{ file: task.scope || task.file, target: "main", change: task.description }],
|
||||
implementation: task.implementation?.length >= 2
|
||||
? task.implementation
|
||||
: [`Analyze ${task.scope || task.file}`, `Implement ${task.title}`, `Add error handling`],
|
||||
reference: task.reference || { pattern: "existing patterns", files: enrichedContext.relevant_files.slice(0, 2), examples: "Follow existing structure" },
|
||||
acceptance: task.acceptance?.length >= 1
|
||||
? task.acceptance
|
||||
: [`${task.title} completed`, `Follows conventions`],
|
||||
depends_on: task.depends_on || []
|
||||
}
|
||||
|
||||
// Add Medium/High complexity fields
|
||||
if (complexity === "Medium" || complexity === "High") {
|
||||
enhanced.rationale = task.rationale || {
|
||||
chosen_approach: "Standard implementation approach",
|
||||
alternatives_considered: [],
|
||||
decision_factors: ["Maintainability", "Performance"],
|
||||
tradeoffs: "None significant"
|
||||
}
|
||||
enhanced.verification = task.verification || {
|
||||
unit_tests: [`test_${task.id.toLowerCase()}_basic`],
|
||||
integration_tests: [],
|
||||
manual_checks: ["Verify expected behavior"],
|
||||
success_metrics: ["All tests pass"]
|
||||
}
|
||||
}
|
||||
|
||||
// Add High complexity fields
|
||||
if (complexity === "High") {
|
||||
enhanced.risks = task.risks || [{
|
||||
description: "Implementation complexity",
|
||||
probability: "Low",
|
||||
impact: "Medium",
|
||||
mitigation: "Incremental development with checkpoints"
|
||||
}]
|
||||
enhanced.code_skeleton = task.code_skeleton || null
|
||||
}
|
||||
|
||||
return enhanced
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
@@ -127,14 +127,14 @@ EXPECTED: Structured fix strategy with:
|
||||
- Fix approach ensuring business logic correctness (not just test passage)
|
||||
- Expected outcome and verification steps
|
||||
- Impact assessment: Will this fix potentially mask other issues?
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/{template}) |
|
||||
CONSTRAINTS:
|
||||
- For {test_type} tests: {layer_specific_guidance}
|
||||
- Avoid 'surgical fixes' that mask underlying issues
|
||||
- Provide specific line numbers for modifications
|
||||
- Consider previous iteration failures
|
||||
- Validate fix doesn't introduce new vulnerabilities
|
||||
- analysis=READ-ONLY
|
||||
" --tool {cli_tool} --mode analysis --cd {project_root} --timeout {timeout_value}
|
||||
" --tool {cli_tool} --mode analysis --rule {template} --cd {project_root} --timeout {timeout_value}
|
||||
```
|
||||
|
||||
**Layer-Specific Guidance Injection**:
|
||||
|
||||
@@ -385,8 +385,12 @@ Before completing any task, verify:
|
||||
- Make assumptions - verify with existing code
|
||||
- Create unnecessary complexity
|
||||
|
||||
**Bash Tool**:
|
||||
- Use `run_in_background=false` for all Bash/CLI calls to ensure foreground execution
|
||||
**Bash Tool (CLI Execution in Agent)**:
|
||||
- Use `run_in_background=false` for all Bash/CLI calls - agent cannot receive task hook callbacks
|
||||
- Set timeout ≥60 minutes for CLI commands (hooks don't propagate to subagents):
|
||||
```javascript
|
||||
Bash(command="ccw cli -p '...' --tool codex --mode write", timeout=3600000) // 60 min
|
||||
```
|
||||
|
||||
**ALWAYS:**
|
||||
- **Search Tool Priority**: ACE (`mcp__ace-tool__search_context`) → CCW (`mcp__ccw-tools__smart_search`) / Built-in (`Grep`, `Glob`, `Read`)
|
||||
|
||||
@@ -105,7 +105,7 @@ TASK: • Analyze error pattern • Identify potential root causes • Suggest t
|
||||
MODE: analysis
|
||||
CONTEXT: @{affected_files}
|
||||
EXPECTED: Structured hypothesis list with priority ranking
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/01-diagnose-bug-root-cause.txt) | Focus on testable conditions
|
||||
CONSTRAINTS: Focus on testable conditions
|
||||
" --tool gemini --mode analysis --cd {project_root}
|
||||
```
|
||||
|
||||
@@ -213,7 +213,7 @@ EXPECTED:
|
||||
- Evidence summary
|
||||
- Root cause identification (if confirmed)
|
||||
- Next steps (if inconclusive)
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/01-diagnose-bug-root-cause.txt) | Evidence-based reasoning only
|
||||
CONSTRAINTS: Evidence-based reasoning only
|
||||
" --tool gemini --mode analysis
|
||||
```
|
||||
|
||||
@@ -271,7 +271,7 @@ TASK:
|
||||
MODE: write
|
||||
CONTEXT: @{affected_files}
|
||||
EXPECTED: Working fix that addresses root cause
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/development/02-implement-feature.txt) | Minimal changes only
|
||||
CONSTRAINTS: Minimal changes only
|
||||
" --tool codex --mode write --cd {project_root}
|
||||
```
|
||||
|
||||
|
||||
@@ -70,8 +70,8 @@ The agent supports **two execution modes** based on task JSON's `meta.cli_execut
|
||||
CONTEXT: @**/* ./src/modules/auth|code|code:5|dirs:2
|
||||
./src/modules/api|code|code:3|dirs:0
|
||||
EXPECTED: Documentation files in .workflow/docs/my_project/src/modules/
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/documentation/module-documentation.txt) | Mirror source structure
|
||||
" --tool gemini --mode write --cd src/modules
|
||||
CONSTRAINTS: Mirror source structure
|
||||
" --tool gemini --mode write --rule documentation-module --cd src/modules
|
||||
```
|
||||
|
||||
4. **CLI Execution** (Gemini CLI):
|
||||
@@ -216,7 +216,7 @@ Before completion, verify:
|
||||
{
|
||||
"step": "analyze_module_structure",
|
||||
"action": "Deep analysis of module structure and API",
|
||||
"command": "ccw cli -p \"PURPOSE: Document module comprehensively\nTASK: Extract module purpose, architecture, public API, dependencies\nMODE: analysis\nCONTEXT: @**/* System: [system_context]\nEXPECTED: Complete module analysis for documentation\nRULES: $(cat ~/.claude/workflows/cli-templates/prompts/documentation/module-documentation.txt)\" --tool gemini --mode analysis --cd src/auth",
|
||||
"command": "ccw cli -p \"PURPOSE: Document module comprehensively\nTASK: Extract module purpose, architecture, public API, dependencies\nMODE: analysis\nCONTEXT: @**/* System: [system_context]\nEXPECTED: Complete module analysis for documentation\nCONSTRAINTS: Mirror source structure\" --tool gemini --mode analysis --rule documentation-module --cd src/auth",
|
||||
"output_to": "module_analysis",
|
||||
"on_error": "fail"
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ color: green
|
||||
- 5-phase task lifecycle (analyze → implement → test → optimize → commit)
|
||||
- Conflict-aware planning (isolate file modifications across issues)
|
||||
- Dependency DAG validation
|
||||
- Auto-bind for single solution, return for selection on multiple
|
||||
- Execute bind command for single solution, return for selection on multiple
|
||||
|
||||
**Key Principle**: Generate tasks conforming to schema with quantified acceptance criteria.
|
||||
|
||||
@@ -56,14 +56,61 @@ Phase 4: Validation & Output (15%)
|
||||
ccw issue status <issue-id> --json
|
||||
```
|
||||
|
||||
**Step 2**: Analyze and classify
|
||||
**Step 2**: Analyze failure history (if present)
|
||||
```javascript
|
||||
function analyzeFailureHistory(issue) {
|
||||
if (!issue.feedback || issue.feedback.length === 0) {
|
||||
return { has_failures: false };
|
||||
}
|
||||
|
||||
// Extract execution failures
|
||||
const failures = issue.feedback.filter(f => f.type === 'failure' && f.stage === 'execute');
|
||||
|
||||
if (failures.length === 0) {
|
||||
return { has_failures: false };
|
||||
}
|
||||
|
||||
// Parse failure details
|
||||
const failureAnalysis = failures.map(f => {
|
||||
const detail = JSON.parse(f.content);
|
||||
return {
|
||||
solution_id: detail.solution_id,
|
||||
task_id: detail.task_id,
|
||||
error_type: detail.error_type, // test_failure, compilation, timeout, etc.
|
||||
message: detail.message,
|
||||
stack_trace: detail.stack_trace,
|
||||
timestamp: f.created_at
|
||||
};
|
||||
});
|
||||
|
||||
// Identify patterns
|
||||
const errorTypes = failureAnalysis.map(f => f.error_type);
|
||||
const repeatedErrors = errorTypes.filter((e, i, arr) => arr.indexOf(e) !== i);
|
||||
|
||||
return {
|
||||
has_failures: true,
|
||||
failure_count: failures.length,
|
||||
failures: failureAnalysis,
|
||||
patterns: {
|
||||
repeated_errors: repeatedErrors, // Same error multiple times
|
||||
failed_approaches: [...new Set(failureAnalysis.map(f => f.solution_id))]
|
||||
}
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
**Step 3**: Analyze and classify
|
||||
```javascript
|
||||
function analyzeIssue(issue) {
|
||||
const failureAnalysis = analyzeFailureHistory(issue);
|
||||
|
||||
return {
|
||||
issue_id: issue.id,
|
||||
requirements: extractRequirements(issue.context),
|
||||
scope: inferScope(issue.title, issue.context),
|
||||
complexity: determineComplexity(issue) // Low | Medium | High
|
||||
complexity: determineComplexity(issue), // Low | Medium | High
|
||||
failure_analysis: failureAnalysis, // Failure context for planning
|
||||
is_replan: failureAnalysis.has_failures // Flag for replanning
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -104,6 +151,41 @@ mcp__ace-tool__search_context({
|
||||
|
||||
#### Phase 3: Solution Planning
|
||||
|
||||
**Failure-Aware Planning** (when `issue.failure_analysis.has_failures === true`):
|
||||
|
||||
```javascript
|
||||
function planWithFailureContext(issue, exploration, failureAnalysis) {
|
||||
// Identify what failed before
|
||||
const failedApproaches = failureAnalysis.patterns.failed_approaches;
|
||||
const rootCauses = failureAnalysis.failures.map(f => ({
|
||||
error: f.error_type,
|
||||
message: f.message,
|
||||
task: f.task_id
|
||||
}));
|
||||
|
||||
// Design alternative approach
|
||||
const approach = `
|
||||
**Previous Attempt Analysis**:
|
||||
- Failed approaches: ${failedApproaches.join(', ')}
|
||||
- Root causes: ${rootCauses.map(r => `${r.error} (${r.task}): ${r.message}`).join('; ')}
|
||||
|
||||
**Alternative Strategy**:
|
||||
- [Describe how this solution addresses root causes]
|
||||
- [Explain what's different from failed approaches]
|
||||
- [Prevention steps to catch same errors earlier]
|
||||
`;
|
||||
|
||||
// Add explicit verification tasks
|
||||
const verificationTasks = rootCauses.map(rc => ({
|
||||
verification_type: rc.error,
|
||||
check: `Prevent ${rc.error}: ${rc.message}`,
|
||||
method: `Add unit test / compile check / timeout limit`
|
||||
}));
|
||||
|
||||
return { approach, verificationTasks };
|
||||
}
|
||||
```
|
||||
|
||||
**Multi-Solution Generation**:
|
||||
|
||||
Generate multiple candidate solutions when:
|
||||
@@ -111,30 +193,30 @@ Generate multiple candidate solutions when:
|
||||
- Multiple valid implementation approaches exist
|
||||
- Trade-offs between approaches (performance vs simplicity, etc.)
|
||||
|
||||
| Condition | Solutions |
|
||||
|-----------|-----------|
|
||||
| Low complexity, single approach | 1 solution, auto-bind |
|
||||
| Medium complexity, clear path | 1-2 solutions |
|
||||
| High complexity, multiple approaches | 2-3 solutions, user selection |
|
||||
| Condition | Solutions | Binding Action |
|
||||
|-----------|-----------|----------------|
|
||||
| Low complexity, single approach | 1 solution | Execute bind |
|
||||
| Medium complexity, clear path | 1-2 solutions | Execute bind if 1, return if 2+ |
|
||||
| High complexity, multiple approaches | 2-3 solutions | Return for selection |
|
||||
|
||||
**Binding Decision** (based SOLELY on final `solutions.length`):
|
||||
```javascript
|
||||
// After generating all solutions
|
||||
if (solutions.length === 1) {
|
||||
exec(`ccw issue bind ${issueId} ${solutions[0].id}`); // MUST execute
|
||||
} else {
|
||||
return { pending_selection: solutions }; // Return for user choice
|
||||
}
|
||||
```
|
||||
|
||||
**Solution Evaluation** (for each candidate):
|
||||
```javascript
|
||||
{
|
||||
analysis: {
|
||||
risk: "low|medium|high", // Implementation risk
|
||||
impact: "low|medium|high", // Scope of changes
|
||||
complexity: "low|medium|high" // Technical complexity
|
||||
},
|
||||
score: 0.0-1.0 // Overall quality score (higher = recommended)
|
||||
analysis: { risk: "low|medium|high", impact: "low|medium|high", complexity: "low|medium|high" },
|
||||
score: 0.0-1.0 // Higher = recommended
|
||||
}
|
||||
```
|
||||
|
||||
**Selection Flow**:
|
||||
1. Generate all candidate solutions
|
||||
2. Evaluate and score each
|
||||
3. Single solution → auto-bind
|
||||
4. Multiple solutions → return `pending_selection` for user choice
|
||||
|
||||
**Task Decomposition** following schema:
|
||||
```javascript
|
||||
function decomposeTasks(issue, exploration) {
|
||||
@@ -248,8 +330,8 @@ Write({ file_path: filePath, content: newContent })
|
||||
```
|
||||
|
||||
**Step 2: Bind decision**
|
||||
- **Single solution** → Auto-bind: `ccw issue bind <issue-id> <solution-id>`
|
||||
- **Multiple solutions** → Return for user selection (no bind)
|
||||
- 1 solution → Execute `ccw issue bind <issue-id> <solution-id>`
|
||||
- 2+ solutions → Return `pending_selection` (no bind)
|
||||
|
||||
---
|
||||
|
||||
@@ -264,14 +346,7 @@ Write({ file_path: filePath, content: newContent })
|
||||
|
||||
Each line is a solution JSON containing tasks. Schema: `cat .claude/workflows/cli-templates/schemas/solution-schema.json`
|
||||
|
||||
### 2.2 Binding
|
||||
|
||||
| Scenario | Action |
|
||||
|----------|--------|
|
||||
| Single solution | `ccw issue bind <issue-id> <solution-id>` (auto) |
|
||||
| Multiple solutions | Register only, return for selection |
|
||||
|
||||
### 2.3 Return Summary
|
||||
### 2.2 Return Summary
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -310,15 +385,17 @@ Each line is a solution JSON containing tasks. Schema: `cat .claude/workflows/cl
|
||||
**ALWAYS**:
|
||||
1. **Search Tool Priority**: ACE (`mcp__ace-tool__search_context`) → CCW (`mcp__ccw-tools__smart_search`) / Built-in (`Grep`, `Glob`, `Read`)
|
||||
2. Read schema first: `cat .claude/workflows/cli-templates/schemas/solution-schema.json`
|
||||
2. Use ACE semantic search as PRIMARY exploration tool
|
||||
3. Fetch issue details via `ccw issue status <id> --json`
|
||||
4. Quantify acceptance.criteria with testable conditions
|
||||
5. Validate DAG before output
|
||||
6. Evaluate each solution with `analysis` and `score`
|
||||
7. Write solutions to `.workflow/issues/solutions/{issue-id}.jsonl` (append mode)
|
||||
8. For HIGH complexity: generate 2-3 candidate solutions
|
||||
9. **Solution ID format**: `SOL-{issue-id}-{uid}` where uid is 4 random alphanumeric chars (e.g., `SOL-GH-123-a7x9`)
|
||||
10. **GitHub Reply Task**: If issue has `github_url` or `github_number`, add final task to comment on GitHub issue with completion summary
|
||||
3. Use ACE semantic search as PRIMARY exploration tool
|
||||
4. Fetch issue details via `ccw issue status <id> --json`
|
||||
5. **Analyze failure history**: Check `issue.feedback` for type='failure', stage='execute'
|
||||
6. **For replanning**: Reference previous failures in `solution.approach`, add prevention steps
|
||||
7. Quantify acceptance.criteria with testable conditions
|
||||
8. Validate DAG before output
|
||||
9. Evaluate each solution with `analysis` and `score`
|
||||
10. Write solutions to `.workflow/issues/solutions/{issue-id}.jsonl` (append mode)
|
||||
11. For HIGH complexity: generate 2-3 candidate solutions
|
||||
12. **Solution ID format**: `SOL-{issue-id}-{uid}` where uid is 4 random alphanumeric chars (e.g., `SOL-GH-123-a7x9`)
|
||||
13. **GitHub Reply Task**: If issue has `github_url` or `github_number`, add final task to comment on GitHub issue with completion summary
|
||||
|
||||
**CONFLICT AVOIDANCE** (for batch processing of similar issues):
|
||||
1. **File isolation**: Each issue's solution should target distinct files when possible
|
||||
@@ -332,9 +409,9 @@ Each line is a solution JSON containing tasks. Schema: `cat .claude/workflows/cl
|
||||
2. Use vague criteria ("works correctly", "good performance")
|
||||
3. Create circular dependencies
|
||||
4. Generate more than 10 tasks per issue
|
||||
5. **Bind when multiple solutions exist** - MUST check `solutions.length === 1` before calling `ccw issue bind`
|
||||
5. Skip bind when `solutions.length === 1` (MUST execute bind command)
|
||||
|
||||
**OUTPUT**:
|
||||
1. Write solutions to `.workflow/issues/solutions/{issue-id}.jsonl` (JSONL format)
|
||||
2. Single solution → `ccw issue bind <issue-id> <solution-id>`; Multiple → return only
|
||||
3. Return JSON with `bound`, `pending_selection`
|
||||
1. Write solutions to `.workflow/issues/solutions/{issue-id}.jsonl`
|
||||
2. Execute bind or return `pending_selection` based on solution count
|
||||
3. Return JSON: `{ bound: [...], pending_selection: [...] }`
|
||||
|
||||
@@ -87,7 +87,7 @@ TASK: • Detect file conflicts (same file modified by multiple solutions)
|
||||
MODE: analysis
|
||||
CONTEXT: @.workflow/issues/solutions/**/*.jsonl | Solution data: \${SOLUTIONS_JSON}
|
||||
EXPECTED: JSON array of conflicts with type, severity, solutions, recommended_order
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md) | Severity: high (API/data) > medium (file/dependency) > low (architecture)
|
||||
CONSTRAINTS: Severity: high (API/data) > medium (file/dependency) > low (architecture)
|
||||
" --tool gemini --mode analysis --cd .workflow/issues
|
||||
```
|
||||
|
||||
|
||||
361
.claude/commands/cli/codex-review.md
Normal file
361
.claude/commands/cli/codex-review.md
Normal file
@@ -0,0 +1,361 @@
|
||||
---
|
||||
name: codex-review
|
||||
description: Interactive code review using Codex CLI via ccw endpoint with configurable review target, model, and custom instructions
|
||||
argument-hint: "[--uncommitted|--base <branch>|--commit <sha>] [--model <model>] [--title <title>] [prompt]"
|
||||
allowed-tools: Bash(*), AskUserQuestion(*), Read(*)
|
||||
---
|
||||
|
||||
# Codex Review Command (/cli:codex-review)
|
||||
|
||||
## Overview
|
||||
Interactive code review command that invokes `codex review` via ccw cli endpoint with guided parameter selection.
|
||||
|
||||
**Codex Review Parameters** (from `codex review --help`):
|
||||
| Parameter | Description |
|
||||
|-----------|-------------|
|
||||
| `[PROMPT]` | Custom review instructions (positional) |
|
||||
| `-c model=<model>` | Override model via config |
|
||||
| `--uncommitted` | Review staged, unstaged, and untracked changes |
|
||||
| `--base <BRANCH>` | Review changes against base branch |
|
||||
| `--commit <SHA>` | Review changes introduced by a commit |
|
||||
| `--title <TITLE>` | Optional commit title for review summary |
|
||||
|
||||
## Prompt Template Format
|
||||
|
||||
Follow the standard ccw cli prompt template:
|
||||
|
||||
```
|
||||
PURPOSE: [what] + [why] + [success criteria] + [constraints/scope]
|
||||
TASK: • [step 1] • [step 2] • [step 3]
|
||||
MODE: review
|
||||
CONTEXT: [review target description] | Memory: [relevant context]
|
||||
EXPECTED: [deliverable format] + [quality criteria]
|
||||
CONSTRAINTS: [focus constraints]
|
||||
```
|
||||
|
||||
## EXECUTION INSTRUCTIONS - START HERE
|
||||
|
||||
**When this command is triggered, follow these exact steps:**
|
||||
|
||||
### Step 1: Parse Arguments
|
||||
|
||||
Check if user provided arguments directly:
|
||||
- `--uncommitted` → Record target = uncommitted
|
||||
- `--base <branch>` → Record target = base, branch name
|
||||
- `--commit <sha>` → Record target = commit, sha value
|
||||
- `--model <model>` → Record model selection
|
||||
- `--title <title>` → Record title
|
||||
- Remaining text → Use as custom focus/prompt
|
||||
|
||||
If no target specified → Continue to Step 2 for interactive selection.
|
||||
|
||||
### Step 2: Interactive Parameter Selection
|
||||
|
||||
**2.1 Review Target Selection**
|
||||
|
||||
```javascript
|
||||
AskUserQuestion({
|
||||
questions: [{
|
||||
question: "What do you want to review?",
|
||||
header: "Review Target",
|
||||
options: [
|
||||
{ label: "Uncommitted changes (Recommended)", description: "Review staged, unstaged, and untracked changes" },
|
||||
{ label: "Compare to branch", description: "Review changes against a base branch (e.g., main)" },
|
||||
{ label: "Specific commit", description: "Review changes introduced by a specific commit" }
|
||||
],
|
||||
multiSelect: false
|
||||
}]
|
||||
})
|
||||
```
|
||||
|
||||
**2.2 Branch/Commit Input (if needed)**
|
||||
|
||||
If "Compare to branch" selected:
|
||||
```javascript
|
||||
AskUserQuestion({
|
||||
questions: [{
|
||||
question: "Which base branch to compare against?",
|
||||
header: "Base Branch",
|
||||
options: [
|
||||
{ label: "main", description: "Compare against main branch" },
|
||||
{ label: "master", description: "Compare against master branch" },
|
||||
{ label: "develop", description: "Compare against develop branch" }
|
||||
],
|
||||
multiSelect: false
|
||||
}]
|
||||
})
|
||||
```
|
||||
|
||||
If "Specific commit" selected:
|
||||
- Run `git log --oneline -10` to show recent commits
|
||||
- Ask user to provide commit SHA or select from list
|
||||
|
||||
**2.3 Model Selection (Optional)**
|
||||
|
||||
```javascript
|
||||
AskUserQuestion({
|
||||
questions: [{
|
||||
question: "Which model to use for review?",
|
||||
header: "Model",
|
||||
options: [
|
||||
{ label: "Default", description: "Use codex default model (gpt-5.2)" },
|
||||
{ label: "o3", description: "OpenAI o3 reasoning model" },
|
||||
{ label: "gpt-4.1", description: "GPT-4.1 model" },
|
||||
{ label: "o4-mini", description: "OpenAI o4-mini (faster)" }
|
||||
],
|
||||
multiSelect: false
|
||||
}]
|
||||
})
|
||||
```
|
||||
|
||||
**2.4 Review Focus Selection**
|
||||
|
||||
```javascript
|
||||
AskUserQuestion({
|
||||
questions: [{
|
||||
question: "What should the review focus on?",
|
||||
header: "Focus Area",
|
||||
options: [
|
||||
{ label: "General review (Recommended)", description: "Comprehensive review: correctness, style, bugs, docs" },
|
||||
{ label: "Security focus", description: "Security vulnerabilities, input validation, auth issues" },
|
||||
{ label: "Performance focus", description: "Performance bottlenecks, complexity, resource usage" },
|
||||
{ label: "Code quality", description: "Readability, maintainability, SOLID principles" }
|
||||
],
|
||||
multiSelect: false
|
||||
}]
|
||||
})
|
||||
```
|
||||
|
||||
### Step 3: Build Prompt and Command
|
||||
|
||||
**3.1 Construct Prompt Based on Focus**
|
||||
|
||||
**General Review Prompt:**
|
||||
```
|
||||
PURPOSE: Comprehensive code review to identify issues, improve quality, and ensure best practices; success = actionable feedback with clear priorities
|
||||
TASK: • Review code correctness and logic errors • Check coding standards and consistency • Identify potential bugs and edge cases • Evaluate documentation completeness
|
||||
MODE: review
|
||||
CONTEXT: {target_description} | Memory: Project conventions from CLAUDE.md
|
||||
EXPECTED: Structured review report with: severity levels (Critical/High/Medium/Low), file:line references, specific improvement suggestions, priority ranking
|
||||
CONSTRAINTS: Focus on actionable feedback
|
||||
```
|
||||
|
||||
**Security Focus Prompt:**
|
||||
```
|
||||
PURPOSE: Security-focused code review to identify vulnerabilities and security risks; success = all security issues documented with remediation
|
||||
TASK: • Scan for injection vulnerabilities (SQL, XSS, command) • Check authentication and authorization logic • Evaluate input validation and sanitization • Identify sensitive data exposure risks
|
||||
MODE: review
|
||||
CONTEXT: {target_description} | Memory: Security best practices, OWASP Top 10
|
||||
EXPECTED: Security report with: vulnerability classification, CVE references where applicable, remediation code snippets, risk severity matrix
|
||||
CONSTRAINTS: Security-first analysis | Flag all potential vulnerabilities
|
||||
```
|
||||
|
||||
**Performance Focus Prompt:**
|
||||
```
|
||||
PURPOSE: Performance-focused code review to identify bottlenecks and optimization opportunities; success = measurable improvement recommendations
|
||||
TASK: • Analyze algorithmic complexity (Big-O) • Identify memory allocation issues • Check for N+1 queries and blocking operations • Evaluate caching opportunities
|
||||
MODE: review
|
||||
CONTEXT: {target_description} | Memory: Performance patterns and anti-patterns
|
||||
EXPECTED: Performance report with: complexity analysis, bottleneck identification, optimization suggestions with expected impact, benchmark recommendations
|
||||
CONSTRAINTS: Performance optimization focus
|
||||
```
|
||||
|
||||
**Code Quality Focus Prompt:**
|
||||
```
|
||||
PURPOSE: Code quality review to improve maintainability and readability; success = cleaner, more maintainable code
|
||||
TASK: • Assess SOLID principles adherence • Identify code duplication and abstraction opportunities • Review naming conventions and clarity • Evaluate test coverage implications
|
||||
MODE: review
|
||||
CONTEXT: {target_description} | Memory: Project coding standards
|
||||
EXPECTED: Quality report with: principle violations, refactoring suggestions, naming improvements, maintainability score
|
||||
CONSTRAINTS: Code quality and maintainability focus
|
||||
```
|
||||
|
||||
**3.2 Build Target Description**
|
||||
|
||||
Based on selection, set `{target_description}`:
|
||||
- Uncommitted: `Reviewing uncommitted changes (staged + unstaged + untracked)`
|
||||
- Base branch: `Reviewing changes against {branch} branch`
|
||||
- Commit: `Reviewing changes introduced by commit {sha}`
|
||||
|
||||
### Step 4: Execute via CCW CLI
|
||||
|
||||
Build and execute the ccw cli command:
|
||||
|
||||
```bash
|
||||
# Base structure
|
||||
ccw cli -p "<PROMPT>" --tool codex --mode review [OPTIONS]
|
||||
```
|
||||
|
||||
**Command Construction:**
|
||||
|
||||
```bash
|
||||
# Variables from user selection
|
||||
TARGET_FLAG="" # --uncommitted | --base <branch> | --commit <sha>
|
||||
MODEL_FLAG="" # --model <model> (if not default)
|
||||
TITLE_FLAG="" # --title "<title>" (if provided)
|
||||
|
||||
# Build target flag
|
||||
if [ "$target" = "uncommitted" ]; then
|
||||
TARGET_FLAG="--uncommitted"
|
||||
elif [ "$target" = "base" ]; then
|
||||
TARGET_FLAG="--base $branch"
|
||||
elif [ "$target" = "commit" ]; then
|
||||
TARGET_FLAG="--commit $sha"
|
||||
fi
|
||||
|
||||
# Build model flag (only if not default)
|
||||
if [ "$model" != "default" ] && [ -n "$model" ]; then
|
||||
MODEL_FLAG="--model $model"
|
||||
fi
|
||||
|
||||
# Build title flag (if provided)
|
||||
if [ -n "$title" ]; then
|
||||
TITLE_FLAG="--title \"$title\""
|
||||
fi
|
||||
|
||||
# Execute
|
||||
ccw cli -p "$PROMPT" --tool codex --mode review $TARGET_FLAG $MODEL_FLAG $TITLE_FLAG
|
||||
```
|
||||
|
||||
**Full Example Commands:**
|
||||
|
||||
**Option 1: With custom prompt (reviews uncommitted by default):**
|
||||
```bash
|
||||
ccw cli -p "
|
||||
PURPOSE: Comprehensive code review to identify issues and improve quality; success = actionable feedback with priorities
|
||||
TASK: • Review correctness and logic • Check standards compliance • Identify bugs and edge cases • Evaluate documentation
|
||||
MODE: review
|
||||
CONTEXT: Reviewing uncommitted changes | Memory: Project conventions
|
||||
EXPECTED: Structured report with severity levels, file:line refs, improvement suggestions
|
||||
CONSTRAINTS: Actionable feedback
|
||||
" --tool codex --mode review --rule analysis-review-code-quality
|
||||
```
|
||||
|
||||
**Option 2: Target flag only (no prompt allowed):**
|
||||
```bash
|
||||
ccw cli --tool codex --mode review --uncommitted
|
||||
```
|
||||
|
||||
### Step 5: Execute and Display Results
|
||||
|
||||
```bash
|
||||
Bash({
|
||||
command: "ccw cli -p \"$PROMPT\" --tool codex --mode review $FLAGS",
|
||||
run_in_background: true
|
||||
})
|
||||
```
|
||||
|
||||
Wait for completion and display formatted results.
|
||||
|
||||
## Quick Usage Examples
|
||||
|
||||
### Direct Execution (No Interaction)
|
||||
|
||||
```bash
|
||||
# Review uncommitted changes with default settings
|
||||
/cli:codex-review --uncommitted
|
||||
|
||||
# Review against main branch
|
||||
/cli:codex-review --base main
|
||||
|
||||
# Review specific commit
|
||||
/cli:codex-review --commit abc123
|
||||
|
||||
# Review with custom model
|
||||
/cli:codex-review --uncommitted --model o3
|
||||
|
||||
# Review with security focus
|
||||
/cli:codex-review --uncommitted security
|
||||
|
||||
# Full options
|
||||
/cli:codex-review --base main --model o3 --title "Auth Feature" security
|
||||
```
|
||||
|
||||
### Interactive Mode
|
||||
|
||||
```bash
|
||||
# Start interactive selection (guided flow)
|
||||
/cli:codex-review
|
||||
```
|
||||
|
||||
## Focus Area Mapping
|
||||
|
||||
| User Selection | Prompt Focus | Key Checks |
|
||||
|----------------|--------------|------------|
|
||||
| General review | Comprehensive | Correctness, style, bugs, docs |
|
||||
| Security focus | Security-first | Injection, auth, validation, exposure |
|
||||
| Performance focus | Optimization | Complexity, memory, queries, caching |
|
||||
| Code quality | Maintainability | SOLID, duplication, naming, tests |
|
||||
|
||||
## Error Handling
|
||||
|
||||
### No Changes to Review
|
||||
```
|
||||
No changes found for review target. Suggestions:
|
||||
- For --uncommitted: Make some code changes first
|
||||
- For --base: Ensure branch exists and has diverged
|
||||
- For --commit: Verify commit SHA exists
|
||||
```
|
||||
|
||||
### Invalid Branch
|
||||
```bash
|
||||
# Show available branches
|
||||
git branch -a --list | head -20
|
||||
```
|
||||
|
||||
### Invalid Commit
|
||||
```bash
|
||||
# Show recent commits
|
||||
git log --oneline -10
|
||||
```
|
||||
|
||||
## Integration Notes
|
||||
|
||||
- Uses `ccw cli --tool codex --mode review` endpoint
|
||||
- Model passed via prompt (codex uses `-c model=` internally)
|
||||
- Target flags (`--uncommitted`, `--base`, `--commit`) passed through to codex
|
||||
- Prompt follows standard ccw cli template format for consistency
|
||||
|
||||
## Validation Constraints
|
||||
|
||||
**IMPORTANT: Target flags and prompt are mutually exclusive**
|
||||
|
||||
The codex CLI has a constraint where target flags (`--uncommitted`, `--base`, `--commit`) cannot be used with a positional `[PROMPT]` argument:
|
||||
|
||||
```
|
||||
error: the argument '--uncommitted' cannot be used with '[PROMPT]'
|
||||
error: the argument '--base <BRANCH>' cannot be used with '[PROMPT]'
|
||||
error: the argument '--commit <SHA>' cannot be used with '[PROMPT]'
|
||||
```
|
||||
|
||||
**Behavior:**
|
||||
- When ANY target flag is specified, ccw cli automatically skips template concatenation (systemRules/roles)
|
||||
- The review uses codex's default review behavior for the specified target
|
||||
- Custom prompts are only supported WITHOUT target flags (reviews uncommitted changes by default)
|
||||
|
||||
**Valid combinations:**
|
||||
| Command | Result |
|
||||
|---------|--------|
|
||||
| `codex review "Focus on security"` | ✓ Custom prompt, reviews uncommitted (default) |
|
||||
| `codex review --uncommitted` | ✓ No prompt, uses default review |
|
||||
| `codex review --base main` | ✓ No prompt, uses default review |
|
||||
| `codex review --commit abc123` | ✓ No prompt, uses default review |
|
||||
| `codex review --uncommitted "prompt"` | ✗ Invalid - mutually exclusive |
|
||||
| `codex review --base main "prompt"` | ✗ Invalid - mutually exclusive |
|
||||
| `codex review --commit abc123 "prompt"` | ✗ Invalid - mutually exclusive |
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
# ✓ Valid: prompt only (reviews uncommitted by default)
|
||||
ccw cli -p "Focus on security" --tool codex --mode review
|
||||
|
||||
# ✓ Valid: target flag only (no prompt)
|
||||
ccw cli --tool codex --mode review --uncommitted
|
||||
ccw cli --tool codex --mode review --base main
|
||||
ccw cli --tool codex --mode review --commit abc123
|
||||
|
||||
# ✗ Invalid: target flag with prompt (will fail)
|
||||
ccw cli -p "Review this" --tool codex --mode review --uncommitted
|
||||
ccw cli -p "Review this" --tool codex --mode review --base main
|
||||
ccw cli -p "Review this" --tool codex --mode review --commit abc123
|
||||
```
|
||||
@@ -267,7 +267,7 @@ EXPECTED: JSON exploration plan following exploration-plan-schema.json:
|
||||
"estimated_iterations": N,
|
||||
"termination_conditions": [...]
|
||||
}
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md) | Use ACE context to inform targets | Focus on actionable plan
|
||||
CONSTRAINTS: Use ACE context to inform targets | Focus on actionable plan
|
||||
`;
|
||||
|
||||
// Step 3: Execute Gemini planning
|
||||
|
||||
@@ -131,7 +131,7 @@ TASK: • Analyze issue titles/tags semantically • Identify functional/archite
|
||||
MODE: analysis
|
||||
CONTEXT: Issue metadata only
|
||||
EXPECTED: JSON with groups array, each containing max 4 issue_ids, theme, rationale
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md) | Each issue in exactly one group | Max 4 issues per group | Balance group sizes
|
||||
CONSTRAINTS: Each issue in exactly one group | Max 4 issues per group | Balance group sizes
|
||||
|
||||
INPUT:
|
||||
${JSON.stringify(issueSummaries, null, 2)}
|
||||
@@ -195,12 +195,26 @@ ${issueList}
|
||||
|
||||
### Workflow
|
||||
1. Fetch issue details: ccw issue status <id> --json
|
||||
2. Load project context files
|
||||
3. Explore codebase (ACE semantic search)
|
||||
4. Plan solution with tasks (schema: solution-schema.json)
|
||||
5. **If github_url exists**: Add final task to comment on GitHub issue
|
||||
6. Write solution to: .workflow/issues/solutions/{issue-id}.jsonl
|
||||
7. Single solution → auto-bind; Multiple → return for selection
|
||||
2. **Analyze failure history** (if issue.feedback exists):
|
||||
- Extract failure details from issue.feedback (type='failure', stage='execute')
|
||||
- Parse error_type, message, task_id, solution_id from content JSON
|
||||
- Identify failure patterns: repeated errors, root causes, blockers
|
||||
- **Constraint**: Avoid repeating failed approaches
|
||||
3. Load project context files
|
||||
4. Explore codebase (ACE semantic search)
|
||||
5. Plan solution with tasks (schema: solution-schema.json)
|
||||
- **If previous solution failed**: Reference failure analysis in solution.approach
|
||||
- Add explicit verification steps to prevent same failure mode
|
||||
6. **If github_url exists**: Add final task to comment on GitHub issue
|
||||
7. Write solution to: .workflow/issues/solutions/{issue-id}.jsonl
|
||||
8. Single solution → auto-bind; Multiple → return for selection
|
||||
|
||||
### Failure-Aware Planning Rules
|
||||
- **Extract failure patterns**: Parse issue.feedback where type='failure' and stage='execute'
|
||||
- **Identify root causes**: Analyze error_type (test_failure, compilation, timeout, etc.)
|
||||
- **Design alternative approach**: Create solution that addresses root cause
|
||||
- **Add prevention steps**: Include explicit verification to catch same error earlier
|
||||
- **Document lessons**: Reference previous failures in solution.approach
|
||||
|
||||
### Rules
|
||||
- Solution ID format: SOL-{issue-id}-{uid} (uid: 4 random alphanumeric chars, e.g., a7x9)
|
||||
|
||||
@@ -65,9 +65,13 @@ Queue formation command using **issue-queue-agent** that analyzes all bound solu
|
||||
--queues <n> Number of parallel queues (default: 1)
|
||||
--issue <id> Form queue for specific issue only
|
||||
--append <id> Append issue to active queue (don't create new)
|
||||
--force Skip active queue check, always create new queue
|
||||
|
||||
# CLI subcommands (ccw issue queue ...)
|
||||
ccw issue queue list List all queues with status
|
||||
ccw issue queue add <issue-id> Add issue to queue (interactive if active queue exists)
|
||||
ccw issue queue add <issue-id> -f Add to new queue without prompt (force)
|
||||
ccw issue queue merge <src> --queue <target> Merge source queue into target queue
|
||||
ccw issue queue switch <queue-id> Switch active queue
|
||||
ccw issue queue archive Archive current queue
|
||||
ccw issue queue delete <queue-id> Delete queue from history
|
||||
@@ -92,7 +96,7 @@ Phase 2-4: Agent-Driven Queue Formation (issue-queue-agent)
|
||||
│ ├─ Build dependency DAG from conflicts
|
||||
│ ├─ Calculate semantic priority per solution
|
||||
│ └─ Assign execution groups (parallel/sequential)
|
||||
└─ Each agent writes: queue JSON + index update
|
||||
└─ Each agent writes: queue JSON + index update (NOT active yet)
|
||||
|
||||
Phase 5: Conflict Clarification (if needed)
|
||||
├─ Collect `clarifications` arrays from all agents
|
||||
@@ -102,7 +106,24 @@ Phase 5: Conflict Clarification (if needed)
|
||||
|
||||
Phase 6: Status Update & Summary
|
||||
├─ Update issue statuses to 'queued'
|
||||
└─ Display queue summary (N queues), next step: /issue:execute
|
||||
└─ Display new queue summary (N queues)
|
||||
|
||||
Phase 7: Active Queue Check & Decision (REQUIRED)
|
||||
├─ Read queue index: ccw issue queue list --brief
|
||||
├─ Get generated queue ID from agent output
|
||||
├─ If NO active queue exists:
|
||||
│ ├─ Set generated queue as active_queue_id
|
||||
│ ├─ Update index.json
|
||||
│ └─ Display: "Queue created and activated"
|
||||
│
|
||||
└─ If active queue exists with items:
|
||||
├─ Display both queues to user
|
||||
├─ Use AskUserQuestion to prompt:
|
||||
│ ├─ "Use new queue (keep existing)" → Set new as active, keep old inactive
|
||||
│ ├─ "Merge: add new items to existing" → Merge new → existing, delete new
|
||||
│ ├─ "Merge: add existing items to new" → Merge existing → new, archive old
|
||||
│ └─ "Cancel" → Delete new queue, keep existing active
|
||||
└─ Execute chosen action
|
||||
```
|
||||
|
||||
## Implementation
|
||||
@@ -306,6 +327,41 @@ ccw issue update <issue-id> --status queued
|
||||
- Show unplanned issues (planned but NOT in queue)
|
||||
- Show next step: `/issue:execute`
|
||||
|
||||
### Phase 7: Active Queue Check & Decision
|
||||
|
||||
**After agent completes Phase 1-6, check for active queue:**
|
||||
|
||||
```bash
|
||||
ccw issue queue list --brief
|
||||
```
|
||||
|
||||
**Decision:**
|
||||
- If `active_queue_id` is null → `ccw issue queue switch <new-queue-id>` (activate new queue)
|
||||
- If active queue exists → Use **AskUserQuestion** to prompt user
|
||||
|
||||
**AskUserQuestion:**
|
||||
```javascript
|
||||
AskUserQuestion({
|
||||
questions: [{
|
||||
question: "Active queue exists. How would you like to proceed?",
|
||||
header: "Queue Action",
|
||||
options: [
|
||||
{ label: "Merge into existing queue", description: "Add new items to active queue, delete new queue" },
|
||||
{ label: "Use new queue", description: "Switch to new queue, keep existing in history" },
|
||||
{ label: "Cancel", description: "Delete new queue, keep existing active" }
|
||||
],
|
||||
multiSelect: false
|
||||
}]
|
||||
})
|
||||
```
|
||||
|
||||
**Action Commands:**
|
||||
|
||||
| User Choice | Commands |
|
||||
|-------------|----------|
|
||||
| **Merge into existing** | `ccw issue queue merge <new-queue-id> --queue <active-queue-id>` then `ccw issue queue delete <new-queue-id>` |
|
||||
| **Use new queue** | `ccw issue queue switch <new-queue-id>` |
|
||||
| **Cancel** | `ccw issue queue delete <new-queue-id>` |
|
||||
|
||||
## Storage Structure (Queue History)
|
||||
|
||||
@@ -360,6 +416,9 @@ ccw issue update <issue-id> --status queued
|
||||
| User cancels clarification | Abort queue formation |
|
||||
| **index.json not updated** | Auto-fix: Set active_queue_id to new queue |
|
||||
| **Queue file missing solutions** | Abort with error, agent must regenerate |
|
||||
| **User cancels queue add** | Display message, return without changes |
|
||||
| **Merge with empty source** | Skip merge, display warning |
|
||||
| **All items duplicate** | Skip merge, display "All items already exist" |
|
||||
|
||||
## Quality Checklist
|
||||
|
||||
|
||||
@@ -223,8 +223,8 @@ TASK:
|
||||
MODE: analysis
|
||||
CONTEXT: @src/**/*.controller.ts @src/**/*.routes.ts @src/**/*.dto.ts @src/**/middleware/**/*
|
||||
EXPECTED: JSON format API structure analysis report with modules, endpoints, security schemes, and error codes
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md) | Strict RESTful standards | Identify all public endpoints | Document output language: {lang}
|
||||
" --tool gemini --mode analysis --cd {project_root}
|
||||
CONSTRAINTS: Strict RESTful standards | Identify all public endpoints | Document output language: {lang}
|
||||
" --tool gemini --mode analysis --rule analysis-code-patterns --cd {project_root}
|
||||
```
|
||||
|
||||
**Update swagger-planning-data.json** with analysis results:
|
||||
@@ -387,7 +387,7 @@ bash(cat ${session_dir}/.process/swagger-planning-data.json | jq -r '.api_struct
|
||||
"step": 1,
|
||||
"title": "Generate OpenAPI spec file",
|
||||
"description": "Create complete swagger.yaml specification file",
|
||||
"cli_prompt": "PURPOSE: Generate OpenAPI 3.0.3 specification file from analyzed API structure\nTASK:\n• Define openapi version: 3.0.3\n• Define info: title, description, version, contact, license\n• Define servers: development, staging, production environments\n• Define tags: organized by business modules\n• Define paths: all API endpoints with complete specifications\n• Define components: schemas, securitySchemes, parameters, responses\nMODE: write\nCONTEXT: @[api_analysis]\nEXPECTED: Complete swagger.yaml file following OpenAPI 3.0.3 specification\nRULES: $(cat ~/.claude/workflows/cli-templates/protocols/write-protocol.md) $(cat ~/.claude/workflows/cli-templates/prompts/documentation/swagger-api.txt) | Use {lang} for all descriptions | Strict RESTful standards",
|
||||
"cli_prompt": "PURPOSE: Generate OpenAPI 3.0.3 specification file from analyzed API structure\nTASK:\n• Define openapi version: 3.0.3\n• Define info: title, description, version, contact, license\n• Define servers: development, staging, production environments\n• Define tags: organized by business modules\n• Define paths: all API endpoints with complete specifications\n• Define components: schemas, securitySchemes, parameters, responses\nMODE: write\nCONTEXT: @[api_analysis]\nEXPECTED: Complete swagger.yaml file following OpenAPI 3.0.3 specification\nCONSTRAINTS: Use {lang} for all descriptions | Strict RESTful standards\n--rule documentation-swagger-api",
|
||||
"output": "swagger.yaml"
|
||||
}
|
||||
],
|
||||
@@ -429,7 +429,7 @@ bash(cat ${session_dir}/.process/swagger-planning-data.json | jq -r '.api_struct
|
||||
{
|
||||
"step": 1,
|
||||
"title": "Generate authentication documentation",
|
||||
"cli_prompt": "PURPOSE: Generate comprehensive authentication documentation for API security\nTASK:\n• Document authentication mechanism: JWT Bearer Token\n• Explain header format: Authorization: Bearer <token>\n• Describe token lifecycle: acquisition, refresh, expiration handling\n• Define permission levels: public, user, admin, super_admin\n• Document authentication failure responses: 401/403 error handling\nMODE: write\nCONTEXT: @[auth_patterns] @src/**/auth/**/* @src/**/guard/**/*\nEXPECTED: Complete authentication guide in {lang}\nRULES: $(cat ~/.claude/workflows/cli-templates/protocols/write-protocol.md) | Include code examples | Clear step-by-step instructions",
|
||||
"cli_prompt": "PURPOSE: Generate comprehensive authentication documentation for API security\nTASK:\n• Document authentication mechanism: JWT Bearer Token\n• Explain header format: Authorization: Bearer <token>\n• Describe token lifecycle: acquisition, refresh, expiration handling\n• Define permission levels: public, user, admin, super_admin\n• Document authentication failure responses: 401/403 error handling\nMODE: write\nCONTEXT: @[auth_patterns] @src/**/auth/**/* @src/**/guard/**/*\nEXPECTED: Complete authentication guide in {lang}\nCONSTRAINTS: Include code examples | Clear step-by-step instructions\n--rule development-feature",
|
||||
"output": "{auth_doc_name}"
|
||||
}
|
||||
],
|
||||
@@ -464,7 +464,7 @@ bash(cat ${session_dir}/.process/swagger-planning-data.json | jq -r '.api_struct
|
||||
{
|
||||
"step": 1,
|
||||
"title": "Generate error code specification document",
|
||||
"cli_prompt": "PURPOSE: Generate comprehensive error code specification for consistent API error handling\nTASK:\n• Define error response format: {code, message, details, timestamp}\n• Document authentication errors (AUTH_xxx): 401/403 series\n• Document parameter errors (PARAM_xxx): 400 series\n• Document business errors (BIZ_xxx): business logic errors\n• Document system errors (SYS_xxx): 500 series\n• For each error code: HTTP status, error message, possible causes, resolution suggestions\nMODE: write\nCONTEXT: @src/**/*.exception.ts @src/**/*.filter.ts\nEXPECTED: Complete error code specification in {lang} with tables and examples\nRULES: $(cat ~/.claude/workflows/cli-templates/protocols/write-protocol.md) | Include response examples | Clear categorization",
|
||||
"cli_prompt": "PURPOSE: Generate comprehensive error code specification for consistent API error handling\nTASK:\n• Define error response format: {code, message, details, timestamp}\n• Document authentication errors (AUTH_xxx): 401/403 series\n• Document parameter errors (PARAM_xxx): 400 series\n• Document business errors (BIZ_xxx): business logic errors\n• Document system errors (SYS_xxx): 500 series\n• For each error code: HTTP status, error message, possible causes, resolution suggestions\nMODE: write\nCONTEXT: @src/**/*.exception.ts @src/**/*.filter.ts\nEXPECTED: Complete error code specification in {lang} with tables and examples\nCONSTRAINTS: Include response examples | Clear categorization\n--rule development-feature",
|
||||
"output": "{error_doc_name}"
|
||||
}
|
||||
],
|
||||
@@ -523,7 +523,7 @@ bash(cat ${session_dir}/.process/swagger-planning-data.json | jq -r '.api_struct
|
||||
"step": 1,
|
||||
"title": "Generate module API documentation",
|
||||
"description": "Generate complete API documentation for ${module_name}",
|
||||
"cli_prompt": "PURPOSE: Generate complete RESTful API documentation for ${module_name} module\nTASK:\n• Create module overview: purpose, use cases, prerequisites\n• Generate endpoint index: grouped by functionality\n• For each endpoint document:\n - Functional description: purpose and business context\n - Request method: GET/POST/PUT/DELETE\n - URL path: complete API path\n - Request headers: Authorization and other required headers\n - Path parameters: {id} and other path variables\n - Query parameters: pagination, filters, etc.\n - Request body: JSON Schema format\n - Response body: success and error responses\n - Field description table: type, required, example, description\n• Add usage examples: cURL, JavaScript, Python\n• Add version info: v1.0.0, last updated date\nMODE: write\nCONTEXT: @[module_endpoints] @[source_code]\nEXPECTED: Complete module API documentation in {lang} with all endpoints fully documented\nRULES: $(cat ~/.claude/workflows/cli-templates/protocols/write-protocol.md) $(cat ~/.claude/workflows/cli-templates/prompts/documentation/swagger-api.txt) | RESTful standards | Include all response codes",
|
||||
"cli_prompt": "PURPOSE: Generate complete RESTful API documentation for ${module_name} module\nTASK:\n• Create module overview: purpose, use cases, prerequisites\n• Generate endpoint index: grouped by functionality\n• For each endpoint document:\n - Functional description: purpose and business context\n - Request method: GET/POST/PUT/DELETE\n - URL path: complete API path\n - Request headers: Authorization and other required headers\n - Path parameters: {id} and other path variables\n - Query parameters: pagination, filters, etc.\n - Request body: JSON Schema format\n - Response body: success and error responses\n - Field description table: type, required, example, description\n• Add usage examples: cURL, JavaScript, Python\n• Add version info: v1.0.0, last updated date\nMODE: write\nCONTEXT: @[module_endpoints] @[source_code]\nEXPECTED: Complete module API documentation in {lang} with all endpoints fully documented\nCONSTRAINTS: RESTful standards | Include all response codes\n--rule documentation-swagger-api",
|
||||
"output": "${module_doc_name}"
|
||||
}
|
||||
],
|
||||
@@ -559,7 +559,7 @@ bash(cat ${session_dir}/.process/swagger-planning-data.json | jq -r '.api_struct
|
||||
{
|
||||
"step": 1,
|
||||
"title": "Generate API overview",
|
||||
"cli_prompt": "PURPOSE: Generate API overview document with navigation and quick start guide\nTASK:\n• Create introduction: system features, tech stack, version\n• Write quick start guide: authentication, first request example\n• Build module navigation: categorized links to all modules\n• Document environment configuration: development, staging, production\n• List SDKs and tools: client libraries, Postman collection\nMODE: write\nCONTEXT: @[all_module_docs] @.workflow/docs/${project_name}/api/swagger.yaml\nEXPECTED: Complete API overview in {lang} with navigation links\nRULES: $(cat ~/.claude/workflows/cli-templates/protocols/write-protocol.md) | Clear structure | Quick start focus",
|
||||
"cli_prompt": "PURPOSE: Generate API overview document with navigation and quick start guide\nTASK:\n• Create introduction: system features, tech stack, version\n• Write quick start guide: authentication, first request example\n• Build module navigation: categorized links to all modules\n• Document environment configuration: development, staging, production\n• List SDKs and tools: client libraries, Postman collection\nMODE: write\nCONTEXT: @[all_module_docs] @.workflow/docs/${project_name}/api/swagger.yaml\nEXPECTED: Complete API overview in {lang} with navigation links\nCONSTRAINTS: Clear structure | Quick start focus\n--rule development-feature",
|
||||
"output": "README.md"
|
||||
}
|
||||
],
|
||||
@@ -602,7 +602,7 @@ bash(cat ${session_dir}/.process/swagger-planning-data.json | jq -r '.api_struct
|
||||
{
|
||||
"step": 1,
|
||||
"title": "Generate test report",
|
||||
"cli_prompt": "PURPOSE: Generate comprehensive API test validation report\nTASK:\n• Document test environment configuration\n• Calculate endpoint coverage statistics\n• Report test results: pass/fail counts\n• Document boundary tests: parameter limits, null values, special characters\n• Document exception tests: auth failures, permission denied, resource not found\n• List issues found with recommendations\nMODE: write\nCONTEXT: @[swagger_spec]\nEXPECTED: Complete test report in {lang} with detailed results\nRULES: $(cat ~/.claude/workflows/cli-templates/protocols/write-protocol.md) | Include test cases | Clear pass/fail status",
|
||||
"cli_prompt": "PURPOSE: Generate comprehensive API test validation report\nTASK:\n• Document test environment configuration\n• Calculate endpoint coverage statistics\n• Report test results: pass/fail counts\n• Document boundary tests: parameter limits, null values, special characters\n• Document exception tests: auth failures, permission denied, resource not found\n• List issues found with recommendations\nMODE: write\nCONTEXT: @[swagger_spec]\nEXPECTED: Complete test report in {lang} with detailed results\nCONSTRAINTS: Include test cases | Clear pass/fail status\n--rule development-tests",
|
||||
"output": "{test_doc_name}"
|
||||
}
|
||||
],
|
||||
|
||||
@@ -147,8 +147,8 @@ You are generating path-conditional rules for Claude Code.
|
||||
|
||||
## Instructions
|
||||
|
||||
Read the agent prompt template for detailed instructions:
|
||||
$(cat ~/.claude/workflows/cli-templates/prompts/rules/tech-rules-agent-prompt.txt)
|
||||
Read the agent prompt template for detailed instructions.
|
||||
Use --rule rules-tech-rules-agent-prompt to load the template automatically.
|
||||
|
||||
## Execution Steps
|
||||
|
||||
|
||||
666
.claude/commands/workflow/debug-with-file.md
Normal file
666
.claude/commands/workflow/debug-with-file.md
Normal file
@@ -0,0 +1,666 @@
|
||||
---
|
||||
name: debug-with-file
|
||||
description: Interactive hypothesis-driven debugging with documented exploration, understanding evolution, and Gemini-assisted correction
|
||||
argument-hint: "\"bug description or error message\""
|
||||
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
|
||||
---
|
||||
|
||||
# Workflow Debug-With-File Command (/workflow:debug-with-file)
|
||||
|
||||
## Overview
|
||||
|
||||
Enhanced evidence-based debugging with **documented exploration process**. Records understanding evolution, consolidates insights, and uses Gemini to correct misunderstandings.
|
||||
|
||||
**Core workflow**: Explore → Document → Log → Analyze → Correct Understanding → Fix → Verify
|
||||
|
||||
**Key enhancements over /workflow:debug**:
|
||||
- **understanding.md**: Timeline of exploration and learning
|
||||
- **Gemini-assisted correction**: Validates and corrects hypotheses
|
||||
- **Consolidation**: Simplifies proven-wrong understanding to avoid clutter
|
||||
- **Learning retention**: Preserves what was learned, even from failed attempts
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
/workflow:debug-with-file <BUG_DESCRIPTION>
|
||||
|
||||
# Arguments
|
||||
<bug-description> Bug description, error message, or stack trace (required)
|
||||
```
|
||||
|
||||
## Execution Process
|
||||
|
||||
```
|
||||
Session Detection:
|
||||
├─ Check if debug session exists for this bug
|
||||
├─ EXISTS + understanding.md exists → Continue mode
|
||||
└─ NOT_FOUND → Explore mode
|
||||
|
||||
Explore Mode:
|
||||
├─ Locate error source in codebase
|
||||
├─ Document initial understanding in understanding.md
|
||||
├─ Generate testable hypotheses with Gemini validation
|
||||
├─ Add NDJSON logging instrumentation
|
||||
└─ Output: Hypothesis list + await user reproduction
|
||||
|
||||
Analyze Mode:
|
||||
├─ Parse debug.log, validate each hypothesis
|
||||
├─ Use Gemini to analyze evidence and correct understanding
|
||||
├─ Update understanding.md with:
|
||||
│ ├─ New evidence
|
||||
│ ├─ Corrected misunderstandings (strikethrough + correction)
|
||||
│ └─ Consolidated current understanding
|
||||
└─ Decision:
|
||||
├─ Confirmed → Fix root cause
|
||||
├─ Inconclusive → Add more logging, iterate
|
||||
└─ All rejected → Gemini-assisted new hypotheses
|
||||
|
||||
Fix & Cleanup:
|
||||
├─ Apply fix based on confirmed hypothesis
|
||||
├─ User verifies
|
||||
├─ Document final understanding + lessons learned
|
||||
├─ Remove debug instrumentation
|
||||
└─ If not fixed → Return to Analyze mode
|
||||
```
|
||||
|
||||
## Implementation
|
||||
|
||||
### Session Setup & Mode Detection
|
||||
|
||||
```javascript
|
||||
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
|
||||
|
||||
const bugSlug = bug_description.toLowerCase().replace(/[^a-z0-9]+/g, '-').substring(0, 30)
|
||||
const dateStr = getUtc8ISOString().substring(0, 10)
|
||||
|
||||
const sessionId = `DBG-${bugSlug}-${dateStr}`
|
||||
const sessionFolder = `.workflow/.debug/${sessionId}`
|
||||
const debugLogPath = `${sessionFolder}/debug.log`
|
||||
const understandingPath = `${sessionFolder}/understanding.md`
|
||||
const hypothesesPath = `${sessionFolder}/hypotheses.json`
|
||||
|
||||
// Auto-detect mode
|
||||
const sessionExists = fs.existsSync(sessionFolder)
|
||||
const hasUnderstanding = sessionExists && fs.existsSync(understandingPath)
|
||||
const logHasContent = sessionExists && fs.existsSync(debugLogPath) && fs.statSync(debugLogPath).size > 0
|
||||
|
||||
const mode = logHasContent ? 'analyze' : (hasUnderstanding ? 'continue' : 'explore')
|
||||
|
||||
if (!sessionExists) {
|
||||
bash(`mkdir -p ${sessionFolder}`)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Explore Mode
|
||||
|
||||
**Step 1.1: Locate Error Source**
|
||||
|
||||
```javascript
|
||||
// Extract keywords from bug description
|
||||
const keywords = extractErrorKeywords(bug_description)
|
||||
|
||||
// Search codebase for error locations
|
||||
const searchResults = []
|
||||
for (const keyword of keywords) {
|
||||
const results = Grep({ pattern: keyword, path: ".", output_mode: "content", "-C": 3 })
|
||||
searchResults.push({ keyword, results })
|
||||
}
|
||||
|
||||
// Identify affected files and functions
|
||||
const affectedLocations = analyzeSearchResults(searchResults)
|
||||
```
|
||||
|
||||
**Step 1.2: Document Initial Understanding**
|
||||
|
||||
Create `understanding.md` with exploration timeline:
|
||||
|
||||
```markdown
|
||||
# Understanding Document
|
||||
|
||||
**Session ID**: ${sessionId}
|
||||
**Bug Description**: ${bug_description}
|
||||
**Started**: ${getUtc8ISOString()}
|
||||
|
||||
---
|
||||
|
||||
## Exploration Timeline
|
||||
|
||||
### Iteration 1 - Initial Exploration (${timestamp})
|
||||
|
||||
#### Current Understanding
|
||||
|
||||
Based on bug description and initial code search:
|
||||
|
||||
- Error pattern: ${errorPattern}
|
||||
- Affected areas: ${affectedLocations.map(l => l.file).join(', ')}
|
||||
- Initial hypothesis: ${initialThoughts}
|
||||
|
||||
#### Evidence from Code Search
|
||||
|
||||
${searchResults.map(r => `
|
||||
**Keyword: "${r.keyword}"**
|
||||
- Found in: ${r.results.files.join(', ')}
|
||||
- Key findings: ${r.insights}
|
||||
`).join('\n')}
|
||||
|
||||
#### Next Steps
|
||||
|
||||
- Generate testable hypotheses
|
||||
- Add instrumentation
|
||||
- Await reproduction
|
||||
|
||||
---
|
||||
|
||||
## Current Consolidated Understanding
|
||||
|
||||
${initialConsolidatedUnderstanding}
|
||||
```
|
||||
|
||||
**Step 1.3: Gemini-Assisted Hypothesis Generation**
|
||||
|
||||
```bash
|
||||
ccw cli -p "
|
||||
PURPOSE: Generate debugging hypotheses for: ${bug_description}
|
||||
Success criteria: Testable hypotheses with clear evidence criteria
|
||||
|
||||
TASK:
|
||||
• Analyze error pattern and code search results
|
||||
• Identify 3-5 most likely root causes
|
||||
• For each hypothesis, specify:
|
||||
- What might be wrong
|
||||
- What evidence would confirm/reject it
|
||||
- Where to add instrumentation
|
||||
• Rank by likelihood
|
||||
|
||||
MODE: analysis
|
||||
|
||||
CONTEXT: @${sessionFolder}/understanding.md | Search results in understanding.md
|
||||
|
||||
EXPECTED:
|
||||
- Structured hypothesis list (JSON format)
|
||||
- Each hypothesis with: id, description, testable_condition, logging_point, evidence_criteria
|
||||
- Likelihood ranking (1=most likely)
|
||||
|
||||
CONSTRAINTS: Focus on testable conditions
|
||||
" --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause
|
||||
```
|
||||
|
||||
Save Gemini output to `hypotheses.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"iteration": 1,
|
||||
"timestamp": "2025-01-21T10:00:00+08:00",
|
||||
"hypotheses": [
|
||||
{
|
||||
"id": "H1",
|
||||
"description": "Data structure mismatch - expected key not present",
|
||||
"testable_condition": "Check if target key exists in dict",
|
||||
"logging_point": "file.py:func:42",
|
||||
"evidence_criteria": {
|
||||
"confirm": "data shows missing key",
|
||||
"reject": "key exists with valid value"
|
||||
},
|
||||
"likelihood": 1,
|
||||
"status": "pending"
|
||||
}
|
||||
],
|
||||
"gemini_insights": "...",
|
||||
"corrected_assumptions": []
|
||||
}
|
||||
```
|
||||
|
||||
**Step 1.4: Add NDJSON Instrumentation**
|
||||
|
||||
For each hypothesis, add logging (same as original debug command).
|
||||
|
||||
**Step 1.5: Update understanding.md**
|
||||
|
||||
Append hypothesis section:
|
||||
|
||||
```markdown
|
||||
#### Hypotheses Generated (Gemini-Assisted)
|
||||
|
||||
${hypotheses.map(h => `
|
||||
**${h.id}** (Likelihood: ${h.likelihood}): ${h.description}
|
||||
- Logging at: ${h.logging_point}
|
||||
- Testing: ${h.testable_condition}
|
||||
- Evidence to confirm: ${h.evidence_criteria.confirm}
|
||||
- Evidence to reject: ${h.evidence_criteria.reject}
|
||||
`).join('\n')}
|
||||
|
||||
**Gemini Insights**: ${geminiInsights}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Analyze Mode
|
||||
|
||||
**Step 2.1: Parse Debug Log**
|
||||
|
||||
```javascript
|
||||
// Parse NDJSON log
|
||||
const entries = Read(debugLogPath).split('\n')
|
||||
.filter(l => l.trim())
|
||||
.map(l => JSON.parse(l))
|
||||
|
||||
// Group by hypothesis
|
||||
const byHypothesis = groupBy(entries, 'hid')
|
||||
```
|
||||
|
||||
**Step 2.2: Gemini-Assisted Evidence Analysis**
|
||||
|
||||
```bash
|
||||
ccw cli -p "
|
||||
PURPOSE: Analyze debug log evidence to validate/correct hypotheses for: ${bug_description}
|
||||
Success criteria: Clear verdict per hypothesis + corrected understanding
|
||||
|
||||
TASK:
|
||||
• Parse log entries by hypothesis
|
||||
• Evaluate evidence against expected criteria
|
||||
• Determine verdict: confirmed | rejected | inconclusive
|
||||
• Identify incorrect assumptions from previous understanding
|
||||
• Suggest corrections to understanding
|
||||
|
||||
MODE: analysis
|
||||
|
||||
CONTEXT:
|
||||
@${debugLogPath}
|
||||
@${understandingPath}
|
||||
@${hypothesesPath}
|
||||
|
||||
EXPECTED:
|
||||
- Per-hypothesis verdict with reasoning
|
||||
- Evidence summary
|
||||
- List of incorrect assumptions with corrections
|
||||
- Updated consolidated understanding
|
||||
- Root cause if confirmed, or next investigation steps
|
||||
|
||||
CONSTRAINTS: Evidence-based reasoning only, no speculation
|
||||
" --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause
|
||||
```
|
||||
|
||||
**Step 2.3: Update Understanding with Corrections**
|
||||
|
||||
Append new iteration to `understanding.md`:
|
||||
|
||||
```markdown
|
||||
### Iteration ${n} - Evidence Analysis (${timestamp})
|
||||
|
||||
#### Log Analysis Results
|
||||
|
||||
${results.map(r => `
|
||||
**${r.id}**: ${r.verdict.toUpperCase()}
|
||||
- Evidence: ${JSON.stringify(r.evidence)}
|
||||
- Reasoning: ${r.reason}
|
||||
`).join('\n')}
|
||||
|
||||
#### Corrected Understanding
|
||||
|
||||
Previous misunderstandings identified and corrected:
|
||||
|
||||
${corrections.map(c => `
|
||||
- ~~${c.wrong}~~ → ${c.corrected}
|
||||
- Why wrong: ${c.reason}
|
||||
- Evidence: ${c.evidence}
|
||||
`).join('\n')}
|
||||
|
||||
#### New Insights
|
||||
|
||||
${newInsights.join('\n- ')}
|
||||
|
||||
#### Gemini Analysis
|
||||
|
||||
${geminiAnalysis}
|
||||
|
||||
${confirmedHypothesis ? `
|
||||
#### Root Cause Identified
|
||||
|
||||
**${confirmedHypothesis.id}**: ${confirmedHypothesis.description}
|
||||
|
||||
Evidence supporting this conclusion:
|
||||
${confirmedHypothesis.supportingEvidence}
|
||||
` : `
|
||||
#### Next Steps
|
||||
|
||||
${nextSteps}
|
||||
`}
|
||||
|
||||
---
|
||||
|
||||
## Current Consolidated Understanding (Updated)
|
||||
|
||||
${consolidatedUnderstanding}
|
||||
```
|
||||
|
||||
**Step 2.4: Consolidate Understanding**
|
||||
|
||||
At the bottom of `understanding.md`, update the consolidated section:
|
||||
|
||||
- Remove or simplify proven-wrong assumptions
|
||||
- Keep them in strikethrough for reference
|
||||
- Focus on current valid understanding
|
||||
- Avoid repeating details from timeline
|
||||
|
||||
```markdown
|
||||
## Current Consolidated Understanding
|
||||
|
||||
### What We Know
|
||||
|
||||
- ${validUnderstanding1}
|
||||
- ${validUnderstanding2}
|
||||
|
||||
### What Was Disproven
|
||||
|
||||
- ~~Initial assumption: ${wrongAssumption}~~ (Evidence: ${disproofEvidence})
|
||||
|
||||
### Current Investigation Focus
|
||||
|
||||
${currentFocus}
|
||||
|
||||
### Remaining Questions
|
||||
|
||||
- ${openQuestion1}
|
||||
- ${openQuestion2}
|
||||
```
|
||||
|
||||
**Step 2.5: Update hypotheses.json**
|
||||
|
||||
```json
|
||||
{
|
||||
"iteration": 2,
|
||||
"timestamp": "2025-01-21T10:15:00+08:00",
|
||||
"hypotheses": [
|
||||
{
|
||||
"id": "H1",
|
||||
"status": "rejected",
|
||||
"verdict_reason": "Evidence shows key exists with valid value",
|
||||
"evidence": {...}
|
||||
},
|
||||
{
|
||||
"id": "H2",
|
||||
"status": "confirmed",
|
||||
"verdict_reason": "Log data confirms timing issue",
|
||||
"evidence": {...}
|
||||
}
|
||||
],
|
||||
"gemini_corrections": [
|
||||
{
|
||||
"wrong_assumption": "...",
|
||||
"corrected_to": "...",
|
||||
"reason": "..."
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Fix & Verification
|
||||
|
||||
**Step 3.1: Apply Fix**
|
||||
|
||||
(Same as original debug command)
|
||||
|
||||
**Step 3.2: Document Resolution**
|
||||
|
||||
Append to `understanding.md`:
|
||||
|
||||
```markdown
|
||||
### Iteration ${n} - Resolution (${timestamp})
|
||||
|
||||
#### Fix Applied
|
||||
|
||||
- Modified files: ${modifiedFiles.join(', ')}
|
||||
- Fix description: ${fixDescription}
|
||||
- Root cause addressed: ${rootCause}
|
||||
|
||||
#### Verification Results
|
||||
|
||||
${verificationResults}
|
||||
|
||||
#### Lessons Learned
|
||||
|
||||
What we learned from this debugging session:
|
||||
|
||||
1. ${lesson1}
|
||||
2. ${lesson2}
|
||||
3. ${lesson3}
|
||||
|
||||
#### Key Insights for Future
|
||||
|
||||
- ${insight1}
|
||||
- ${insight2}
|
||||
```
|
||||
|
||||
**Step 3.3: Cleanup**
|
||||
|
||||
Remove debug instrumentation (same as original command).
|
||||
|
||||
---
|
||||
|
||||
## Session Folder Structure
|
||||
|
||||
```
|
||||
.workflow/.debug/DBG-{slug}-{date}/
|
||||
├── debug.log # NDJSON log (execution evidence)
|
||||
├── understanding.md # NEW: Exploration timeline + consolidated understanding
|
||||
├── hypotheses.json # NEW: Hypothesis history with verdicts
|
||||
└── resolution.md # Optional: Final summary
|
||||
```
|
||||
|
||||
## Understanding Document Template
|
||||
|
||||
```markdown
|
||||
# Understanding Document
|
||||
|
||||
**Session ID**: DBG-xxx-2025-01-21
|
||||
**Bug Description**: [original description]
|
||||
**Started**: 2025-01-21T10:00:00+08:00
|
||||
|
||||
---
|
||||
|
||||
## Exploration Timeline
|
||||
|
||||
### Iteration 1 - Initial Exploration (2025-01-21 10:00)
|
||||
|
||||
#### Current Understanding
|
||||
...
|
||||
|
||||
#### Evidence from Code Search
|
||||
...
|
||||
|
||||
#### Hypotheses Generated (Gemini-Assisted)
|
||||
...
|
||||
|
||||
### Iteration 2 - Evidence Analysis (2025-01-21 10:15)
|
||||
|
||||
#### Log Analysis Results
|
||||
...
|
||||
|
||||
#### Corrected Understanding
|
||||
- ~~[wrong]~~ → [corrected]
|
||||
|
||||
#### Gemini Analysis
|
||||
...
|
||||
|
||||
---
|
||||
|
||||
## Current Consolidated Understanding
|
||||
|
||||
### What We Know
|
||||
- [valid understanding points]
|
||||
|
||||
### What Was Disproven
|
||||
- ~~[disproven assumptions]~~
|
||||
|
||||
### Current Investigation Focus
|
||||
[current focus]
|
||||
|
||||
### Remaining Questions
|
||||
- [open questions]
|
||||
```
|
||||
|
||||
## Iteration Flow
|
||||
|
||||
```
|
||||
First Call (/workflow:debug-with-file "error"):
|
||||
├─ No session exists → Explore mode
|
||||
├─ Extract error keywords, search codebase
|
||||
├─ Document initial understanding in understanding.md
|
||||
├─ Use Gemini to generate hypotheses
|
||||
├─ Add logging instrumentation
|
||||
└─ Await user reproduction
|
||||
|
||||
After Reproduction (/workflow:debug-with-file "error"):
|
||||
├─ Session exists + debug.log has content → Analyze mode
|
||||
├─ Parse log, use Gemini to evaluate hypotheses
|
||||
├─ Update understanding.md with:
|
||||
│ ├─ Evidence analysis results
|
||||
│ ├─ Corrected misunderstandings (strikethrough)
|
||||
│ ├─ New insights
|
||||
│ └─ Updated consolidated understanding
|
||||
├─ Update hypotheses.json with verdicts
|
||||
└─ Decision:
|
||||
├─ Confirmed → Fix → Document resolution
|
||||
├─ Inconclusive → Add logging, document next steps
|
||||
└─ All rejected → Gemini-assisted new hypotheses
|
||||
|
||||
Output:
|
||||
├─ .workflow/.debug/DBG-{slug}-{date}/debug.log
|
||||
├─ .workflow/.debug/DBG-{slug}-{date}/understanding.md (evolving document)
|
||||
└─ .workflow/.debug/DBG-{slug}-{date}/hypotheses.json (history)
|
||||
```
|
||||
|
||||
## Gemini Integration Points
|
||||
|
||||
### 1. Hypothesis Generation (Explore Mode)
|
||||
|
||||
**Purpose**: Generate evidence-based, testable hypotheses
|
||||
|
||||
**Prompt Pattern**:
|
||||
```
|
||||
PURPOSE: Generate debugging hypotheses + evidence criteria
|
||||
TASK: Analyze error + code → testable hypotheses with clear pass/fail criteria
|
||||
CONTEXT: @understanding.md (search results)
|
||||
EXPECTED: JSON with hypotheses, likelihood ranking, evidence criteria
|
||||
```
|
||||
|
||||
### 2. Evidence Analysis (Analyze Mode)
|
||||
|
||||
**Purpose**: Validate hypotheses and correct misunderstandings
|
||||
|
||||
**Prompt Pattern**:
|
||||
```
|
||||
PURPOSE: Analyze debug log evidence + correct understanding
|
||||
TASK: Evaluate each hypothesis → identify wrong assumptions → suggest corrections
|
||||
CONTEXT: @debug.log @understanding.md @hypotheses.json
|
||||
EXPECTED: Verdicts + corrections + updated consolidated understanding
|
||||
```
|
||||
|
||||
### 3. New Hypothesis Generation (After All Rejected)
|
||||
|
||||
**Purpose**: Generate new hypotheses based on what was disproven
|
||||
|
||||
**Prompt Pattern**:
|
||||
```
|
||||
PURPOSE: Generate new hypotheses given disproven assumptions
|
||||
TASK: Review rejected hypotheses → identify knowledge gaps → new investigation angles
|
||||
CONTEXT: @understanding.md (with disproven section) @hypotheses.json
|
||||
EXPECTED: New hypotheses avoiding previously rejected paths
|
||||
```
|
||||
|
||||
## Error Correction Mechanism
|
||||
|
||||
### Correction Format in understanding.md
|
||||
|
||||
```markdown
|
||||
#### Corrected Understanding
|
||||
|
||||
- ~~Assumed dict key "config" was missing~~ → Key exists, but value is None
|
||||
- Why wrong: Only checked existence, not value validity
|
||||
- Evidence: H1 log shows {"config": null, "exists": true}
|
||||
|
||||
- ~~Thought error occurred in initialization~~ → Error happens during runtime update
|
||||
- Why wrong: Stack trace misread as init code
|
||||
- Evidence: H2 timestamp shows 30s after startup
|
||||
```
|
||||
|
||||
### Consolidation Rules
|
||||
|
||||
When updating "Current Consolidated Understanding":
|
||||
|
||||
1. **Simplify disproven items**: Move to "What Was Disproven" with single-line summary
|
||||
2. **Keep valid insights**: Promote confirmed findings to "What We Know"
|
||||
3. **Avoid duplication**: Don't repeat timeline details in consolidated section
|
||||
4. **Focus on current state**: What do we know NOW, not the journey
|
||||
5. **Preserve key corrections**: Keep important wrong→right transformations for learning
|
||||
|
||||
**Bad (cluttered)**:
|
||||
```markdown
|
||||
## Current Consolidated Understanding
|
||||
|
||||
In iteration 1 we thought X, but in iteration 2 we found Y, then in iteration 3...
|
||||
Also we checked A and found B, and then we checked C...
|
||||
```
|
||||
|
||||
**Good (consolidated)**:
|
||||
```markdown
|
||||
## Current Consolidated Understanding
|
||||
|
||||
### What We Know
|
||||
- Error occurs during runtime update, not initialization
|
||||
- Config value is None (not missing key)
|
||||
|
||||
### What Was Disproven
|
||||
- ~~Initialization error~~ (Timing evidence)
|
||||
- ~~Missing key hypothesis~~ (Key exists)
|
||||
|
||||
### Current Investigation Focus
|
||||
Why is config value None during update?
|
||||
```
|
||||
|
||||
## Post-Completion Expansion
|
||||
|
||||
完成后询问用户是否扩展为issue(test/enhance/refactor/doc),选中项调用 `/issue:new "{summary} - {dimension}"`
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Situation | Action |
|
||||
|-----------|--------|
|
||||
| Empty debug.log | Verify reproduction triggered the code path |
|
||||
| All hypotheses rejected | Use Gemini to generate new hypotheses based on disproven assumptions |
|
||||
| Fix doesn't work | Document failed fix attempt, iterate with refined understanding |
|
||||
| >5 iterations | Review consolidated understanding, escalate to `/workflow:lite-fix` with full context |
|
||||
| Gemini unavailable | Fallback to manual hypothesis generation, document without Gemini insights |
|
||||
| Understanding too long | Consolidate aggressively, archive old iterations to separate file |
|
||||
|
||||
## Comparison with /workflow:debug
|
||||
|
||||
| Feature | /workflow:debug | /workflow:debug-with-file |
|
||||
|---------|-----------------|---------------------------|
|
||||
| NDJSON logging | ✅ | ✅ |
|
||||
| Hypothesis generation | Manual | Gemini-assisted |
|
||||
| Exploration documentation | ❌ | ✅ understanding.md |
|
||||
| Understanding evolution | ❌ | ✅ Timeline + corrections |
|
||||
| Error correction | ❌ | ✅ Strikethrough + reasoning |
|
||||
| Consolidated learning | ❌ | ✅ Current understanding section |
|
||||
| Hypothesis history | ❌ | ✅ hypotheses.json |
|
||||
| Gemini validation | ❌ | ✅ At key decision points |
|
||||
|
||||
## Usage Recommendations
|
||||
|
||||
Use `/workflow:debug-with-file` when:
|
||||
- Complex bugs requiring multiple investigation rounds
|
||||
- Learning from debugging process is valuable
|
||||
- Team needs to understand debugging rationale
|
||||
- Bug might recur, documentation helps prevention
|
||||
|
||||
Use `/workflow:debug` when:
|
||||
- Simple, quick bugs
|
||||
- One-off issues
|
||||
- Documentation overhead not needed
|
||||
@@ -81,6 +81,7 @@ AskUserQuestion({
|
||||
options: [
|
||||
{ label: "Skip", description: "No review" },
|
||||
{ label: "Gemini Review", description: "Gemini CLI tool" },
|
||||
{ label: "Codex Review", description: "Git-aware review (prompt OR --uncommitted)" },
|
||||
{ label: "Agent Review", description: "Current agent review" }
|
||||
]
|
||||
}
|
||||
@@ -171,10 +172,23 @@ Output:
|
||||
**Operations**:
|
||||
- Initialize result tracking for multi-execution scenarios
|
||||
- Set up `previousExecutionResults` array for context continuity
|
||||
- **In-Memory Mode**: Echo execution strategy from lite-plan for transparency
|
||||
|
||||
```javascript
|
||||
// Initialize result tracking
|
||||
previousExecutionResults = []
|
||||
|
||||
// In-Memory Mode: Echo execution strategy (transparency before execution)
|
||||
if (executionContext) {
|
||||
console.log(`
|
||||
📋 Execution Strategy (from lite-plan):
|
||||
Method: ${executionContext.executionMethod}
|
||||
Review: ${executionContext.codeReviewTool}
|
||||
Tasks: ${executionContext.planObject.tasks.length}
|
||||
Complexity: ${executionContext.planObject.complexity}
|
||||
${executionContext.executorAssignments ? ` Assignments: ${JSON.stringify(executionContext.executorAssignments)}` : ''}
|
||||
`)
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2: Task Grouping & Batch Creation
|
||||
@@ -313,7 +327,7 @@ for (const call of sequential) {
|
||||
|
||||
```javascript
|
||||
function buildExecutionPrompt(batch) {
|
||||
// Task template (4 parts: Modification Points → How → Reference → Done)
|
||||
// Task template (6 parts: Modification Points → Why → How → Reference → Risks → Done)
|
||||
const formatTask = (t) => `
|
||||
## ${t.title}
|
||||
|
||||
@@ -322,18 +336,38 @@ function buildExecutionPrompt(batch) {
|
||||
### Modification Points
|
||||
${t.modification_points.map(p => `- **${p.file}** → \`${p.target}\`: ${p.change}`).join('\n')}
|
||||
|
||||
${t.rationale ? `
|
||||
### Why this approach (Medium/High)
|
||||
${t.rationale.chosen_approach}
|
||||
${t.rationale.decision_factors?.length > 0 ? `\nKey factors: ${t.rationale.decision_factors.join(', ')}` : ''}
|
||||
${t.rationale.tradeoffs ? `\nTradeoffs: ${t.rationale.tradeoffs}` : ''}
|
||||
` : ''}
|
||||
|
||||
### How to do it
|
||||
${t.description}
|
||||
|
||||
${t.implementation.map(step => `- ${step}`).join('\n')}
|
||||
|
||||
${t.code_skeleton ? `
|
||||
### Code skeleton (High)
|
||||
${t.code_skeleton.interfaces?.length > 0 ? `**Interfaces**: ${t.code_skeleton.interfaces.map(i => `\`${i.name}\` - ${i.purpose}`).join(', ')}` : ''}
|
||||
${t.code_skeleton.key_functions?.length > 0 ? `\n**Functions**: ${t.code_skeleton.key_functions.map(f => `\`${f.signature}\` - ${f.purpose}`).join(', ')}` : ''}
|
||||
${t.code_skeleton.classes?.length > 0 ? `\n**Classes**: ${t.code_skeleton.classes.map(c => `\`${c.name}\` - ${c.purpose}`).join(', ')}` : ''}
|
||||
` : ''}
|
||||
|
||||
### Reference
|
||||
- Pattern: ${t.reference?.pattern || 'N/A'}
|
||||
- Files: ${t.reference?.files?.join(', ') || 'N/A'}
|
||||
${t.reference?.examples ? `- Notes: ${t.reference.examples}` : ''}
|
||||
|
||||
${t.risks?.length > 0 ? `
|
||||
### Risk mitigations (High)
|
||||
${t.risks.map(r => `- ${r.description} → **${r.mitigation}**`).join('\n')}
|
||||
` : ''}
|
||||
|
||||
### Done when
|
||||
${t.acceptance.map(c => `- [ ] ${c}`).join('\n')}`
|
||||
${t.acceptance.map(c => `- [ ] ${c}`).join('\n')}
|
||||
${t.verification?.success_metrics?.length > 0 ? `\n**Success metrics**: ${t.verification.success_metrics.join(', ')}` : ''}`
|
||||
|
||||
// Build prompt
|
||||
const sections = []
|
||||
@@ -350,9 +384,14 @@ ${t.acceptance.map(c => `- [ ] ${c}`).join('\n')}`
|
||||
if (clarificationContext) {
|
||||
context.push(`### Clarifications\n${Object.entries(clarificationContext).map(([q, a]) => `- ${q}: ${a}`).join('\n')}`)
|
||||
}
|
||||
if (executionContext?.planObject?.data_flow?.diagram) {
|
||||
context.push(`### Data Flow\n${executionContext.planObject.data_flow.diagram}`)
|
||||
}
|
||||
if (executionContext?.session?.artifacts?.plan) {
|
||||
context.push(`### Artifacts\nPlan: ${executionContext.session.artifacts.plan}`)
|
||||
}
|
||||
// Project guidelines (user-defined constraints from /workflow:session:solidify)
|
||||
context.push(`### Project Guidelines\n@.workflow/project-guidelines.json`)
|
||||
if (context.length > 0) sections.push(`## Context\n${context.join('\n\n')}`)
|
||||
|
||||
sections.push(`Complete each task according to its "Done when" checklist.`)
|
||||
@@ -392,16 +431,8 @@ ccw cli -p "${buildExecutionPrompt(batch)}" --tool codex --mode write
|
||||
|
||||
**Execution with fixed IDs** (predictable ID pattern):
|
||||
```javascript
|
||||
// Launch CLI in foreground (NOT background)
|
||||
// Timeout based on complexity: Low=40min, Medium=60min, High=100min
|
||||
const timeoutByComplexity = {
|
||||
"Low": 2400000, // 40 minutes
|
||||
"Medium": 3600000, // 60 minutes
|
||||
"High": 6000000 // 100 minutes
|
||||
}
|
||||
|
||||
// Launch CLI in background, wait for task hook callback
|
||||
// Generate fixed execution ID: ${sessionId}-${groupId}
|
||||
// This enables predictable ID lookup without relying on resume context chains
|
||||
const sessionId = executionContext?.session?.id || 'standalone'
|
||||
const fixedExecutionId = `${sessionId}-${batch.groupId}` // e.g., "implement-auth-2025-12-13-P1"
|
||||
|
||||
@@ -413,16 +444,12 @@ const cli_command = previousCliId
|
||||
? `ccw cli -p "${buildExecutionPrompt(batch)}" --tool codex --mode write --id ${fixedExecutionId} --resume ${previousCliId}`
|
||||
: `ccw cli -p "${buildExecutionPrompt(batch)}" --tool codex --mode write --id ${fixedExecutionId}`
|
||||
|
||||
bash_result = Bash(
|
||||
// Execute in background, stop output and wait for task hook callback
|
||||
Bash(
|
||||
command=cli_command,
|
||||
timeout=timeoutByComplexity[planObject.complexity] || 3600000
|
||||
run_in_background=true
|
||||
)
|
||||
|
||||
// Execution ID is now predictable: ${fixedExecutionId}
|
||||
// Can also extract from output: "ID: implement-auth-2025-12-13-P1"
|
||||
const cliExecutionId = fixedExecutionId
|
||||
|
||||
// Update TodoWrite when execution completes
|
||||
// STOP HERE - CLI executes in background, task hook will notify on completion
|
||||
```
|
||||
|
||||
**Resume on Failure** (with fixed ID):
|
||||
@@ -460,32 +487,41 @@ Progress tracked at batch level (not individual task level). Icons: ⚡ (paralle
|
||||
|
||||
**Skip Condition**: Only run if `codeReviewTool ≠ "Skip"`
|
||||
|
||||
**Review Focus**: Verify implementation against plan acceptance criteria
|
||||
- Read plan.json for task acceptance criteria
|
||||
**Review Focus**: Verify implementation against plan acceptance criteria and verification requirements
|
||||
- Read plan.json for task acceptance criteria and verification checklist
|
||||
- Check each acceptance criterion is fulfilled
|
||||
- Verify success metrics from verification field (Medium/High complexity)
|
||||
- Run unit/integration tests specified in verification field
|
||||
- Validate code quality and identify issues
|
||||
- Ensure alignment with planned approach
|
||||
- Ensure alignment with planned approach and risk mitigations
|
||||
|
||||
**Operations**:
|
||||
- Agent Review: Current agent performs direct review
|
||||
- Gemini Review: Execute gemini CLI with review prompt
|
||||
- Custom tool: Execute specified CLI tool (qwen, codex, etc.)
|
||||
- Codex Review: Two options - (A) with prompt for complex reviews, (B) `--uncommitted` flag only for quick reviews
|
||||
- Custom tool: Execute specified CLI tool (qwen, etc.)
|
||||
|
||||
**Unified Review Template** (All tools use same standard):
|
||||
|
||||
**Review Criteria**:
|
||||
- **Acceptance Criteria**: Verify each criterion from plan.tasks[].acceptance
|
||||
- **Verification Checklist** (Medium/High): Check unit_tests, integration_tests, success_metrics from plan.tasks[].verification
|
||||
- **Code Quality**: Analyze quality, identify issues, suggest improvements
|
||||
- **Plan Alignment**: Validate implementation matches planned approach
|
||||
- **Plan Alignment**: Validate implementation matches planned approach and risk mitigations
|
||||
|
||||
**Shared Prompt Template** (used by all CLI tools):
|
||||
```
|
||||
PURPOSE: Code review for implemented changes against plan acceptance criteria
|
||||
TASK: • Verify plan acceptance criteria fulfillment • Analyze code quality • Identify issues • Suggest improvements • Validate plan adherence
|
||||
PURPOSE: Code review for implemented changes against plan acceptance criteria and verification requirements
|
||||
TASK: • Verify plan acceptance criteria fulfillment • Check verification requirements (unit tests, success metrics) • Analyze code quality • Identify issues • Suggest improvements • Validate plan adherence and risk mitigations
|
||||
MODE: analysis
|
||||
CONTEXT: @**/* @{plan.json} [@{exploration.json}] | Memory: Review lite-execute changes against plan requirements
|
||||
EXPECTED: Quality assessment with acceptance criteria verification, issue identification, and recommendations. Explicitly check each acceptance criterion from plan.json tasks.
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/02-review-code-quality.txt) | Focus on plan acceptance criteria and plan adherence | analysis=READ-ONLY
|
||||
CONTEXT: @**/* @{plan.json} [@{exploration.json}] | Memory: Review lite-execute changes against plan requirements including verification checklist
|
||||
EXPECTED: Quality assessment with:
|
||||
- Acceptance criteria verification (all tasks)
|
||||
- Verification checklist validation (Medium/High: unit_tests, integration_tests, success_metrics)
|
||||
- Issue identification
|
||||
- Recommendations
|
||||
Explicitly check each acceptance criterion and verification item from plan.json tasks.
|
||||
CONSTRAINTS: Focus on plan acceptance criteria, verification requirements, and plan adherence | analysis=READ-ONLY
|
||||
```
|
||||
|
||||
**Tool-Specific Execution** (Apply shared prompt template above):
|
||||
@@ -504,8 +540,17 @@ ccw cli -p "[Shared Prompt Template with artifacts]" --tool gemini --mode analys
|
||||
ccw cli -p "[Shared Prompt Template with artifacts]" --tool qwen --mode analysis
|
||||
# Same prompt as Gemini, different execution engine
|
||||
|
||||
# Method 4: Codex Review (autonomous)
|
||||
ccw cli -p "[Verify plan acceptance criteria at ${plan.json}]" --tool codex --mode write
|
||||
# Method 4: Codex Review (git-aware) - Two mutually exclusive options:
|
||||
|
||||
# Option A: With custom prompt (reviews uncommitted by default)
|
||||
ccw cli -p "[Shared Prompt Template with artifacts]" --tool codex --mode review
|
||||
# Use for complex reviews with specific focus areas
|
||||
|
||||
# Option B: Target flag only (no prompt allowed)
|
||||
ccw cli --tool codex --mode review --uncommitted
|
||||
# Quick review of uncommitted changes without custom instructions
|
||||
|
||||
# ⚠️ IMPORTANT: -p prompt and target flags (--uncommitted/--base/--commit) are MUTUALLY EXCLUSIVE
|
||||
```
|
||||
|
||||
**Multi-Round Review with Fixed IDs**:
|
||||
|
||||
@@ -380,6 +380,7 @@ if (uniqueClarifications.length > 0) {
|
||||
const schema = Bash(`cat ~/.claude/workflows/cli-templates/schemas/fix-plan-json-schema.json`)
|
||||
|
||||
// Step 2: Generate fix-plan following schema (Claude directly, no agent)
|
||||
// For Medium complexity: include rationale + verification (optional, but recommended)
|
||||
const fixPlan = {
|
||||
summary: "...",
|
||||
root_cause: "...",
|
||||
@@ -389,13 +390,67 @@ const fixPlan = {
|
||||
recommended_execution: "Agent",
|
||||
severity: severity,
|
||||
risk_level: "...",
|
||||
_metadata: { timestamp: getUtc8ISOString(), source: "direct-planning", planning_mode: "direct" }
|
||||
|
||||
// Medium complexity fields (optional for direct planning, auto-filled for Low)
|
||||
...(severity === "Medium" ? {
|
||||
design_decisions: [
|
||||
{
|
||||
decision: "Use immediate_patch strategy for minimal risk",
|
||||
rationale: "Keeps changes localized and quick to review",
|
||||
tradeoff: "Defers comprehensive refactoring"
|
||||
}
|
||||
],
|
||||
tasks_with_rationale: {
|
||||
// Each task gets rationale if Medium
|
||||
task_rationale_example: {
|
||||
rationale: {
|
||||
chosen_approach: "Direct fix approach",
|
||||
alternatives_considered: ["Workaround", "Refactor"],
|
||||
decision_factors: ["Minimal impact", "Quick turnaround"],
|
||||
tradeoffs: "Doesn't address underlying issue"
|
||||
},
|
||||
verification: {
|
||||
unit_tests: ["test_bug_fix_basic"],
|
||||
integration_tests: [],
|
||||
manual_checks: ["Reproduce issue", "Verify fix"],
|
||||
success_metrics: ["Issue resolved", "No regressions"]
|
||||
}
|
||||
}
|
||||
}
|
||||
} : {}),
|
||||
|
||||
_metadata: {
|
||||
timestamp: getUtc8ISOString(),
|
||||
source: "direct-planning",
|
||||
planning_mode: "direct",
|
||||
complexity: severity === "Medium" ? "Medium" : "Low"
|
||||
}
|
||||
}
|
||||
|
||||
// Step 3: Write fix-plan to session folder
|
||||
// Step 3: Merge task rationale into tasks array
|
||||
if (severity === "Medium") {
|
||||
fixPlan.tasks = fixPlan.tasks.map(task => ({
|
||||
...task,
|
||||
rationale: fixPlan.tasks_with_rationale[task.id]?.rationale || {
|
||||
chosen_approach: "Standard fix",
|
||||
alternatives_considered: [],
|
||||
decision_factors: ["Correctness", "Simplicity"],
|
||||
tradeoffs: "None"
|
||||
},
|
||||
verification: fixPlan.tasks_with_rationale[task.id]?.verification || {
|
||||
unit_tests: [`test_${task.id}_basic`],
|
||||
integration_tests: [],
|
||||
manual_checks: ["Verify fix works"],
|
||||
success_metrics: ["Test pass"]
|
||||
}
|
||||
}))
|
||||
delete fixPlan.tasks_with_rationale // Clean up temp field
|
||||
}
|
||||
|
||||
// Step 4: Write fix-plan to session folder
|
||||
Write(`${sessionFolder}/fix-plan.json`, JSON.stringify(fixPlan, null, 2))
|
||||
|
||||
// Step 4: MUST continue to Phase 4 (Confirmation) - DO NOT execute code here
|
||||
// Step 5: MUST continue to Phase 4 (Confirmation) - DO NOT execute code here
|
||||
```
|
||||
|
||||
**High/Critical Severity** - Invoke cli-lite-planning-agent:
|
||||
@@ -451,11 +506,41 @@ Generate fix-plan.json with:
|
||||
- description
|
||||
- modification_points: ALL files to modify for this fix (group related changes)
|
||||
- implementation (2-5 steps covering all modification_points)
|
||||
- verification (test criteria)
|
||||
- acceptance: Quantified acceptance criteria
|
||||
- depends_on: task IDs this task depends on (use sparingly)
|
||||
|
||||
**High/Critical complexity fields per task** (REQUIRED):
|
||||
- rationale:
|
||||
- chosen_approach: Why this fix approach (not alternatives)
|
||||
- alternatives_considered: Other approaches evaluated
|
||||
- decision_factors: Key factors influencing choice
|
||||
- tradeoffs: Known tradeoffs of this approach
|
||||
- verification:
|
||||
- unit_tests: Test names to add/verify
|
||||
- integration_tests: Integration test names
|
||||
- manual_checks: Manual verification steps
|
||||
- success_metrics: Quantified success criteria
|
||||
- risks:
|
||||
- description: Risk description
|
||||
- probability: Low|Medium|High
|
||||
- impact: Low|Medium|High
|
||||
- mitigation: How to mitigate
|
||||
- fallback: Fallback if fix fails
|
||||
- code_skeleton (optional): Key interfaces/functions to implement
|
||||
- interfaces: [{name, definition, purpose}]
|
||||
- key_functions: [{signature, purpose, returns}]
|
||||
|
||||
**Top-level High/Critical fields** (REQUIRED):
|
||||
- data_flow: How data flows through affected code
|
||||
- diagram: "A → B → C" style flow
|
||||
- stages: [{stage, input, output, component}]
|
||||
- design_decisions: Global fix decisions
|
||||
- [{decision, rationale, tradeoff}]
|
||||
|
||||
- estimated_time, recommended_execution, severity, risk_level
|
||||
- _metadata:
|
||||
- timestamp, source, planning_mode
|
||||
- complexity: "High" | "Critical"
|
||||
- diagnosis_angles: ${JSON.stringify(manifest.diagnoses.map(d => d.angle))}
|
||||
|
||||
## Task Grouping Rules
|
||||
@@ -467,11 +552,21 @@ Generate fix-plan.json with:
|
||||
|
||||
## Execution
|
||||
1. Read ALL diagnosis files for comprehensive context
|
||||
2. Execute CLI planning using Gemini (Qwen fallback)
|
||||
2. Execute CLI planning using Gemini (Qwen fallback) with --rule planning-fix-strategy template
|
||||
3. Synthesize findings from multiple diagnosis angles
|
||||
4. Parse output and structure fix-plan
|
||||
5. Write JSON: Write('${sessionFolder}/fix-plan.json', jsonContent)
|
||||
6. Return brief completion summary
|
||||
4. Generate fix-plan with:
|
||||
- For High/Critical: REQUIRED new fields (rationale, verification, risks, code_skeleton, data_flow, design_decisions)
|
||||
- Each task MUST have rationale (why this fix), verification (how to verify success), and risks (potential issues)
|
||||
5. Parse output and structure fix-plan
|
||||
6. Write JSON: Write('${sessionFolder}/fix-plan.json', jsonContent)
|
||||
7. Return brief completion summary
|
||||
|
||||
## Output Format for CLI
|
||||
Include these sections in your fix-plan output:
|
||||
- Summary, Root Cause, Strategy (existing)
|
||||
- Data Flow: Diagram showing affected code paths
|
||||
- Design Decisions: Key architectural choices in the fix
|
||||
- Tasks: Each with rationale (Medium/High), verification (Medium/High), risks (High), code_skeleton (High)
|
||||
`
|
||||
)
|
||||
```
|
||||
@@ -565,7 +660,11 @@ const fixPlan = JSON.parse(Read(`${sessionFolder}/fix-plan.json`))
|
||||
executionContext = {
|
||||
mode: "bugfix",
|
||||
severity: fixPlan.severity,
|
||||
planObject: fixPlan,
|
||||
planObject: {
|
||||
...fixPlan,
|
||||
// Ensure complexity is set based on severity for new field consumption
|
||||
complexity: fixPlan.complexity || (fixPlan.severity === 'Critical' ? 'High' : (fixPlan.severity === 'High' ? 'High' : 'Medium'))
|
||||
},
|
||||
diagnosisContext: diagnoses,
|
||||
diagnosisAngles: manifest.diagnoses.map(d => d.angle),
|
||||
diagnosisManifest: manifest,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
---
|
||||
name: workflow:lite-lite-lite
|
||||
description: Ultra-lightweight multi-tool analysis and direct execution. No artifacts, auto tool selection based on task analysis, user-driven iteration via AskUser.
|
||||
description: Ultra-lightweight multi-tool analysis and direct execution. No artifacts for simple tasks; auto-creates planning docs in .workflow/.scratchpad/ for complex tasks. Auto tool selection based on task analysis, user-driven iteration via AskUser.
|
||||
argument-hint: "<task description>"
|
||||
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Bash(*), mcp__ace-tool__search_context(*)
|
||||
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Bash(*), Write(*), mcp__ace-tool__search_context(*), mcp__ccw-tools__write_file(*)
|
||||
---
|
||||
|
||||
# Ultra-Lite Multi-Tool Workflow
|
||||
@@ -14,22 +14,23 @@ allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Bash(*), mcp_
|
||||
/workflow:lite-lite-lite "Refactor payment module for multi-gateway support"
|
||||
```
|
||||
|
||||
**Core Philosophy**: Minimal friction, maximum velocity. No files, no artifacts - just analyze and execute.
|
||||
**Core Philosophy**: Minimal friction, maximum velocity. Simple tasks = no artifacts. Complex tasks = lightweight planning doc in `.workflow/.scratchpad/`.
|
||||
|
||||
## Overview
|
||||
|
||||
**Zero-artifact workflow**: Clarify → Select Tools → Multi-Mode Analysis → Decision → Direct Execution
|
||||
**Complexity-aware workflow**: Clarify → Assess Complexity → Select Tools → Multi-Mode Analysis → Decision → Direct Execution
|
||||
|
||||
**vs multi-cli-plan**: No IMPL_PLAN.md, plan.json, synthesis.json - all state in memory.
|
||||
**vs multi-cli-plan**: No IMPL_PLAN.md, plan.json, synthesis.json - state in memory or lightweight scratchpad doc for complex tasks.
|
||||
|
||||
## Execution Flow
|
||||
|
||||
```
|
||||
Phase 1: Clarify Requirements → AskUser for missing details
|
||||
Phase 1.5: Assess Complexity → Determine if planning doc needed
|
||||
Phase 2: Select Tools (CLI → Mode → Agent) → 3-step selection
|
||||
Phase 3: Multi-Mode Analysis → Execute with --resume chaining
|
||||
Phase 4: User Decision → Execute / Refine / Change / Cancel
|
||||
Phase 5: Direct Execution → No plan files, immediate implementation
|
||||
Phase 5: Direct Execution → No plan files (simple) or scratchpad doc (complex)
|
||||
```
|
||||
|
||||
## Phase 1: Clarify Requirements
|
||||
@@ -58,6 +59,25 @@ mcp__ace-tool__search_context({
|
||||
})
|
||||
```
|
||||
|
||||
## Phase 1.5: Assess Complexity
|
||||
|
||||
| Level | Creates Plan Doc | Trigger Keywords |
|
||||
|-------|------------------|------------------|
|
||||
| **simple** | ❌ | (default) |
|
||||
| **moderate** | ✅ | module, system, service, integration, multiple |
|
||||
| **complex** | ✅ | refactor, migrate, security, auth, payment, database |
|
||||
|
||||
```javascript
|
||||
// Complexity detection (after ACE query)
|
||||
const isComplex = /refactor|migrate|security|auth|payment|database/i.test(taskDescription)
|
||||
const isModerate = /module|system|service|integration|multiple/i.test(taskDescription) || aceContext?.relevant_files?.length > 2
|
||||
|
||||
if (isComplex || isModerate) {
|
||||
const planPath = `.workflow/.scratchpad/lite3-${taskSlug}-${dateStr}.md`
|
||||
// Create planning doc with: Task, Status, Complexity, Analysis Summary, Execution Plan, Progress Log
|
||||
}
|
||||
```
|
||||
|
||||
## Phase 2: Select Tools
|
||||
|
||||
### Tool Definitions
|
||||
@@ -167,7 +187,7 @@ TASK: ${tasks.map(t => `• ${t}`).join(' ')}
|
||||
MODE: analysis
|
||||
CONTEXT: @**/*
|
||||
EXPECTED: ${expected}
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md) | ${rules}
|
||||
CONSTRAINTS: ${rules}
|
||||
`
|
||||
}
|
||||
|
||||
@@ -308,6 +328,8 @@ function aggregateResults(mode, results) {
|
||||
critiques: parseCritiques(results.find(r => r.phase === 'challenge')?.result), riskScore: calculateRiskScore(results) }
|
||||
}
|
||||
}
|
||||
|
||||
// If planPath exists: update Analysis Summary & Execution Plan sections
|
||||
```
|
||||
|
||||
## Phase 4: User Decision
|
||||
@@ -348,13 +370,14 @@ AskUserQuestion({
|
||||
multiSelect: false
|
||||
}]
|
||||
})
|
||||
// If planPath exists: record decision to Decisions Made table
|
||||
// Routing: Execute → Phase 5 | Refine → Phase 3 | Change → Phase 2 | Cancel → End
|
||||
```
|
||||
|
||||
## Phase 5: Direct Execution
|
||||
|
||||
```javascript
|
||||
// No IMPL_PLAN.md, no plan.json - direct implementation
|
||||
// Simple tasks: No artifacts | Complex tasks: Update scratchpad doc
|
||||
const executionAgents = agents.filter(a => a.canExecute)
|
||||
const executionTool = selectedAgent.canExecute ? selectedAgent : selectedCLIs[0]
|
||||
|
||||
@@ -373,11 +396,12 @@ TASK: ${extractedTasks.join(' • ')}
|
||||
MODE: write
|
||||
CONTEXT: @${affectedFiles.join(' @')}
|
||||
EXPECTED: Working implementation with all changes applied
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/write-protocol.md)
|
||||
CONSTRAINTS: Follow existing patterns
|
||||
" --tool ${executionTool.name} --mode write`,
|
||||
run_in_background: false
|
||||
})
|
||||
}
|
||||
// If planPath exists: update Status to completed/failed, append to Progress Log
|
||||
```
|
||||
|
||||
## TodoWrite Structure
|
||||
@@ -385,6 +409,7 @@ RULES: $(cat ~/.claude/workflows/cli-templates/protocols/write-protocol.md)
|
||||
```javascript
|
||||
TodoWrite({ todos: [
|
||||
{ content: "Phase 1: Clarify requirements", status: "in_progress", activeForm: "Clarifying requirements" },
|
||||
{ content: "Phase 1.5: Assess complexity", status: "pending", activeForm: "Assessing complexity" },
|
||||
{ content: "Phase 2: Select tools", status: "pending", activeForm: "Selecting tools" },
|
||||
{ content: "Phase 3: Multi-mode analysis", status: "pending", activeForm: "Running analysis" },
|
||||
{ content: "Phase 4: User decision", status: "pending", activeForm: "Awaiting decision" },
|
||||
@@ -409,16 +434,19 @@ TodoWrite({ todos: [
|
||||
| Task unclear | Default to first CLI + code-developer |
|
||||
| Ambiguous task | Force clarification via AskUser |
|
||||
| Execution fails | Present error, ask user for direction |
|
||||
| Plan doc write fails | Continue without doc (degrade to zero-artifact mode) |
|
||||
| Scratchpad dir missing | Auto-create `.workflow/.scratchpad/` |
|
||||
|
||||
## Comparison with multi-cli-plan
|
||||
|
||||
| Aspect | lite-lite-lite | multi-cli-plan |
|
||||
|--------|----------------|----------------|
|
||||
| **Artifacts** | None | IMPL_PLAN.md, plan.json, synthesis.json |
|
||||
| **Artifacts** | Conditional (scratchpad doc for complex tasks) | Always (IMPL_PLAN.md, plan.json, synthesis.json) |
|
||||
| **Session** | Stateless (--resume chaining) | Persistent session folder |
|
||||
| **Tool Selection** | 3-step (CLI → Mode → Agent) | Config-driven fixed tools |
|
||||
| **Analysis Modes** | 5 modes with --resume | Fixed synthesis rounds |
|
||||
| **Best For** | Quick analysis, adversarial validation | Complex multi-step implementations |
|
||||
| **Complexity** | Auto-detected (simple/moderate/complex) | Assumed complex |
|
||||
| **Best For** | Quick analysis, simple-to-moderate tasks | Complex multi-step implementations |
|
||||
|
||||
## Post-Completion Expansion
|
||||
|
||||
|
||||
@@ -497,6 +497,7 @@ ${plan.tasks.map((t, i) => `${i+1}. ${t.title} (${t.file})`).join('\n')}
|
||||
|
||||
**Step 4.2: Collect Confirmation**
|
||||
```javascript
|
||||
// Note: Execution "Other" option allows specifying CLI tools from ~/.claude/cli-tools.json
|
||||
AskUserQuestion({
|
||||
questions: [
|
||||
{
|
||||
@@ -524,8 +525,9 @@ AskUserQuestion({
|
||||
header: "Review",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Gemini Review", description: "Gemini CLI" },
|
||||
{ label: "Agent Review", description: "@code-reviewer" },
|
||||
{ label: "Gemini Review", description: "Gemini CLI review" },
|
||||
{ label: "Codex Review", description: "Git-aware review (prompt OR --uncommitted)" },
|
||||
{ label: "Agent Review", description: "@code-reviewer agent" },
|
||||
{ label: "Skip", description: "No review" }
|
||||
]
|
||||
}
|
||||
|
||||
@@ -17,15 +17,13 @@ allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Bash(*), Writ
|
||||
/workflow:multi-cli-plan "Add dark mode support" --max-rounds=3
|
||||
/workflow:multi-cli-plan "Refactor payment module" --tools=gemini,codex,claude
|
||||
/workflow:multi-cli-plan "Fix memory leak" --mode=serial
|
||||
|
||||
# Resume session
|
||||
/workflow:lite-execute --session=MCP-xxx
|
||||
```
|
||||
|
||||
**Context Source**: ACE semantic search + Multi-CLI analysis
|
||||
**Output Directory**: `.workflow/.multi-cli-plan/{session-id}/`
|
||||
**Default Max Rounds**: 3 (convergence may complete earlier)
|
||||
**CLI Tools**: @cli-discuss-agent (analysis), @cli-lite-planning-agent (plan generation)
|
||||
**Execution**: Auto-hands off to `/workflow:lite-execute --in-memory` after plan approval
|
||||
|
||||
## What & Why
|
||||
|
||||
@@ -71,22 +69,27 @@ Phase 3: Present Options
|
||||
└─ Display solutions with trade-offs from agent output
|
||||
|
||||
Phase 4: User Decision
|
||||
├─ Approve solution → Phase 5
|
||||
├─ Need clarification → Return to Phase 2
|
||||
└─ Change direction → Reset with feedback
|
||||
├─ Select solution approach
|
||||
├─ Select execution method (Agent/Codex/Auto)
|
||||
├─ Select code review tool (Skip/Gemini/Codex/Agent)
|
||||
└─ Route:
|
||||
├─ Approve → Phase 5
|
||||
├─ Need More Analysis → Return to Phase 2
|
||||
└─ Cancel → Save session
|
||||
|
||||
Phase 5: Plan Generation (via @cli-lite-planning-agent)
|
||||
├─ Generate IMPL_PLAN.md + plan.json
|
||||
└─ Hand off to /workflow:lite-execute
|
||||
Phase 5: Plan Generation & Execution Handoff
|
||||
├─ Generate plan.json (via @cli-lite-planning-agent)
|
||||
├─ Build executionContext with user selections
|
||||
└─ Execute to /workflow:lite-execute --in-memory
|
||||
```
|
||||
|
||||
### Agent Roles
|
||||
|
||||
| Agent | Responsibility |
|
||||
|-------|---------------|
|
||||
| **Orchestrator** | Session management, ACE context, user decisions, phase transitions |
|
||||
| **Orchestrator** | Session management, ACE context, user decisions, phase transitions, executionContext assembly |
|
||||
| **@cli-discuss-agent** | Multi-CLI execution (Gemini/Codex/Claude), cross-verification, solution synthesis, synthesis.json output |
|
||||
| **@cli-lite-planning-agent** | Task decomposition, IMPL_PLAN.md + plan.json generation |
|
||||
| **@cli-lite-planning-agent** | Task decomposition, plan.json generation following schema |
|
||||
|
||||
## Core Responsibilities
|
||||
|
||||
@@ -205,25 +208,49 @@ Disagreements: ${synthesis.cross_verification.disagreements.length}
|
||||
**Decision Options**:
|
||||
```javascript
|
||||
AskUserQuestion({
|
||||
questions: [{
|
||||
question: "Which solution approach?",
|
||||
header: "Solution",
|
||||
options: solutions.map((s, i) => ({
|
||||
label: `Option ${i+1}: ${s.name}`,
|
||||
description: `${s.effort} effort, ${s.risk} risk`
|
||||
})).concat([
|
||||
{ label: "Need More Analysis", description: "Return to Phase 2" }
|
||||
])
|
||||
}]
|
||||
questions: [
|
||||
{
|
||||
question: "Which solution approach?",
|
||||
header: "Solution",
|
||||
multiSelect: false,
|
||||
options: solutions.map((s, i) => ({
|
||||
label: `Option ${i+1}: ${s.name}`,
|
||||
description: `${s.effort} effort, ${s.risk} risk`
|
||||
})).concat([
|
||||
{ label: "Need More Analysis", description: "Return to Phase 2" }
|
||||
])
|
||||
},
|
||||
{
|
||||
question: "Execution method:",
|
||||
header: "Execution",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Agent", description: "@code-developer agent" },
|
||||
{ label: "Codex", description: "codex CLI tool" },
|
||||
{ label: "Auto", description: "Auto-select based on complexity" }
|
||||
]
|
||||
},
|
||||
{
|
||||
question: "Code review after execution?",
|
||||
header: "Review",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Skip", description: "No review" },
|
||||
{ label: "Gemini Review", description: "Gemini CLI tool" },
|
||||
{ label: "Codex Review", description: "codex review --uncommitted" },
|
||||
{ label: "Agent Review", description: "Current agent review" }
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
**Routing**:
|
||||
- Approve → Phase 5
|
||||
- Approve + execution method → Phase 5
|
||||
- Need More Analysis → Phase 2 with feedback
|
||||
- Add constraints → Collect details, then Phase 5
|
||||
- Cancel → Save session for resumption
|
||||
|
||||
### Phase 5: Plan Generation
|
||||
### Phase 5: Plan Generation & Execution Handoff
|
||||
|
||||
**Step 1: Build Context-Package** (Orchestrator responsibility):
|
||||
```javascript
|
||||
@@ -340,31 +367,63 @@ ${JSON.stringify(contextPackage, null, 2)}
|
||||
4. Use implementation_plan.tasks[] as task foundation
|
||||
5. Preserve task dependencies (depends_on) and execution_flow
|
||||
6. Expand tasks with detailed acceptance criteria
|
||||
7. Generate IMPL_PLAN.md documenting milestones and key_points
|
||||
8. Generate plan.json following schema exactly
|
||||
7. Generate plan.json following schema exactly
|
||||
|
||||
## Output
|
||||
- ${sessionFolder}/IMPL_PLAN.md
|
||||
- ${sessionFolder}/plan.json
|
||||
|
||||
## Completion Checklist
|
||||
- [ ] IMPL_PLAN.md documents approach, milestones, technical_concerns
|
||||
- [ ] plan.json preserves task dependencies from implementation_plan
|
||||
- [ ] Task execution order follows execution_flow
|
||||
- [ ] Key_points reflected in task descriptions
|
||||
- [ ] User constraints applied to implementation
|
||||
- [ ] Acceptance criteria are testable
|
||||
- [ ] Schema fields match plan-json-schema.json exactly
|
||||
`
|
||||
})
|
||||
```
|
||||
|
||||
**Hand off to Execution**:
|
||||
**Step 3: Build executionContext**:
|
||||
```javascript
|
||||
if (userConfirms) {
|
||||
SlashCommand("/workflow:lite-execute --in-memory")
|
||||
// After plan.json is generated by cli-lite-planning-agent
|
||||
const plan = JSON.parse(Read(`${sessionFolder}/plan.json`))
|
||||
|
||||
// Build executionContext (same structure as lite-plan)
|
||||
executionContext = {
|
||||
planObject: plan,
|
||||
explorationsContext: null, // Multi-CLI doesn't use exploration files
|
||||
explorationAngles: [], // No exploration angles
|
||||
explorationManifest: null, // No manifest
|
||||
clarificationContext: null, // Store user feedback from Phase 2 if exists
|
||||
executionMethod: userSelection.execution_method, // From Phase 4
|
||||
codeReviewTool: userSelection.code_review_tool, // From Phase 4
|
||||
originalUserInput: taskDescription,
|
||||
|
||||
// Optional: Task-level executor assignments
|
||||
executorAssignments: null, // Could be enhanced in future
|
||||
|
||||
session: {
|
||||
id: sessionId,
|
||||
folder: sessionFolder,
|
||||
artifacts: {
|
||||
explorations: [], // No explorations in multi-CLI workflow
|
||||
explorations_manifest: null,
|
||||
plan: `${sessionFolder}/plan.json`,
|
||||
synthesis_rounds: Array.from({length: currentRound}, (_, i) =>
|
||||
`${sessionFolder}/rounds/${i+1}/synthesis.json`
|
||||
),
|
||||
context_package: `${sessionFolder}/context-package.json`
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Step 4: Hand off to Execution**:
|
||||
```javascript
|
||||
// Execute to lite-execute with in-memory context
|
||||
SlashCommand("/workflow:lite-execute --in-memory")
|
||||
```
|
||||
|
||||
## Output File Structure
|
||||
|
||||
```
|
||||
@@ -375,7 +434,6 @@ if (userConfirms) {
|
||||
│ ├── 2/synthesis.json # Round 2 analysis (cli-discuss-agent)
|
||||
│ └── .../
|
||||
├── context-package.json # Extracted context for planning (orchestrator)
|
||||
├── IMPL_PLAN.md # Documentation (cli-lite-planning-agent)
|
||||
└── plan.json # Structured plan (cli-lite-planning-agent)
|
||||
```
|
||||
|
||||
@@ -386,8 +444,7 @@ if (userConfirms) {
|
||||
| `session-state.json` | Orchestrator | Session metadata, rounds, decisions |
|
||||
| `rounds/*/synthesis.json` | cli-discuss-agent | Solutions, convergence, cross-verification |
|
||||
| `context-package.json` | Orchestrator | Extracted solution, dependencies, consensus for planning |
|
||||
| `IMPL_PLAN.md` | cli-lite-planning-agent | Human-readable plan |
|
||||
| `plan.json` | cli-lite-planning-agent | Structured tasks for execution |
|
||||
| `plan.json` | cli-lite-planning-agent | Structured tasks for lite-execute |
|
||||
|
||||
## synthesis.json Schema
|
||||
|
||||
@@ -495,9 +552,6 @@ TodoWrite({ todos: [
|
||||
## Related Commands
|
||||
|
||||
```bash
|
||||
# Resume saved session
|
||||
/workflow:lite-execute --session=MCP-xxx
|
||||
|
||||
# Simpler single-round planning
|
||||
/workflow:lite-plan "task description"
|
||||
|
||||
@@ -505,6 +559,10 @@ TodoWrite({ todos: [
|
||||
/issue:discover-by-prompt "find issues"
|
||||
|
||||
# View session files
|
||||
cat .workflow/.multi-cli-plan/{session-id}/IMPL_PLAN.md
|
||||
cat .workflow/.multi-cli-plan/{session-id}/plan.json
|
||||
cat .workflow/.multi-cli-plan/{session-id}/rounds/1/synthesis.json
|
||||
cat .workflow/.multi-cli-plan/{session-id}/context-package.json
|
||||
|
||||
# Direct execution (if you have plan.json)
|
||||
/workflow:lite-execute plan.json
|
||||
```
|
||||
|
||||
@@ -37,6 +37,44 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
|
||||
7. **Task Attachment Model**: SlashCommand execute **attaches** sub-tasks to current workflow. Orchestrator **executes** these attached tasks itself, then **collapses** them after completion
|
||||
8. **⚠️ CRITICAL: DO NOT STOP**: Continuous multi-phase workflow. After executing all attached tasks, immediately collapse them and execute next phase
|
||||
|
||||
## TDD Compliance Requirements
|
||||
|
||||
### The Iron Law
|
||||
|
||||
```
|
||||
NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
|
||||
```
|
||||
|
||||
**Enforcement Method**:
|
||||
- Phase 5: `implementation_approach` includes test-first steps (Red → Green → Refactor)
|
||||
- Green phase: Includes test-fix-cycle configuration (max 3 iterations)
|
||||
- Auto-revert: Triggered when max iterations reached without passing tests
|
||||
|
||||
**Verification**: Phase 6 validates Red-Green-Refactor structure in all generated tasks
|
||||
|
||||
### TDD Compliance Checkpoint
|
||||
|
||||
| Checkpoint | Validation Phase | Evidence Required |
|
||||
|------------|------------------|-------------------|
|
||||
| Test-first structure | Phase 5 | `implementation_approach` has 3 steps |
|
||||
| Red phase exists | Phase 6 | Step 1: `tdd_phase: "red"` |
|
||||
| Green phase with test-fix | Phase 6 | Step 2: `tdd_phase: "green"` + test-fix-cycle |
|
||||
| Refactor phase exists | Phase 6 | Step 3: `tdd_phase: "refactor"` |
|
||||
|
||||
### Core TDD Principles (from ref skills)
|
||||
|
||||
**Red Flags - STOP and Reassess**:
|
||||
- Code written before test
|
||||
- Test passes immediately (no Red phase witnessed)
|
||||
- Cannot explain why test should fail
|
||||
- "Just this once" rationalization
|
||||
- "Tests after achieve same goals" thinking
|
||||
|
||||
**Why Order Matters**:
|
||||
- Tests written after code pass immediately → proves nothing
|
||||
- Test-first forces edge case discovery before implementation
|
||||
- Tests-after verify what was built, not what's required
|
||||
|
||||
## 6-Phase Execution (with Conflict Resolution)
|
||||
|
||||
### Phase 1: Session Discovery
|
||||
@@ -183,7 +221,7 @@ SlashCommand(command="/workflow:tools:conflict-resolution --session [sessionId]
|
||||
{"content": "Phase 3: Test Coverage Analysis", "status": "completed", "activeForm": "Executing test coverage analysis"},
|
||||
{"content": "Phase 4: Conflict Resolution", "status": "in_progress", "activeForm": "Executing conflict resolution"},
|
||||
{"content": " → Detect conflicts with CLI analysis", "status": "in_progress", "activeForm": "Detecting conflicts"},
|
||||
{"content": " → Present conflicts to user", "status": "pending", "activeForm": "Presenting conflicts"},
|
||||
{"content": " → Log and analyze detected conflicts", "status": "pending", "activeForm": "Analyzing conflicts"},
|
||||
{"content": " → Apply resolution strategies", "status": "pending", "activeForm": "Applying resolution strategies"},
|
||||
{"content": "Phase 5: TDD Task Generation", "status": "pending", "activeForm": "Executing TDD task generation"},
|
||||
{"content": "Phase 6: TDD Structure Validation", "status": "pending", "activeForm": "Validating TDD structure"}
|
||||
@@ -251,6 +289,13 @@ SlashCommand(command="/workflow:tools:task-generate-tdd --session [sessionId]")
|
||||
- IMPL_PLAN.md contains workflow_type: "tdd" in frontmatter
|
||||
- Task count ≤10 (compliance with task limit)
|
||||
|
||||
**Red Flag Detection** (Non-Blocking Warnings):
|
||||
- Task count >10: `⚠️ High task count may indicate insufficient decomposition`
|
||||
- Missing test-fix-cycle: `⚠️ Green phase lacks auto-revert configuration`
|
||||
- Generic task names: `⚠️ Vague task names suggest unclear TDD cycles`
|
||||
|
||||
**Action**: Log warnings to `.workflow/active/[sessionId]/.process/tdd-warnings.log` (non-blocking)
|
||||
|
||||
<!-- TodoWrite: When task-generate-tdd executed, INSERT 3 task-generate-tdd tasks -->
|
||||
|
||||
**TodoWrite Update (Phase 5 SlashCommand executed - tasks attached)**:
|
||||
@@ -302,6 +347,42 @@ SlashCommand(command="/workflow:tools:task-generate-tdd --session [sessionId]")
|
||||
5. Test-fix cycle: Green phase step includes test-fix-cycle logic with max_iterations
|
||||
6. Task count: Total tasks ≤10 (simple + subtasks)
|
||||
|
||||
**Red Flag Checklist** (from TDD best practices):
|
||||
- [ ] No tasks skip Red phase (`tdd_phase: "red"` exists in step 1)
|
||||
- [ ] Test files referenced in Red phase (explicit paths, not placeholders)
|
||||
- [ ] Green phase has test-fix-cycle with `max_iterations` configured
|
||||
- [ ] Refactor phase has clear completion criteria
|
||||
|
||||
**Non-Compliance Warning Format**:
|
||||
```
|
||||
⚠️ TDD Red Flag: [issue description]
|
||||
Task: [IMPL-N]
|
||||
Recommendation: [action to fix]
|
||||
```
|
||||
|
||||
**Evidence Gathering** (Before Completion Claims):
|
||||
|
||||
```bash
|
||||
# Verify session artifacts exist
|
||||
ls -la .workflow/active/[sessionId]/{IMPL_PLAN.md,TODO_LIST.md}
|
||||
ls -la .workflow/active/[sessionId]/.task/IMPL-*.json
|
||||
|
||||
# Count generated artifacts
|
||||
echo "IMPL tasks: $(ls .workflow/active/[sessionId]/.task/IMPL-*.json 2>/dev/null | wc -l)"
|
||||
|
||||
# Sample task structure verification (first task)
|
||||
jq '{id, tdd: .meta.tdd_workflow, phases: [.flow_control.implementation_approach[].tdd_phase]}' \
|
||||
"$(ls .workflow/active/[sessionId]/.task/IMPL-*.json | head -1)"
|
||||
```
|
||||
|
||||
**Evidence Required Before Summary**:
|
||||
| Evidence Type | Verification Method | Pass Criteria |
|
||||
|---------------|---------------------|---------------|
|
||||
| File existence | `ls -la` artifacts | All files present |
|
||||
| Task count | Count IMPL-*.json | Count matches claims |
|
||||
| TDD structure | jq sample extraction | Shows red/green/refactor |
|
||||
| Warning log | Check tdd-warnings.log | Logged (may be empty) |
|
||||
|
||||
**Return Summary**:
|
||||
```
|
||||
TDD Planning complete for session: [sessionId]
|
||||
@@ -333,6 +414,9 @@ TDD Configuration:
|
||||
- Green phase includes test-fix cycle (max 3 iterations)
|
||||
- Auto-revert on max iterations reached
|
||||
|
||||
⚠️ ACTION REQUIRED: Before execution, ensure you understand WHY each Red phase test is expected to fail.
|
||||
This is crucial for valid TDD - if you don't know why the test fails, you can't verify it tests the right thing.
|
||||
|
||||
Recommended Next Steps:
|
||||
1. /workflow:action-plan-verify --session [sessionId] # Verify TDD plan quality and dependencies
|
||||
2. /workflow:execute --session [sessionId] # Start TDD execution
|
||||
@@ -400,7 +484,7 @@ TDD Workflow Orchestrator
|
||||
│ IF conflict_risk ≥ medium:
|
||||
│ └─ /workflow:tools:conflict-resolution ← ATTACHED (3 tasks)
|
||||
│ ├─ Phase 4.1: Detect conflicts with CLI
|
||||
│ ├─ Phase 4.2: Present conflicts to user
|
||||
│ ├─ Phase 4.2: Log and analyze detected conflicts
|
||||
│ └─ Phase 4.3: Apply resolution strategies
|
||||
│ └─ Returns: conflict-resolution.json ← COLLAPSED
|
||||
│ ELSE:
|
||||
@@ -439,6 +523,34 @@ Convert user input to TDD-structured format:
|
||||
- **Command failure**: Keep phase in_progress, report error
|
||||
- **TDD validation failure**: Report incomplete chains or wrong dependencies
|
||||
|
||||
### TDD Warning Patterns
|
||||
|
||||
| Pattern | Warning Message | Recommended Action |
|
||||
|---------|----------------|-------------------|
|
||||
| Task count >10 | High task count detected | Consider splitting into multiple sessions |
|
||||
| Missing test-fix-cycle | Green phase lacks auto-revert | Add `max_iterations: 3` to task config |
|
||||
| Red phase missing test path | Test file path not specified | Add explicit test file paths |
|
||||
| Generic task names | Vague names like "Add feature" | Use specific behavior descriptions |
|
||||
| No refactor criteria | Refactor phase lacks completion criteria | Define clear refactor scope |
|
||||
|
||||
### Non-Blocking Warning Policy
|
||||
|
||||
**All warnings are advisory** - they do not halt execution:
|
||||
1. Warnings logged to `.process/tdd-warnings.log`
|
||||
2. Summary displayed in Phase 6 output
|
||||
3. User decides whether to address before `/workflow:execute`
|
||||
|
||||
### Error Handling Quick Reference
|
||||
|
||||
| Error Type | Detection | Recovery Action |
|
||||
|------------|-----------|-----------------|
|
||||
| Parsing failure | Empty/malformed output | Retry once, then report |
|
||||
| Missing context-package | File read error | Re-run `/workflow:tools:context-gather` |
|
||||
| Invalid task JSON | jq parse error | Report malformed file path |
|
||||
| High task count (>10) | Count validation | Log warning, continue (non-blocking) |
|
||||
| Test-context missing | File not found | Re-run `/workflow:tools:test-context-gather` |
|
||||
| Phase timeout | No response | Retry phase, check CLI connectivity |
|
||||
|
||||
## Related Commands
|
||||
|
||||
**Prerequisite Commands**:
|
||||
@@ -458,3 +570,28 @@ Convert user input to TDD-structured format:
|
||||
- `/workflow:execute` - Begin TDD implementation
|
||||
- `/workflow:tdd-verify` - Post-execution: Verify TDD compliance and generate quality report
|
||||
|
||||
## Next Steps Decision Table
|
||||
|
||||
| Situation | Recommended Command | Purpose |
|
||||
|-----------|---------------------|---------|
|
||||
| First time planning | `/workflow:action-plan-verify` | Validate task structure before execution |
|
||||
| Warnings in tdd-warnings.log | Review log, refine tasks | Address Red Flags before proceeding |
|
||||
| High task count warning | Consider `/workflow:session:start` | Split into focused sub-sessions |
|
||||
| Ready to implement | `/workflow:execute` | Begin TDD Red-Green-Refactor cycles |
|
||||
| After implementation | `/workflow:tdd-verify` | Generate TDD compliance report |
|
||||
| Need to review tasks | `/workflow:status --session [id]` | Inspect current task breakdown |
|
||||
| Plan needs changes | `/task:replan` | Update task JSON with new requirements |
|
||||
|
||||
### TDD Workflow State Transitions
|
||||
|
||||
```
|
||||
/workflow:tdd-plan
|
||||
↓
|
||||
[Planning Complete] ──→ /workflow:action-plan-verify (recommended)
|
||||
↓
|
||||
[Verified/Ready] ─────→ /workflow:execute
|
||||
↓
|
||||
[Implementation] ─────→ /workflow:tdd-verify (post-execution)
|
||||
↓
|
||||
[Quality Report] ─────→ Done or iterate
|
||||
```
|
||||
|
||||
@@ -154,8 +154,8 @@ Task(subagent_type="cli-execution-agent", run_in_background=false, prompt=`
|
||||
- Validation of exploration conflict_indicators
|
||||
- ModuleOverlap conflicts with overlap_analysis
|
||||
- Targeted clarification questions
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/02-analyze-code-patterns.txt) | Focus on breaking changes, migration needs, and functional overlaps | Prioritize exploration-identified conflicts | analysis=READ-ONLY
|
||||
" --tool gemini --mode analysis --cd {project_root}
|
||||
CONSTRAINTS: Focus on breaking changes, migration needs, and functional overlaps | Prioritize exploration-identified conflicts | analysis=READ-ONLY
|
||||
" --tool gemini --mode analysis --rule analysis-code-patterns --cd {project_root}
|
||||
|
||||
Fallback: Qwen (same prompt) → Claude (manual analysis)
|
||||
|
||||
|
||||
@@ -90,7 +90,7 @@ Template: ~/.claude/workflows/cli-templates/prompts/test/test-concept-analysis.t
|
||||
|
||||
## EXECUTION STEPS
|
||||
1. Execute Gemini analysis:
|
||||
ccw cli -p "$(cat ~/.claude/workflows/cli-templates/prompts/test/test-concept-analysis.txt)" --tool gemini --mode write --cd .workflow/active/{test_session_id}/.process
|
||||
ccw cli -p "..." --tool gemini --mode write --rule test-test-concept-analysis --cd .workflow/active/{test_session_id}/.process
|
||||
|
||||
2. Generate TEST_ANALYSIS_RESULTS.md:
|
||||
Synthesize gemini-test-analysis.md into standardized format for task generation
|
||||
|
||||
303
.claude/skills/ccw-loop/README.md
Normal file
303
.claude/skills/ccw-loop/README.md
Normal file
@@ -0,0 +1,303 @@
|
||||
# CCW Loop Skill
|
||||
|
||||
无状态迭代开发循环工作流,支持开发 (Develop)、调试 (Debug)、验证 (Validate) 三个阶段,每个阶段都有独立的文件记录进展。
|
||||
|
||||
## Overview
|
||||
|
||||
CCW Loop 是一个自主模式 (Autonomous) 的 Skill,通过文件驱动的无状态循环,帮助开发者系统化地完成开发任务。
|
||||
|
||||
### 核心特性
|
||||
|
||||
1. **无状态循环**: 每次执行从文件读取状态,不依赖内存
|
||||
2. **文件驱动**: 所有进度记录在 Markdown 文件中,可审计、可回顾
|
||||
3. **Gemini 辅助**: 关键决策点使用 CLI 工具进行深度分析
|
||||
4. **可恢复**: 任何时候中断后可继续
|
||||
5. **双模式**: 支持交互式和自动循环
|
||||
|
||||
### 三大阶段
|
||||
|
||||
- **Develop**: 任务分解 → 代码实现 → 进度记录
|
||||
- **Debug**: 假设生成 → 证据收集 → 根因分析 → 修复验证
|
||||
- **Validate**: 测试执行 → 覆盖率检查 → 质量评估
|
||||
|
||||
## Installation
|
||||
|
||||
已包含在 `.claude/skills/ccw-loop/`,无需额外安装。
|
||||
|
||||
## Usage
|
||||
|
||||
### 基本用法
|
||||
|
||||
```bash
|
||||
# 启动新循环
|
||||
/ccw-loop "实现用户认证功能"
|
||||
|
||||
# 继续现有循环
|
||||
/ccw-loop --resume LOOP-auth-2026-01-22
|
||||
|
||||
# 自动循环模式
|
||||
/ccw-loop --auto "修复登录bug并添加测试"
|
||||
```
|
||||
|
||||
### 交互式流程
|
||||
|
||||
```
|
||||
1. 启动: /ccw-loop "任务描述"
|
||||
2. 初始化: 自动分析任务并生成子任务列表
|
||||
3. 显示菜单:
|
||||
- 📝 继续开发 (Develop)
|
||||
- 🔍 开始调试 (Debug)
|
||||
- ✅ 运行验证 (Validate)
|
||||
- 📊 查看详情 (Status)
|
||||
- 🏁 完成循环 (Complete)
|
||||
- 🚪 退出 (Exit)
|
||||
4. 执行选择的动作
|
||||
5. 重复步骤 3-4 直到完成
|
||||
```
|
||||
|
||||
### 自动循环流程
|
||||
|
||||
```
|
||||
Develop (所有任务) → Debug (如有需要) → Validate → 完成
|
||||
```
|
||||
|
||||
## Directory Structure
|
||||
|
||||
```
|
||||
.workflow/.loop/{session-id}/
|
||||
├── meta.json # 会话元数据 (不可修改)
|
||||
├── state.json # 当前状态 (每次更新)
|
||||
├── summary.md # 完成报告 (结束时生成)
|
||||
├── develop/
|
||||
│ ├── progress.md # 开发进度时间线
|
||||
│ ├── tasks.json # 任务列表
|
||||
│ └── changes.log # 代码变更日志 (NDJSON)
|
||||
├── debug/
|
||||
│ ├── understanding.md # 理解演变文档
|
||||
│ ├── hypotheses.json # 假设历史
|
||||
│ └── debug.log # 调试日志 (NDJSON)
|
||||
└── validate/
|
||||
├── validation.md # 验证报告
|
||||
├── test-results.json # 测试结果
|
||||
└── coverage.json # 覆盖率数据
|
||||
```
|
||||
|
||||
## Action Reference
|
||||
|
||||
| Action | 描述 | 触发条件 |
|
||||
|--------|------|----------|
|
||||
| action-init | 初始化会话 | 首次启动 |
|
||||
| action-menu | 显示操作菜单 | 交互模式下每次循环 |
|
||||
| action-develop-with-file | 执行开发任务 | 有待处理任务 |
|
||||
| action-debug-with-file | 假设驱动调试 | 需要调试 |
|
||||
| action-validate-with-file | 运行测试验证 | 需要验证 |
|
||||
| action-complete | 完成并生成报告 | 所有任务完成 |
|
||||
|
||||
详细说明见 [specs/action-catalog.md](specs/action-catalog.md)
|
||||
|
||||
## CLI Integration
|
||||
|
||||
CCW Loop 在关键决策点集成 CLI 工具:
|
||||
|
||||
### 任务分解 (action-init)
|
||||
```bash
|
||||
ccw cli -p "PURPOSE: 分解开发任务..."
|
||||
--tool gemini
|
||||
--mode analysis
|
||||
--rule planning-breakdown-task-steps
|
||||
```
|
||||
|
||||
### 代码实现 (action-develop)
|
||||
```bash
|
||||
ccw cli -p "PURPOSE: 实现功能代码..."
|
||||
--tool gemini
|
||||
--mode write
|
||||
--rule development-implement-feature
|
||||
```
|
||||
|
||||
### 假设生成 (action-debug - 探索)
|
||||
```bash
|
||||
ccw cli -p "PURPOSE: Generate debugging hypotheses..."
|
||||
--tool gemini
|
||||
--mode analysis
|
||||
--rule analysis-diagnose-bug-root-cause
|
||||
```
|
||||
|
||||
### 证据分析 (action-debug - 分析)
|
||||
```bash
|
||||
ccw cli -p "PURPOSE: Analyze debug log evidence..."
|
||||
--tool gemini
|
||||
--mode analysis
|
||||
--rule analysis-diagnose-bug-root-cause
|
||||
```
|
||||
|
||||
### 质量评估 (action-validate)
|
||||
```bash
|
||||
ccw cli -p "PURPOSE: Analyze test results and coverage..."
|
||||
--tool gemini
|
||||
--mode analysis
|
||||
--rule analysis-review-code-quality
|
||||
```
|
||||
|
||||
## State Management
|
||||
|
||||
### State Schema
|
||||
|
||||
参见 [phases/state-schema.md](phases/state-schema.md)
|
||||
|
||||
### State Transitions
|
||||
|
||||
```
|
||||
pending → running → completed
|
||||
↓
|
||||
user_exit
|
||||
↓
|
||||
failed
|
||||
```
|
||||
|
||||
### State Recovery
|
||||
|
||||
如果 `state.json` 损坏,可从其他文件重建:
|
||||
- develop/tasks.json → develop.*
|
||||
- debug/hypotheses.json → debug.*
|
||||
- validate/test-results.json → validate.*
|
||||
|
||||
## Examples
|
||||
|
||||
### Example 1: 功能开发
|
||||
|
||||
```bash
|
||||
# 1. 启动循环
|
||||
/ccw-loop "Add user profile page"
|
||||
|
||||
# 2. 系统初始化,生成任务:
|
||||
# - task-001: Create profile component
|
||||
# - task-002: Add API endpoints
|
||||
# - task-003: Implement tests
|
||||
|
||||
# 3. 选择 "继续开发"
|
||||
# → 执行 task-001 (Gemini 辅助实现)
|
||||
# → 更新 progress.md
|
||||
|
||||
# 4. 重复开发直到所有任务完成
|
||||
|
||||
# 5. 选择 "运行验证"
|
||||
# → 运行测试
|
||||
# → 检查覆盖率
|
||||
# → 生成 validation.md
|
||||
|
||||
# 6. 选择 "完成循环"
|
||||
# → 生成 summary.md
|
||||
# → 询问是否扩展为 Issue
|
||||
```
|
||||
|
||||
### Example 2: Bug 修复
|
||||
|
||||
```bash
|
||||
# 1. 启动循环
|
||||
/ccw-loop "Fix login timeout issue"
|
||||
|
||||
# 2. 选择 "开始调试"
|
||||
# → 输入 bug 描述: "Login times out after 30s"
|
||||
# → Gemini 生成假设 (H1, H2, H3)
|
||||
# → 添加 NDJSON 日志
|
||||
# → 提示复现 bug
|
||||
|
||||
# 3. 复现 bug (在应用中操作)
|
||||
|
||||
# 4. 再次选择 "开始调试"
|
||||
# → 解析 debug.log
|
||||
# → Gemini 分析证据
|
||||
# → H2 确认为根因
|
||||
# → 生成修复代码
|
||||
# → 更新 understanding.md
|
||||
|
||||
# 5. 选择 "运行验证"
|
||||
# → 测试通过
|
||||
|
||||
# 6. 完成
|
||||
```
|
||||
|
||||
## Templates
|
||||
|
||||
- [progress-template.md](templates/progress-template.md): 开发进度文档模板
|
||||
- [understanding-template.md](templates/understanding-template.md): 调试理解文档模板
|
||||
- [validation-template.md](templates/validation-template.md): 验证报告模板
|
||||
|
||||
## Specifications
|
||||
|
||||
- [loop-requirements.md](specs/loop-requirements.md): 循环需求规范
|
||||
- [action-catalog.md](specs/action-catalog.md): 动作目录
|
||||
|
||||
## Integration
|
||||
|
||||
### Dashboard Integration
|
||||
|
||||
CCW Loop 与 Dashboard Loop Monitor 集成:
|
||||
- Dashboard 创建 Loop → 触发此 Skill
|
||||
- state.json → Dashboard 实时显示
|
||||
- 任务列表双向同步
|
||||
- 控制按钮映射到 actions
|
||||
|
||||
### Issue System Integration
|
||||
|
||||
完成后可扩展为 Issue:
|
||||
- 维度: test, enhance, refactor, doc
|
||||
- 自动调用 `/issue:new`
|
||||
- 上下文自动填充
|
||||
|
||||
## Error Handling
|
||||
|
||||
| 情况 | 处理 |
|
||||
|------|------|
|
||||
| Session 不存在 | 创建新会话 |
|
||||
| state.json 损坏 | 从文件重建 |
|
||||
| CLI 工具失败 | 回退到手动模式 |
|
||||
| 测试失败 | 循环回到 develop/debug |
|
||||
| >10 迭代 | 警告用户,建议拆分 |
|
||||
|
||||
## Limitations
|
||||
|
||||
1. **单会话限制**: 同一时间只能有一个活跃会话
|
||||
2. **迭代限制**: 建议不超过 10 次迭代
|
||||
3. **CLI 依赖**: 部分功能依赖 Gemini CLI 可用性
|
||||
4. **测试框架**: 需要 package.json 中定义测试脚本
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Q: 如何查看当前会话状态?
|
||||
|
||||
A: 在菜单中选择 "查看详情 (Status)"
|
||||
|
||||
### Q: 如何恢复中断的会话?
|
||||
|
||||
A: 使用 `--resume` 参数:
|
||||
```bash
|
||||
/ccw-loop --resume LOOP-xxx-2026-01-22
|
||||
```
|
||||
|
||||
### Q: 如果 CLI 工具失败怎么办?
|
||||
|
||||
A: Skill 会自动降级到手动模式,提示用户手动输入
|
||||
|
||||
### Q: 如何添加自定义 action?
|
||||
|
||||
A: 参见 [specs/action-catalog.md](specs/action-catalog.md) 的 "Action Extensions" 部分
|
||||
|
||||
## Contributing
|
||||
|
||||
添加新功能:
|
||||
1. 创建 action 文件在 `phases/actions/`
|
||||
2. 更新 orchestrator 决策逻辑
|
||||
3. 添加到 action-catalog.md
|
||||
4. 更新 action-menu.md
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
|
||||
---
|
||||
|
||||
**Version**: 1.0.0
|
||||
**Last Updated**: 2026-01-22
|
||||
**Author**: CCW Team
|
||||
259
.claude/skills/ccw-loop/SKILL.md
Normal file
259
.claude/skills/ccw-loop/SKILL.md
Normal file
@@ -0,0 +1,259 @@
|
||||
---
|
||||
name: ccw-loop
|
||||
description: Stateless iterative development loop workflow with documented progress. Supports develop, debug, and validate phases with file-based state tracking. Triggers on "ccw-loop", "dev loop", "development loop", "开发循环", "迭代开发".
|
||||
allowed-tools: Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*), TodoWrite(*)
|
||||
---
|
||||
|
||||
# CCW Loop - Stateless Iterative Development Workflow
|
||||
|
||||
无状态迭代开发循环工作流,支持开发 (develop)、调试 (debug)、验证 (validate) 三个阶段,每个阶段都有独立的文件记录进展。
|
||||
|
||||
## Arguments
|
||||
|
||||
| Arg | Required | Description |
|
||||
|-----|----------|-------------|
|
||||
| task | No | Task description (for new loop, mutually exclusive with --loop-id) |
|
||||
| --loop-id | No | Existing loop ID to continue (from API or previous session) |
|
||||
| --auto | No | Auto-cycle mode (develop → debug → validate → complete) |
|
||||
|
||||
## Unified Architecture (API + Skill Integration)
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Dashboard (UI) │
|
||||
│ [Create] [Start] [Pause] [Resume] [Stop] [View Progress] │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ loop-v2-routes.ts (Control Plane) │
|
||||
│ │
|
||||
│ State: .loop/{loopId}.json (MASTER) │
|
||||
│ Tasks: .loop/{loopId}.tasks.jsonl │
|
||||
│ │
|
||||
│ /start → Trigger ccw-loop skill with --loop-id │
|
||||
│ /pause → Set status='paused' (skill checks before action) │
|
||||
│ /stop → Set status='failed' (skill terminates) │
|
||||
│ /resume → Set status='running' (skill continues) │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ ccw-loop Skill (Execution Plane) │
|
||||
│ │
|
||||
│ Reads/Writes: .loop/{loopId}.json (unified state) │
|
||||
│ Writes: .loop/{loopId}.progress/* (progress files) │
|
||||
│ │
|
||||
│ BEFORE each action: │
|
||||
│ → Check status: paused/stopped → exit gracefully │
|
||||
│ → running → continue with action │
|
||||
│ │
|
||||
│ Actions: init → develop → debug → validate → complete │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Key Design Principles
|
||||
|
||||
1. **统一状态**: API 和 Skill 共享 `.loop/{loopId}.json` 状态文件
|
||||
2. **控制信号**: Skill 每个 Action 前检查 status 字段 (paused/stopped)
|
||||
3. **文件驱动**: 所有进度、理解、结果都记录在 `.loop/{loopId}.progress/`
|
||||
4. **可恢复**: 任何时候可以继续之前的循环 (`--loop-id`)
|
||||
5. **双触发**: 支持 API 触发 (`--loop-id`) 和直接调用 (task description)
|
||||
6. **Gemini 辅助**: 使用 CLI 工具进行深度分析和假设验证
|
||||
|
||||
## Execution Modes
|
||||
|
||||
### Mode 1: Interactive (交互式)
|
||||
|
||||
用户手动选择每个动作,适合复杂任务。
|
||||
|
||||
```
|
||||
用户 → 选择动作 → 执行 → 查看结果 → 选择下一动作
|
||||
```
|
||||
|
||||
### Mode 2: Auto-Loop (自动循环)
|
||||
|
||||
按预设顺序自动执行,适合标准开发流程。
|
||||
|
||||
```
|
||||
Develop → Debug → Validate → (如有问题) → Develop → ...
|
||||
```
|
||||
|
||||
## Session Structure (Unified Location)
|
||||
|
||||
```
|
||||
.loop/
|
||||
├── {loopId}.json # 主状态文件 (API + Skill 共享)
|
||||
├── {loopId}.tasks.jsonl # 任务列表 (API 管理)
|
||||
└── {loopId}.progress/ # Skill 进度文件
|
||||
├── develop.md # 开发进度记录
|
||||
├── debug.md # 理解演变文档
|
||||
├── validate.md # 验证报告
|
||||
├── changes.log # 代码变更日志 (NDJSON)
|
||||
└── debug.log # 调试日志 (NDJSON)
|
||||
```
|
||||
|
||||
## Directory Setup
|
||||
|
||||
```javascript
|
||||
// loopId 来源:
|
||||
// 1. API 触发时: 从 --loop-id 参数获取
|
||||
// 2. 直接调用时: 生成新的 loop-v2-{timestamp}-{random}
|
||||
|
||||
const loopId = args['--loop-id'] || generateLoopId()
|
||||
const loopFile = `.loop/${loopId}.json`
|
||||
const progressDir = `.loop/${loopId}.progress`
|
||||
|
||||
// 创建进度目录
|
||||
Bash(`mkdir -p "${progressDir}"`)
|
||||
```
|
||||
|
||||
## Action Catalog
|
||||
|
||||
| Action | Purpose | Output Files | CLI Integration |
|
||||
|--------|---------|--------------|-----------------|
|
||||
| [action-init](phases/actions/action-init.md) | 初始化循环会话 | meta.json, state.json | - |
|
||||
| [action-develop-with-file](phases/actions/action-develop-with-file.md) | 开发任务执行 | progress.md, tasks.json | gemini --mode write |
|
||||
| [action-debug-with-file](phases/actions/action-debug-with-file.md) | 假设驱动调试 | understanding.md, hypotheses.json | gemini --mode analysis |
|
||||
| [action-validate-with-file](phases/actions/action-validate-with-file.md) | 测试与验证 | validation.md, test-results.json | gemini --mode analysis |
|
||||
| [action-complete](phases/actions/action-complete.md) | 完成循环 | summary.md | - |
|
||||
| [action-menu](phases/actions/action-menu.md) | 显示操作菜单 | - | - |
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
# 启动新循环 (直接调用)
|
||||
/ccw-loop "实现用户认证功能"
|
||||
|
||||
# 继续现有循环 (API 触发或手动恢复)
|
||||
/ccw-loop --loop-id loop-v2-20260122-abc123
|
||||
|
||||
# 自动循环模式
|
||||
/ccw-loop --auto "修复登录bug并添加测试"
|
||||
|
||||
# API 触发自动循环
|
||||
/ccw-loop --loop-id loop-v2-20260122-abc123 --auto
|
||||
```
|
||||
|
||||
## Execution Flow
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ /ccw-loop [<task> | --loop-id <id>] [--auto] │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ 1. Parameter Detection: │
|
||||
│ ├─ IF --loop-id provided: │
|
||||
│ │ ├─ Read .loop/{loopId}.json │
|
||||
│ │ ├─ Validate status === 'running' │
|
||||
│ │ └─ Continue from skill_state.current_action │
|
||||
│ └─ ELSE (task description): │
|
||||
│ ├─ Generate new loopId │
|
||||
│ ├─ Create .loop/{loopId}.json │
|
||||
│ └─ Initialize with action-init │
|
||||
│ │
|
||||
│ 2. Orchestrator Loop: │
|
||||
│ ├─ Read state from .loop/{loopId}.json │
|
||||
│ ├─ Check control signals: │
|
||||
│ │ ├─ status === 'paused' → Exit (wait for resume) │
|
||||
│ │ ├─ status === 'failed' → Exit with error │
|
||||
│ │ └─ status === 'running' → Continue │
|
||||
│ ├─ Show menu / auto-select next action │
|
||||
│ ├─ Execute action │
|
||||
│ ├─ Update .loop/{loopId}.progress/{action}.md │
|
||||
│ ├─ Update .loop/{loopId}.json (skill_state) │
|
||||
│ └─ Loop or exit based on user choice / completion │
|
||||
│ │
|
||||
│ 3. Action Execution: │
|
||||
│ ├─ BEFORE: checkControlSignals() → exit if paused/stopped │
|
||||
│ ├─ Develop: Plan → Implement → Document progress │
|
||||
│ ├─ Debug: Hypothesize → Instrument → Analyze → Fix │
|
||||
│ ├─ Validate: Test → Check → Report │
|
||||
│ └─ AFTER: Update skill_state in .loop/{loopId}.json │
|
||||
│ │
|
||||
│ 4. Termination: │
|
||||
│ ├─ Control signal: paused (graceful exit, wait resume) │
|
||||
│ ├─ Control signal: stopped (failed state) │
|
||||
│ ├─ User exits (interactive mode) │
|
||||
│ ├─ All tasks completed (status → completed) │
|
||||
│ └─ Max iterations reached │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Reference Documents
|
||||
|
||||
| Document | Purpose |
|
||||
|----------|---------|
|
||||
| [phases/orchestrator.md](phases/orchestrator.md) | 编排器:状态读取 + 动作选择 |
|
||||
| [phases/state-schema.md](phases/state-schema.md) | 状态结构定义 |
|
||||
| [specs/loop-requirements.md](specs/loop-requirements.md) | 循环需求规范 |
|
||||
| [specs/action-catalog.md](specs/action-catalog.md) | 动作目录 |
|
||||
| [templates/progress-template.md](templates/progress-template.md) | 进度文档模板 |
|
||||
| [templates/understanding-template.md](templates/understanding-template.md) | 理解文档模板 |
|
||||
|
||||
## Integration with Loop Monitor (Dashboard)
|
||||
|
||||
此 Skill 与 CCW Dashboard 的 Loop Monitor 实现 **控制平面 + 执行平面** 分离架构:
|
||||
|
||||
### Control Plane (Dashboard/API → loop-v2-routes.ts)
|
||||
|
||||
1. **创建循环**: `POST /api/loops/v2` → 创建 `.loop/{loopId}.json`
|
||||
2. **启动执行**: `POST /api/loops/v2/:loopId/start` → 触发 `/ccw-loop --loop-id {loopId} --auto`
|
||||
3. **暂停执行**: `POST /api/loops/v2/:loopId/pause` → 设置 `status='paused'` (Skill 下次检查时退出)
|
||||
4. **恢复执行**: `POST /api/loops/v2/:loopId/resume` → 设置 `status='running'` → 重新触发 Skill
|
||||
5. **停止执行**: `POST /api/loops/v2/:loopId/stop` → 设置 `status='failed'`
|
||||
|
||||
### Execution Plane (ccw-loop Skill)
|
||||
|
||||
1. **读取状态**: 从 `.loop/{loopId}.json` 读取 API 设置的状态
|
||||
2. **检查控制**: 每个 Action 前检查 `status` 字段
|
||||
3. **执行动作**: develop → debug → validate → complete
|
||||
4. **更新进度**: 写入 `.loop/{loopId}.progress/*.md` 和更新 `skill_state`
|
||||
5. **状态同步**: Dashboard 通过读取 `.loop/{loopId}.json` 获取进度
|
||||
|
||||
## CLI Integration Points
|
||||
|
||||
### Develop Phase
|
||||
```bash
|
||||
ccw cli -p "PURPOSE: Implement {task}...
|
||||
TASK: • Analyze requirements • Write code • Update progress
|
||||
MODE: write
|
||||
CONTEXT: @progress.md @tasks.json
|
||||
EXPECTED: Implementation + updated progress.md
|
||||
" --tool gemini --mode write --rule development-implement-feature
|
||||
```
|
||||
|
||||
### Debug Phase
|
||||
```bash
|
||||
ccw cli -p "PURPOSE: Generate debugging hypotheses...
|
||||
TASK: • Analyze error • Generate hypotheses • Add instrumentation
|
||||
MODE: analysis
|
||||
CONTEXT: @understanding.md @debug.log
|
||||
EXPECTED: Hypotheses + instrumentation plan
|
||||
" --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause
|
||||
```
|
||||
|
||||
### Validate Phase
|
||||
```bash
|
||||
ccw cli -p "PURPOSE: Validate implementation...
|
||||
TASK: • Run tests • Check coverage • Verify requirements
|
||||
MODE: analysis
|
||||
CONTEXT: @validation.md @test-results.json
|
||||
EXPECTED: Validation report
|
||||
" --tool gemini --mode analysis --rule analysis-review-code-quality
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Situation | Action |
|
||||
|-----------|--------|
|
||||
| Session not found | Create new session |
|
||||
| State file corrupted | Rebuild from file contents |
|
||||
| CLI tool fails | Fallback to manual analysis |
|
||||
| Tests fail | Loop back to develop/debug |
|
||||
| >10 iterations | Warn user, suggest break |
|
||||
|
||||
## Post-Completion Expansion
|
||||
|
||||
完成后询问用户是否扩展为 issue (test/enhance/refactor/doc),选中项调用 `/issue:new "{summary} - {dimension}"`
|
||||
320
.claude/skills/ccw-loop/phases/actions/action-complete.md
Normal file
320
.claude/skills/ccw-loop/phases/actions/action-complete.md
Normal file
@@ -0,0 +1,320 @@
|
||||
# Action: Complete
|
||||
|
||||
完成 CCW Loop 会话,生成总结报告。
|
||||
|
||||
## Purpose
|
||||
|
||||
- 生成完成报告
|
||||
- 汇总所有阶段成果
|
||||
- 提供后续建议
|
||||
- 询问是否扩展为 Issue
|
||||
|
||||
## Preconditions
|
||||
|
||||
- [ ] state.initialized === true
|
||||
- [ ] state.status === 'running'
|
||||
|
||||
## Execution
|
||||
|
||||
### Step 1: 汇总统计
|
||||
|
||||
```javascript
|
||||
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
|
||||
|
||||
const sessionFolder = `.workflow/.loop/${state.session_id}`
|
||||
|
||||
const stats = {
|
||||
// 时间统计
|
||||
duration: Date.now() - new Date(state.created_at).getTime(),
|
||||
iterations: state.iteration_count,
|
||||
|
||||
// 开发统计
|
||||
develop: {
|
||||
total_tasks: state.develop.total_count,
|
||||
completed_tasks: state.develop.completed_count,
|
||||
completion_rate: state.develop.total_count > 0
|
||||
? (state.develop.completed_count / state.develop.total_count * 100).toFixed(1)
|
||||
: 0
|
||||
},
|
||||
|
||||
// 调试统计
|
||||
debug: {
|
||||
iterations: state.debug.iteration,
|
||||
hypotheses_tested: state.debug.hypotheses.length,
|
||||
root_cause_found: state.debug.confirmed_hypothesis !== null
|
||||
},
|
||||
|
||||
// 验证统计
|
||||
validate: {
|
||||
runs: state.validate.test_results.length,
|
||||
passed: state.validate.passed,
|
||||
coverage: state.validate.coverage,
|
||||
failed_tests: state.validate.failed_tests.length
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\n生成完成报告...')
|
||||
```
|
||||
|
||||
### Step 2: 生成总结报告
|
||||
|
||||
```javascript
|
||||
const summaryReport = `# CCW Loop Session Summary
|
||||
|
||||
**Session ID**: ${state.session_id}
|
||||
**Task**: ${state.task_description}
|
||||
**Started**: ${state.created_at}
|
||||
**Completed**: ${getUtc8ISOString()}
|
||||
**Duration**: ${formatDuration(stats.duration)}
|
||||
|
||||
---
|
||||
|
||||
## Executive Summary
|
||||
|
||||
${state.validate.passed
|
||||
? '✅ **任务成功完成** - 所有测试通过,验证成功'
|
||||
: state.develop.completed_count === state.develop.total_count
|
||||
? '⚠️ **开发完成,验证未通过** - 需要进一步调试'
|
||||
: '⏸️ **任务部分完成** - 仍有待处理项'}
|
||||
|
||||
---
|
||||
|
||||
## Development Phase
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Total Tasks | ${stats.develop.total_tasks} |
|
||||
| Completed | ${stats.develop.completed_tasks} |
|
||||
| Completion Rate | ${stats.develop.completion_rate}% |
|
||||
|
||||
### Completed Tasks
|
||||
|
||||
${state.develop.tasks.filter(t => t.status === 'completed').map(t => `
|
||||
- ✅ ${t.description}
|
||||
- Files: ${t.files_changed?.join(', ') || 'N/A'}
|
||||
- Completed: ${t.completed_at}
|
||||
`).join('\n')}
|
||||
|
||||
### Pending Tasks
|
||||
|
||||
${state.develop.tasks.filter(t => t.status !== 'completed').map(t => `
|
||||
- ⏳ ${t.description}
|
||||
`).join('\n') || '_None_'}
|
||||
|
||||
---
|
||||
|
||||
## Debug Phase
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Iterations | ${stats.debug.iterations} |
|
||||
| Hypotheses Tested | ${stats.debug.hypotheses_tested} |
|
||||
| Root Cause Found | ${stats.debug.root_cause_found ? 'Yes' : 'No'} |
|
||||
|
||||
${stats.debug.root_cause_found ? `
|
||||
### Confirmed Root Cause
|
||||
|
||||
**${state.debug.confirmed_hypothesis}**: ${state.debug.hypotheses.find(h => h.id === state.debug.confirmed_hypothesis)?.description || 'N/A'}
|
||||
` : ''}
|
||||
|
||||
### Hypothesis Summary
|
||||
|
||||
${state.debug.hypotheses.map(h => `
|
||||
- **${h.id}**: ${h.status.toUpperCase()}
|
||||
- ${h.description}
|
||||
`).join('\n') || '_No hypotheses tested_'}
|
||||
|
||||
---
|
||||
|
||||
## Validation Phase
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Test Runs | ${stats.validate.runs} |
|
||||
| Status | ${stats.validate.passed ? 'PASSED' : 'FAILED'} |
|
||||
| Coverage | ${stats.validate.coverage || 'N/A'}% |
|
||||
| Failed Tests | ${stats.validate.failed_tests} |
|
||||
|
||||
${stats.validate.failed_tests > 0 ? `
|
||||
### Failed Tests
|
||||
|
||||
${state.validate.failed_tests.map(t => `- ❌ ${t}`).join('\n')}
|
||||
` : ''}
|
||||
|
||||
---
|
||||
|
||||
## Files Modified
|
||||
|
||||
${listModifiedFiles(sessionFolder)}
|
||||
|
||||
---
|
||||
|
||||
## Key Learnings
|
||||
|
||||
${state.debug.iteration > 0 ? `
|
||||
### From Debugging
|
||||
|
||||
${extractLearnings(state.debug.hypotheses)}
|
||||
` : ''}
|
||||
|
||||
---
|
||||
|
||||
## Recommendations
|
||||
|
||||
${generateRecommendations(stats, state)}
|
||||
|
||||
---
|
||||
|
||||
## Session Artifacts
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| \`develop/progress.md\` | Development progress timeline |
|
||||
| \`develop/tasks.json\` | Task list with status |
|
||||
| \`debug/understanding.md\` | Debug exploration and learnings |
|
||||
| \`debug/hypotheses.json\` | Hypothesis history |
|
||||
| \`validate/validation.md\` | Validation report |
|
||||
| \`validate/test-results.json\` | Test execution results |
|
||||
|
||||
---
|
||||
|
||||
*Generated by CCW Loop at ${getUtc8ISOString()}*
|
||||
`
|
||||
|
||||
Write(`${sessionFolder}/summary.md`, summaryReport)
|
||||
console.log(`\n报告已保存: ${sessionFolder}/summary.md`)
|
||||
```
|
||||
|
||||
### Step 3: 询问后续扩展
|
||||
|
||||
```javascript
|
||||
console.log('\n' + '═'.repeat(60))
|
||||
console.log(' 任务已完成')
|
||||
console.log('═'.repeat(60))
|
||||
|
||||
const expansionResponse = await AskUserQuestion({
|
||||
questions: [{
|
||||
question: "是否将发现扩展为 Issue?",
|
||||
header: "扩展选项",
|
||||
multiSelect: true,
|
||||
options: [
|
||||
{ label: "测试 (Test)", description: "添加更多测试用例" },
|
||||
{ label: "增强 (Enhance)", description: "功能增强建议" },
|
||||
{ label: "重构 (Refactor)", description: "代码重构建议" },
|
||||
{ label: "文档 (Doc)", description: "文档更新需求" },
|
||||
{ label: "否,直接完成", description: "不创建 Issue" }
|
||||
]
|
||||
}]
|
||||
})
|
||||
|
||||
const selectedExpansions = expansionResponse["扩展选项"]
|
||||
|
||||
if (selectedExpansions && !selectedExpansions.includes("否,直接完成")) {
|
||||
for (const expansion of selectedExpansions) {
|
||||
const dimension = expansion.split(' ')[0].toLowerCase()
|
||||
const issueSummary = `${state.task_description} - ${dimension}`
|
||||
|
||||
console.log(`\n创建 Issue: ${issueSummary}`)
|
||||
|
||||
// 调用 /issue:new 创建 issue
|
||||
await Bash({
|
||||
command: `/issue:new "${issueSummary}"`,
|
||||
run_in_background: false
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 4: 最终输出
|
||||
|
||||
```javascript
|
||||
console.log(`
|
||||
═══════════════════════════════════════════════════════════
|
||||
✅ CCW Loop 会话完成
|
||||
═══════════════════════════════════════════════════════════
|
||||
|
||||
会话 ID: ${state.session_id}
|
||||
用时: ${formatDuration(stats.duration)}
|
||||
迭代: ${stats.iterations}
|
||||
|
||||
开发: ${stats.develop.completed_tasks}/${stats.develop.total_tasks} 任务完成
|
||||
调试: ${stats.debug.iterations} 次迭代
|
||||
验证: ${stats.validate.passed ? '通过 ✅' : '未通过 ❌'}
|
||||
|
||||
报告: ${sessionFolder}/summary.md
|
||||
|
||||
═══════════════════════════════════════════════════════════
|
||||
`)
|
||||
```
|
||||
|
||||
## State Updates
|
||||
|
||||
```javascript
|
||||
return {
|
||||
stateUpdates: {
|
||||
status: 'completed',
|
||||
completed_at: getUtc8ISOString(),
|
||||
summary: stats
|
||||
},
|
||||
continue: false,
|
||||
message: `会话 ${state.session_id} 已完成`
|
||||
}
|
||||
```
|
||||
|
||||
## Helper Functions
|
||||
|
||||
```javascript
|
||||
function formatDuration(ms) {
|
||||
const seconds = Math.floor(ms / 1000)
|
||||
const minutes = Math.floor(seconds / 60)
|
||||
const hours = Math.floor(minutes / 60)
|
||||
|
||||
if (hours > 0) {
|
||||
return `${hours}h ${minutes % 60}m`
|
||||
} else if (minutes > 0) {
|
||||
return `${minutes}m ${seconds % 60}s`
|
||||
} else {
|
||||
return `${seconds}s`
|
||||
}
|
||||
}
|
||||
|
||||
function generateRecommendations(stats, state) {
|
||||
const recommendations = []
|
||||
|
||||
if (stats.develop.completion_rate < 100) {
|
||||
recommendations.push('- 完成剩余开发任务')
|
||||
}
|
||||
|
||||
if (!stats.validate.passed) {
|
||||
recommendations.push('- 修复失败的测试')
|
||||
}
|
||||
|
||||
if (stats.validate.coverage && stats.validate.coverage < 80) {
|
||||
recommendations.push(`- 提高测试覆盖率 (当前: ${stats.validate.coverage}%)`)
|
||||
}
|
||||
|
||||
if (stats.debug.iterations > 3 && !stats.debug.root_cause_found) {
|
||||
recommendations.push('- 考虑代码重构以简化调试')
|
||||
}
|
||||
|
||||
if (recommendations.length === 0) {
|
||||
recommendations.push('- 考虑代码审查')
|
||||
recommendations.push('- 更新相关文档')
|
||||
recommendations.push('- 准备部署')
|
||||
}
|
||||
|
||||
return recommendations.join('\n')
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error Type | Recovery |
|
||||
|------------|----------|
|
||||
| 报告生成失败 | 显示基本统计,跳过文件写入 |
|
||||
| Issue 创建失败 | 记录错误,继续完成 |
|
||||
|
||||
## Next Actions
|
||||
|
||||
- 无 (终止状态)
|
||||
- 如需继续: 使用 `ccw-loop --resume {session-id}` 重新打开会话
|
||||
485
.claude/skills/ccw-loop/phases/actions/action-debug-with-file.md
Normal file
485
.claude/skills/ccw-loop/phases/actions/action-debug-with-file.md
Normal file
@@ -0,0 +1,485 @@
|
||||
# Action: Debug With File
|
||||
|
||||
假设驱动调试,记录理解演变到 understanding.md,支持 Gemini 辅助分析和假设生成。
|
||||
|
||||
## Purpose
|
||||
|
||||
执行假设驱动的调试流程,包括:
|
||||
- 定位错误源
|
||||
- 生成可测试假设
|
||||
- 添加 NDJSON 日志
|
||||
- 分析日志证据
|
||||
- 纠正错误理解
|
||||
- 应用修复
|
||||
|
||||
## Preconditions
|
||||
|
||||
- [ ] state.initialized === true
|
||||
- [ ] state.status === 'running'
|
||||
|
||||
## Session Setup
|
||||
|
||||
```javascript
|
||||
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
|
||||
|
||||
const sessionFolder = `.workflow/.loop/${state.session_id}`
|
||||
const debugFolder = `${sessionFolder}/debug`
|
||||
const understandingPath = `${debugFolder}/understanding.md`
|
||||
const hypothesesPath = `${debugFolder}/hypotheses.json`
|
||||
const debugLogPath = `${debugFolder}/debug.log`
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Mode Detection
|
||||
|
||||
```javascript
|
||||
// 自动检测模式
|
||||
const understandingExists = fs.existsSync(understandingPath)
|
||||
const logHasContent = fs.existsSync(debugLogPath) && fs.statSync(debugLogPath).size > 0
|
||||
|
||||
const debugMode = logHasContent ? 'analyze' : (understandingExists ? 'continue' : 'explore')
|
||||
|
||||
console.log(`Debug mode: ${debugMode}`)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Explore Mode (首次调试)
|
||||
|
||||
### Step 1.1: 定位错误源
|
||||
|
||||
```javascript
|
||||
if (debugMode === 'explore') {
|
||||
// 询问用户 bug 描述
|
||||
const bugInput = await AskUserQuestion({
|
||||
questions: [{
|
||||
question: "请描述遇到的 bug 或错误信息:",
|
||||
header: "Bug 描述",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "手动输入", description: "输入错误描述或堆栈" },
|
||||
{ label: "从测试失败", description: "从验证阶段的失败测试中获取" }
|
||||
]
|
||||
}]
|
||||
})
|
||||
|
||||
const bugDescription = bugInput["Bug 描述"]
|
||||
|
||||
// 提取关键词并搜索
|
||||
const searchResults = await Task({
|
||||
subagent_type: 'Explore',
|
||||
run_in_background: false,
|
||||
prompt: `Search codebase for error patterns related to: ${bugDescription}`
|
||||
})
|
||||
|
||||
// 分析搜索结果,识别受影响的位置
|
||||
const affectedLocations = analyzeSearchResults(searchResults)
|
||||
}
|
||||
```
|
||||
|
||||
### Step 1.2: 记录初始理解
|
||||
|
||||
```javascript
|
||||
// 创建 understanding.md
|
||||
const initialUnderstanding = `# Understanding Document
|
||||
|
||||
**Session ID**: ${state.session_id}
|
||||
**Bug Description**: ${bugDescription}
|
||||
**Started**: ${getUtc8ISOString()}
|
||||
|
||||
---
|
||||
|
||||
## Exploration Timeline
|
||||
|
||||
### Iteration 1 - Initial Exploration (${getUtc8ISOString()})
|
||||
|
||||
#### Current Understanding
|
||||
|
||||
Based on bug description and initial code search:
|
||||
|
||||
- Error pattern: ${errorPattern}
|
||||
- Affected areas: ${affectedLocations.map(l => l.file).join(', ')}
|
||||
- Initial hypothesis: ${initialThoughts}
|
||||
|
||||
#### Evidence from Code Search
|
||||
|
||||
${searchResults.map(r => `
|
||||
**Keyword: "${r.keyword}"**
|
||||
- Found in: ${r.files.join(', ')}
|
||||
- Key findings: ${r.insights}
|
||||
`).join('\n')}
|
||||
|
||||
#### Next Steps
|
||||
|
||||
- Generate testable hypotheses
|
||||
- Add instrumentation
|
||||
- Await reproduction
|
||||
|
||||
---
|
||||
|
||||
## Current Consolidated Understanding
|
||||
|
||||
${initialConsolidatedUnderstanding}
|
||||
`
|
||||
|
||||
Write(understandingPath, initialUnderstanding)
|
||||
```
|
||||
|
||||
### Step 1.3: Gemini 辅助假设生成
|
||||
|
||||
```bash
|
||||
ccw cli -p "
|
||||
PURPOSE: Generate debugging hypotheses for: ${bugDescription}
|
||||
Success criteria: Testable hypotheses with clear evidence criteria
|
||||
|
||||
TASK:
|
||||
• Analyze error pattern and code search results
|
||||
• Identify 3-5 most likely root causes
|
||||
• For each hypothesis, specify:
|
||||
- What might be wrong
|
||||
- What evidence would confirm/reject it
|
||||
- Where to add instrumentation
|
||||
• Rank by likelihood
|
||||
|
||||
MODE: analysis
|
||||
|
||||
CONTEXT: @${understandingPath} | Search results in understanding.md
|
||||
|
||||
EXPECTED:
|
||||
- Structured hypothesis list (JSON format)
|
||||
- Each hypothesis with: id, description, testable_condition, logging_point, evidence_criteria
|
||||
- Likelihood ranking (1=most likely)
|
||||
|
||||
CONSTRAINTS: Focus on testable conditions
|
||||
" --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause
|
||||
```
|
||||
|
||||
### Step 1.4: 保存假设
|
||||
|
||||
```javascript
|
||||
const hypotheses = {
|
||||
iteration: 1,
|
||||
timestamp: getUtc8ISOString(),
|
||||
bug_description: bugDescription,
|
||||
hypotheses: [
|
||||
{
|
||||
id: "H1",
|
||||
description: "...",
|
||||
testable_condition: "...",
|
||||
logging_point: "file.ts:func:42",
|
||||
evidence_criteria: {
|
||||
confirm: "...",
|
||||
reject: "..."
|
||||
},
|
||||
likelihood: 1,
|
||||
status: "pending"
|
||||
}
|
||||
// ...
|
||||
],
|
||||
gemini_insights: "...",
|
||||
corrected_assumptions: []
|
||||
}
|
||||
|
||||
Write(hypothesesPath, JSON.stringify(hypotheses, null, 2))
|
||||
```
|
||||
|
||||
### Step 1.5: 添加 NDJSON 日志
|
||||
|
||||
```javascript
|
||||
// 为每个假设添加日志点
|
||||
for (const hypothesis of hypotheses.hypotheses) {
|
||||
const [file, func, line] = hypothesis.logging_point.split(':')
|
||||
|
||||
const logStatement = `console.log(JSON.stringify({
|
||||
hid: "${hypothesis.id}",
|
||||
ts: Date.now(),
|
||||
func: "${func}",
|
||||
data: { /* 相关数据 */ }
|
||||
}))`
|
||||
|
||||
// 使用 Edit 工具添加日志
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Analyze Mode (有日志后)
|
||||
|
||||
### Step 2.1: 解析调试日志
|
||||
|
||||
```javascript
|
||||
if (debugMode === 'analyze') {
|
||||
// 读取 NDJSON 日志
|
||||
const logContent = Read(debugLogPath)
|
||||
const entries = logContent.split('\n')
|
||||
.filter(l => l.trim())
|
||||
.map(l => JSON.parse(l))
|
||||
|
||||
// 按假设分组
|
||||
const byHypothesis = groupBy(entries, 'hid')
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2.2: Gemini 辅助证据分析
|
||||
|
||||
```bash
|
||||
ccw cli -p "
|
||||
PURPOSE: Analyze debug log evidence to validate/correct hypotheses for: ${bugDescription}
|
||||
Success criteria: Clear verdict per hypothesis + corrected understanding
|
||||
|
||||
TASK:
|
||||
• Parse log entries by hypothesis
|
||||
• Evaluate evidence against expected criteria
|
||||
• Determine verdict: confirmed | rejected | inconclusive
|
||||
• Identify incorrect assumptions from previous understanding
|
||||
• Suggest corrections to understanding
|
||||
|
||||
MODE: analysis
|
||||
|
||||
CONTEXT:
|
||||
@${debugLogPath}
|
||||
@${understandingPath}
|
||||
@${hypothesesPath}
|
||||
|
||||
EXPECTED:
|
||||
- Per-hypothesis verdict with reasoning
|
||||
- Evidence summary
|
||||
- List of incorrect assumptions with corrections
|
||||
- Updated consolidated understanding
|
||||
- Root cause if confirmed, or next investigation steps
|
||||
|
||||
CONSTRAINTS: Evidence-based reasoning only, no speculation
|
||||
" --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause
|
||||
```
|
||||
|
||||
### Step 2.3: 更新理解文档
|
||||
|
||||
```javascript
|
||||
// 追加新迭代到 understanding.md
|
||||
const iteration = state.debug.iteration + 1
|
||||
|
||||
const analysisEntry = `
|
||||
### Iteration ${iteration} - Evidence Analysis (${getUtc8ISOString()})
|
||||
|
||||
#### Log Analysis Results
|
||||
|
||||
${results.map(r => `
|
||||
**${r.id}**: ${r.verdict.toUpperCase()}
|
||||
- Evidence: ${JSON.stringify(r.evidence)}
|
||||
- Reasoning: ${r.reason}
|
||||
`).join('\n')}
|
||||
|
||||
#### Corrected Understanding
|
||||
|
||||
Previous misunderstandings identified and corrected:
|
||||
|
||||
${corrections.map(c => `
|
||||
- ~~${c.wrong}~~ → ${c.corrected}
|
||||
- Why wrong: ${c.reason}
|
||||
- Evidence: ${c.evidence}
|
||||
`).join('\n')}
|
||||
|
||||
#### New Insights
|
||||
|
||||
${newInsights.join('\n- ')}
|
||||
|
||||
#### Gemini Analysis
|
||||
|
||||
${geminiAnalysis}
|
||||
|
||||
${confirmedHypothesis ? `
|
||||
#### Root Cause Identified
|
||||
|
||||
**${confirmedHypothesis.id}**: ${confirmedHypothesis.description}
|
||||
|
||||
Evidence supporting this conclusion:
|
||||
${confirmedHypothesis.supportingEvidence}
|
||||
` : `
|
||||
#### Next Steps
|
||||
|
||||
${nextSteps}
|
||||
`}
|
||||
|
||||
---
|
||||
|
||||
## Current Consolidated Understanding (Updated)
|
||||
|
||||
### What We Know
|
||||
|
||||
- ${validUnderstanding1}
|
||||
- ${validUnderstanding2}
|
||||
|
||||
### What Was Disproven
|
||||
|
||||
- ~~${wrongAssumption}~~ (Evidence: ${disproofEvidence})
|
||||
|
||||
### Current Investigation Focus
|
||||
|
||||
${currentFocus}
|
||||
|
||||
### Remaining Questions
|
||||
|
||||
- ${openQuestion1}
|
||||
- ${openQuestion2}
|
||||
`
|
||||
|
||||
const existingContent = Read(understandingPath)
|
||||
Write(understandingPath, existingContent + analysisEntry)
|
||||
```
|
||||
|
||||
### Step 2.4: 更新假设状态
|
||||
|
||||
```javascript
|
||||
const hypothesesData = JSON.parse(Read(hypothesesPath))
|
||||
|
||||
// 更新假设状态
|
||||
hypothesesData.hypotheses = hypothesesData.hypotheses.map(h => ({
|
||||
...h,
|
||||
status: results.find(r => r.id === h.id)?.verdict || h.status,
|
||||
evidence: results.find(r => r.id === h.id)?.evidence || h.evidence,
|
||||
verdict_reason: results.find(r => r.id === h.id)?.reason || h.verdict_reason
|
||||
}))
|
||||
|
||||
hypothesesData.iteration++
|
||||
hypothesesData.timestamp = getUtc8ISOString()
|
||||
|
||||
Write(hypothesesPath, JSON.stringify(hypothesesData, null, 2))
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Fix & Verification
|
||||
|
||||
### Step 3.1: 应用修复
|
||||
|
||||
```javascript
|
||||
if (confirmedHypothesis) {
|
||||
console.log(`\n根因确认: ${confirmedHypothesis.description}`)
|
||||
console.log('准备应用修复...')
|
||||
|
||||
// 使用 Gemini 生成修复代码
|
||||
const fixPrompt = `
|
||||
PURPOSE: Fix the identified root cause
|
||||
Root Cause: ${confirmedHypothesis.description}
|
||||
Evidence: ${confirmedHypothesis.supportingEvidence}
|
||||
|
||||
TASK:
|
||||
• Generate fix code
|
||||
• Ensure backward compatibility
|
||||
• Add tests if needed
|
||||
|
||||
MODE: write
|
||||
|
||||
CONTEXT: @${confirmedHypothesis.logging_point.split(':')[0]}
|
||||
|
||||
EXPECTED: Fixed code + verification steps
|
||||
`
|
||||
|
||||
await Bash({
|
||||
command: `ccw cli -p "${fixPrompt}" --tool gemini --mode write --rule development-debug-runtime-issues`,
|
||||
run_in_background: false
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
### Step 3.2: 记录解决方案
|
||||
|
||||
```javascript
|
||||
const resolutionEntry = `
|
||||
### Resolution (${getUtc8ISOString()})
|
||||
|
||||
#### Fix Applied
|
||||
|
||||
- Modified files: ${modifiedFiles.join(', ')}
|
||||
- Fix description: ${fixDescription}
|
||||
- Root cause addressed: ${rootCause}
|
||||
|
||||
#### Verification Results
|
||||
|
||||
${verificationResults}
|
||||
|
||||
#### Lessons Learned
|
||||
|
||||
1. ${lesson1}
|
||||
2. ${lesson2}
|
||||
|
||||
#### Key Insights for Future
|
||||
|
||||
- ${insight1}
|
||||
- ${insight2}
|
||||
`
|
||||
|
||||
const existingContent = Read(understandingPath)
|
||||
Write(understandingPath, existingContent + resolutionEntry)
|
||||
```
|
||||
|
||||
### Step 3.3: 清理日志
|
||||
|
||||
```javascript
|
||||
// 移除调试日志
|
||||
// (可选,根据用户选择)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## State Updates
|
||||
|
||||
```javascript
|
||||
return {
|
||||
stateUpdates: {
|
||||
debug: {
|
||||
current_bug: bugDescription,
|
||||
hypotheses: hypothesesData.hypotheses,
|
||||
confirmed_hypothesis: confirmedHypothesis?.id || null,
|
||||
iteration: hypothesesData.iteration,
|
||||
last_analysis_at: getUtc8ISOString(),
|
||||
understanding_updated: true
|
||||
},
|
||||
last_action: 'action-debug-with-file'
|
||||
},
|
||||
continue: true,
|
||||
message: confirmedHypothesis
|
||||
? `根因确认: ${confirmedHypothesis.description}\n修复已应用,请验证`
|
||||
: `分析完成,需要更多证据\n请复现 bug 后再次执行`
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error Type | Recovery |
|
||||
|------------|----------|
|
||||
| 空 debug.log | 提示用户复现 bug |
|
||||
| 所有假设被否定 | 使用 Gemini 生成新假设 |
|
||||
| 修复无效 | 记录失败尝试,迭代 |
|
||||
| >5 迭代 | 建议升级到 /workflow:lite-fix |
|
||||
| Gemini 不可用 | 回退到手动分析 |
|
||||
|
||||
## Understanding Document Template
|
||||
|
||||
参考 [templates/understanding-template.md](../../templates/understanding-template.md)
|
||||
|
||||
## CLI Integration
|
||||
|
||||
### 假设生成
|
||||
```bash
|
||||
ccw cli -p "PURPOSE: Generate debugging hypotheses..." --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause
|
||||
```
|
||||
|
||||
### 证据分析
|
||||
```bash
|
||||
ccw cli -p "PURPOSE: Analyze debug log evidence..." --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause
|
||||
```
|
||||
|
||||
### 生成修复
|
||||
```bash
|
||||
ccw cli -p "PURPOSE: Fix the identified root cause..." --tool gemini --mode write --rule development-debug-runtime-issues
|
||||
```
|
||||
|
||||
## Next Actions (Hints)
|
||||
|
||||
- 根因确认: `action-validate-with-file` (验证修复)
|
||||
- 需要更多证据: 等待用户复现,再次执行此动作
|
||||
- 所有假设否定: 重新执行此动作生成新假设
|
||||
- 用户选择: `action-menu` (返回菜单)
|
||||
@@ -0,0 +1,365 @@
|
||||
# Action: Develop With File
|
||||
|
||||
增量开发任务执行,记录进度到 progress.md,支持 Gemini 辅助实现。
|
||||
|
||||
## Purpose
|
||||
|
||||
执行开发任务并记录进度,包括:
|
||||
- 分析任务需求
|
||||
- 使用 Gemini/CLI 实现代码
|
||||
- 记录代码变更
|
||||
- 更新进度文档
|
||||
|
||||
## Preconditions
|
||||
|
||||
- [ ] state.status === 'running'
|
||||
- [ ] state.skill_state !== null
|
||||
- [ ] state.skill_state.develop.tasks.some(t => t.status === 'pending')
|
||||
|
||||
## Session Setup (Unified Location)
|
||||
|
||||
```javascript
|
||||
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
|
||||
|
||||
// 统一位置: .loop/{loopId}
|
||||
const loopId = state.loop_id
|
||||
const loopFile = `.loop/${loopId}.json`
|
||||
const progressDir = `.loop/${loopId}.progress`
|
||||
const progressPath = `${progressDir}/develop.md`
|
||||
const changesLogPath = `${progressDir}/changes.log`
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Execution
|
||||
|
||||
### Step 0: Check Control Signals (CRITICAL)
|
||||
|
||||
```javascript
|
||||
/**
|
||||
* CRITICAL: 每个 Action 必须在开始时检查控制信号
|
||||
* 如果 API 设置了 paused/stopped,Skill 应立即退出
|
||||
*/
|
||||
function checkControlSignals(loopId) {
|
||||
const state = JSON.parse(Read(`.loop/${loopId}.json`))
|
||||
|
||||
switch (state.status) {
|
||||
case 'paused':
|
||||
console.log('⏸️ Loop paused by API. Exiting action.')
|
||||
return { continue: false, reason: 'paused' }
|
||||
|
||||
case 'failed':
|
||||
console.log('⏹️ Loop stopped by API. Exiting action.')
|
||||
return { continue: false, reason: 'stopped' }
|
||||
|
||||
case 'running':
|
||||
return { continue: true, reason: 'running' }
|
||||
|
||||
default:
|
||||
return { continue: false, reason: 'unknown_status' }
|
||||
}
|
||||
}
|
||||
|
||||
// Execute check
|
||||
const control = checkControlSignals(loopId)
|
||||
if (!control.continue) {
|
||||
return {
|
||||
skillStateUpdates: { current_action: null },
|
||||
continue: false,
|
||||
message: `Action terminated: ${control.reason}`
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 1: 加载任务列表
|
||||
|
||||
```javascript
|
||||
// 读取任务列表 (从 skill_state)
|
||||
let tasks = state.skill_state?.develop?.tasks || []
|
||||
|
||||
// 如果任务列表为空,询问用户创建
|
||||
if (tasks.length === 0) {
|
||||
// 使用 Gemini 分析任务描述,生成任务列表
|
||||
const analysisPrompt = `
|
||||
PURPOSE: 分析开发任务并分解为可执行步骤
|
||||
Success: 生成 3-7 个具体、可验证的子任务
|
||||
|
||||
TASK:
|
||||
• 分析任务描述: ${state.task_description}
|
||||
• 识别关键功能点
|
||||
• 分解为独立子任务
|
||||
• 为每个子任务指定工具和模式
|
||||
|
||||
MODE: analysis
|
||||
|
||||
CONTEXT: @package.json @src/**/*.ts | Memory: 项目结构
|
||||
|
||||
EXPECTED:
|
||||
JSON 格式:
|
||||
{
|
||||
"tasks": [
|
||||
{
|
||||
"id": "task-001",
|
||||
"description": "任务描述",
|
||||
"tool": "gemini",
|
||||
"mode": "write",
|
||||
"files": ["src/xxx.ts"]
|
||||
}
|
||||
]
|
||||
}
|
||||
`
|
||||
|
||||
const result = await Task({
|
||||
subagent_type: 'cli-execution-agent',
|
||||
run_in_background: false,
|
||||
prompt: `Execute Gemini CLI with prompt: ${analysisPrompt}`
|
||||
})
|
||||
|
||||
tasks = JSON.parse(result).tasks
|
||||
}
|
||||
|
||||
// 找到第一个待处理任务
|
||||
const currentTask = tasks.find(t => t.status === 'pending')
|
||||
|
||||
if (!currentTask) {
|
||||
return {
|
||||
skillStateUpdates: {
|
||||
develop: { ...state.skill_state.develop, current_task: null }
|
||||
},
|
||||
continue: true,
|
||||
message: '所有开发任务已完成'
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2: 执行开发任务
|
||||
|
||||
```javascript
|
||||
console.log(`\n执行任务: ${currentTask.description}`)
|
||||
|
||||
// 更新任务状态
|
||||
currentTask.status = 'in_progress'
|
||||
|
||||
// 使用 Gemini 实现
|
||||
const implementPrompt = `
|
||||
PURPOSE: 实现开发任务
|
||||
Task: ${currentTask.description}
|
||||
Success criteria: 代码实现完成,测试通过
|
||||
|
||||
TASK:
|
||||
• 分析现有代码结构
|
||||
• 实现功能代码
|
||||
• 添加必要的类型定义
|
||||
• 确保代码风格一致
|
||||
|
||||
MODE: write
|
||||
|
||||
CONTEXT: @${currentTask.files?.join(' @') || 'src/**/*.ts'}
|
||||
|
||||
EXPECTED:
|
||||
- 完整的代码实现
|
||||
- 代码变更列表
|
||||
- 简要实现说明
|
||||
|
||||
CONSTRAINTS: 遵循现有代码风格 | 不破坏现有功能
|
||||
`
|
||||
|
||||
const implementResult = await Bash({
|
||||
command: `ccw cli -p "${implementPrompt}" --tool gemini --mode write --rule development-implement-feature`,
|
||||
run_in_background: false
|
||||
})
|
||||
|
||||
// 记录代码变更
|
||||
const timestamp = getUtc8ISOString()
|
||||
const changeEntry = {
|
||||
timestamp,
|
||||
task_id: currentTask.id,
|
||||
description: currentTask.description,
|
||||
files_changed: currentTask.files || [],
|
||||
result: 'success'
|
||||
}
|
||||
|
||||
// 追加到 changes.log (NDJSON 格式)
|
||||
const changesContent = Read(changesLogPath) || ''
|
||||
Write(changesLogPath, changesContent + JSON.stringify(changeEntry) + '\n')
|
||||
```
|
||||
|
||||
### Step 3: 更新进度文档
|
||||
|
||||
```javascript
|
||||
const timestamp = getUtc8ISOString()
|
||||
const iteration = state.develop.completed_count + 1
|
||||
|
||||
// 读取现有进度文档
|
||||
let progressContent = Read(progressPath) || ''
|
||||
|
||||
// 如果是新文档,添加头部
|
||||
if (!progressContent) {
|
||||
progressContent = `# Development Progress
|
||||
|
||||
**Session ID**: ${state.session_id}
|
||||
**Task**: ${state.task_description}
|
||||
**Started**: ${timestamp}
|
||||
|
||||
---
|
||||
|
||||
## Progress Timeline
|
||||
|
||||
`
|
||||
}
|
||||
|
||||
// 追加本次进度
|
||||
const progressEntry = `
|
||||
### Iteration ${iteration} - ${currentTask.description} (${timestamp})
|
||||
|
||||
#### Task Details
|
||||
|
||||
- **ID**: ${currentTask.id}
|
||||
- **Tool**: ${currentTask.tool}
|
||||
- **Mode**: ${currentTask.mode}
|
||||
|
||||
#### Implementation Summary
|
||||
|
||||
${implementResult.summary || '实现完成'}
|
||||
|
||||
#### Files Changed
|
||||
|
||||
${currentTask.files?.map(f => `- \`${f}\``).join('\n') || '- No files specified'}
|
||||
|
||||
#### Status: COMPLETED
|
||||
|
||||
---
|
||||
|
||||
`
|
||||
|
||||
Write(progressPath, progressContent + progressEntry)
|
||||
|
||||
// 更新任务状态
|
||||
currentTask.status = 'completed'
|
||||
currentTask.completed_at = timestamp
|
||||
```
|
||||
|
||||
### Step 4: 更新任务列表文件
|
||||
|
||||
```javascript
|
||||
// 更新 tasks.json
|
||||
const updatedTasks = tasks.map(t =>
|
||||
t.id === currentTask.id ? currentTask : t
|
||||
)
|
||||
|
||||
Write(tasksPath, JSON.stringify(updatedTasks, null, 2))
|
||||
```
|
||||
|
||||
## State Updates
|
||||
|
||||
```javascript
|
||||
return {
|
||||
stateUpdates: {
|
||||
develop: {
|
||||
tasks: updatedTasks,
|
||||
current_task_id: null,
|
||||
completed_count: state.develop.completed_count + 1,
|
||||
total_count: updatedTasks.length,
|
||||
last_progress_at: getUtc8ISOString()
|
||||
},
|
||||
last_action: 'action-develop-with-file'
|
||||
},
|
||||
continue: true,
|
||||
message: `任务完成: ${currentTask.description}\n进度: ${state.develop.completed_count + 1}/${updatedTasks.length}`
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error Type | Recovery |
|
||||
|------------|----------|
|
||||
| Gemini CLI 失败 | 提示用户手动实现,记录到 progress.md |
|
||||
| 文件写入失败 | 重试一次,失败则记录错误 |
|
||||
| 任务解析失败 | 询问用户手动输入任务 |
|
||||
|
||||
## Progress Document Template
|
||||
|
||||
```markdown
|
||||
# Development Progress
|
||||
|
||||
**Session ID**: LOOP-xxx-2026-01-22
|
||||
**Task**: 实现用户认证功能
|
||||
**Started**: 2026-01-22T10:00:00+08:00
|
||||
|
||||
---
|
||||
|
||||
## Progress Timeline
|
||||
|
||||
### Iteration 1 - 分析登录组件 (2026-01-22T10:05:00+08:00)
|
||||
|
||||
#### Task Details
|
||||
|
||||
- **ID**: task-001
|
||||
- **Tool**: gemini
|
||||
- **Mode**: analysis
|
||||
|
||||
#### Implementation Summary
|
||||
|
||||
分析了现有登录组件结构,识别了需要修改的文件和依赖关系。
|
||||
|
||||
#### Files Changed
|
||||
|
||||
- `src/components/Login.tsx`
|
||||
- `src/hooks/useAuth.ts`
|
||||
|
||||
#### Status: COMPLETED
|
||||
|
||||
---
|
||||
|
||||
### Iteration 2 - 实现登录 API (2026-01-22T10:15:00+08:00)
|
||||
|
||||
...
|
||||
|
||||
---
|
||||
|
||||
## Current Statistics
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Total Tasks | 5 |
|
||||
| Completed | 2 |
|
||||
| In Progress | 1 |
|
||||
| Pending | 2 |
|
||||
| Progress | 40% |
|
||||
|
||||
---
|
||||
|
||||
## Next Steps
|
||||
|
||||
- [ ] 完成剩余任务
|
||||
- [ ] 运行测试
|
||||
- [ ] 代码审查
|
||||
```
|
||||
|
||||
## CLI Integration
|
||||
|
||||
### 任务分析
|
||||
```bash
|
||||
ccw cli -p "PURPOSE: 分解开发任务为子任务
|
||||
TASK: • 分析任务描述 • 识别功能点 • 生成任务列表
|
||||
MODE: analysis
|
||||
CONTEXT: @package.json @src/**/*
|
||||
EXPECTED: JSON 任务列表
|
||||
" --tool gemini --mode analysis --rule planning-breakdown-task-steps
|
||||
```
|
||||
|
||||
### 代码实现
|
||||
```bash
|
||||
ccw cli -p "PURPOSE: 实现功能代码
|
||||
TASK: • 分析需求 • 编写代码 • 添加类型
|
||||
MODE: write
|
||||
CONTEXT: @src/xxx.ts
|
||||
EXPECTED: 完整实现
|
||||
" --tool gemini --mode write --rule development-implement-feature
|
||||
```
|
||||
|
||||
## Next Actions (Hints)
|
||||
|
||||
- 所有任务完成: `action-debug-with-file` (开始调试)
|
||||
- 任务失败: `action-develop-with-file` (重试或下一个任务)
|
||||
- 用户选择: `action-menu` (返回菜单)
|
||||
200
.claude/skills/ccw-loop/phases/actions/action-init.md
Normal file
200
.claude/skills/ccw-loop/phases/actions/action-init.md
Normal file
@@ -0,0 +1,200 @@
|
||||
# Action: Initialize
|
||||
|
||||
初始化 CCW Loop 会话,创建目录结构和初始状态。
|
||||
|
||||
## Purpose
|
||||
|
||||
- 创建会话目录结构
|
||||
- 初始化状态文件
|
||||
- 分析任务描述生成初始任务列表
|
||||
- 准备执行环境
|
||||
|
||||
## Preconditions
|
||||
|
||||
- [ ] state.status === 'pending'
|
||||
- [ ] state.initialized === false
|
||||
|
||||
## Execution
|
||||
|
||||
### Step 1: 创建目录结构
|
||||
|
||||
```javascript
|
||||
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
|
||||
|
||||
const taskSlug = state.task_description.toLowerCase().replace(/[^a-z0-9]+/g, '-').substring(0, 30)
|
||||
const dateStr = getUtc8ISOString().substring(0, 10)
|
||||
const sessionId = `LOOP-${taskSlug}-${dateStr}`
|
||||
const sessionFolder = `.workflow/.loop/${sessionId}`
|
||||
|
||||
Bash(`mkdir -p "${sessionFolder}/develop"`)
|
||||
Bash(`mkdir -p "${sessionFolder}/debug"`)
|
||||
Bash(`mkdir -p "${sessionFolder}/validate"`)
|
||||
|
||||
console.log(`Session created: ${sessionId}`)
|
||||
console.log(`Location: ${sessionFolder}`)
|
||||
```
|
||||
|
||||
### Step 2: 创建元数据文件
|
||||
|
||||
```javascript
|
||||
const meta = {
|
||||
session_id: sessionId,
|
||||
task_description: state.task_description,
|
||||
created_at: getUtc8ISOString(),
|
||||
mode: state.mode || 'interactive'
|
||||
}
|
||||
|
||||
Write(`${sessionFolder}/meta.json`, JSON.stringify(meta, null, 2))
|
||||
```
|
||||
|
||||
### Step 3: 分析任务生成开发任务列表
|
||||
|
||||
```javascript
|
||||
// 使用 Gemini 分析任务描述
|
||||
console.log('\n分析任务描述...')
|
||||
|
||||
const analysisPrompt = `
|
||||
PURPOSE: 分析开发任务并分解为可执行步骤
|
||||
Success: 生成 3-7 个具体、可验证的子任务
|
||||
|
||||
TASK:
|
||||
• 分析任务描述: ${state.task_description}
|
||||
• 识别关键功能点
|
||||
• 分解为独立子任务
|
||||
• 为每个子任务指定工具和模式
|
||||
|
||||
MODE: analysis
|
||||
|
||||
CONTEXT: @package.json @src/**/*.ts (如存在)
|
||||
|
||||
EXPECTED:
|
||||
JSON 格式:
|
||||
{
|
||||
"tasks": [
|
||||
{
|
||||
"id": "task-001",
|
||||
"description": "任务描述",
|
||||
"tool": "gemini",
|
||||
"mode": "write",
|
||||
"priority": 1
|
||||
}
|
||||
],
|
||||
"estimated_complexity": "low|medium|high",
|
||||
"key_files": ["file1.ts", "file2.ts"]
|
||||
}
|
||||
|
||||
CONSTRAINTS: 生成实际可执行的任务
|
||||
`
|
||||
|
||||
const result = await Bash({
|
||||
command: `ccw cli -p "${analysisPrompt}" --tool gemini --mode analysis --rule planning-breakdown-task-steps`,
|
||||
run_in_background: false
|
||||
})
|
||||
|
||||
const analysis = JSON.parse(result.stdout)
|
||||
const tasks = analysis.tasks.map((t, i) => ({
|
||||
...t,
|
||||
id: t.id || `task-${String(i + 1).padStart(3, '0')}`,
|
||||
status: 'pending',
|
||||
created_at: getUtc8ISOString(),
|
||||
completed_at: null,
|
||||
files_changed: []
|
||||
}))
|
||||
|
||||
// 保存任务列表
|
||||
Write(`${sessionFolder}/develop/tasks.json`, JSON.stringify(tasks, null, 2))
|
||||
```
|
||||
|
||||
### Step 4: 初始化进度文档
|
||||
|
||||
```javascript
|
||||
const progressInitial = `# Development Progress
|
||||
|
||||
**Session ID**: ${sessionId}
|
||||
**Task**: ${state.task_description}
|
||||
**Started**: ${getUtc8ISOString()}
|
||||
**Estimated Complexity**: ${analysis.estimated_complexity}
|
||||
|
||||
---
|
||||
|
||||
## Task List
|
||||
|
||||
${tasks.map((t, i) => `${i + 1}. [ ] ${t.description}`).join('\n')}
|
||||
|
||||
## Key Files
|
||||
|
||||
${analysis.key_files?.map(f => `- \`${f}\``).join('\n') || '- To be determined'}
|
||||
|
||||
---
|
||||
|
||||
## Progress Timeline
|
||||
|
||||
`
|
||||
|
||||
Write(`${sessionFolder}/develop/progress.md`, progressInitial)
|
||||
```
|
||||
|
||||
### Step 5: 显示初始化结果
|
||||
|
||||
```javascript
|
||||
console.log(`\n✅ 会话初始化完成`)
|
||||
console.log(`\n任务列表 (${tasks.length} 项):`)
|
||||
tasks.forEach((t, i) => {
|
||||
console.log(` ${i + 1}. ${t.description} [${t.tool}/${t.mode}]`)
|
||||
})
|
||||
console.log(`\n预估复杂度: ${analysis.estimated_complexity}`)
|
||||
console.log(`\n执行 'develop' 开始开发,或 'menu' 查看更多选项`)
|
||||
```
|
||||
|
||||
## State Updates
|
||||
|
||||
```javascript
|
||||
return {
|
||||
stateUpdates: {
|
||||
session_id: sessionId,
|
||||
status: 'running',
|
||||
initialized: true,
|
||||
develop: {
|
||||
tasks: tasks,
|
||||
current_task_id: null,
|
||||
completed_count: 0,
|
||||
total_count: tasks.length,
|
||||
last_progress_at: null
|
||||
},
|
||||
debug: {
|
||||
current_bug: null,
|
||||
hypotheses: [],
|
||||
confirmed_hypothesis: null,
|
||||
iteration: 0,
|
||||
last_analysis_at: null,
|
||||
understanding_updated: false
|
||||
},
|
||||
validate: {
|
||||
test_results: [],
|
||||
coverage: null,
|
||||
passed: false,
|
||||
failed_tests: [],
|
||||
last_run_at: null
|
||||
},
|
||||
context: {
|
||||
estimated_complexity: analysis.estimated_complexity,
|
||||
key_files: analysis.key_files
|
||||
}
|
||||
},
|
||||
continue: true,
|
||||
message: `会话 ${sessionId} 已初始化\n${tasks.length} 个开发任务待执行`
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error Type | Recovery |
|
||||
|------------|----------|
|
||||
| 目录创建失败 | 检查权限,重试 |
|
||||
| Gemini 分析失败 | 提示用户手动输入任务 |
|
||||
| 任务解析失败 | 使用默认任务列表 |
|
||||
|
||||
## Next Actions
|
||||
|
||||
- 成功: `action-menu` (显示操作菜单) 或 `action-develop-with-file` (直接开始开发)
|
||||
- 失败: 报错退出
|
||||
192
.claude/skills/ccw-loop/phases/actions/action-menu.md
Normal file
192
.claude/skills/ccw-loop/phases/actions/action-menu.md
Normal file
@@ -0,0 +1,192 @@
|
||||
# Action: Menu
|
||||
|
||||
显示交互式操作菜单,让用户选择下一步操作。
|
||||
|
||||
## Purpose
|
||||
|
||||
- 显示当前状态摘要
|
||||
- 提供操作选项
|
||||
- 接收用户选择
|
||||
- 返回下一个动作
|
||||
|
||||
## Preconditions
|
||||
|
||||
- [ ] state.initialized === true
|
||||
- [ ] state.status === 'running'
|
||||
|
||||
## Execution
|
||||
|
||||
### Step 1: 生成状态摘要
|
||||
|
||||
```javascript
|
||||
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
|
||||
|
||||
// 开发进度
|
||||
const developProgress = state.develop.total_count > 0
|
||||
? `${state.develop.completed_count}/${state.develop.total_count} (${(state.develop.completed_count / state.develop.total_count * 100).toFixed(0)}%)`
|
||||
: '未开始'
|
||||
|
||||
// 调试状态
|
||||
const debugStatus = state.debug.confirmed_hypothesis
|
||||
? `✅ 已确认根因`
|
||||
: state.debug.iteration > 0
|
||||
? `🔍 迭代 ${state.debug.iteration}`
|
||||
: '未开始'
|
||||
|
||||
// 验证状态
|
||||
const validateStatus = state.validate.passed
|
||||
? `✅ 通过`
|
||||
: state.validate.test_results.length > 0
|
||||
? `❌ ${state.validate.failed_tests.length} 个失败`
|
||||
: '未运行'
|
||||
|
||||
const statusSummary = `
|
||||
═══════════════════════════════════════════════════════════
|
||||
CCW Loop - ${state.session_id}
|
||||
═══════════════════════════════════════════════════════════
|
||||
|
||||
任务: ${state.task_description}
|
||||
迭代: ${state.iteration_count}
|
||||
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ 开发 (Develop) │ ${developProgress.padEnd(20)} │
|
||||
│ 调试 (Debug) │ ${debugStatus.padEnd(20)} │
|
||||
│ 验证 (Validate) │ ${validateStatus.padEnd(20)} │
|
||||
└─────────────────────────────────────────────────────┘
|
||||
|
||||
═══════════════════════════════════════════════════════════
|
||||
`
|
||||
|
||||
console.log(statusSummary)
|
||||
```
|
||||
|
||||
### Step 2: 显示操作选项
|
||||
|
||||
```javascript
|
||||
const options = [
|
||||
{
|
||||
label: "📝 继续开发 (Develop)",
|
||||
description: state.develop.completed_count < state.develop.total_count
|
||||
? `执行下一个开发任务`
|
||||
: "所有任务已完成,可添加新任务",
|
||||
action: "action-develop-with-file"
|
||||
},
|
||||
{
|
||||
label: "🔍 开始调试 (Debug)",
|
||||
description: state.debug.iteration > 0
|
||||
? "继续假设驱动调试"
|
||||
: "开始新的调试会话",
|
||||
action: "action-debug-with-file"
|
||||
},
|
||||
{
|
||||
label: "✅ 运行验证 (Validate)",
|
||||
description: "运行测试并检查覆盖率",
|
||||
action: "action-validate-with-file"
|
||||
},
|
||||
{
|
||||
label: "📊 查看详情 (Status)",
|
||||
description: "查看详细进度和文件",
|
||||
action: "action-status"
|
||||
},
|
||||
{
|
||||
label: "🏁 完成循环 (Complete)",
|
||||
description: "结束当前循环",
|
||||
action: "action-complete"
|
||||
},
|
||||
{
|
||||
label: "🚪 退出 (Exit)",
|
||||
description: "保存状态并退出",
|
||||
action: "exit"
|
||||
}
|
||||
]
|
||||
|
||||
const response = await AskUserQuestion({
|
||||
questions: [{
|
||||
question: "选择下一步操作:",
|
||||
header: "操作",
|
||||
multiSelect: false,
|
||||
options: options.map(o => ({
|
||||
label: o.label,
|
||||
description: o.description
|
||||
}))
|
||||
}]
|
||||
})
|
||||
|
||||
const selectedLabel = response["操作"]
|
||||
const selectedOption = options.find(o => o.label === selectedLabel)
|
||||
const nextAction = selectedOption?.action || 'action-menu'
|
||||
```
|
||||
|
||||
### Step 3: 处理特殊选项
|
||||
|
||||
```javascript
|
||||
if (nextAction === 'exit') {
|
||||
console.log('\n保存状态并退出...')
|
||||
return {
|
||||
stateUpdates: {
|
||||
status: 'user_exit'
|
||||
},
|
||||
continue: false,
|
||||
message: '会话已保存,使用 --resume 可继续'
|
||||
}
|
||||
}
|
||||
|
||||
if (nextAction === 'action-status') {
|
||||
// 显示详细状态
|
||||
const sessionFolder = `.workflow/.loop/${state.session_id}`
|
||||
|
||||
console.log('\n=== 开发进度 ===')
|
||||
const progress = Read(`${sessionFolder}/develop/progress.md`)
|
||||
console.log(progress?.substring(0, 500) + '...')
|
||||
|
||||
console.log('\n=== 调试状态 ===')
|
||||
if (state.debug.hypotheses.length > 0) {
|
||||
state.debug.hypotheses.forEach(h => {
|
||||
console.log(` ${h.id}: ${h.status} - ${h.description.substring(0, 50)}...`)
|
||||
})
|
||||
} else {
|
||||
console.log(' 尚未开始调试')
|
||||
}
|
||||
|
||||
console.log('\n=== 验证结果 ===')
|
||||
if (state.validate.test_results.length > 0) {
|
||||
const latest = state.validate.test_results[state.validate.test_results.length - 1]
|
||||
console.log(` 最近运行: ${latest.timestamp}`)
|
||||
console.log(` 通过率: ${latest.summary.pass_rate}%`)
|
||||
} else {
|
||||
console.log(' 尚未运行验证')
|
||||
}
|
||||
|
||||
// 返回菜单
|
||||
return {
|
||||
stateUpdates: {},
|
||||
continue: true,
|
||||
nextAction: 'action-menu',
|
||||
message: ''
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## State Updates
|
||||
|
||||
```javascript
|
||||
return {
|
||||
stateUpdates: {
|
||||
// 不更新状态,仅返回下一个动作
|
||||
},
|
||||
continue: true,
|
||||
nextAction: nextAction,
|
||||
message: `执行: ${selectedOption?.label || nextAction}`
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error Type | Recovery |
|
||||
|------------|----------|
|
||||
| 用户取消 | 返回菜单 |
|
||||
| 无效选择 | 重新显示菜单 |
|
||||
|
||||
## Next Actions
|
||||
|
||||
根据用户选择动态决定下一个动作。
|
||||
@@ -0,0 +1,307 @@
|
||||
# Action: Validate With File
|
||||
|
||||
运行测试并验证实现,记录结果到 validation.md,支持 Gemini 辅助分析测试覆盖率和质量。
|
||||
|
||||
## Purpose
|
||||
|
||||
执行测试验证流程,包括:
|
||||
- 运行单元测试
|
||||
- 运行集成测试
|
||||
- 检查代码覆盖率
|
||||
- 生成验证报告
|
||||
- 分析失败原因
|
||||
|
||||
## Preconditions
|
||||
|
||||
- [ ] state.initialized === true
|
||||
- [ ] state.status === 'running'
|
||||
- [ ] state.develop.completed_count > 0 || state.debug.confirmed_hypothesis !== null
|
||||
|
||||
## Session Setup
|
||||
|
||||
```javascript
|
||||
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
|
||||
|
||||
const sessionFolder = `.workflow/.loop/${state.session_id}`
|
||||
const validateFolder = `${sessionFolder}/validate`
|
||||
const validationPath = `${validateFolder}/validation.md`
|
||||
const testResultsPath = `${validateFolder}/test-results.json`
|
||||
const coveragePath = `${validateFolder}/coverage.json`
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Execution
|
||||
|
||||
### Step 1: 运行测试
|
||||
|
||||
```javascript
|
||||
console.log('\n运行测试...')
|
||||
|
||||
// 检测测试框架
|
||||
const packageJson = JSON.parse(Read('package.json'))
|
||||
const testScript = packageJson.scripts?.test || 'npm test'
|
||||
|
||||
// 运行测试并捕获输出
|
||||
const testResult = await Bash({
|
||||
command: testScript,
|
||||
timeout: 300000 // 5分钟
|
||||
})
|
||||
|
||||
// 解析测试输出
|
||||
const testResults = parseTestOutput(testResult.stdout)
|
||||
```
|
||||
|
||||
### Step 2: 检查覆盖率
|
||||
|
||||
```javascript
|
||||
// 运行覆盖率检查
|
||||
let coverageData = null
|
||||
|
||||
if (packageJson.scripts?.['test:coverage']) {
|
||||
const coverageResult = await Bash({
|
||||
command: 'npm run test:coverage',
|
||||
timeout: 300000
|
||||
})
|
||||
|
||||
// 解析覆盖率报告
|
||||
coverageData = parseCoverageReport(coverageResult.stdout)
|
||||
|
||||
Write(coveragePath, JSON.stringify(coverageData, null, 2))
|
||||
}
|
||||
```
|
||||
|
||||
### Step 3: Gemini 辅助分析
|
||||
|
||||
```bash
|
||||
ccw cli -p "
|
||||
PURPOSE: Analyze test results and coverage
|
||||
Success criteria: Identify quality issues and suggest improvements
|
||||
|
||||
TASK:
|
||||
• Analyze test execution results
|
||||
• Review code coverage metrics
|
||||
• Identify missing test cases
|
||||
• Suggest quality improvements
|
||||
• Verify requirements coverage
|
||||
|
||||
MODE: analysis
|
||||
|
||||
CONTEXT:
|
||||
@${testResultsPath}
|
||||
@${coveragePath}
|
||||
@${sessionFolder}/develop/progress.md
|
||||
|
||||
EXPECTED:
|
||||
- Quality assessment report
|
||||
- Failed tests analysis
|
||||
- Coverage gaps identification
|
||||
- Improvement recommendations
|
||||
- Pass/Fail decision with rationale
|
||||
|
||||
CONSTRAINTS: Evidence-based quality assessment
|
||||
" --tool gemini --mode analysis --rule analysis-review-code-quality
|
||||
```
|
||||
|
||||
### Step 4: 生成验证报告
|
||||
|
||||
```javascript
|
||||
const timestamp = getUtc8ISOString()
|
||||
const iteration = (state.validate.test_results?.length || 0) + 1
|
||||
|
||||
const validationReport = `# Validation Report
|
||||
|
||||
**Session ID**: ${state.session_id}
|
||||
**Task**: ${state.task_description}
|
||||
**Validated**: ${timestamp}
|
||||
|
||||
---
|
||||
|
||||
## Iteration ${iteration} - Validation Run
|
||||
|
||||
### Test Execution Summary
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Total Tests | ${testResults.total} |
|
||||
| Passed | ${testResults.passed} |
|
||||
| Failed | ${testResults.failed} |
|
||||
| Skipped | ${testResults.skipped} |
|
||||
| Duration | ${testResults.duration_ms}ms |
|
||||
| **Pass Rate** | **${(testResults.passed / testResults.total * 100).toFixed(1)}%** |
|
||||
|
||||
### Coverage Report
|
||||
|
||||
${coverageData ? `
|
||||
| File | Statements | Branches | Functions | Lines |
|
||||
|------|------------|----------|-----------|-------|
|
||||
${coverageData.files.map(f => `| ${f.path} | ${f.statements}% | ${f.branches}% | ${f.functions}% | ${f.lines}% |`).join('\n')}
|
||||
|
||||
**Overall Coverage**: ${coverageData.overall.statements}%
|
||||
` : '_No coverage data available_'}
|
||||
|
||||
### Failed Tests
|
||||
|
||||
${testResults.failed > 0 ? `
|
||||
${testResults.failures.map(f => `
|
||||
#### ${f.test_name}
|
||||
|
||||
- **Suite**: ${f.suite}
|
||||
- **Error**: ${f.error_message}
|
||||
- **Stack**:
|
||||
\`\`\`
|
||||
${f.stack_trace}
|
||||
\`\`\`
|
||||
`).join('\n')}
|
||||
` : '_All tests passed_'}
|
||||
|
||||
### Gemini Quality Analysis
|
||||
|
||||
${geminiAnalysis}
|
||||
|
||||
### Recommendations
|
||||
|
||||
${recommendations.map(r => `- ${r}`).join('\n')}
|
||||
|
||||
---
|
||||
|
||||
## Validation Decision
|
||||
|
||||
**Result**: ${testResults.passed === testResults.total ? '✅ PASS' : '❌ FAIL'}
|
||||
|
||||
**Rationale**: ${validationDecision}
|
||||
|
||||
${testResults.passed !== testResults.total ? `
|
||||
### Next Actions
|
||||
|
||||
1. Review failed tests
|
||||
2. Debug failures using action-debug-with-file
|
||||
3. Fix issues and re-run validation
|
||||
` : `
|
||||
### Next Actions
|
||||
|
||||
1. Consider code review
|
||||
2. Prepare for deployment
|
||||
3. Update documentation
|
||||
`}
|
||||
`
|
||||
|
||||
// 写入验证报告
|
||||
Write(validationPath, validationReport)
|
||||
```
|
||||
|
||||
### Step 5: 保存测试结果
|
||||
|
||||
```javascript
|
||||
const testResultsData = {
|
||||
iteration,
|
||||
timestamp,
|
||||
summary: {
|
||||
total: testResults.total,
|
||||
passed: testResults.passed,
|
||||
failed: testResults.failed,
|
||||
skipped: testResults.skipped,
|
||||
pass_rate: (testResults.passed / testResults.total * 100).toFixed(1),
|
||||
duration_ms: testResults.duration_ms
|
||||
},
|
||||
tests: testResults.tests,
|
||||
failures: testResults.failures,
|
||||
coverage: coverageData?.overall || null
|
||||
}
|
||||
|
||||
Write(testResultsPath, JSON.stringify(testResultsData, null, 2))
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## State Updates
|
||||
|
||||
```javascript
|
||||
const validationPassed = testResults.failed === 0 && testResults.passed > 0
|
||||
|
||||
return {
|
||||
stateUpdates: {
|
||||
validate: {
|
||||
test_results: [...(state.validate.test_results || []), testResultsData],
|
||||
coverage: coverageData?.overall.statements || null,
|
||||
passed: validationPassed,
|
||||
failed_tests: testResults.failures.map(f => f.test_name),
|
||||
last_run_at: getUtc8ISOString()
|
||||
},
|
||||
last_action: 'action-validate-with-file'
|
||||
},
|
||||
continue: true,
|
||||
message: validationPassed
|
||||
? `验证通过 ✅\n测试: ${testResults.passed}/${testResults.total}\n覆盖率: ${coverageData?.overall.statements || 'N/A'}%`
|
||||
: `验证失败 ❌\n失败: ${testResults.failed}/${testResults.total}\n建议进入调试模式`
|
||||
}
|
||||
```
|
||||
|
||||
## Test Output Parsers
|
||||
|
||||
### Jest/Vitest Parser
|
||||
|
||||
```javascript
|
||||
function parseJestOutput(stdout) {
|
||||
const testPattern = /Tests:\s+(\d+) passed.*?(\d+) failed.*?(\d+) total/
|
||||
const match = stdout.match(testPattern)
|
||||
|
||||
return {
|
||||
total: parseInt(match[3]),
|
||||
passed: parseInt(match[1]),
|
||||
failed: parseInt(match[2]),
|
||||
// ... parse individual test results
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Pytest Parser
|
||||
|
||||
```javascript
|
||||
function parsePytestOutput(stdout) {
|
||||
const summaryPattern = /(\d+) passed.*?(\d+) failed.*?(\d+) error/
|
||||
// ... implementation
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error Type | Recovery |
|
||||
|------------|----------|
|
||||
| Tests don't run | 检查测试脚本配置,提示用户 |
|
||||
| All tests fail | 建议进入 debug 模式 |
|
||||
| Coverage tool missing | 跳过覆盖率检查,仅运行测试 |
|
||||
| Timeout | 增加超时时间或拆分测试 |
|
||||
|
||||
## Validation Report Template
|
||||
|
||||
参考 [templates/validation-template.md](../../templates/validation-template.md)
|
||||
|
||||
## CLI Integration
|
||||
|
||||
### 质量分析
|
||||
```bash
|
||||
ccw cli -p "PURPOSE: Analyze test results and coverage...
|
||||
TASK: • Review results • Identify gaps • Suggest improvements
|
||||
MODE: analysis
|
||||
CONTEXT: @test-results.json @coverage.json
|
||||
EXPECTED: Quality assessment
|
||||
" --tool gemini --mode analysis --rule analysis-review-code-quality
|
||||
```
|
||||
|
||||
### 测试生成 (如覆盖率低)
|
||||
```bash
|
||||
ccw cli -p "PURPOSE: Generate missing test cases...
|
||||
TASK: • Analyze uncovered code • Write tests
|
||||
MODE: write
|
||||
CONTEXT: @coverage.json @src/**/*
|
||||
EXPECTED: Test code
|
||||
" --tool gemini --mode write --rule development-generate-tests
|
||||
```
|
||||
|
||||
## Next Actions (Hints)
|
||||
|
||||
- 验证通过: `action-complete` (完成循环)
|
||||
- 验证失败: `action-debug-with-file` (调试失败测试)
|
||||
- 覆盖率低: `action-develop-with-file` (添加测试)
|
||||
- 用户选择: `action-menu` (返回菜单)
|
||||
486
.claude/skills/ccw-loop/phases/orchestrator.md
Normal file
486
.claude/skills/ccw-loop/phases/orchestrator.md
Normal file
@@ -0,0 +1,486 @@
|
||||
# Orchestrator
|
||||
|
||||
根据当前状态选择并执行下一个动作,实现无状态循环工作流。与 API (loop-v2-routes.ts) 协作实现控制平面/执行平面分离。
|
||||
|
||||
## Role
|
||||
|
||||
检查控制信号 → 读取文件状态 → 选择动作 → 执行 → 更新文件 → 循环,直到完成或被外部暂停/停止。
|
||||
|
||||
## State Management (Unified Location)
|
||||
|
||||
### 读取状态
|
||||
|
||||
```javascript
|
||||
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
|
||||
|
||||
/**
|
||||
* 读取循环状态 (统一位置)
|
||||
* @param loopId - Loop ID (e.g., "loop-v2-20260122-abc123")
|
||||
*/
|
||||
function readLoopState(loopId) {
|
||||
const stateFile = `.loop/${loopId}.json`
|
||||
|
||||
if (!fs.existsSync(stateFile)) {
|
||||
return null
|
||||
}
|
||||
|
||||
const state = JSON.parse(Read(stateFile))
|
||||
return state
|
||||
}
|
||||
```
|
||||
|
||||
### 更新状态
|
||||
|
||||
```javascript
|
||||
/**
|
||||
* 更新循环状态 (只更新 skill_state 部分,不修改 API 字段)
|
||||
* @param loopId - Loop ID
|
||||
* @param updates - 更新内容 (skill_state 字段)
|
||||
*/
|
||||
function updateLoopState(loopId, updates) {
|
||||
const stateFile = `.loop/${loopId}.json`
|
||||
const currentState = readLoopState(loopId)
|
||||
|
||||
if (!currentState) {
|
||||
throw new Error(`Loop state not found: ${loopId}`)
|
||||
}
|
||||
|
||||
// 只更新 skill_state 和 updated_at
|
||||
const newState = {
|
||||
...currentState,
|
||||
updated_at: getUtc8ISOString(),
|
||||
skill_state: {
|
||||
...currentState.skill_state,
|
||||
...updates
|
||||
}
|
||||
}
|
||||
|
||||
Write(stateFile, JSON.stringify(newState, null, 2))
|
||||
return newState
|
||||
}
|
||||
```
|
||||
|
||||
### 创建新循环状态 (直接调用时)
|
||||
|
||||
```javascript
|
||||
/**
|
||||
* 创建新的循环状态 (仅在直接调用时使用,API 触发时状态已存在)
|
||||
*/
|
||||
function createLoopState(loopId, taskDescription) {
|
||||
const stateFile = `.loop/${loopId}.json`
|
||||
const now = getUtc8ISOString()
|
||||
|
||||
const state = {
|
||||
// API 兼容字段
|
||||
loop_id: loopId,
|
||||
title: taskDescription.substring(0, 100),
|
||||
description: taskDescription,
|
||||
max_iterations: 10,
|
||||
status: 'running', // 直接调用时设为 running
|
||||
current_iteration: 0,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
|
||||
// Skill 扩展字段
|
||||
skill_state: null // 由 action-init 初始化
|
||||
}
|
||||
|
||||
// 确保目录存在
|
||||
Bash(`mkdir -p ".loop"`)
|
||||
Bash(`mkdir -p ".loop/${loopId}.progress"`)
|
||||
|
||||
Write(stateFile, JSON.stringify(state, null, 2))
|
||||
return state
|
||||
}
|
||||
```
|
||||
|
||||
## Control Signal Checking
|
||||
|
||||
```javascript
|
||||
/**
|
||||
* 检查 API 控制信号
|
||||
* 必须在每个 Action 开始前调用
|
||||
* @returns { continue: boolean, reason: string }
|
||||
*/
|
||||
function checkControlSignals(loopId) {
|
||||
const state = readLoopState(loopId)
|
||||
|
||||
if (!state) {
|
||||
return { continue: false, reason: 'state_not_found' }
|
||||
}
|
||||
|
||||
switch (state.status) {
|
||||
case 'paused':
|
||||
// API 暂停了循环,Skill 应退出等待 resume
|
||||
console.log(`⏸️ Loop paused by API. Waiting for resume...`)
|
||||
return { continue: false, reason: 'paused' }
|
||||
|
||||
case 'failed':
|
||||
// API 停止了循环 (用户手动停止)
|
||||
console.log(`⏹️ Loop stopped by API.`)
|
||||
return { continue: false, reason: 'stopped' }
|
||||
|
||||
case 'completed':
|
||||
// 已完成
|
||||
console.log(`✅ Loop already completed.`)
|
||||
return { continue: false, reason: 'completed' }
|
||||
|
||||
case 'created':
|
||||
// API 创建但未启动 (不应该走到这里)
|
||||
console.log(`⚠️ Loop not started by API.`)
|
||||
return { continue: false, reason: 'not_started' }
|
||||
|
||||
case 'running':
|
||||
// 正常继续
|
||||
return { continue: true, reason: 'running' }
|
||||
|
||||
default:
|
||||
console.log(`⚠️ Unknown status: ${state.status}`)
|
||||
return { continue: false, reason: 'unknown_status' }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Decision Logic
|
||||
|
||||
```javascript
|
||||
/**
|
||||
* 选择下一个 Action (基于 skill_state)
|
||||
*/
|
||||
function selectNextAction(state, mode = 'interactive') {
|
||||
const skillState = state.skill_state
|
||||
|
||||
// 1. 终止条件检查 (API status)
|
||||
if (state.status === 'completed') return null
|
||||
if (state.status === 'failed') return null
|
||||
if (state.current_iteration >= state.max_iterations) {
|
||||
console.warn(`已达到最大迭代次数 (${state.max_iterations})`)
|
||||
return 'action-complete'
|
||||
}
|
||||
|
||||
// 2. 初始化检查
|
||||
if (!skillState || !skillState.current_action) {
|
||||
return 'action-init'
|
||||
}
|
||||
|
||||
// 3. 模式判断
|
||||
if (mode === 'interactive') {
|
||||
return 'action-menu' // 显示菜单让用户选择
|
||||
}
|
||||
|
||||
// 4. 自动模式:基于状态自动选择
|
||||
if (mode === 'auto') {
|
||||
// 按优先级:develop → debug → validate
|
||||
|
||||
// 如果有待开发任务
|
||||
const hasPendingDevelop = skillState.develop?.tasks?.some(t => t.status === 'pending')
|
||||
if (hasPendingDevelop) {
|
||||
return 'action-develop-with-file'
|
||||
}
|
||||
|
||||
// 如果开发完成但未调试
|
||||
if (skillState.last_action === 'action-develop-with-file') {
|
||||
const needsDebug = skillState.develop?.completed < skillState.develop?.total
|
||||
if (needsDebug) {
|
||||
return 'action-debug-with-file'
|
||||
}
|
||||
}
|
||||
|
||||
// 如果调试完成但未验证
|
||||
if (skillState.last_action === 'action-debug-with-file' ||
|
||||
skillState.debug?.confirmed_hypothesis) {
|
||||
return 'action-validate-with-file'
|
||||
}
|
||||
|
||||
// 如果验证失败,回到开发
|
||||
if (skillState.last_action === 'action-validate-with-file') {
|
||||
if (!skillState.validate?.passed) {
|
||||
return 'action-develop-with-file'
|
||||
}
|
||||
}
|
||||
|
||||
// 全部通过,完成
|
||||
if (skillState.validate?.passed && !hasPendingDevelop) {
|
||||
return 'action-complete'
|
||||
}
|
||||
|
||||
// 默认:开发
|
||||
return 'action-develop-with-file'
|
||||
}
|
||||
|
||||
// 5. 默认完成
|
||||
return 'action-complete'
|
||||
}
|
||||
```
|
||||
|
||||
## Execution Loop
|
||||
|
||||
```javascript
|
||||
/**
|
||||
* 运行编排器
|
||||
* @param options.loopId - 现有 Loop ID (API 触发时)
|
||||
* @param options.task - 任务描述 (直接调用时)
|
||||
* @param options.mode - 'interactive' | 'auto'
|
||||
*/
|
||||
async function runOrchestrator(options = {}) {
|
||||
const { loopId: existingLoopId, task, mode = 'interactive' } = options
|
||||
|
||||
console.log('=== CCW Loop Orchestrator Started ===')
|
||||
|
||||
// 1. 确定 loopId
|
||||
let loopId
|
||||
let state
|
||||
|
||||
if (existingLoopId) {
|
||||
// API 触发:使用现有 loopId
|
||||
loopId = existingLoopId
|
||||
state = readLoopState(loopId)
|
||||
|
||||
if (!state) {
|
||||
console.error(`Loop not found: ${loopId}`)
|
||||
return { status: 'error', message: 'Loop not found' }
|
||||
}
|
||||
|
||||
console.log(`Resuming loop: ${loopId}`)
|
||||
console.log(`Status: ${state.status}`)
|
||||
|
||||
} else if (task) {
|
||||
// 直接调用:创建新 loopId
|
||||
const timestamp = getUtc8ISOString().replace(/[-:]/g, '').split('.')[0]
|
||||
const random = Math.random().toString(36).substring(2, 10)
|
||||
loopId = `loop-v2-${timestamp}-${random}`
|
||||
|
||||
console.log(`Creating new loop: ${loopId}`)
|
||||
console.log(`Task: ${task}`)
|
||||
|
||||
state = createLoopState(loopId, task)
|
||||
|
||||
} else {
|
||||
console.error('Either --loop-id or task description is required')
|
||||
return { status: 'error', message: 'Missing loopId or task' }
|
||||
}
|
||||
|
||||
const progressDir = `.loop/${loopId}.progress`
|
||||
|
||||
// 2. 主循环
|
||||
let iteration = state.current_iteration || 0
|
||||
|
||||
while (iteration < state.max_iterations) {
|
||||
iteration++
|
||||
|
||||
// ========================================
|
||||
// CRITICAL: Check control signals first
|
||||
// ========================================
|
||||
const control = checkControlSignals(loopId)
|
||||
if (!control.continue) {
|
||||
console.log(`\n🛑 Loop terminated: ${control.reason}`)
|
||||
break
|
||||
}
|
||||
|
||||
// 重新读取状态 (可能被 API 更新)
|
||||
state = readLoopState(loopId)
|
||||
|
||||
console.log(`\n[Iteration ${iteration}] Status: ${state.status}`)
|
||||
|
||||
// 选择下一个动作
|
||||
const actionId = selectNextAction(state, mode)
|
||||
|
||||
if (!actionId) {
|
||||
console.log('No action selected, terminating.')
|
||||
break
|
||||
}
|
||||
|
||||
console.log(`[Iteration ${iteration}] Executing: ${actionId}`)
|
||||
|
||||
// 更新 current_iteration
|
||||
state = {
|
||||
...state,
|
||||
current_iteration: iteration,
|
||||
updated_at: getUtc8ISOString()
|
||||
}
|
||||
Write(`.loop/${loopId}.json`, JSON.stringify(state, null, 2))
|
||||
|
||||
// 执行动作
|
||||
try {
|
||||
const actionPromptFile = `.claude/skills/ccw-loop/phases/actions/${actionId}.md`
|
||||
|
||||
if (!fs.existsSync(actionPromptFile)) {
|
||||
console.error(`Action file not found: ${actionPromptFile}`)
|
||||
continue
|
||||
}
|
||||
|
||||
const actionPrompt = Read(actionPromptFile)
|
||||
|
||||
// 构建 Agent 提示
|
||||
const agentPrompt = `
|
||||
[LOOP CONTEXT]
|
||||
Loop ID: ${loopId}
|
||||
State File: .loop/${loopId}.json
|
||||
Progress Dir: ${progressDir}
|
||||
|
||||
[CURRENT STATE]
|
||||
${JSON.stringify(state, null, 2)}
|
||||
|
||||
[ACTION INSTRUCTIONS]
|
||||
${actionPrompt}
|
||||
|
||||
[TASK]
|
||||
You are executing ${actionId} for loop: ${state.title || state.description}
|
||||
|
||||
[CONTROL SIGNALS]
|
||||
Before executing, check if status is still 'running'.
|
||||
If status is 'paused' or 'failed', exit gracefully.
|
||||
|
||||
[RETURN]
|
||||
Return JSON with:
|
||||
- skillStateUpdates: Object with skill_state fields to update
|
||||
- continue: Boolean indicating if loop should continue
|
||||
- message: String with user message
|
||||
`
|
||||
|
||||
const result = await Task({
|
||||
subagent_type: 'universal-executor',
|
||||
run_in_background: false,
|
||||
description: `Execute ${actionId}`,
|
||||
prompt: agentPrompt
|
||||
})
|
||||
|
||||
// 解析结果
|
||||
const actionResult = JSON.parse(result)
|
||||
|
||||
// 更新状态 (只更新 skill_state)
|
||||
updateLoopState(loopId, {
|
||||
current_action: null,
|
||||
last_action: actionId,
|
||||
completed_actions: [
|
||||
...(state.skill_state?.completed_actions || []),
|
||||
actionId
|
||||
],
|
||||
...actionResult.skillStateUpdates
|
||||
})
|
||||
|
||||
// 显示消息
|
||||
if (actionResult.message) {
|
||||
console.log(`\n${actionResult.message}`)
|
||||
}
|
||||
|
||||
// 检查是否继续
|
||||
if (actionResult.continue === false) {
|
||||
console.log('Action requested termination.')
|
||||
break
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error(`Error executing ${actionId}: ${error.message}`)
|
||||
|
||||
// 错误处理
|
||||
updateLoopState(loopId, {
|
||||
current_action: null,
|
||||
errors: [
|
||||
...(state.skill_state?.errors || []),
|
||||
{
|
||||
action: actionId,
|
||||
message: error.message,
|
||||
timestamp: getUtc8ISOString()
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (iteration >= state.max_iterations) {
|
||||
console.log(`\n⚠️ Reached maximum iterations (${state.max_iterations})`)
|
||||
console.log('Consider breaking down the task or taking a break.')
|
||||
}
|
||||
|
||||
console.log('\n=== CCW Loop Orchestrator Finished ===')
|
||||
|
||||
// 返回最终状态
|
||||
const finalState = readLoopState(loopId)
|
||||
return {
|
||||
status: finalState.status,
|
||||
loop_id: loopId,
|
||||
iterations: iteration,
|
||||
final_state: finalState
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Action Catalog
|
||||
|
||||
| Action | Purpose | Preconditions | Effects |
|
||||
|--------|---------|---------------|---------|
|
||||
| [action-init](actions/action-init.md) | 初始化会话 | status=pending | initialized=true |
|
||||
| [action-menu](actions/action-menu.md) | 显示操作菜单 | initialized=true | 用户选择下一动作 |
|
||||
| [action-develop-with-file](actions/action-develop-with-file.md) | 开发任务 | initialized=true | 更新 progress.md |
|
||||
| [action-debug-with-file](actions/action-debug-with-file.md) | 假设调试 | initialized=true | 更新 understanding.md |
|
||||
| [action-validate-with-file](actions/action-validate-with-file.md) | 测试验证 | initialized=true | 更新 validation.md |
|
||||
| [action-complete](actions/action-complete.md) | 完成循环 | validation_passed=true | status=completed |
|
||||
|
||||
## Termination Conditions
|
||||
|
||||
1. **API 暂停**: `state.status === 'paused'` (Skill 退出,等待 resume)
|
||||
2. **API 停止**: `state.status === 'failed'` (Skill 终止)
|
||||
3. **任务完成**: `state.status === 'completed'`
|
||||
4. **迭代限制**: `state.current_iteration >= state.max_iterations`
|
||||
5. **Action 请求终止**: `actionResult.continue === false`
|
||||
|
||||
## Error Recovery
|
||||
|
||||
| Error Type | Recovery Strategy |
|
||||
|------------|-------------------|
|
||||
| 动作执行失败 | 记录错误,增加 error_count,继续下一动作 |
|
||||
| 状态文件损坏 | 从其他文件重建状态 (progress.md, understanding.md 等) |
|
||||
| 用户中止 | 保存当前状态,允许 --resume 恢复 |
|
||||
| CLI 工具失败 | 回退到手动分析模式 |
|
||||
|
||||
## Mode Strategies
|
||||
|
||||
### Interactive Mode (默认)
|
||||
|
||||
每次显示菜单,让用户选择动作:
|
||||
|
||||
```
|
||||
当前状态: 开发中
|
||||
可用操作:
|
||||
1. 继续开发 (develop)
|
||||
2. 开始调试 (debug)
|
||||
3. 运行验证 (validate)
|
||||
4. 查看进度 (status)
|
||||
5. 退出 (exit)
|
||||
|
||||
请选择:
|
||||
```
|
||||
|
||||
### Auto Mode (自动循环)
|
||||
|
||||
按预设流程自动执行:
|
||||
|
||||
```
|
||||
Develop → Debug → Validate →
|
||||
↓ (如验证失败)
|
||||
Develop (修复) → Debug → Validate → 完成
|
||||
```
|
||||
|
||||
## State Machine (API Status)
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> created: API creates loop
|
||||
created --> running: API /start → Trigger Skill
|
||||
running --> paused: API /pause → Set status
|
||||
running --> completed: action-complete
|
||||
running --> failed: API /stop OR error
|
||||
paused --> running: API /resume → Re-trigger Skill
|
||||
completed --> [*]
|
||||
failed --> [*]
|
||||
|
||||
note right of paused
|
||||
Skill checks status before each action
|
||||
If paused, Skill exits gracefully
|
||||
end note
|
||||
|
||||
note right of running
|
||||
Skill executes: init → develop → debug → validate
|
||||
end note
|
||||
```
|
||||
474
.claude/skills/ccw-loop/phases/state-schema.md
Normal file
474
.claude/skills/ccw-loop/phases/state-schema.md
Normal file
@@ -0,0 +1,474 @@
|
||||
# State Schema
|
||||
|
||||
CCW Loop 的状态结构定义(统一版本)。
|
||||
|
||||
## 状态文件
|
||||
|
||||
**位置**: `.loop/{loopId}.json` (统一位置,API + Skill 共享)
|
||||
|
||||
**旧版本位置** (仅向后兼容): `.workflow/.loop/{session-id}/state.json`
|
||||
|
||||
## 结构定义
|
||||
|
||||
### 统一状态接口 (Unified Loop State)
|
||||
|
||||
```typescript
|
||||
/**
|
||||
* Unified Loop State - API 和 Skill 共享的状态结构
|
||||
* API (loop-v2-routes.ts) 拥有状态的主控权
|
||||
* Skill (ccw-loop) 读取和更新此状态
|
||||
*/
|
||||
interface LoopState {
|
||||
// =====================================================
|
||||
// API FIELDS (from loop-v2-routes.ts)
|
||||
// 这些字段由 API 管理,Skill 只读
|
||||
// =====================================================
|
||||
|
||||
loop_id: string // Loop ID, e.g., "loop-v2-20260122-abc123"
|
||||
title: string // Loop 标题
|
||||
description: string // Loop 描述
|
||||
max_iterations: number // 最大迭代次数
|
||||
status: 'created' | 'running' | 'paused' | 'completed' | 'failed'
|
||||
current_iteration: number // 当前迭代次数
|
||||
created_at: string // 创建时间 (ISO8601)
|
||||
updated_at: string // 最后更新时间 (ISO8601)
|
||||
completed_at?: string // 完成时间 (ISO8601)
|
||||
failure_reason?: string // 失败原因
|
||||
|
||||
// =====================================================
|
||||
// SKILL EXTENSION FIELDS
|
||||
// 这些字段由 Skill 管理,API 只读
|
||||
// =====================================================
|
||||
|
||||
skill_state?: {
|
||||
// 当前执行动作
|
||||
current_action: 'init' | 'develop' | 'debug' | 'validate' | 'complete' | null
|
||||
last_action: string | null
|
||||
completed_actions: string[]
|
||||
mode: 'interactive' | 'auto'
|
||||
|
||||
// === 开发阶段 ===
|
||||
develop: {
|
||||
total: number
|
||||
completed: number
|
||||
current_task?: string
|
||||
tasks: DevelopTask[]
|
||||
last_progress_at: string | null
|
||||
}
|
||||
|
||||
// === 调试阶段 ===
|
||||
debug: {
|
||||
active_bug?: string
|
||||
hypotheses_count: number
|
||||
hypotheses: Hypothesis[]
|
||||
confirmed_hypothesis: string | null
|
||||
iteration: number
|
||||
last_analysis_at: string | null
|
||||
}
|
||||
|
||||
// === 验证阶段 ===
|
||||
validate: {
|
||||
pass_rate: number // 测试通过率 (0-100)
|
||||
coverage: number // 覆盖率 (0-100)
|
||||
test_results: TestResult[]
|
||||
passed: boolean
|
||||
failed_tests: string[]
|
||||
last_run_at: string | null
|
||||
}
|
||||
|
||||
// === 错误追踪 ===
|
||||
errors: Array<{
|
||||
action: string
|
||||
message: string
|
||||
timestamp: string
|
||||
}>
|
||||
}
|
||||
}
|
||||
|
||||
interface DevelopTask {
|
||||
id: string
|
||||
description: string
|
||||
tool: 'gemini' | 'qwen' | 'codex' | 'bash'
|
||||
mode: 'analysis' | 'write'
|
||||
status: 'pending' | 'in_progress' | 'completed' | 'failed'
|
||||
files_changed: string[]
|
||||
created_at: string
|
||||
completed_at: string | null
|
||||
}
|
||||
|
||||
interface Hypothesis {
|
||||
id: string // H1, H2, ...
|
||||
description: string
|
||||
testable_condition: string
|
||||
logging_point: string
|
||||
evidence_criteria: {
|
||||
confirm: string
|
||||
reject: string
|
||||
}
|
||||
likelihood: number // 1 = 最可能
|
||||
status: 'pending' | 'confirmed' | 'rejected' | 'inconclusive'
|
||||
evidence: Record<string, any> | null
|
||||
verdict_reason: string | null
|
||||
}
|
||||
|
||||
interface TestResult {
|
||||
test_name: string
|
||||
suite: string
|
||||
status: 'passed' | 'failed' | 'skipped'
|
||||
duration_ms: number
|
||||
error_message: string | null
|
||||
stack_trace: string | null
|
||||
}
|
||||
```
|
||||
|
||||
## 初始状态
|
||||
|
||||
### 由 API 创建时 (Dashboard 触发)
|
||||
|
||||
```json
|
||||
{
|
||||
"loop_id": "loop-v2-20260122-abc123",
|
||||
"title": "Implement user authentication",
|
||||
"description": "Add login/logout functionality",
|
||||
"max_iterations": 10,
|
||||
"status": "created",
|
||||
"current_iteration": 0,
|
||||
"created_at": "2026-01-22T10:00:00+08:00",
|
||||
"updated_at": "2026-01-22T10:00:00+08:00"
|
||||
}
|
||||
```
|
||||
|
||||
### 由 Skill 初始化后 (action-init)
|
||||
|
||||
```json
|
||||
{
|
||||
"loop_id": "loop-v2-20260122-abc123",
|
||||
"title": "Implement user authentication",
|
||||
"description": "Add login/logout functionality",
|
||||
"max_iterations": 10,
|
||||
"status": "running",
|
||||
"current_iteration": 0,
|
||||
"created_at": "2026-01-22T10:00:00+08:00",
|
||||
"updated_at": "2026-01-22T10:00:05+08:00",
|
||||
|
||||
"skill_state": {
|
||||
"current_action": "init",
|
||||
"last_action": null,
|
||||
"completed_actions": [],
|
||||
"mode": "auto",
|
||||
|
||||
"develop": {
|
||||
"total": 3,
|
||||
"completed": 0,
|
||||
"current_task": null,
|
||||
"tasks": [
|
||||
{ "id": "task-001", "description": "Create auth component", "status": "pending" }
|
||||
],
|
||||
"last_progress_at": null
|
||||
},
|
||||
|
||||
"debug": {
|
||||
"active_bug": null,
|
||||
"hypotheses_count": 0,
|
||||
"hypotheses": [],
|
||||
"confirmed_hypothesis": null,
|
||||
"iteration": 0,
|
||||
"last_analysis_at": null
|
||||
},
|
||||
|
||||
"validate": {
|
||||
"pass_rate": 0,
|
||||
"coverage": 0,
|
||||
"test_results": [],
|
||||
"passed": false,
|
||||
"failed_tests": [],
|
||||
"last_run_at": null
|
||||
},
|
||||
|
||||
"errors": []
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 控制信号检查 (Control Signals)
|
||||
|
||||
Skill 在每个 Action 开始前必须检查控制信号:
|
||||
|
||||
```javascript
|
||||
/**
|
||||
* 检查 API 控制信号
|
||||
* @returns { continue: boolean, action: 'pause_exit' | 'stop_exit' | 'continue' }
|
||||
*/
|
||||
function checkControlSignals(loopId) {
|
||||
const state = JSON.parse(Read(`.loop/${loopId}.json`))
|
||||
|
||||
switch (state.status) {
|
||||
case 'paused':
|
||||
// API 暂停了循环,Skill 应退出等待 resume
|
||||
return { continue: false, action: 'pause_exit' }
|
||||
|
||||
case 'failed':
|
||||
// API 停止了循环 (用户手动停止)
|
||||
return { continue: false, action: 'stop_exit' }
|
||||
|
||||
case 'running':
|
||||
// 正常继续
|
||||
return { continue: true, action: 'continue' }
|
||||
|
||||
default:
|
||||
// 异常状态
|
||||
return { continue: false, action: 'stop_exit' }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 在 Action 中使用
|
||||
|
||||
```markdown
|
||||
## Execution
|
||||
|
||||
### Step 1: Check Control Signals
|
||||
|
||||
\`\`\`javascript
|
||||
const control = checkControlSignals(loopId)
|
||||
if (!control.continue) {
|
||||
// 输出退出原因
|
||||
console.log(`Loop ${control.action}: status = ${state.status}`)
|
||||
|
||||
// 如果是 pause_exit,保存当前进度
|
||||
if (control.action === 'pause_exit') {
|
||||
updateSkillState(loopId, { current_action: 'paused' })
|
||||
}
|
||||
|
||||
return // 退出 Action
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
### Step 2: Execute Action Logic
|
||||
...
|
||||
```
|
||||
|
||||
## 状态转换规则
|
||||
|
||||
### 1. 初始化 (action-init)
|
||||
|
||||
```javascript
|
||||
// Skill 初始化后
|
||||
{
|
||||
// API 字段更新
|
||||
status: 'created' → 'running', // 或保持 'running' 如果 API 已设置
|
||||
updated_at: timestamp,
|
||||
|
||||
// Skill 字段初始化
|
||||
skill_state: {
|
||||
current_action: 'init',
|
||||
mode: 'auto',
|
||||
develop: {
|
||||
tasks: [...parsed_tasks],
|
||||
total: N,
|
||||
completed: 0
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 开发进行中 (action-develop-with-file)
|
||||
|
||||
```javascript
|
||||
// 开发任务执行后
|
||||
{
|
||||
updated_at: timestamp,
|
||||
current_iteration: state.current_iteration + 1,
|
||||
|
||||
skill_state: {
|
||||
current_action: 'develop',
|
||||
last_action: 'action-develop-with-file',
|
||||
completed_actions: [...state.skill_state.completed_actions, 'action-develop-with-file'],
|
||||
develop: {
|
||||
current_task: 'task-xxx',
|
||||
completed: N+1,
|
||||
last_progress_at: timestamp
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. 调试进行中 (action-debug-with-file)
|
||||
|
||||
```javascript
|
||||
// 调试执行后
|
||||
{
|
||||
updated_at: timestamp,
|
||||
current_iteration: state.current_iteration + 1,
|
||||
|
||||
skill_state: {
|
||||
current_action: 'debug',
|
||||
last_action: 'action-debug-with-file',
|
||||
debug: {
|
||||
active_bug: '...',
|
||||
hypotheses_count: N,
|
||||
hypotheses: [...new_hypotheses],
|
||||
iteration: N+1,
|
||||
last_analysis_at: timestamp
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4. 验证完成 (action-validate-with-file)
|
||||
|
||||
```javascript
|
||||
// 验证执行后
|
||||
{
|
||||
updated_at: timestamp,
|
||||
current_iteration: state.current_iteration + 1,
|
||||
|
||||
skill_state: {
|
||||
current_action: 'validate',
|
||||
last_action: 'action-validate-with-file',
|
||||
validate: {
|
||||
test_results: [...results],
|
||||
pass_rate: 95.5,
|
||||
coverage: 85.0,
|
||||
passed: true | false,
|
||||
failed_tests: ['test1', 'test2'],
|
||||
last_run_at: timestamp
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5. 完成 (action-complete)
|
||||
|
||||
```javascript
|
||||
// 循环完成后
|
||||
{
|
||||
status: 'running' → 'completed',
|
||||
completed_at: timestamp,
|
||||
updated_at: timestamp,
|
||||
|
||||
skill_state: {
|
||||
current_action: 'complete',
|
||||
last_action: 'action-complete'
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 状态派生字段
|
||||
|
||||
以下字段可从状态计算得出,不需要存储:
|
||||
|
||||
```javascript
|
||||
// 开发完成度
|
||||
const developProgress = state.develop.total_count > 0
|
||||
? (state.develop.completed_count / state.develop.total_count) * 100
|
||||
: 0
|
||||
|
||||
// 是否有待开发任务
|
||||
const hasPendingDevelop = state.develop.tasks.some(t => t.status === 'pending')
|
||||
|
||||
// 调试是否完成
|
||||
const debugCompleted = state.debug.confirmed_hypothesis !== null
|
||||
|
||||
// 验证是否通过
|
||||
const validationPassed = state.validate.passed && state.validate.test_results.length > 0
|
||||
|
||||
// 整体进度
|
||||
const overallProgress = (
|
||||
(developProgress * 0.5) +
|
||||
(debugCompleted ? 25 : 0) +
|
||||
(validationPassed ? 25 : 0)
|
||||
)
|
||||
```
|
||||
|
||||
## 文件同步
|
||||
|
||||
### 统一位置 (Unified Location)
|
||||
|
||||
状态与文件的对应关系:
|
||||
|
||||
| 状态字段 | 同步文件 | 同步时机 |
|
||||
|----------|----------|----------|
|
||||
| 整个 LoopState | `.loop/{loopId}.json` | 每次状态变更 (主文件) |
|
||||
| `skill_state.develop` | `.loop/{loopId}.progress/develop.md` | 每次开发操作后 |
|
||||
| `skill_state.debug` | `.loop/{loopId}.progress/debug.md` | 每次调试操作后 |
|
||||
| `skill_state.validate` | `.loop/{loopId}.progress/validate.md` | 每次验证操作后 |
|
||||
| 代码变更日志 | `.loop/{loopId}.progress/changes.log` | 每次文件修改 (NDJSON) |
|
||||
| 调试日志 | `.loop/{loopId}.progress/debug.log` | 每次调试日志 (NDJSON) |
|
||||
|
||||
### 文件结构示例
|
||||
|
||||
```
|
||||
.loop/
|
||||
├── loop-v2-20260122-abc123.json # 主状态文件 (API + Skill)
|
||||
├── loop-v2-20260122-abc123.tasks.jsonl # 任务列表 (API 管理)
|
||||
└── loop-v2-20260122-abc123.progress/ # Skill 进度文件
|
||||
├── develop.md # 开发进度
|
||||
├── debug.md # 调试理解
|
||||
├── validate.md # 验证报告
|
||||
├── changes.log # 代码变更 (NDJSON)
|
||||
└── debug.log # 调试日志 (NDJSON)
|
||||
```
|
||||
|
||||
## 状态恢复
|
||||
|
||||
如果主状态文件 `.loop/{loopId}.json` 损坏,可以从进度文件重建 skill_state:
|
||||
|
||||
```javascript
|
||||
function rebuildSkillStateFromProgress(loopId) {
|
||||
const progressDir = `.loop/${loopId}.progress`
|
||||
|
||||
// 尝试从进度文件解析状态
|
||||
const skill_state = {
|
||||
develop: parseProgressFile(`${progressDir}/develop.md`),
|
||||
debug: parseProgressFile(`${progressDir}/debug.md`),
|
||||
validate: parseProgressFile(`${progressDir}/validate.md`)
|
||||
}
|
||||
|
||||
return skill_state
|
||||
}
|
||||
|
||||
// 解析进度 Markdown 文件
|
||||
function parseProgressFile(filePath) {
|
||||
const content = Read(filePath)
|
||||
if (!content) return null
|
||||
|
||||
// 从 Markdown 表格和结构中提取数据
|
||||
// ... implementation
|
||||
}
|
||||
```
|
||||
|
||||
### 恢复策略
|
||||
|
||||
1. **API 字段**: 无法恢复 - 需要从 API 重新获取或用户手动输入
|
||||
2. **skill_state 字段**: 可以从 `.progress/` 目录的 Markdown 文件解析
|
||||
3. **任务列表**: 从 `.loop/{loopId}.tasks.jsonl` 恢复
|
||||
|
||||
## 状态验证
|
||||
|
||||
```javascript
|
||||
function validateState(state) {
|
||||
const errors = []
|
||||
|
||||
// 必需字段
|
||||
if (!state.session_id) errors.push('Missing session_id')
|
||||
if (!state.task_description) errors.push('Missing task_description')
|
||||
|
||||
// 状态一致性
|
||||
if (state.initialized && state.status === 'pending') {
|
||||
errors.push('Inconsistent: initialized but status is pending')
|
||||
}
|
||||
|
||||
if (state.status === 'completed' && !state.validate.passed) {
|
||||
errors.push('Inconsistent: completed but validation not passed')
|
||||
}
|
||||
|
||||
// 开发任务一致性
|
||||
const completedTasks = state.develop.tasks.filter(t => t.status === 'completed').length
|
||||
if (completedTasks !== state.develop.completed_count) {
|
||||
errors.push('Inconsistent: completed_count mismatch')
|
||||
}
|
||||
|
||||
return { valid: errors.length === 0, errors }
|
||||
}
|
||||
```
|
||||
300
.claude/skills/ccw-loop/specs/action-catalog.md
Normal file
300
.claude/skills/ccw-loop/specs/action-catalog.md
Normal file
@@ -0,0 +1,300 @@
|
||||
# Action Catalog
|
||||
|
||||
CCW Loop 所有可用动作的目录和说明。
|
||||
|
||||
## Available Actions
|
||||
|
||||
| Action | Purpose | Preconditions | Effects | CLI Integration |
|
||||
|--------|---------|---------------|---------|-----------------|
|
||||
| [action-init](../phases/actions/action-init.md) | 初始化会话 | status=pending, initialized=false | status→running, initialized→true, 创建目录和任务列表 | Gemini 任务分解 |
|
||||
| [action-menu](../phases/actions/action-menu.md) | 显示操作菜单 | initialized=true, status=running | 返回用户选择的动作 | - |
|
||||
| [action-develop-with-file](../phases/actions/action-develop-with-file.md) | 执行开发任务 | initialized=true, pending tasks > 0 | 更新 progress.md, 完成一个任务 | Gemini 代码实现 |
|
||||
| [action-debug-with-file](../phases/actions/action-debug-with-file.md) | 假设驱动调试 | initialized=true | 更新 understanding.md, hypotheses.json | Gemini 假设生成和证据分析 |
|
||||
| [action-validate-with-file](../phases/actions/action-validate-with-file.md) | 运行测试验证 | initialized=true, develop > 0 or debug confirmed | 更新 validation.md, test-results.json | Gemini 质量分析 |
|
||||
| [action-complete](../phases/actions/action-complete.md) | 完成循环 | initialized=true | status→completed, 生成 summary.md | - |
|
||||
|
||||
## Action Dependencies Graph
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
START([用户启动 /ccw-loop]) --> INIT[action-init]
|
||||
INIT --> MENU[action-menu]
|
||||
|
||||
MENU --> DEVELOP[action-develop-with-file]
|
||||
MENU --> DEBUG[action-debug-with-file]
|
||||
MENU --> VALIDATE[action-validate-with-file]
|
||||
MENU --> STATUS[action-status]
|
||||
MENU --> COMPLETE[action-complete]
|
||||
MENU --> EXIT([退出])
|
||||
|
||||
DEVELOP --> MENU
|
||||
DEBUG --> MENU
|
||||
VALIDATE --> MENU
|
||||
STATUS --> MENU
|
||||
COMPLETE --> END([结束])
|
||||
EXIT --> END
|
||||
|
||||
style INIT fill:#e1f5fe
|
||||
style MENU fill:#fff3e0
|
||||
style DEVELOP fill:#e8f5e9
|
||||
style DEBUG fill:#fce4ec
|
||||
style VALIDATE fill:#f3e5f5
|
||||
style COMPLETE fill:#c8e6c9
|
||||
```
|
||||
|
||||
## Action Execution Matrix
|
||||
|
||||
### Interactive Mode
|
||||
|
||||
| State | Auto-Selected Action | User Options |
|
||||
|-------|---------------------|--------------|
|
||||
| pending | action-init | - |
|
||||
| running, !initialized | action-init | - |
|
||||
| running, initialized | action-menu | All actions |
|
||||
|
||||
### Auto Mode
|
||||
|
||||
| Condition | Selected Action |
|
||||
|-----------|----------------|
|
||||
| pending_develop_tasks > 0 | action-develop-with-file |
|
||||
| last_action=develop, !debug_completed | action-debug-with-file |
|
||||
| last_action=debug, !validation_completed | action-validate-with-file |
|
||||
| validation_failed | action-develop-with-file (fix) |
|
||||
| validation_passed, no pending | action-complete |
|
||||
|
||||
## Action Inputs/Outputs
|
||||
|
||||
### action-init
|
||||
|
||||
**Inputs**:
|
||||
- state.task_description
|
||||
- User input (optional)
|
||||
|
||||
**Outputs**:
|
||||
- meta.json
|
||||
- state.json (初始化)
|
||||
- develop/tasks.json
|
||||
- develop/progress.md
|
||||
|
||||
**State Changes**:
|
||||
```javascript
|
||||
{
|
||||
status: 'pending' → 'running',
|
||||
initialized: false → true,
|
||||
develop.tasks: [] → [task1, task2, ...]
|
||||
}
|
||||
```
|
||||
|
||||
### action-develop-with-file
|
||||
|
||||
**Inputs**:
|
||||
- state.develop.tasks
|
||||
- User selection (如有多个待处理任务)
|
||||
|
||||
**Outputs**:
|
||||
- develop/progress.md (追加)
|
||||
- develop/tasks.json (更新)
|
||||
- develop/changes.log (追加)
|
||||
|
||||
**State Changes**:
|
||||
```javascript
|
||||
{
|
||||
develop.current_task_id: null → 'task-xxx' → null,
|
||||
develop.completed_count: N → N+1,
|
||||
last_action: X → 'action-develop-with-file'
|
||||
}
|
||||
```
|
||||
|
||||
### action-debug-with-file
|
||||
|
||||
**Inputs**:
|
||||
- Bug description (用户输入或从测试失败获取)
|
||||
- debug.log (如已有)
|
||||
|
||||
**Outputs**:
|
||||
- debug/understanding.md (追加)
|
||||
- debug/hypotheses.json (更新)
|
||||
- Code changes (添加日志或修复)
|
||||
|
||||
**State Changes**:
|
||||
```javascript
|
||||
{
|
||||
debug.current_bug: null → 'bug description',
|
||||
debug.hypotheses: [...updated],
|
||||
debug.iteration: N → N+1,
|
||||
debug.confirmed_hypothesis: null → 'H1' (如确认)
|
||||
}
|
||||
```
|
||||
|
||||
### action-validate-with-file
|
||||
|
||||
**Inputs**:
|
||||
- 测试脚本 (从 package.json)
|
||||
- 覆盖率工具 (可选)
|
||||
|
||||
**Outputs**:
|
||||
- validate/validation.md (追加)
|
||||
- validate/test-results.json (更新)
|
||||
- validate/coverage.json (更新)
|
||||
|
||||
**State Changes**:
|
||||
```javascript
|
||||
{
|
||||
validate.test_results: [...new results],
|
||||
validate.coverage: null → 85.5,
|
||||
validate.passed: false → true,
|
||||
validate.failed_tests: ['test1', 'test2'] → []
|
||||
}
|
||||
```
|
||||
|
||||
### action-complete
|
||||
|
||||
**Inputs**:
|
||||
- state (完整状态)
|
||||
- User choices (扩展选项)
|
||||
|
||||
**Outputs**:
|
||||
- summary.md
|
||||
- Issues (如选择扩展)
|
||||
|
||||
**State Changes**:
|
||||
```javascript
|
||||
{
|
||||
status: 'running' → 'completed',
|
||||
completed_at: null → timestamp
|
||||
}
|
||||
```
|
||||
|
||||
## Action Sequences
|
||||
|
||||
### Typical Happy Path
|
||||
|
||||
```
|
||||
action-init
|
||||
→ action-develop-with-file (task 1)
|
||||
→ action-develop-with-file (task 2)
|
||||
→ action-develop-with-file (task 3)
|
||||
→ action-validate-with-file
|
||||
→ PASS
|
||||
→ action-complete
|
||||
```
|
||||
|
||||
### Debug Iteration Path
|
||||
|
||||
```
|
||||
action-init
|
||||
→ action-develop-with-file (task 1)
|
||||
→ action-validate-with-file
|
||||
→ FAIL
|
||||
→ action-debug-with-file (探索)
|
||||
→ action-debug-with-file (分析)
|
||||
→ Root cause found
|
||||
→ action-validate-with-file
|
||||
→ PASS
|
||||
→ action-complete
|
||||
```
|
||||
|
||||
### Multi-Iteration Path
|
||||
|
||||
```
|
||||
action-init
|
||||
→ action-develop-with-file (task 1)
|
||||
→ action-debug-with-file
|
||||
→ action-develop-with-file (task 2)
|
||||
→ action-validate-with-file
|
||||
→ FAIL
|
||||
→ action-debug-with-file
|
||||
→ action-validate-with-file
|
||||
→ PASS
|
||||
→ action-complete
|
||||
```
|
||||
|
||||
## Error Scenarios
|
||||
|
||||
### CLI Tool Failure
|
||||
|
||||
```
|
||||
action-develop-with-file
|
||||
→ Gemini CLI fails
|
||||
→ Fallback to manual implementation
|
||||
→ Prompt user for code
|
||||
→ Continue
|
||||
```
|
||||
|
||||
### Test Failure
|
||||
|
||||
```
|
||||
action-validate-with-file
|
||||
→ Tests fail
|
||||
→ Record failed tests
|
||||
→ Suggest action-debug-with-file
|
||||
→ User chooses debug or manual fix
|
||||
```
|
||||
|
||||
### Max Iterations Reached
|
||||
|
||||
```
|
||||
state.iteration_count >= 10
|
||||
→ Warning message
|
||||
→ Suggest break or task split
|
||||
→ Allow continue or exit
|
||||
```
|
||||
|
||||
## Action Extensions
|
||||
|
||||
### Adding New Actions
|
||||
|
||||
To add a new action:
|
||||
|
||||
1. Create `phases/actions/action-{name}.md`
|
||||
2. Define preconditions, execution, state updates
|
||||
3. Add to this catalog
|
||||
4. Update orchestrator.md decision logic
|
||||
5. Add to action-menu.md options
|
||||
|
||||
### Action Template
|
||||
|
||||
```markdown
|
||||
# Action: {Name}
|
||||
|
||||
{Brief description}
|
||||
|
||||
## Purpose
|
||||
|
||||
{Detailed purpose}
|
||||
|
||||
## Preconditions
|
||||
|
||||
- [ ] condition1
|
||||
- [ ] condition2
|
||||
|
||||
## Execution
|
||||
|
||||
### Step 1: {Step Name}
|
||||
|
||||
\`\`\`javascript
|
||||
// code
|
||||
\`\`\`
|
||||
|
||||
## State Updates
|
||||
|
||||
\`\`\`javascript
|
||||
return {
|
||||
stateUpdates: {
|
||||
// updates
|
||||
},
|
||||
continue: true,
|
||||
message: "..."
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error Type | Recovery |
|
||||
|------------|----------|
|
||||
| ... | ... |
|
||||
|
||||
## Next Actions (Hints)
|
||||
|
||||
- condition: next_action
|
||||
```
|
||||
192
.claude/skills/ccw-loop/specs/loop-requirements.md
Normal file
192
.claude/skills/ccw-loop/specs/loop-requirements.md
Normal file
@@ -0,0 +1,192 @@
|
||||
# Loop Requirements Specification
|
||||
|
||||
CCW Loop 的核心需求和约束定义。
|
||||
|
||||
## Core Requirements
|
||||
|
||||
### 1. 无状态循环
|
||||
|
||||
**Requirement**: 每次执行从文件读取状态,执行后写回文件,不依赖内存状态。
|
||||
|
||||
**Rationale**: 支持随时中断和恢复,状态持久化。
|
||||
|
||||
**Validation**:
|
||||
- [ ] 每个 action 开始时从文件读取状态
|
||||
- [ ] 每个 action 结束时将状态写回文件
|
||||
- [ ] 无全局变量或内存状态依赖
|
||||
|
||||
### 2. 文件驱动进度
|
||||
|
||||
**Requirement**: 所有进度、理解、验证结果都记录在专用 Markdown 文件中。
|
||||
|
||||
**Rationale**: 可审计、可回顾、团队可见。
|
||||
|
||||
**Validation**:
|
||||
- [ ] develop/progress.md 记录开发进度
|
||||
- [ ] debug/understanding.md 记录理解演变
|
||||
- [ ] validate/validation.md 记录验证结果
|
||||
- [ ] 所有文件使用 Markdown 格式,易读
|
||||
|
||||
### 3. CLI 工具集成
|
||||
|
||||
**Requirement**: 关键决策点使用 Gemini/CLI 进行深度分析。
|
||||
|
||||
**Rationale**: 利用 LLM 能力提高质量。
|
||||
|
||||
**Validation**:
|
||||
- [ ] 任务分解使用 Gemini
|
||||
- [ ] 假设生成使用 Gemini
|
||||
- [ ] 证据分析使用 Gemini
|
||||
- [ ] 质量评估使用 Gemini
|
||||
|
||||
### 4. 用户控制循环
|
||||
|
||||
**Requirement**: 支持交互式和自动循环两种模式,用户可随时介入。
|
||||
|
||||
**Rationale**: 灵活性,适应不同场景。
|
||||
|
||||
**Validation**:
|
||||
- [ ] 交互模式:每步显示菜单
|
||||
- [ ] 自动模式:按预设流程执行
|
||||
- [ ] 用户可随时退出
|
||||
- [ ] 状态可恢复
|
||||
|
||||
### 5. 可恢复性
|
||||
|
||||
**Requirement**: 任何时候中断后,可以从上次位置继续。
|
||||
|
||||
**Rationale**: 长时间任务支持,意外中断恢复。
|
||||
|
||||
**Validation**:
|
||||
- [ ] 状态保存在 state.json
|
||||
- [ ] 使用 --resume 可继续
|
||||
- [ ] 历史记录完整保留
|
||||
|
||||
## Quality Standards
|
||||
|
||||
### Completeness
|
||||
|
||||
| Dimension | Threshold |
|
||||
|-----------|-----------|
|
||||
| 进度文档完整性 | 每个任务都有记录 |
|
||||
| 理解文档演变 | 每次迭代都有更新 |
|
||||
| 验证报告详尽 | 包含所有测试结果 |
|
||||
|
||||
### Consistency
|
||||
|
||||
| Dimension | Threshold |
|
||||
|-----------|-----------|
|
||||
| 文件格式一致 | 所有 Markdown 文件使用相同模板 |
|
||||
| 状态同步一致 | state.json 与文件内容匹配 |
|
||||
| 时间戳格式 | 统一使用 ISO8601 格式 |
|
||||
|
||||
### Usability
|
||||
|
||||
| Dimension | Threshold |
|
||||
|-----------|-----------|
|
||||
| 菜单易用性 | 选项清晰,描述准确 |
|
||||
| 进度可见性 | 随时可查看当前状态 |
|
||||
| 错误提示 | 错误消息清晰,提供恢复建议 |
|
||||
|
||||
## Constraints
|
||||
|
||||
### 1. 文件结构约束
|
||||
|
||||
```
|
||||
.workflow/.loop/{session-id}/
|
||||
├── meta.json # 只写一次,不再修改
|
||||
├── state.json # 每次 action 后更新
|
||||
├── develop/
|
||||
│ ├── progress.md # 只追加,不删除
|
||||
│ ├── tasks.json # 任务状态更新
|
||||
│ └── changes.log # NDJSON 格式,只追加
|
||||
├── debug/
|
||||
│ ├── understanding.md # 只追加,记录时间线
|
||||
│ ├── hypotheses.json # 更新假设状态
|
||||
│ └── debug.log # NDJSON 格式
|
||||
└── validate/
|
||||
├── validation.md # 每次验证追加
|
||||
├── test-results.json # 累积测试结果
|
||||
└── coverage.json # 最新覆盖率
|
||||
```
|
||||
|
||||
### 2. 命名约束
|
||||
|
||||
- Session ID: `LOOP-{slug}-{YYYY-MM-DD}`
|
||||
- Task ID: `task-{NNN}` (三位数字)
|
||||
- Hypothesis ID: `H{N}` (单字母+数字)
|
||||
|
||||
### 3. 状态转换约束
|
||||
|
||||
```
|
||||
pending → running → completed
|
||||
↓
|
||||
user_exit
|
||||
↓
|
||||
failed
|
||||
```
|
||||
|
||||
Only allow: `pending→running`, `running→completed/user_exit/failed`
|
||||
|
||||
### 4. 错误限制约束
|
||||
|
||||
- 最大错误次数: 3
|
||||
- 超过 3 次错误 → 自动终止
|
||||
- 每次错误 → 记录到 state.errors[]
|
||||
|
||||
### 5. 迭代限制约束
|
||||
|
||||
- 最大迭代次数: 10 (警告)
|
||||
- 超过 10 次 → 警告用户,但不强制停止
|
||||
- 建议拆分任务或休息
|
||||
|
||||
## Integration Requirements
|
||||
|
||||
### 1. Dashboard 集成
|
||||
|
||||
**Requirement**: 与 CCW Dashboard Loop Monitor 无缝集成。
|
||||
|
||||
**Specification**:
|
||||
- Dashboard 创建 Loop → 调用此 Skill
|
||||
- state.json → Dashboard 实时显示
|
||||
- 任务列表双向同步
|
||||
- 状态控制按钮映射到 actions
|
||||
|
||||
### 2. Issue 系统集成
|
||||
|
||||
**Requirement**: 完成后可扩展为 Issue。
|
||||
|
||||
**Specification**:
|
||||
- 支持维度: test, enhance, refactor, doc
|
||||
- 调用 `/issue:new "{summary} - {dimension}"`
|
||||
- 自动填充上下文
|
||||
|
||||
### 3. CLI 工具集成
|
||||
|
||||
**Requirement**: 使用 CCW CLI 工具进行分析和实现。
|
||||
|
||||
**Specification**:
|
||||
- 任务分解: `--rule planning-breakdown-task-steps`
|
||||
- 代码实现: `--rule development-implement-feature`
|
||||
- 根因分析: `--rule analysis-diagnose-bug-root-cause`
|
||||
- 质量评估: `--rule analysis-review-code-quality`
|
||||
|
||||
## Non-Functional Requirements
|
||||
|
||||
### Performance
|
||||
|
||||
- Session 初始化: < 5s
|
||||
- Action 执行: < 30s (不含 CLI 调用)
|
||||
- 状态读写: < 1s
|
||||
|
||||
### Reliability
|
||||
|
||||
- 状态文件损坏恢复: 支持从其他文件重建
|
||||
- CLI 工具失败降级: 回退到手动模式
|
||||
- 错误重试: 支持一次自动重试
|
||||
|
||||
### Maintainability
|
||||
|
||||
- 文档化: 所有 action 都有清晰说明
|
||||
- 模块化: 每个 action 独立可测
|
||||
- 可扩展: 易于添加新 action
|
||||
175
.claude/skills/ccw-loop/templates/progress-template.md
Normal file
175
.claude/skills/ccw-loop/templates/progress-template.md
Normal file
@@ -0,0 +1,175 @@
|
||||
# Progress Document Template
|
||||
|
||||
开发进度文档的标准模板。
|
||||
|
||||
## Template Structure
|
||||
|
||||
```markdown
|
||||
# Development Progress
|
||||
|
||||
**Session ID**: {{session_id}}
|
||||
**Task**: {{task_description}}
|
||||
**Started**: {{started_at}}
|
||||
**Estimated Complexity**: {{complexity}}
|
||||
|
||||
---
|
||||
|
||||
## Task List
|
||||
|
||||
{{#each tasks}}
|
||||
{{@index}}. [{{#if completed}}x{{else}} {{/if}}] {{description}}
|
||||
{{/each}}
|
||||
|
||||
## Key Files
|
||||
|
||||
{{#each key_files}}
|
||||
- `{{this}}`
|
||||
{{/each}}
|
||||
|
||||
---
|
||||
|
||||
## Progress Timeline
|
||||
|
||||
{{#each iterations}}
|
||||
### Iteration {{@index}} - {{task_name}} ({{timestamp}})
|
||||
|
||||
#### Task Details
|
||||
|
||||
- **ID**: {{task_id}}
|
||||
- **Tool**: {{tool}}
|
||||
- **Mode**: {{mode}}
|
||||
|
||||
#### Implementation Summary
|
||||
|
||||
{{summary}}
|
||||
|
||||
#### Files Changed
|
||||
|
||||
{{#each files_changed}}
|
||||
- `{{this}}`
|
||||
{{/each}}
|
||||
|
||||
#### Status: {{status}}
|
||||
|
||||
---
|
||||
{{/each}}
|
||||
|
||||
## Current Statistics
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Total Tasks | {{total_tasks}} |
|
||||
| Completed | {{completed_tasks}} |
|
||||
| In Progress | {{in_progress_tasks}} |
|
||||
| Pending | {{pending_tasks}} |
|
||||
| Progress | {{progress_percentage}}% |
|
||||
|
||||
---
|
||||
|
||||
## Next Steps
|
||||
|
||||
{{#each next_steps}}
|
||||
- [ ] {{this}}
|
||||
{{/each}}
|
||||
```
|
||||
|
||||
## Template Variables
|
||||
|
||||
| Variable | Type | Source | Description |
|
||||
|----------|------|--------|-------------|
|
||||
| `session_id` | string | state.session_id | 会话 ID |
|
||||
| `task_description` | string | state.task_description | 任务描述 |
|
||||
| `started_at` | string | state.created_at | 开始时间 |
|
||||
| `complexity` | string | state.context.estimated_complexity | 预估复杂度 |
|
||||
| `tasks` | array | state.develop.tasks | 任务列表 |
|
||||
| `key_files` | array | state.context.key_files | 关键文件 |
|
||||
| `iterations` | array | 从文件解析 | 迭代历史 |
|
||||
| `total_tasks` | number | state.develop.total_count | 总任务数 |
|
||||
| `completed_tasks` | number | state.develop.completed_count | 已完成数 |
|
||||
|
||||
## Usage Example
|
||||
|
||||
```javascript
|
||||
const progressTemplate = Read('.claude/skills/ccw-loop/templates/progress-template.md')
|
||||
|
||||
function renderProgress(state) {
|
||||
let content = progressTemplate
|
||||
|
||||
// 替换简单变量
|
||||
content = content.replace('{{session_id}}', state.session_id)
|
||||
content = content.replace('{{task_description}}', state.task_description)
|
||||
content = content.replace('{{started_at}}', state.created_at)
|
||||
content = content.replace('{{complexity}}', state.context?.estimated_complexity || 'unknown')
|
||||
|
||||
// 替换任务列表
|
||||
const taskList = state.develop.tasks.map((t, i) => {
|
||||
const checkbox = t.status === 'completed' ? 'x' : ' '
|
||||
return `${i + 1}. [${checkbox}] ${t.description}`
|
||||
}).join('\n')
|
||||
content = content.replace('{{#each tasks}}...{{/each}}', taskList)
|
||||
|
||||
// 替换统计
|
||||
content = content.replace('{{total_tasks}}', state.develop.total_count)
|
||||
content = content.replace('{{completed_tasks}}', state.develop.completed_count)
|
||||
// ...
|
||||
|
||||
return content
|
||||
}
|
||||
```
|
||||
|
||||
## Section Templates
|
||||
|
||||
### Task Entry
|
||||
|
||||
```markdown
|
||||
### Iteration {{N}} - {{task_name}} ({{timestamp}})
|
||||
|
||||
#### Task Details
|
||||
|
||||
- **ID**: {{task_id}}
|
||||
- **Tool**: {{tool}}
|
||||
- **Mode**: {{mode}}
|
||||
|
||||
#### Implementation Summary
|
||||
|
||||
{{summary}}
|
||||
|
||||
#### Files Changed
|
||||
|
||||
{{#each files}}
|
||||
- `{{this}}`
|
||||
{{/each}}
|
||||
|
||||
#### Status: COMPLETED
|
||||
|
||||
---
|
||||
```
|
||||
|
||||
### Statistics Table
|
||||
|
||||
```markdown
|
||||
## Current Statistics
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Total Tasks | {{total}} |
|
||||
| Completed | {{completed}} |
|
||||
| In Progress | {{in_progress}} |
|
||||
| Pending | {{pending}} |
|
||||
| Progress | {{percentage}}% |
|
||||
```
|
||||
|
||||
### Next Steps
|
||||
|
||||
```markdown
|
||||
## Next Steps
|
||||
|
||||
{{#if all_completed}}
|
||||
- [ ] Run validation tests
|
||||
- [ ] Code review
|
||||
- [ ] Update documentation
|
||||
{{else}}
|
||||
- [ ] Complete remaining {{pending}} tasks
|
||||
- [ ] Review completed work
|
||||
{{/if}}
|
||||
```
|
||||
303
.claude/skills/ccw-loop/templates/understanding-template.md
Normal file
303
.claude/skills/ccw-loop/templates/understanding-template.md
Normal file
@@ -0,0 +1,303 @@
|
||||
# Understanding Document Template
|
||||
|
||||
调试理解演变文档的标准模板。
|
||||
|
||||
## Template Structure
|
||||
|
||||
```markdown
|
||||
# Understanding Document
|
||||
|
||||
**Session ID**: {{session_id}}
|
||||
**Bug Description**: {{bug_description}}
|
||||
**Started**: {{started_at}}
|
||||
|
||||
---
|
||||
|
||||
## Exploration Timeline
|
||||
|
||||
{{#each iterations}}
|
||||
### Iteration {{number}} - {{title}} ({{timestamp}})
|
||||
|
||||
{{#if is_exploration}}
|
||||
#### Current Understanding
|
||||
|
||||
Based on bug description and initial code search:
|
||||
|
||||
- Error pattern: {{error_pattern}}
|
||||
- Affected areas: {{affected_areas}}
|
||||
- Initial hypothesis: {{initial_thoughts}}
|
||||
|
||||
#### Evidence from Code Search
|
||||
|
||||
{{#each search_results}}
|
||||
**Keyword: "{{keyword}}"**
|
||||
- Found in: {{files}}
|
||||
- Key findings: {{insights}}
|
||||
{{/each}}
|
||||
{{/if}}
|
||||
|
||||
{{#if has_hypotheses}}
|
||||
#### Hypotheses Generated (Gemini-Assisted)
|
||||
|
||||
{{#each hypotheses}}
|
||||
**{{id}}** (Likelihood: {{likelihood}}): {{description}}
|
||||
- Logging at: {{logging_point}}
|
||||
- Testing: {{testable_condition}}
|
||||
- Evidence to confirm: {{confirm_criteria}}
|
||||
- Evidence to reject: {{reject_criteria}}
|
||||
{{/each}}
|
||||
|
||||
**Gemini Insights**: {{gemini_insights}}
|
||||
{{/if}}
|
||||
|
||||
{{#if is_analysis}}
|
||||
#### Log Analysis Results
|
||||
|
||||
{{#each results}}
|
||||
**{{id}}**: {{verdict}}
|
||||
- Evidence: {{evidence}}
|
||||
- Reasoning: {{reason}}
|
||||
{{/each}}
|
||||
|
||||
#### Corrected Understanding
|
||||
|
||||
Previous misunderstandings identified and corrected:
|
||||
|
||||
{{#each corrections}}
|
||||
- ~~{{wrong}}~~ → {{corrected}}
|
||||
- Why wrong: {{reason}}
|
||||
- Evidence: {{evidence}}
|
||||
{{/each}}
|
||||
|
||||
#### New Insights
|
||||
|
||||
{{#each insights}}
|
||||
- {{this}}
|
||||
{{/each}}
|
||||
|
||||
#### Gemini Analysis
|
||||
|
||||
{{gemini_analysis}}
|
||||
{{/if}}
|
||||
|
||||
{{#if root_cause_found}}
|
||||
#### Root Cause Identified
|
||||
|
||||
**{{hypothesis_id}}**: {{description}}
|
||||
|
||||
Evidence supporting this conclusion:
|
||||
{{supporting_evidence}}
|
||||
{{else}}
|
||||
#### Next Steps
|
||||
|
||||
{{next_steps}}
|
||||
{{/if}}
|
||||
|
||||
---
|
||||
{{/each}}
|
||||
|
||||
## Current Consolidated Understanding
|
||||
|
||||
### What We Know
|
||||
|
||||
{{#each valid_understandings}}
|
||||
- {{this}}
|
||||
{{/each}}
|
||||
|
||||
### What Was Disproven
|
||||
|
||||
{{#each disproven}}
|
||||
- ~~{{assumption}}~~ (Evidence: {{evidence}})
|
||||
{{/each}}
|
||||
|
||||
### Current Investigation Focus
|
||||
|
||||
{{current_focus}}
|
||||
|
||||
### Remaining Questions
|
||||
|
||||
{{#each questions}}
|
||||
- {{this}}
|
||||
{{/each}}
|
||||
```
|
||||
|
||||
## Template Variables
|
||||
|
||||
| Variable | Type | Source | Description |
|
||||
|----------|------|--------|-------------|
|
||||
| `session_id` | string | state.session_id | 会话 ID |
|
||||
| `bug_description` | string | state.debug.current_bug | Bug 描述 |
|
||||
| `iterations` | array | 从文件解析 | 迭代历史 |
|
||||
| `hypotheses` | array | state.debug.hypotheses | 假设列表 |
|
||||
| `valid_understandings` | array | 从 Gemini 分析 | 有效理解 |
|
||||
| `disproven` | array | 从假设状态 | 被否定的假设 |
|
||||
|
||||
## Section Templates
|
||||
|
||||
### Exploration Section
|
||||
|
||||
```markdown
|
||||
### Iteration {{N}} - Initial Exploration ({{timestamp}})
|
||||
|
||||
#### Current Understanding
|
||||
|
||||
Based on bug description and initial code search:
|
||||
|
||||
- Error pattern: {{pattern}}
|
||||
- Affected areas: {{areas}}
|
||||
- Initial hypothesis: {{thoughts}}
|
||||
|
||||
#### Evidence from Code Search
|
||||
|
||||
{{#each search_results}}
|
||||
**Keyword: "{{keyword}}"**
|
||||
- Found in: {{files}}
|
||||
- Key findings: {{insights}}
|
||||
{{/each}}
|
||||
|
||||
#### Next Steps
|
||||
|
||||
- Generate testable hypotheses
|
||||
- Add instrumentation
|
||||
- Await reproduction
|
||||
```
|
||||
|
||||
### Hypothesis Section
|
||||
|
||||
```markdown
|
||||
#### Hypotheses Generated (Gemini-Assisted)
|
||||
|
||||
| ID | Description | Likelihood | Status |
|
||||
|----|-------------|------------|--------|
|
||||
{{#each hypotheses}}
|
||||
| {{id}} | {{description}} | {{likelihood}} | {{status}} |
|
||||
{{/each}}
|
||||
|
||||
**Details:**
|
||||
|
||||
{{#each hypotheses}}
|
||||
**{{id}}**: {{description}}
|
||||
- Logging at: `{{logging_point}}`
|
||||
- Testing: {{testable_condition}}
|
||||
- Confirm: {{evidence_criteria.confirm}}
|
||||
- Reject: {{evidence_criteria.reject}}
|
||||
{{/each}}
|
||||
```
|
||||
|
||||
### Analysis Section
|
||||
|
||||
```markdown
|
||||
### Iteration {{N}} - Evidence Analysis ({{timestamp}})
|
||||
|
||||
#### Log Analysis Results
|
||||
|
||||
{{#each results}}
|
||||
**{{id}}**: **{{verdict}}**
|
||||
- Evidence: \`{{evidence}}\`
|
||||
- Reasoning: {{reason}}
|
||||
{{/each}}
|
||||
|
||||
#### Corrected Understanding
|
||||
|
||||
| Previous Assumption | Corrected To | Reason |
|
||||
|---------------------|--------------|--------|
|
||||
{{#each corrections}}
|
||||
| ~~{{wrong}}~~ | {{corrected}} | {{reason}} |
|
||||
{{/each}}
|
||||
|
||||
#### Gemini Analysis
|
||||
|
||||
{{gemini_analysis}}
|
||||
```
|
||||
|
||||
### Consolidated Understanding Section
|
||||
|
||||
```markdown
|
||||
## Current Consolidated Understanding
|
||||
|
||||
### What We Know
|
||||
|
||||
{{#each valid}}
|
||||
- {{this}}
|
||||
{{/each}}
|
||||
|
||||
### What Was Disproven
|
||||
|
||||
{{#each disproven}}
|
||||
- ~~{{this.assumption}}~~ (Evidence: {{this.evidence}})
|
||||
{{/each}}
|
||||
|
||||
### Current Investigation Focus
|
||||
|
||||
{{focus}}
|
||||
|
||||
### Remaining Questions
|
||||
|
||||
{{#each questions}}
|
||||
- {{this}}
|
||||
{{/each}}
|
||||
```
|
||||
|
||||
### Resolution Section
|
||||
|
||||
```markdown
|
||||
### Resolution ({{timestamp}})
|
||||
|
||||
#### Fix Applied
|
||||
|
||||
- Modified files: {{files}}
|
||||
- Fix description: {{description}}
|
||||
- Root cause addressed: {{root_cause}}
|
||||
|
||||
#### Verification Results
|
||||
|
||||
{{verification}}
|
||||
|
||||
#### Lessons Learned
|
||||
|
||||
{{#each lessons}}
|
||||
{{@index}}. {{this}}
|
||||
{{/each}}
|
||||
|
||||
#### Key Insights for Future
|
||||
|
||||
{{#each insights}}
|
||||
- {{this}}
|
||||
{{/each}}
|
||||
```
|
||||
|
||||
## Consolidation Rules
|
||||
|
||||
更新 "Current Consolidated Understanding" 时遵循以下规则:
|
||||
|
||||
1. **简化被否定项**: 移到 "What Was Disproven",只保留单行摘要
|
||||
2. **保留有效见解**: 将确认的发现提升到 "What We Know"
|
||||
3. **避免重复**: 不在合并部分重复时间线细节
|
||||
4. **关注当前状态**: 描述现在知道什么,而不是过程
|
||||
5. **保留关键纠正**: 保留重要的 wrong→right 转换供学习
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
**错误示例 (冗余)**:
|
||||
```markdown
|
||||
## Current Consolidated Understanding
|
||||
|
||||
In iteration 1 we thought X, but in iteration 2 we found Y, then in iteration 3...
|
||||
Also we checked A and found B, and then we checked C...
|
||||
```
|
||||
|
||||
**正确示例 (精简)**:
|
||||
```markdown
|
||||
## Current Consolidated Understanding
|
||||
|
||||
### What We Know
|
||||
- Error occurs during runtime update, not initialization
|
||||
- Config value is None (not missing key)
|
||||
|
||||
### What Was Disproven
|
||||
- ~~Initialization error~~ (Timing evidence)
|
||||
- ~~Missing key hypothesis~~ (Key exists)
|
||||
|
||||
### Current Investigation Focus
|
||||
Why is config value None during update?
|
||||
```
|
||||
258
.claude/skills/ccw-loop/templates/validation-template.md
Normal file
258
.claude/skills/ccw-loop/templates/validation-template.md
Normal file
@@ -0,0 +1,258 @@
|
||||
# Validation Report Template
|
||||
|
||||
验证报告的标准模板。
|
||||
|
||||
## Template Structure
|
||||
|
||||
```markdown
|
||||
# Validation Report
|
||||
|
||||
**Session ID**: {{session_id}}
|
||||
**Task**: {{task_description}}
|
||||
**Validated**: {{timestamp}}
|
||||
|
||||
---
|
||||
|
||||
## Iteration {{iteration}} - Validation Run
|
||||
|
||||
### Test Execution Summary
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Total Tests | {{total_tests}} |
|
||||
| Passed | {{passed_tests}} |
|
||||
| Failed | {{failed_tests}} |
|
||||
| Skipped | {{skipped_tests}} |
|
||||
| Duration | {{duration}}ms |
|
||||
| **Pass Rate** | **{{pass_rate}}%** |
|
||||
|
||||
### Coverage Report
|
||||
|
||||
{{#if has_coverage}}
|
||||
| File | Statements | Branches | Functions | Lines |
|
||||
|------|------------|----------|-----------|-------|
|
||||
{{#each coverage_files}}
|
||||
| {{path}} | {{statements}}% | {{branches}}% | {{functions}}% | {{lines}}% |
|
||||
{{/each}}
|
||||
|
||||
**Overall Coverage**: {{overall_coverage}}%
|
||||
{{else}}
|
||||
_No coverage data available_
|
||||
{{/if}}
|
||||
|
||||
### Failed Tests
|
||||
|
||||
{{#if has_failures}}
|
||||
{{#each failures}}
|
||||
#### {{test_name}}
|
||||
|
||||
- **Suite**: {{suite}}
|
||||
- **Error**: {{error_message}}
|
||||
- **Stack**:
|
||||
\`\`\`
|
||||
{{stack_trace}}
|
||||
\`\`\`
|
||||
{{/each}}
|
||||
{{else}}
|
||||
_All tests passed_
|
||||
{{/if}}
|
||||
|
||||
### Gemini Quality Analysis
|
||||
|
||||
{{gemini_analysis}}
|
||||
|
||||
### Recommendations
|
||||
|
||||
{{#each recommendations}}
|
||||
- {{this}}
|
||||
{{/each}}
|
||||
|
||||
---
|
||||
|
||||
## Validation Decision
|
||||
|
||||
**Result**: {{#if passed}}✅ PASS{{else}}❌ FAIL{{/if}}
|
||||
|
||||
**Rationale**: {{rationale}}
|
||||
|
||||
{{#if not_passed}}
|
||||
### Next Actions
|
||||
|
||||
1. Review failed tests
|
||||
2. Debug failures using action-debug-with-file
|
||||
3. Fix issues and re-run validation
|
||||
{{else}}
|
||||
### Next Actions
|
||||
|
||||
1. Consider code review
|
||||
2. Prepare for deployment
|
||||
3. Update documentation
|
||||
{{/if}}
|
||||
```
|
||||
|
||||
## Template Variables
|
||||
|
||||
| Variable | Type | Source | Description |
|
||||
|----------|------|--------|-------------|
|
||||
| `session_id` | string | state.session_id | 会话 ID |
|
||||
| `task_description` | string | state.task_description | 任务描述 |
|
||||
| `timestamp` | string | 当前时间 | 验证时间 |
|
||||
| `iteration` | number | 从文件计算 | 验证迭代次数 |
|
||||
| `total_tests` | number | 测试输出 | 总测试数 |
|
||||
| `passed_tests` | number | 测试输出 | 通过数 |
|
||||
| `failed_tests` | number | 测试输出 | 失败数 |
|
||||
| `pass_rate` | number | 计算得出 | 通过率 |
|
||||
| `coverage_files` | array | 覆盖率报告 | 文件覆盖率 |
|
||||
| `failures` | array | 测试输出 | 失败测试详情 |
|
||||
| `gemini_analysis` | string | Gemini CLI | 质量分析 |
|
||||
| `recommendations` | array | Gemini CLI | 建议列表 |
|
||||
|
||||
## Section Templates
|
||||
|
||||
### Test Summary
|
||||
|
||||
```markdown
|
||||
### Test Execution Summary
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Total Tests | {{total}} |
|
||||
| Passed | {{passed}} |
|
||||
| Failed | {{failed}} |
|
||||
| Skipped | {{skipped}} |
|
||||
| Duration | {{duration}}ms |
|
||||
| **Pass Rate** | **{{rate}}%** |
|
||||
```
|
||||
|
||||
### Coverage Table
|
||||
|
||||
```markdown
|
||||
### Coverage Report
|
||||
|
||||
| File | Statements | Branches | Functions | Lines |
|
||||
|------|------------|----------|-----------|-------|
|
||||
{{#each files}}
|
||||
| `{{path}}` | {{statements}}% | {{branches}}% | {{functions}}% | {{lines}}% |
|
||||
{{/each}}
|
||||
|
||||
**Overall Coverage**: {{overall}}%
|
||||
|
||||
**Coverage Thresholds**:
|
||||
- ✅ Good: ≥ 80%
|
||||
- ⚠️ Warning: 60-79%
|
||||
- ❌ Poor: < 60%
|
||||
```
|
||||
|
||||
### Failed Test Details
|
||||
|
||||
```markdown
|
||||
### Failed Tests
|
||||
|
||||
{{#each failures}}
|
||||
#### ❌ {{test_name}}
|
||||
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Suite | {{suite}} |
|
||||
| Error | {{error_message}} |
|
||||
| Duration | {{duration}}ms |
|
||||
|
||||
**Stack Trace**:
|
||||
\`\`\`
|
||||
{{stack_trace}}
|
||||
\`\`\`
|
||||
|
||||
**Possible Causes**:
|
||||
{{#each possible_causes}}
|
||||
- {{this}}
|
||||
{{/each}}
|
||||
|
||||
---
|
||||
{{/each}}
|
||||
```
|
||||
|
||||
### Quality Analysis
|
||||
|
||||
```markdown
|
||||
### Gemini Quality Analysis
|
||||
|
||||
#### Code Quality Assessment
|
||||
|
||||
| Dimension | Score | Status |
|
||||
|-----------|-------|--------|
|
||||
| Correctness | {{correctness}}/10 | {{correctness_status}} |
|
||||
| Completeness | {{completeness}}/10 | {{completeness_status}} |
|
||||
| Reliability | {{reliability}}/10 | {{reliability_status}} |
|
||||
| Maintainability | {{maintainability}}/10 | {{maintainability_status}} |
|
||||
|
||||
#### Key Findings
|
||||
|
||||
{{#each findings}}
|
||||
- **{{severity}}**: {{description}}
|
||||
{{/each}}
|
||||
|
||||
#### Recommendations
|
||||
|
||||
{{#each recommendations}}
|
||||
{{@index}}. {{this}}
|
||||
{{/each}}
|
||||
```
|
||||
|
||||
### Decision Section
|
||||
|
||||
```markdown
|
||||
## Validation Decision
|
||||
|
||||
**Result**: {{#if passed}}✅ PASS{{else}}❌ FAIL{{/if}}
|
||||
|
||||
**Rationale**:
|
||||
{{rationale}}
|
||||
|
||||
**Confidence Level**: {{confidence}}
|
||||
|
||||
### Decision Matrix
|
||||
|
||||
| Criteria | Status | Weight | Score |
|
||||
|----------|--------|--------|-------|
|
||||
| All tests pass | {{tests_pass}} | 40% | {{tests_score}} |
|
||||
| Coverage ≥ 80% | {{coverage_pass}} | 30% | {{coverage_score}} |
|
||||
| No critical issues | {{no_critical}} | 20% | {{critical_score}} |
|
||||
| Quality analysis pass | {{quality_pass}} | 10% | {{quality_score}} |
|
||||
| **Total** | | 100% | **{{total_score}}** |
|
||||
|
||||
**Threshold**: 70% to pass
|
||||
|
||||
### Next Actions
|
||||
|
||||
{{#if passed}}
|
||||
1. ✅ Code review (recommended)
|
||||
2. ✅ Update documentation
|
||||
3. ✅ Prepare for deployment
|
||||
{{else}}
|
||||
1. ❌ Review failed tests
|
||||
2. ❌ Debug failures
|
||||
3. ❌ Fix issues and re-run
|
||||
{{/if}}
|
||||
```
|
||||
|
||||
## Historical Comparison
|
||||
|
||||
```markdown
|
||||
## Validation History
|
||||
|
||||
| Iteration | Date | Pass Rate | Coverage | Status |
|
||||
|-----------|------|-----------|----------|--------|
|
||||
{{#each history}}
|
||||
| {{iteration}} | {{date}} | {{pass_rate}}% | {{coverage}}% | {{status}} |
|
||||
{{/each}}
|
||||
|
||||
### Trend Analysis
|
||||
|
||||
{{#if improving}}
|
||||
📈 **Improving**: Pass rate increased from {{previous_rate}}% to {{current_rate}}%
|
||||
{{else if declining}}
|
||||
📉 **Declining**: Pass rate decreased from {{previous_rate}}% to {{current_rate}}%
|
||||
{{else}}
|
||||
➡️ **Stable**: Pass rate remains at {{current_rate}}%
|
||||
{{/if}}
|
||||
```
|
||||
@@ -8,6 +8,44 @@ allowed-tools: Task(*), SlashCommand(*), AskUserQuestion(*), Read(*), Bash(*), G
|
||||
|
||||
无状态工作流协调器,根据任务意图自动选择最优工作流。
|
||||
|
||||
## Workflow System Overview
|
||||
|
||||
CCW 提供两个工作流系统:**Main Workflow** 和 **Issue Workflow**,协同覆盖完整的软件开发生命周期。
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────────────────┐
|
||||
│ Main Workflow │
|
||||
│ │
|
||||
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
|
||||
│ │ Level 1 │ → │ Level 2 │ → │ Level 3 │ → │ Level 4 │ │
|
||||
│ │ Rapid │ │ Lightweight │ │ Standard │ │ Brainstorm │ │
|
||||
│ │ │ │ │ │ │ │ │ │
|
||||
│ │ lite-lite- │ │ lite-plan │ │ plan │ │ brainstorm │ │
|
||||
│ │ lite │ │ lite-fix │ │ tdd-plan │ │ :auto- │ │
|
||||
│ │ │ │ multi-cli- │ │ test-fix- │ │ parallel │ │
|
||||
│ │ │ │ plan │ │ gen │ │ ↓ │ │
|
||||
│ │ │ │ │ │ │ │ plan │ │
|
||||
│ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ │
|
||||
│ │
|
||||
│ Complexity: ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━▶ │
|
||||
│ Low High │
|
||||
└─────────────────────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
│ After development
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────────────────┐
|
||||
│ Issue Workflow │
|
||||
│ │
|
||||
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
|
||||
│ │ Accumulate │ → │ Plan │ → │ Execute │ │
|
||||
│ │ Discover & │ │ Batch │ │ Parallel │ │
|
||||
│ │ Collect │ │ Planning │ │ Execution │ │
|
||||
│ └──────────────┘ └──────────────┘ └──────────────┘ │
|
||||
│ │
|
||||
│ Supplementary role: Maintain main branch stability, worktree isolation │
|
||||
└─────────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
@@ -17,7 +55,7 @@ allowed-tools: Task(*), SlashCommand(*), AskUserQuestion(*), Read(*), Bash(*), G
|
||||
│ Phase 1 │ Input Analysis (rule-based, fast path) │
|
||||
│ Phase 1.5 │ CLI Classification (semantic, smart path) │
|
||||
│ Phase 1.75 │ Requirement Clarification (clarity < 2) │
|
||||
│ Phase 2 │ Chain Selection (intent → workflow) │
|
||||
│ Phase 2 │ Level Selection (intent → level → workflow) │
|
||||
│ Phase 2.5 │ CLI Action Planning (high complexity) │
|
||||
│ Phase 3 │ User Confirmation (optional) │
|
||||
│ Phase 4 │ TODO Tracking Setup │
|
||||
@@ -25,23 +63,79 @@ allowed-tools: Task(*), SlashCommand(*), AskUserQuestion(*), Read(*), Bash(*), G
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Level Quick Reference
|
||||
|
||||
| Level | Name | Workflows | Artifacts | Execution |
|
||||
|-------|------|-----------|-----------|-----------|
|
||||
| **1** | Rapid | `lite-lite-lite` | None | Direct execute |
|
||||
| **2** | Lightweight | `lite-plan`, `lite-fix`, `multi-cli-plan` | Memory/Lightweight files | → `lite-execute` |
|
||||
| **3** | Standard | `plan`, `tdd-plan`, `test-fix-gen` | Session persistence | → `execute` / `test-cycle-execute` |
|
||||
| **4** | Brainstorm | `brainstorm:auto-parallel` → `plan` | Multi-role analysis + Session | → `execute` |
|
||||
| **-** | Issue | `discover` → `plan` → `queue` → `execute` | Issue records | Worktree isolation (optional) |
|
||||
|
||||
## Workflow Selection Decision Tree
|
||||
|
||||
```
|
||||
Start
|
||||
│
|
||||
├─ Is it post-development maintenance?
|
||||
│ ├─ Yes → Issue Workflow
|
||||
│ └─ No ↓
|
||||
│
|
||||
├─ Are requirements clear?
|
||||
│ ├─ Uncertain → Level 4 (brainstorm:auto-parallel)
|
||||
│ └─ Clear ↓
|
||||
│
|
||||
├─ Need persistent Session?
|
||||
│ ├─ Yes → Level 3 (plan / tdd-plan / test-fix-gen)
|
||||
│ └─ No ↓
|
||||
│
|
||||
├─ Need multi-perspective / solution comparison?
|
||||
│ ├─ Yes → Level 2 (multi-cli-plan)
|
||||
│ └─ No ↓
|
||||
│
|
||||
├─ Is it a bug fix?
|
||||
│ ├─ Yes → Level 2 (lite-fix)
|
||||
│ └─ No ↓
|
||||
│
|
||||
├─ Need planning?
|
||||
│ ├─ Yes → Level 2 (lite-plan)
|
||||
│ └─ No → Level 1 (lite-lite-lite)
|
||||
```
|
||||
|
||||
## Intent Classification
|
||||
|
||||
### Priority Order
|
||||
### Priority Order (with Level Mapping)
|
||||
|
||||
| Priority | Intent | Patterns | Flow |
|
||||
|----------|--------|----------|------|
|
||||
| 1 | bugfix/hotfix | `urgent,production,critical` + bug | `bugfix.hotfix` |
|
||||
| 1 | bugfix | `fix,bug,error,crash,fail` | `bugfix.standard` |
|
||||
| 2 | issue batch | `issues,batch` + `fix,resolve` | `issue` |
|
||||
| 3 | exploration | `不确定,explore,研究,what if` | `full` |
|
||||
| 3 | multi-perspective | `多视角,权衡,比较方案,cross-verify` | `multi-cli-plan` |
|
||||
| 4 | quick-task | `快速,简单,small,quick` + feature | `lite-lite-lite` |
|
||||
| 5 | ui design | `ui,design,component,style` | `ui` |
|
||||
| 6 | tdd | `tdd,test-driven,先写测试` | `tdd` |
|
||||
| 7 | review | `review,审查,code review` | `review-fix` |
|
||||
| 8 | documentation | `文档,docs,readme` | `docs` |
|
||||
| 99 | feature | complexity-based | `rapid`/`coupled` |
|
||||
| Priority | Intent | Patterns | Level | Flow |
|
||||
|----------|--------|----------|-------|------|
|
||||
| 1 | bugfix/hotfix | `urgent,production,critical` + bug | L2 | `bugfix.hotfix` |
|
||||
| 1 | bugfix | `fix,bug,error,crash,fail` | L2 | `bugfix.standard` |
|
||||
| 2 | issue batch | `issues,batch` + `fix,resolve` | Issue | `issue` |
|
||||
| 3 | exploration | `不确定,explore,研究,what if` | L4 | `full` |
|
||||
| 3 | multi-perspective | `多视角,权衡,比较方案,cross-verify` | L2 | `multi-cli-plan` |
|
||||
| 4 | quick-task | `快速,简单,small,quick` + feature | L1 | `lite-lite-lite` |
|
||||
| 5 | ui design | `ui,design,component,style` | L3/L4 | `ui` |
|
||||
| 6 | tdd | `tdd,test-driven,先写测试` | L3 | `tdd` |
|
||||
| 7 | test-fix | `测试失败,test fail,fix test` | L3 | `test-fix-gen` |
|
||||
| 8 | review | `review,审查,code review` | L3 | `review-fix` |
|
||||
| 9 | documentation | `文档,docs,readme` | L2 | `docs` |
|
||||
| 99 | feature | complexity-based | L2/L3 | `rapid`/`coupled` |
|
||||
|
||||
### Quick Selection Guide
|
||||
|
||||
| Scenario | Recommended Workflow | Level |
|
||||
|----------|---------------------|-------|
|
||||
| Quick fixes, config adjustments | `lite-lite-lite` | 1 |
|
||||
| Clear single-module features | `lite-plan → lite-execute` | 2 |
|
||||
| Bug diagnosis and fix | `lite-fix` | 2 |
|
||||
| Production emergencies | `lite-fix --hotfix` | 2 |
|
||||
| Technology selection, solution comparison | `multi-cli-plan → lite-execute` | 2 |
|
||||
| Multi-module changes, refactoring | `plan → verify → execute` | 3 |
|
||||
| Test-driven development | `tdd-plan → execute → tdd-verify` | 3 |
|
||||
| Test failure fixes | `test-fix-gen → test-cycle-execute` | 3 |
|
||||
| New features, architecture design | `brainstorm:auto-parallel → plan → execute` | 4 |
|
||||
| Post-development issue fixes | Issue Workflow | - |
|
||||
|
||||
### Complexity Assessment
|
||||
|
||||
@@ -214,24 +308,100 @@ CLI 可返回建议:`use_default` | `modify` (调整步骤) | `upgrade` (升
|
||||
|
||||
## Workflow Flow Details
|
||||
|
||||
### Issue Workflow (两阶段生命周期)
|
||||
### Issue Workflow (Main Workflow 补充机制)
|
||||
|
||||
Issue 工作流设计为两阶段生命周期,支持在项目迭代过程中积累问题并集中解决。
|
||||
Issue Workflow 是 Main Workflow 的**补充机制**,专注于开发后的持续维护。
|
||||
|
||||
**Phase 1: Accumulation (积累阶段)**
|
||||
- 触发:任务完成后的 review、代码审查发现、测试失败
|
||||
- 活动:需求扩展、bug 分析、测试覆盖、安全审查
|
||||
- 命令:`/issue:discover`, `/issue:discover-by-prompt`, `/issue:new`
|
||||
#### 设计理念
|
||||
|
||||
**Phase 2: Batch Resolution (批量解决阶段)**
|
||||
- 触发:积累足够 issue 后的集中处理
|
||||
- 流程:plan → queue → execute
|
||||
- 命令:`/issue:plan --all-pending` → `/issue:queue` → `/issue:execute`
|
||||
| 方面 | Main Workflow | Issue Workflow |
|
||||
|------|---------------|----------------|
|
||||
| **用途** | 主要开发周期 | 开发后维护 |
|
||||
| **时机** | 功能开发阶段 | 主工作流完成后 |
|
||||
| **范围** | 完整功能实现 | 针对性修复/增强 |
|
||||
| **并行性** | 依赖分析 → Agent 并行 | Worktree 隔离 (可选) |
|
||||
| **分支模型** | 当前分支工作 | 可使用隔离的 worktree |
|
||||
|
||||
#### 为什么 Main Workflow 不自动使用 Worktree?
|
||||
|
||||
**依赖分析已解决并行性问题**:
|
||||
1. 规划阶段 (`/workflow:plan`) 执行依赖分析
|
||||
2. 自动识别任务依赖和关键路径
|
||||
3. 划分为**并行组**(独立任务)和**串行链**(依赖任务)
|
||||
4. Agent 并行执行独立任务,无需文件系统隔离
|
||||
|
||||
#### 两阶段生命周期
|
||||
|
||||
```
|
||||
任务完成 → discover → 积累 issue → ... → plan all → queue → parallel execute
|
||||
↑ ↓
|
||||
└────── 迭代循环 ───────┘
|
||||
┌─────────────────────────────────────────────────────────────────────┐
|
||||
│ Phase 1: Accumulation (积累阶段) │
|
||||
│ │
|
||||
│ Triggers: 任务完成后的 review、代码审查发现、测试失败 │
|
||||
│ │
|
||||
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
|
||||
│ │ discover │ │ discover- │ │ new │ │
|
||||
│ │ Auto-find │ │ by-prompt │ │ Manual │ │
|
||||
│ └────────────┘ └────────────┘ └────────────┘ │
|
||||
│ │
|
||||
│ 持续积累 issues 到待处理队列 │
|
||||
└─────────────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
│ 积累足够后
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────────┐
|
||||
│ Phase 2: Batch Resolution (批量解决阶段) │
|
||||
│ │
|
||||
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
|
||||
│ │ plan │ ──→ │ queue │ ──→ │ execute │ │
|
||||
│ │ --all- │ │ Optimize │ │ Parallel │ │
|
||||
│ │ pending │ │ order │ │ execution │ │
|
||||
│ └────────────┘ └────────────┘ └────────────┘ │
|
||||
│ │
|
||||
│ 支持 worktree 隔离,保持主分支稳定 │
|
||||
└─────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
#### 与 Main Workflow 的协作
|
||||
|
||||
```
|
||||
开发迭代循环
|
||||
┌─────────────────────────────────────────────────────────────────────┐
|
||||
│ │
|
||||
│ ┌─────────┐ ┌─────────┐ │
|
||||
│ │ Feature │ ──→ Main Workflow ──→ Done ──→│ Review │ │
|
||||
│ │ Request │ (Level 1-4) └────┬────┘ │
|
||||
│ └─────────┘ │ │
|
||||
│ ▲ │ 发现 Issues │
|
||||
│ │ ▼ │
|
||||
│ │ ┌─────────┐ │
|
||||
│ 继续 │ │ Issue │ │
|
||||
│ 新功能│ │ Workflow│ │
|
||||
│ │ └────┬────┘ │
|
||||
│ │ ┌──────────────────────────────┘ │
|
||||
│ │ │ 修复完成 │
|
||||
│ │ ▼ │
|
||||
│ ┌────┴────┐◀────── │
|
||||
│ │ Main │ Merge │
|
||||
│ │ Branch │ back │
|
||||
│ └─────────┘ │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
#### 命令列表
|
||||
|
||||
**积累阶段:**
|
||||
```bash
|
||||
/issue:discover # 多视角自动发现
|
||||
/issue:discover-by-prompt # 基于提示发现
|
||||
/issue:new # 手动创建
|
||||
```
|
||||
|
||||
**批量解决阶段:**
|
||||
```bash
|
||||
/issue:plan --all-pending # 批量规划所有待处理
|
||||
/issue:queue # 生成优化执行队列
|
||||
/issue:execute # 并行执行
|
||||
```
|
||||
|
||||
### lite-lite-lite vs multi-cli-plan
|
||||
|
||||
@@ -73,10 +73,37 @@
|
||||
},
|
||||
|
||||
"flows": {
|
||||
"_level_guide": {
|
||||
"L1": "Rapid - No artifacts, direct execution",
|
||||
"L2": "Lightweight - Memory/lightweight files, → lite-execute",
|
||||
"L3": "Standard - Session persistence, → execute/test-cycle-execute",
|
||||
"L4": "Brainstorm - Multi-role analysis + Session, → execute"
|
||||
},
|
||||
"lite-lite-lite": {
|
||||
"name": "Ultra-Rapid Execution",
|
||||
"level": "L1",
|
||||
"description": "零文件 + 自动CLI选择 + 语义描述 + 直接执行",
|
||||
"complexity": ["low"],
|
||||
"artifacts": "none",
|
||||
"steps": [
|
||||
{ "phase": "clarify", "description": "需求澄清 (AskUser if needed)" },
|
||||
{ "phase": "auto-select", "description": "任务分析 → 自动选择CLI组合" },
|
||||
{ "phase": "multi-cli", "description": "并行多CLI分析" },
|
||||
{ "phase": "decision", "description": "展示结果 → AskUser决策" },
|
||||
{ "phase": "execute", "description": "直接执行 (无中间文件)" }
|
||||
],
|
||||
"cli_hints": {
|
||||
"analysis": { "tool": "auto", "mode": "analysis", "parallel": true },
|
||||
"execution": { "tool": "auto", "mode": "write" }
|
||||
},
|
||||
"estimated_time": "10-30 min"
|
||||
},
|
||||
"rapid": {
|
||||
"name": "Rapid Iteration",
|
||||
"description": "多模型协作分析 + 直接执行",
|
||||
"level": "L2",
|
||||
"description": "内存规划 + 直接执行",
|
||||
"complexity": ["low", "medium"],
|
||||
"artifacts": "memory://plan",
|
||||
"steps": [
|
||||
{ "command": "/workflow:lite-plan", "optional": false, "auto_continue": true },
|
||||
{ "command": "/workflow:lite-execute", "optional": false }
|
||||
@@ -87,107 +114,12 @@
|
||||
},
|
||||
"estimated_time": "15-45 min"
|
||||
},
|
||||
"full": {
|
||||
"name": "Full Exploration",
|
||||
"description": "头脑风暴 + 规划 + 执行",
|
||||
"complexity": ["medium", "high"],
|
||||
"steps": [
|
||||
{ "command": "/workflow:brainstorm:auto-parallel", "optional": false, "confirm_before": true },
|
||||
{ "command": "/workflow:plan", "optional": false },
|
||||
{ "command": "/workflow:action-plan-verify", "optional": true, "auto_continue": true },
|
||||
{ "command": "/workflow:execute", "optional": false }
|
||||
],
|
||||
"cli_hints": {
|
||||
"role_analysis": { "tool": "gemini", "mode": "analysis", "trigger": "always", "parallel": true },
|
||||
"execution": { "tool": "codex", "mode": "write", "trigger": "task_count >= 3" }
|
||||
},
|
||||
"estimated_time": "1-3 hours"
|
||||
},
|
||||
"coupled": {
|
||||
"name": "Coupled Planning",
|
||||
"description": "完整规划 + 验证 + 执行",
|
||||
"complexity": ["high"],
|
||||
"steps": [
|
||||
{ "command": "/workflow:plan", "optional": false },
|
||||
{ "command": "/workflow:action-plan-verify", "optional": false, "auto_continue": true },
|
||||
{ "command": "/workflow:execute", "optional": false },
|
||||
{ "command": "/workflow:review", "optional": true }
|
||||
],
|
||||
"cli_hints": {
|
||||
"pre_analysis": { "tool": "gemini", "mode": "analysis", "trigger": "always" },
|
||||
"execution": { "tool": "codex", "mode": "write", "trigger": "always" }
|
||||
},
|
||||
"estimated_time": "2-4 hours"
|
||||
},
|
||||
"bugfix": {
|
||||
"name": "Bug Fix",
|
||||
"description": "智能诊断 + 修复",
|
||||
"complexity": ["low", "medium"],
|
||||
"variants": {
|
||||
"standard": [{ "command": "/workflow:lite-fix", "optional": false }],
|
||||
"hotfix": [{ "command": "/workflow:lite-fix --hotfix", "optional": false }]
|
||||
},
|
||||
"cli_hints": {
|
||||
"diagnosis": { "tool": "gemini", "mode": "analysis", "trigger": "always" },
|
||||
"fix": { "tool": "codex", "mode": "write", "trigger": "severity >= medium" }
|
||||
},
|
||||
"estimated_time": "10-30 min"
|
||||
},
|
||||
"issue": {
|
||||
"name": "Issue Lifecycle",
|
||||
"description": "发现积累 → 批量规划 → 队列优化 → 并行执行",
|
||||
"complexity": ["medium", "high"],
|
||||
"phases": {
|
||||
"accumulation": {
|
||||
"description": "项目迭代中持续发现和积累issue",
|
||||
"commands": ["/issue:discover", "/issue:new"],
|
||||
"trigger": "post-task, code-review, test-failure"
|
||||
},
|
||||
"resolution": {
|
||||
"description": "集中规划和执行积累的issue",
|
||||
"steps": [
|
||||
{ "command": "/issue:plan --all-pending", "optional": false },
|
||||
{ "command": "/issue:queue", "optional": false },
|
||||
{ "command": "/issue:execute", "optional": false }
|
||||
]
|
||||
}
|
||||
},
|
||||
"cli_hints": {
|
||||
"discovery": { "tool": "gemini", "mode": "analysis", "trigger": "perspective_analysis", "parallel": true },
|
||||
"solution_generation": { "tool": "gemini", "mode": "analysis", "trigger": "always", "parallel": true },
|
||||
"batch_execution": { "tool": "codex", "mode": "write", "trigger": "always" }
|
||||
},
|
||||
"estimated_time": "1-4 hours"
|
||||
},
|
||||
"lite-lite-lite": {
|
||||
"name": "Ultra-Lite Multi-CLI",
|
||||
"description": "零文件 + 自动CLI选择 + 语义描述 + 直接执行",
|
||||
"complexity": ["low", "medium"],
|
||||
"steps": [
|
||||
{ "phase": "clarify", "description": "需求澄清 (AskUser if needed)" },
|
||||
{ "phase": "auto-select", "description": "任务分析 → 自动选择CLI组合" },
|
||||
{ "phase": "multi-cli", "description": "并行多CLI分析" },
|
||||
{ "phase": "decision", "description": "展示结果 → AskUser决策" },
|
||||
{ "phase": "execute", "description": "直接执行 (无中间文件)" }
|
||||
],
|
||||
"vs_multi_cli_plan": {
|
||||
"artifacts": "None vs IMPL_PLAN.md + plan.json + synthesis.json",
|
||||
"session": "Stateless vs Persistent",
|
||||
"cli_selection": "Auto-select based on task analysis vs Config-driven",
|
||||
"iteration": "Via AskUser vs Via rounds/synthesis",
|
||||
"execution": "Direct vs Via lite-execute",
|
||||
"best_for": "Quick fixes, simple features vs Complex multi-step implementations"
|
||||
},
|
||||
"cli_hints": {
|
||||
"analysis": { "tool": "auto", "mode": "analysis", "parallel": true },
|
||||
"execution": { "tool": "auto", "mode": "write" }
|
||||
},
|
||||
"estimated_time": "10-30 min"
|
||||
},
|
||||
"multi-cli-plan": {
|
||||
"name": "Multi-CLI Collaborative Planning",
|
||||
"level": "L2",
|
||||
"description": "ACE上下文 + 多CLI协作分析 + 迭代收敛 + 计划生成",
|
||||
"complexity": ["medium", "high"],
|
||||
"artifacts": ".workflow/.multi-cli-plan/{session}/",
|
||||
"steps": [
|
||||
{ "command": "/workflow:multi-cli-plan", "optional": false, "phases": [
|
||||
"context_gathering: ACE语义搜索",
|
||||
@@ -210,28 +142,154 @@
|
||||
"discussion": { "tools": ["gemini", "codex", "claude"], "mode": "analysis", "parallel": true },
|
||||
"planning": { "tool": "gemini", "mode": "analysis" }
|
||||
},
|
||||
"output": ".workflow/.multi-cli-plan/{session-id}/",
|
||||
"estimated_time": "30-90 min"
|
||||
},
|
||||
"coupled": {
|
||||
"name": "Standard Planning",
|
||||
"level": "L3",
|
||||
"description": "完整规划 + 验证 + 执行",
|
||||
"complexity": ["medium", "high"],
|
||||
"artifacts": ".workflow/active/{session}/",
|
||||
"steps": [
|
||||
{ "command": "/workflow:plan", "optional": false },
|
||||
{ "command": "/workflow:action-plan-verify", "optional": false, "auto_continue": true },
|
||||
{ "command": "/workflow:execute", "optional": false },
|
||||
{ "command": "/workflow:review", "optional": true }
|
||||
],
|
||||
"cli_hints": {
|
||||
"pre_analysis": { "tool": "gemini", "mode": "analysis", "trigger": "always" },
|
||||
"execution": { "tool": "codex", "mode": "write", "trigger": "always" }
|
||||
},
|
||||
"estimated_time": "2-4 hours"
|
||||
},
|
||||
"full": {
|
||||
"name": "Full Exploration (Brainstorm)",
|
||||
"level": "L4",
|
||||
"description": "头脑风暴 + 规划 + 执行",
|
||||
"complexity": ["high"],
|
||||
"artifacts": ".workflow/active/{session}/.brainstorming/",
|
||||
"steps": [
|
||||
{ "command": "/workflow:brainstorm:auto-parallel", "optional": false, "confirm_before": true },
|
||||
{ "command": "/workflow:plan", "optional": false },
|
||||
{ "command": "/workflow:action-plan-verify", "optional": true, "auto_continue": true },
|
||||
{ "command": "/workflow:execute", "optional": false }
|
||||
],
|
||||
"cli_hints": {
|
||||
"role_analysis": { "tool": "gemini", "mode": "analysis", "trigger": "always", "parallel": true },
|
||||
"execution": { "tool": "codex", "mode": "write", "trigger": "task_count >= 3" }
|
||||
},
|
||||
"estimated_time": "1-3 hours"
|
||||
},
|
||||
"bugfix": {
|
||||
"name": "Bug Fix",
|
||||
"level": "L2",
|
||||
"description": "智能诊断 + 修复 (5 phases)",
|
||||
"complexity": ["low", "medium"],
|
||||
"artifacts": ".workflow/.lite-fix/{bug-slug}-{date}/",
|
||||
"variants": {
|
||||
"standard": [{ "command": "/workflow:lite-fix", "optional": false }],
|
||||
"hotfix": [{ "command": "/workflow:lite-fix --hotfix", "optional": false }]
|
||||
},
|
||||
"phases": [
|
||||
"Phase 1: Bug Analysis & Diagnosis (severity pre-assessment)",
|
||||
"Phase 2: Clarification (optional, AskUserQuestion)",
|
||||
"Phase 3: Fix Planning (Low/Medium → Claude, High/Critical → cli-lite-planning-agent)",
|
||||
"Phase 4: Confirmation & Selection",
|
||||
"Phase 5: Execute (→ lite-execute --mode bugfix)"
|
||||
],
|
||||
"cli_hints": {
|
||||
"diagnosis": { "tool": "gemini", "mode": "analysis", "trigger": "always" },
|
||||
"fix": { "tool": "codex", "mode": "write", "trigger": "severity >= medium" }
|
||||
},
|
||||
"estimated_time": "10-30 min"
|
||||
},
|
||||
"issue": {
|
||||
"name": "Issue Lifecycle",
|
||||
"level": "Supplementary",
|
||||
"description": "发现积累 → 批量规划 → 队列优化 → 并行执行 (Main Workflow 补充机制)",
|
||||
"complexity": ["medium", "high"],
|
||||
"artifacts": ".workflow/.issues/",
|
||||
"purpose": "Post-development continuous maintenance, maintain main branch stability",
|
||||
"phases": {
|
||||
"accumulation": {
|
||||
"description": "项目迭代中持续发现和积累issue",
|
||||
"commands": ["/issue:discover", "/issue:discover-by-prompt", "/issue:new"],
|
||||
"trigger": "post-task, code-review, test-failure"
|
||||
},
|
||||
"resolution": {
|
||||
"description": "集中规划和执行积累的issue",
|
||||
"steps": [
|
||||
{ "command": "/issue:plan --all-pending", "optional": false },
|
||||
{ "command": "/issue:queue", "optional": false },
|
||||
{ "command": "/issue:execute", "optional": false }
|
||||
]
|
||||
}
|
||||
},
|
||||
"worktree_support": {
|
||||
"description": "可选的 worktree 隔离,保持主分支稳定",
|
||||
"use_case": "主开发完成后的 issue 修复"
|
||||
},
|
||||
"cli_hints": {
|
||||
"discovery": { "tool": "gemini", "mode": "analysis", "trigger": "perspective_analysis", "parallel": true },
|
||||
"solution_generation": { "tool": "gemini", "mode": "analysis", "trigger": "always", "parallel": true },
|
||||
"batch_execution": { "tool": "codex", "mode": "write", "trigger": "always" }
|
||||
},
|
||||
"estimated_time": "1-4 hours"
|
||||
},
|
||||
"tdd": {
|
||||
"name": "Test-Driven Development",
|
||||
"description": "TDD规划 + 执行 + 验证",
|
||||
"level": "L3",
|
||||
"description": "TDD规划 + 执行 + 验证 (6 phases)",
|
||||
"complexity": ["medium", "high"],
|
||||
"artifacts": ".workflow/active/{session}/",
|
||||
"steps": [
|
||||
{ "command": "/workflow:tdd-plan", "optional": false },
|
||||
{ "command": "/workflow:action-plan-verify", "optional": true, "auto_continue": true },
|
||||
{ "command": "/workflow:execute", "optional": false },
|
||||
{ "command": "/workflow:tdd-verify", "optional": false }
|
||||
],
|
||||
"tdd_structure": {
|
||||
"description": "Each IMPL task contains complete internal Red-Green-Refactor cycle",
|
||||
"meta": "tdd_workflow: true",
|
||||
"flow_control": "implementation_approach contains 3 steps (red/green/refactor)"
|
||||
},
|
||||
"cli_hints": {
|
||||
"test_strategy": { "tool": "gemini", "mode": "analysis", "trigger": "always" },
|
||||
"red_green_refactor": { "tool": "codex", "mode": "write", "trigger": "always" }
|
||||
},
|
||||
"estimated_time": "1-3 hours"
|
||||
},
|
||||
"test-fix": {
|
||||
"name": "Test Fix Generation",
|
||||
"level": "L3",
|
||||
"description": "测试修复生成 + 执行循环 (5 phases)",
|
||||
"complexity": ["medium", "high"],
|
||||
"artifacts": ".workflow/active/WFS-test-{session}/",
|
||||
"dual_mode": {
|
||||
"session_mode": { "input": "WFS-xxx", "context_source": "Source session summaries" },
|
||||
"prompt_mode": { "input": "Text/file path", "context_source": "Direct codebase analysis" }
|
||||
},
|
||||
"steps": [
|
||||
{ "command": "/workflow:test-fix-gen", "optional": false },
|
||||
{ "command": "/workflow:test-cycle-execute", "optional": false }
|
||||
],
|
||||
"task_structure": [
|
||||
"IMPL-001.json (test understanding & generation)",
|
||||
"IMPL-001.5-review.json (quality gate)",
|
||||
"IMPL-002.json (test execution & fix cycle)"
|
||||
],
|
||||
"cli_hints": {
|
||||
"analysis": { "tool": "gemini", "mode": "analysis", "trigger": "always" },
|
||||
"fix_cycle": { "tool": "codex", "mode": "write", "trigger": "pass_rate < 0.95" }
|
||||
},
|
||||
"estimated_time": "1-2 hours"
|
||||
},
|
||||
"ui": {
|
||||
"name": "UI-First Development",
|
||||
"level": "L3/L4",
|
||||
"description": "UI设计 + 规划 + 执行",
|
||||
"complexity": ["medium", "high"],
|
||||
"artifacts": ".workflow/active/{session}/",
|
||||
"variants": {
|
||||
"explore": [
|
||||
{ "command": "/workflow:ui-design:explore-auto", "optional": false },
|
||||
@@ -250,8 +308,10 @@
|
||||
},
|
||||
"review-fix": {
|
||||
"name": "Review and Fix",
|
||||
"level": "L3",
|
||||
"description": "多维审查 + 自动修复",
|
||||
"complexity": ["medium"],
|
||||
"artifacts": ".workflow/active/{session}/review_report.md",
|
||||
"steps": [
|
||||
{ "command": "/workflow:review-session-cycle", "optional": false },
|
||||
{ "command": "/workflow:review-fix", "optional": true }
|
||||
@@ -264,6 +324,7 @@
|
||||
},
|
||||
"docs": {
|
||||
"name": "Documentation",
|
||||
"level": "L2",
|
||||
"description": "批量文档生成",
|
||||
"complexity": ["low", "medium"],
|
||||
"variants": {
|
||||
@@ -278,8 +339,17 @@
|
||||
},
|
||||
|
||||
"intent_rules": {
|
||||
"_level_mapping": {
|
||||
"description": "Intent → Level → Flow mapping guide",
|
||||
"L1": ["lite-lite-lite"],
|
||||
"L2": ["rapid", "bugfix", "multi-cli-plan", "docs"],
|
||||
"L3": ["coupled", "tdd", "test-fix", "review-fix", "ui"],
|
||||
"L4": ["full"],
|
||||
"Supplementary": ["issue"]
|
||||
},
|
||||
"bugfix": {
|
||||
"priority": 1,
|
||||
"level": "L2",
|
||||
"variants": {
|
||||
"hotfix": {
|
||||
"patterns": ["hotfix", "urgent", "production", "critical", "emergency", "紧急", "生产环境", "线上"],
|
||||
@@ -293,6 +363,7 @@
|
||||
},
|
||||
"issue_batch": {
|
||||
"priority": 2,
|
||||
"level": "Supplementary",
|
||||
"patterns": {
|
||||
"batch": ["issues", "batch", "queue", "多个", "批量"],
|
||||
"action": ["fix", "resolve", "处理", "解决"]
|
||||
@@ -302,11 +373,25 @@
|
||||
},
|
||||
"exploration": {
|
||||
"priority": 3,
|
||||
"level": "L4",
|
||||
"patterns": ["不确定", "不知道", "explore", "研究", "分析一下", "怎么做", "what if", "探索"],
|
||||
"flow": "full"
|
||||
},
|
||||
"ui_design": {
|
||||
"multi_perspective": {
|
||||
"priority": 3,
|
||||
"level": "L2",
|
||||
"patterns": ["多视角", "权衡", "比较方案", "cross-verify", "多CLI", "协作分析"],
|
||||
"flow": "multi-cli-plan"
|
||||
},
|
||||
"quick_task": {
|
||||
"priority": 4,
|
||||
"level": "L1",
|
||||
"patterns": ["快速", "简单", "small", "quick", "simple", "trivial", "小改动"],
|
||||
"flow": "lite-lite-lite"
|
||||
},
|
||||
"ui_design": {
|
||||
"priority": 5,
|
||||
"level": "L3/L4",
|
||||
"patterns": ["ui", "界面", "design", "设计", "component", "组件", "style", "样式", "layout", "布局"],
|
||||
"variants": {
|
||||
"imitate": { "triggers": ["参考", "模仿", "像", "类似"], "flow": "ui.imitate" },
|
||||
@@ -314,17 +399,26 @@
|
||||
}
|
||||
},
|
||||
"tdd": {
|
||||
"priority": 5,
|
||||
"priority": 6,
|
||||
"level": "L3",
|
||||
"patterns": ["tdd", "test-driven", "测试驱动", "先写测试", "test first"],
|
||||
"flow": "tdd"
|
||||
},
|
||||
"test_fix": {
|
||||
"priority": 7,
|
||||
"level": "L3",
|
||||
"patterns": ["测试失败", "test fail", "fix test", "test error", "pass rate", "coverage gap"],
|
||||
"flow": "test-fix"
|
||||
},
|
||||
"review": {
|
||||
"priority": 6,
|
||||
"priority": 8,
|
||||
"level": "L3",
|
||||
"patterns": ["review", "审查", "检查代码", "code review", "质量检查"],
|
||||
"flow": "review-fix"
|
||||
},
|
||||
"documentation": {
|
||||
"priority": 7,
|
||||
"priority": 9,
|
||||
"level": "L2",
|
||||
"patterns": ["文档", "documentation", "docs", "readme"],
|
||||
"variants": {
|
||||
"incremental": { "triggers": ["更新", "增量"], "flow": "docs.incremental" },
|
||||
@@ -334,9 +428,9 @@
|
||||
"feature": {
|
||||
"priority": 99,
|
||||
"complexity_map": {
|
||||
"high": "coupled",
|
||||
"medium": "rapid",
|
||||
"low": "rapid"
|
||||
"high": { "level": "L3", "flow": "coupled" },
|
||||
"medium": { "level": "L2", "flow": "rapid" },
|
||||
"low": { "level": "L1", "flow": "lite-lite-lite" }
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -304,28 +304,22 @@ async function runWithTool(tool, context) {
|
||||
### 引用协议模板
|
||||
|
||||
```bash
|
||||
# 分析模式 - 必须引用 analysis-protocol.md
|
||||
# Analysis mode - use --rule to auto-load protocol and template (appended to prompt)
|
||||
ccw cli -p "
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md)
|
||||
$(cat ~/.claude/workflows/cli-templates/prompts/analysis/02-analyze-code-patterns.txt)
|
||||
..." --tool gemini --mode analysis
|
||||
CONSTRAINTS: ...
|
||||
..." --tool gemini --mode analysis --rule analysis-code-patterns
|
||||
|
||||
# 写入模式 - 必须引用 write-protocol.md
|
||||
# Write mode - use --rule to auto-load protocol and template (appended to prompt)
|
||||
ccw cli -p "
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/write-protocol.md)
|
||||
$(cat ~/.claude/workflows/cli-templates/prompts/development/02-implement-feature.txt)
|
||||
..." --tool codex --mode write
|
||||
CONSTRAINTS: ...
|
||||
..." --tool codex --mode write --rule development-feature
|
||||
```
|
||||
|
||||
### 动态模板构建
|
||||
|
||||
```javascript
|
||||
function buildPrompt(config) {
|
||||
const { purpose, task, mode, context, expected, template } = config;
|
||||
|
||||
const protocolPath = mode === 'write'
|
||||
? '~/.claude/workflows/cli-templates/protocols/write-protocol.md'
|
||||
: '~/.claude/workflows/cli-templates/protocols/analysis-protocol.md';
|
||||
const { purpose, task, mode, context, expected, constraints } = config;
|
||||
|
||||
return `
|
||||
PURPOSE: ${purpose}
|
||||
@@ -333,8 +327,8 @@ TASK: ${task.map(t => `• ${t}`).join('\n')}
|
||||
MODE: ${mode}
|
||||
CONTEXT: ${context}
|
||||
EXPECTED: ${expected}
|
||||
RULES: $(cat ${protocolPath}) $(cat ${template})
|
||||
`;
|
||||
CONSTRAINTS: ${constraints || ''}
|
||||
`; // Use --rule option to auto-append protocol + template
|
||||
}
|
||||
```
|
||||
|
||||
@@ -435,11 +429,11 @@ CLI 调用 (Bash + ccw cli):
|
||||
- 相关任务使用 `--resume` 保持上下文
|
||||
- 独立任务不使用 `--resume`
|
||||
|
||||
### 4. 提示词规范
|
||||
### 4. Prompt Specification
|
||||
|
||||
- 始终使用 PURPOSE/TASK/MODE/CONTEXT/EXPECTED/RULES 结构
|
||||
- 必须引用协议模板(analysis-protocol 或 write-protocol)
|
||||
- 使用 `$(cat ...)` 动态加载模板
|
||||
- Always use PURPOSE/TASK/MODE/CONTEXT/EXPECTED/CONSTRAINTS structure
|
||||
- Use `--rule <template>` to auto-append protocol + template to prompt
|
||||
- Template name format: `category-function` (e.g., `analysis-code-patterns`)
|
||||
|
||||
### 5. 结果处理
|
||||
|
||||
|
||||
@@ -76,8 +76,8 @@ TASK: • Extract conflicts from IMPL_PLAN and lessons • Group by type (archit
|
||||
MODE: analysis
|
||||
CONTEXT: @.workflow/.archives/*/IMPL_PLAN.md @.workflow/.archives/manifest.json
|
||||
EXPECTED: Conflict patterns with frequency and resolution
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/workflow/skill-aggregation.txt) | analysis=READ-ONLY
|
||||
" --tool gemini --cd .workflow/.archives
|
||||
CONSTRAINTS: analysis=READ-ONLY
|
||||
" --tool gemini --mode analysis --rule workflow-skill-aggregation --cd .workflow/.archives
|
||||
```
|
||||
|
||||
**Pattern Grouping**:
|
||||
@@ -72,8 +72,8 @@ TASK: • Group successes by functional domain • Categorize challenges by seve
|
||||
MODE: analysis
|
||||
CONTEXT: @.workflow/.archives/manifest.json
|
||||
EXPECTED: Aggregated lessons with frequency counts
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/workflow/skill-aggregation.txt) | analysis=READ-ONLY
|
||||
" --tool gemini --cd .workflow/.archives
|
||||
CONSTRAINTS: analysis=READ-ONLY
|
||||
" --tool gemini --mode analysis --rule workflow-skill-aggregation --cd .workflow/.archives
|
||||
```
|
||||
|
||||
**Severity Classification**:
|
||||
@@ -65,6 +65,35 @@
|
||||
"items": { "type": "string" },
|
||||
"description": "Files/modules affected"
|
||||
},
|
||||
"feedback": {
|
||||
"type": "array",
|
||||
"description": "Execution feedback history (failures, clarifications, rejections) for planning phase reference",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["type", "stage", "content", "created_at"],
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"enum": ["failure", "clarification", "rejection"],
|
||||
"description": "Type of feedback"
|
||||
},
|
||||
"stage": {
|
||||
"type": "string",
|
||||
"enum": ["new", "plan", "execute"],
|
||||
"description": "Which stage the feedback occurred (new=creation, plan=planning, execute=execution)"
|
||||
},
|
||||
"content": {
|
||||
"type": "string",
|
||||
"description": "JSON string for failures (with solution_id, task_id, error_type, message, stack_trace) or plain text for clarifications/rejections"
|
||||
},
|
||||
"created_at": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"description": "Timestamp when feedback was created"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"lifecycle_requirements": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -143,11 +143,211 @@
|
||||
}
|
||||
},
|
||||
"description": "CLI execution strategy based on task dependencies"
|
||||
},
|
||||
"rationale": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"chosen_approach": {
|
||||
"type": "string",
|
||||
"description": "The selected implementation approach and why it was chosen"
|
||||
},
|
||||
"alternatives_considered": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "Alternative approaches that were considered but not chosen"
|
||||
},
|
||||
"decision_factors": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "Key factors that influenced the decision (performance, maintainability, cost, etc.)"
|
||||
},
|
||||
"tradeoffs": {
|
||||
"type": "string",
|
||||
"description": "Known tradeoffs of the chosen approach"
|
||||
}
|
||||
},
|
||||
"description": "Design rationale explaining WHY this approach was chosen (required for Medium/High complexity)"
|
||||
},
|
||||
"verification": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"unit_tests": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "List of unit test names/descriptions to create"
|
||||
},
|
||||
"integration_tests": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "List of integration test names/descriptions to create"
|
||||
},
|
||||
"manual_checks": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "Manual verification steps with specific actions"
|
||||
},
|
||||
"success_metrics": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "Quantified metrics for success (e.g., 'Response time <200ms', 'Coverage >80%')"
|
||||
}
|
||||
},
|
||||
"description": "Detailed verification steps beyond acceptance criteria (required for Medium/High complexity)"
|
||||
},
|
||||
"risks": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["description", "probability", "impact", "mitigation"],
|
||||
"properties": {
|
||||
"description": {
|
||||
"type": "string",
|
||||
"description": "Description of the risk"
|
||||
},
|
||||
"probability": {
|
||||
"type": "string",
|
||||
"enum": ["Low", "Medium", "High"],
|
||||
"description": "Likelihood of the risk occurring"
|
||||
},
|
||||
"impact": {
|
||||
"type": "string",
|
||||
"enum": ["Low", "Medium", "High"],
|
||||
"description": "Impact severity if the risk occurs"
|
||||
},
|
||||
"mitigation": {
|
||||
"type": "string",
|
||||
"description": "Strategy to mitigate or prevent the risk"
|
||||
},
|
||||
"fallback": {
|
||||
"type": "string",
|
||||
"description": "Alternative approach if mitigation fails"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Risk assessment and mitigation strategies (required for High complexity)"
|
||||
},
|
||||
"code_skeleton": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"interfaces": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {"type": "string"},
|
||||
"definition": {"type": "string"},
|
||||
"purpose": {"type": "string"}
|
||||
}
|
||||
},
|
||||
"description": "Key interface/type definitions"
|
||||
},
|
||||
"key_functions": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"signature": {"type": "string"},
|
||||
"purpose": {"type": "string"},
|
||||
"returns": {"type": "string"}
|
||||
}
|
||||
},
|
||||
"description": "Critical function signatures"
|
||||
},
|
||||
"classes": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {"type": "string"},
|
||||
"purpose": {"type": "string"},
|
||||
"methods": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Key class structures"
|
||||
}
|
||||
},
|
||||
"description": "Code skeleton with interface/function signatures (required for High complexity)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Structured task breakdown (1-10 tasks)"
|
||||
},
|
||||
"data_flow": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"diagram": {
|
||||
"type": "string",
|
||||
"description": "ASCII/text representation of data flow (e.g., 'A → B → C')"
|
||||
},
|
||||
"stages": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["stage", "input", "output", "component"],
|
||||
"properties": {
|
||||
"stage": {
|
||||
"type": "string",
|
||||
"description": "Stage name (e.g., 'Extraction', 'Processing', 'Storage')"
|
||||
},
|
||||
"input": {
|
||||
"type": "string",
|
||||
"description": "Input data format/type"
|
||||
},
|
||||
"output": {
|
||||
"type": "string",
|
||||
"description": "Output data format/type"
|
||||
},
|
||||
"component": {
|
||||
"type": "string",
|
||||
"description": "Component/module handling this stage"
|
||||
},
|
||||
"transformations": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "Data transformations applied in this stage"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Detailed data flow stages"
|
||||
},
|
||||
"dependencies": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "External dependencies or data sources"
|
||||
}
|
||||
},
|
||||
"description": "Global data flow design showing how data moves through the system (required for High complexity)"
|
||||
},
|
||||
"design_decisions": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["decision", "rationale"],
|
||||
"properties": {
|
||||
"decision": {
|
||||
"type": "string",
|
||||
"description": "The design decision made"
|
||||
},
|
||||
"rationale": {
|
||||
"type": "string",
|
||||
"description": "Why this decision was made"
|
||||
},
|
||||
"tradeoff": {
|
||||
"type": "string",
|
||||
"description": "What was traded off for this decision"
|
||||
},
|
||||
"alternatives": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "Alternatives that were considered"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Global design decisions that affect the entire plan"
|
||||
},
|
||||
"flow_control": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
2. [Tool Selection](#tool-selection)
|
||||
3. [Prompt Template](#prompt-template)
|
||||
4. [CLI Execution](#cli-execution)
|
||||
5. [Execution Configuration](#execution-configuration)
|
||||
5. [Auto-Invoke Triggers](#auto-invoke-triggers)
|
||||
6. [Best Practices](#best-practices)
|
||||
|
||||
---
|
||||
@@ -110,13 +110,13 @@ When primary tool fails or is unavailable:
|
||||
|
||||
### Universal Prompt Template
|
||||
|
||||
```
|
||||
PURPOSE: [what] + [why] + [success criteria] + [constraints/scope]
|
||||
```bash
|
||||
ccw cli -p "PURPOSE: [what] + [why] + [success criteria] + [constraints/scope]
|
||||
TASK: • [step 1: specific action] • [step 2: specific action] • [step 3: specific action]
|
||||
MODE: [analysis|write]
|
||||
CONTEXT: @[file patterns] | Memory: [session/tech/module context]
|
||||
EXPECTED: [deliverable format] + [quality criteria] + [structure requirements]
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/[mode]-protocol.md) $(cat ~/.claude/workflows/cli-templates/prompts/[category]/[template].txt) | [domain constraints]
|
||||
CONSTRAINTS: [domain constraints]" --tool <tool-id> --mode <analysis|write> --rule <category-template>
|
||||
```
|
||||
|
||||
### Intent Capture Checklist (Before CLI Execution)
|
||||
@@ -165,11 +165,11 @@ Every command MUST include these fields:
|
||||
- Bad Example: "Report"
|
||||
- Good Example: "Markdown report with: severity levels (Critical/High/Medium/Low), file:line references, remediation code snippets, priority ranking"
|
||||
|
||||
- **RULES**
|
||||
- Purpose: Protocol + template + constraints
|
||||
- Components: $(cat protocol) + $(cat template) + domain rules
|
||||
- Bad Example: (missing)
|
||||
- Good Example: "$(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md) $(cat ~/.claude/workflows/cli-templates/prompts/analysis/03-assess-security-risks.txt) \| Focus on authentication \| Ignore test files"
|
||||
- **CONSTRAINTS**
|
||||
- Purpose: Domain-specific constraints
|
||||
- Components: Scope limits, special requirements, focus areas
|
||||
- Bad Example: (missing or too vague)
|
||||
- Good Example: "Focus on authentication | Ignore test files | No breaking changes"
|
||||
|
||||
### CONTEXT Configuration
|
||||
|
||||
@@ -204,7 +204,11 @@ Memory: Integration with auth module, using shared error patterns from @shared/u
|
||||
For complex requirements, discover files BEFORE CLI execution:
|
||||
|
||||
```bash
|
||||
# Step 1: Discover files
|
||||
# Step 1: Discover files (choose one method)
|
||||
# Method A: ACE semantic search (recommended)
|
||||
mcp__ace-tool__search_context(project_root_path="/path", query="React components with export")
|
||||
|
||||
# Method B: Ripgrep pattern search
|
||||
rg "export.*Component" --files-with-matches --type ts
|
||||
|
||||
# Step 2: Build CONTEXT
|
||||
@@ -214,108 +218,60 @@ CONTEXT: @components/Auth.tsx @types/auth.d.ts | Memory: Previous type refactori
|
||||
ccw cli -p "..." --tool <tool-id> --mode analysis --cd src
|
||||
```
|
||||
|
||||
### RULES Configuration
|
||||
### --rule Configuration
|
||||
|
||||
**Format**: `RULES: $(cat ~/.claude/workflows/cli-templates/prompts/[category]/[template].txt) | [constraints]`
|
||||
**Use `--rule` option to auto-load templates**:
|
||||
|
||||
**⚠️ MANDATORY**: Exactly ONE template reference is REQUIRED. Select from Task-Template Matrix or use universal fallback:
|
||||
- `universal/00-universal-rigorous-style.txt` - For precision-critical tasks (default fallback)
|
||||
- `universal/00-universal-creative-style.txt` - For exploratory tasks
|
||||
|
||||
**Command Substitution Rules**:
|
||||
- Use `$(cat ...)` directly in **double quotes** - command substitution executes in your local shell BEFORE passing to ccw
|
||||
- Shell expands `$(cat ...)` into file content automatically - do NOT read template content first
|
||||
- NEVER use escape characters (`\$`, `\"`, `\'`) or single quotes - these prevent shell expansion
|
||||
- Tilde (`~`) expands correctly in prompt context
|
||||
|
||||
**Critical**: Use double quotes `"..."` around the entire prompt to enable `$(cat ...)` expansion:
|
||||
```bash
|
||||
# ✓ CORRECT - double quotes allow shell expansion
|
||||
ccw cli -p "RULES: $(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md) ..." --tool <tool-id>
|
||||
|
||||
# ✗ WRONG - single quotes prevent expansion
|
||||
ccw cli -p 'RULES: $(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md) ...' --tool <tool-id>
|
||||
|
||||
# ✗ WRONG - escaped $ prevents expansion
|
||||
ccw cli -p "RULES: \$(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md) ..." --tool <tool-id>
|
||||
ccw cli -p "..." --tool gemini --mode analysis --rule analysis-review-architecture
|
||||
```
|
||||
|
||||
### Mode Protocol References (MANDATORY)
|
||||
### Mode Protocol References
|
||||
|
||||
**⚠️ REQUIRED**: Every CLI execution MUST include the corresponding mode protocol in RULES:
|
||||
|
||||
#### Mode Rule Templates
|
||||
|
||||
**Purpose**: Mode protocols define permission boundaries and operational constraints for each execution mode.
|
||||
**`--rule` auto-loads Protocol based on mode**:
|
||||
- `--mode analysis` → analysis-protocol.md
|
||||
- `--mode write` → write-protocol.md
|
||||
|
||||
**Protocol Mapping**:
|
||||
|
||||
- **`analysis`** mode
|
||||
- Protocol: `$(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md)`
|
||||
- Permission: Read-only operations
|
||||
- Enforces: No file creation/modification/deletion
|
||||
- Permission: Read-only
|
||||
- Constraint: No file create/modify/delete
|
||||
|
||||
- **`write`** mode
|
||||
- Protocol: `$(cat ~/.claude/workflows/cli-templates/protocols/write-protocol.md)`
|
||||
- Permission: Create/Modify/Delete files
|
||||
- Enforces: Explicit write authorization and full workflow execution capability
|
||||
|
||||
**RULES Format** (protocol MUST be included):
|
||||
```bash
|
||||
# Analysis mode - MUST include analysis-protocol.md
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md) $(cat ~/.claude/workflows/cli-templates/prompts/analysis/...) | constraints
|
||||
|
||||
# Write mode - MUST include write-protocol.md
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/write-protocol.md) $(cat ~/.claude/workflows/cli-templates/prompts/development/...) | constraints
|
||||
```
|
||||
|
||||
**Validation**: CLI execution without mode protocol reference is INVALID
|
||||
|
||||
**Why Mode Rules Are Required**:
|
||||
- Ensures consistent permission enforcement across all tools
|
||||
- Prevents accidental file modifications during analysis tasks
|
||||
- Provides explicit authorization trail for write operations
|
||||
- Enables safe automation with clear boundaries
|
||||
- Constraint: Full workflow execution
|
||||
|
||||
### Template System
|
||||
|
||||
**Base Path**: `~/.claude/workflows/cli-templates/prompts/`
|
||||
**Available `--rule` template names**:
|
||||
|
||||
**Naming Convention**:
|
||||
- `00-*` - Universal fallbacks (when no specific match)
|
||||
- `01-*` - Universal, high-frequency
|
||||
- `02-*` - Common specialized
|
||||
- `03-*` - Domain-specific
|
||||
|
||||
**Universal Templates**:
|
||||
|
||||
- **`universal/00-universal-rigorous-style.txt`**: Precision-critical, systematic methodology
|
||||
- **`universal/00-universal-creative-style.txt`**: Exploratory, innovative solutions
|
||||
|
||||
**Task-Template Matrix**:
|
||||
**Universal**:
|
||||
- `universal-rigorous-style` - Precise tasks
|
||||
- `universal-creative-style` - Exploratory tasks
|
||||
|
||||
**Analysis**:
|
||||
- Execution Tracing: `analysis/01-trace-code-execution.txt`
|
||||
- Bug Diagnosis: `analysis/01-diagnose-bug-root-cause.txt`
|
||||
- Code Patterns: `analysis/02-analyze-code-patterns.txt`
|
||||
- Document Analysis: `analysis/02-analyze-technical-document.txt`
|
||||
- Architecture Review: `analysis/02-review-architecture.txt`
|
||||
- Code Review: `analysis/02-review-code-quality.txt`
|
||||
- Performance: `analysis/03-analyze-performance.txt`
|
||||
- Security: `analysis/03-assess-security-risks.txt`
|
||||
- `analysis-trace-code-execution` - Execution tracing
|
||||
- `analysis-diagnose-bug-root-cause` - Bug diagnosis
|
||||
- `analysis-analyze-code-patterns` - Code patterns
|
||||
- `analysis-analyze-technical-document` - Document analysis
|
||||
- `analysis-review-architecture` - Architecture review
|
||||
- `analysis-review-code-quality` - Code review
|
||||
- `analysis-analyze-performance` - Performance analysis
|
||||
- `analysis-assess-security-risks` - Security assessment
|
||||
|
||||
**Planning**:
|
||||
- Architecture: `planning/01-plan-architecture-design.txt`
|
||||
- Task Breakdown: `planning/02-breakdown-task-steps.txt`
|
||||
- Component Design: `planning/02-design-component-spec.txt`
|
||||
- Migration: `planning/03-plan-migration-strategy.txt`
|
||||
- `planning-plan-architecture-design` - Architecture design
|
||||
- `planning-breakdown-task-steps` - Task breakdown
|
||||
- `planning-design-component-spec` - Component design
|
||||
- `planning-plan-migration-strategy` - Migration strategy
|
||||
|
||||
**Development**:
|
||||
- Feature: `development/02-implement-feature.txt`
|
||||
- Refactoring: `development/02-refactor-codebase.txt`
|
||||
- Tests: `development/02-generate-tests.txt`
|
||||
- UI Component: `development/02-implement-component-ui.txt`
|
||||
- Debugging: `development/03-debug-runtime-issues.txt`
|
||||
- `development-implement-feature` - Feature implementation
|
||||
- `development-refactor-codebase` - Code refactoring
|
||||
- `development-generate-tests` - Test generation
|
||||
- `development-implement-component-ui` - UI component
|
||||
- `development-debug-runtime-issues` - Runtime debugging
|
||||
|
||||
---
|
||||
|
||||
@@ -336,10 +292,13 @@ RULES: $(cat ~/.claude/workflows/cli-templates/protocols/write-protocol.md) $(ca
|
||||
- **`review`**
|
||||
- Permission: Read-only (code review output)
|
||||
- Use For: Git-aware code review of uncommitted changes, branch diffs, specific commits
|
||||
- Specification: **codex only** - uses `codex review` subcommand with `--uncommitted` by default
|
||||
- Specification: **codex only** - uses `codex review` subcommand
|
||||
- Tool Behavior:
|
||||
- `codex`: Executes `codex review --uncommitted [prompt]` for structured code review
|
||||
- `codex`: Executes `codex review` for structured code review
|
||||
- Other tools (gemini/qwen/claude): Accept mode but no operation change (treated as analysis)
|
||||
- **Constraint**: Target flags (`--uncommitted`, `--base`, `--commit`) and prompt are mutually exclusive
|
||||
- With prompt only: `ccw cli -p "Focus on security" --tool codex --mode review` (reviews uncommitted by default)
|
||||
- With target flag only: `ccw cli --tool codex --mode review --commit abc123` (no prompt allowed)
|
||||
|
||||
### Command Options
|
||||
|
||||
@@ -368,6 +327,11 @@ RULES: $(cat ~/.claude/workflows/cli-templates/protocols/write-protocol.md) $(ca
|
||||
- Description: Resume previous session
|
||||
- Default: -
|
||||
|
||||
- **`--rule <template>`**
|
||||
- Description: Template name, auto-loads protocol + template appended to prompt
|
||||
- Default: universal-rigorous-style
|
||||
- Auto-selects protocol based on --mode
|
||||
|
||||
### Directory Configuration
|
||||
|
||||
#### Working Directory (`--cd`)
|
||||
@@ -429,62 +393,60 @@ ASSISTANT RESPONSE: [Previous output]
|
||||
|
||||
**Analysis Task** (Security Audit):
|
||||
```bash
|
||||
ccw cli -p "
|
||||
PURPOSE: Identify OWASP Top 10 vulnerabilities in authentication module to pass security audit; success = all critical/high issues documented with remediation
|
||||
ccw cli -p "PURPOSE: Identify OWASP Top 10 vulnerabilities in authentication module to pass security audit; success = all critical/high issues documented with remediation
|
||||
TASK: • Scan for injection flaws (SQL, command, LDAP) • Check authentication bypass vectors • Evaluate session management • Assess sensitive data exposure
|
||||
MODE: analysis
|
||||
CONTEXT: @src/auth/**/* @src/middleware/auth.ts | Memory: Using bcrypt for passwords, JWT for sessions
|
||||
EXPECTED: Security report with: severity matrix, file:line references, CVE mappings where applicable, remediation code snippets prioritized by risk
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md) $(cat ~/.claude/workflows/cli-templates/prompts/analysis/03-assess-security-risks.txt) | Focus on authentication | Ignore test files
|
||||
" --tool <tool-id> --mode analysis --cd src/auth
|
||||
CONSTRAINTS: Focus on authentication | Ignore test files
|
||||
" --tool gemini --mode analysis --rule analysis-assess-security-risks --cd src/auth
|
||||
```
|
||||
|
||||
**Implementation Task** (New Feature):
|
||||
```bash
|
||||
ccw cli -p "
|
||||
PURPOSE: Implement rate limiting for API endpoints to prevent abuse; must be configurable per-endpoint; backward compatible with existing clients
|
||||
ccw cli -p "PURPOSE: Implement rate limiting for API endpoints to prevent abuse; must be configurable per-endpoint; backward compatible with existing clients
|
||||
TASK: • Create rate limiter middleware with sliding window • Implement per-route configuration • Add Redis backend for distributed state • Include bypass for internal services
|
||||
MODE: write
|
||||
CONTEXT: @src/middleware/**/* @src/config/**/* | Memory: Using Express.js, Redis already configured, existing middleware pattern in auth.ts
|
||||
EXPECTED: Production-ready code with: TypeScript types, unit tests, integration test, configuration example, migration guide
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/write-protocol.md) $(cat ~/.claude/workflows/cli-templates/prompts/development/02-implement-feature.txt) | Follow existing middleware patterns | No breaking changes
|
||||
" --tool <tool-id> --mode write
|
||||
CONSTRAINTS: Follow existing middleware patterns | No breaking changes
|
||||
" --tool gemini --mode write --rule development-implement-feature
|
||||
```
|
||||
|
||||
**Bug Fix Task**:
|
||||
```bash
|
||||
ccw cli -p "
|
||||
PURPOSE: Fix memory leak in WebSocket connection handler causing server OOM after 24h; root cause must be identified before any fix
|
||||
ccw cli -p "PURPOSE: Fix memory leak in WebSocket connection handler causing server OOM after 24h; root cause must be identified before any fix
|
||||
TASK: • Trace connection lifecycle from open to close • Identify event listener accumulation • Check cleanup on disconnect • Verify garbage collection eligibility
|
||||
MODE: analysis
|
||||
CONTEXT: @src/websocket/**/* @src/services/connection-manager.ts | Memory: Using ws library, ~5000 concurrent connections in production
|
||||
EXPECTED: Root cause analysis with: memory profile, leak source (file:line), fix recommendation with code, verification steps
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md) $(cat ~/.claude/workflows/cli-templates/prompts/analysis/01-diagnose-bug-root-cause.txt) | Focus on resource cleanup
|
||||
" --tool <tool-id> --mode analysis --cd src
|
||||
CONSTRAINTS: Focus on resource cleanup
|
||||
" --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause --cd src
|
||||
```
|
||||
|
||||
**Refactoring Task**:
|
||||
```bash
|
||||
ccw cli -p "
|
||||
PURPOSE: Refactor payment processing to use strategy pattern for multi-gateway support; no functional changes; all existing tests must pass
|
||||
ccw cli -p "PURPOSE: Refactor payment processing to use strategy pattern for multi-gateway support; no functional changes; all existing tests must pass
|
||||
TASK: • Extract gateway interface from current implementation • Create strategy classes for Stripe, PayPal • Implement factory for gateway selection • Migrate existing code to use strategies
|
||||
MODE: write
|
||||
CONTEXT: @src/payments/**/* @src/types/payment.ts | Memory: Currently only Stripe, adding PayPal next sprint, must support future gateways
|
||||
EXPECTED: Refactored code with: strategy interface, concrete implementations, factory class, updated tests, migration checklist
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/protocols/write-protocol.md) $(cat ~/.claude/workflows/cli-templates/prompts/development/02-refactor-codebase.txt) | Preserve all existing behavior | Tests must pass
|
||||
" --tool <tool-id> --mode write
|
||||
CONSTRAINTS: Preserve all existing behavior | Tests must pass
|
||||
" --tool gemini --mode write --rule development-refactor-codebase
|
||||
```
|
||||
|
||||
**Code Review Task** (codex review mode):
|
||||
```bash
|
||||
# Review uncommitted changes (default)
|
||||
# Option 1: Custom prompt (reviews uncommitted changes by default)
|
||||
ccw cli -p "Focus on security vulnerabilities and error handling" --tool codex --mode review
|
||||
|
||||
# Review with custom instructions
|
||||
ccw cli -p "Check for breaking changes in API contracts and backward compatibility" --tool codex --mode review
|
||||
# Option 2: Target flag only (no prompt allowed with target flags)
|
||||
ccw cli --tool codex --mode review --uncommitted
|
||||
ccw cli --tool codex --mode review --base main
|
||||
ccw cli --tool codex --mode review --commit abc123
|
||||
```
|
||||
|
||||
> **Note**: `--mode review` only triggers special behavior for `codex` tool (uses `codex review --uncommitted`). Other tools accept the mode but execute as standard analysis.
|
||||
> **Note**: `--mode review` only triggers special behavior for `codex` tool. Target flags (`--uncommitted`, `--base`, `--commit`) and prompt are **mutually exclusive** - use one or the other, not both.
|
||||
|
||||
---
|
||||
|
||||
@@ -500,6 +462,41 @@ ccw cli -p "Check for breaking changes in API contracts and backward compatibili
|
||||
|
||||
---
|
||||
|
||||
## Auto-Invoke Triggers
|
||||
|
||||
**Proactive CLI invocation** - Auto-invoke `ccw cli` when encountering these scenarios:
|
||||
|
||||
| Trigger Condition | Suggested Rule | When to Use |
|
||||
|-------------------|----------------|-------------|
|
||||
| **Self-repair fails** | `analysis-diagnose-bug-root-cause` | After 1+ failed fix attempts |
|
||||
| **Ambiguous requirements** | `planning-breakdown-task-steps` | Task description lacks clarity |
|
||||
| **Architecture decisions** | `planning-plan-architecture-design` | Complex feature needs design |
|
||||
| **Pattern uncertainty** | `analysis-analyze-code-patterns` | Unsure of existing conventions |
|
||||
| **Critical code paths** | `analysis-assess-security-risks` | Security/performance sensitive |
|
||||
|
||||
### Execution Principles
|
||||
|
||||
- **Default mode**: `--mode analysis` (read-only, safe for auto-execution)
|
||||
- **No confirmation needed**: Invoke proactively when triggers match
|
||||
- **Wait for results**: Complete analysis before next action
|
||||
- **Tool selection**: Use context-appropriate tool or fallback chain (`gemini` → `qwen` → `codex`)
|
||||
- **Rule flexibility**: Suggested rules are guidelines, not requirements - choose the most appropriate template for the situation
|
||||
|
||||
### Example: Bug Fix with Auto-Invoke
|
||||
|
||||
```bash
|
||||
# After 1+ failed fix attempts, auto-invoke root cause analysis
|
||||
ccw cli -p "PURPOSE: Identify root cause of [bug description]; success = actionable fix strategy
|
||||
TASK: • Trace execution flow • Identify failure point • Analyze state at failure • Determine fix approach
|
||||
MODE: analysis
|
||||
CONTEXT: @src/module/**/* | Memory: Previous fix attempts failed at [location]
|
||||
EXPECTED: Root cause analysis with: failure mechanism, stack trace interpretation, fix recommendation with code
|
||||
CONSTRAINTS: Focus on [specific area]
|
||||
" --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Core Principles
|
||||
@@ -509,16 +506,15 @@ ccw cli -p "Check for breaking changes in API contracts and backward compatibili
|
||||
- **Use tools early and often** - Tools are faster and more thorough
|
||||
- **Unified CLI** - Always use `ccw cli -p` for consistent parameter handling
|
||||
- **Default mode is analysis** - Omit `--mode` for read-only operations, explicitly use `--mode write` for file modifications
|
||||
- **One template required** - ALWAYS reference exactly ONE template in RULES (use universal fallback if no specific match)
|
||||
- **Use `--rule` for templates** - Auto-loads protocol + template appended to prompt
|
||||
- **Write protection** - Require EXPLICIT `--mode write` for file operations
|
||||
- **Use double quotes for shell expansion** - Always wrap prompts in double quotes `"..."` to enable `$(cat ...)` command substitution; NEVER use single quotes or escape characters (`\$`, `\"`, `\'`)
|
||||
|
||||
### Workflow Principles
|
||||
|
||||
- **Use CCW unified interface** for all executions
|
||||
- **Always include template** - Use Task-Template Matrix or universal fallback
|
||||
- **Always include template** - Use `--rule <template-name>` to load templates
|
||||
- **Be specific** - Clear PURPOSE, TASK, EXPECTED fields
|
||||
- **Include constraints** - File patterns, scope in RULES
|
||||
- **Include constraints** - File patterns, scope in CONSTRAINTS
|
||||
- **Leverage memory context** when building on previous work
|
||||
- **Discover patterns first** - Use rg/MCP before CLI execution
|
||||
- **Default to full context** - Use `@**/*` unless specific files needed
|
||||
@@ -530,8 +526,8 @@ ccw cli -p "Check for breaking changes in API contracts and backward compatibili
|
||||
- [ ] **Context gathered** - File references + memory (default `@**/*`)
|
||||
- [ ] **Directory navigation** - `--cd` and/or `--includeDirs`
|
||||
- [ ] **Tool selected** - Explicit `--tool` or tag-based auto-selection
|
||||
- [ ] **Template applied (REQUIRED)** - Use specific or universal fallback template
|
||||
- [ ] **Constraints specified** - Scope, requirements
|
||||
- [ ] **Rule template** - `--rule <template-name>` loads template
|
||||
- [ ] **Constraints** - Domain constraints in CONSTRAINTS field
|
||||
|
||||
### Execution Workflow
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user