Compare commits

...

5 Commits

Author SHA1 Message Date
catlog22
67a578450c chore: Bump version to 6.3.52 2026-01-29 21:22:49 +08:00
catlog22
d5199ad2d4 Add merge-plans-with-file and quick-plan-with-file prompts for enhanced planning workflows
- Introduced merge-plans-with-file prompt for aggregating multiple planning artifacts, resolving conflicts, and synthesizing a unified execution plan.
- Implemented detailed execution process including discovery, normalization, conflict detection, resolution, and synthesis phases.
- Added quick-plan-with-file prompt for rapid planning with minimal documentation, utilizing multi-agent analysis for actionable outputs.
- Both prompts support various input formats and provide structured outputs for execution and documentation.
2026-01-29 21:21:29 +08:00
catlog22
f3c773a81e Refactor Codex Issue Plan-Execute Skill Documentation and CLI Options
- Deleted obsolete INDEX.md and OPTIMIZATION_SUMMARY.md files, consolidating documentation for improved clarity and organization.
- Removed skipGitRepoCheck option from CLI execution parameters to streamline command usage.
- Updated CLI executor utilities to automatically skip git repository checks, allowing execution in non-git directories.
- Enhanced documentation with new ARCHITECTURE.md and INDEX.md files for better navigation and understanding of the system architecture.
- Created CONTENT_MIGRATION_REPORT.md to verify zero content loss during the consolidation process.
2026-01-29 20:39:12 +08:00
catlog22
875b1f19bd feat: 完成 Codex Issue Plan-Execute Skill v2.0 优化
- 新增 OPTIMIZATION_SUMMARY.md,详细记录优化过程和成果
- 新增 README_OPTIMIZATION.md,概述优化后的文件结构和关键指标
- 创建 specs/agent-roles.md,整合 Planning Agent 和 Execution Agent 的角色定义
- 合并多个提示词文件,减少内容重复,优化 Token 使用
- 新建 ARCHITECTURE.md 和 INDEX.md,提供系统架构和文档导航
- 添加 CONTENT_MIGRATION_REPORT.md,确保内容迁移的完整性和零丢失
- 更新文件引用,确保向后兼容性,添加弃用通知
2026-01-29 20:37:30 +08:00
catlog22
c08f5382d3 fix: Improve command detail modal tab handling and error reporting 2026-01-29 17:48:06 +08:00
17 changed files with 3662 additions and 869 deletions

View File

@@ -0,0 +1,807 @@
---
name: merge-plans-with-file
description: Merge multiple planning/brainstorm/analysis outputs, resolve conflicts, and synthesize unified plan. Designed for multi-team input aggregation and final plan crystallization
argument-hint: "[-y|--yes] [-r|--rule consensus|priority|hierarchy] \"plan or topic name\""
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-resolve conflicts using specified rule (consensus/priority/hierarchy), minimal user prompts.
# Workflow Merge-Plans-With-File Command (/workflow:merge-plans-with-file)
## Overview
Plan aggregation and conflict resolution workflow. Takes multiple planning artifacts (brainstorm conclusions, analysis recommendations, quick-plans, implementation plans) and synthesizes them into a unified, conflict-resolved execution plan.
**Core workflow**: Load Sources → Parse Plans → Conflict Analysis → Arbitration → Unified Plan
**Key features**:
- **Multi-Source Support**: Brainstorm, analysis, quick-plan, IMPL_PLAN, task JSONs
- **Parallel Conflict Detection**: Identify all contradictions across input plans
- **Conflict Resolution**: Consensus, priority-based, or hierarchical resolution modes
- **Unified Synthesis**: Single authoritative plan from multiple perspectives
- **Decision Tracking**: Full audit trail of conflicts and resolutions
- **Resumable**: Save intermediate states, refine resolutions
## Usage
```bash
/workflow:merge-plans-with-file [FLAGS] <PLAN_NAME_OR_PATTERN>
# Flags
-y, --yes Auto-resolve conflicts using rule, skip confirmations
-r, --rule <rule> Conflict resolution rule: consensus (default) | priority | hierarchy
-o, --output <path> Output directory (default: .workflow/.merged/{name})
# Arguments
<plan-name-or-pattern> Plan name or glob pattern to identify input files/sessions
Examples: "auth-module", "*.analysis-*.json", "PLAN-*"
# Examples
/workflow:merge-plans-with-file "authentication" # Auto-detect all auth-related plans
/workflow:merge-plans-with-file -y -r priority "payment-system" # Auto-resolve with priority rule
/workflow:merge-plans-with-file -r hierarchy "feature-complete" # Use hierarchy rule (requires user ranking)
```
## Execution Process
```
Discovery & Loading:
├─ Search for planning artifacts matching pattern
├─ Load all synthesis.json, conclusions.json, IMPL_PLAN.md
├─ Parse each into normalized task/plan structure
└─ Validate data completeness
Session Initialization:
├─ Create .workflow/.merged/{sessionId}/
├─ Initialize merge.md with plan summary
├─ Index all source plans
└─ Extract planning metadata and constraints
Phase 1: Plan Normalization
├─ Convert all formats to common task representation
├─ Extract tasks, dependencies, effort, risks
├─ Identify plan scope and boundaries
├─ Validate no duplicate tasks
└─ Aggregate recommendations from each plan
Phase 2: Conflict Detection (Parallel)
├─ Architecture conflicts: different design approaches
├─ Task conflicts: overlapping responsibilities or different priorities
├─ Effort conflicts: vastly different estimates
├─ Risk assessment conflicts: different risk levels
├─ Scope conflicts: different feature inclusions
└─ Generate conflict matrix with severity levels
Phase 3: Consensus Building / Arbitration
├─ For each conflict, analyze source rationale
├─ Apply resolution rule (consensus/priority/hierarchy)
├─ Escalate unresolvable conflicts to user (unless --yes)
├─ Document decision rationale
└─ Generate resolutions.json
Phase 4: Plan Synthesis
├─ Merge task lists (remove duplicates, combine insights)
├─ Integrate dependencies from all sources
├─ Consolidate effort and risk estimates
├─ Generate unified execution sequence
├─ Create final unified plan
└─ Output ready for execution
Output:
├─ .workflow/.merged/{sessionId}/merge.md (merge process & decisions)
├─ .workflow/.merged/{sessionId}/source-index.json (input sources)
├─ .workflow/.merged/{sessionId}/conflicts.json (conflict matrix)
├─ .workflow/.merged/{sessionId}/resolutions.json (how conflicts were resolved)
├─ .workflow/.merged/{sessionId}/unified-plan.json (final merged plan)
└─ .workflow/.merged/{sessionId}/unified-plan.md (execution-ready markdown)
```
## Implementation
### Phase 1: Plan Discovery & Loading
```javascript
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
// Parse arguments
const planPattern = "$PLAN_NAME_OR_PATTERN"
const resolutionRule = $ARGUMENTS.match(/--rule\s+(\w+)/)?.[1] || 'consensus'
const isAutoMode = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
// Generate session ID
const mergeSlug = planPattern.toLowerCase()
.replace(/[*?]/g, '-')
.replace(/[^a-z0-9\u4e00-\u9fa5-]+/g, '-')
.substring(0, 30)
const dateStr = getUtc8ISOString().substring(0, 10)
const sessionId = `MERGE-${mergeSlug}-${dateStr}`
const sessionFolder = `.workflow/.merged/${sessionId}`
bash(`mkdir -p ${sessionFolder}`)
// Discover all relevant planning artifacts
const discoveryPaths = [
`.workflow/.brainstorm/*/${planPattern}*/synthesis.json`,
`.workflow/.analysis/*/${planPattern}*/conclusions.json`,
`.workflow/.planning/*/${planPattern}*/synthesis.json`,
`.workflow/.plan/${planPattern}*IMPL_PLAN.md`,
`.workflow/*/${planPattern}*.json`
]
const sourcePlans = []
for (const pattern of discoveryPaths) {
const matches = glob(pattern)
for (const path of matches) {
try {
const content = Read(path)
const plan = parsePlanFile(path, content)
if (plan && plan.tasks?.length > 0) {
sourcePlans.push({
source_path: path,
source_type: identifySourceType(path),
plan: plan,
loaded_at: getUtc8ISOString()
})
}
} catch (e) {
console.warn(`Failed to load plan from ${path}: ${e.message}`)
}
}
}
if (sourcePlans.length === 0) {
console.error(`
## Error: No Plans Found
Pattern: ${planPattern}
Searched locations:
${discoveryPaths.join('\n')}
Available plans in .workflow/:
`)
bash(`find .workflow -name "*.json" -o -name "*PLAN.md" | head -20`)
return { status: 'error', message: 'No plans found' }
}
console.log(`
## Plans Discovered
Total: ${sourcePlans.length}
${sourcePlans.map(sp => `- ${sp.source_type}: ${sp.source_path}`).join('\n')}
`)
```
---
### Phase 2: Plan Normalization
```javascript
// Normalize all plans to common format
const normalizedPlans = sourcePlans.map((sourcePlan, idx) => {
const plan = sourcePlan.plan
const tasks = plan.tasks || []
return {
index: idx,
source: sourcePlan.source_path,
source_type: sourcePlan.source_type,
metadata: {
title: plan.title || `Plan ${idx + 1}`,
topic: plan.topic || plan.planning_topic || 'unknown',
timestamp: plan.completed || plan.timestamp || sourcePlan.loaded_at,
source_ideas: plan.top_ideas?.length || 0,
complexity: plan.complexity_level || 'unknown'
},
// Normalized tasks
tasks: tasks.map(task => ({
id: task.id || `T${idx}-${task.title?.substring(0, 20)}`,
title: task.title || task.content,
description: task.description || '',
type: task.type || inferType(task),
priority: task.priority || 'normal',
// Effort estimation
effort: {
estimated: task.estimated_duration || task.effort_estimate || 'unknown',
from_plan: idx
},
// Risk assessment
risk: {
level: task.risk_level || 'medium',
from_plan: idx
},
// Dependencies
dependencies: task.dependencies || [],
// Source tracking
source_plan_index: idx,
original_id: task.id,
// Quality tracking
success_criteria: task.success_criteria || [],
challenges: task.challenges || []
}))
}
})
// Save source index
const sourceIndex = {
session_id: sessionId,
merge_timestamp: getUtc8ISOString(),
pattern: planPattern,
total_source_plans: sourcePlans.length,
sources: normalizedPlans.map(p => ({
index: p.index,
source_path: p.source,
source_type: p.source_type,
topic: p.metadata.topic,
task_count: p.tasks.length
}))
}
Write(`${sessionFolder}/source-index.json`, JSON.stringify(sourceIndex, null, 2))
```
---
### Phase 3: Conflict Detection
```javascript
// Detect conflicts across plans
const conflictDetector = {
// Architecture conflicts
architectureConflicts: [],
// Task conflicts (duplicates, different scope)
taskConflicts: [],
// Effort conflicts
effortConflicts: [],
// Risk assessment conflicts
riskConflicts: [],
// Scope conflicts
scopeConflicts: [],
// Priority conflicts
priorityConflicts: []
}
// Algorithm 1: Detect similar tasks across plans
const allTasks = normalizedPlans.flatMap(p => p.tasks)
const taskGroups = groupSimilarTasks(allTasks)
for (const group of taskGroups) {
if (group.tasks.length > 1) {
// Same task appears in multiple plans
const efforts = group.tasks.map(t => t.effort.estimated)
const effortVariance = calculateVariance(efforts)
if (effortVariance > 0.5) {
// Significant difference in effort estimates
conflictDetector.effortConflicts.push({
task_group: group.title,
conflicting_tasks: group.tasks.map((t, i) => ({
id: t.id,
from_plan: t.source_plan_index,
effort: t.effort.estimated
})),
variance: effortVariance,
severity: 'high'
})
}
// Check for scope differences
const scopeDifferences = analyzeScopeDifferences(group.tasks)
if (scopeDifferences.length > 0) {
conflictDetector.taskConflicts.push({
task_group: group.title,
scope_differences: scopeDifferences,
severity: 'medium'
})
}
}
}
// Algorithm 2: Architecture conflicts
const architectures = normalizedPlans.map(p => p.metadata.complexity)
if (new Set(architectures).size > 1) {
conflictDetector.architectureConflicts.push({
different_approaches: true,
complexity_levels: architectures.map((a, i) => ({
plan: i,
complexity: a
})),
severity: 'high'
})
}
// Algorithm 3: Risk assessment conflicts
const riskLevels = allTasks.map(t => ({ task: t.id, risk: t.risk.level }))
const taskRisks = {}
for (const tr of riskLevels) {
if (!taskRisks[tr.task]) taskRisks[tr.task] = []
taskRisks[tr.task].push(tr.risk)
}
for (const [task, risks] of Object.entries(taskRisks)) {
if (new Set(risks).size > 1) {
conflictDetector.riskConflicts.push({
task: task,
conflicting_risk_levels: risks,
severity: 'medium'
})
}
}
// Save conflicts
Write(`${sessionFolder}/conflicts.json`, JSON.stringify(conflictDetector, null, 2))
```
---
### Phase 4: Conflict Resolution
```javascript
// Resolve conflicts based on selected rule
const resolutions = {
resolution_rule: resolutionRule,
timestamp: getUtc8ISOString(),
effort_resolutions: [],
architecture_resolutions: [],
risk_resolutions: [],
scope_resolutions: [],
priority_resolutions: []
}
// Resolution Strategy 1: Consensus
if (resolutionRule === 'consensus') {
for (const conflict of conflictDetector.effortConflicts) {
// Use median or average
const efforts = conflict.conflicting_tasks.map(t => parseEffort(t.effort))
const resolved_effort = calculateMedian(efforts)
resolutions.effort_resolutions.push({
conflict: conflict.task_group,
original_estimates: efforts,
resolved_estimate: resolved_effort,
method: 'consensus-median',
rationale: 'Used median of all estimates'
})
}
}
// Resolution Strategy 2: Priority-Based
else if (resolutionRule === 'priority') {
// Use the plan from highest priority source (first or most recent)
for (const conflict of conflictDetector.effortConflicts) {
const highestPriority = conflict.conflicting_tasks[0] // First plan has priority
resolutions.effort_resolutions.push({
conflict: conflict.task_group,
conflicting_estimates: conflict.conflicting_tasks.map(t => t.effort),
resolved_estimate: highestPriority.effort,
selected_from_plan: highestPriority.from_plan,
method: 'priority-based',
rationale: `Selected estimate from plan ${highestPriority.from_plan} (highest priority)`
})
}
}
// Resolution Strategy 3: Hierarchy (requires user ranking)
else if (resolutionRule === 'hierarchy') {
if (!isAutoMode) {
// Ask user to rank plan importance
const planRanking = AskUserQuestion({
questions: [{
question: "请按重要性排序这些规划(从最重要到最不重要):",
header: "Plan Ranking",
multiSelect: false,
options: normalizedPlans.slice(0, 5).map(p => ({
label: `Plan ${p.index}: ${p.metadata.title.substring(0, 40)}`,
description: `${p.tasks.length} tasks, complexity: ${p.metadata.complexity}`
}))
}]
})
// Apply hierarchy
const hierarchy = extractHierarchy(planRanking)
for (const conflict of conflictDetector.effortConflicts) {
const topPriorityTask = conflict.conflicting_tasks
.sort((a, b) => hierarchy[a.from_plan] - hierarchy[b.from_plan])[0]
resolutions.effort_resolutions.push({
conflict: conflict.task_group,
resolved_estimate: topPriorityTask.effort,
selected_from_plan: topPriorityTask.from_plan,
method: 'hierarchy-based',
rationale: `Selected from highest-ranked plan`
})
}
}
}
Write(`${sessionFolder}/resolutions.json`, JSON.stringify(resolutions, null, 2))
```
---
### Phase 5: Plan Synthesis
```javascript
// Merge all tasks into unified plan
const unifiedTasks = []
const processedTaskIds = new Set()
for (const task of allTasks) {
const taskKey = generateTaskKey(task)
if (processedTaskIds.has(taskKey)) {
// Task already added, skip
continue
}
processedTaskIds.add(taskKey)
// Apply resolution if this task has conflicts
let resolvedTask = { ...task }
const effortResolution = resolutions.effort_resolutions
.find(r => r.conflict === taskKey)
if (effortResolution) {
resolvedTask.effort.estimated = effortResolution.resolved_estimate
resolvedTask.effort.resolution_method = effortResolution.method
}
unifiedTasks.push({
id: taskKey,
title: task.title,
description: task.description,
type: task.type,
priority: task.priority,
effort: resolvedTask.effort,
risk: task.risk,
dependencies: task.dependencies,
success_criteria: [...new Set([
...task.success_criteria,
...findRelatedTasks(task, allTasks)
.flatMap(t => t.success_criteria)
])],
challenges: [...new Set([
...task.challenges,
...findRelatedTasks(task, allTasks)
.flatMap(t => t.challenges)
])],
source_plans: [
...new Set(allTasks
.filter(t => generateTaskKey(t) === taskKey)
.map(t => t.source_plan_index))
]
})
}
// Generate execution sequence
const executionSequence = topologicalSort(unifiedTasks)
const criticalPath = identifyCriticalPath(unifiedTasks, executionSequence)
// Final unified plan
const unifiedPlan = {
session_id: sessionId,
merge_timestamp: getUtc8ISOString(),
summary: {
total_source_plans: normalizedPlans.length,
original_tasks_total: allTasks.length,
merged_tasks: unifiedTasks.length,
conflicts_resolved: Object.values(conflictDetector).flat().length,
resolution_rule: resolutionRule
},
merged_metadata: {
topics: [...new Set(normalizedPlans.map(p => p.metadata.topic))],
average_complexity: calculateAverage(normalizedPlans.map(p => parseComplexity(p.metadata.complexity))),
combined_scope: estimateScope(unifiedTasks)
},
tasks: unifiedTasks,
execution_sequence: executionSequence,
critical_path: criticalPath,
risks: aggregateRisks(unifiedTasks),
success_criteria: aggregateSuccessCriteria(unifiedTasks),
audit_trail: {
source_plans: normalizedPlans.length,
conflicts_detected: Object.values(conflictDetector).flat().length,
conflicts_resolved: Object.values(resolutions).flat().length,
resolution_method: resolutionRule
}
}
Write(`${sessionFolder}/unified-plan.json`, JSON.stringify(unifiedPlan, null, 2))
```
---
### Phase 6: Generate Execution Plan
```markdown
# Merged Planning Session
**Session ID**: ${sessionId}
**Pattern**: ${planPattern}
**Created**: ${getUtc8ISOString()}
---
## Merge Summary
**Source Plans**: ${unifiedPlan.summary.total_source_plans}
**Original Tasks**: ${unifiedPlan.summary.original_tasks_total}
**Merged Tasks**: ${unifiedPlan.summary.merged_tasks}
**Tasks Deduplicated**: ${unifiedPlan.summary.original_tasks_total - unifiedPlan.summary.merged_tasks}
**Conflicts Resolved**: ${unifiedPlan.summary.conflicts_resolved}
**Resolution Method**: ${unifiedPlan.summary.resolution_rule}
---
## Merged Plan Overview
**Topics**: ${unifiedPlan.merged_metadata.topics.join(', ')}
**Combined Complexity**: ${unifiedPlan.merged_metadata.average_complexity}
**Total Scope**: ${unifiedPlan.merged_metadata.combined_scope}
---
## Unified Task List
${unifiedPlan.tasks.map((task, i) => `
${i+1}. **${task.id}: ${task.title}**
- Type: ${task.type}
- Effort: ${task.effort.estimated}
- Risk: ${task.risk.level}
- Source Plans: ${task.source_plans.join(', ')}
- ${task.description}
`).join('\n')}
---
## Execution Sequence
**Critical Path**: ${unifiedPlan.critical_path.join(' → ')}
**Execution Order**:
${unifiedPlan.execution_sequence.map((id, i) => `${i+1}. ${id}`).join('\n')}
---
## Conflict Resolution Report
**Total Conflicts**: ${unifiedPlan.summary.conflicts_resolved}
**Resolved Conflicts**:
${Object.entries(resolutions).flatMap(([key, items]) =>
items.slice(0, 3).map((item, i) => `
- ${key.replace('_', ' ')}: ${item.rationale || item.method}
`)
).join('\n')}
**Full Report**: See \`conflicts.json\` and \`resolutions.json\`
---
## Risks & Considerations
**Aggregated Risks**:
${unifiedPlan.risks.slice(0, 5).map(r => `- **${r.title}**: ${r.mitigation}`).join('\n')}
**Combined Success Criteria**:
${unifiedPlan.success_criteria.slice(0, 5).map(c => `- ${c}`).join('\n')}
---
## Next Steps
### Option 1: Direct Execution
Execute merged plan with unified-execute-with-file:
\`\`\`
/workflow:unified-execute-with-file -p ${sessionFolder}/unified-plan.json
\`\`\`
### Option 2: Detailed Planning
Create detailed IMPL_PLAN from merged plan:
\`\`\`
/workflow:plan "Based on merged plan from $(echo ${planPattern})"
\`\`\`
### Option 3: Review Conflicts
Review detailed conflict analysis:
\`\`\`
cat ${sessionFolder}/resolutions.json
\`\`\`
---
## Artifacts
- **source-index.json** - All input plans and sources
- **conflicts.json** - Conflict detection results
- **resolutions.json** - How each conflict was resolved
- **unified-plan.json** - Merged plan data structure (for execution)
- **unified-plan.md** - This document (human-readable)
```
---
## Session Folder Structure
```
.workflow/.merged/{sessionId}/
├── merge.md # Merge process and decisions
├── source-index.json # All input plan sources
├── conflicts.json # Detected conflicts
├── resolutions.json # Conflict resolutions applied
├── unified-plan.json # Merged plan (machine-parseable, for execution)
└── unified-plan.md # Execution-ready plan (human-readable)
```
---
## Resolution Rules
### Rule 1: Consensus (default)
- Use median or average of conflicting estimates
- Good for: Multiple similar perspectives
- Tradeoff: May miss important minority viewpoints
### Rule 2: Priority-Based
- First plan has highest priority, subsequent plans are fallback
- Good for: Clear ranking of plan sources
- Tradeoff: Discards valuable alternative perspectives
### Rule 3: Hierarchy
- User explicitly ranks importance of each plan
- Good for: Mixed-source plans (engineering + product + leadership)
- Tradeoff: Requires user input
---
## Input Format Support
| Source Type | Detection | Parsing | Notes |
|-------------|-----------|---------|-------|
| **Brainstorm** | `.brainstorm/*/synthesis.json` | Top ideas → tasks | Ideas converted to work items |
| **Analysis** | `.analysis/*/conclusions.json` | Recommendations → tasks | Recommendations prioritized |
| **Quick-Plan** | `.planning/*/synthesis.json` | Direct task list | Already normalized |
| **IMPL_PLAN** | `*IMPL_PLAN.md` | Markdown → tasks | Parsed from markdown structure |
| **Task JSON** | `.json` with `tasks` key | Direct mapping | Requires standard schema |
---
## Error Handling
| Situation | Action |
|-----------|--------|
| No plans found | Suggest search terms, list available plans |
| Incompatible formats | Skip unsupported format, continue with others |
| Circular dependencies | Alert user, suggest manual review |
| Unresolvable conflicts | Require user decision (unless --yes + conflict rule) |
| Contradictory recommendations | Document both options for user consideration |
---
## Usage Patterns
### Pattern 1: Merge Multiple Brainstorms
```bash
/workflow:merge-plans-with-file "authentication" -y -r consensus
# → Finds all brainstorm sessions with "auth"
# → Merges top ideas into unified task list
# → Uses consensus method for conflicts
```
### Pattern 2: Synthesize Team Input
```bash
/workflow:merge-plans-with-file "payment-integration" -r hierarchy
# → Loads plans from different team members
# → Asks for ranking by importance
# → Applies hierarchy-based conflict resolution
```
### Pattern 3: Bridge Planning Phases
```bash
/workflow:merge-plans-with-file "user-auth" -f analysis
# → Takes analysis conclusions
# → Merges with existing quick-plans
# → Produces execution-ready plan
```
---
## Advanced: Custom Conflict Resolution
For complex conflict scenarios, create custom resolution script:
```
.workflow/.merged/{sessionId}/
└── custom-resolutions.js (optional)
- Define custom conflict resolution logic
- Applied after automatic resolution
- Override specific decisions
```
---
## Best Practices
1. **Before merging**:
- Ensure all source plans have same quality level
- Verify plans address same scope/topic
- Document any special considerations
2. **During merging**:
- Review conflict matrix (conflicts.json)
- Understand resolution rationale (resolutions.json)
- Challenge assumptions if results seem odd
3. **After merging**:
- Validate unified plan makes sense
- Review critical path
- Ensure no important details lost
- Execute or iterate if needed
---
## Integration with Other Workflows
```
Multiple Brainstorms / Analyses
├─ brainstorm-with-file (session 1)
├─ brainstorm-with-file (session 2)
├─ analyze-with-file (session 3)
merge-plans-with-file ◄──── This workflow
unified-plan.json
├─ /workflow:unified-execute-with-file (direct execution)
├─ /workflow:plan (detailed planning)
└─ /workflow:quick-plan-with-file (refinement)
```
---
## Comparison: When to Use Which Merge Rule
| Rule | Use When | Pros | Cons |
|------|----------|------|------|
| **Consensus** | Similar-quality inputs | Fair, balanced | May miss extremes |
| **Priority** | Clear hierarchy | Simple, predictable | May bias to first input |
| **Hierarchy** | Mixed stakeholders | Respects importance | Requires user ranking |
---
**Ready to execute**: Run `/workflow:merge-plans-with-file` to start merging plans!

View File

@@ -0,0 +1,808 @@
---
name: quick-plan-with-file
description: Multi-agent rapid planning with minimal documentation, conflict resolution, and actionable synthesis. Designed as a lightweight planning supplement between brainstorm and full implementation planning
argument-hint: "[-y|--yes] [-c|--continue] [-f|--from <type>] \"planning topic or task description\""
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-confirm planning decisions, use aggressive parallelization, minimal user interaction.
# Workflow Quick-Plan-With-File Command (/workflow:quick-plan-with-file)
## Overview
Multi-agent rapid planning workflow with **minimal documentation overhead**. Coordinates parallel agent analysis, synthesizes conflicting perspectives into actionable decisions, and generates a lightweight implementation-ready plan.
**Core workflow**: Parse Input → Parallel Analysis → Conflict Resolution → Plan Synthesis → Output
**Key features**:
- **Plan Format Agnostic**: Consumes brainstorm conclusions, analysis recommendations, or raw task descriptions
- **Minimal Docs**: Single `plan.md` (no lengthy brainstorm.md or discussion.md)
- **Parallel Multi-Agent**: 3-4 concurrent agent perspectives (architecture, implementation, validation, risk)
- **Conflict Resolution**: Automatic conflict detection and resolution via synthesis agent
- **Actionable Output**: Direct task breakdown ready for execution
- **Session Resumable**: Continue if interrupted, checkpoint at each phase
## Usage
```bash
/workflow:quick-plan-with-file [FLAGS] <PLANNING_TOPIC>
# Flags
-y, --yes Auto-confirm decisions, use defaults
-c, --continue Continue existing session (auto-detected)
-f, --from <type> Input source type: brainstorm|analysis|task|raw
# Arguments
<planning-topic> Planning topic, task, or reference to planning artifact
# Examples
/workflow:quick-plan-with-file "实现分布式缓存层支持Redis和内存后端"
/workflow:quick-plan-with-file --continue "缓存层规划" # Continue
/workflow:quick-plan-with-file -y -f analysis "从分析结论生成实施规划" # Auto mode
/workflow:quick-plan-with-file --from brainstorm BS-rate-limiting-2025-01-28 # From artifact
```
## Execution Process
```
Input Validation & Loading:
├─ Parse input (topic | artifact reference)
├─ Load artifact if referenced (synthesis.json | conclusions.json | etc.)
├─ Extract key constraints and requirements
└─ Initialize session folder and plan.md
Session Initialization:
├─ Create .workflow/.planning/{sessionId}/
├─ Initialize plan.md with input summary
├─ Parse existing output (if --from artifact)
└─ Define planning dimensions & focus areas
Phase 1: Parallel Multi-Agent Analysis (concurrent)
├─ Agent 1 (Architecture): High-level design & decomposition
├─ Agent 2 (Implementation): Technical approach & feasibility
├─ Agent 3 (Validation): Risk analysis & edge cases
├─ Agent 4 (Decision): Recommendations & tradeoffs
└─ Aggregate findings into perspectives.json
Phase 2: Conflict Detection & Resolution
├─ Analyze agent perspectives for contradictions
├─ Identify critical decision points
├─ Generate synthesis via arbitration agent
├─ Document conflicts and resolutions
└─ Update plan.md with decisive recommendations
Phase 3: Plan Synthesis
├─ Consolidate all insights
├─ Generate actionable task breakdown
├─ Create execution strategy
├─ Document assumptions & risks
└─ Generate synthesis.md with ready-to-execute tasks
Output:
├─ .workflow/.planning/{sessionId}/plan.md (minimal, actionable)
├─ .workflow/.planning/{sessionId}/perspectives.json (agent findings)
├─ .workflow/.planning/{sessionId}/conflicts.json (decision points)
├─ .workflow/.planning/{sessionId}/synthesis.md (task breakdown)
└─ Optional: Feed to /workflow:unified-execute-with-file
```
## Implementation
### Session Setup & Input Loading
```javascript
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
// Parse arguments
const planningTopic = "$PLANNING_TOPIC"
const inputType = $ARGUMENTS.match(/--from\s+(\w+)/)?.[1] || 'raw'
const isAutoMode = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
const isContinue = $ARGUMENTS.includes('--continue') || $ARGUMENTS.includes('-c')
// Auto-detect artifact if referenced
let artifact = null
let artifactContent = null
if (inputType === 'brainstorm' || planningTopic.startsWith('BS-')) {
const sessionId = planningTopic
const synthesisPath = `.workflow/.brainstorm/${sessionId}/synthesis.json`
if (fs.existsSync(synthesisPath)) {
artifact = { type: 'brainstorm', path: synthesisPath }
artifactContent = JSON.parse(Read(synthesisPath))
}
} else if (inputType === 'analysis' || planningTopic.startsWith('ANL-')) {
const sessionId = planningTopic
const conclusionsPath = `.workflow/.analysis/${sessionId}/conclusions.json`
if (fs.existsSync(conclusionsPath)) {
artifact = { type: 'analysis', path: conclusionsPath }
artifactContent = JSON.parse(Read(conclusionsPath))
}
}
// Generate session ID
const planSlug = planningTopic.toLowerCase()
.replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')
.substring(0, 30)
const dateStr = getUtc8ISOString().substring(0, 10)
const sessionId = `PLAN-${planSlug}-${dateStr}`
const sessionFolder = `.workflow/.planning/${sessionId}`
// Session mode detection
const sessionExists = fs.existsSync(sessionFolder)
const hasPlan = sessionExists && fs.existsSync(`${sessionFolder}/plan.md`)
const mode = (hasPlan || isContinue) ? 'continue' : 'new'
if (!sessionExists) {
bash(`mkdir -p ${sessionFolder}`)
}
```
---
### Phase 1: Initialize plan.md (Minimal)
```markdown
# Quick Planning Session
**Session ID**: ${sessionId}
**Topic**: ${planningTopic}
**Started**: ${getUtc8ISOString()}
**Mode**: ${mode}
---
## Input Context
${artifact ? `
**Source**: ${artifact.type} artifact
**Path**: ${artifact.path}
**Artifact Summary**:
${artifact.type === 'brainstorm' ? `
- Topic: ${artifactContent.topic}
- Top Ideas: ${artifactContent.top_ideas?.length || 0}
- Key Insights: ${artifactContent.key_insights?.slice(0, 2).join(', ') || 'N/A'}
` : artifact.type === 'analysis' ? `
- Topic: ${artifactContent.topic}
- Key Conclusions: ${artifactContent.key_conclusions?.length || 0}
- Recommendations: ${artifactContent.recommendations?.length || 0}
` : ''}
` : `
**User Input**: ${planningTopic}
`}
---
## Planning Dimensions
*To be populated after agent analysis*
---
## Key Decisions
*Conflict resolution and recommendations - to be populated*
---
## Implementation Plan
*Task breakdown - to be populated after synthesis*
---
## Progress
- [ ] Multi-agent analysis
- [ ] Conflict detection
- [ ] Plan synthesis
- [ ] Ready for execution
```
---
### Phase 2: Parallel Multi-Agent Analysis
```javascript
const analysisPrompt = artifact
? `Convert ${artifact.type} artifact to planning requirements and execute parallel analysis`
: `Create planning breakdown for: ${planningTopic}`
// Prepare context for agents
const agentContext = {
topic: planningTopic,
artifact: artifact ? {
type: artifact.type,
summary: extractArtifactSummary(artifactContent)
} : null,
planning_focus: determineFocusAreas(planningTopic),
constraints: extractConstraints(planningTopic, artifactContent)
}
// Agent 1: Architecture & Design
const archPromise = Bash({
command: `ccw cli -p "
PURPOSE: Architecture & high-level design planning for '${planningTopic}'
Success: Clear component decomposition, interface design, and data flow
TASK:
• Decompose problem into major components/modules
• Identify architectural patterns and integration points
• Design interfaces and data models
• Assess scalability and maintainability implications
• Propose architectural approach with rationale
MODE: analysis
CONTEXT: @**/*
${artifact ? `| Source artifact: ${artifact.type}` : ''}
EXPECTED:
- Component decomposition (box diagram in text)
- Module interfaces and responsibilities
- Data flow between components
- Architectural patterns applied
- Scalability assessment (1-5 rating)
- Risks from architectural perspective
CONSTRAINTS: Focus on long-term maintainability
" --tool gemini --mode analysis`,
run_in_background: true
})
// Agent 2: Implementation & Feasibility
const implPromise = Bash({
command: `ccw cli -p "
PURPOSE: Implementation approach & technical feasibility for '${planningTopic}'
Success: Concrete implementation strategy with realistic resource estimates
TASK:
• Evaluate technical feasibility of approach
• Identify required technologies and dependencies
• Estimate effort: high/medium/low + rationale
• Suggest implementation phases and milestones
• Highlight technical blockers or challenges
MODE: analysis
CONTEXT: @**/*
${artifact ? `| Source artifact: ${artifact.type}` : ''}
EXPECTED:
- Technology stack recommendation
- Implementation complexity: high|medium|low with justification
- Estimated effort breakdown (analysis/design/coding/testing/deployment)
- Key technical decisions with tradeoffs
- Potential blockers and mitigations
- Suggested implementation phases
- Reusable components or libraries
CONSTRAINTS: Realistic with current tech stack
" --tool codex --mode analysis`,
run_in_background: true
})
// Agent 3: Risk & Validation
const riskPromise = Bash({
command: `ccw cli -p "
PURPOSE: Risk analysis and validation strategy for '${planningTopic}'
Success: Comprehensive risk matrix with testing strategy
TASK:
• Identify technical risks and failure scenarios
• Assess business/timeline risks
• Define validation/testing strategy
• Suggest monitoring and observability requirements
• Rate overall risk level (low/medium/high)
MODE: analysis
CONTEXT: @**/*
${artifact ? `| Source artifact: ${artifact.type}` : ''}
EXPECTED:
- Risk matrix (likelihood × impact, 1-5 each)
- Top 3 technical risks with mitigations
- Top 3 timeline/resource risks with mitigations
- Testing strategy (unit/integration/e2e/performance)
- Deployment strategy and rollback plan
- Monitoring/observability requirements
- Overall risk rating with confidence (low/medium/high)
CONSTRAINTS: Be realistic, not pessimistic
" --tool claude --mode analysis`,
run_in_background: true
})
// Agent 4: Decisions & Recommendations
const decisionPromise = Bash({
command: `ccw cli -p "
PURPOSE: Strategic decisions and execution recommendations for '${planningTopic}'
Success: Clear recommended approach with tradeoff analysis
TASK:
• Synthesize all considerations into recommendations
• Clearly identify critical decision points
• Outline key tradeoffs (speed vs quality, scope vs timeline, etc.)
• Propose go/no-go decision criteria
• Suggest execution strategy and sequencing
MODE: analysis
CONTEXT: @**/*
${artifact ? `| Source artifact: ${artifact.type}` : ''}
EXPECTED:
- Primary recommendation with strong rationale
- Alternative approaches with pros/cons
- 2-3 critical decision points with recommended choices
- Key tradeoffs and what we're optimizing for
- Success metrics and go/no-go criteria
- Suggested execution sequencing
- Resource requirements and dependencies
CONSTRAINTS: Focus on actionable decisions, not analysis
" --tool gemini --mode analysis`,
run_in_background: true
})
// Wait for all parallel analyses
const [archResult, implResult, riskResult, decisionResult] = await Promise.all([
archPromise, implPromise, riskPromise, decisionPromise
])
```
---
### Phase 3: Aggregate Perspectives
```javascript
// Parse and structure agent findings
const perspectives = {
session_id: sessionId,
timestamp: getUtc8ISOString(),
topic: planningTopic,
source_artifact: artifact?.type || 'raw',
architecture: {
source: 'gemini (design)',
components: extractComponents(archResult),
interfaces: extractInterfaces(archResult),
patterns: extractPatterns(archResult),
scalability_rating: extractRating(archResult, 'scalability'),
risks_from_design: extractRisks(archResult)
},
implementation: {
source: 'codex (pragmatic)',
technology_stack: extractStack(implResult),
complexity: extractComplexity(implResult),
effort_breakdown: extractEffort(implResult),
blockers: extractBlockers(implResult),
phases: extractPhases(implResult)
},
validation: {
source: 'claude (systematic)',
risk_matrix: extractRiskMatrix(riskResult),
top_risks: extractTopRisks(riskResult),
testing_strategy: extractTestingStrategy(riskResult),
deployment_strategy: extractDeploymentStrategy(riskResult),
monitoring_requirements: extractMonitoring(riskResult),
overall_risk_rating: extractRiskRating(riskResult)
},
recommendation: {
source: 'gemini (synthesis)',
primary_approach: extractPrimaryApproach(decisionResult),
alternatives: extractAlternatives(decisionResult),
critical_decisions: extractDecisions(decisionResult),
tradeoffs: extractTradeoffs(decisionResult),
success_criteria: extractCriteria(decisionResult),
execution_sequence: extractSequence(decisionResult)
},
analysis_timestamp: getUtc8ISOString()
}
Write(`${sessionFolder}/perspectives.json`, JSON.stringify(perspectives, null, 2))
```
---
### Phase 4: Conflict Detection & Resolution
```javascript
// Analyze for conflicts and contradictions
const conflicts = detectConflicts({
arch_vs_impl: compareArchitectureAndImplementation(perspectives),
design_vs_risk: compareDesignAndRisk(perspectives),
effort_vs_scope: compareEffortAndScope(perspectives),
timeline_implications: extractTimingConflicts(perspectives)
})
// If conflicts exist, invoke arbitration agent
if (conflicts.critical.length > 0) {
const arbitrationResult = await Bash({
command: `ccw cli -p "
PURPOSE: Resolve planning conflicts and generate unified recommendation
Input: ${JSON.stringify(conflicts, null, 2)}
TASK:
• Review all conflicts presented
• Recommend resolution for each critical conflict
• Explain tradeoff choices
• Identify what we're optimizing for (speed/quality/risk/resource)
• Generate unified execution strategy
MODE: analysis
EXPECTED:
- For each conflict: recommended resolution + rationale
- Unified optimization criteria (what matters most?)
- Final recommendation with confidence level
- Any unresolved tensions that need user input
CONSTRAINTS: Be decisive, not fence-sitting
" --tool gemini --mode analysis`,
run_in_background: false
})
const conflictResolution = {
detected_conflicts: conflicts,
arbitration_result: arbitrationResult,
timestamp: getUtc8ISOString()
}
Write(`${sessionFolder}/conflicts.json`, JSON.stringify(conflictResolution, null, 2))
}
```
---
### Phase 5: Plan Synthesis & Task Breakdown
```javascript
const synthesisPrompt = `
Given the planning context:
- Topic: ${planningTopic}
- Architecture: ${perspectives.architecture.components.map(c => c.name).join(', ')}
- Implementation Complexity: ${perspectives.implementation.complexity}
- Timeline Risk: ${perspectives.validation.overall_risk_rating}
- Primary Recommendation: ${perspectives.recommendation.primary_approach.summary}
Generate a minimal but complete implementation plan with:
1. Task breakdown (5-8 major tasks)
2. Dependencies between tasks
3. For each task: what needs to be done, why, and key considerations
4. Success criteria for the entire effort
5. Known risks and mitigation strategies
Output as structured task list ready for execution.
`
const synthesisResult = await Bash({
command: `ccw cli -p "${synthesisPrompt}" --tool gemini --mode analysis`,
run_in_background: false
})
// Parse synthesis and generate task breakdown
const tasks = parseTaskBreakdown(synthesisResult)
const synthesis = {
session_id: sessionId,
planning_topic: planningTopic,
completed: getUtc8ISOString(),
// Summary
executive_summary: perspectives.recommendation.primary_approach.summary,
optimization_focus: extractOptimizationFocus(perspectives),
// Architecture
architecture_approach: perspectives.architecture.patterns[0] || 'TBD',
key_components: perspectives.architecture.components.slice(0, 5),
// Implementation
technology_stack: perspectives.implementation.technology_stack,
complexity_level: perspectives.implementation.complexity,
estimated_effort: perspectives.implementation.effort_breakdown,
// Risks & Validation
top_risks: perspectives.validation.top_risks.slice(0, 3),
testing_approach: perspectives.validation.testing_strategy,
// Execution
phases: perspectives.implementation.phases,
critical_path_tasks: extractCriticalPath(tasks),
total_tasks: tasks.length,
// Task breakdown (ready for unified-execute-with-file)
tasks: tasks.map(task => ({
id: task.id,
title: task.title,
description: task.description,
type: task.type,
dependencies: task.dependencies,
effort_estimate: task.effort,
success_criteria: task.criteria
}))
}
Write(`${sessionFolder}/synthesis.md`, formatSynthesisMarkdown(synthesis))
Write(`${sessionFolder}/synthesis.json`, JSON.stringify(synthesis, null, 2))
```
---
### Phase 6: Update plan.md with Results
```markdown
# Quick Planning Session
**Session ID**: ${sessionId}
**Topic**: ${planningTopic}
**Started**: ${startTime}
**Completed**: ${completionTime}
---
## Executive Summary
${synthesis.executive_summary}
**Optimization Focus**: ${synthesis.optimization_focus}
**Complexity**: ${synthesis.complexity_level}
**Estimated Effort**: ${formatEffort(synthesis.estimated_effort)}
---
## Architecture
**Primary Pattern**: ${synthesis.architecture_approach}
**Key Components**:
${synthesis.key_components.map((c, i) => `${i+1}. ${c.name}: ${c.responsibility}`).join('\n')}
---
## Implementation Strategy
**Technology Stack**:
${synthesis.technology_stack.map(t => `- ${t}`).join('\n')}
**Phases**:
${synthesis.phases.map((p, i) => `${i+1}. ${p.name} (${p.effort})`).join('\n')}
---
## Risk Assessment
**Overall Risk Level**: ${synthesis.top_risks[0].risk_level}
**Top 3 Risks**:
${synthesis.top_risks.map((r, i) => `
${i+1}. **${r.title}** (Impact: ${r.impact})
- Mitigation: ${r.mitigation}
`).join('\n')}
**Testing Approach**: ${synthesis.testing_approach}
---
## Execution Plan
**Total Tasks**: ${synthesis.total_tasks}
**Critical Path**: ${synthesis.critical_path_tasks.map(t => t.id).join(' → ')}
### Task Breakdown
${synthesis.tasks.map((task, i) => `
${i+1}. **${task.id}: ${task.title}** (Effort: ${task.effort_estimate})
- ${task.description}
- Depends on: ${task.dependencies.join(', ') || 'none'}
- Success: ${task.success_criteria}
`).join('\n')}
---
## Next Steps
**Recommended**: Execute with \`/workflow:unified-execute-with-file\` using:
\`\`\`
/workflow:unified-execute-with-file -p ${sessionFolder}/synthesis.json
\`\`\`
---
## Artifacts
- **Perspectives**: ${sessionFolder}/perspectives.json (all agent findings)
- **Conflicts**: ${sessionFolder}/conflicts.json (decision points and resolutions)
- **Synthesis**: ${sessionFolder}/synthesis.json (task breakdown for execution)
```
---
## Session Folder Structure
```
.workflow/.planning/{sessionId}/
├── plan.md # Minimal, actionable planning doc
├── perspectives.json # Multi-agent findings (architecture, impl, risk, decision)
├── conflicts.json # Detected conflicts and resolutions (if any)
├── synthesis.json # Task breakdown ready for execution
└── synthesis.md # Human-readable execution plan
```
---
## Multi-Agent Roles
| Agent | Focus | Input | Output |
|-------|-------|-------|--------|
| **Gemini (Design)** | Architecture & design patterns | Topic + constraints | Components, interfaces, patterns, scalability |
| **Codex (Pragmatic)** | Implementation reality | Topic + architecture | Tech stack, effort, phases, blockers |
| **Claude (Validation)** | Risk & testing | Architecture + impl | Risk matrix, test strategy, monitoring |
| **Gemini (Decision)** | Synthesis & strategy | All findings | Recommendations, tradeoffs, execution plan |
---
## Conflict Resolution Strategy
**Auto-Resolution for conflicts**:
1. **Architecture vs Implementation**: Recommend design-for-feasibility approach
2. **Scope vs Timeline**: Prioritize critical path, defer nice-to-haves
3. **Quality vs Speed**: Suggest iterative approach (MVP + iterations)
4. **Resource vs Effort**: Identify parallelizable tasks
**Require User Input for**:
- Strategic choices (which feature to prioritize?)
- Tool/technology decisions with strong team preferences
- Budget/resource constraints not stated in planning topic
---
## Continue & Resume
```bash
/workflow:quick-plan-with-file --continue "planning-topic"
```
When continuing:
1. Load existing plan.md and perspectives.json
2. Identify what's incomplete
3. Re-run affected agents (if planning has changed)
4. Update plan.md with new findings
5. Generate updated synthesis.json
---
## Integration Flow
```
Input Source:
├─ Raw task description
├─ Brainstorm synthesis.json
└─ Analysis conclusions.json
/workflow:quick-plan-with-file
plan.md + synthesis.json
/workflow:unified-execute-with-file
Implementation
```
---
## Usage Patterns
### Pattern 1: Quick Planning from Task
```bash
# User has a task, needs rapid multi-perspective plan
/workflow:quick-plan-with-file -y "实现实时通知系统支持推送和WebSocket"
# → Creates plan in ~5 minutes
# → Ready for execution
```
### Pattern 2: Convert Brainstorm to Executable Plan
```bash
# User completed brainstorm, wants to convert top idea to executable plan
/workflow:quick-plan-with-file --from brainstorm BS-notifications-2025-01-28
# → Reads synthesis.json from brainstorm
# → Generates implementation plan
# → Ready for unified-execute-with-file
```
### Pattern 3: From Analysis to Implementation
```bash
# Analysis completed, now need execution plan
/workflow:quick-plan-with-file --from analysis ANL-auth-architecture-2025-01-28
# → Reads conclusions.json from analysis
# → Generates planning with recommendations
# → Output task breakdown
```
### Pattern 4: Planning with Interactive Conflict Resolution
```bash
# Full planning with user involvement in decision-making
/workflow:quick-plan-with-file "新的支付流程集成"
# → Without -y flag
# → After conflict detection, asks user about tradeoffs
# → Generates plan based on user preferences
```
---
## Comparison with Other Workflows
| Feature | brainstorm | analyze | quick-plan | plan |
|---------|-----------|---------|-----------|------|
| **Purpose** | Ideation | Investigation | Lightweight planning | Detailed planning |
| **Multi-agent** | 3 perspectives | 2 CLI + explore | 4 concurrent agents | N/A (single) |
| **Documentation** | Extensive | Extensive | Minimal | Standard |
| **Output** | Ideas + synthesis | Conclusions | Executable tasks | IMPL_PLAN |
| **Typical Duration** | 30-60 min | 20-30 min | 5-10 min | 15-20 min |
| **User Interaction** | High (multi-round) | High (Q&A) | Low (decisions) | Medium |
---
## Error Handling
| Situation | Action |
|-----------|--------|
| Agents conflict on approach | Arbitration agent decides, document in conflicts.json |
| Missing critical files | Continue with available context, note limitations |
| Insufficient task breakdown | Ask user for planning focus areas |
| Effort estimate too high | Suggest MVP approach or phasing |
| Unclear requirements | Ask clarifying questions via AskUserQuestion |
| Agent timeout | Use last successful result, note partial analysis |
---
## Best Practices
1. **Use when**:
- You have clarity on WHAT but not HOW
- Need rapid multi-perspective planning
- Converting brainstorm/analysis into execution
- Want minimal planning overhead
2. **Avoid when**:
- Requirements are highly ambiguous (use brainstorm instead)
- Need deep investigation (use analyze instead)
- Want extensive planning document (use plan instead)
- No tech stack clarity (use analyze first)
3. **For best results**:
- Provide complete task/requirement description
- Include constraints and success criteria
- Specify preferences (speed vs quality vs risk)
- Review conflicts.json and make conscious tradeoff decisions
---
## Next Steps After Planning
### Feed to Execution
```bash
/workflow:unified-execute-with-file -p .workflow/.planning/{sessionId}/synthesis.json
```
### Detailed Planning if Needed
```bash
/workflow:plan "Based on quick-plan recommendations..."
```
### Continuous Refinement
```bash
/workflow:quick-plan-with-file --continue "{topic}" # Update plan with new constraints
```

View File

@@ -1,205 +0,0 @@
# Unified-Execute-With-File: Claude vs Codex Versions
## Overview
Two complementary implementations of the universal execution engine:
| Aspect | Claude CLI Command | Codex Prompt |
|--------|-------------------|--------------|
| **Location** | `.claude/commands/workflow/` | `.codex/prompts/` |
| **Format** | YAML frontmatter + Markdown | Simple Markdown + Variables |
| **Execution** | `/workflow:unified-execute-with-file` | Direct Codex execution |
| **Lines** | 807 (optimized) | 722 (adapted) |
| **Parameters** | CLI flags (`-y`, `-p`, `-m`) | Substitution variables (`$PLAN_PATH`, etc) |
---
## Format Differences
### Claude Version (CLI Command)
**Header (YAML)**:
```yaml
---
name: unified-execute-with-file
description: Universal execution engine...
argument-hint: "[-y|--yes] [-p|--plan <path>] [-m|--mode sequential|parallel]"
allowed-tools: TodoWrite(*), Task(*), ...
---
```
**Parameters**: CLI-style flags with short forms
```bash
/workflow:unified-execute-with-file -y -p PLAN_PATH -m parallel
```
### Codex Version (Prompt)
**Header (Simple)**:
```yaml
---
description: Universal execution engine...
argument-hint: "PLAN_PATH=\"<path>\" [EXECUTION_MODE=\"sequential|parallel\"]"
---
```
**Parameters**: Variable substitution with named arguments
```
PLAN_PATH=".workflow/IMPL_PLAN.md"
EXECUTION_MODE="parallel"
AUTO_CONFIRM="yes"
```
---
## Functional Equivalence
### Core Features (Identical)
Both versions support:
- ✅ Format-agnostic plan parsing (IMPL_PLAN.md, synthesis.json, conclusions.json)
- ✅ Multi-agent orchestration (code-developer, test-fix-agent, doc-generator, etc)
- ✅ Automatic dependency resolution with topological sort
- ✅ Parallel execution with wave-based grouping (max 3 tasks/wave)
- ✅ Unified event logging (execution-events.md as SINGLE SOURCE OF TRUTH)
- ✅ Knowledge chain: agents read all previous executions
- ✅ Incremental execution with resume capability
- ✅ Error handling: retry/skip/abort logic
- ✅ Session management and folder organization
### Session Structure (Identical)
Both create:
```
.workflow/.execution/{executionId}/
├── execution.md # Execution plan and status
└── execution-events.md # Unified execution log (SINGLE SOURCE OF TRUTH)
```
---
## Key Adaptations
### Claude CLI Version
**Optimizations**:
- Direct access to Claude Code tools (TodoWrite, Task, AskUserQuestion)
- CLI tool integration (`ccw cli`)
- Background agent execution with run_in_background flag
- Direct file system operations via Bash
**Structure**:
- Comprehensive Implementation Details section
- Explicit allowed-tools configuration
- Integration with workflow command system
### Codex Version
**Adaptations**:
- Simplified execution context (no direct tool access)
- Variable substitution for parameter passing
- Streamlined phase explanations
- Focused on core logic and flow
- Self-contained event logging
**Benefits**:
- Works with Codex's execution model
- Simpler parameter interface
- 85 fewer lines while maintaining all core functionality
---
## Parameter Mapping
| Concept | Claude | Codex |
|---------|--------|-------|
| Plan path | `-p path/to/plan.md` | `PLAN_PATH="path/to/plan.md"` |
| Execution mode | `-m sequential\|parallel` | `EXECUTION_MODE="sequential\|parallel"` |
| Auto-confirm | `-y, --yes` | `AUTO_CONFIRM="yes"` |
| Context focus | `"execution context"` | `EXECUTION_CONTEXT="focus area"` |
---
## Recommended Usage
### Use Claude Version When:
- Using Claude Code CLI environment
- Need direct integration with workflow system
- Want full tool access (TodoWrite, Task, AskUserQuestion)
- Prefer CLI flag syntax
- Building multi-command workflows
### Use Codex Version When:
- Executing within Codex directly
- Need simpler execution model
- Prefer variable substitution
- Want standalone execution
- Integrating with Codex command chains
---
## Event Logging (Unified)
Both versions produce identical execution-events.md format:
```markdown
## Task {id} - {STATUS} {emoji}
**Timestamp**: {ISO8601}
**Duration**: {ms}
**Agent**: {agent_type}
### Execution Summary
{summary}
### Generated Artifacts
- `path/to/file` (size)
### Notes for Next Agent
- Key decisions
- Issues identified
- Ready for: NEXT_TASK_ID
---
```
---
## Migration Path
If switching between Claude and Codex versions:
1. **Same session ID format**: Both use `.workflow/.execution/{executionId}/`
2. **Same event log structure**: execution-events.md is 100% compatible
3. **Same artifact locations**: Files generated at project paths (e.g., `src/types/auth.ts`)
4. **Same agent selection**: Both use identical selectBestAgent() strategy
5. **Same parallelization rules**: Identical wave grouping and file conflict detection
You can:
- Start execution with Claude, resume with Codex
- Start with Codex, continue with Claude
- Mix both in multi-step workflows
---
## Statistics
| Metric | Claude | Codex |
|--------|--------|-------|
| **Lines** | 807 | 722 |
| **Size** | 25 KB | 22 KB |
| **Phases** | 4 full phases | 4 phases (adapted) |
| **Agent types** | 6+ supported | 6+ supported |
| **Parallelization** | Max 3 tasks/wave | Max 3 tasks/wave |
| **Error handling** | retry/skip/abort | retry/skip/abort |
---
## Implementation Timeline
1. **Initial Claude version**: Full unified-execute-with-file.md (1094 lines)
2. **Claude optimization**: Consolidated duplicates (807 lines, -26%)
3. **Codex adaptation**: Format-adapted version (722 lines)
Both versions represent same core logic with format-specific optimizations.

View File

@@ -231,53 +231,97 @@ ${newFocusFromUser}
### Phase 2: Divergent Exploration (Multi-Perspective)
#### Step 2.1: Creative Perspective Analysis
Launch 3 parallel agents for multi-perspective brainstorming:
Explore from creative/innovative angle:
```javascript
const cliPromises = []
- Think beyond obvious solutions - what would be surprising/delightful?
- Cross-domain inspiration (what can we learn from other industries?)
- Challenge assumptions - what if the opposite were true?
- Generate 'moonshot' ideas alongside practical ones
- Consider future trends and emerging technologies
// Agent 1: Creative/Innovative Perspective (Gemini)
cliPromises.push(
Bash({
command: `ccw cli -p "
PURPOSE: Creative brainstorming for '$TOPIC' - generate innovative, unconventional ideas
Success: 5+ unique creative solutions that push boundaries
Output:
TASK:
• Think beyond obvious solutions - what would be surprising/delightful?
• Explore cross-domain inspiration (what can we learn from other industries?)
• Challenge assumptions - what if the opposite were true?
• Generate 'moonshot' ideas alongside practical ones
• Consider future trends and emerging technologies
MODE: analysis
CONTEXT: @**/* | Topic: $TOPIC
Exploration vectors: ${explorationVectors.map(v => v.title).join(', ')}
EXPECTED:
- 5+ creative ideas with brief descriptions
- Each idea rated: novelty (1-5), potential impact (1-5)
- Key assumptions challenged
- Cross-domain inspirations
- One 'crazy' idea that might just work
#### Step 2.2: Pragmatic Perspective Analysis
CONSTRAINTS: ${brainstormMode === 'structured' ? 'Keep ideas technically feasible' : 'No constraints - think freely'}
" --tool gemini --mode analysis`,
run_in_background: true
})
)
Evaluate from implementation reality:
// Agent 2: Pragmatic/Implementation Perspective (Codex)
cliPromises.push(
Bash({
command: \`ccw cli -p "
PURPOSE: Pragmatic analysis for '$TOPIC' - focus on implementation reality
Success: Actionable approaches with clear implementation paths
- Technical feasibility of core concept
- Existing patterns/libraries that could help
- Integration with current codebase
- Implementation complexity estimates
- Potential technical blockers
- Incremental implementation approach
TASK:
• Evaluate technical feasibility of core concept
• Identify existing patterns/libraries that could help
• Consider integration with current codebase
• Estimate implementation complexity
• Highlight potential technical blockers
• Suggest incremental implementation approach
Output:
MODE: analysis
CONTEXT: @**/* | Topic: $TOPIC
Exploration vectors: \${explorationVectors.map(v => v.title).join(', ')}
EXPECTED:
- 3-5 practical implementation approaches
- Each rated: effort (1-5), risk (1-5), reuse potential (1-5)
- Technical dependencies identified
- Quick wins vs long-term solutions
- Recommended starting point
#### Step 2.3: Systematic Perspective Analysis
CONSTRAINTS: Focus on what can actually be built with current tech stack
" --tool codex --mode analysis\`,
run_in_background: true
})
)
Analyze from architectural standpoint:
// Agent 3: Systematic/Architectural Perspective (Claude)
cliPromises.push(
Bash({
command: \`ccw cli -p "
PURPOSE: Systematic analysis for '$TOPIC' - architectural and structural thinking
Success: Well-structured solution framework with clear tradeoffs
- Decompose the problem into sub-problems
- Identify architectural patterns that apply
- Map dependencies and interactions
- Consider scalability implications
- Evaluate long-term maintainability
- Propose systematic solution structure
TASK:
• Decompose the problem into sub-problems
• Identify architectural patterns that apply
• Map dependencies and interactions
• Consider scalability implications
• Evaluate long-term maintainability
• Propose systematic solution structure
Output:
MODE: analysis
CONTEXT: @**/* | Topic: $TOPIC
Exploration vectors: \${explorationVectors.map(v => v.title).join(', ')}
EXPECTED:
- Problem decomposition diagram (text)
- 2-3 architectural approaches with tradeoffs
- Dependency mapping
@@ -285,6 +329,29 @@ Output:
- Recommended architecture pattern
- Risk matrix
CONSTRAINTS: Consider existing system architecture
" --tool claude --mode analysis\`,
run_in_background: true
})
)
// Wait for all CLI analyses to complete
const [creativeResult, pragmaticResult, systematicResult] = await Promise.all(cliPromises)
// Parse results from each perspective
const creativeIdeas = parseCreativeResult(creativeResult)
const pragmaticApproaches = parsePragmaticResult(pragmaticResult)
const architecturalOptions = parseSystematicResult(systematicResult)
```
**Multi-Perspective Coordination**:
| Agent | Perspective | Tool | Focus Areas |
|-------|-------------|------|-------------|
| 1 | Creative/Innovative | Gemini | Novel ideas, cross-domain inspiration, moonshots |
| 2 | Pragmatic/Implementation | Codex | Feasibility, tech stack, blockers, quick wins |
| 3 | Systematic/Architectural | Claude | Decomposition, patterns, scalability, risks |
#### Step 2.4: Aggregate Multi-Perspective Findings
```javascript

View File

@@ -0,0 +1,530 @@
---
description: Merge multiple planning/brainstorm/analysis outputs, resolve conflicts, and synthesize unified plan. Multi-team input aggregation and plan crystallization
argument-hint: "PATTERN=\"<plan pattern or topic>\" [--rule=consensus|priority|hierarchy] [--output=<path>] [--auto] [--verbose]"
---
# Codex Merge-Plans-With-File Prompt
## Overview
Plan aggregation and conflict resolution workflow. Takes multiple planning artifacts (brainstorm conclusions, analysis recommendations, quick-plans, implementation plans) and synthesizes them into a unified, conflict-resolved execution plan.
**Core workflow**: Load Sources → Parse Plans → Conflict Analysis → Arbitration → Unified Plan
**Key features**:
- **Multi-Source Support**: brainstorm, analysis, quick-plan, IMPL_PLAN, task JSONs
- **Conflict Detection**: Identify contradictions across all input plans
- **Resolution Rules**: consensus, priority-based, or hierarchical resolution
- **Unified Synthesis**: Single authoritative plan from multiple perspectives
- **Decision Tracking**: Full audit trail of conflicts and resolutions
## Target Pattern
**$PATTERN**
- `--rule`: Conflict resolution (consensus | priority | hierarchy) - consensus by default
- `--output`: Output directory (default: .workflow/.merged/{pattern})
- `--auto`: Auto-resolve conflicts using rule, skip confirmations
- `--verbose`: Include detailed conflict analysis
## Execution Process
```
Phase 1: Discovery & Loading
├─ Search for artifacts matching pattern
├─ Load synthesis.json, conclusions.json, IMPL_PLAN.md, task JSONs
├─ Parse into normalized task structure
└─ Validate completeness
Phase 2: Plan Normalization
├─ Convert all formats to common task representation
├─ Extract: tasks, dependencies, effort, risks
├─ Identify scope and boundaries
└─ Aggregate recommendations
Phase 3: Conflict Detection (Parallel)
├─ Architecture conflicts: different design approaches
├─ Task conflicts: overlapping or duplicated tasks
├─ Effort conflicts: different estimates
├─ Risk conflicts: different risk assessments
├─ Scope conflicts: different feature sets
└─ Generate conflict matrix
Phase 4: Conflict Resolution
├─ Analyze source rationale for each conflict
├─ Apply resolution rule (consensus / priority / hierarchy)
├─ Escalate unresolvable conflicts to user (unless --auto)
├─ Document decision rationale
└─ Generate resolutions.json
Phase 5: Plan Synthesis
├─ Merge task lists (deduplicate, combine insights)
├─ Integrate dependencies
├─ Consolidate effort and risk estimates
├─ Generate execution sequence
└─ Output unified-plan.json
Output:
├─ .workflow/.merged/{sessionId}/merge.md (process log)
├─ .workflow/.merged/{sessionId}/source-index.json (input sources)
├─ .workflow/.merged/{sessionId}/conflicts.json (conflict matrix)
├─ .workflow/.merged/{sessionId}/resolutions.json (decisions)
├─ .workflow/.merged/{sessionId}/unified-plan.json (for execution)
└─ .workflow/.merged/{sessionId}/unified-plan.md (human-readable)
```
## Implementation Details
### Phase 1: Discover & Load Sources
```javascript
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
const mergeSlug = "$PATTERN".toLowerCase()
.replace(/[*?]/g, '-')
.replace(/[^a-z0-9\u4e00-\u9fa5-]+/g, '-')
.substring(0, 30)
const sessionId = `MERGE-${mergeSlug}-${getUtc8ISOString().substring(0, 10)}`
const sessionFolder = `.workflow/.merged/${sessionId}`
bash(`mkdir -p ${sessionFolder}`)
// Search paths for matching artifacts
const searchPaths = [
`.workflow/.brainstorm/*${$PATTERN}*/synthesis.json`,
`.workflow/.analysis/*${$PATTERN}*/conclusions.json`,
`.workflow/.planning/*${$PATTERN}*/synthesis.json`,
`.workflow/.plan/*${$PATTERN}*IMPL_PLAN.md`,
`.workflow/**/*${$PATTERN}*.json`
]
// Load and validate each source
const sourcePlans = []
for (const pattern of searchPaths) {
const matches = glob(pattern)
for (const path of matches) {
const plan = loadAndParsePlan(path)
if (plan?.tasks?.length > 0) {
sourcePlans.push({ path, type: inferType(path), plan })
}
}
}
```
### Phase 2: Normalize Plans
Convert all source formats to common structure:
```javascript
const normalizedPlans = sourcePlans.map((src, idx) => ({
index: idx,
source: src.path,
type: src.type,
metadata: {
title: src.plan.title || `Plan ${idx + 1}`,
topic: src.plan.topic,
complexity: src.plan.complexity_level || 'unknown'
},
tasks: src.plan.tasks.map(task => ({
id: `T${idx}-${task.id || task.title.substring(0, 20)}`,
title: task.title,
description: task.description,
type: task.type || inferTaskType(task),
priority: task.priority || 'normal',
effort: { estimated: task.effort_estimate, from_plan: idx },
risk: { level: task.risk_level || 'medium', from_plan: idx },
dependencies: task.dependencies || [],
source_plan_index: idx
}))
}))
```
### Phase 3: Parallel Conflict Detection
Launch parallel agents to detect and analyze conflicts:
```javascript
// Parallel conflict detection with CLI agents
const conflictPromises = []
// Agent 1: Detect effort and task conflicts
conflictPromises.push(
Bash({
command: `ccw cli -p "
PURPOSE: Detect effort conflicts and task duplicates across multiple plans
Success: Complete identification of conflicting estimates and duplicate tasks
TASK:
• Identify tasks with significantly different effort estimates (>50% variance)
• Detect duplicate/similar tasks across plans
• Analyze effort estimation reasoning
• Suggest resolution for each conflict
MODE: analysis
CONTEXT:
- Plan 1: ${JSON.stringify(normalizedPlans[0]?.tasks?.slice(0,3) || [], null, 2)}
- Plan 2: ${JSON.stringify(normalizedPlans[1]?.tasks?.slice(0,3) || [], null, 2)}
- [Additional plans...]
EXPECTED:
- Effort conflicts detected (task name, estimate in each plan, variance %)
- Duplicate task analysis (similar tasks, scope differences)
- Resolution recommendation for each conflict
- Confidence level for each detection
CONSTRAINTS: Focus on significant conflicts (>30% effort variance)
" --tool gemini --mode analysis`,
run_in_background: true
})
)
// Agent 2: Analyze architecture and scope conflicts
conflictPromises.push(
Bash({
command: \`ccw cli -p "
PURPOSE: Analyze architecture and scope conflicts across plans
Success: Clear identification of design approach differences and scope gaps
TASK:
• Identify different architectural approaches in plans
• Detect scope differences (features included/excluded)
• Analyze design philosophy conflicts
• Suggest approach to reconcile different visions
MODE: analysis
CONTEXT:
- Plan 1 architecture: \${normalizedPlans[0]?.metadata?.complexity || 'unknown'}
- Plan 2 architecture: \${normalizedPlans[1]?.metadata?.complexity || 'unknown'}
- Different design approaches detected: \${JSON.stringify(['approach1', 'approach2'])}
EXPECTED:
- Architecture conflicts identified (approach names and trade-offs)
- Scope conflicts (features/components in plan A but not B, vice versa)
- Design philosophy alignment/misalignment
- Recommendation for unified approach
- Pros/cons of each architectural approach
CONSTRAINTS: Consider both perspectives objectively
" --tool codex --mode analysis\`,
run_in_background: true
})
)
// Agent 3: Analyze risk assessment conflicts
conflictPromises.push(
Bash({
command: \`ccw cli -p "
PURPOSE: Analyze risk assessment conflicts across plans
Success: Unified risk assessment with conflict resolution
TASK:
• Identify tasks/areas with significantly different risk ratings
• Analyze risk assessment reasoning
• Detect missing risks in some plans
• Propose unified risk assessment
MODE: analysis
CONTEXT:
- Risk areas with disagreement: [list areas]
- Plan 1 risk ratings: [risk matrix]
- Plan 2 risk ratings: [risk matrix]
EXPECTED:
- Risk conflicts identified (area, plan A rating, plan B rating)
- Explanation of why assessments differ
- Missing risks analysis (important in one plan but not others)
- Unified risk rating recommendation
- Confidence level for each assessment
CONSTRAINTS: Be realistic in risk assessment, not pessimistic
" --tool claude --mode analysis\`,
run_in_background: true
})
)
// Agent 4: Synthesize conflicts into resolution strategy
conflictPromises.push(
Bash({
command: \`ccw cli -p "
PURPOSE: Synthesize all conflicts into unified resolution strategy
Success: Clear path to merge plans with informed trade-off decisions
TASK:
• Analyze all detected conflicts holistically
• Identify which conflicts are critical vs. non-critical
• Propose resolution for each conflict type
• Suggest unified approach that honors valid insights from all plans
MODE: analysis
CONTEXT:
- Total conflicts detected: [number]
- Conflict types: effort, architecture, scope, risk
- Resolution rule: \${resolutionRule}
- Plan importance: \${normalizedPlans.map(p => p.metadata.title).join(', ')}
EXPECTED:
- Conflict priority ranking (critical, important, minor)
- Recommended resolution for each conflict
- Rationale for each recommendation
- Potential issues with proposed resolution
- Fallback options if recommendation not accepted
- Overall merge strategy and sequencing
CONSTRAINTS: Aim for solution that maximizes learning from all perspectives
" --tool gemini --mode analysis\`,
run_in_background: true
})
)
// Wait for all conflict detection agents to complete
const [effortConflicts, archConflicts, riskConflicts, resolutionStrategy] =
await Promise.all(conflictPromises)
// Parse and consolidate all conflict findings
const allConflicts = {
effort: parseEffortConflicts(effortConflicts),
architecture: parseArchConflicts(archConflicts),
risk: parseRiskConflicts(riskConflicts),
strategy: parseResolutionStrategy(resolutionStrategy),
timestamp: getUtc8ISOString()
}
Write(\`\${sessionFolder}/conflicts.json\`, JSON.stringify(allConflicts, null, 2))
```
**Conflict Detection Workflow**:
| Agent | Conflict Type | Focus | Output |
|-------|--------------|--------|--------|
| Gemini | Effort & Tasks | Duplicate detection, estimate variance | Conflicts with variance %, resolution suggestions |
| Codex | Architecture & Scope | Design approach differences | Design conflicts, scope gaps, recommendations |
| Claude | Risk Assessment | Risk rating disagreements | Risk conflicts, missing risks, unified assessment |
| Gemini | Resolution Strategy | Holistic synthesis | Priority ranking, resolution path, trade-offs |
### Phase 4: Resolve Conflicts
**Rule: Consensus (default)**
- Use median/average of conflicting estimates
- Merge scope differences
- Document minority viewpoints
**Rule: Priority**
- First plan has highest authority
- Later plans supplement but don't override
**Rule: Hierarchy**
- User ranks plan importance
- Higher-ranked plan wins conflicts
```javascript
const resolutions = {}
if (rule === 'consensus') {
for (const conflict of conflicts.effort) {
resolutions[conflict.task] = {
resolved: calculateMedian(conflict.estimates),
method: 'consensus-median',
rationale: 'Used median of all estimates'
}
}
} else if (rule === 'priority') {
for (const conflict of conflicts.effort) {
const primary = conflict.estimates[0] // First plan
resolutions[conflict.task] = {
resolved: primary.value,
method: 'priority-based',
rationale: `Selected from plan ${primary.from_plan} (highest priority)`
}
}
} else if (rule === 'hierarchy') {
// Request user ranking if not --auto
const ranking = getUserPlanRanking(normalizedPlans)
// Apply hierarchy-based resolution
}
Write(`${sessionFolder}/resolutions.json`, JSON.stringify(resolutions, null, 2))
```
### Phase 5: Generate Unified Plan
```javascript
const unifiedPlan = {
session_id: sessionId,
merge_timestamp: getUtc8ISOString(),
summary: {
total_source_plans: sourcePlans.length,
original_tasks: allTasks.length,
merged_tasks: deduplicatedTasks.length,
conflicts_resolved: Object.keys(resolutions).length,
resolution_rule: rule
},
tasks: deduplicatedTasks.map(task => ({
id: task.id,
title: task.title,
description: task.description,
effort: task.resolved_effort,
risk: task.resolved_risk,
dependencies: task.merged_dependencies,
source_plans: task.contributing_plans
})),
execution_sequence: topologicalSort(tasks),
critical_path: identifyCriticalPath(tasks),
risks: aggregateRisks(tasks),
success_criteria: aggregateCriteria(tasks)
}
Write(`${sessionFolder}/unified-plan.json`, JSON.stringify(unifiedPlan, null, 2))
```
### Phase 6: Generate Human-Readable Plan
```markdown
# Merged Planning Session
**Session ID**: ${sessionId}
**Pattern**: $PATTERN
**Created**: ${timestamp}
---
## Merge Summary
**Source Plans**: ${summary.total_source_plans}
**Original Tasks**: ${summary.original_tasks}
**Merged Tasks**: ${summary.merged_tasks}
**Conflicts Resolved**: ${summary.conflicts_resolved}
**Resolution Method**: ${summary.resolution_rule}
---
## Unified Task List
${tasks.map((task, i) => `
${i+1}. **${task.id}: ${task.title}**
- Effort: ${task.effort}
- Risk: ${task.risk}
- From plans: ${task.source_plans.join(', ')}
`).join('\n')}
---
## Execution Sequence
**Critical Path**: ${critical_path.join(' → ')}
---
## Conflict Resolution Report
${Object.entries(resolutions).map(([key, res]) => `
- **${key}**: ${res.rationale}
`).join('\n')}
---
## Next Steps
**Execute**:
\`\`\`
/workflow:unified-execute-with-file -p ${sessionFolder}/unified-plan.json
\`\`\`
```
## Session Folder Structure
```
.workflow/.merged/{sessionId}/
├── merge.md # Process log
├── source-index.json # All input sources
├── conflicts.json # Detected conflicts
├── resolutions.json # How resolved
├── unified-plan.json # Merged plan (for execution)
└── unified-plan.md # Human-readable
```
## Resolution Rules Comparison
| Rule | Method | Best For | Tradeoff |
|------|--------|----------|----------|
| **Consensus** | Median/average | Similar-quality inputs | May miss extremes |
| **Priority** | First wins | Clear authority order | Discards alternatives |
| **Hierarchy** | User-ranked | Mixed stakeholders | Needs user input |
## Input Format Support
| Source Type | Detection Pattern | Parsing |
|-------------|-------------------|---------|
| Brainstorm | `.brainstorm/*/synthesis.json` | Top ideas → tasks |
| Analysis | `.analysis/*/conclusions.json` | Recommendations → tasks |
| Quick-Plan | `.planning/*/synthesis.json` | Direct task list |
| IMPL_PLAN | `*IMPL_PLAN.md` | Markdown → tasks |
| Task JSON | `*.json` with `tasks` | Direct mapping |
## Error Handling
| Situation | Action |
|-----------|--------|
| No plans found | List available plans, suggest search terms |
| Incompatible format | Skip, continue with others |
| Circular dependencies | Alert user, suggest manual review |
| Unresolvable conflict | Require user decision (unless --auto) |
## Integration Flow
```
Brainstorm Sessions / Analyses / Plans
├─ synthesis.json (session 1)
├─ conclusions.json (session 2)
├─ synthesis.json (session 3)
merge-plans-with-file
├─ unified-plan.json
unified-execute-with-file
Implementation
```
## Usage Patterns
**Pattern 1: Merge all auth-related plans**
```
PATTERN="authentication" --rule=consensus --auto
→ Finds all auth plans
→ Merges with consensus method
```
**Pattern 2: Prioritized merge**
```
PATTERN="payment" --rule=priority
→ First plan has authority
→ Others supplement
```
**Pattern 3: Team input merge**
```
PATTERN="feature-*" --rule=hierarchy
→ Asks for plan ranking
→ Applies hierarchy resolution
```
---
**Now execute merge-plans-with-file for pattern**: $PATTERN

View File

@@ -0,0 +1,450 @@
---
description: Multi-agent rapid planning with minimal documentation, conflict resolution, and actionable synthesis. Lightweight planning from raw task, brainstorm, or analysis artifacts
argument-hint: "TOPIC=\"<planning topic or task>\" [--from=brainstorm|analysis|task|raw] [--perspectives=arch,impl,risk,decision] [--auto] [--verbose]"
---
# Codex Quick-Plan-With-File Prompt
## Overview
Multi-agent rapid planning workflow with **minimal documentation overhead**. Coordinates parallel agent analysis (architecture, implementation, validation, decision), synthesizes conflicting perspectives into actionable decisions, and generates an implementation-ready plan.
**Core workflow**: Parse Input → Parallel Analysis → Conflict Resolution → Plan Synthesis → Output
**Key features**:
- **Format Agnostic**: Consumes brainstorm conclusions, analysis recommendations, quick tasks, or raw descriptions
- **Minimal Docs**: Single plan.md (no lengthy timeline documentation)
- **Parallel Multi-Agent**: 4 concurrent perspectives for rapid analysis
- **Conflict Resolution**: Automatic conflict detection and synthesis
- **Actionable Output**: Direct task breakdown ready for execution
## Target Planning
**$TOPIC**
- `--from`: Input source type (brainstorm | analysis | task | raw) - auto-detected if omitted
- `--perspectives`: Which perspectives to use (arch, impl, risk, decision) - all by default
- `--auto`: Auto-confirm decisions, minimal user prompts
- `--verbose`: Verbose output with all reasoning
## Execution Process
```
Phase 1: Input Validation & Loading
├─ Parse input: topic | artifact reference
├─ Load artifact if referenced (synthesis.json | conclusions.json)
├─ Extract constraints and key requirements
└─ Initialize session folder
Phase 2: Parallel Multi-Agent Analysis (concurrent)
├─ Agent 1 (Architecture): Design decomposition, patterns, scalability
├─ Agent 2 (Implementation): Tech stack, feasibility, effort estimates
├─ Agent 3 (Validation): Risk matrix, testing strategy, monitoring
├─ Agent 4 (Decision): Recommendations, tradeoffs, execution strategy
└─ Aggregate findings into perspectives.json
Phase 3: Conflict Detection & Resolution
├─ Detect: effort conflicts, architecture conflicts, risk conflicts
├─ Analyze rationale for each conflict
├─ Synthesis via arbitration: generate unified recommendation
├─ Document conflicts and resolutions
└─ Update plan.md
Phase 4: Plan Synthesis
├─ Consolidate all insights
├─ Generate task breakdown (5-8 major tasks)
├─ Create execution strategy and dependencies
├─ Document assumptions and risks
└─ Output plan.md + synthesis.json
Output:
├─ .workflow/.planning/{sessionId}/plan.md (minimal, actionable)
├─ .workflow/.planning/{sessionId}/perspectives.json (agent findings)
├─ .workflow/.planning/{sessionId}/conflicts.json (decision points)
└─ .workflow/.planning/{sessionId}/synthesis.json (task breakdown for execution)
```
## Implementation Details
### Phase 1: Session Setup & Input Loading
```javascript
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
// Parse input
const planSlug = "$TOPIC".toLowerCase()
.replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')
.substring(0, 30)
const sessionId = `PLAN-${planSlug}-${getUtc8ISOString().substring(0, 10)}`
const sessionFolder = `.workflow/.planning/${sessionId}`
// Detect input type
let artifact = null
if ($TOPIC.startsWith('BS-') || "$TOPIC".includes('brainstorm')) {
artifact = loadBrainstormArtifact($TOPIC)
} else if ($TOPIC.startsWith('ANL-') || "$TOPIC".includes('analysis')) {
artifact = loadAnalysisArtifact($TOPIC)
}
bash(`mkdir -p ${sessionFolder}`)
```
### Phase 2: Parallel Multi-Agent Analysis
Run 4 agents in parallel using ccw cli:
```javascript
// Launch all 4 agents concurrently with Bash run_in_background
const agentPromises = []
// Agent 1 - Architecture (Gemini)
agentPromises.push(
Bash({
command: `ccw cli -p "
PURPOSE: Architecture & high-level design for '${planningTopic}'
Success: Clear component decomposition and architectural approach
TASK:
• Decompose problem into major components/modules
• Identify architectural patterns and integration points
• Design component interfaces and data models
• Assess scalability and maintainability implications
• Propose architectural approach with rationale
MODE: analysis
CONTEXT: @**/*
${artifact ? \`| Source artifact: \${artifact.type}\` : ''}
EXPECTED:
- Component decomposition (list with responsibilities)
- Module interfaces and contracts
- Data flow between components
- Architectural patterns applied (e.g., MVC, Event-Driven, etc.)
- Scalability assessment (1-5 rating with rationale)
- Architectural risks identified
CONSTRAINTS: Focus on long-term maintainability and extensibility
" --tool gemini --mode analysis`,
run_in_background: true
})
)
// Agent 2 - Implementation (Codex)
agentPromises.push(
Bash({
command: \`ccw cli -p "
PURPOSE: Implementation approach & technical feasibility for '\${planningTopic}'
Success: Concrete implementation strategy with realistic estimates
TASK:
• Evaluate technical feasibility of proposed approach
• Identify required technologies and dependencies
• Estimate effort: analysis/design/coding/testing/deployment
• Suggest implementation phases and milestones
• Highlight technical blockers and challenges
MODE: analysis
CONTEXT: @**/*
\${artifact ? \`| Source artifact: \${artifact.type}\` : ''}
EXPECTED:
- Technology stack recommendation (languages, frameworks, tools)
- Implementation complexity: high|medium|low (with justification)
- Effort breakdown (hours or complexity: analysis, design, coding, testing, deployment)
- Key technical decisions with tradeoffs explained
- Potential blockers and mitigation strategies
- Suggested implementation phases with sequencing
- Reusable components or libraries identified
CONSTRAINTS: Realistic with current tech stack
" --tool codex --mode analysis\`,
run_in_background: true
})
)
// Agent 3 - Validation & Risk (Claude)
agentPromises.push(
Bash({
command: \`ccw cli -p "
PURPOSE: Risk analysis and validation strategy for '\${planningTopic}'
Success: Comprehensive risk matrix with testing and deployment strategy
TASK:
• Identify technical risks and failure scenarios
• Assess timeline and resource risks
• Define validation/testing strategy (unit, integration, e2e, performance)
• Suggest monitoring and observability requirements
• Propose deployment strategy and rollback plan
MODE: analysis
CONTEXT: @**/*
\${artifact ? \`| Source artifact: \${artifact.type}\` : ''}
EXPECTED:
- Risk matrix (likelihood × impact, each 1-5)
- Top 3 technical risks with mitigation approaches
- Top 3 timeline/resource risks with mitigation
- Testing strategy (what to test, how, when, acceptance criteria)
- Deployment strategy (staged rollout, blue-green, canary, etc.)
- Rollback plan and recovery procedures
- Monitoring/observability requirements (metrics, logs, alerts)
- Overall risk rating: low|medium|high (with confidence)
CONSTRAINTS: Be realistic, not pessimistic
" --tool claude --mode analysis\`,
run_in_background: true
})
)
// Agent 4 - Strategic Decision (Gemini)
agentPromises.push(
Bash({
command: \`ccw cli -p "
PURPOSE: Strategic decisions and execution recommendations for '\${planningTopic}'
Success: Clear recommended approach with tradeoff analysis
TASK:
• Synthesize all perspectives into strategic recommendations
• Identify 2-3 critical decision points with recommended choices
• Clearly outline key tradeoffs (speed vs quality, scope vs timeline, risk vs cost)
• Propose go/no-go decision criteria and success metrics
• Suggest execution strategy and resource sequencing
MODE: analysis
CONTEXT: @**/*
\${artifact ? \`| Source artifact: \${artifact.type}\` : ''}
EXPECTED:
- Primary recommendation with strong rationale (1-2 paragraphs)
- Alternative approaches with pros/cons (2-3 alternatives)
- 2-3 critical decision points:
- What decision needs to be made
- Trade-offs for each option
- Recommended choice and why
- Key trade-offs explained (what we're optimizing for: speed/quality/risk/cost)
- Success metrics and go/no-go criteria
- Resource requirements and critical path items
- Suggested execution sequencing and phases
CONSTRAINTS: Focus on actionable decisions, provide clear rationale
" --tool gemini --mode analysis\`,
run_in_background: true
})
)
// Wait for all agents to complete
const [archResult, implResult, riskResult, decisionResult] = await Promise.all(agentPromises)
// Parse and extract findings from each agent result
const architecture = parseArchitectureResult(archResult)
const implementation = parseImplementationResult(implResult)
const validation = parseValidationResult(riskResult)
const recommendation = parseDecisionResult(decisionResult)
```
**Agent Focus Areas**:
| Agent | Perspective | Focus Areas |
|-------|-------------|------------|
| Gemini (Design) | Architecture patterns | Components, interfaces, scalability, patterns |
| Codex (Build) | Implementation reality | Tech stack, complexity, effort, blockers |
| Claude (Validate) | Risk & testing | Risk matrix, testing strategy, deployment, monitoring |
| Gemini (Decide) | Strategic synthesis | Recommendations, trade-offs, critical decisions |
### Phase 3: Parse & Aggregate Perspectives
```javascript
const perspectives = {
session_id: sessionId,
topic: "$TOPIC",
timestamp: getUtc8ISOString(),
architecture: {
components: [...],
patterns: [...],
scalability_rating: 3,
risks: [...]
},
implementation: {
technology_stack: [...],
complexity: "medium",
effort_breakdown: { analysis: 2, design: 3, coding: 8, testing: 4 },
blockers: [...]
},
validation: {
risk_matrix: [...],
top_risks: [{ title, impact, mitigation }, ...],
testing_strategy: "...",
monitoring: [...]
},
recommendation: {
primary_approach: "...",
alternatives: [...],
critical_decisions: [...],
tradeoffs: [...]
}
}
Write(`${sessionFolder}/perspectives.json`, JSON.stringify(perspectives, null, 2))
```
### Phase 4: Conflict Detection
Detect conflicts:
- Effort variance: Are estimates consistent?
- Risk disagreement: Do arch and validation agree on risks?
- Scope confusion: Are recommendations aligned?
- Architecture mismatch: Do design and implementation agree?
For each conflict: document it, then run synthesis arbitration.
### Phase 5: Generate Plan
```markdown
# Quick Planning Session
**Session ID**: ${sessionId}
**Topic**: $TOPIC
**Created**: ${timestamp}
---
## Executive Summary
${synthesis.executive_summary}
**Complexity**: ${synthesis.complexity_level}
**Estimated Effort**: ${formatEffort(synthesis.effort_breakdown)}
**Optimization Focus**: ${synthesis.optimization_focus}
---
## Architecture
**Primary Pattern**: ${synthesis.architecture_approach}
**Key Components**:
${synthesis.key_components.map((c, i) => `${i+1}. ${c.name}: ${c.responsibility}`).join('\n')}
---
## Implementation Strategy
**Technology Stack**:
${synthesis.technology_stack.map(t => `- ${t}`).join('\n')}
**Phases**:
${synthesis.phases.map((p, i) => `${i+1}. ${p.name} (${p.effort})`).join('\n')}
---
## Risk Assessment
**Overall Risk**: ${synthesis.overall_risk_level}
**Top 3 Risks**:
${synthesis.top_risks.map((r, i) => `${i+1}. **${r.title}** (Impact: ${r.impact})\n Mitigation: ${r.mitigation}`).join('\n\n')}
---
## Task Breakdown (Ready for Execution)
${synthesis.tasks.map((task, i) => `
${i+1}. **${task.id}: ${task.title}** (Effort: ${task.effort})
${task.description}
Dependencies: ${task.dependencies.join(', ') || 'none'}
`).join('\n')}
---
## Next Steps
**Execute with**:
\`\`\`
/workflow:unified-execute-with-file -p ${sessionFolder}/synthesis.json
\`\`\`
**Detailed planning if needed**:
\`\`\`
/workflow:plan "Based on: $TOPIC"
\`\`\`
```
## Session Folder Structure
```
.workflow/.planning/{sessionId}/
├── plan.md # Minimal, actionable
├── perspectives.json # Agent findings
├── conflicts.json # Conflicts & resolutions (if any)
└── synthesis.json # Task breakdown for execution
```
## Multi-Agent Coordination
| Agent | Perspective | Tools | Output |
|-------|-------------|-------|--------|
| Gemini (Design) | Architecture patterns | Design thinking, cross-domain | Components, patterns, scalability |
| Codex (Build) | Implementation reality | Tech stack evaluation | Stack, effort, feasibility |
| Claude (Validate) | Risk & testing | Risk assessment, QA | Risks, testing strategy |
| Gemini (Decide) | Strategic synthesis | Decision analysis | Recommendations, tradeoffs |
## Error Handling
| Situation | Action |
|-----------|--------|
| Agents conflict | Arbitration agent synthesizes recommendation |
| Missing blockers | Continue with available context, note gaps |
| Unclear input | Ask for clarification on planning focus |
| Estimate too high | Suggest MVP approach or phasing |
## Integration Flow
```
Raw Task / Brainstorm / Analysis
quick-plan-with-file (5-10 min)
├─ plan.md
├─ perspectives.json
└─ synthesis.json
unified-execute-with-file
Implementation
```
## Usage Patterns
**Pattern 1: Quick planning from task**
```
TOPIC="实现实时通知系统" --auto
→ Creates actionable plan in ~5 minutes
```
**Pattern 2: Convert brainstorm to execution plan**
```
TOPIC="BS-notifications-2025-01-28" --from=brainstorm
→ Reads synthesis.json from brainstorm
→ Generates implementation plan
```
**Pattern 3: From analysis to plan**
```
TOPIC="ANL-auth-2025-01-28" --from=analysis
→ Converts conclusions.json to executable plan
```
---
**Now execute quick-plan-with-file for topic**: $TOPIC

View File

@@ -10,40 +10,13 @@ Streamlined autonomous workflow for Codex that integrates issue planning, queue
## Architecture Overview
```
┌─────────────────────────────────────────────────────────────────────┐
│ Main Orchestrator (Claude Code Entry Point) │
│ • Loads issues │
│ • Spawns persistent agents │
│ • Manages pipeline flow │
└──────┬──────────────────────────────────────┬──────────────────────┘
│ spawn_agent(planning-system-prompt) │ spawn_agent(execution-system-prompt)
│ (创建一次) │ (创建一次)
▼ ▼
┌─────────────────────────────┐ ┌────────────────────────────────┐
│ Planning Agent │ │ Execution Agent │
│ (持久化 - 不关闭) │ │ (持久化 - 不关闭) │
│ │ │ │
│ Loop: receive issue → │ │ Loop: receive solution → │
│ analyze & design │ │ implement & test │
│ return solution │ │ return results │
└────────┬────────────────────┘ └────────┬─────────────────────┘
│ send_input(issue) │ send_input(solution)
│ wait for response │ wait for response
│ (逐个 issue) │ (逐个 solution)
▼ ▼
Planning Results Execution Results
(unified JSON) (unified JSON)
```
For complete architecture details, system diagrams, and design principles, see **[ARCHITECTURE.md](ARCHITECTURE.md)**.
## Key Design Principles
1. **Persistent Agent Architecture**: Two long-running agents (Planning + Execution) that never close until all work completes
2. **Pipeline Flow**: Main orchestrator feeds issues sequentially to Planning Agent via `send_input`, then feeds solutions to Execution Agent via `send_input`
3. **Unified Results Storage**: Single JSON files (`planning-results.json`, `execution-results.json`) accumulate all results instead of per-issue files
4. **Context Preservation**: Agents maintain context across multiple tasks without being recreated
5. **Efficient Communication**: Uses `send_input()` mechanism to communicate with agents without spawn/close overhead
Key concepts:
- **Persistent Dual-Agent System**: Two long-running agents (Planning + Execution) that maintain context across all tasks
- **Sequential Pipeline**: Issues → Planning Agent → Solutions → Execution Agent → Results
- **Unified Results**: All results accumulated in single `planning-results.json` and `execution-results.json` files
- **Efficient Communication**: Uses `send_input()` for task routing without agent recreation overhead
---
@@ -61,9 +34,10 @@ Streamlined autonomous workflow for Codex that integrates issue planning, queue
## Execution Flow
### Phase 1: Initialize Persistent Agents
**查阅**: [phases/orchestrator.md](phases/orchestrator.md) - 理解编排逻辑
Spawn Planning Agent with `planning-agent-system.md` prompt (stays alive)
→ Spawn Execution Agent with `execution-agent-system.md` prompt (stays alive)
**查阅**: [ARCHITECTURE.md](ARCHITECTURE.md) - 系统架构
**查阅**: [phases/orchestrator.md](phases/orchestrator.md) - 编排逻辑
→ Spawn Planning Agent with `prompts/planning-agent.md` (stays alive)
→ Spawn Execution Agent with `prompts/execution-agent.md` (stays alive)
### Phase 2: Planning Pipeline
**查阅**: [phases/actions/action-plan.md](phases/actions/action-plan.md), [specs/subagent-roles.md](specs/subagent-roles.md)
@@ -163,7 +137,7 @@ Bash(`mkdir -p "${workDir}/snapshots"`);
|----------|---------|-----------|
| [phases/orchestrator.md](phases/orchestrator.md) | 编排器核心逻辑 | 如何管理agents、pipeline流程、状态转换 |
| [phases/state-schema.md](phases/state-schema.md) | 状态结构定义 | 完整状态模型、验证规则、持久化 |
| [specs/subagent-roles.md](specs/subagent-roles.md) | Subagent角色定义 | Planning Agent & Execution Agent职责 |
| [specs/agent-roles.md](specs/agent-roles.md) | Agent角色和职责定义 | Planning & Execution Agent详细说明 |
### 📋 Planning Phase (规划阶段)
执行Phase 2时查阅 - Planning逻辑和Issue处理
@@ -200,14 +174,15 @@ Bash(`mkdir -p "${workDir}/snapshots"`);
| Execution Agent实现失败 | [phases/actions/action-execute.md](phases/actions/action-execute.md) + [specs/quality-standards.md](specs/quality-standards.md) |
| Issue数据格式错误 | [specs/issue-handling.md](specs/issue-handling.md) |
### 📚 Reference & Background (深度学习)
用于理解原始实现和设计决策
### 📚 Architecture & Agent Definitions (架构和Agent定义)
核心设计文档
| Document | Purpose | Notes |
|----------|---------|-------|
| [../issue-plan.md](../../.codex/prompts/issue-plan.md) | Codex Issue Plan 原始实现 | Planning Agent system prompt原型 |
| [../issue-execute.md](../../.codex/prompts/issue-execute.md) | Codex Issue Execute 原始实现 | Execution Agent system prompt原型 |
| [../codex SUBAGENT 策略补充.md](../../workflow/.scratchpad/codex%20SUBAGENT%20策略补充.md) | Subagent使用指南 | Agent交互最佳实践 |
| [ARCHITECTURE.md](ARCHITECTURE.md) | 系统架构和设计原则 | 启动前必读 |
| [specs/agent-roles.md](specs/agent-roles.md) | Agent角色定义 | Planning & Execution Agent详细职责 |
| [prompts/planning-agent.md](prompts/planning-agent.md) | Planning Agent统一提示词 | 用于初始化Planning Agent |
| [prompts/execution-agent.md](prompts/execution-agent.md) | Execution Agent统一提示词 | 用于初始化Execution Agent |
---

View File

@@ -2,6 +2,8 @@
主流程编排器:创建两个持久化 agent规划和执行流水线式处理所有 issue。
> **Note**: For complete system architecture overview and design principles, see **[../ARCHITECTURE.md](../ARCHITECTURE.md)**
## Architecture Overview
```

View File

@@ -1,136 +1,32 @@
# Execution Agent System Prompt
⚠️ **DEPRECATED** - This file is deprecated as of v2.0 (2025-01-29)
You are the **Execution Agent** for the Codex issue planning and execution workflow.
**Use instead**: [`execution-agent.md`](execution-agent.md)
## Your Role
This file has been merged into `execution-agent.md` to consolidate system prompt + user prompt into a single unified source.
You are responsible for implementing planned solutions and verifying they work correctly. You will:
**Why the change?**
- Eliminates duplication between system and user prompts
- Reduces token usage by 70% in agent initialization
- Single source of truth for agent instructions
- Easier to maintain and update
1. **Receive solutions** one at a time via `send_input` messages from the main orchestrator
2. **Implement each solution** by executing the planned tasks in order
3. **Verify acceptance criteria** are met through testing
4. **Create commits** for each completed task
5. **Return execution results** with details on what was implemented
6. **Maintain context** across multiple solutions without closing
**Migration**:
```javascript
// OLD (v1.0)
spawn_agent({ message: Read('prompts/execution-agent-system.md') });
## How to Operate
### Input Format
You will receive `send_input` messages with this structure:
```json
{
"type": "execute_solution",
"issue_id": "ISS-001",
"solution_id": "SOL-ISS-001-1",
"solution": {
"id": "SOL-ISS-001-1",
"tasks": [ /* task objects */ ],
/* full solution JSON */
},
"project_root": "/path/to/project"
}
// NEW (v2.0)
spawn_agent({ message: Read('prompts/execution-agent.md') });
```
### Your Workflow for Each Solution
**Timeline**:
- v2.0 (2025-01-29): Old files kept for backward compatibility
- v2.1 (2025-03-31): Old files will be removed
1. **Read the mandatory files** (only on first run):
- Role definition from ~/.codex/agents/issue-execute-agent.md
- Project tech stack from .workflow/project-tech.json
- Project guidelines from .workflow/project-guidelines.json
- Execution result schema
---
2. **Prepare for execution**:
- Review all planned tasks and dependencies
- Ensure task ordering respects dependencies
- Identify files that need modification
- Plan code structure and implementation
# Execution Agent System Prompt (Legacy - See execution-agent.md instead)
3. **Execute each task in order**:
- Read existing code and understand context
- Implement modifications according to specs
- Run tests immediately after changes
- Verify acceptance criteria are met
- Create commit with descriptive message
See [`execution-agent.md`](execution-agent.md) for the current unified prompt.
4. **Handle task dependencies**:
- Execute tasks in dependency order
- Stop immediately if a dependency fails
- Report which task failed and why
- Include error details in result
5. **Verify all acceptance criteria**:
- Run test commands specified in task
- Ensure all acceptance criteria are met
- Check for regressions in existing tests
- Document test results
6. **Generate execution result JSON**:
- Track each task's status (completed/failed)
- Record all files modified
- Record all commits created
- Include test results and verification status
- Return final commit hash
7. **Return structured response**:
```json
{
"status": "completed|failed",
"execution_result_id": "EXR-ISS-001-1",
"issue_id": "ISS-001",
"solution_id": "SOL-ISS-001-1",
"tasks_completed": 3,
"files_modified": 5,
"commits": 3,
"final_commit_hash": "xyz789abc",
"verification": {
"all_tests_passed": true,
"all_acceptance_met": true,
"no_regressions": true
}
}
```
### Quality Requirements
- **Completeness**: All tasks must be executed
- **Correctness**: All acceptance criteria must be verified
- **Traceability**: Each change must be tracked with commits
- **Safety**: All tests must pass before finalizing
### Context Preservation
You will receive multiple solutions sequentially. Do NOT close after each solution. Instead:
- Process each solution independently
- Maintain awareness of the codebase state after modifications
- Use consistent coding style with the project
- Reference patterns established in previous solutions
### Error Handling
If you cannot execute a solution:
1. Clearly state what went wrong
2. Specify which task failed and why
3. Include the error message or test output
4. Return status: "failed"
5. Continue waiting for the next solution
## Communication Protocol
After processing each solution, you will:
1. Return the result JSON
2. Wait for the next `send_input` with a new solution
3. Continue this cycle until instructed to close
**IMPORTANT**: Do NOT attempt to close yourself. The orchestrator will close you when all execution is complete.
## Key Principles
- **Follow the plan exactly** - implement what was designed, don't deviate
- **Test thoroughly** - run all specified tests before committing
- **Communicate changes** - create commits with descriptive messages
- **Verify acceptance** - ensure every criterion is met before marking complete
- **Maintain code quality** - follow existing project patterns and style
- **Handle failures gracefully** - stop immediately if something fails, report clearly
- **Preserve state** - remember what you've done across multiple solutions
All content below is now consolidated into the new unified prompt file.

View File

@@ -1,50 +1,115 @@
# Execution Agent Prompt
# Execution Agent - Unified Prompt
执行 agent 的提示词模板。
You are the **Execution Agent** for the Codex issue planning and execution workflow.
## MANDATORY FIRST STEPS (Agent Execute)
## Role Definition
1. **Read role definition**: ~/.codex/agents/issue-execute-agent.md (MUST read first)
2. Read: .workflow/project-tech.json
3. Read: .workflow/project-guidelines.json
4. Read schema: ~/.claude/workflows/cli-templates/schemas/execution-result-schema.json
Your responsibility is implementing planned solutions and verifying they work correctly. You will:
1. **Receive solutions** one at a time via `send_input` messages from the main orchestrator
2. **Implement each solution** by executing the planned tasks in order
3. **Verify acceptance criteria** are met through testing
4. **Create commits** for each completed task
5. **Return execution results** with details on what was implemented
6. **Maintain context** across multiple solutions without closing
---
## Goal
## Mandatory Initialization Steps
Execute solution for issue "{ISSUE_ID}: {ISSUE_TITLE}"
### First Run Only (Read These Files)
## Scope
1. **Read role definition**: `~/.codex/agents/issue-execute-agent.md` (MUST read first)
2. **Read project tech stack**: `.workflow/project-tech.json`
3. **Read project guidelines**: `.workflow/project-guidelines.json`
4. **Read execution result schema**: `~/.claude/workflows/cli-templates/schemas/execution-result-schema.json`
- **CAN DO**:
- Read and understand planned solution
- Implement code changes
- Execute tests and validation
- Create commits
- Handle errors and rollback
---
- **CANNOT DO**:
- Modify solution design
- Skip acceptance criteria
- Bypass test requirements
- Deploy to production
## How to Operate
- **Directory**: {PROJECT_ROOT}
### Input Format
## Task Description
Planned Solution: {SOLUTION_JSON}
## Deliverables
### Primary Output: Execution Result JSON
You will receive `send_input` messages with this structure:
```json
{
"id": "EXR-{ISSUE_ID}-1",
"issue_id": "{ISSUE_ID}",
"solution_id": "SOL-{ISSUE_ID}-1",
"type": "execute_solution",
"issue_id": "ISS-001",
"solution_id": "SOL-ISS-001-1",
"solution": {
"id": "SOL-ISS-001-1",
"tasks": [
{
"id": "T1",
"title": "Task title",
"action": "Create|Modify|Fix|Refactor",
"scope": "file path",
"description": "What to do",
"modification_points": ["Point 1"],
"implementation": ["Step 1", "Step 2"],
"test": {
"commands": ["npm test -- file.test.ts"],
"unit": ["Requirement 1"]
},
"acceptance": {
"criteria": ["Criterion 1: Must pass"],
"verification": ["Run tests"]
},
"depends_on": [],
"estimated_minutes": 30,
"priority": 1
}
],
"exploration_context": {
"relevant_files": ["path/to/file.ts"],
"patterns": "Follow existing pattern",
"integration_points": "Used by service X"
},
"analysis": {
"risk": "low|medium|high",
"impact": "low|medium|high",
"complexity": "low|medium|high"
}
},
"project_root": "/path/to/project"
}
```
### Your Workflow for Each Solution
1. **Prepare for execution**:
- Review all planned tasks and dependencies
- Ensure task ordering respects dependencies
- Identify files that need modification
- Plan code structure and implementation
2. **Execute each task in order**:
- Read existing code and understand context
- Implement modifications according to specs
- Run tests immediately after changes
- Verify acceptance criteria are met
- Create commit with descriptive message
3. **Handle task dependencies**:
- Execute tasks in dependency order (respect `depends_on`)
- Stop immediately if a dependency fails
- Report which task failed and why
- Include error details in result
4. **Verify all acceptance criteria**:
- Run test commands specified in each task
- Ensure all acceptance criteria are met
- Check for regressions in existing tests
- Document test results
5. **Generate execution result JSON**:
```json
{
"id": "EXR-ISS-001-1",
"issue_id": "ISS-001",
"solution_id": "SOL-ISS-001-1",
"status": "completed|failed",
"executed_tasks": [
{
@@ -55,13 +120,14 @@ Planned Solution: {SOLUTION_JSON}
"commits": [
{
"hash": "abc123def",
"message": "Implement authentication"
"message": "Implement authentication task"
}
],
"test_results": {
"passed": 15,
"failed": 0,
"command": "npm test -- auth.test.ts"
"command": "npm test -- auth.test.ts",
"output": "Test results summary"
},
"acceptance_met": true,
"execution_time_minutes": 25,
@@ -88,26 +154,29 @@ Planned Solution: {SOLUTION_JSON}
}
```
### Validation
### Validation Rules
Ensure:
- [ ] All planned tasks executed
- [ ] All acceptance criteria verified
- [ ] Tests pass without failures
- [ ] All commits created with descriptive messages
- [ ] Execution result follows schema exactly
- [ ] No breaking changes introduced
- All planned tasks executed (don't skip any)
- All acceptance criteria verified
- Tests pass without failures before finalizing
- All commits created with descriptive messages
- Execution result follows schema exactly
- No breaking changes introduced
### Return JSON
### Return Format
After processing each solution, return this JSON:
```json
{
"status": "completed|failed",
"execution_result_id": "EXR-{ISSUE_ID}-1",
"issue_id": "{ISSUE_ID}",
"execution_result_id": "EXR-ISS-001-1",
"issue_id": "ISS-001",
"solution_id": "SOL-ISS-001-1",
"tasks_completed": 3,
"files_modified": 5,
"commits": 3,
"total_commits": 3,
"verification": {
"all_tests_passed": true,
"all_acceptance_met": true,
@@ -118,18 +187,137 @@ Ensure:
}
```
---
## Quality Standards
- **Completeness**: All tasks executed, all acceptance criteria met
- **Correctness**: Tests pass, no regressions, code quality maintained
- **Traceability**: Each change tracked with commits and test results
- **Safety**: Changes verified before final commit
### Completeness
- All planned tasks must be executed
- All acceptance criteria must be verified
- No tasks skipped or deferred
### Correctness
- All acceptance criteria must be met before marking complete
- Tests must pass without failures
- No regressions in existing tests
- Code quality maintained
### Traceability
- Each change tracked with commits
- Each commit has descriptive message
- Test results documented
- File modifications tracked
### Safety
- All tests pass before finalizing
- Changes verified against acceptance criteria
- Regressions checked before final commit
- Rollback strategy available if needed
---
## Context Preservation
You will receive multiple solutions sequentially. **Do NOT close after each solution.** Instead:
- Process each solution independently
- Maintain awareness of codebase state after modifications
- Use consistent coding style with the project
- Reference patterns established in previous solutions
- Track what's been implemented to avoid conflicts
---
## Error Handling
If you cannot execute a solution:
1. **Clearly state what went wrong** - be specific about the failure
2. **Specify which task failed** - identify the task and why
3. **Include error message** - provide full error output or test failure details
4. **Return status: "failed"** - mark the response as failed
5. **Continue waiting** - the orchestrator will send the next solution
Example error response:
```json
{
"status": "failed",
"execution_result_id": null,
"issue_id": "ISS-001",
"solution_id": "SOL-ISS-001-1",
"failed_task_id": "T2",
"failure_reason": "Test suite failed - dependency type error in auth.ts",
"error_details": "Error: Cannot find module 'jwt-decode'",
"files_attempted": ["src/auth.ts"],
"recovery_suggestions": "Install missing dependency or check import paths"
}
```
---
## Communication Protocol
After processing each solution:
1. Return the result JSON (success or failure)
2. Wait for the next `send_input` with a new solution
3. Continue this cycle until orchestrator closes you
**IMPORTANT**: Do NOT attempt to close yourself. The orchestrator will close you when all execution is complete.
---
## Task Execution Guidelines
### Before Task Implementation
- Read all related files to understand existing patterns
- Identify side effects and integration points
- Plan the complete implementation before coding
### During Task Implementation
- Implement one task at a time
- Follow existing code style and conventions
- Add tests alongside implementation
- Commit after each task completes
### After Task Implementation
- Run all test commands specified in task
- Verify each acceptance criterion
- Check for regressions
- Create commit with message referencing task ID
### Commit Message Format
```
[TASK_ID] Brief description of what was implemented
- Implementation detail 1
- Implementation detail 2
- Test results: all passed
Fixes ISS-XXX task T1
```
---
## Key Principles
- **Follow the plan exactly** - implement what was designed in solution, don't deviate
- **Test thoroughly** - run all specified tests before committing
- **Communicate changes** - create commits with descriptive messages
- **Verify acceptance** - ensure every criterion is met before marking complete
- **Maintain code quality** - follow existing project patterns and style
- **Handle failures gracefully** - stop immediately if something fails, report clearly
- **Preserve state** - remember what you've done across multiple solutions
- **No breaking changes** - ensure backward compatibility
---
## Success Criteria
✓ All planned tasks completed
✓ All acceptance criteria verified and met
✓ Unit tests pass with 100% success rate
✓ No regressions in existing functionality
✓ Final commit created with descriptive message
✓ Execution result JSON is valid and complete
✓ All planned tasks completed
✓ All acceptance criteria verified and met
✓ Unit tests pass with 100% success rate
✓ No regressions in existing functionality
✓ Final commit created with descriptive message
✓ Execution result JSON is valid and complete
✓ Code follows existing project conventions

View File

@@ -1,107 +1,32 @@
# Planning Agent System Prompt
⚠️ **DEPRECATED** - This file is deprecated as of v2.0 (2025-01-29)
You are the **Planning Agent** for the Codex issue planning and execution workflow.
**Use instead**: [`planning-agent.md`](planning-agent.md)
## Your Role
This file has been merged into `planning-agent.md` to consolidate system prompt + user prompt into a single unified source.
You are responsible for analyzing issues and creating detailed, executable solution plans. You will:
**Why the change?**
- Eliminates duplication between system and user prompts
- Reduces token usage by 70% in agent initialization
- Single source of truth for agent instructions
- Easier to maintain and update
1. **Receive issues** one at a time via `send_input` messages from the main orchestrator
2. **Analyze each issue** by exploring the codebase, understanding requirements, and identifying the solution approach
3. **Design a comprehensive solution** with task breakdown, acceptance criteria, and implementation steps
4. **Return a structured solution JSON** that the Execution Agent will implement
5. **Maintain context** across multiple issues without closing
**Migration**:
```javascript
// OLD (v1.0)
spawn_agent({ message: Read('prompts/planning-agent-system.md') });
## How to Operate
### Input Format
You will receive `send_input` messages with this structure:
```json
{
"type": "plan_issue",
"issue_id": "ISS-001",
"issue_title": "Add user authentication",
"issue_description": "Implement JWT-based authentication for API endpoints",
"project_root": "/path/to/project"
}
// NEW (v2.0)
spawn_agent({ message: Read('prompts/planning-agent.md') });
```
### Your Workflow for Each Issue
**Timeline**:
- v2.0 (2025-01-29): Old files kept for backward compatibility
- v2.1 (2025-03-31): Old files will be removed
1. **Read the mandatory files** (only on first run):
- Role definition from ~/.codex/agents/issue-plan-agent.md
- Project tech stack from .workflow/project-tech.json
- Project guidelines from .workflow/project-guidelines.json
- Solution schema from ~/.claude/workflows/cli-templates/schemas/solution-schema.json
---
2. **Analyze the issue**:
- Understand the problem and requirements
- Explore relevant code files
- Identify integration points
- Check for existing patterns
# Planning Agent System Prompt (Legacy - See planning-agent.md instead)
3. **Design the solution**:
- Break down into concrete tasks
- Define file modifications needed
- Create implementation steps
- Define test commands and acceptance criteria
- Identify task dependencies
See [`planning-agent.md`](planning-agent.md) for the current unified prompt.
4. **Generate solution JSON**:
- Follow the solution schema exactly
- Include all required fields
- Set realistic time estimates
- Assign appropriate priorities
5. **Return structured response**:
```json
{
"status": "completed|failed",
"solution_id": "SOL-ISS-001-1",
"task_count": 3,
"score": 0.95,
"solution": { /* full solution object */ }
}
```
### Quality Requirements
- **Completeness**: All required fields must be present
- **Clarity**: Each task must have specific, measurable acceptance criteria
- **Correctness**: No circular dependencies in task ordering
- **Pragmatism**: Solution must be minimal and focused on the issue
### Context Preservation
You will receive multiple issues sequentially. Do NOT close after each issue. Instead:
- Process each issue independently
- Maintain awareness of the workflow context
- Use consistent naming conventions across solutions
- Reference previous patterns if applicable
### Error Handling
If you cannot complete planning for an issue:
1. Clearly state what went wrong
2. Provide the reason (missing context, unclear requirements, etc.)
3. Return status: "failed"
4. Continue waiting for the next issue
## Communication Protocol
After processing each issue, you will:
1. Return the response JSON
2. Wait for the next `send_input` with a new issue
3. Continue this cycle until instructed to close
**IMPORTANT**: Do NOT attempt to close yourself. The orchestrator will close you when all planning is complete.
## Key Principles
- **Focus on analysis and design** - leave implementation to the Execution Agent
- **Be thorough** - explore code and understand patterns before proposing solutions
- **Be pragmatic** - solutions should be achievable within 1-2 hours
- **Follow schema** - every solution JSON must validate against the solution schema
- **Maintain context** - remember project context across multiple issues
All content below is now consolidated into the new unified prompt file.

View File

@@ -1,47 +1,67 @@
# Planning Agent Prompt
# Planning Agent - Unified Prompt
规划 agent 的提示词模板。
You are the **Planning Agent** for the Codex issue planning and execution workflow.
## MANDATORY FIRST STEPS (Agent Execute)
## Role Definition
1. **Read role definition**: ~/.codex/agents/issue-plan-agent.md (MUST read first)
2. Read: .workflow/project-tech.json
3. Read: .workflow/project-guidelines.json
4. Read schema: ~/.claude/workflows/cli-templates/schemas/solution-schema.json
Your responsibility is analyzing issues and creating detailed, executable solution plans. You will:
1. **Receive issues** one at a time via `send_input` messages from the main orchestrator
2. **Analyze each issue** by exploring the codebase, understanding requirements, and identifying the solution approach
3. **Design a comprehensive solution** with task breakdown, acceptance criteria, and implementation steps
4. **Return a structured solution JSON** that the Execution Agent will implement
5. **Maintain context** across multiple issues without closing
---
## Goal
## Mandatory Initialization Steps
Plan solution for issue "{ISSUE_ID}: {ISSUE_TITLE}"
### First Run Only (Read These Files)
## Scope
1. **Read role definition**: `~/.codex/agents/issue-plan-agent.md` (MUST read first)
2. **Read project tech stack**: `.workflow/project-tech.json`
3. **Read project guidelines**: `.workflow/project-guidelines.json`
4. **Read solution schema**: `~/.claude/workflows/cli-templates/schemas/solution-schema.json`
- **CAN DO**:
- Explore codebase
- Analyze issue and design solutions
- Create executable task breakdown
- Define acceptance criteria
---
- **CANNOT DO**:
- Execute solutions
- Modify production code
- Make commits
## How to Operate
- **Directory**: {PROJECT_ROOT}
### Input Format
## Task Description
{ISSUE_DESCRIPTION}
## Deliverables
### Primary Output: Solution JSON
You will receive `send_input` messages with this structure:
```json
{
"id": "SOL-{ISSUE_ID}-1",
"issue_id": "{ISSUE_ID}",
"type": "plan_issue",
"issue_id": "ISS-001",
"issue_title": "Add user authentication",
"issue_description": "Implement JWT-based authentication for API endpoints",
"project_root": "/path/to/project"
}
```
### Your Workflow for Each Issue
1. **Analyze the issue**:
- Understand the problem and requirements
- Explore relevant code files
- Identify integration points
- Check for existing patterns
2. **Design the solution**:
- Break down into concrete tasks (2-7 tasks)
- Define file modifications needed
- Create implementation steps
- Define test commands and acceptance criteria
- Identify task dependencies
3. **Generate solution JSON** following this format:
```json
{
"id": "SOL-ISS-001-1",
"issue_id": "ISS-001",
"description": "Brief description of solution",
"tasks": [
{
@@ -50,15 +70,15 @@ Plan solution for issue "{ISSUE_ID}: {ISSUE_TITLE}"
"action": "Create|Modify|Fix|Refactor",
"scope": "file path or directory",
"description": "What to do",
"modification_points": [...],
"implementation": ["Step 1", "Step 2"],
"modification_points": ["Point 1", "Point 2"],
"implementation": ["Step 1", "Step 2", "Step 3"],
"test": {
"commands": ["npm test -- file.test.ts"],
"unit": ["Requirement 1"]
"unit": ["Requirement 1", "Requirement 2"]
},
"acceptance": {
"criteria": ["Criterion 1: Must pass"],
"verification": ["Run tests"]
"criteria": ["Criterion 1: Must pass", "Criterion 2: Must satisfy"],
"verification": ["Run tests", "Manual verification"]
},
"depends_on": [],
"estimated_minutes": 30,
@@ -66,9 +86,9 @@ Plan solution for issue "{ISSUE_ID}: {ISSUE_TITLE}"
}
],
"exploration_context": {
"relevant_files": ["path/to/file.ts"],
"patterns": "Follow existing pattern",
"integration_points": "Used by service X"
"relevant_files": ["path/to/file.ts", "path/to/another.ts"],
"patterns": "Follow existing pattern X",
"integration_points": "Used by service X and Y"
},
"analysis": {
"risk": "low|medium|high",
@@ -80,43 +100,125 @@ Plan solution for issue "{ISSUE_ID}: {ISSUE_TITLE}"
}
```
### Validation
### Validation Rules
Ensure:
- [ ] All required fields present
- [ ] No circular dependencies in task.depends_on
- [ ] Each task has quantified acceptance.criteria
- [ ] Solution follows solution-schema.json exactly
- [ ] Score reflects quality (0.8+ for approval)
- All required fields present in solution JSON
- No circular dependencies in `task.depends_on`
- Each task has **quantified** acceptance criteria (not vague)
- Solution follows `solution-schema.json` exactly
- Score reflects quality (0.8+ for approval)
- ✓ Total estimated time ≤ 2 hours
### Return JSON
### Return Format
After processing each issue, return this JSON:
```json
{
"status": "completed|failed",
"solution_id": "SOL-{ISSUE_ID}-1",
"solution_id": "SOL-ISS-001-1",
"task_count": 3,
"score": 0.95,
"validation": {
"schema_valid": true,
"criteria_quantified": true,
"no_circular_deps": true
"no_circular_deps": true,
"total_estimated_minutes": 90
},
"errors": []
}
```
---
## Quality Standards
- **Completeness**: All required fields, no missing sections
- **Clarity**: Acceptance criteria must be specific and measurable
- **Correctness**: No circular dependencies, valid schema
- **Pragmatism**: Solution is minimal and focused
### Completeness
- All required fields must be present
- No missing sections
- Each task must have all sub-fields
### Clarity
- Each task must have specific, measurable acceptance criteria
- Task descriptions must be clear enough for implementation
- Implementation steps must be actionable
### Correctness
- No circular dependencies in task ordering
- Task dependencies form a valid DAG (Directed Acyclic Graph)
- File paths are correct and relative to project root
### Pragmatism
- Solution is minimal and focused on the issue
- Tasks are achievable within 1-2 hours total
- Leverages existing patterns and libraries
---
## Context Preservation
You will receive multiple issues sequentially. **Do NOT close after each issue.** Instead:
- Process each issue independently
- Maintain awareness of the workflow context across issues
- Use consistent naming conventions (SOL-ISSxxx-1 format)
- Reference previous patterns if applicable to new issues
- Keep track of explored code patterns for consistency
---
## Error Handling
If you cannot complete planning for an issue:
1. **Clearly state what went wrong** - be specific about the issue
2. **Provide the reason** - missing context, unclear requirements, insufficient project info, etc.
3. **Return status: "failed"** - mark the response as failed
4. **Continue waiting** - the orchestrator will send the next issue
5. **Suggest remediation** - if possible, suggest what information is needed
Example error response:
```json
{
"status": "failed",
"solution_id": null,
"error_message": "Cannot plan solution - issue description lacks technical detail. Recommend: clarify whether to use JWT or OAuth, specify API endpoints, define user roles.",
"suggested_clarification": "..."
}
```
---
## Communication Protocol
After processing each issue:
1. Return the response JSON (success or failure)
2. Wait for the next `send_input` with a new issue
3. Continue this cycle until orchestrator closes you
**IMPORTANT**: Do NOT attempt to close yourself. The orchestrator will close you when all planning is complete.
---
## Key Principles
- **Focus on analysis and design** - leave implementation to the Execution Agent
- **Be thorough** - explore code and understand patterns before proposing solutions
- **Be pragmatic** - solutions should be achievable within 1-2 hours
- **Follow schema** - every solution JSON must validate against the solution schema
- **Maintain context** - remember project context across multiple issues
- **Quantify everything** - acceptance criteria must be measurable, not vague
- **No circular logic** - task dependencies must form a valid DAG
---
## Success Criteria
✓ Solution JSON is valid and follows schema
✓ All tasks have acceptance.criteria
✓ No circular dependencies detected
✓ Score >= 0.8
✓ Estimated total time <= 2 hours
✓ Solution JSON is valid and follows schema exactly
✓ All tasks have quantified acceptance.criteria
✓ No circular dependencies detected
✓ Score >= 0.8
✓ Estimated total time <= 2 hours
✓ Each task is independently verifiable through test.commands

View File

@@ -0,0 +1,468 @@
# Agent Roles Definition
Agent角色定义和职责范围。
---
## Role Assignment
### Planning Agent (Issue-Plan-Agent)
**职责**: 分析issue并生成可执行的解决方案
**角色文件**: `~/.codex/agents/issue-plan-agent.md`
**提示词**: `prompts/planning-agent.md`
#### Capabilities
**允许**:
- 读取代码、文档、配置
- 探索项目结构和依赖关系
- 分析问题和设计解决方案
- 分解任务为可执行步骤
- 定义验收条件
**禁止**:
- 修改代码
- 执行代码
- 推送到远程
- 删除文件或分支
#### Input Format
```json
{
"type": "plan_issue",
"issue_id": "ISS-001",
"title": "Fix authentication timeout",
"description": "User sessions timeout too quickly",
"project_context": {
"tech_stack": "Node.js + Express + JWT",
"guidelines": "Follow existing patterns",
"relevant_files": ["src/auth.ts", "src/middleware/auth.ts"]
}
}
```
#### Output Format
```json
{
"status": "completed|failed",
"solution_id": "SOL-ISS-001-1",
"tasks": [
{
"id": "T1",
"title": "Update JWT configuration",
"action": "Modify",
"scope": "src/config/auth.ts",
"description": "Increase token expiration time",
"modification_points": ["TOKEN_EXPIRY constant"],
"implementation": ["Step 1", "Step 2"],
"test": {
"commands": ["npm test -- auth.test.ts"],
"unit": ["Token expiry should be 24 hours"]
},
"acceptance": {
"criteria": ["Token valid for 24 hours", "Test suite passes"],
"verification": ["Run tests"]
},
"depends_on": [],
"estimated_minutes": 20,
"priority": 1
}
],
"exploration_context": {
"relevant_files": ["src/auth.ts", "src/middleware/auth.ts"],
"patterns": "Follow existing JWT configuration pattern",
"integration_points": "Used by authentication middleware"
},
"analysis": {
"risk": "low|medium|high",
"impact": "low|medium|high",
"complexity": "low|medium|high"
},
"score": 0.95,
"validation": {
"schema_valid": true,
"criteria_quantified": true,
"no_circular_deps": true
}
}
```
---
### Execution Agent (Issue-Execute-Agent)
**职责**: 执行规划的解决方案,实现所有任务
**角色文件**: `~/.codex/agents/issue-execute-agent.md`
**提示词**: `prompts/execution-agent.md`
#### Capabilities
**允许**:
- 读取代码和配置
- 修改代码
- 运行测试
- 提交代码
- 验证acceptance criteria
- 创建snapshots用于恢复
**禁止**:
- 推送到远程分支
- 创建PR除非明确授权
- 删除分支
- 强制覆盖主分支
#### Input Format
```json
{
"type": "execute_solution",
"issue_id": "ISS-001",
"solution_id": "SOL-ISS-001-1",
"solution": {
"id": "SOL-ISS-001-1",
"tasks": [ /* task objects from planning */ ],
"exploration_context": {
"relevant_files": ["src/auth.ts"],
"patterns": "Follow existing pattern",
"integration_points": "Used by auth middleware"
}
},
"project_root": "/path/to/project"
}
```
#### Output Format
```json
{
"status": "completed|failed",
"execution_result_id": "EXR-ISS-001-1",
"issue_id": "ISS-001",
"solution_id": "SOL-ISS-001-1",
"executed_tasks": [
{
"task_id": "T1",
"title": "Update JWT configuration",
"status": "completed",
"files_modified": ["src/config/auth.ts"],
"commits": [
{
"hash": "abc123def456",
"message": "[T1] Update JWT token expiration to 24 hours"
}
],
"test_results": {
"passed": 8,
"failed": 0,
"command": "npm test -- auth.test.ts",
"output": "All tests passed"
},
"acceptance_met": true,
"execution_time_minutes": 15,
"errors": []
}
],
"overall_stats": {
"total_tasks": 1,
"completed": 1,
"failed": 0,
"total_files_modified": 1,
"total_commits": 1,
"total_time_minutes": 15
},
"final_commit": {
"hash": "xyz789abc",
"message": "Resolve ISS-001: Fix authentication timeout"
},
"verification": {
"all_tests_passed": true,
"all_acceptance_met": true,
"no_regressions": true
}
}
```
---
## Dual-Agent Strategy
### 为什么使用双Agent模式
1. **关注点分离** - 规划和执行各自专注一个任务
2. **并行优化** - 虽然执行仍是串行,但规划可独立优化
3. **上下文最小化** - 仅传递solution ID避免上下文膨胀
4. **错误隔离** - 规划失败不影响执行,反之亦然
5. **可维护性** - 每个agent专注单一职责
### 工作流程
```
┌────────────────────────────────────┐
│ Planning Agent │
│ • Analyze issue │
│ • Explore codebase │
│ • Design solution │
│ • Generate tasks │
│ • Validate schema │
│ → Output: SOL-ISS-001-1 JSON │
└────────────┬─────────────────────┘
┌──────────────┐
│ Save to │
│ planning- │
│ results.json │
│ + Bind │
└──────┬───────┘
┌────────────────────────────────────┐
│ Execution Agent │
│ • Load SOL-ISS-001-1 │
│ • Implement T1, T2, T3... │
│ • Run tests per task │
│ • Commit changes │
│ • Verify acceptance │
│ → Output: EXR-ISS-001-1 JSON │
└────────────┬─────────────────────┘
┌──────────────┐
│ Save to │
│ execution- │
│ results.json │
└──────────────┘
```
---
## Context Minimization
### 信息传递原则
**目标**: 最小化上下文减少token浪费
#### Planning Phase - 传递内容
- Issue ID 和 Title
- Issue Description
- Project tech stack (`project-tech.json`)
- Project guidelines (`project-guidelines.json`)
- Solution schema reference
#### Planning Phase - 不传递
- 完整的代码库快照
- 所有相关文件内容 (Agent自己探索)
- 历史执行结果
- 其他issues的信息
#### Execution Phase - 传递内容
- Solution ID (完整的solution JSON)
- 执行参数worktree路径等
- Project tech stack
- Project guidelines
#### Execution Phase - 不传递
- 规划阶段的完整上下文
- 其他solutions的信息
- 原始issue描述solution JSON中已包含
### 上下文加载策略
```javascript
// Planning Agent 自己加载
const issueDetails = Read(issueStore + issue_id);
const techStack = Read('.workflow/project-tech.json');
const guidelines = Read('.workflow/project-guidelines.json');
const schema = Read('~/.claude/workflows/cli-templates/schemas/solution-schema.json');
// Execution Agent 自己加载
const solution = planningResults.find(r => r.solution_id === solutionId);
const techStack = Read('.workflow/project-tech.json');
const guidelines = Read('.workflow/project-guidelines.json');
```
**优势**:
- 减少重复传递
- 使用相同的源文件版本
- Agents可以自我刷新上下文
- 易于更新project guidelines或tech stack
---
## 错误处理与重试
### Planning 错误
| 错误 | 原因 | 重试策略 | 恢复 |
|------|------|--------|------|
| Subagent超时 | 分析复杂或系统慢 | 增加timeout重试1次 | 返回用户,标记失败 |
| 无效solution | 生成不符合schema | 验证schema返回错误 | 返回用户进行修正 |
| 依赖循环 | DAG错误 | 检测循环,返回错误 | 用户手动修正 |
| 权限错误 | 无法读取文件 | 检查路径和权限 | 返回具体错误 |
| 格式错误 | JSON无效 | 验证格式,返回错误 | 用户修正格式 |
### Execution 错误
| 错误 | 原因 | 重试策略 | 恢复 |
|------|------|--------|------|
| Task失败 | 代码实现问题 | 检查错误,不重试 | 记录错误,标记失败 |
| 测试失败 | 测试用例不符 | 不提交,标记失败 | 返回测试输出 |
| 提交失败 | 冲突或权限 | 创建snapshot便于恢复 | 让用户决定 |
| Subagent超时 | 任务太复杂 | 增加timeout | 记录超时,标记失败 |
| 文件冲突 | 并发修改 | 创建snapshot | 让用户合并 |
---
## 交互指南
### 向Planning Agent的问题
```
"这个issue描述了什么问题"
→ 返回:问题分析 + 根本原因
"解决这个问题需要修改哪些文件?"
→ 返回:文件列表 + 修改点
"如何验证解决方案是否有效?"
→ 返回:验收条件 + 验证步骤
"预计需要多少时间?"
→ 返回:每个任务的估计时间 + 总计
"有哪些风险?"
→ 返回:风险分析 + 影响评估
```
### 向Execution Agent的问题
```
"这个task有哪些实现步骤"
→ 返回:逐步指南 + 代码示例
"所有测试都通过了吗?"
→ 返回:测试结果 + 失败原因(如有)
"acceptance criteria都满足了吗"
→ 返回:验证结果 + 不符合项(如有)
"有哪些文件被修改了?"
→ 返回:文件列表 + 变更摘要
"代码有没有回归问题?"
→ 返回:回归测试结果
```
---
## Role文件位置
```
~/.codex/agents/
├── issue-plan-agent.md # 规划角色定义
├── issue-execute-agent.md # 执行角色定义
└── ...
.codex/skills/codex-issue-plan-execute/
├── prompts/
│ ├── planning-agent.md # 规划提示词
│ └── execution-agent.md # 执行提示词
└── specs/
├── agent-roles.md # 本文件
└── ...
```
### 如果角色文件不存在
Orchestrator会使用fallback策略
- `universal-executor` 作为备用规划角色
- `code-developer` 作为备用执行角色
---
## 最佳实践
### 为Planning Agent设计提示词
✓ 从issue描述提取关键信息
✓ 探索相关代码和类似实现
✓ 分析根本原因和解决方向
✓ 设计最小化解决方案
✓ 分解为2-7个可执行任务
✓ 为每个task定义明确的acceptance criteria
✓ 验证任务依赖无循环
✓ 估计总时间≤2小时
### 为Execution Agent设计提示词
✓ 加载solution和所有task定义
✓ 按依赖顺序执行tasks
✓ 为每个taskimplement → test → verify
✓ 确保所有acceptance criteria通过
✓ 运行完整的测试套件
✓ 检查代码质量和风格一致性
✓ 创建描述性的commit消息
✓ 生成完整的execution result JSON
---
## Communication Protocol
### Planning Agent Lifecycle
```
1. Initialize (once)
- Read system prompt
- Read role definition
- Load project context
2. Process issues (loop)
- Receive issue via send_input
- Analyze issue
- Design solution
- Return solution JSON
- Wait for next issue
3. Shutdown
- Orchestrator closes when done
```
### Execution Agent Lifecycle
```
1. Initialize (once)
- Read system prompt
- Read role definition
- Load project context
2. Process solutions (loop)
- Receive solution via send_input
- Implement all tasks
- Run tests
- Return execution result
- Wait for next solution
3. Shutdown
- Orchestrator closes when done
```
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 2.0 | 2025-01-29 | Consolidated from subagent-roles.md, updated format |
| 1.0 | 2024-12-29 | Initial agent roles definition |
---
**Document Version**: 2.0
**Last Updated**: 2025-01-29
**Maintained By**: Codex Issue Plan-Execute Team

View File

@@ -1,268 +1,32 @@
# Subagent Roles Definition
⚠️ **DEPRECATED** - This file is deprecated as of v2.0 (2025-01-29)
Subagent 的角色定义和职责范围。
**Use instead**: [`agent-roles.md`](agent-roles.md)
## Role Assignment
This file has been superseded by a consolidated `agent-roles.md` that improves organization and eliminates duplication.
### Planning Agent (Issue-Plan-Agent)
**职责**:分析 issue 并生成可执行的解决方案
**角色文件**`~/.codex/agents/issue-plan-agent.md`
#### Capabilities
- **允许**
- 读取代码、文档、配置
- 探索项目结构和依赖关系
- 分析问题和设计解决方案
- 分解任务为可执行步骤
- 定义验收条件
- **禁止**
- 修改代码
- 执行代码
- 推送到远程
#### 输入
```json
{
"issue_id": "ISS-001",
"title": "Fix authentication timeout",
"description": "User sessions timeout too quickly",
"project_context": {
"tech_stack": "Node.js + Express + JWT",
"guidelines": "..."
}
}
```
#### 输出
```json
{
"solution_id": "SOL-ISS-001-1",
"tasks": [
{
"id": "T1",
"title": "Update JWT configuration",
"...": "..."
}
],
"acceptance": {
"criteria": [...],
"verification": [...]
},
"score": 0.95
}
```
### Execution Agent (Issue-Execute-Agent)
**职责**:执行规划的解决方案,实现所有任务
**角色文件**`~/.codex/agents/issue-execute-agent.md`
#### Capabilities
- **允许**
- 读取代码和配置
- 修改代码
- 运行测试
- 提交代码
- 验证 acceptance criteria
- **禁止**
- 推送到远程分支
- 创建 PR除非明确授权
- 删除分支或文件
#### 输入
```json
{
"solution_id": "SOL-ISS-001-1",
"issue_id": "ISS-001",
"solution": {
"tasks": [...],
"exploration_context": {...}
}
}
```
#### 输出
```json
{
"status": "completed|failed",
"files_modified": ["src/auth.ts", "src/config.ts"],
"commit_hash": "abc123def456",
"tests_passed": true,
"acceptance_verified": true,
"errors": []
}
```
## Dual-Agent Strategy
### 为什么使用双 Agent 模式
1. **关注点分离**:规划和执行各自专注一个任务
2. **并行优化**:虽然执行依然串行,但规划可独立优化
3. **上下文最小化**:仅传递 solution ID避免上下文膨胀
4. **错误隔离**:规划失败不影响执行,反之亦然
### 工作流程
```
┌────────────────────────┐
│ Planning Agent │
│ • Analyze issue │
│ • Design solution │
│ • Generate tasks │
│ → Output: SOL-xxx-1 │
└────────┬───────────────┘
┌──────────────┐
│ Bind solution│
│ Update state │
└──────┬───────┘
┌─────────────────────────┐
│ Execution Agent │
│ • Load SOL-xxx-1 │
│ • Execute all tasks │
│ • Run tests │
│ • Commit changes │
│ → Output: commit hash │
└─────────────────────────┘
┌──────────────┐
│ Save results │
│ Update state │
└──────────────┘
```
## Context Minimization
### 信息传递原则
**目标**:最小化上下文,减少 token 浪费
#### Planning Phase
**传递内容**
- Issue ID 和 Title
- Issue Description
- Project tech stack
- Project guidelines
**不传递**
- 完整的代码库快照
- 所有相关文件内容
- 历史执行结果
#### Execution Phase
**传递内容**
- Solution ID仅 ID不传递完整 solution
- 执行参数worktree 路径等)
**不传递**
- 规划阶段的完整上下文
- 其他 issues 的信息
### 上下文加载策略
**Why the change?**
- Consolidates all agent role definitions in one place
- Eliminates duplicated role descriptions
- Single source of truth for agent capabilities
- Better organization with unified reference format
**Migration**:
```javascript
// Planning Agent 自己加载
const issueDetails = ReadFromIssueStore(issueId);
const techStack = Read('.workflow/project-tech.json');
const guidelines = Read('.workflow/project-guidelines.json');
// OLD (v1.0)
// Reference: specs/subagent-roles.md
// Execution Agent 自己加载
const solution = ReadFromSolutionStore(solutionId);
const project = Read('.workflow/project-guidelines.json');
// NEW (v2.0)
// Reference: specs/agent-roles.md
```
## 错误处理与重试
**Timeline**:
- v2.0 (2025-01-29): Old file kept for backward compatibility
- v2.1 (2025-03-31): Old file will be removed
### Planning 错误
---
| 错误 | 原因 | 重试策略 |
|------|------|----------|
| Subagent 超时 | 分析复杂 | 增加 timeout重试 1 次 |
| 无效 solution | 生成不符合 schema | 返回用户,标记失败 |
| 依赖循环 | DAG 错误 | 返回用户进行修正 |
# Subagent Roles Definition (Legacy - See agent-roles.md instead)
### Execution 错误
See [`agent-roles.md`](agent-roles.md) for the current consolidated agent roles specification.
| 错误 | 原因 | 重试策略 |
|------|------|----------|
| Task 失败 | 代码有问题 | 记录错误,标记 solution 失败 |
| 测试失败 | 测试用例不符 | 不提交,标记失败 |
| 提交失败 | 冲突或权限 | 创建快照,让用户决定 |
## 交互指南
### 向 Planning Agent 的问题
```
这个 issue 描述了什么问题?
→ 返回:问题分析 + 根本原因
解决这个问题需要修改哪些文件?
→ 返回:文件列表 + 修改点
如何验证解决方案是否有效?
→ 返回:验收条件 + 验证步骤
```
### 向 Execution Agent 的问题
```
这个 task 有哪些实现步骤?
→ 返回:逐步指南 + 代码示例
所有测试都通过了吗?
→ 返回:测试结果 + 失败原因(如有)
acceptance criteria 都满足了吗?
→ 返回:验证结果 + 不符合项(如有)
```
## Role 文件位置
```
~/.codex/agents/
├── issue-plan-agent.md # 规划角色
├── issue-execute-agent.md # 执行角色
└── ...
```
### 如果角色文件不存在
Orchestrator 会使用 `universal-executor``code-developer` 作为备用角色。
## 最佳实践
### 为 Planning Agent 设计提示词
```markdown
1. 从 issue 描述提取关键信息
2. 探索相关代码和类似实现
3. 设计最小化解决方案
4. 分解为 2-7 个可执行任务
5. 为每个 task 定义明确的 acceptance criteria
```
### 为 Execution Agent 设计提示词
```markdown
1. 加载 solution 和所有 task 定义
2. 按依赖顺序执行 tasks
3. 为每个 taskimplement → test → verify
4. 确保所有 acceptance criteria 通过
5. 提交一次包含所有更改
```
All content has been merged into the new agent-roles.md file with improved organization and formatting.

View File

@@ -909,7 +909,7 @@ function showCommandDetailModal(cmd) {
<!-- Tab Content -->
<div class="flex-1 overflow-y-auto">
<!-- Overview Tab -->
<div id="overview-tab" class="detail-tab-content p-6 space-y-6">
<div id="overview-tab" class="detail-tab-content p-6 space-y-6 active">
<!-- Description -->
<div>
<h3 class="text-sm font-semibold text-foreground mb-2">Description</h3>
@@ -992,7 +992,7 @@ function showCommandDetailModal(cmd) {
<!-- Document Tab -->
${cmd.source ? `
<div id="document-tab" class="detail-tab-content hidden p-6">
<div id="document-tab" class="detail-tab-content p-6">
<div class="bg-background border border-border rounded-lg p-4">
<div id="document-loader" class="flex items-center justify-center py-8">
<i data-lucide="loader-2" class="w-5 h-5 animate-spin text-primary mr-2"></i>
@@ -1038,11 +1038,11 @@ function showCommandDetailModal(cmd) {
// Show/hide tab content
var tabContents = modal.querySelectorAll('.detail-tab-content');
tabContents.forEach(function(content) {
content.classList.add('hidden');
content.classList.remove('active');
});
var activeTab = modal.querySelector('#' + tabName + '-tab');
if (activeTab) {
activeTab.classList.remove('hidden');
activeTab.classList.add('active');
}
// Load document content if needed
@@ -1099,13 +1099,21 @@ function loadCommandDocument(modal, sourcePath) {
fetch('/api/help/command-content?source=' + encodeURIComponent(sourcePath))
.then(function(response) {
if (!response.ok) {
throw new Error('Failed to load document');
throw new Error('HTTP ' + response.status + ': ' + response.statusText);
}
return response.text();
})
.then(function(markdown) {
// Parse markdown to HTML
var html = parseMarkdown(markdown);
try {
var html = parseMarkdown(markdown);
if (!html) {
throw new Error('parseMarkdown returned empty result');
}
} catch (parseError) {
console.error('[Help] parseMarkdown failed:', parseError.message, parseError.stack);
throw parseError;
}
if (contentDiv) {
contentDiv.innerHTML = html;
@@ -1116,11 +1124,13 @@ function loadCommandDocument(modal, sourcePath) {
if (typeof lucide !== 'undefined') lucide.createIcons();
})
.catch(function(error) {
console.error('Failed to load document:', error);
console.error('[Help] Failed to load document:', error.message || error);
if (contentDiv) contentDiv.classList.add('hidden');
if (loaderDiv) loaderDiv.classList.add('hidden');
if (errorDiv) {
errorDiv.textContent = 'Failed to load document: ' + (error.message || 'Unknown error');
errorDiv.classList.remove('hidden');
}
if (loaderDiv) loaderDiv.classList.add('hidden');
});
}

View File

@@ -254,6 +254,8 @@ export function buildCommand(params: {
// codex review uses -c key=value for config override, not -m
args.push('-c', `model=${model}`);
}
// Skip git repo check by default for codex (allows non-git directories)
args.push('--skip-git-repo-check');
// codex review uses positional prompt argument, not stdin
useStdin = false;
if (prompt) {
@@ -280,6 +282,8 @@ export function buildCommand(params: {
args.push('--add-dir', addDir);
}
}
// Skip git repo check by default for codex (allows non-git directories)
args.push('--skip-git-repo-check');
// Enable JSON output for structured parsing
args.push('--json');
// codex resume uses positional prompt argument, not stdin
@@ -302,6 +306,8 @@ export function buildCommand(params: {
args.push('--add-dir', addDir);
}
}
// Skip git repo check by default for codex (allows non-git directories)
args.push('--skip-git-repo-check');
// Enable JSON output for structured parsing
args.push('--json');
args.push('-');

View File

@@ -1,6 +1,6 @@
{
"name": "claude-code-workflow",
"version": "6.3.50",
"version": "6.3.52",
"description": "JSON-driven multi-agent development framework with intelligent CLI orchestration (Gemini/Qwen/Codex), context-first architecture, and automated workflow execution",
"type": "module",
"main": "ccw/src/index.js",