Enhance CCW Orchestrator with Requirement Analysis Features

- Updated SKILL.md to reflect new requirement analysis capabilities, including input analysis and clarity scoring.
- Expanded issue workflow in issue.md to include discovery and creation phases, along with detailed command references.
- Introduced requirement analysis specification in requirement-analysis.md, outlining clarity scoring, dimension extraction, and validation processes.
- Added output templates specification in output-templates.md for consistent user experience across classification, planning, clarification, execution, and summary outputs.
This commit is contained in:
catlog22
2026-01-14 20:15:42 +08:00
parent 959d60b31f
commit 1f5ce9c03a
5 changed files with 1015 additions and 157 deletions

View File

@@ -12,21 +12,22 @@ allowed-tools: Task(*), SlashCommand(*), AskUserQuestion(*), Read(*), Bash(*), G
```
┌─────────────────────────────────────────────────────────────────┐
│ CCW Orchestrator (Stateless)
│ CCW Orchestrator (Stateless + Requirement Analysis)
├─────────────────────────────────────────────────────────────────┤
│ │
│ Input Analysis
│ Input Analysis & Requirement Extraction
│ ├─ Intent Classification (bugfix/feature/refactor/issue/...) │
│ ├─ Complexity Assessment (low/medium/high) │
│ ├─ Context Detection (codebase familiarity needed?)
│ ├─ Dimension Extraction (WHAT/WHERE/WHY/HOW)
│ ├─ Clarity Scoring (0-3) with auto-clarification │
│ └─ Constraint Extraction (time/scope/quality) │
│ │
│ Workflow Selection (Decision Tree) │
│ ├─ 🐛 Bug? → lite-fix / lite-fix --hotfix │
│ ├─ ❓ Unclear? → brainstorm → plan → execute
│ ├─ ❓ Unclear? → clarify → brainstorm → plan → execute │
│ ├─ ⚡ Simple? → lite-plan → lite-execute │
│ ├─ 🔧 Complex? → plan → execute │
│ ├─ 📋 Issue? → issue:plan → issue:queue → issue:execute │
│ ├─ 📋 Issue? → discover → plan → queue → execute
│ └─ 🎨 UI? → ui-design → plan → execute │
│ │
│ Execution Dispatch │
@@ -70,12 +71,16 @@ allowed-tools: Task(*), SlashCommand(*), AskUserQuestion(*), Read(*), Bash(*), G
- 根因不清楚需要诊断
### 5. Issue (长时间多点修复) 📌
**Pattern**: Issue规划 + 队列 + 批量执行
**Commands**: `/issue:plan``/issue:queue``/issue:execute`
**Pattern**: 发现 + 创建 + 规划 + 队列 + 批量执行
**Commands**:
- 完整链: `/issue:discover``/issue:new``/issue:plan``/issue:queue``/issue:execute`
- 快速链: `/issue:plan``/issue:queue``/issue:execute`
- 提示发现: `/issue:discover-by-prompt``/issue:plan``/issue:queue``/issue:execute`
**When to use**:
- 多个相关问题需要批量处理
- 长时间跨度的修复任务
- 需要优先级排序和冲突解决
- 安全审计、技术债务清理、GitHub Issues 批量导入
### 6. UI-First (设计驱动) 🎨
**Pattern**: UI设计 + 规划 + 执行
@@ -415,13 +420,15 @@ TodoWrite({
| Document | Purpose |
|----------|---------|
| [phases/orchestrator.md](phases/orchestrator.md) | 编排器决策逻辑 + TODO 跟踪 |
| [phases/orchestrator.md](phases/orchestrator.md) | 编排器决策逻辑 + 澄清流程 + TODO 跟踪 |
| [phases/actions/rapid.md](phases/actions/rapid.md) | 快速迭代组合 |
| [phases/actions/full.md](phases/actions/full.md) | 完整流程组合 |
| [phases/actions/coupled.md](phases/actions/coupled.md) | 复杂耦合组合 |
| [phases/actions/bugfix.md](phases/actions/bugfix.md) | 缺陷修复组合 |
| [phases/actions/issue.md](phases/actions/issue.md) | Issue工作流组合 |
| [phases/actions/issue.md](phases/actions/issue.md) | Issue工作流组合 (完整链路) |
| [specs/intent-classification.md](specs/intent-classification.md) | 意图分类规范 |
| [specs/requirement-analysis.md](specs/requirement-analysis.md) | 需求分析规范 (NEW) |
| [specs/output-templates.md](specs/output-templates.md) | 输出格式模板 (NEW) |
| [WORKFLOW_DECISION_GUIDE.md](/WORKFLOW_DECISION_GUIDE.md) | 工作流决策指南 |
## Examples

View File

@@ -1,201 +1,335 @@
# Action: Issue Workflow
Issue 批量处理工作流:规划 + 队列 + 批量执行
Issue 批量处理工作流:发现 → 创建 → 规划 队列 批量执行
## Pattern
## Complete Workflow Pattern
```
issue:plan → issue:queue → issue:execute
┌─────────────────────────────────────────────────────────────────┐
│ Issue Workflow - Complete Chain │
├─────────────────────────────────────────────────────────────────┤
│ │
│ Discovery Phase (Optional) │
│ ├─ /issue:discover - 多视角问题发现 │
│ └─ /issue:discover-by-prompt - 基于提示的迭代发现 │
│ │
│ Creation Phase │
│ └─ /issue:new - 创建结构化 Issue │
│ │
│ Planning Phase │
│ └─ /issue:plan - 生成解决方案 │
│ │
│ Queue Phase │
│ └─ /issue:queue - 冲突分析 + 队列构建 │
│ │
│ Execution Phase │
│ └─ /issue:execute - DAG 并行执行 │
│ │
└─────────────────────────────────────────────────────────────────┘
```
## Workflow Patterns
### Pattern 1: Full Discovery Flow
```
/issue:discover → /issue:new → /issue:plan → /issue:queue → /issue:execute
```
**Use when**: 不知道有什么问题,需要全面发现
### Pattern 2: Prompt-Driven Discovery
```
/issue:discover-by-prompt → /issue:plan → /issue:queue → /issue:execute
```
**Use when**: 有特定方向的问题探索
### Pattern 3: Direct Planning (Default)
```
/issue:plan → /issue:queue → /issue:execute
```
**Use when**: 已有明确的 Issue 列表
### Pattern 4: GitHub Import
```
/issue:new (GitHub URL) → /issue:plan → /issue:queue → /issue:execute
```
**Use when**: 从 GitHub Issues 导入
## Command Reference
### /issue:discover
多视角问题发现,支持 8 种视角的并行探索。
**视角列表**:
| Perspective | Description | Agent Type |
|-------------|-------------|------------|
| bug | 功能缺陷和错误 | CLI explore |
| ux | 用户体验问题 | CLI explore |
| test | 测试覆盖缺口 | CLI explore |
| quality | 代码质量问题 | CLI explore |
| security | 安全漏洞 | CLI explore + Exa |
| performance | 性能瓶颈 | CLI explore |
| maintainability | 可维护性问题 | CLI explore |
| best-practices | 最佳实践偏离 | CLI explore + Exa |
**输出**: `.workflow/issues/discoveries/` 下的发现报告
**调用方式**:
```bash
/issue:discover # 全视角发现
/issue:discover --perspectives security,performance # 指定视角
```
### /issue:discover-by-prompt
基于用户提示的智能发现,使用 Gemini 规划迭代探索策略。
**核心能力**:
- ACE 语义搜索上下文收集
- 跨模块比较(如 API 契约一致性)
- 多轮迭代探索直到收敛
**调用方式**:
```bash
/issue:discover-by-prompt "检查前端后端API契约一致性"
```
### /issue:new
从 GitHub URL 或文本描述创建结构化 Issue。
**清晰度检测** (0-3分):
| Score | Level | Action |
|-------|-------|--------|
| 0 | 无法理解 | 必须澄清 |
| 1 | 基本理解 | 建议澄清 |
| 2 | 清晰 | 直接创建 |
| 3 | 详细 | 直接创建 |
**调用方式**:
```bash
/issue:new https://github.com/user/repo/issues/123 # GitHub 导入
/issue:new "登录页面在移动端显示异常" # 文本创建
```
**输出**: `.workflow/issues/issues.jsonl` 追加新 Issue
### /issue:plan
为每个 Issue 生成解决方案,使用 `issue-plan-agent`
**核心流程**:
1. 加载未规划的 Issues
2. ACE 上下文探索
3. 生成 1-3 个解决方案/Issue
4. 用户选择绑定方案
**调用方式**:
```bash
/issue:plan # 规划所有未绑定 Issue
/issue:plan --issue ISS-001 # 规划特定 Issue
```
**输出**: `.workflow/issues/solutions/ISS-xxx.jsonl`
### /issue:queue
解决方案级别的队列构建冲突分析DAG 生成。
**使用 Agent**: `issue-queue-agent`
**冲突检测类型**:
| Type | Description | Severity | Resolution |
|------|-------------|----------|------------|
| file | 同文件修改 | Low | Sequential |
| api | API 签名变更 | Medium | Dependency ordering |
| data | 数据结构冲突 | High | User decision |
| dependency | 包依赖冲突 | Medium | Version negotiation |
| architecture | 架构方向冲突 | Critical | User decision |
**DAG 结构**:
```
execution_groups:
├── P1: Parallel (independent solutions)
├── S1: Sequential (depends on P1)
└── P2: Parallel (depends on S1)
```
**调用方式**:
```bash
/issue:queue # 构建队列
/issue:queue --dry-run # 预览冲突分析
```
**输出**: `.workflow/issues/queues/QUE-xxx.json`
### /issue:execute
DAG 并行执行编排器,单 worktree 策略。
**Executor 选项**:
| Executor | Best For | Mode |
|----------|----------|------|
| codex (recommended) | 代码实现 | Autonomous |
| gemini | 复杂分析 | Analysis first |
| agent | 灵活控制 | Supervised |
**执行策略**:
- 单 worktree 用于整个队列
- 按 solution 粒度分发
- 自动处理依赖顺序
- 支持断点续传
**调用方式**:
```bash
/issue:execute # 执行当前队列
/issue:execute --queue QUE-xxx # 执行特定队列
/issue:execute --resume # 恢复中断的执行
```
## Trigger Conditions
- Keywords: "issues", "batch", "queue", "多个", "批量"
- Multiple related problems
- Long-running fix campaigns
- Priority-based processing needed
CCW 自动识别以下关键词触发 Issue 工作流:
## Execution Flow
```javascript
const issuePatterns = {
// Batch processing
batch: /issues?|batch|queue|多个|批量|一批/i,
// Action requirement
action: /fix|resolve|处理|修复|解决/i,
// Discovery
discover: /discover|find|发现|检查|扫描|audit/i,
// GitHub specific
github: /github\.com\/.*\/issues/i
}
```mermaid
sequenceDiagram
participant U as User
participant O as CCW Orchestrator
participant IP as issue:plan
participant IQ as issue:queue
participant IE as issue:execute
U->>O: Multiple issues / batch fix
O->>O: Classify: issue
Note over IP: Phase 1: Issue Planning
O->>IP: /issue:plan
IP->>IP: Load unplanned issues
IP->>IP: Generate solutions per issue
IP->>U: Review solutions
U->>IP: Bind selected solutions
Note over IQ: Phase 2: Queue Formation
IP->>IQ: /issue:queue
IQ->>IQ: Conflict analysis
IQ->>IQ: Priority calculation
IQ->>IQ: DAG construction
IQ->>U: High-severity conflicts?
U->>IQ: Resolve conflicts
IQ->>IQ: Generate execution queue
Note over IE: Phase 3: Execution
IQ->>IE: /issue:execute
IE->>IE: DAG-based parallel execution
IE->>IE: Per-solution progress tracking
IE-->>U: Batch execution complete
// Trigger when: batch + action OR discover OR github
```
## When to Use
**Ideal scenarios**:
- 多个相关 Bug 需要批量修复
- GitHub Issues 批量处理
- 技术债务清理
- 安全漏洞批量修复
- 代码质量改进活动
**Avoid when**:
- 单一问题 → `/workflow:lite-fix`
- 独立不相关的任务 → 分别处理
- 紧急生产问题 → `/workflow:lite-fix --hotfix`
## Issue Lifecycle
```
draft → planned → queued → executing → completed
↓ ↓
skipped on-hold
┌───────┐ ┌────────┐ ┌────────┐ ┌───────────┐ ┌───────────┐
│ draft │ ──▶ │ planned│ ──▶ │ queued │ ──▶ │ executing │ ──▶ │ completed │
└───────┘ └────────┘ └────────┘ └───────────┘ └───────────┘
│ │
▼ ▼
┌─────────┐ ┌─────────┐
│ skipped │ │ on-hold │
└─────────┘ └─────────┘
```
## Conflict Types
| Type | Description | Resolution |
|------|-------------|------------|
| File | 多个解决方案修改同一文件 | Sequential execution |
| API | API 签名变更影响 | Dependency ordering |
| Data | 数据结构变更冲突 | User decision |
| Dependency | 包依赖冲突 | Version negotiation |
| Architecture | 架构方向冲突 | User decision (high severity) |
## Configuration
```javascript
const issueConfig = {
discover: {
perspectives: ['bug', 'ux', 'test', 'quality', 'security', 'performance', 'maintainability', 'best-practices'],
parallelExploration: true,
exaIntegration: ['security', 'best-practices']
},
create: {
clarityThreshold: 2, // Minimum clarity score to proceed
autoClarify: true, // Prompt for missing info
githubPublish: 'ask' // ask | always | never
},
plan: {
solutionsPerIssue: 3, // Generate up to 3 solutions
autoSelect: false, // User must bind solution
solutionsPerIssue: 3, // Generate up to 3 solutions
autoSelect: false, // User must bind solution
planningAgent: 'issue-plan-agent'
},
queue: {
conflictAnalysis: true,
priorityCalculation: true,
clarifyThreshold: 'high', // Ask user for high-severity conflicts
clarifyThreshold: 'high', // Ask user for high-severity conflicts
queueAgent: 'issue-queue-agent'
},
execute: {
dagParallel: true,
executionLevel: 'solution', // Execute by solution, not task
executionLevel: 'solution',
executor: 'codex',
resumable: true
}
}
```
## Example Invocations
```bash
# From GitHub Issues
ccw "批量处理所有 label:bug 的 GitHub Issues"
→ issue:new (import from GitHub)
→ issue:plan (generate solutions)
→ issue:queue (form execution queue)
→ issue:execute (batch execute)
# Tech debt cleanup
ccw "处理所有 TODO 注释和已知技术债务"
→ issue:discover (find issues)
→ issue:plan (plan solutions)
→ issue:queue (prioritize)
→ issue:execute (execute)
# Security vulnerabilities
ccw "修复所有 npm audit 报告的安全漏洞"
→ issue:new (from audit report)
→ issue:plan (upgrade strategies)
→ issue:queue (conflict resolution)
→ issue:execute (staged upgrades)
```
## Queue Structure
```json
{
"queue_id": "QUE-20251227-143000",
"status": "active",
"execution_groups": [
{
"id": "P1",
"type": "parallel",
"solutions": ["SOL-ISS-001-1", "SOL-ISS-002-1"],
"description": "Independent fixes, no file overlap"
},
{
"id": "S1",
"type": "sequential",
"solutions": ["SOL-ISS-003-1"],
"depends_on": ["P1"],
"description": "Depends on P1 completion"
}
]
}
```
## Output Artifacts
## Output Structure
```
.workflow/issues/
├── issues.jsonl # All issues (one per line)
├── issues.jsonl # All issues (append-only)
├── discoveries/
│ ├── DIS-xxx.json # Discovery session
│ └── reports/
│ ├── security.md
│ └── performance.md
├── solutions/
│ ├── ISS-001.jsonl # Solutions for ISS-001
│ ├── ISS-001.jsonl # Solutions for ISS-001
│ └── ISS-002.jsonl
├── queues/
│ ├── index.json # Queue index
│ └── QUE-xxx.json # Queue details
│ ├── index.json # Queue index
│ └── QUE-xxx.json # Queue details
└── execution/
└── {queue-id}/
├── progress.json
├── logs/
└── results/
```
## Progress Tracking
```javascript
// Real-time progress during execution
const progress = {
queue_id: "QUE-xxx",
total_solutions: 5,
completed: 2,
in_progress: 1,
pending: 2,
current_group: "P1",
eta: "15 minutes"
}
```
## Resume Capability
## Example Invocations
```bash
# If execution interrupted
ccw "继续执行 issue 队列"
Detects active queue: QUE-xxx
Resumes from last checkpoint
→ /issue:execute --resume
# Complete discovery flow
ccw "全面检查代码库问题并批量修复"
/issue:discover (全视角)
/issue:new (创建发现的问题)
→ /issue:plan (生成方案)
→ /issue:queue (构建队列)
→ /issue:execute (批量执行)
# Security audit
ccw "安全审计并修复所有漏洞"
→ /issue:discover --perspectives security
→ /issue:plan
→ /issue:queue
→ /issue:execute
# GitHub batch processing
ccw "处理所有 label:bug 的 GitHub Issues"
→ /issue:new (批量导入)
→ /issue:plan
→ /issue:queue
→ /issue:execute
# Tech debt cleanup
ccw "清理技术债务"
→ /issue:discover --perspectives quality,maintainability
→ /issue:plan
→ /issue:queue
→ /issue:execute
```
## Integration with CCW Orchestrator
在 orchestrator.md 中的集成点:
```javascript
// Intent classification
if (matchesIssuePattern(input)) {
// Determine entry point
if (hasDiscoveryIntent(input)) {
if (hasPromptDirection(input)) {
return { workflow: 'issue:discover-by-prompt → issue:plan → issue:queue → issue:execute' }
}
return { workflow: 'issue:discover → issue:plan → issue:queue → issue:execute' }
}
if (hasGitHubUrl(input)) {
return { workflow: 'issue:new → issue:plan → issue:queue → issue:execute' }
}
// Default: direct planning
return { workflow: 'issue:plan → issue:queue → issue:execute' }
}
```

View File

@@ -6,13 +6,14 @@
```
┌──────────────────────────────────────────────────────────────────┐
│ CCW Orchestrator (CLI-Enhanced)
│ CCW Orchestrator (CLI-Enhanced + Requirement Analysis)
├──────────────────────────────────────────────────────────────────┤
│ │
│ Phase 1: Input Analysis (Rule-Based, Fast Path) │
│ ├─ Parse input (natural language / explicit command) │
│ ├─ Classify intent (bugfix / feature / issue / ui / docs) │
─ Assess complexity (low / medium / high) │
─ Assess complexity (low / medium / high) │
│ └─ Extract requirement dimensions (WHAT/WHERE/WHY/HOW) │
│ │
│ Phase 1.5: CLI-Assisted Classification (Smart Path) │
│ ├─ Trigger: low match count / high complexity / long input │
@@ -20,6 +21,12 @@
│ ├─ Get confidence score and reasoning │
│ └─ Fallback to rule-based if CLI fails │
│ │
│ Phase 1.75: Requirement Clarification (NEW) │
│ ├─ Calculate clarity score (0-3) │
│ ├─ Trigger: clarity_score < 2 OR missing critical dimensions │
│ ├─ Generate targeted clarification questions │
│ └─ Refine requirement dimensions with user input │
│ │
│ Phase 2: Chain Selection │
│ ├─ Load index/workflow-chains.json │
│ ├─ Match intent → chain(s) │
@@ -49,6 +56,46 @@
└──────────────────────────────────────────────────────────────────┘
```
## Requirement Analysis Integration
See [specs/requirement-analysis.md](../specs/requirement-analysis.md) for full specification.
### Clarity Scoring
| Score | Level | Action |
|-------|-------|--------|
| 0 | 模糊 | 必须澄清 |
| 1 | 基本 | 建议澄清 |
| 2 | 清晰 | 可直接执行 |
| 3 | 详细 | 直接执行 |
### Dimension Extraction
```javascript
// Extract requirement dimensions during Phase 1
function extractDimensions(input) {
return {
what: extractWhat(input), // Action + Target
where: extractWhere(input), // Scope + Paths
why: extractWhy(input), // Goal + Motivation
how: extractHow(input), // Constraints + Preferences
clarity_score: 0, // Calculated later
missing_dimensions: [] // Identified later
}
}
```
## Output Templates Integration
See [specs/output-templates.md](../specs/output-templates.md) for full specification.
All output uses standardized templates for consistency:
- Classification Summary
- Requirement Analysis
- Planning Summary
- Execution Progress
- Workflow Complete
## CLI Enhancement Features
### Trigger Conditions
@@ -356,6 +403,181 @@ RULES: Output ONLY valid JSON without markdown code blocks. Be concise but accur
}
```
### Phase 1.75: Requirement Clarification
当需求不够清晰时,主动向用户发起澄清。
```javascript
// Requirement clarification for ambiguous inputs
async function clarifyRequirement(analysis, dimensions) {
// Skip if already clear
if (dimensions.clarity_score >= 2) {
return { needsClarification: false, dimensions }
}
// Skip for explicit commands
if (analysis.passthrough) {
return { needsClarification: false, dimensions }
}
console.log('### Requirement Clarification\n')
console.log('> Your request needs more detail. Let me ask a few questions.\n')
// Generate questions based on missing dimensions
const questions = generateClarificationQuestions(dimensions)
if (questions.length === 0) {
return { needsClarification: false, dimensions }
}
// Display current understanding
console.log(`
**Current Understanding**:
| Dimension | Value | Status |
|-----------|-------|--------|
| WHAT | ${dimensions.what.action || 'unknown'} ${dimensions.what.target || ''} | ${dimensions.what.target ? '✓' : '⚠'} |
| WHERE | ${dimensions.where.scope}: ${dimensions.where.paths?.join(', ') || 'unknown'} | ${dimensions.where.paths?.length ? '✓' : '⚠'} |
| WHY | ${dimensions.why.goal || 'not specified'} | ${dimensions.why.goal ? '✓' : '○'} |
| HOW | ${dimensions.how.constraints?.join(', ') || 'no constraints'} | ○ |
**Clarity Score**: ${dimensions.clarity_score}/3
`)
// Ask user for clarification (max 4 questions)
const responses = AskUserQuestion({
questions: questions.slice(0, 4)
})
// Refine dimensions with user responses
const refinedDimensions = refineDimensions(dimensions, responses)
refinedDimensions.clarity_score = Math.min(3, dimensions.clarity_score + 1)
console.log('> Requirements clarified. Proceeding with workflow selection.\n')
return { needsClarification: false, dimensions: refinedDimensions }
}
// Generate clarification questions based on missing info
function generateClarificationQuestions(dimensions) {
const questions = []
// WHAT: If target is unclear
if (!dimensions.what.target) {
questions.push({
question: "你想要对什么进行操作?",
header: "目标",
multiSelect: false,
options: [
{ label: "特定文件", description: "修改特定的文件或代码" },
{ label: "功能模块", description: "处理整个功能模块" },
{ label: "系统级", description: "架构或系统级变更" },
{ label: "让我指定", description: "我会提供具体说明" }
]
})
}
// WHERE: If scope is unknown
if (dimensions.where.scope === 'unknown' && !dimensions.where.paths?.length) {
questions.push({
question: "操作的范围是什么?",
header: "范围",
multiSelect: false,
options: [
{ label: "自动发现", description: "分析代码库后推荐相关位置" },
{ label: "当前目录", description: "只在当前工作目录" },
{ label: "全项目", description: "整个项目范围" },
{ label: "让我指定", description: "我会提供具体路径" }
]
})
}
// WHY: If goal is unclear for complex tasks
if (!dimensions.why.goal && dimensions.what.action !== 'analyze') {
questions.push({
question: "这个操作的主要目标是什么?",
header: "目标",
multiSelect: false,
options: [
{ label: "修复问题", description: "解决已知的Bug或错误" },
{ label: "新增功能", description: "添加新的能力或特性" },
{ label: "改进质量", description: "提升性能、可维护性" },
{ label: "代码审查", description: "检查和评估代码" }
]
})
}
// HOW: If constraints matter for the task
if (dimensions.what.action === 'refactor' || dimensions.what.action === 'create') {
questions.push({
question: "有什么特殊要求或限制?",
header: "约束",
multiSelect: true,
options: [
{ label: "保持兼容", description: "不破坏现有功能" },
{ label: "最小改动", description: "尽量少修改文件" },
{ label: "包含测试", description: "需要添加测试" },
{ label: "无特殊要求", description: "按最佳实践处理" }
]
})
}
return questions
}
// Refine dimensions based on user responses
function refineDimensions(dimensions, responses) {
const refined = { ...dimensions }
// Apply user selections to dimensions
if (responses['目标']) {
if (responses['目标'] === '特定文件') {
refined.where.scope = 'file'
} else if (responses['目标'] === '功能模块') {
refined.where.scope = 'module'
} else if (responses['目标'] === '系统级') {
refined.where.scope = 'system'
}
}
if (responses['范围']) {
if (responses['范围'] === '全项目') {
refined.where.scope = 'system'
} else if (responses['范围'] === '当前目录') {
refined.where.scope = 'module'
}
}
if (responses['目标']) {
const goalMapping = {
'修复问题': 'fix bug',
'新增功能': 'add feature',
'改进质量': 'improve quality',
'代码审查': 'code review'
}
refined.why.goal = goalMapping[responses['目标']] || responses['目标']
}
if (responses['约束']) {
const constraints = Array.isArray(responses['约束']) ? responses['约束'] : [responses['约束']]
refined.how.constraints = constraints.filter(c => c !== '无特殊要求')
}
// Update missing dimensions
refined.missing_dimensions = identifyMissing(refined)
return refined
}
// Identify still-missing dimensions
function identifyMissing(dimensions) {
const missing = []
if (!dimensions.what.target) missing.push('what.target')
if (dimensions.where.scope === 'unknown') missing.push('where.scope')
// why and how are optional
return missing
}
```
### Phase 2: Chain Selection
```javascript

View File

@@ -0,0 +1,258 @@
# Output Templates Specification
CCW 标准输出格式模板,确保一致的用户体验。
## Template Categories
| Category | Usage | Key Elements |
|----------|-------|--------------|
| Classification | Intent/complexity output | Intent, Complexity, Source |
| Planning | Chain selection output | Chain, Steps, Estimated time |
| Clarification | User interaction | Questions, Options, Context |
| Execution | Progress updates | Step, Status, Progress bar |
| Summary | Final results | Completed, Duration, Artifacts |
## Classification Output Template
```markdown
### Classification Summary
- **Source**: [Rule-Based|CLI-Assisted] ([confidence]% confidence)
- **Intent**: [intent_type] ([variant])
- **Complexity**: [low|medium|high]
- **Reasoning**: [brief explanation]
**Recommended Workflow**: [chain_name]
```
### Example
```markdown
### Classification Summary
- **Source**: CLI-Assisted (85% confidence)
- **Intent**: feature (implementation)
- **Complexity**: medium
- **Reasoning**: Request involves creating new functionality with moderate scope
**Recommended Workflow**: lite-plan → lite-execute
```
## Requirement Analysis Template
```markdown
### Requirement Analysis
**Input**: [truncated user input...]
| Dimension | Value | Status |
|-----------|-------|--------|
| WHAT | [action] [target] | ✓ extracted |
| WHERE | [scope]: [paths] | ✓ extracted |
| WHY | [goal] | ⚠ inferred |
| HOW | [constraints] | ✗ missing |
**Clarity Score**: [score]/3 ([level])
**Action**: [proceed|clarify|confirm]
```
## Planning Output Template
```markdown
### Workflow Planning
**Selected Chain**: [chain_name] ([chain_id])
**Description**: [chain_description]
**Complexity**: [chain_complexity]
**Estimated Time**: [estimated_time]
**Execution Steps**:
| # | Command | Auto | Description |
|---|---------|------|-------------|
| 1 | [command] | [Y/N] | [step description] |
| 2 | [command] | [Y/N] | [step description] |
**Risks**: [identified risks or "None identified"]
**Suggestions**: [optimization suggestions or "N/A"]
```
## Clarification Output Template
```markdown
### Clarification Needed
Your request needs more detail. Please help me understand:
**Missing Information**:
- [ ] [dimension]: [what's needed]
**Questions**:
[AskUserQuestion widget renders here]
```
## Execution Progress Template
```markdown
### Execution Progress
**Workflow**: [chain_name]
**Status**: [step N of M]
[████████░░░░░░░░] 50% (2/4 steps)
**Current Step**: [current command]
**Completed**:
- ✓ [step 1 command]
- ✓ [step 2 command]
**Pending**:
- ○ [step 3 command]
- ○ [step 4 command]
```
## Summary Output Template
```markdown
### Workflow Complete
**Chain**: [chain_name]
**Duration**: [elapsed time]
**Steps**: [completed]/[total]
**Results**:
| Step | Status | Notes |
|------|--------|-------|
| [command] | ✓ | [result notes] |
**Artifacts Generated**:
- [artifact path]
**Next Actions** (optional):
- [suggested follow-up]
```
## Error Output Template
```markdown
### Workflow Error
**Step**: [failed step command]
**Error**: [error message]
**Possible Causes**:
- [cause 1]
- [cause 2]
**Suggested Actions**:
1. [action 1]
2. [action 2]
Type `retry` to retry or `abort` to stop.
```
## Issue Workflow Templates
### Issue Discovery Output
```markdown
### Issue Discovery
**Perspectives Analyzed**: [list of perspectives]
**Issues Found**: [count]
| ID | Type | Severity | Location | Description |
|----|------|----------|----------|-------------|
| [ISS-xxx] | [type] | [severity] | [file:line] | [brief] |
**Recommended Next Step**: `/issue:new` or `/issue:plan`
```
### Issue Queue Output
```markdown
### Execution Queue
**Queue ID**: [QUE-xxx]
**Total Solutions**: [count]
**Execution Groups**: [count]
**Queue Structure**:
```
[P1] Parallel Group (2 solutions)
├─ SOL-001: [description]
└─ SOL-002: [description]
[S1] Sequential (depends on P1)
└─ SOL-003: [description]
```
**Conflicts Detected**: [count] ([severity level])
```
### Issue Execution Progress
```markdown
### Issue Execution
**Queue**: [QUE-xxx]
**Progress**: [completed]/[total] solutions
[████████░░░░░░░░] 50%
**Current Group**: [P1|S1|...]
**Executing**: [SOL-xxx] - [description]
**Completed**:
- ✓ SOL-001: [result]
- ✓ SOL-002: [result]
**ETA**: [estimated time remaining]
```
## Implementation Guide
```javascript
// Template rendering function
function renderTemplate(templateType, data) {
const templates = {
classification: renderClassification,
requirement: renderRequirement,
planning: renderPlanning,
clarification: renderClarification,
execution: renderExecution,
summary: renderSummary,
error: renderError
}
return templates[templateType](data)
}
// Example: Classification template
function renderClassification(data) {
return `### Classification Summary
- **Source**: ${data.source} ${data.confidence ? `(${Math.round(data.confidence * 100)}% confidence)` : ''}
- **Intent**: ${data.intent.type}${data.intent.variant ? ` (${data.intent.variant})` : ''}
- **Complexity**: ${data.complexity}
${data.reasoning ? `- **Reasoning**: ${data.reasoning}` : ''}
**Recommended Workflow**: ${data.workflow}`
}
// Progress bar helper
function renderProgressBar(completed, total, width = 16) {
const filled = Math.round((completed / total) * width)
const empty = width - filled
const percentage = Math.round((completed / total) * 100)
return `[${'█'.repeat(filled)}${'░'.repeat(empty)}] ${percentage}% (${completed}/${total})`
}
```
## Consistency Rules
1. **Headers**: Always use `###` for section headers
2. **Tables**: Use markdown tables for structured data
3. **Status Icons**: ✓ (done), ○ (pending), ⚠ (warning), ✗ (error)
4. **Progress**: Always show percentage and fraction
5. **Timing**: Show elapsed time in human-readable format
6. **Paths**: Show relative paths when possible

View File

@@ -0,0 +1,237 @@
# Requirement Analysis Specification
结构化需求分析规范:将用户输入分解为可操作的维度。
## Overview
```
┌─────────────────────────────────────────────────────────────────┐
│ Requirement Analysis Pipeline │
├─────────────────────────────────────────────────────────────────┤
│ │
│ Step 1: Clarity Assessment │
│ ├─ Score: 0-3 (0=模糊, 1=基本, 2=清晰, 3=详细) │
│ ├─ Missing dimensions detection │
│ └─ Trigger clarification if score < 2 │
│ │
│ Step 2: Dimension Extraction │
│ ├─ WHAT: 要做什么 (功能/修复/优化) │
│ ├─ WHERE: 在哪里做 (文件/模块/系统) │
│ ├─ WHY: 为什么做 (目标/动机) │
│ ├─ HOW: 怎么做 (约束/偏好) │
│ └─ WHEN: 时间/优先级约束 │
│ │
│ Step 3: Validation │
│ ├─ Check dimension completeness │
│ ├─ Detect conflicts │
│ └─ Generate structured requirement object │
│ │
└─────────────────────────────────────────────────────────────────┘
```
## Clarity Scoring
| Score | Level | Description | Action |
|-------|-------|-------------|--------|
| 0 | 模糊 | 无法理解用户意图 | 必须澄清 |
| 1 | 基本 | 知道做什么,缺少细节 | 建议澄清 |
| 2 | 清晰 | 意图和范围明确 | 可直接执行 |
| 3 | 详细 | 所有维度都已指定 | 直接执行 |
### Clarity Indicators
```javascript
const clarityIndicators = {
// Score +1 for each present
positive: [
/具体|specific|明确/i, // Explicit intent
/在\s*[\w\/]+\s*(文件|模块|目录)/i, // Location specified
/使用|用|采用|通过/i, // Method specified
/因为|为了|目的是/i, // Reason given
/不要|避免|禁止/i, // Constraints given
],
// Score -1 for each present
negative: [
/不知道|不确定|maybe|可能/i, // Uncertainty
/怎么办|如何|what should/i, // Seeking guidance
/帮我|help me/i, // Generic help
]
}
```
## Dimension Schema
```typescript
interface RequirementDimensions {
// WHAT dimension
what: {
action: 'create' | 'fix' | 'refactor' | 'optimize' | 'analyze' | 'review';
target: string; // What to act on
description: string; // Brief description
};
// WHERE dimension
where: {
scope: 'file' | 'module' | 'system' | 'unknown';
paths?: string[]; // Specific paths mentioned
patterns?: string[]; // File patterns mentioned
};
// WHY dimension
why: {
goal?: string; // End goal
motivation?: string; // Why now
success_criteria?: string; // How to know done
};
// HOW dimension
how: {
constraints?: string[]; // Must/Must not
preferences?: string[]; // Should/Should not
approach?: string; // Suggested approach
};
// Metadata
clarity_score: 0 | 1 | 2 | 3;
missing_dimensions: string[];
confidence: number; // 0.0 - 1.0
}
```
## Extraction Rules
### WHAT Extraction
```javascript
const whatPatterns = {
create: /创建|新增|添加|实现|生成|create|add|implement|generate/i,
fix: /修复|修正|解决|fix|repair|resolve|debug/i,
refactor: /重构|优化结构|重写|refactor|restructure|rewrite/i,
optimize: /优化|提升|改进|性能|optimize|improve|enhance|performance/i,
analyze: /分析|理解|探索|研究|analyze|understand|explore|research/i,
review: /审查|检查|评估|review|check|assess|audit/i
}
```
### WHERE Extraction
```javascript
const wherePatterns = {
file: /(\S+\.(ts|js|py|md|json|yaml|yml))/g,
module: /(src\/\S+|lib\/\S+|packages\/\S+)/g,
directory: /(\/[\w\-\.\/]+)/g
}
```
### Constraint Extraction
```javascript
const constraintPatterns = {
must: /必须|一定要|需要|must|required|need to/i,
must_not: /不要|禁止|不能|避免|must not|don't|avoid/i,
should: /应该|最好|建议|should|prefer|recommend/i,
should_not: /不应该|不建议|尽量不|should not|better not/i
}
```
## Clarification Flow
当 clarity_score < 2 时触发澄清流程:
```javascript
function generateClarificationQuestions(dimensions) {
const questions = []
if (!dimensions.what.target) {
questions.push({
question: "你想要对什么进行操作?",
header: "目标",
options: [
{ label: "文件/代码", description: "修改特定文件或代码" },
{ label: "功能/模块", description: "处理整个功能模块" },
{ label: "系统/架构", description: "系统级变更" }
]
})
}
if (!dimensions.where.paths?.length && dimensions.where.scope === 'unknown') {
questions.push({
question: "你想在哪里进行这个操作?",
header: "位置",
options: [
{ label: "让我指定", description: "我会提供具体路径" },
{ label: "自动发现", description: "分析代码库后推荐" },
{ label: "全局", description: "整个项目范围" }
]
})
}
if (!dimensions.why.goal) {
questions.push({
question: "这个操作的目标是什么?",
header: "目标",
options: [
{ label: "修复问题", description: "解决已知Bug或错误" },
{ label: "新增功能", description: "添加新的能力" },
{ label: "改进质量", description: "提升性能/可维护性" },
{ label: "其他", description: "其他目标" }
]
})
}
return questions
}
```
## Integration with Orchestrator
```javascript
// In orchestrator.md Phase 1: Input Analysis
function analyzeRequirement(userInput) {
// Step 1: Extract dimensions
const dimensions = extractDimensions(userInput)
// Step 2: Calculate clarity score
dimensions.clarity_score = calculateClarityScore(userInput, dimensions)
// Step 3: Identify missing dimensions
dimensions.missing_dimensions = identifyMissing(dimensions)
return dimensions
}
// In Phase 1.5: After CLI Classification
function shouldClarify(dimensions, intent) {
// Clarify if:
// 1. Clarity score < 2
// 2. High complexity with missing dimensions
// 3. Ambiguous intent
return (
dimensions.clarity_score < 2 ||
(intent.complexity === 'high' && dimensions.missing_dimensions.length > 0)
)
}
```
## Output Format
分析完成后输出结构化需求摘要:
```markdown
### Requirement Analysis
**Input**: [Original user input]
**Dimensions**:
| Dimension | Value | Source |
|-----------|-------|--------|
| WHAT | [action] [target] | extracted/inferred |
| WHERE | [scope]: [paths] | extracted/unknown |
| WHY | [goal] | extracted/missing |
| HOW | [constraints] | extracted/none |
**Clarity**: [score]/3 - [level description]
**Missing**: [list of missing dimensions]
**Action**: [proceed/clarify/confirm]
```