feat: Add multi-perspective issue discovery and structured issue creation

- Implemented issue discovery prompt to analyze code from various perspectives (bug, UX, test, quality, security, performance, maintainability, best-practices).
- Created structured issue generation prompt from GitHub URLs or text descriptions, including clarity detection and optional clarification questions.
- Introduced CCW Loop-B hybrid orchestrator pattern for iterative development, featuring a coordinator and specialized workers with batch wait support.
- Defined state management, session structure, and output schemas for the CCW Loop-B workflow.
- Added error handling and best practices documentation for the new features.
This commit is contained in:
catlog22
2026-01-22 22:53:05 +08:00
parent f5b6bb97bc
commit 9a3608173a
10 changed files with 2114 additions and 224 deletions

View File

@@ -0,0 +1,102 @@
# CCW Loop-B (Hybrid Orchestrator Pattern)
协调器 + 专用 worker 的迭代开发工作流。
## Overview
CCW Loop-B 采用混合模式设计:
- **Coordinator**: 状态管理、worker 调度、结果汇聚
- **Workers**: 专注各自领域develop/debug/validate
## Installation
```
.codex/skills/ccw-loop-b/
+-- SKILL.md # Main skill definition
+-- README.md # This file
+-- phases/
| +-- orchestrator.md # Coordinator logic
| +-- state-schema.md # State structure
+-- specs/
+-- action-catalog.md # Action catalog
.codex/agents/
+-- ccw-loop-b-init.md # Init worker
+-- ccw-loop-b-develop.md # Develop worker
+-- ccw-loop-b-debug.md # Debug worker
+-- ccw-loop-b-validate.md # Validate worker
+-- ccw-loop-b-complete.md # Complete worker
```
## Execution Modes
| Mode | Description | Use Case |
|------|-------------|----------|
| `interactive` | 用户选择 action | 复杂任务,需要人工决策 |
| `auto` | 自动顺序执行 | 标准开发流程 |
| `parallel` | 并行多维度分析 | 需要快速全面评估 |
## Usage
```bash
# Interactive (default)
/ccw-loop-b TASK="Implement feature X"
# Auto mode
/ccw-loop-b --mode=auto TASK="Fix bug Y"
# Parallel analysis
/ccw-loop-b --mode=parallel TASK="Analyze module Z"
# Resume
/ccw-loop-b --loop-id=loop-b-xxx
```
## Session Files
```
.loop/
+-- {loopId}.json # Master state
+-- {loopId}.workers/ # Worker outputs (JSON)
+-- {loopId}.progress/ # Human-readable progress (MD)
```
## Core Pattern
### Coordinator + Worker
```javascript
// Coordinator spawns specialized worker
const worker = spawn_agent({ message: buildWorkerPrompt(action) })
// Wait for completion
const result = wait({ ids: [worker], timeout_ms: 600000 })
// Process result
const output = result.status[worker].completed
updateState(output)
// Cleanup
close_agent({ id: worker })
```
### Batch Wait (Parallel Mode)
```javascript
// Spawn multiple workers
const workers = [
spawn_agent({ message: developPrompt }),
spawn_agent({ message: debugPrompt }),
spawn_agent({ message: validatePrompt })
]
// Batch wait
const results = wait({ ids: workers, timeout_ms: 900000 })
// Merge results
const merged = mergeOutputs(results)
```
## License
MIT

View File

@@ -0,0 +1,322 @@
---
description: Hybrid orchestrator pattern for iterative development. Coordinator + specialized workers with batch wait support. Triggers on "ccw-loop-b".
argument-hint: TASK="<task description>" [--loop-id=<id>] [--mode=<interactive|auto|parallel>]
---
# CCW Loop-B - Hybrid Orchestrator Pattern
协调器 + 专用 worker 的迭代开发工作流。支持单 agent 深度交互、多 agent 并行、混合模式灵活切换。
## Arguments
| Arg | Required | Description |
|-----|----------|-------------|
| TASK | No | Task description (for new loop) |
| --loop-id | No | Existing loop ID to continue |
| --mode | No | `interactive` (default) / `auto` / `parallel` |
## Architecture
```
+------------------------------------------------------------+
| Main Coordinator |
| 职责: 状态管理 + worker 调度 + 结果汇聚 + 用户交互 |
+------------------------------------------------------------+
|
+--------------------+--------------------+
| | |
v v v
+----------------+ +----------------+ +----------------+
| Worker-Develop | | Worker-Debug | | Worker-Validate|
| 专注: 代码实现 | | 专注: 问题诊断 | | 专注: 测试验证 |
+----------------+ +----------------+ +----------------+
```
## Execution Modes
### Mode: Interactive (default)
协调器展示菜单,用户选择 actionspawn 对应 worker 执行。
```
Coordinator -> Show menu -> User selects -> spawn worker -> wait -> Display result -> Loop
```
### Mode: Auto
自动按预设顺序执行worker 完成后自动切换到下一阶段。
```
Init -> Develop -> [if issues] Debug -> Validate -> [if fail] Loop back -> Complete
```
### Mode: Parallel
并行 spawn 多个 worker 分析不同维度batch wait 汇聚结果。
```
Coordinator -> spawn [develop, debug, validate] in parallel -> wait({ ids: all }) -> Merge -> Decide
```
## Session Structure
```
.loop/
+-- {loopId}.json # Master state
+-- {loopId}.workers/ # Worker outputs
| +-- develop.output.json
| +-- debug.output.json
| +-- validate.output.json
+-- {loopId}.progress/ # Human-readable progress
+-- develop.md
+-- debug.md
+-- validate.md
+-- summary.md
```
## Subagent API
| API | 作用 |
|-----|------|
| `spawn_agent({ message })` | 创建 agent返回 `agent_id` |
| `wait({ ids, timeout_ms })` | 等待结果(唯一取结果入口) |
| `send_input({ id, message })` | 继续交互 |
| `close_agent({ id })` | 关闭回收 |
## Implementation
### Coordinator Logic
```javascript
// ==================== HYBRID ORCHESTRATOR ====================
// 1. Initialize
const loopId = args['--loop-id'] || generateLoopId()
const mode = args['--mode'] || 'interactive'
let state = readOrCreateState(loopId, taskDescription)
// 2. Mode selection
switch (mode) {
case 'interactive':
await runInteractiveMode(loopId, state)
break
case 'auto':
await runAutoMode(loopId, state)
break
case 'parallel':
await runParallelMode(loopId, state)
break
}
```
### Interactive Mode (单 agent 交互或按需 spawn worker)
```javascript
async function runInteractiveMode(loopId, state) {
while (state.status === 'running') {
// Show menu, get user choice
const action = await showMenuAndGetChoice(state)
if (action === 'exit') break
// Spawn specialized worker for the action
const workerId = spawn_agent({
message: buildWorkerPrompt(action, loopId, state)
})
// Wait for worker completion
const result = wait({ ids: [workerId], timeout_ms: 600000 })
const output = result.status[workerId].completed
// Update state and display result
state = updateState(loopId, action, output)
displayResult(output)
// Cleanup worker
close_agent({ id: workerId })
}
}
```
### Auto Mode (顺序执行 worker 链)
```javascript
async function runAutoMode(loopId, state) {
const actionSequence = ['init', 'develop', 'debug', 'validate', 'complete']
let currentIndex = state.skill_state?.action_index || 0
while (currentIndex < actionSequence.length && state.status === 'running') {
const action = actionSequence[currentIndex]
// Spawn worker
const workerId = spawn_agent({
message: buildWorkerPrompt(action, loopId, state)
})
const result = wait({ ids: [workerId], timeout_ms: 600000 })
const output = result.status[workerId].completed
// Parse worker result to determine next step
const workerResult = parseWorkerResult(output)
// Update state
state = updateState(loopId, action, output)
close_agent({ id: workerId })
// Determine next action
if (workerResult.needs_loop_back) {
// Loop back to develop or debug
currentIndex = actionSequence.indexOf(workerResult.loop_back_to)
} else if (workerResult.status === 'failed') {
// Stop on failure
break
} else {
currentIndex++
}
}
}
```
### Parallel Mode (批量 spawn + wait)
```javascript
async function runParallelMode(loopId, state) {
// Spawn multiple workers in parallel
const workers = {
develop: spawn_agent({ message: buildWorkerPrompt('develop', loopId, state) }),
debug: spawn_agent({ message: buildWorkerPrompt('debug', loopId, state) }),
validate: spawn_agent({ message: buildWorkerPrompt('validate', loopId, state) })
}
// Batch wait for all workers
const results = wait({
ids: Object.values(workers),
timeout_ms: 900000 // 15 minutes for all
})
// Collect outputs
const outputs = {}
for (const [role, workerId] of Object.entries(workers)) {
outputs[role] = results.status[workerId].completed
close_agent({ id: workerId })
}
// Merge and analyze results
const mergedAnalysis = mergeWorkerOutputs(outputs)
// Update state with merged results
updateState(loopId, 'parallel-analysis', mergedAnalysis)
// Coordinator decides next action based on merged results
const decision = decideNextAction(mergedAnalysis)
return decision
}
```
### Worker Prompt Builder
```javascript
function buildWorkerPrompt(action, loopId, state) {
const workerRoles = {
develop: '~/.codex/agents/ccw-loop-b-develop.md',
debug: '~/.codex/agents/ccw-loop-b-debug.md',
validate: '~/.codex/agents/ccw-loop-b-validate.md',
init: '~/.codex/agents/ccw-loop-b-init.md',
complete: '~/.codex/agents/ccw-loop-b-complete.md'
}
return `
## TASK ASSIGNMENT
### MANDATORY FIRST STEPS (Agent Execute)
1. **Read role definition**: ${workerRoles[action]} (MUST read first)
2. Read: .workflow/project-tech.json
3. Read: .workflow/project-guidelines.json
---
## LOOP CONTEXT
- **Loop ID**: ${loopId}
- **Action**: ${action}
- **State File**: .loop/${loopId}.json
- **Output File**: .loop/${loopId}.workers/${action}.output.json
- **Progress File**: .loop/${loopId}.progress/${action}.md
## CURRENT STATE
${JSON.stringify(state, null, 2)}
## TASK DESCRIPTION
${state.description}
## EXPECTED OUTPUT
\`\`\`
WORKER_RESULT:
- action: ${action}
- status: success | failed | needs_input
- summary: <brief summary>
- files_changed: [list]
- next_suggestion: <suggested next action>
- loop_back_to: <action name if needs loop back>
DETAILED_OUTPUT:
<structured output specific to action type>
\`\`\`
Execute the ${action} action now.
`
}
```
## Worker Roles
| Worker | Role File | 专注领域 |
|--------|-----------|----------|
| init | ccw-loop-b-init.md | 会话初始化、任务解析 |
| develop | ccw-loop-b-develop.md | 代码实现、重构 |
| debug | ccw-loop-b-debug.md | 问题诊断、假设验证 |
| validate | ccw-loop-b-validate.md | 测试执行、覆盖率 |
| complete | ccw-loop-b-complete.md | 总结收尾 |
## State Schema
See [phases/state-schema.md](phases/state-schema.md)
## Usage
```bash
# Interactive mode (default)
/ccw-loop-b TASK="Implement user authentication"
# Auto mode
/ccw-loop-b --mode=auto TASK="Fix login bug"
# Parallel analysis mode
/ccw-loop-b --mode=parallel TASK="Analyze and improve payment module"
# Resume existing loop
/ccw-loop-b --loop-id=loop-b-20260122-abc123
```
## Error Handling
| Situation | Action |
|-----------|--------|
| Worker timeout | send_input 请求收敛 |
| Worker failed | Log error, 协调器决策是否重试 |
| Batch wait partial timeout | 使用已完成结果继续 |
| State corrupted | 从 progress 文件重建 |
## Best Practices
1. **协调器保持轻量**: 只做调度和状态管理,具体工作交给 worker
2. **Worker 职责单一**: 每个 worker 专注一个领域
3. **结果标准化**: Worker 输出遵循统一 WORKER_RESULT 格式
4. **灵活模式切换**: 根据任务复杂度选择合适模式
5. **及时清理**: Worker 完成后 close_agent 释放资源

View File

@@ -0,0 +1,257 @@
# Orchestrator (Hybrid Pattern)
协调器负责状态管理、worker 调度、结果汇聚。
## Role
```
Read state -> Select mode -> Spawn workers -> Wait results -> Merge -> Update state -> Loop/Exit
```
## State Management
### Read State
```javascript
function readState(loopId) {
const stateFile = `.loop/${loopId}.json`
return fs.existsSync(stateFile)
? JSON.parse(Read(stateFile))
: null
}
```
### Create State
```javascript
function createState(loopId, taskDescription, mode) {
const now = new Date().toISOString()
return {
loop_id: loopId,
title: taskDescription.substring(0, 100),
description: taskDescription,
mode: mode,
status: 'running',
current_iteration: 0,
max_iterations: 10,
created_at: now,
updated_at: now,
skill_state: {
phase: 'init',
action_index: 0,
workers_completed: [],
parallel_results: null
}
}
}
```
## Mode Handlers
### Interactive Mode
```javascript
async function runInteractiveMode(loopId, state) {
while (state.status === 'running') {
// 1. Show menu
const action = await showMenu(state)
if (action === 'exit') break
// 2. Spawn worker
const worker = spawn_agent({
message: buildWorkerPrompt(action, loopId, state)
})
// 3. Wait for result
const result = wait({ ids: [worker], timeout_ms: 600000 })
// 4. Handle timeout
if (result.timed_out) {
send_input({ id: worker, message: 'Please converge and output WORKER_RESULT' })
const retryResult = wait({ ids: [worker], timeout_ms: 300000 })
if (retryResult.timed_out) {
console.log('Worker timeout, skipping')
close_agent({ id: worker })
continue
}
}
// 5. Process output
const output = result.status[worker].completed
state = processWorkerOutput(loopId, action, output, state)
// 6. Cleanup
close_agent({ id: worker })
// 7. Display result
displayResult(output)
}
}
```
### Auto Mode
```javascript
async function runAutoMode(loopId, state) {
const sequence = ['init', 'develop', 'debug', 'validate', 'complete']
let idx = state.skill_state?.action_index || 0
while (idx < sequence.length && state.status === 'running') {
const action = sequence[idx]
// Spawn and wait
const worker = spawn_agent({ message: buildWorkerPrompt(action, loopId, state) })
const result = wait({ ids: [worker], timeout_ms: 600000 })
const output = result.status[worker].completed
close_agent({ id: worker })
// Parse result
const workerResult = parseWorkerResult(output)
state = processWorkerOutput(loopId, action, output, state)
// Determine next
if (workerResult.loop_back_to) {
idx = sequence.indexOf(workerResult.loop_back_to)
} else if (workerResult.status === 'failed') {
break
} else {
idx++
}
// Update action index
state.skill_state.action_index = idx
saveState(loopId, state)
}
}
```
### Parallel Mode
```javascript
async function runParallelMode(loopId, state) {
// Spawn all workers
const workers = {
develop: spawn_agent({ message: buildWorkerPrompt('develop', loopId, state) }),
debug: spawn_agent({ message: buildWorkerPrompt('debug', loopId, state) }),
validate: spawn_agent({ message: buildWorkerPrompt('validate', loopId, state) })
}
// Batch wait
const results = wait({
ids: Object.values(workers),
timeout_ms: 900000
})
// Collect outputs
const outputs = {}
for (const [role, id] of Object.entries(workers)) {
if (results.status[id].completed) {
outputs[role] = results.status[id].completed
}
close_agent({ id })
}
// Merge analysis
state.skill_state.parallel_results = outputs
saveState(loopId, state)
// Coordinator analyzes merged results
return analyzeAndDecide(outputs)
}
```
## Worker Prompt Template
```javascript
function buildWorkerPrompt(action, loopId, state) {
const roleFiles = {
init: '~/.codex/agents/ccw-loop-b-init.md',
develop: '~/.codex/agents/ccw-loop-b-develop.md',
debug: '~/.codex/agents/ccw-loop-b-debug.md',
validate: '~/.codex/agents/ccw-loop-b-validate.md',
complete: '~/.codex/agents/ccw-loop-b-complete.md'
}
return `
## TASK ASSIGNMENT
### MANDATORY FIRST STEPS
1. **Read role definition**: ${roleFiles[action]}
2. Read: .workflow/project-tech.json
3. Read: .workflow/project-guidelines.json
---
## CONTEXT
- Loop ID: ${loopId}
- Action: ${action}
- State: ${JSON.stringify(state, null, 2)}
## TASK
${state.description}
## OUTPUT FORMAT
\`\`\`
WORKER_RESULT:
- action: ${action}
- status: success | failed | needs_input
- summary: <brief>
- files_changed: []
- next_suggestion: <action>
- loop_back_to: <action or null>
DETAILED_OUTPUT:
<action-specific output>
\`\`\`
`
}
```
## Result Processing
```javascript
function parseWorkerResult(output) {
const result = {
action: 'unknown',
status: 'unknown',
summary: '',
files_changed: [],
next_suggestion: null,
loop_back_to: null
}
const match = output.match(/WORKER_RESULT:\s*([\s\S]*?)(?:DETAILED_OUTPUT:|$)/)
if (match) {
const lines = match[1].split('\n')
for (const line of lines) {
const m = line.match(/^-\s*(\w+):\s*(.+)$/)
if (m) {
const [, key, value] = m
if (key === 'files_changed') {
try { result.files_changed = JSON.parse(value) } catch {}
} else {
result[key] = value.trim()
}
}
}
}
return result
}
```
## Termination Conditions
1. User exits (interactive)
2. Sequence complete (auto)
3. Worker failed with no recovery
4. Max iterations reached
5. API paused/stopped
## Best Practices
1. **Worker 生命周期**: spawn → wait → close不保留 worker
2. **结果持久化**: Worker 输出写入 `.loop/{loopId}.workers/`
3. **状态同步**: 每次 worker 完成后更新 state
4. **超时处理**: send_input 请求收敛,再超时则跳过

View File

@@ -0,0 +1,181 @@
# State Schema (CCW Loop-B)
## Master State Structure
```json
{
"loop_id": "loop-b-20260122-abc123",
"title": "Implement user authentication",
"description": "Full task description here",
"mode": "interactive | auto | parallel",
"status": "running | paused | completed | failed",
"current_iteration": 3,
"max_iterations": 10,
"created_at": "2026-01-22T10:00:00.000Z",
"updated_at": "2026-01-22T10:30:00.000Z",
"skill_state": {
"phase": "develop | debug | validate | complete",
"action_index": 2,
"workers_completed": ["init", "develop"],
"parallel_results": null,
"pending_tasks": [],
"completed_tasks": [],
"findings": []
}
}
```
## Field Descriptions
### Core Fields (API Compatible)
| Field | Type | Description |
|-------|------|-------------|
| `loop_id` | string | Unique identifier |
| `title` | string | Short title (max 100 chars) |
| `description` | string | Full task description |
| `mode` | enum | Execution mode |
| `status` | enum | Current status |
| `current_iteration` | number | Iteration counter |
| `max_iterations` | number | Safety limit |
| `created_at` | ISO string | Creation timestamp |
| `updated_at` | ISO string | Last update timestamp |
### Skill State Fields
| Field | Type | Description |
|-------|------|-------------|
| `phase` | enum | Current execution phase |
| `action_index` | number | Position in action sequence (auto mode) |
| `workers_completed` | array | List of completed worker actions |
| `parallel_results` | object | Merged results from parallel mode |
| `pending_tasks` | array | Tasks waiting to be executed |
| `completed_tasks` | array | Tasks already done |
| `findings` | array | Discoveries during execution |
## Worker Output Structure
Each worker writes to `.loop/{loopId}.workers/{action}.output.json`:
```json
{
"action": "develop",
"status": "success",
"summary": "Implemented 3 functions",
"files_changed": ["src/auth.ts", "src/utils.ts"],
"next_suggestion": "validate",
"loop_back_to": null,
"timestamp": "2026-01-22T10:15:00.000Z",
"detailed_output": {
"tasks_completed": [
{ "id": "T1", "description": "Create auth module" }
],
"metrics": {
"lines_added": 150,
"lines_removed": 20
}
}
}
```
## Progress File Structure
Human-readable progress in `.loop/{loopId}.progress/{action}.md`:
```markdown
# Develop Progress
## Session: loop-b-20260122-abc123
### Iteration 1 (2026-01-22 10:15)
**Task**: Implement auth module
**Changes**:
- Created `src/auth.ts` with login/logout functions
- Added JWT token handling in `src/utils.ts`
**Status**: Success
---
### Iteration 2 (2026-01-22 10:30)
...
```
## Status Transitions
```
+--------+
| init |
+--------+
|
v
+------> +---------+
| | develop |
| +---------+
| |
| +--------+--------+
| | |
| v v
| +-------+ +---------+
| | debug |<------| validate|
| +-------+ +---------+
| | |
| +--------+--------+
| |
| v
| [needs fix?]
| yes | | no
| v v
+------------+ +----------+
| complete |
+----------+
```
## Parallel Results Schema
When `mode === 'parallel'`:
```json
{
"parallel_results": {
"develop": {
"status": "success",
"summary": "...",
"suggestions": []
},
"debug": {
"status": "success",
"issues_found": [],
"suggestions": []
},
"validate": {
"status": "success",
"test_results": {},
"coverage": {}
},
"merged_at": "2026-01-22T10:45:00.000Z"
}
}
```
## Directory Structure
```
.loop/
+-- loop-b-20260122-abc123.json # Master state
+-- loop-b-20260122-abc123.workers/
| +-- init.output.json
| +-- develop.output.json
| +-- debug.output.json
| +-- validate.output.json
| +-- complete.output.json
+-- loop-b-20260122-abc123.progress/
+-- develop.md
+-- debug.md
+-- validate.md
+-- summary.md
```