Full-stack development team: 8 specialized agents with Superpowers framework integration for automated workflow from requirements to deployment. 🆕 v6.6.0: Complete workflow automation with auto/interactive modes, Git worktree for seamless project creation, and Callstack React Native best practices integration.

version
6.6.0
GitHub stars
16

Install

/plugin install ceo@ceo-skills-marketplace

Run it inside Claude Code after adding the marketplace with /plugin marketplace add pyinx/ceo-skills-plugin.

Contents

Discovered from source

Skills 12

Brainstorming Ideas Into Designs

Overview

Help turn ideas into fully formed designs and specs through natural collaborative dialogue.

Start by understanding the current project context, then ask questions one at a time to refine the idea. Once you understand what you're building, present the design in small sections (200-300 words), checking after each section whether it looks right so far.

The Process

Understanding the idea:

  • Check out the current project state first (files, docs, recent commits)
  • Ask questions one at a time to refine the idea
  • Prefer multiple choice questions when possible, but open-ended is fine too
  • Only one question per message - if a topic needs more exploration, break it into multiple questions
  • Focus on understanding: purpose, constraints, success criteria

Exploring approaches:

  • Propose 2-3 different approaches with trade-offs
  • Present options conversationally with your recommendation and reasoning
  • Lead with your recommended option and explain why

Presenting the design:

  • Once you believe you understand what you're building, present the design
  • Break it into sections of 200-300 words
  • Ask after each section whether it looks right so far
  • Cover: architecture, components, data flow, error handling, testing
  • Be ready to go back and clarify if something doesn't make sense

After the Design

Documentation:

  • Write the validated design to docs/plans/YYYY-MM-DD-<topic>-design.md
  • Use elements-of-style:writing-clearly-and-concisely skill if available
  • Commit the design document to git

Implementation (if continuing):

  • Ask: "Ready to set up for implementation?"
  • Use superpowers:using-git-worktrees to create isolated workspace
  • Use superpowers:writing-plans to create detailed implementation plan

Key Principles

  • One question at a time - Don't overwhelm with multiple questions
  • Multiple choice preferred - Easier to answer than open-ended when possible
  • YAGNI ruthlessly - Remove unnecessary features from all designs
  • Explore alternatives - Always propose 2-3 approaches before settling
  • Incremental validation - Present design in sections, validate each
  • Be flexible - Go back and clarify when something doesn't make sense

CEO Agent - Direct Orchestration (v6.6.0)

When user requests software development, execute the following workflow:

Architecture Overview

v6.0 integrates Superpowers frameworks:

  • Phase 0: Brainstorming for requirement exploration
  • Phase 3.5: Git worktrees for workspace isolation
  • Phase 4: Subagent-driven development with two-stage code review
  • Phase 4.5: TDD enforcement
  • Phase 5: Parallel agent dispatch for independent test failures

Key principles:

  1. 流程自洽:Ensure workflow is complete, non-redundant, and naturally connected
  2. 保留自动化:Retain maximum automation, only key checkpoints require human confirmation
  3. 符合规范:Follow Claude Skill standards, prioritize Claude Code CLI native capabilities

Step 1: Initialize State Files

⚠️ NOTE: CEO agents are already installed as part of the ceo-skills plugin. No agent verification or installation is required.

Note: The Write tool will automatically create the .claudedocs directory if it doesn't exist.

Write initial task plan using Write tool

Create .claudedocs/task_plan.md with the following content:

# 任务计划

## Workflow配置 🆕 v6.5.0
- 执行模式: 待定(Step 1.5选择)
- 自动流转: 待定

## 用户需求
{USER_INPUT}

## 工作区配置
🔧 v6.5.0: 在阶段3.5创建Git Worktree后填充
- 工作区类型: Git Worktree
- 项目路径: 待定(阶段3.5创建)
- Git 分支: 待定(阶段3.5创建)

## 当前阶段
初始化

## 阶段进度
- [ ] 阶段0: 需求探索(brainstorming)
- [ ] 阶段1: 需求澄清(产品经理)
- [ ] 阶段2: 产品设计(UI/UX设计师)
- [ ] 阶段3: 架构设计(系统架构师)
- [ ] 阶段3.3: 平台决策(Web/Mobile/Both)🆕
- [ ] 阶段3.5: 工作区准备(git-worktrees)🔧 v6.5: 解决权限问题
- [ ] 阶段4: 开发实现(并行:Web+Mobile)🆕
- [ ] 阶段5: 测试验证(测试工程师-并行修复)
- [ ] 阶段6: 交付部署(市场营销师)

## 全局目标
1. 理解并澄清用户需求
2. 设计符合用户期望的产品
3. 实现高质量、可维护的代码
4. 确保充分测试和验证
5. 交付完整的文档和部署方案

Step 1.5: 选择Workflow执行模式 🆕 v6.5.0

Purpose: 在开始workflow前,让用户选择执行模式。

模式说明

  • 🤖 自动模式(推荐):完全自动化执行,跳过所有确认检查点,适合快速原型开发
  • 👤 交互模式:在关键阶段暂停,等待用户确认,适合重要项目

Execution

Use AskUserQuestion tool:

Question: "选择CEO Workflow执行模式:"
Header: "⚙️ Workflow模式配置"
Options:
  - label: "🤖 自动模式(推荐)"
    description: "完全自动化执行,跳过所有确认检查点,适合快速原型开发"
  - label: "👤 交互模式"
    description: "在每个关键阶段暂停,等待用户确认,适合重要项目"

Save user selection to task_plan.md:

If user selects "🤖 自动模式":

Edit file: .claudedocs/task_plan.md
Replace: "## Workflow配置\n- 执行模式: 待定(Step 1.5选择)\n- 自动流转: 待定"
With:
"""
## Workflow配置
- 执行模式: 自动模式
- 自动流转: 启用
- 确认检查点: 跳过
"""

If user selects "👤 交互模式":

Edit file: .claudedocs/task_plan.md
Replace: "## Workflow配置\n- 执行模式: 待定(Step 1.5选择)\n- 自动流转: 待定"
With:
"""
## Workflow配置
- 执行模式: 交互模式
- 自动流转: 禁用
- 确认检查点: 启用
"""

Display confirmation message:

═════════════════════════════════════════════════════════════
✅ Workflow模式已配置
═════════════════════════════════════════════════════════════

执行模式: {用户选择的模式}
{if 自动模式} 🤖 自动模式:将自动流转到所有阶段,无需手动确认
{if 交互模式} 👤 交互模式:将在关键阶段等待您确认

📋 下一步: Phase 0 - 需求探索

Proceed to Step 2 (Phase 0).

  • Git 分支: 待定(阶段3.5创建)

当前阶段

初始化

阶段进度

  • 阶段0: 需求探索(brainstorming)
  • 阶段1: 需求澄清(产品经理)
  • 阶段2: 产品设计(UI/UX设计师)
  • 阶段3: 架构设计(系统架构师)
  • 阶段3.3: 平台决策(Web/Mobile/Both)🆕
  • 阶段3.5: 工作区准备(git-worktrees)🔧 v6.5: 解决权限问题
  • 阶段4: 开发实现(并行:Web+Mobile)🆕
  • 阶段5: 测试验证(测试工程师-并行修复)
  • 阶段6: 交付部署(市场营销师)

全局目标

  1. 理解并澄清用户需求
  2. 设计符合用户期望的产品
  3. 实现高质量、可维护的代码
  4. 确保充分测试和验证
  5. 交付完整的文档和部署方案

### Initialize notes file
Create `.claudedocs/notes.md` with the following content:
```markdown
# 项目笔记

## 初始化
项目启动时间: [执行时自动记录]

Step 2: Detect Current Phase and Resume

⚠️ CRITICAL: Before starting any phase, check if there's an existing workflow to resume.

Check for existing task plan

Use Read tool to check if task plan exists:

Read file: .claudedocs/task_plan.md

If task_plan.md exists (Resume Mode)

  1. Parse current phase: Read "## 当前阶段" section
  2. Check progress: Read "## 阶段进度" to see completed phases
  3. Jump to next phase: Use the mapping below

Phase mapping:

"初始化" OR "阶段0: 需求探索" → Go to Step 3 (Phase 0)
"阶段1: 需求澄清" → Go to Step 4 (Phase 1)
"阶段2: 产品设计" → Go to Step 5 (Phase 2)
"阶段3: 架构设计" → Go to Step 6 (Phase 3)
"阶段3.5: 工作区准备" → Go to Step 7 (Phase 3.5)
"阶段4: 开发实现" → Go to Step 8 (Phase 4)
"阶段5: 测试验证" → Go to Step 9 (Phase 5)
"阶段6: 交付部署" → Go to Step 10 (Phase 6)

Display resume message:

═════════════════════════════════════════════════════════════
🔄 恢复工作流
═════════════════════════════════════════════════════════════

检测到现有任务计划,将从 {CURRENT_PHASE} 继续执行。

Then jump to the appropriate step above.

If task_plan.md doesn't exist (Fresh Start)

Display initialization message:

═════════════════════════════════════════════════════════════
🚀 启动新的 CEO 工作流
═════════════════════════════════════════════════════════════

将创建新的任务计划并执行完整 6 阶段开发流程。

Proceed to Step 3 (Phase 0).


Step 3: Execute Phase 0 - 需求探索(Brainstorming)

🆕 NEW in v6.0: Integrate Superpowers brainstorming for requirement exploration.

Purpose

Before generating formal PRD, conduct conversational exploration to fully understand user requirements through dialogue.

Process

Follow the brainstorming process:

digraph phase0_brainstorming {
    rankdir=TB;
    start [label="用户输入模糊需求", shape=ellipse];
    context [label="检查项目状态\n(文件、文档、最近提交)", shape=box];
    questions [label="苏格拉底式提问\n(一次一个问题)", shape=box, style=filled, fillcolor="#e1f5ff"];
    approaches [label="提出2-3种方案\n(含权衡分析)", shape=box];
    design [label="分段展示设计\n(200-300词/段)", shape=box];
    validate [label="每段后验证\n'这看起来对吗?'", shape=diamond];
    doc [label="保存设计文档\n.claudedocs/phase0-design.md", shape=box];

    start → context;
    context → questions;
    questions → approaches;
    approaches → design;
    design → validate;
    validate → design [label="否,调整"];
    validate → doc [label="是"];
}

Key Rules

提问规则:

  • 一次一个问题:不要用多个问题淹没用户
  • 优先选择题:比开放性问题更容易回答
  • 聚焦理解:目的、约束、成功标准

设计展示规则:

  • 分段展示:每段200-300词
  • 每段验证:展示后询问"这看起来对吗?"
  • 灵活调整:如有不清楚,返回澄清

产出物:

  • 设计文档:.claudedocs/phase0-design.md
  • 包含内容:架构、组件、数据流、错误处理、测试策略

Execution

⚠️ DO NOT use AskUserQuestion tool - brainstorming is a natural conversational process.

Invoke the brainstorming skill (from superpowers), execute it, then continue to Phase 1.

After brainstorming completes, save design document to:

.claudedocs/phase0-design.md

Then update task_plan.md to mark Phase 0 as completed:

Edit: Replace "- [ ] 阶段0: 需求探索(brainstorming)"
With:  "- [x] 阶段0: 需求探索(brainstorming)"
Edit: Replace "## 当前阶段\n初始化"
With: "## 当前阶段\n阶段0: 需求探索(完成)"

Proceed to Phase 1.

═════════════════════════════════════════════════════════════
✅ Phase 0 完成 - 需求探索
═════════════════════════════════════════════════════════════

📄 设计文档: .claudedocs/phase0-design.md
📋 下一步: Phase 1 - 需求澄清(产品经理)

Step 4: Execute Phase 1 - 需求澄清(产品经理)

⚠️ MANDATORY: Read Previous Phase Output

Before executing this phase, you MUST read all previous outputs:

Read file: .claudedocs/phase0-design.md

This ensures you have complete context from Phase 0.

Update task plan current phase

Use Edit tool to update task_plan.md:

Replace: "## 当前阶段\n初始化"
With: "## 当前阶段\n阶段1: 需求澄清"

Call Product Manager agent

⚠️ IMPORTANT: Execute the following steps in order to ensure the agent completes BEFORE the confirmation checkpoint.

Step 1: Launch agent

Task tool: Launch the ceo-product-manager agent with the following context:

## CEO任务上下文

### 用户输入
{USER_INPUT}

### 阶段0输出(NEW - 设计文档)
[使用Read工具读取 .claudedocs/phase0-design.md 内容]

### 你的任务
1. 基于阶段0设计文档生成产品需求文档(PRD)
2. 构建用户画像
3. 定义MVP范围
4. 识别未澄清的问题(如有)

### ⚠️ 关键约束 - 提问规则
- **最多提问5个问题**:降低用户认知负担
- **分批提问**:如果问题超过5个,分多次提问,每次最多5个
- **优先级排序**:先问最重要、最核心的问题

### 输出要求
- 输出完整的PRD文档到 .claudedocs/ceo-product-manager_result.md
- 包含用户画像、功能列表、优先级
- 如果有未问的问题,在文档末尾列出"待确认的问题"

Save the returned task_id as {PRODUCT_MANAGER_TASK_ID}

Step 2: Wait for agent completion

TaskOutput: Wait for {PRODUCT_MANAGER_TASK_ID}
Parameters: block=true, timeout=300000

⚠️ CRITICAL: DO NOT PROCEED until agent completes
⚠️ DO NOT proceed to confirmation checkpoint until this step completes

Step 3: Verify output file exists

Read file: .claudedocs/ceo-product-manager_result.md

⚠️ If file doesn't exist, agent failed - inform user and ask what to do

After agent completes and output is verified, proceed to confirmation checkpoint below.

Step 4.2: CONDITIONAL - User Confirmation Checkpoint 🆕 v6.5.0

⚠️ CONDITIONAL CHECKPOINT - 根据workflow模式决定是否需要确认

Check workflow mode first:

Read file: .claudedocs/task_plan.md

Extract:
  - 执行模式: (自动模式 | 交互模式)

If 执行模式 == "自动模式":

✅ 自动模式:跳过确认检查点

直接执行批准操作:
1. Use Edit tool to update task_plan.md:
   Replace: "## 当前阶段\n阶段1: 需求澄清"
   With: "## 当前阶段\n阶段2: 产品设计"
   Replace: "- [ ] 阶段0: 需求探索(brainstorming)"
   With: "- [x] 阶段0: 需求探索(brainstorming)"
   Replace: "- [ ] 阶段1: 需求澄清(产品经理)"
   With: "- [x] 阶段1: 需求澄清(产品经理)"

2. Display message:

═════════════════════════════════════════════════════════════ ✅ 自动模式:PRD已自动批准 ═════════════════════════════════════════════════════════════

🤖 执行模式: 自动模式 📄 PRD文档: .claudedocs/ceo-product-manager_result.md ✅ 状态: 已自动批准,继续下一阶段

📋 下一步: Phase 2 - 产品设计(UI/UX设计师)


3. Proceed to Step 5 (Phase 2).

If 执行模式 == "交互模式":

👤 交互模式:执行用户确认流程

⚠️ **CRITICAL**: You MUST pause here and wait for user confirmation before proceeding.

First, use Read tool to display PRD preview:

Read file: .claudedocs/ceo-product-manager_result.md Limit: 50 lines Display to user with formatted header: "📋 产品需求文档预览"


Then, use AskUserQuestion tool to get user confirmation:

Question: "请查看产品需求文档(PRD)并提供反馈。是否批准此PRD?" Header: "🎯 检查点 1 - 产品需求文档确认" Options:

  • label: "✅ 批准PRD" description: "PRD符合预期,批准并继续下一阶段"
  • label: "📝 修改PRD" description: "我有修改意见,需要调整PRD"
  • label: "🔄 重做PRD" description: "PRD不符合预期,需要重新澄清需求"
  • label: "🛑 终止workflow" description: "结束整个开发流程"

⚠️ **DO NOT PROCEED** until user selects an option.

Step 4.3: Process User Decision

If user selects ✅ 批准PRD:

  1. Use Edit tool to update task_plan.md:
    • Mark Phase 0 and Phase 1 as completed
    • Update current phase to "阶段2: 产品设计"
  2. Proceed to Step 5 (Phase 2).
═════════════════════════════════════════════════════════════
✅ Phase 1 完成 - 需求澄清
═════════════════════════════════════════════════════════════

📄 PRD文档: .claudedocs/ceo-product-manager_result.md
📋 下一步: Phase 2 - 产品设计(UI/UX设计师)

If user selects 📝 修改PRD:

  1. Use AskUserQuestion to collect specific modification requests
  2. Call Product Manager again with feedback
  3. After revision completes, repeat Step 4.2 (confirmation checkpoint)

If user selects 🔄 重做PRD:

  1. Use AskUserQuestion to collect new requirements
  2. Call Product Manager for new round
  3. After new PRD completes, repeat Step 4.2 (confirmation checkpoint)

If user selects 🛑 终止workflow:

  1. Display termination message
  2. Update task_plan.md with termination status
  3. End workflow

Step 5: Execute Phase 2 - 产品设计

⚠️ MANDATORY: Read Previous Phase Outputs

Before executing this phase, you MUST read all previous outputs:

Read file: .claudedocs/phase0-design.md
Read file: .claudedocs/ceo-product-manager_result.md

This ensures you have complete context from Phase 0 and Phase 1.

Update task plan current phase

Use Edit tool to update task_plan.md:

Replace: "## 当前阶段\n阶段1: 需求澄清"
With: "## 当前阶段\n阶段2: 产品设计"

Call UI/UX Designer agent

⚠️ IMPORTANT: Execute the following steps in order to ensure the agent completes BEFORE proceeding.

Step 1: Launch agent

Task tool: Launch the ceo-ui-ux-designer agent with the following context:

## CEO任务上下文

### 用户输入
{USER_INPUT}

### 阶段0-1输出
[使用Read工具读取阶段0设计文档和阶段1 PRD]

### 用户对阶段0-1问题的回答
{USER_ANSWERS_PHASE0_1}

### 你的任务
1. 基于PRD设计用户故事
2. 设计交互流程
3. 设计视觉界面
4. 创建原型设计

### ⚠️ 关键约束 - 提问规则
- **最多提问5个问题**:降低用户认知负担
- **分批提问**:如果问题超过5个,分多次提问,每次最多5个
- **优先级排序**:先问最重要、最核心的设计问题

### 输出要求
- 输出完整的设计文档到 .claudedocs/ceo-ui-ux-designer_result.md
- 包含用户故事、交互流程、视觉设计

Save the returned task_id as {UI_UX_TASK_ID}

Step 2: Wait for agent completion

TaskOutput: Wait for {UI_UX_TASK_ID}
Parameters: block=true, timeout=300000

⚠️ CRITICAL: DO NOT PROCEED until agent completes

Step 3: Verify output file exists

Read file: .claudedocs/ceo-ui-ux-designer_result.md

⚠️ If file doesn't exist, agent failed - inform user and ask what to do

After agent completes and output is verified:

  1. Use Edit tool to update task_plan.md: Mark Phase 2 as completed
  2. Proceed directly to Phase 3 (no confirmation required).
═════════════════════════════════════════════════════════════
✅ Phase 2 完成 - 产品设计
═════════════════════════════════════════════════════════════

📄 设计文档: .claudedocs/ceo-ui-ux-designer_result.md
📋 下一步: Phase 3 - 架构设计(系统架构师)

Step 6: Execute Phase 3 - 架构设计

⚠️ MANDATORY: Read Previous Phase Outputs

Before executing this phase, you MUST read all previous outputs:

Read file: .claudedocs/phase0-design.md
Read file: .claudedocs/ceo-product-manager_result.md
Read file: .claudedocs/ceo-ui-ux-designer_result.md

This ensures you have complete context from Phase 0, 1, and 2.

Update task plan current phase

Use Edit tool to update task_plan.md:

Replace: "## 当前阶段\n阶段2: 产品设计"
With: "## 当前阶段\n阶段3: 架构设计"

Call System Architect agent

⚠️ CRITICAL: Execute the following steps in order to ensure the agent completes BEFORE the confirmation checkpoint.

Step 1: Launch agent

Task tool: Launch the ceo-system-architect agent with the following context:

## CEO任务上下文

### 用户输入
{USER_INPUT}

### 前期阶段输出
[使用Read工具读取所有前期输出文件]

### 用户回答
{USER_ANSWERS}

### 你的任务
1. 技术栈选型(前端、后端、数据库)
2. 系统架构设计
3. API规范设计
4. 数据模型设计

### ⚠️ 关键约束 - 提问规则
- **最多提问5个问题**:降低用户认知负担
- **分批提问**:如果技术决策问题超过5个,分多次提问
- **优先级排序**:先问最关键的技术选型问题

### 输出要求
- 输出完整的架构设计文档到 .claudedocs/ceo-system-architect_result.md

Save the returned task_id as {ARCHITECT_TASK_ID}

Step 2: Wait for agent completion

TaskOutput: Wait for {ARCHITECT_TASK_ID}
Parameters: block=true, timeout=300000

⚠️ CRITICAL: DO NOT PROCEED until agent completes
⚠️ DO NOT proceed to confirmation checkpoint until this step completes

Step 3: Verify output file exists

Read file: .claudedocs/ceo-system-architect_result.md

⚠️ If file doesn't exist, agent failed - inform user and ask what to do
⚠️ DO NOT proceed to confirmation checkpoint if file doesn't exist

After agent completes and output is verified, CHECK WORKFLOW MODE before proceeding.

⚠️ DO NOT PROCEED to Phase 3.5 until user confirms the architecture (交互模式) or auto-approves (自动模式)!

Step 6.1: CONDITIONAL - Architecture Confirmation Checkpoint 🆕 v6.5.0

🚨 CONDITIONAL CHECKPOINT - 根据workflow模式决定是否需要确认

Check workflow mode first:

Read file: .claudedocs/task_plan.md

Extract:
  - 执行模式: (自动模式 | 交互模式)

If 执行模式 == "自动模式":

✅ 自动模式:跳过确认检查点

直接执行批准操作:
1. Use Edit tool to update task_plan.md:
   Replace: "## 当前阶段\n阶段3: 架构设计"
   With: "## 当前阶段\n阶段3.3: 平台决策"
   Replace: "- [ ] 阶段3: 架构设计(系统架构师)"
   With: "- [x] 阶段3: 架构设计(系统架构师)"

2. Display message:

═════════════════════════════════════════════════════════════ ✅ 自动模式:架构已自动批准 ═════════════════════════════════════════════════════════════

🤖 执行模式: 自动模式 📄 架构文档: .claudedocs/ceo-system-architect_result.md ✅ 状态: 已自动批准,继续平台决策

📋 下一步: Phase 3.3 - 平台决策


3. Proceed to Step 6.3 (Phase 3.3).

If 执行模式 == "交互模式":

👤 交互模式:执行用户确认流程

🚨 **CRITICAL CHECKPOINT - MANDATORY USER CONFIRMATION REQUIRED**

You are at the Architecture Confirmation Checkpoint. You MUST execute this step before proceeding to Phase 3.5.

**Step 1**: Display architecture document preview using Read tool:

Read file: .claudedocs/ceo-system-architect_result.md Limit: 50 lines Display formatted header: "🏗️ 技术架构设计文档预览"


**Step 2**: Use AskUserQuestion tool to get user confirmation:

Question: "请查看技术架构设计文档并提供反馈。是否批准此架构方案?" Header: "🏗️ 检查点 2 - 技术架构方案确认" Options:

  • label: "✅ 批准架构" description: "架构方案符合预期,批准并继续创建工作区"
  • label: "📝 修改架构" description: "我有修改意见,需要调整架构设计"
  • label: "🔄 重做架构" description: "架构不符合预期,需要重新设计"
  • label: "🛑 终止workflow" description: "结束整个开发流程"

**Step 3**: ⚠️ **WAIT FOR USER RESPONSE - DO NOT PROCEED**

⚠️ **DO NOT PROCEED** until user selects an option.
⚠️ **DO NOT PROCEED to Phase 3.5** until user selects "✅ 批准架构".

Step 6.2: Process User Decision

If user selects ✅ 批准架构:

  1. Use Edit tool to update task_plan.md:
    • Mark Phase 3 as completed
    • Update current phase to "阶段3.3: 平台决策"
  2. Proceed to Step 6.3 (Phase 3.3 - 平台决策).
═════════════════════════════════════════════════════════════
✅ Phase 3 完成 - 架构设计
═════════════════════════════════════════════════════════════

📄 架构文档: .claudedocs/ceo-system-architect_result.md
📋 下一步: Phase 3.3 - 平台决策(Web/Mobile/Both)

Step 6.3: 🆕 Phase 3.3 - 平台决策(NEW in v6.4.0)

🆕 NEW in v6.4.0: 在架构设计后进行平台决策,动态决定开发Web、Mobile还是Both。

Purpose

根据产品需求、用户场景、功能需求和技术约束,决定开发平台:

  • Web Only: 仅Web应用
  • Mobile Only: 仅移动应用
  • Both: Web + Mobile并行开发

决策流程

Step 1: 分析决策因素

基于以下因素进行分析:

决策因素:
  用户因素:
    - 目标用户类型(办公用户/移动用户/全场景用户)
    - 主要使用设备(桌面/移动/混合)
    - 使用场景(固定/移动/灵活)

  功能因素:
    - 需要的原生功能(GPS、相机、传感器等)
    - 复杂表单处理(Web优势)
    - 实时协作(Web优势)
    - 离线需求(Mobile优势)

  技术因素:
    - 技术栈复杂度
    - 开发时间要求
    - 团队能力匹配

  约束因素:
    - 开发预算
    - 上市时间要求
    - 维护成本考虑

Step 2: 生成平台决策

基于分析生成决策文档:

interface PlatformDecision {
  // 目标平台
  platforms: ('web' | 'mobile')[];

  // 开发优先级
  priority: 'web-first' | 'mobile-first' | 'parallel';

  // 决策理由
  rationale: string;

  // 实施建议
  implementation: {
    phasedRollout: boolean;
    mvpPlatform: 'web' | 'mobile';
    featuresByPlatform: {
      web: string[];
      mobile: string[];
      shared: string[];
    };
  };
}

Step 3: 保存决策文档

使用Write工具创建平台决策文档:

Write file: .claudedocs/platform-decision.md

Content:
# 平台决策文档

## 决策结果
- **目标平台**: {web | mobile | both}
- **开发优先级**: {web-first | mobile-first | parallel}
- **决策理由**: {rationale}

## 实施计划
- **分阶段发布**: {yes | no}
- **MVP平台**: {web | mobile}

## 功能分配
- **Web独有功能**: [...]
- **Mobile独有功能**: [...]
- **共享功能**: [...]

Step 4: 更新任务计划

使用Edit工具更新task_plan.md:

Replace: "## 当前阶段\n阶段3: 架构设计"
With: "## 当前阶段\n阶段3.3: 平台决策"

Step 6.4: CONDITIONAL - 平台决策确认检查点 🆕 v6.5.0

⚠️ CONDITIONAL CHECKPOINT - 根据workflow模式决定是否需要确认

Check workflow mode first:

Read file: .claudedocs/task_plan.md

Extract:
  - 执行模式: (自动模式 | 交互模式)

If 执行模式 == "自动模式":

✅ 自动模式:跳过确认检查点

直接执行批准操作:
1. Use Edit tool to update task_plan.md:
   Replace: "## 当前阶段\n阶段3.3: 平台决策"
   With: "## 当前阶段\n阶段3.5: 工作区准备"
   Replace: "- [ ] 阶段3.3: 平台决策(Web/Mobile/Both)"
   With: "- [x] 阶段3.3: 平台决策(Web/Mobile/Both)"

2. Extract platform decision and add to global goals:

Read file: .claudedocs/platform-decision.md

Extract:

  • platforms: (web | mobile | both)
  • priority: (web-first | mobile-first | parallel)

Add to task_plan.md "## 全局目标":
  • 开发平台: {platforms}
  • 优先级策略: {priority}

3. Display message:

═════════════════════════════════════════════════════════════ ✅ 自动模式:平台决策已自动批准 ═════════════════════════════════════════════════════════════

🤖 执行模式: 自动模式 📄 决策文档: .claudedocs/platform-decision.md 📱 开发平台: {platforms} ⚡ 优先级: {priority} ✅ 状态: 已自动批准,继续工作区准备

📋 下一步: Phase 3.5 - 工作区准备(Git Worktrees)


4. Proceed to Step 7 (Phase 3.5).

If 执行模式 == "交互模式":

👤 交互模式:执行用户确认流程

🚨 **CRITICAL CHECKPOINT - MANDATORY USER CONFIRMATION REQUIRED**

**Step 1**: 显示平台决策文档预览:

```bash
Read file: .claudedocs/platform-decision.md
Limit: 30 lines
Display formatted header: "📱 平台决策预览"

Step 2: 使用AskUserQuestion工具获取用户确认:

Question: "根据产品需求和技术架构分析,建议开发{platforms},采用{priority}策略。是否批准此平台决策?"
Header: "📱 检查点 2.5 - 平台决策确认"
Options:
  - label: "✅ 批准决策"
    description: "同意平台决策,继续工作区准备"
  - label: "📝 修改决策"
    description: "有不同意见,需要调整平台决策"
  - label: "🛑 终止workflow"
    description: "结束整个开发流程"

Step 3: ⚠️ 等待用户响应 - 不要继续执行


### Step 6.5: 处理用户决策

**如果用户选择 ✅ 批准决策**:

1. 使用Edit工具更新task_plan.md:
   - 标记阶段3.3为已完成
   - 更新当前阶段为"阶段3.5: 工作区准备"
   - 添加平台决策信息到全局目标

```bash
Edit: task_plan.md
Add to "## 全局目标":
  - 开发平台: {platforms}
  - 开发策略: {priority}
  1. 继续执行Step 7 (Phase 3.5)
═════════════════════════════════════════════════════════════
✅ Phase 3.3 完成 - 平台决策
═════════════════════════════════════════════════════════════

📄 决策文档: .claudedocs/platform-decision.md
🎯 目标平台: {platforms}
📋 下一步: Phase 3.5 - 工作区准备(git-worktrees)

如果用户选择 📝 修改决策:

  1. 使用AskUserQuestion收集具体的修改意见
  2. 重新分析并生成新的平台决策
  3. 重复Step 6.4(确认检查点)

如果用户选择 🛑 终止workflow:

  1. 显示终止消息
  2. 更新task_plan.md为终止状态
  3. 结束workflow

If user selects 📝 修改架构:

  1. Use AskUserQuestion to collect specific modification requests
  2. Call System Architect again with feedback
  3. After revision completes, repeat Step 6.1 (confirmation checkpoint)

If user selects 🔄 重做架构:

  1. Use AskUserQuestion to collect new requirements
  2. Call System Architect for new round
  3. After new architecture completes, repeat Step 6.1 (confirmation checkpoint)

If user selects 🛑 终止workflow:

  1. Display termination message
  2. Update task_plan.md with termination status
  3. End workflow

Step 7: Execute Phase 3.5 - 工作区准备(Git Worktrees)

🆕 NEW in v6.0: Integrate Superpowers using-git-worktrees for workspace isolation.

🔧 UPDATED in v6.5.0: 明确使用git-worktree解决Claude Code CLI跨目录访问权限问题。

Purpose

Before starting development, create isolated Git worktree to:

  1. ✅ 避免分支切换污染
  2. ✅ 解决跨目录访问权限问题(worktree属于项目内,无需额外确认)
  3. ✅ 提供独立的工作环境

Why Git Worktree Solves Permission Issues

问题根源:

# 当前工作目录
/path/to/ceo-skills-plugin/

# 操作目标(项目外)
/path/to/another-project/.claudedocs/
# ❌ Claude Code提示权限确认

Git Worktree解决方案:

# 创建worktree(项目内)
git worktree add ../my-project -b feature/my-project

# worktree目录结构
/path/to/repo/
├── .git/                    # 共享Git仓库
├── ceo-skills-plugin/        # 主worktree(当前目录)
└── my-project/               # 新worktree(共享.git)
    └── .git (worktree元数据)

# 操作目标(项目内)
../my-project/.claudedocs/
# ✅ worktree是Git仓库的一部分,无需权限确认

Execution Steps

Step 7.1: 确定项目名称和路径

从架构设计文档中提取项目名称:

Read file: .claudedocs/ceo-system-architect_result.md

Extract:
  - project_name: 项目名称

Step 7.2: 创建Git Worktree

# 计算worktree路径(相对于当前仓库)
WORKTREE_PATH="../${project_name}"
BRANCH_NAME="feature/${project_name}"

# 创建worktree
git worktree add ${WORKTREE_PATH} -b ${BRANCH_NAME}

# 验证创建成功
git worktree list

# 在worktree中创建文档目录(无需权限确认)
mkdir -p ${WORKTREE_PATH}/.claudedocs

Step 7.3: 保存Worktree信息到任务计划

Edit file: .claudedocs/task_plan.md

Add section after "## 用户需求":

## 工作区配置
- 工作区类型: Git Worktree
- 项目路径: ${WORKTREE_PATH}
- Git 分支: ${BRANCH_NAME}
- 相对路径: ../${project_name}

Replace: "## 当前阶段\n阶段3: 架构设计"
With: "## 当前阶段\n阶段3.5: 工作区准备"

Replace: "- [ ] 阶段3.5: 工作区准备(git-worktrees)"
With: "- [x] 阶段3.5: 工作区准备(git-worktrees)"

Step 7.4: 验证Worktree准备完成

# 列出所有worktrees
git worktree list

# 切换到worktree查看(可选)
cd ${WORKTREE_PATH}
pwd
ls -la

Proceed to Step 8 (Phase 4).

═════════════════════════════════════════════════════════════
✅ Phase 3.5 完成 - 工作区准备
═════════════════════════════════════════════════════════════

🌳 工作树路径: {WORKTREE_PATH}
📋 下一步: Phase 4 - 开发实现(子任务驱动)

Step 8: Execute Phase 4 - 开发实现(并行:Web + Mobile)

🆕 ENHANCED in v6.4.0: 支持并行Web和Mobile开发,根据平台决策动态激活agents。

🔧 UPDATED in v6.5.0: 所有项目操作在Git Worktree路径中执行,避免跨目录访问权限问题。

⚠️ MANDATORY: Read Previous Phase Outputs & Platform Decision

Before executing this phase, you MUST read all previous outputs AND the platform decision:

Read file: .claudedocs/phase0-design.md
Read file: .claudedocs/ceo-product-manager_result.md
Read file: .claudedocs/ceo-ui-ux-designer_result.md
Read file: .claudedocs/ceo-system-architect_result.md
Read file: .claudedocs/platform-decision.md  🆕 平台决策

This ensures you have complete context from all previous phases AND know which platforms to develop.

⚠️ CRITICAL: Load Worktree Configuration

🔧 v6.5.0: 从任务计划中加载worktree配置,确保所有项目操作在正确路径中执行:

Read file: .claudedocs/task_plan.md

Extract:
  - WORKTREE_PATH: 工作区路径(如 ../my-project)
  - BRANCH_NAME: Git分支(如 feature/my-project)

重要提示:

  • ✅ 所有项目创建、文件操作、命令执行都在 ${WORKTREE_PATH} 中进行
  • ✅ Worktree是Git仓库的一部分,属于"项目内",无需权限确认
  • ❌ 不要直接操作 /Users/zyb/.../my-project,使用相对路径 ${WORKTREE_PATH}

Execution Steps

Step 8.1: Update task plan current phase

Replace: "## 当前阶段\n阶段3.5: 工作区准备"
With: "## 当前阶段\n阶段4: 开发实现"

Step 8.2: 🆕 Parse Platform Decision

从平台决策文档中提取开发策略:

Read file: .claudedocs/platform-decision.md

Extract:
  - platforms: (web | mobile | both)
  - priority: (web-first | mobile-first | parallel)

Step 8.3: 🆕 根据平台决策配置开发任务

方案A: Backend Only(纯后端)

如果决策是纯后端项目(无前端需求):

📋 开发策略:Backend Only

任务分配:
  - fullstack-developer: 后端API

执行步骤:
  1. 调用subagent-driven-development skill
  2. 激活ceo-fullstack-developer agent(仅后端)
  3. 任务分解:
     - 后端API实现
     - 数据库设计
     - 业务逻辑实现
  4. 执行两阶段代码审查

方案B: Web Frontend + Backend(传统Web)

如果决策是传统Web应用(React/Next.js等):

📋 开发策略:Web Full Stack

任务分配:
  - fullstack-developer: 后端API + Web前端

执行步骤:
  1. 调用subagent-driven-development skill
  2. 激活ceo-fullstack-developer agent
  3. 任务分解:
     - 后端API实现
     - Web前端实现(React/Next.js)
  4. 执行两阶段代码审查

技术栈:
  - 后端: Node.js/Python/Go
  - 前端: React/Next.js/Vue(传统Web技术)

方案C: Cross-Platform Mobile(跨平台移动应用)

如果决策是跨平台移动应用(需要iOS + Android + Web):

📋 开发策略:Cross-Platform Mobile

任务分配:
  - fullstack-developer: 后端API
  - mobile-developer: React Native应用(iOS + Android + Web)

执行步骤:
  1. 调用subagent-driven-development skill
  2. 并行激活agents:
     - ceo-fullstack-developer (后端API)
     - ceo-mobile-developer (React Native应用)
  3. 移动端开发依赖后端API完成
  4. 执行两阶段代码审查

技术栈:
  - 后端: Node.js/Python/Go
  - 移动端: React Native + Expo
  - 平台: iOS、Android、Web(React Native for Web)

说明:
  - React Native的"Web"是通过React Native for Web编译的
  - 这与传统Web前端(React/Next.js)不同
  - 一套代码覆盖三个平台

方案D: Web + Mobile Both(Web + 移动端)

如果决策是同时需要传统Web和移动应用:

📋 开发策略:Web + Mobile Both

任务分配:
  - fullstack-developer: 后端API + 传统Web前端
  - mobile-developer: React Native移动应用

根据优先级策略执行:

#### 策略1: web-first

执行顺序:
  1. 后端API (fullstack-developer)
  2. 传统Web前端 (fullstack-developer)
  3. 移动端 (mobile-developer)

#### 策略2: mobile-first

执行顺序:
  1. 后端API (fullstack-developer)
  2. 移动端 (mobile-developer)
  3. 传统Web前端 (fullstack-developer)

#### 策略3: parallel

执行顺序:
  1. 后端API (fullstack-developer) - 必须首先完成
  2. 并行开发:
     - 传统Web前端 (fullstack-developer)
     - 移动端 (mobile-developer)

技术栈:
  - 后端: Node.js/Python/Go
  - Web前端: React/Next.js(传统Web)
  - 移动端: React Native + Expo

Step 8.4: Extract development tasks from architecture

Read the architecture document and identify all development tasks. Group them into 2-5 minute subtasks.

⚠️ Note: All operations should use absolute paths based on {WORKTREE_PATH}.

Step 8.5: 🆕 根据平台策略执行开发

后端API开发(始终执行)

# 后端API由fullstack-developer统一实现
Task tool: Launch ceo-fullstack-developer agent

任务:
  1. 实现后端API(按照architect设计的API规范)
  2. 实现数据模型
  3. 实现业务逻辑
  4. API文档生成

输出: .claudedocs/backend-api-result.md

Web前端开发(按需执行)

如果 platforms.includes('web'):

Task tool: Launch ceo-fullstack-developer agent

任务:
  1. 实现Web前端组件
  2. 实现Web状态管理
  3. 集成后端API
  4. 响应式实现

依赖: 后端API完成

输出: .claudedocs/web-frontend-result.md

移动端开发(按需执行)

如果 platforms.includes('mobile'):

Task tool: Launch ceo-mobile-developer agent

任务:
  1. 初始化移动项目(使用obytes模板)
  2. 实现移动端UI
  3. 实现移动端状态管理
  4. 集成后端API
  5. 原生功能集成(如需要)

依赖: 后端API完成

输出: .claudedocs/mobile-app-result.md

Step 8.6: 🆕 并行开发协调

根据 priority 策略协调开发:

// web-first 策略
if (priority === 'web-first') {
  await executeBackendAPI();     // fullstack
  await executeWebFrontend();     // fullstack
  await executeMobileApp();       // mobile
}

// mobile-first 策略
else if (priority === 'mobile-first') {
  await executeBackendAPI();      // fullstack
  await executeMobileApp();        // mobile
  await executeWebFrontend();      // fullstack
}

// parallel 策略
else if (priority === 'parallel') {
  await executeBackendAPI();       // fullstack (必须先完成)

  // Web和Mobile并行开发
  await Promise.all([
    executeWebFrontend(),          // fullstack
    executeMobileApp()             // mobile
  ]);
}

⚠️ TDD Enforcement: 所有开发必须遵循TDD:

  • RED: 先写失败的测试
  • GREEN: 写最少的代码通过测试
  • REFACTOR: 重构清理

Step 8.7: Update task plan progress

Edit: Replace "- [ ] 阶段4: 开发实现(并行:Web+Mobile)"
With:  "- [x] 阶段4: 开发实现(并行:Web+Mobile)"
Edit: Update "## 当前阶段" to "阶段5: 测试验证"

Proceed to Step 9 (Phase 5).

═════════════════════════════════════════════════════════════
✅ Phase 4 完成 - 开发实现
═════════════════════════════════════════════════════════════

🎯 开发平台: {platforms}
📊 开发策略: {priority}
💻 后端代码: {WORKTREE_PATH}/backend/
🌐 Web代码: {WORKTREE_PATH}/web/ (如适用)
📱 Mobile代码: {WORKTREE_PATH}/mobile/ (如适用)
📋 下一步: Phase 5 - 测试验证(测试工程师-并行修复)

Step 9: Execute Phase 5 - 测试验证(并行修复)

🆕 ENHANCED in v6.0: Integrate Superpowers dispatching-parallel-agents for independent test failures.

⚠️ MANDATORY: Read Previous Phase Outputs

Before executing this phase, you MUST read all previous outputs:

Read file: .claudedocs/ceo-system-architect_result.md
Read file: .claudedocs/ceo-fullstack-developer_result.md (if exists)

This ensures you have complete context from architecture and development.

Execution Steps

Step 9.1: Update task plan current phase

Replace: "## 当前阶段\n阶段4: 开发实现"
With: "## 当前阶段\n阶段5: 测试验证"

Step 9.2: Call Test Engineer agent

⚠️ IMPORTANT: Execute the following steps in order to ensure the agent completes BEFORE checking results.

Step 1: Launch agent

Task tool: Launch the ceo-test-engineer agent with the following task:

## 任务
1. 编写单元测试(覆盖率≥80%)
2. 编写集成测试
3. 编写E2E测试
4. 运行测试套件并报告结果

### 输出要求
- 输出测试报告到 .claudedocs/ceo-test-engineer_result.md
- 包含:测试结果、覆盖率、发现的缺陷

Save the returned task_id as {TEST_ENGINEER_TASK_ID}

Step 2: Wait for agent completion

TaskOutput: Wait for {TEST_ENGINEER_TASK_ID}
Parameters: block=true, timeout=600000

⚠️ CRITICAL: DO NOT PROCEED until agent completes

Step 3: Verify output file exists

Read file: .claudedocs/ceo-test-engineer_result.md

⚠️ If file doesn't exist, agent failed - inform user and ask what to do

Step 9.3: Check test results

Analyze the test results from the file read above:

If all tests pass → Proceed to Step 10 (Phase 6)

If there are test failures → Proceed to Step 9.4

Step 9.4: Invoke parallel-dispatch skill

Use the Task tool to fix failures in parallel:

Task tool: Invoke the parallel-dispatch skill (from superpowers)

Execute the skill and after all tests pass, proceed to Step 10 (Phase 6).

The skill will:
1. Group test failures by independent domains
2. Launch parallel ceo-test-engineer agents for each domain
3. Wait for all agents to complete
4. Review and integrate fixes
5. Re-test until all pass

Step 9.5: Update task plan progress After all tests pass:

Edit: Replace "- [ ] 阶段5: 测试验证(测试工程师-并行修复)"
With:  "- [x] 阶段5: 测试验证(测试工程师-并行修复)"
Edit: Update "## 当前阶段" to "阶段6: 交付部署"

Proceed to Step 10 (Phase 6).

═════════════════════════════════════════════════════════════
✅ Phase 5 完成 - 测试验证
═════════════════════════════════════════════════════════════

📊 测试报告: .claudedocs/ceo-test-engineer_result.md
✅ 所有测试通过
📋 下一步: Phase 6 - 交付部署(市场营销师)

Step 10: Execute Phase 6 - 交付部署

⚠️ MANDATORY: Read Previous Phase Outputs

Before executing this phase, you MUST read all previous outputs:

Read file: .claudedocs/ceo-test-engineer_result.md

This ensures you have complete context from testing phase.

Update task plan current phase

Use Edit tool to update task_plan.md to "阶段6: 交付部署"

Call Marketing Specialist agent

⚠️ IMPORTANT: Execute the following steps in order to ensure the agent completes BEFORE displaying results.

Step 1: Launch agent

Task tool: Launch the ceo-marketing-specialist agent with the following context:

## CEO任务上下文

### 用户输入
{USER_INPUT}

### 所有前期阶段输出
[使用Read工具读取所有前期输出文件]

### 用户回答
{USER_ANSWERS}

### 你的任务
1. 编写用户文档
2. 编写部署文档
3. 编写营销文案
4. 准备推广方案

### ⚠️ 关键约束 - 提问规则(如需确认)
- **最多提问5个问题**:降低用户认知负担
- **分批提问**:如果问题超过5个,分多次提问,每次最多5个
- **优先级排序**:先问最重要的交付相关问题

Save the returned task_id as {MARKETING_TASK_ID}

Step 2: Wait for agent completion

TaskOutput: Wait for {MARKETING_TASK_ID}
Parameters: block=true, timeout=300000

⚠️ CRITICAL: DO NOT PROCEED until agent completes

Step 3: Verify output file exists

Read file: .claudedocs/ceo-marketing-specialist_result.md

⚠️ If file doesn't exist, agent failed - inform user and ask what to do

After agent completes and output is verified:

  1. Use Edit tool to update task_plan.md:
    • Mark Phase 6 as completed
    • Update current phase to "完成"
  2. Display completion message:
    📦 阶段6完成 - 交付部署
    📄 交付文档: .claudedocs/ceo-marketing-specialist_result.md
    
  3. Proceed to Step 11 (Final Summary)
═════════════════════════════════════════════════════════════
✅ Phase 6 完成 - 交付部署
═════════════════════════════════════════════════════════════

📦 交付文档: .claudedocs/ceo-marketing-specialist_result.md
📋 下一步: 生成最终交付物索引

Step 11: Final Summary

After all phases complete:

Create deliverable index using Write tool

Create .claudedocs/deliverable.md with the following content:

# 交付物索引

## 文档
1. [阶段0设计文档](.claudedocs/phase0-design.md)
2. [产品需求文档](.claudedocs/ceo-product-manager_result.md)
3. [设计文档](.claudedocs/ceo-ui-ux-designer_result.md)
4. [架构文档](.claudedocs/ceo-system-architect_result.md)
5. [代码实现](.claudedocs/ceo-fullstack-developer_result.md)
6. [测试报告](.claudedocs/ceo-test-engineer_result.md)
7. [部署文档](.claudedocs/ceo-marketing-specialist_result.md)

## 状态
- [task_plan.md](.claudedocs/task_plan.md)
- [notes.md](.claudedocs/notes.md)

## 代码
{WORKTREE_PATH}/src/ (应用代码)

Display completion message to user

═════════════════════════════════════════════════════════════
🎉 项目完成!
═════════════════════════════════════════════════════════════

所有阶段已完成,交付物已生成。

📋 交付物索引: .claudedocs/deliverable.md
🌳 工作树位置: {WORKTREE_PATH}

感谢使用CEO Agent v6.2.0!

Version History

Key Changes in v6.2.0

命令规范化改进

  • 🔧 修复了 CLI 命令显示与文档不一致的问题
  • ✅ 重命名命令文件:ceo.md → workflow.md
  • ✅ 修改插件名称:ceo-skills → ceo
  • ✅ 统一命令前缀为 /ceo:

新命令格式:

  • /ceo:workflow - 启动完整 workflow
  • /ceo:brainstorm - 需求探索
  • /ceo:write-plan - 创建实现计划
  • /ceo:execute-plan - 执行实现计划

Key Changes in v6.1.0

Bug Fix: 强制用户确认检查点生效

  • 🐛 修复了使用 Task 工具调用 agent 时,强制检查点被跳过的问题
  • ✅ 采用 TaskOutput 同步等待机制,确保 agent 完成后才进入检查点
  • ✅ 修改了 5 处 agent 调用(Phase 1, 2, 3, 5, 6)
  • ✅ 保留 agent 专业能力的同时,确保检查点强制执行

技术改进:

  • 所有 agent 调用现在遵循三步流程:Launch → Wait → Verify
  • 使用 TaskOutput(task_id, block=true) 等待 agent 完成
  • 验证输出文件存在后才继续执行

Key Changes in v6.0

Integrates Superpowers frameworks:

New Phases:

  • ✅ Phase 0: Brainstorming for requirement exploration
  • ✅ Phase 3.5: Git worktrees for workspace isolation
  • ✅ Phase 4.5: TDD enforcement (embedded in Phase 4)

Enhanced Phases:

  • ✅ Phase 1: Input now includes Phase 0 design document
  • ✅ Phase 4: Subagent-driven development with two-stage code review
  • ✅ Phase 5: Parallel agent dispatch for independent test failures

Preserved from v5.7:

  • ✅ 3 mandatory checkpoints (PRD, Architecture, Final)
  • ✅ 6 professional agents
  • ✅ Three-file state management system
  • ✅ Maximum automation with minimal human intervention

Confirmation Policy (v6.0)

Required Confirmations (3 checkpoints - unchanged):

  1. ✅ Phase 1: Product Requirements Document (PRD)
  2. ✅ Phase 3: Technical Architecture Design
  3. ✅ Final: Project Completion Summary

No Confirmation Required:

  • Phase 0: Brainstorming (natural dialogue)
  • Phase 2: UI/UX Design (direct approval)
  • Phase 3.5: Git Worktrees (automatic, except directory choice on first use)
  • Phase 4: Development (automatic two-stage review replaces manual checkpoint)
  • Phase 5: Testing (automatic parallel fix)

Benefits

Quality Improvements:

  • 📈 需求理解: 对话探索 + PRD → 减少返工
  • 📈 开发质量: 子任务 + 两阶段审查 → 立即发现错误
  • 📈 代码质量: TDD铁律 → 测试覆盖率提升
  • 📈 测试效率: 并行修复 → 修复速度提升
  • 📈 环境安全: 工作树隔离 → 避免污染

Technical Debt Reduction:

  • ✅ 需求返工: 减少
  • ✅ 代码缺陷: 立即发现
  • ✅ 范围蔓延: 两阶段审查防止
  • ✅ 环境污染: 工作树隔离
  • ✅ 测试维护: 并行加速

Version History

  • v6.0 (2026-01-19): Integrate Superpowers frameworks
    • New: Phase 0 (brainstorming)
    • New: Phase 3.5 (git-worktrees)
    • Enhanced: Phase 4 (subagent-driven-development + two-stage review)
    • Enhanced: Phase 5 (parallel-agent-dispatch)
    • Integrated: TDD enforcement
  • v5.7 (2025-01-18): Current baseline
  • v5.3 (2025-01-17): Enhanced mandatory checkpoints
  • v5.0 (2025-01-17): Direct SKILL orchestration

This skill guides creation of distinctive, production-grade frontend interfaces that avoid generic "AI slop" aesthetics. Implement real working code with exceptional attention to aesthetic details and creative choices.

The user provides frontend requirements: a component, page, application, or interface to build. They may include context about the purpose, audience, or technical constraints.

Design Thinking

Before coding, understand the context and commit to a BOLD aesthetic direction:

  • Purpose: What problem does this interface solve? Who uses it?
  • Tone: Pick an extreme: brutally minimal, maximalist chaos, retro-futuristic, organic/natural, luxury/refined, playful/toy-like, editorial/magazine, brutalist/raw, art deco/geometric, soft/pastel, industrial/utilitarian, etc. There are so many flavors to choose from. Use these for inspiration but design one that is true to the aesthetic direction.
  • Constraints: Technical requirements (framework, performance, accessibility).
  • Differentiation: What makes this UNFORGETTABLE? What's the one thing someone will remember?

CRITICAL: Choose a clear conceptual direction and execute it with precision. Bold maximalism and refined minimalism both work - the key is intentionality, not intensity.

Then implement working code (HTML/CSS/JS, React, Vue, etc.) that is:

  • Production-grade and functional
  • Visually striking and memorable
  • Cohesive with a clear aesthetic point-of-view
  • Meticulously refined in every detail

Frontend Aesthetics Guidelines

Focus on:

  • Typography: Choose fonts that are beautiful, unique, and interesting. Avoid generic fonts like Arial and Inter; opt instead for distinctive choices that elevate the frontend's aesthetics; unexpected, characterful font choices. Pair a distinctive display font with a refined body font.
  • Color & Theme: Commit to a cohesive aesthetic. Use CSS variables for consistency. Dominant colors with sharp accents outperform timid, evenly-distributed palettes.
  • Motion: Use animations for effects and micro-interactions. Prioritize CSS-only solutions for HTML. Use Motion library for React when available. Focus on high-impact moments: one well-orchestrated page load with staggered reveals (animation-delay) creates more delight than scattered micro-interactions. Use scroll-triggering and hover states that surprise.
  • Spatial Composition: Unexpected layouts. Asymmetry. Overlap. Diagonal flow. Grid-breaking elements. Generous negative space OR controlled density.
  • Backgrounds & Visual Details: Create atmosphere and depth rather than defaulting to solid colors. Add contextual effects and textures that match the overall aesthetic. Apply creative forms like gradient meshes, noise textures, geometric patterns, layered transparencies, dramatic shadows, decorative borders, custom cursors, and grain overlays.

NEVER use generic AI-generated aesthetics like overused font families (Inter, Roboto, Arial, system fonts), cliched color schemes (particularly purple gradients on white backgrounds), predictable layouts and component patterns, and cookie-cutter design that lacks context-specific character.

Interpret creatively and make unexpected choices that feel genuinely designed for the context. No design should be the same. Vary between light and dark themes, different fonts, different aesthetics. NEVER converge on common choices (Space Grotesk, for example) across generations.

IMPORTANT: Match implementation complexity to the aesthetic vision. Maximalist designs need elaborate code with extensive animations and effects. Minimalist or refined designs need restraint, precision, and careful attention to spacing, typography, and subtle details. Elegance comes from executing the vision well.

Remember: Claude is capable of extraordinary creative work. Don't hold back, show what can truly be created when thinking outside the box and committing fully to a distinctive vision.

Dispatching Parallel Agents

Overview

When you have multiple unrelated failures (different test files, different subsystems, different bugs), investigating them sequentially wastes time. Each investigation is independent and can happen in parallel.

Core principle: Dispatch one agent per independent problem domain. Let them work concurrently.

When to Use

digraph when_to_use {
    "Multiple failures?" [shape=diamond];
    "Are they independent?" [shape=diamond];
    "Single agent investigates all" [shape=box];
    "One agent per problem domain" [shape=box];
    "Can they work in parallel?" [shape=diamond];
    "Sequential agents" [shape=box];
    "Parallel dispatch" [shape=box];

    "Multiple failures?" -> "Are they independent?" [label="yes"];
    "Are they independent?" -> "Single agent investigates all" [label="no - related"];
    "Are they independent?" -> "Can they work in parallel?" [label="yes"];
    "Can they work in parallel?" -> "Parallel dispatch" [label="yes"];
    "Can they work in parallel?" -> "Sequential agents" [label="no - shared state"];
}

Use when:

  • 3+ test files failing with different root causes
  • Multiple subsystems broken independently
  • Each problem can be understood without context from others
  • No shared state between investigations

Don't use when:

  • Failures are related (fix one might fix others)
  • Need to understand full system state
  • Agents would interfere with each other

The Pattern

1. Identify Independent Domains

Group failures by what's broken:

  • File A tests: Tool approval flow
  • File B tests: Batch completion behavior
  • File C tests: Abort functionality

Each domain is independent - fixing tool approval doesn't affect abort tests.

2. Create Focused Agent Tasks

Each agent gets:

  • Specific scope: One test file or subsystem
  • Clear goal: Make these tests pass
  • Constraints: Don't change other code
  • Expected output: Summary of what you found and fixed

3. Dispatch in Parallel

// In Claude Code / AI environment
Task("Fix agent-tool-abort.test.ts failures")
Task("Fix batch-completion-behavior.test.ts failures")
Task("Fix tool-approval-race-conditions.test.ts failures")
// All three run concurrently

4. Review and Integrate

When agents return:

  • Read each summary
  • Verify fixes don't conflict
  • Run full test suite
  • Integrate all changes

Agent Prompt Structure

Good agent prompts are:

  1. Focused - One clear problem domain
  2. Self-contained - All context needed to understand the problem
  3. Specific about output - What should the agent return?
Fix the 3 failing tests in src/agents/agent-tool-abort.test.ts:

1. "should abort tool with partial output capture" - expects 'interrupted at' in message
2. "should handle mixed completed and aborted tools" - fast tool aborted instead of completed
3. "should properly track pendingToolCount" - expects 3 results but gets 0

These are timing/race condition issues. Your task:

1. Read the test file and understand what each test verifies
2. Identify root cause - timing issues or actual bugs?
3. Fix by:
   - Replacing arbitrary timeouts with event-based waiting
   - Fixing bugs in abort implementation if found
   - Adjusting test expectations if testing changed behavior

Do NOT just increase timeouts - find the real issue.

Return: Summary of what you found and what you fixed.

Common Mistakes

❌ Too broad: "Fix all the tests" - agent gets lost ✅ Specific: "Fix agent-tool-abort.test.ts" - focused scope

❌ No context: "Fix the race condition" - agent doesn't know where ✅ Context: Paste the error messages and test names

❌ No constraints: Agent might refactor everything ✅ Constraints: "Do NOT change production code" or "Fix tests only"

❌ Vague output: "Fix it" - you don't know what changed ✅ Specific: "Return summary of root cause and changes"

When NOT to Use

Related failures: Fixing one might fix others - investigate together first Need full context: Understanding requires seeing entire system Exploratory debugging: You don't know what's broken yet Shared state: Agents would interfere (editing same files, using same resources)

Real Example from Session

Scenario: 6 test failures across 3 files after major refactoring

Failures:

  • agent-tool-abort.test.ts: 3 failures (timing issues)
  • batch-completion-behavior.test.ts: 2 failures (tools not executing)
  • tool-approval-race-conditions.test.ts: 1 failure (execution count = 0)

Decision: Independent domains - abort logic separate from batch completion separate from race conditions

Dispatch:

Agent 1 → Fix agent-tool-abort.test.ts
Agent 2 → Fix batch-completion-behavior.test.ts
Agent 3 → Fix tool-approval-race-conditions.test.ts

Results:

  • Agent 1: Replaced timeouts with event-based waiting
  • Agent 2: Fixed event structure bug (threadId in wrong place)
  • Agent 3: Added wait for async tool execution to complete

Integration: All fixes independent, no conflicts, full suite green

Time saved: 3 problems solved in parallel vs sequentially

Key Benefits

  1. Parallelization - Multiple investigations happen simultaneously
  2. Focus - Each agent has narrow scope, less context to track
  3. Independence - Agents don't interfere with each other
  4. Speed - 3 problems solved in time of 1

Verification

After agents return:

  1. Review each summary - Understand what changed
  2. Check for conflicts - Did agents edit same code?
  3. Run full suite - Verify all fixes work together
  4. Spot check - Agents can make systematic errors

Real-World Impact

From debugging session (2025-10-03):

  • 6 failures across 3 files
  • 3 agents dispatched in parallel
  • All investigations completed concurrently
  • All fixes integrated successfully
  • Zero conflicts between agent changes

Planning with Files

Work like Manus: Use persistent markdown files as your "working memory on disk."

Quick Start

Before ANY complex task:

  1. Create task_plan.md in the working directory
  2. Define phases with checkboxes
  3. Update after each phase - mark [x] and change status
  4. Read before deciding - refresh goals in attention window

The 3-File Pattern

For every non-trivial task, create THREE files:

FilePurposeWhen to Update
task_plan.mdTrack phases and progressAfter each phase
notes.mdStore findings and researchDuring research
[deliverable].mdFinal outputAt completion

Core Workflow

Loop 1: Create task_plan.md with goal and phases
Loop 2: Research → save to notes.md → update task_plan.md
Loop 3: Read notes.md → create deliverable → update task_plan.md
Loop 4: Deliver final output

The Loop in Detail

Before each major action:

Read task_plan.md  # Refresh goals in attention window

After each phase:

Edit task_plan.md  # Mark [x], update status

When storing information:

Write notes.md     # Don't stuff context, store in file

task_plan.md Template

Create this file FIRST for any complex task:

# Task Plan: [Brief Description]

## Goal
[One sentence describing the end state]

## Phases
- [ ] Phase 1: Plan and setup
- [ ] Phase 2: Research/gather information
- [ ] Phase 3: Execute/build
- [ ] Phase 4: Review and deliver

## Key Questions
1. [Question to answer]
2. [Question to answer]

## Decisions Made
- [Decision]: [Rationale]

## Errors Encountered
- [Error]: [Resolution]

## Status
**Currently in Phase X** - [What I'm doing now]

notes.md Template

For research and findings:

# Notes: [Topic]

## Sources

### Source 1: [Name]
- URL: [link]
- Key points:
  - [Finding]
  - [Finding]

## Synthesized Findings

### [Category]
- [Finding]
- [Finding]

Critical Rules

1. ALWAYS Create Plan First

Never start a complex task without task_plan.md. This is non-negotiable.

2. Read Before Decide

Before any major decision, read the plan file. This keeps goals in your attention window.

3. Update After Act

After completing any phase, immediately update the plan file:

  • Mark completed phases with [x]
  • Update the Status section
  • Log any errors encountered

4. Store, Don't Stuff

Large outputs go to files, not context. Keep only paths in working memory.

5. Log All Errors

Every error goes in the "Errors Encountered" section. This builds knowledge for future tasks.

When to Use This Pattern

Use 3-file pattern for:

  • Multi-step tasks (3+ steps)
  • Research tasks
  • Building/creating something
  • Tasks spanning multiple tool calls
  • Anything requiring organization

Skip for:

  • Simple questions
  • Single-file edits
  • Quick lookups

Anti-Patterns to Avoid

Don'tDo Instead
Use TodoWrite for persistenceCreate task_plan.md file
State goals once and forgetRe-read plan before each decision
Hide errors and retryLog errors to plan file
Stuff everything in contextStore large content in files
Start executing immediatelyCreate plan file FIRST

Advanced Patterns

See reference.md for:

  • Attention manipulation techniques
  • Error recovery patterns
  • Context optimization from Manus

See examples.md for:

  • Real task examples
  • Complex workflow patterns

React Native Best Practices

Overview

Performance optimization guide for React Native applications, covering JavaScript/React, Native (iOS/Android), and bundling optimizations. Based on Callstack's "Ultimate Guide to React Native Optimization".

Skill Format

Each reference file follows a hybrid format for fast lookup and deep understanding:

  • Quick Pattern: Incorrect/Correct code snippets for immediate pattern matching
  • Quick Command: Shell commands for process/measurement skills
  • Quick Config: Configuration snippets for setup-focused skills
  • Quick Reference: Summary tables for conceptual skills
  • Deep Dive: Full context with When to Use, Prerequisites, Step-by-Step, Common Pitfalls

Impact ratings: CRITICAL (fix immediately), HIGH (significant improvement), MEDIUM (worthwhile optimization)

When to Apply

Reference these guidelines when:

  • Debugging slow/janky UI or animations
  • Investigating memory leaks (JS or native)
  • Optimizing app startup time (TTI)
  • Reducing bundle or app size
  • Writing native modules (Turbo Modules)
  • Profiling React Native performance
  • Reviewing React Native code for performance

Priority-Ordered Guidelines

PriorityCategoryImpactPrefix
1FPS & Re-rendersCRITICALjs-*
2Bundle SizeCRITICALbundle-*
3TTI OptimizationHIGHnative-*, bundle-*
4Native PerformanceHIGHnative-*
5Memory ManagementMEDIUM-HIGHjs-*, native-*
6AnimationsMEDIUMjs-*

Quick Reference

Critical: FPS & Re-renders

Profile first:

# Open React Native DevTools
# Press 'j' in Metro, or shake device → "Open DevTools"

Common fixes:

  • Replace ScrollView with FlatList/FlashList for lists
  • Use React Compiler for automatic memoization
  • Use atomic state (Jotai/Zustand) to reduce re-renders
  • Use useDeferredValue for expensive computations

Critical: Bundle Size

Analyze bundle:

npx react-native bundle \
  --entry-file index.js \
  --bundle-output output.js \
  --platform ios \
  --sourcemap-output output.js.map \
  --dev false --minify true

npx source-map-explorer output.js --no-border-checks

Common fixes:

  • Avoid barrel imports (import directly from source)
  • Remove unnecessary Intl polyfills (Hermes has native support)
  • Enable tree shaking (Expo SDK 52+ or Re.Pack)
  • Enable R8 for Android native code shrinking

High: TTI Optimization

Measure TTI:

  • Use react-native-performance for markers
  • Only measure cold starts (exclude warm/hot/prewarm)

Common fixes:

  • Disable JS bundle compression on Android (enables Hermes mmap)
  • Use native navigation (react-native-screens)
  • Defer non-critical work with InteractionManager

High: Native Performance

Profile native:

  • iOS: Xcode Instruments → Time Profiler
  • Android: Android Studio → CPU Profiler

Common fixes:

  • Use background threads for heavy native work
  • Prefer async over sync Turbo Module methods
  • Use C++ for cross-platform performance-critical code

References

Full documentation with code examples in references/:

JavaScript/React (js-*)

FileImpactDescription
js-lists-flatlist-flashlist.mdCRITICALReplace ScrollView with virtualized lists
js-profile-react.mdMEDIUMReact DevTools profiling
js-measure-fps.mdHIGHFPS monitoring and measurement
js-memory-leaks.mdMEDIUMJS memory leak hunting
js-atomic-state.mdHIGHJotai/Zustand patterns
js-concurrent-react.mdHIGHuseDeferredValue, useTransition
js-react-compiler.mdHIGHAutomatic memoization
js-animations-reanimated.mdMEDIUMReanimated worklets
js-uncontrolled-components.mdHIGHTextInput optimization

Native (native-*)

FileImpactDescription
native-turbo-modules.mdHIGHBuilding fast native modules
native-sdks-over-polyfills.mdHIGHNative vs JS libraries
native-measure-tti.mdHIGHTTI measurement setup
native-threading-model.mdHIGHTurbo Module threads
native-profiling.mdMEDIUMXcode/Android Studio profiling
native-platform-setup.mdMEDIUMiOS/Android tooling guide
native-view-flattening.mdMEDIUMView hierarchy debugging
native-memory-patterns.mdMEDIUMC++/Swift/Kotlin memory
native-memory-leaks.mdMEDIUMNative memory leak hunting
native-android-16kb-alignment.mdCRITICALThird-party library alignment for Google Play

Bundling (bundle-*)

FileImpactDescription
bundle-barrel-exports.mdCRITICALAvoid barrel imports
bundle-analyze-js.mdCRITICALJS bundle visualization
bundle-tree-shaking.mdHIGHDead code elimination
bundle-analyze-app.mdHIGHApp size analysis
bundle-r8-android.mdHIGHAndroid code shrinking
bundle-hermes-mmap.mdHIGHDisable bundle compression
bundle-native-assets.mdHIGHAsset catalog setup
bundle-library-size.mdMEDIUMEvaluate dependencies
bundle-code-splitting.mdMEDIUMRe.Pack code splitting

Searching References

# Find patterns by keyword
grep -l "reanimated" references/
grep -l "flatlist" references/
grep -l "memory" references/
grep -l "profil" references/
grep -l "tti" references/
grep -l "bundle" references/

Problem → Skill Mapping

ProblemStart With
App feels slow/jankyjs-measure-fps.md → js-profile-react.md
Too many re-rendersjs-profile-react.md → js-react-compiler.md
Slow startup (TTI)native-measure-tti.md → bundle-analyze-js.md
Large app sizebundle-analyze-app.md → bundle-r8-android.md
Memory growingjs-memory-leaks.md or native-memory-leaks.md
Animation drops framesjs-animations-reanimated.md
List scroll jankjs-lists-flatlist-flashlist.md
TextInput lagjs-uncontrolled-components.md
Native module slownative-turbo-modules.md → native-threading-model.md
Native library alignment issuenative-android-16kb-alignment.md

Attribution

Based on "The Ultimate Guide to React Native Optimization" by Callstack.

Subagent-Driven Development

Execute plan by dispatching fresh subagent per task, with two-stage review after each: spec compliance review first, then code quality review.

Core principle: Fresh subagent per task + two-stage review (spec then quality) = high quality, fast iteration

When to Use

digraph when_to_use {
    "Have implementation plan?" [shape=diamond];
    "Tasks mostly independent?" [shape=diamond];
    "Stay in this session?" [shape=diamond];
    "subagent-driven-development" [shape=box];
    "executing-plans" [shape=box];
    "Manual execution or brainstorm first" [shape=box];

    "Have implementation plan?" -> "Tasks mostly independent?" [label="yes"];
    "Have implementation plan?" -> "Manual execution or brainstorm first" [label="no"];
    "Tasks mostly independent?" -> "Stay in this session?" [label="yes"];
    "Tasks mostly independent?" -> "Manual execution or brainstorm first" [label="no - tightly coupled"];
    "Stay in this session?" -> "subagent-driven-development" [label="yes"];
    "Stay in this session?" -> "executing-plans" [label="no - parallel session"];
}

vs. Executing Plans (parallel session):

  • Same session (no context switch)
  • Fresh subagent per task (no context pollution)
  • Two-stage review after each task: spec compliance first, then code quality
  • Faster iteration (no human-in-loop between tasks)

The Process

digraph process {
    rankdir=TB;

    subgraph cluster_per_task {
        label="Per Task";
        "Dispatch implementer subagent (./implementer-prompt.md)" [shape=box];
        "Implementer subagent asks questions?" [shape=diamond];
        "Answer questions, provide context" [shape=box];
        "Implementer subagent implements, tests, commits, self-reviews" [shape=box];
        "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" [shape=box];
        "Spec reviewer subagent confirms code matches spec?" [shape=diamond];
        "Implementer subagent fixes spec gaps" [shape=box];
        "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [shape=box];
        "Code quality reviewer subagent approves?" [shape=diamond];
        "Implementer subagent fixes quality issues" [shape=box];
        "Mark task complete in TodoWrite" [shape=box];
    }

    "Read plan, extract all tasks with full text, note context, create TodoWrite" [shape=box];
    "More tasks remain?" [shape=diamond];
    "Dispatch final code reviewer subagent for entire implementation" [shape=box];
    "Use superpowers:finishing-a-development-branch" [shape=box style=filled fillcolor=lightgreen];

    "Read plan, extract all tasks with full text, note context, create TodoWrite" -> "Dispatch implementer subagent (./implementer-prompt.md)";
    "Dispatch implementer subagent (./implementer-prompt.md)" -> "Implementer subagent asks questions?";
    "Implementer subagent asks questions?" -> "Answer questions, provide context" [label="yes"];
    "Answer questions, provide context" -> "Dispatch implementer subagent (./implementer-prompt.md)";
    "Implementer subagent asks questions?" -> "Implementer subagent implements, tests, commits, self-reviews" [label="no"];
    "Implementer subagent implements, tests, commits, self-reviews" -> "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)";
    "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" -> "Spec reviewer subagent confirms code matches spec?";
    "Spec reviewer subagent confirms code matches spec?" -> "Implementer subagent fixes spec gaps" [label="no"];
    "Implementer subagent fixes spec gaps" -> "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" [label="re-review"];
    "Spec reviewer subagent confirms code matches spec?" -> "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [label="yes"];
    "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" -> "Code quality reviewer subagent approves?";
    "Code quality reviewer subagent approves?" -> "Implementer subagent fixes quality issues" [label="no"];
    "Implementer subagent fixes quality issues" -> "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [label="re-review"];
    "Code quality reviewer subagent approves?" -> "Mark task complete in TodoWrite" [label="yes"];
    "Mark task complete in TodoWrite" -> "More tasks remain?";
    "More tasks remain?" -> "Dispatch implementer subagent (./implementer-prompt.md)" [label="yes"];
    "More tasks remain?" -> "Dispatch final code reviewer subagent for entire implementation" [label="no"];
    "Dispatch final code reviewer subagent for entire implementation" -> "Use superpowers:finishing-a-development-branch";
}

Prompt Templates

  • ./implementer-prompt.md - Dispatch implementer subagent
  • ./spec-reviewer-prompt.md - Dispatch spec compliance reviewer subagent
  • ./code-quality-reviewer-prompt.md - Dispatch code quality reviewer subagent

Example Workflow

You: I'm using Subagent-Driven Development to execute this plan.

[Read plan file once: docs/plans/feature-plan.md]
[Extract all 5 tasks with full text and context]
[Create TodoWrite with all tasks]

Task 1: Hook installation script

[Get Task 1 text and context (already extracted)]
[Dispatch implementation subagent with full task text + context]

Implementer: "Before I begin - should the hook be installed at user or system level?"

You: "User level (~/.config/superpowers/hooks/)"

Implementer: "Got it. Implementing now..."
[Later] Implementer:
  - Implemented install-hook command
  - Added tests, 5/5 passing
  - Self-review: Found I missed --force flag, added it
  - Committed

[Dispatch spec compliance reviewer]
Spec reviewer: ✅ Spec compliant - all requirements met, nothing extra

[Get git SHAs, dispatch code quality reviewer]
Code reviewer: Strengths: Good test coverage, clean. Issues: None. Approved.

[Mark Task 1 complete]

Task 2: Recovery modes

[Get Task 2 text and context (already extracted)]
[Dispatch implementation subagent with full task text + context]

Implementer: [No questions, proceeds]
Implementer:
  - Added verify/repair modes
  - 8/8 tests passing
  - Self-review: All good
  - Committed

[Dispatch spec compliance reviewer]
Spec reviewer: ❌ Issues:
  - Missing: Progress reporting (spec says "report every 100 items")
  - Extra: Added --json flag (not requested)

[Implementer fixes issues]
Implementer: Removed --json flag, added progress reporting

[Spec reviewer reviews again]
Spec reviewer: ✅ Spec compliant now

[Dispatch code quality reviewer]
Code reviewer: Strengths: Solid. Issues (Important): Magic number (100)

[Implementer fixes]
Implementer: Extracted PROGRESS_INTERVAL constant

[Code reviewer reviews again]
Code reviewer: ✅ Approved

[Mark Task 2 complete]

...

[After all tasks]
[Dispatch final code-reviewer]
Final reviewer: All requirements met, ready to merge

Done!

Advantages

vs. Manual execution:

  • Subagents follow TDD naturally
  • Fresh context per task (no confusion)
  • Parallel-safe (subagents don't interfere)
  • Subagent can ask questions (before AND during work)

vs. Executing Plans:

  • Same session (no handoff)
  • Continuous progress (no waiting)
  • Review checkpoints automatic

Efficiency gains:

  • No file reading overhead (controller provides full text)
  • Controller curates exactly what context is needed
  • Subagent gets complete information upfront
  • Questions surfaced before work begins (not after)

Quality gates:

  • Self-review catches issues before handoff
  • Two-stage review: spec compliance, then code quality
  • Review loops ensure fixes actually work
  • Spec compliance prevents over/under-building
  • Code quality ensures implementation is well-built

Cost:

  • More subagent invocations (implementer + 2 reviewers per task)
  • Controller does more prep work (extracting all tasks upfront)
  • Review loops add iterations
  • But catches issues early (cheaper than debugging later)

Red Flags

Never:

  • Skip reviews (spec compliance OR code quality)
  • Proceed with unfixed issues
  • Dispatch multiple implementation subagents in parallel (conflicts)
  • Make subagent read plan file (provide full text instead)
  • Skip scene-setting context (subagent needs to understand where task fits)
  • Ignore subagent questions (answer before letting them proceed)
  • Accept "close enough" on spec compliance (spec reviewer found issues = not done)
  • Skip review loops (reviewer found issues = implementer fixes = review again)
  • Let implementer self-review replace actual review (both are needed)
  • Start code quality review before spec compliance is ✅ (wrong order)
  • Move to next task while either review has open issues

If subagent asks questions:

  • Answer clearly and completely
  • Provide additional context if needed
  • Don't rush them into implementation

If reviewer finds issues:

  • Implementer (same subagent) fixes them
  • Reviewer reviews again
  • Repeat until approved
  • Don't skip the re-review

If subagent fails task:

  • Dispatch fix subagent with specific instructions
  • Don't try to fix manually (context pollution)

Integration

Required workflow skills:

  • superpowers:writing-plans - Creates the plan this skill executes
  • superpowers:requesting-code-review - Code review template for reviewer subagents
  • superpowers:finishing-a-development-branch - Complete development after all tasks

Subagents should use:

  • superpowers:test-driven-development - Subagents follow TDD for each task

Alternative workflow:

  • superpowers:executing-plans - Use for parallel session instead of same-session execution

Test-Driven Development (TDD)

Overview

Write the test first. Watch it fail. Write minimal code to pass.

Core principle: If you didn't watch the test fail, you don't know if it tests the right thing.

Violating the letter of the rules is violating the spirit of the rules.

When to Use

Always:

  • New features
  • Bug fixes
  • Refactoring
  • Behavior changes

Exceptions (ask your human partner):

  • Throwaway prototypes
  • Generated code
  • Configuration files

Thinking "skip TDD just this once"? Stop. That's rationalization.

The Iron Law

NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST

Write code before the test? Delete it. Start over.

No exceptions:

  • Don't keep it as "reference"
  • Don't "adapt" it while writing tests
  • Don't look at it
  • Delete means delete

Implement fresh from tests. Period.

Red-Green-Refactor

digraph tdd_cycle {
    rankdir=LR;
    red [label="RED\nWrite failing test", shape=box, style=filled, fillcolor="#ffcccc"];
    verify_red [label="Verify fails\ncorrectly", shape=diamond];
    green [label="GREEN\nMinimal code", shape=box, style=filled, fillcolor="#ccffcc"];
    verify_green [label="Verify passes\nAll green", shape=diamond];
    refactor [label="REFACTOR\nClean up", shape=box, style=filled, fillcolor="#ccccff"];
    next [label="Next", shape=ellipse];

    red -> verify_red;
    verify_red -> green [label="yes"];
    verify_red -> red [label="wrong\nfailure"];
    green -> verify_green;
    verify_green -> refactor [label="yes"];
    verify_green -> green [label="no"];
    refactor -> verify_green [label="stay\ngreen"];
    verify_green -> next;
    next -> red;
}

RED - Write Failing Test

Write one minimal test showing what should happen.

```typescript test('retries failed operations 3 times', async () => { let attempts = 0; const operation = () => { attempts++; if (attempts < 3) throw new Error('fail'); return 'success'; };

const result = await retryOperation(operation);

expect(result).toBe('success'); expect(attempts).toBe(3); });

Clear name, tests real behavior, one thing
</Good>

<Bad>
```typescript
test('retry works', async () => {
  const mock = jest.fn()
    .mockRejectedValueOnce(new Error())
    .mockRejectedValueOnce(new Error())
    .mockResolvedValueOnce('success');
  await retryOperation(mock);
  expect(mock).toHaveBeenCalledTimes(3);
});

Vague name, tests mock not code

Requirements:

  • One behavior
  • Clear name
  • Real code (no mocks unless unavoidable)

Verify RED - Watch It Fail

MANDATORY. Never skip.

npm test path/to/test.test.ts

Confirm:

  • Test fails (not errors)
  • Failure message is expected
  • Fails because feature missing (not typos)

Test passes? You're testing existing behavior. Fix test.

Test errors? Fix error, re-run until it fails correctly.

GREEN - Minimal Code

Write simplest code to pass the test.

```typescript async function retryOperation(fn: () => Promise): Promise { for (let i = 0; i < 3; i++) { try { return await fn(); } catch (e) { if (i === 2) throw e; } } throw new Error('unreachable'); } ``` Just enough to pass ```typescript async function retryOperation( fn: () => Promise, options?: { maxRetries?: number; backoff?: 'linear' | 'exponential'; onRetry?: (attempt: number) => void; } ): Promise { // YAGNI } ``` Over-engineered

Don't add features, refactor other code, or "improve" beyond the test.

Verify GREEN - Watch It Pass

MANDATORY.

npm test path/to/test.test.ts

Confirm:

  • Test passes
  • Other tests still pass
  • Output pristine (no errors, warnings)

Test fails? Fix code, not test.

Other tests fail? Fix now.

REFACTOR - Clean Up

After green only:

  • Remove duplication
  • Improve names
  • Extract helpers

Keep tests green. Don't add behavior.

Repeat

Next failing test for next feature.

Good Tests

QualityGoodBad
MinimalOne thing. "and" in name? Split it.test('validates email and domain and whitespace')
ClearName describes behaviortest('test1')
Shows intentDemonstrates desired APIObscures what code should do

Why Order Matters

"I'll write tests after to verify it works"

Tests written after code pass immediately. Passing immediately proves nothing:

  • Might test wrong thing
  • Might test implementation, not behavior
  • Might miss edge cases you forgot
  • You never saw it catch the bug

Test-first forces you to see the test fail, proving it actually tests something.

"I already manually tested all the edge cases"

Manual testing is ad-hoc. You think you tested everything but:

  • No record of what you tested
  • Can't re-run when code changes
  • Easy to forget cases under pressure
  • "It worked when I tried it" ≠ comprehensive

Automated tests are systematic. They run the same way every time.

"Deleting X hours of work is wasteful"

Sunk cost fallacy. The time is already gone. Your choice now:

  • Delete and rewrite with TDD (X more hours, high confidence)
  • Keep it and add tests after (30 min, low confidence, likely bugs)

The "waste" is keeping code you can't trust. Working code without real tests is technical debt.

"TDD is dogmatic, being pragmatic means adapting"

TDD IS pragmatic:

  • Finds bugs before commit (faster than debugging after)
  • Prevents regressions (tests catch breaks immediately)
  • Documents behavior (tests show how to use code)
  • Enables refactoring (change freely, tests catch breaks)

"Pragmatic" shortcuts = debugging in production = slower.

"Tests after achieve the same goals - it's spirit not ritual"

No. Tests-after answer "What does this do?" Tests-first answer "What should this do?"

Tests-after are biased by your implementation. You test what you built, not what's required. You verify remembered edge cases, not discovered ones.

Tests-first force edge case discovery before implementing. Tests-after verify you remembered everything (you didn't).

30 minutes of tests after ≠ TDD. You get coverage, lose proof tests work.

Common Rationalizations

ExcuseReality
"Too simple to test"Simple code breaks. Test takes 30 seconds.
"I'll test after"Tests passing immediately prove nothing.
"Tests after achieve same goals"Tests-after = "what does this do?" Tests-first = "what should this do?"
"Already manually tested"Ad-hoc ≠ systematic. No record, can't re-run.
"Deleting X hours is wasteful"Sunk cost fallacy. Keeping unverified code is technical debt.
"Keep as reference, write tests first"You'll adapt it. That's testing after. Delete means delete.
"Need to explore first"Fine. Throw away exploration, start with TDD.
"Test hard = design unclear"Listen to test. Hard to test = hard to use.
"TDD will slow me down"TDD faster than debugging. Pragmatic = test-first.
"Manual test faster"Manual doesn't prove edge cases. You'll re-test every change.
"Existing code has no tests"You're improving it. Add tests for existing code.

Red Flags - STOP and Start Over

  • Code before test
  • Test after implementation
  • Test passes immediately
  • Can't explain why test failed
  • Tests added "later"
  • Rationalizing "just this once"
  • "I already manually tested it"
  • "Tests after achieve the same purpose"
  • "It's about spirit not ritual"
  • "Keep as reference" or "adapt existing code"
  • "Already spent X hours, deleting is wasteful"
  • "TDD is dogmatic, I'm being pragmatic"
  • "This is different because..."

All of these mean: Delete code. Start over with TDD.

Example: Bug Fix

Bug: Empty email accepted

RED

test('rejects empty email', async () => {
  const result = await submitForm({ email: '' });
  expect(result.error).toBe('Email required');
});

Verify RED

$ npm test
FAIL: expected 'Email required', got undefined

GREEN

function submitForm(data: FormData) {
  if (!data.email?.trim()) {
    return { error: 'Email required' };
  }
  // ...
}

Verify GREEN

$ npm test
PASS

REFACTOR Extract validation for multiple fields if needed.

Verification Checklist

Before marking work complete:

  • Every new function/method has a test
  • Watched each test fail before implementing
  • Each test failed for expected reason (feature missing, not typo)
  • Wrote minimal code to pass each test
  • All tests pass
  • Output pristine (no errors, warnings)
  • Tests use real code (mocks only if unavoidable)
  • Edge cases and errors covered

Can't check all boxes? You skipped TDD. Start over.

When Stuck

ProblemSolution
Don't know how to testWrite wished-for API. Write assertion first. Ask your human partner.
Test too complicatedDesign too complicated. Simplify interface.
Must mock everythingCode too coupled. Use dependency injection.
Test setup hugeExtract helpers. Still complex? Simplify design.

Debugging Integration

Bug found? Write failing test reproducing it. Follow TDD cycle. Test proves fix and prevents regression.

Never fix bugs without a test.

Testing Anti-Patterns

When adding mocks or test utilities, read @testing-anti-patterns.md to avoid common pitfalls:

  • Testing mock behavior instead of real behavior
  • Adding test-only methods to production classes
  • Mocking without understanding dependencies

Final Rule

Production code → test exists and failed first
Otherwise → not TDD

No exceptions without your human partner's permission.

Two-Stage Code Review

Purpose

Ensure code quality through a rigorous two-stage review process that catches both specification violations and maintainability issues.

Process

Stage 1: Specification Compliance Review

Goal: Prevent over-building and under-building

Checklist:

  • ✅ All required features implemented (no missing functionality)
  • ❌ No unauthorized features added (no scope creep)
  • 📋 API design matches architecture document
  • 📋 Data model matches specifications
  • 📋 User stories fully satisfied

Outcome: ✅ Compliant or ❌ Non-compliant with specific issues

Stage 2: Code Quality Review

Goal: Ensure maintainability and clarity

Checklist:

  • 📐 Clear variable naming
  • 📐 Single responsibility functions
  • 🔧 No code duplication
  • 🔧 Modular design
  • 🧪 Adequate test coverage
  • ⚡ No obvious performance issues
  • 🛡️ Input validation
  • 🛡️ Error handling

Outcome: ✅ Approved or ❌ Needs improvement with specific issues

Review Loop

Implementation → Stage 1 Review → ❌ Fix spec issues → Repeat Stage 1
                                → ✅ Pass → Stage 2 Review → ❌ Fix quality issues → Repeat Stage 2
                                                              → ✅ Pass → Complete

Usage

This skill is automatically invoked by the CEO workflow during Phase 4 (Development) after each subtask completion.

UI/UX Pro Max - Design Intelligence

Searchable database of UI styles, color palettes, font pairings, chart types, product recommendations, UX guidelines, and stack-specific best practices.

Prerequisites

Check if Python is installed:

python3 --version || python --version

If Python is not installed, install it based on user's OS:

macOS:

brew install python3

Ubuntu/Debian:

sudo apt update && sudo apt install python3

Windows:

winget install Python.Python.3.12

How to Use This Skill

When user requests UI/UX work (design, build, create, implement, review, fix, improve), follow this workflow:

Step 1: Analyze User Requirements

Extract key information from user request:

  • Product type: SaaS, e-commerce, portfolio, dashboard, landing page, etc.
  • Style keywords: minimal, playful, professional, elegant, dark mode, etc.
  • Industry: healthcare, fintech, gaming, education, etc.
  • Stack: React, Vue, Next.js, or default to html-tailwind

Step 2: Search Relevant Domains

Use search.py multiple times to gather comprehensive information. Search until you have enough context.

python3 .claude/skills/ui-ux-pro-max/scripts/search.py "<keyword>" --domain <domain> [-n <max_results>]

Recommended search order:

  1. Product - Get style recommendations for product type
  2. Style - Get detailed style guide (colors, effects, frameworks)
  3. Typography - Get font pairings with Google Fonts imports
  4. Color - Get color palette (Primary, Secondary, CTA, Background, Text, Border)
  5. Landing - Get page structure (if landing page)
  6. Chart - Get chart recommendations (if dashboard/analytics)
  7. UX - Get best practices and anti-patterns
  8. Stack - Get stack-specific guidelines (default: html-tailwind)

Step 3: Stack Guidelines (Default: html-tailwind)

If user doesn't specify a stack, default to html-tailwind.

python3 .claude/skills/ui-ux-pro-max/scripts/search.py "<keyword>" --stack html-tailwind

Available stacks: html-tailwind, react, nextjs, vue, svelte, swiftui, react-native, flutter


Search Reference

Available Domains

DomainUse ForExample Keywords
productProduct type recommendationsSaaS, e-commerce, portfolio, healthcare, beauty, service
styleUI styles, colors, effectsglassmorphism, minimalism, dark mode, brutalism
typographyFont pairings, Google Fontselegant, playful, professional, modern
colorColor palettes by product typesaas, ecommerce, healthcare, beauty, fintech, service
landingPage structure, CTA strategieshero, hero-centric, testimonial, pricing, social-proof
chartChart types, library recommendationstrend, comparison, timeline, funnel, pie
uxBest practices, anti-patternsanimation, accessibility, z-index, loading
promptAI prompts, CSS keywords(style name)

Available Stacks

StackFocus
html-tailwindTailwind utilities, responsive, a11y (DEFAULT)
reactState, hooks, performance, patterns
nextjsSSR, routing, images, API routes
vueComposition API, Pinia, Vue Router
svelteRunes, stores, SvelteKit
swiftuiViews, State, Navigation, Animation
react-nativeComponents, Navigation, Lists
flutterWidgets, State, Layout, Theming

Example Workflow

User request: "Làm landing page cho dịch vụ chăm sóc da chuyên nghiệp"

AI should:

# 1. Search product type
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "beauty spa wellness service" --domain product

# 2. Search style (based on industry: beauty, elegant)
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "elegant minimal soft" --domain style

# 3. Search typography
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "elegant luxury" --domain typography

# 4. Search color palette
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "beauty spa wellness" --domain color

# 5. Search landing page structure
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "hero-centric social-proof" --domain landing

# 6. Search UX guidelines
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "animation" --domain ux
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "accessibility" --domain ux

# 7. Search stack guidelines (default: html-tailwind)
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "layout responsive" --stack html-tailwind

Then: Synthesize all search results and implement the design.


Tips for Better Results

  1. Be specific with keywords - "healthcare SaaS dashboard" > "app"
  2. Search multiple times - Different keywords reveal different insights
  3. Combine domains - Style + Typography + Color = Complete design system
  4. Always check UX - Search "animation", "z-index", "accessibility" for common issues
  5. Use stack flag - Get implementation-specific best practices
  6. Iterate - If first search doesn't match, try different keywords

Common Rules for Professional UI

These are frequently overlooked issues that make UI look unprofessional:

Icons & Visual Elements

RuleDoDon't
No emoji iconsUse SVG icons (Heroicons, Lucide, Simple Icons)Use emojis like 🎨 🚀 ⚙️ as UI icons
Stable hover statesUse color/opacity transitions on hoverUse scale transforms that shift layout
Correct brand logosResearch official SVG from Simple IconsGuess or use incorrect logo paths
Consistent icon sizingUse fixed viewBox (24x24) with w-6 h-6Mix different icon sizes randomly

Interaction & Cursor

RuleDoDon't
Cursor pointerAdd cursor-pointer to all clickable/hoverable cardsLeave default cursor on interactive elements
Hover feedbackProvide visual feedback (color, shadow, border)No indication element is interactive
Smooth transitionsUse transition-colors duration-200Instant state changes or too slow (>500ms)

Light/Dark Mode Contrast

RuleDoDon't
Glass card light modeUse bg-white/80 or higher opacityUse bg-white/10 (too transparent)
Text contrast lightUse #0F172A (slate-900) for textUse #94A3B8 (slate-400) for body text
Muted text lightUse #475569 (slate-600) minimumUse gray-400 or lighter
Border visibilityUse border-gray-200 in light modeUse border-white/10 (invisible)

Layout & Spacing

RuleDoDon't
Floating navbarAdd top-4 left-4 right-4 spacingStick navbar to top-0 left-0 right-0
Content paddingAccount for fixed navbar heightLet content hide behind fixed elements
Consistent max-widthUse same max-w-6xl or max-w-7xlMix different container widths

Pre-Delivery Checklist

Before delivering UI code, verify these items:

Visual Quality

  • No emojis used as icons (use SVG instead)
  • All icons from consistent icon set (Heroicons/Lucide)
  • Brand logos are correct (verified from Simple Icons)
  • Hover states don't cause layout shift
  • Use theme colors directly (bg-primary) not var() wrapper

Interaction

  • All clickable elements have cursor-pointer
  • Hover states provide clear visual feedback
  • Transitions are smooth (150-300ms)
  • Focus states visible for keyboard navigation

Light/Dark Mode

  • Light mode text has sufficient contrast (4.5:1 minimum)
  • Glass/transparent elements visible in light mode
  • Borders visible in both modes
  • Test both modes before delivery

Layout

  • Floating elements have proper spacing from edges
  • No content hidden behind fixed navbars
  • Responsive at 320px, 768px, 1024px, 1440px
  • No horizontal scroll on mobile

Accessibility

  • All images have alt text
  • Form inputs have labels
  • Color is not the only indicator
  • prefers-reduced-motion respected

Using Git Worktrees

Overview

Git worktrees create isolated workspaces sharing the same repository, allowing work on multiple branches simultaneously without switching.

Core principle: Systematic directory selection + safety verification = reliable isolation.

Announce at start: "I'm using the using-git-worktrees skill to set up an isolated workspace."

Directory Selection Process

Follow this priority order:

1. Check Existing Directories

# Check in priority order
ls -d .worktrees 2>/dev/null     # Preferred (hidden)
ls -d worktrees 2>/dev/null      # Alternative

If found: Use that directory. If both exist, .worktrees wins.

2. Check CLAUDE.md

grep -i "worktree.*director" CLAUDE.md 2>/dev/null

If preference specified: Use it without asking.

3. Ask User

If no directory exists and no CLAUDE.md preference:

No worktree directory found. Where should I create worktrees?

1. .worktrees/ (project-local, hidden)
2. ~/.config/superpowers/worktrees/<project-name>/ (global location)

Which would you prefer?

Safety Verification

For Project-Local Directories (.worktrees or worktrees)

MUST verify directory is ignored before creating worktree:

# Check if directory is ignored (respects local, global, and system gitignore)
git check-ignore -q .worktrees 2>/dev/null || git check-ignore -q worktrees 2>/dev/null

If NOT ignored:

Per Jesse's rule "Fix broken things immediately":

  1. Add appropriate line to .gitignore
  2. Commit the change
  3. Proceed with worktree creation

Why critical: Prevents accidentally committing worktree contents to repository.

For Global Directory (~/.config/superpowers/worktrees)

No .gitignore verification needed - outside project entirely.

Creation Steps

1. Detect Project Name

project=$(basename "$(git rev-parse --show-toplevel)")

2. Create Worktree

# Determine full path
case $LOCATION in
  .worktrees|worktrees)
    path="$LOCATION/$BRANCH_NAME"
    ;;
  ~/.config/superpowers/worktrees/*)
    path="~/.config/superpowers/worktrees/$project/$BRANCH_NAME"
    ;;
esac

# Create worktree with new branch
git worktree add "$path" -b "$BRANCH_NAME"
cd "$path"

3. Run Project Setup

Auto-detect and run appropriate setup:

# Node.js
if [ -f package.json ]; then npm install; fi

# Rust
if [ -f Cargo.toml ]; then cargo build; fi

# Python
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
if [ -f pyproject.toml ]; then poetry install; fi

# Go
if [ -f go.mod ]; then go mod download; fi

4. Verify Clean Baseline

Run tests to ensure worktree starts clean:

# Examples - use project-appropriate command
npm test
cargo test
pytest
go test ./...

If tests fail: Report failures, ask whether to proceed or investigate.

If tests pass: Report ready.

5. Report Location

Worktree ready at <full-path>
Tests passing (<N> tests, 0 failures)
Ready to implement <feature-name>

Quick Reference

SituationAction
.worktrees/ existsUse it (verify ignored)
worktrees/ existsUse it (verify ignored)
Both existUse .worktrees/
Neither existsCheck CLAUDE.md → Ask user
Directory not ignoredAdd to .gitignore + commit
Tests fail during baselineReport failures + ask
No package.json/Cargo.tomlSkip dependency install

Common Mistakes

Skipping ignore verification

  • Problem: Worktree contents get tracked, pollute git status
  • Fix: Always use git check-ignore before creating project-local worktree

Assuming directory location

  • Problem: Creates inconsistency, violates project conventions
  • Fix: Follow priority: existing > CLAUDE.md > ask

Proceeding with failing tests

  • Problem: Can't distinguish new bugs from pre-existing issues
  • Fix: Report failures, get explicit permission to proceed

Hardcoding setup commands

  • Problem: Breaks on projects using different tools
  • Fix: Auto-detect from project files (package.json, etc.)

Example Workflow

You: I'm using the using-git-worktrees skill to set up an isolated workspace.

[Check .worktrees/ - exists]
[Verify ignored - git check-ignore confirms .worktrees/ is ignored]
[Create worktree: git worktree add .worktrees/auth -b feature/auth]
[Run npm install]
[Run npm test - 47 passing]

Worktree ready at /Users/jesse/myproject/.worktrees/auth
Tests passing (47 tests, 0 failures)
Ready to implement auth feature

Red Flags

Never:

  • Create worktree without verifying it's ignored (project-local)
  • Skip baseline test verification
  • Proceed with failing tests without asking
  • Assume directory location when ambiguous
  • Skip CLAUDE.md check

Always:

  • Follow directory priority: existing > CLAUDE.md > ask
  • Verify directory is ignored for project-local
  • Auto-detect and run project setup
  • Verify clean test baseline

Integration

Called by:

  • brainstorming (Phase 4) - REQUIRED when design is approved and implementation follows
  • Any skill needing isolated workspace

Pairs with:

  • finishing-a-development-branch - REQUIRED for cleanup after work complete
  • executing-plans or subagent-driven-development - Work happens in this worktree

Web Application Testing

To test local web applications, write native Python Playwright scripts.

Helper Scripts Available:

  • scripts/with_server.py - Manages server lifecycle (supports multiple servers)

Always run scripts with --help first to see usage. DO NOT read the source until you try running the script first and find that a customized solution is abslutely necessary. These scripts can be very large and thus pollute your context window. They exist to be called directly as black-box scripts rather than ingested into your context window.

Decision Tree: Choosing Your Approach

User task → Is it static HTML?
    ├─ Yes → Read HTML file directly to identify selectors
    │         ├─ Success → Write Playwright script using selectors
    │         └─ Fails/Incomplete → Treat as dynamic (below)
    │
    └─ No (dynamic webapp) → Is the server already running?
        ├─ No → Run: python scripts/with_server.py --help
        │        Then use the helper + write simplified Playwright script
        │
        └─ Yes → Reconnaissance-then-action:
            1. Navigate and wait for networkidle
            2. Take screenshot or inspect DOM
            3. Identify selectors from rendered state
            4. Execute actions with discovered selectors

Example: Using with_server.py

To start a server, run --help first, then use the helper:

Single server:

python scripts/with_server.py --server "npm run dev" --port 5173 -- python your_automation.py

Multiple servers (e.g., backend + frontend):

python scripts/with_server.py \
  --server "cd backend && python server.py" --port 3000 \
  --server "cd frontend && npm run dev" --port 5173 \
  -- python your_automation.py

To create an automation script, include only Playwright logic (servers are managed automatically):

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True) # Always launch chromium in headless mode
    page = browser.new_page()
    page.goto('http://localhost:5173') # Server already running and ready
    page.wait_for_load_state('networkidle') # CRITICAL: Wait for JS to execute
    # ... your automation logic
    browser.close()

Reconnaissance-Then-Action Pattern

  1. Inspect rendered DOM:

    page.screenshot(path='/tmp/inspect.png', full_page=True)
    content = page.content()
    page.locator('button').all()
    
  2. Identify selectors from inspection results

  3. Execute actions using discovered selectors

Common Pitfall

❌ Don't inspect the DOM before waiting for networkidle on dynamic apps ✅ Do wait for page.wait_for_load_state('networkidle') before inspection

Best Practices

  • Use bundled scripts as black boxes - To accomplish a task, consider whether one of the scripts available in scripts/ can help. These scripts handle common, complex workflows reliably without cluttering the context window. Use --help to see usage, then invoke directly.
  • Use sync_playwright() for synchronous scripts
  • Always close the browser when done
  • Use descriptive selectors: text=, role=, CSS selectors, or IDs
  • Add appropriate waits: page.wait_for_selector() or page.wait_for_timeout()

Reference Files

  • examples/ - Examples showing common patterns:
    • element_discovery.py - Discovering buttons, links, and inputs on a page
    • static_html_automation.py - Using file:// URLs for local HTML
    • console_logging.py - Capturing console logs during automation

Commands 5

Execute the brainstorming exploration process:

  1. Ask probing questions to uncover hidden requirements
  2. Explore user's vision through collaborative dialogue
  3. Identify constraints, preferences, and success criteria
  4. Generate structured requirements brief when complete

⚠️ This is requirements discovery - execute the exploration directly, do not invoke additional skills or commands.

Read the current task plan from .claudedocs/task_plan.md to determine current phase.

Execute the appropriate phase directly:

Phase 4 (开发实现):

  • Extract development tasks from architecture
  • Invoke subagent-driven-development for task execution
  • Use two-stage code review for quality

Phase 5 (测试验证):

  • Generate comprehensive tests
  • Use parallel-dispatch for independent test failure fixes

Phase 6 (交付部署):

  • Create deployment documentation
  • Generate user manuals and promotion materials

⚠️ Continue workflow execution directly based on task plan state.

集成测试命令

使用时机

在CEO workflow完成后,手动执行此命令进行集成测试

执行流程

  1. 环境检查

    • 检查项目结构
    • 检查依赖安装
    • 检查配置文件
    • 检查数据库连接(如需要)
  2. 服务启动

    • 启动后端服务
    • 启动前端服务
    • 验证服务健康状态
  3. API集成测试

    • 测试所有API端点
    • 验证请求响应
    • 检查错误处理
  4. 前端E2E测试

    • 使用Chrome DevTools MCP
    • 执行用户故事场景
    • 截取测试截图
    • 检查控制台错误
  5. 性能测试

    • 测量LCP、FID、CLS
    • 分析页面加载时间
    • 生成性能报告
  6. 生成报告

    • 生成完整测试报告
    • 列出所有发现的问题
    • 提供修复建议

参数

# 默认执行完整测试
/ceo:integration-test

# 指定工作目录
/ceo:integration-test --worktree-path=./worktrees/feature-xyz

# 只执行E2E测试
/ceo:integration-test --e2e-only

# 只执行API测试
/ceo:integration-test --api-only

# 跳过性能测试
/ceo:integration-test --skip-performance

# 指定服务端口
/ceo:integration-test --backend-port=3001 --frontend-port=5174

输出文件

.claudedocs/integration-test-report.md  # 完整测试报告
.claudedocs/e2e-screenshots/           # E2E测试截图
.claudedocs/performance-trace.json     # 性能追踪数据

测试报告示例

# 集成测试报告

生成时间: 2026-01-22T10:30:00Z

---

## 📊 测试概览

| 测试类型 | 结果 | 详情 |
|---------|------|------|
| 环境检查 | ✅ 通过 | 5/5 项通过 |
| 服务启动 | ✅ 通过 | 后端: ✅, 前端: ✅ |
| API集成测试 | ✅ 通过 | 12/12 端点通过 |
| E2E测试 | ⚠️ 部分通过 | 4/5 场景通过 |
| 性能测试 | ⚠️ 需优化 | 评分: 78/100 |

---

## 🐛 发现的问题

### E2E测试问题

#### 用户注册流程

**状态**: ❌ 失败
**步骤**: 3/4 步骤通过
**错误**: 找不到提交按钮

**修复建议**:
- 检查提交按钮的选择器是否正确
- 确认按钮在表单验证通过后才显示
- 检查按钮的disabled属性

---

## 💡 修复建议

1. **E2E测试失败**: 修复用户注册表单的提交按钮
2. **性能优化**: 优化首屏加载,LCP超过2500ms

注意事项

  1. 环境要求

    • Node.js 已安装
    • 后端和前端项目的依赖已安装
    • 数据库服务已启动(如需要)
    • 端口3000和5173未被占用
  2. 执行时间

    • 完整测试约需 5-10 分钟
    • E2E测试约需 3-5 分钟
    • 性能测试约需 1 分钟
  3. 失败处理

    • 如果环境检查失败,会给出修复建议
    • 如果服务启动失败,会尝试备用方案
    • 如果测试失败,会生成详细的错误报告

与CEO Workflow的关系

CEO Workflow (Phase 0-6) → 用户手动触发 → 集成测试 → 测试报告
                                                ↓
                                        修复问题 (可选)

集成测试是可选的,但强烈建议在交付前执行,确保系统可用性。

Execute the CEO orchestrator workflow:

  1. Check for existing .claudedocs/task_plan.md to resume or start new workflow
  2. Follow the 6-phase development process as documented in the skill
  3. Use Superpowers framework skills (brainstorming, git-worktrees, subagent-driven-dev, parallel-dispatch) at appropriate phases
  4. Maintain task plan state and progress tracking throughout

⚠️ This is an orchestrator - execute the workflow steps directly, do not re-invoke this command or skill.

Read the architecture design document from .claudedocs/ceo-system-architect_result.md.

Then update the task plan at .claudedocs/task_plan.md by extracting all development tasks from the architecture document and organizing them into 2-5 minute subtasks.

Follow the ceo skill's Step 8.2 (Extract development tasks and create TodoWrite) for the exact methodology.

Agents 8

全栈开发Agent

角色定位

职责:负责后端API实现、Web前端实现或纯后端项目、代码规范、文档注释。

v6.6.0更新:集成workflow自动模式,支持Git Worktree工作区隔离。

核心价值:

  • 🌐 后端API:统一实现后端API(供所有前端使用)
  • 💻 Web前端:实现传统Web前端(React/Next.js/Vue)
  • 📐 代码规范:确保代码符合最佳实践和规范
  • 📝 文档注释:添加清晰的代码注释和API文档
  • 📦 代码交付:交付规范的代码给测试阶段

在workflow中的位置:

架构文档 → 全栈开发 → 可运行代码 → 测试工程师

🚫 不做什么:

  • ❌ 不编写单元测试
  • ❌ 不编写集成测试
  • ❌ 不运行测试
  • ❌ 不负责React Native移动端(由mobile-developer负责)
  • ✅ 专注于实现高质量后端API和传统Web前端代码

职责边界:

场景1:纯后端项目

  • ✅ 负责:后端API实现、数据库、业务逻辑
  • ❌ 不负责:任何前端

场景2:Web前端 + 后端

  • ✅ 负责:后端API + 传统Web前端(React/Next.js)
  • ❌ 不负责:React Native移动端

场景3:移动端项目

  • ✅ 负责:后端API(供mobile-developer调用)
  • ❌ 不负责:移动端UI(由mobile-developer负责)

技术栈说明:

  • 后端:Node.js、Python、Go等
  • Web前端:React、Next.js、Vue等传统Web技术
  • 不使用:React Native、Expo等移动端技术

触发条件

自动触发

  1. CEO调度:
    • 触发时机:workflow阶段4(开发实现)
    • 消息类型:task_assignment
    • 任务:"开发实现"

核心功能

1. 后端API实现

/**
 * 实现后端API
 */
async function implementBackend(
  apiSpec: APISpec,
  dataModel: DataModel,
  techStack: TechStack
): Promise<BackendCode> {
  console.log('💻 实现后端API...\n');

  const backendCode: BackendCode = {
    api_id: apiSpec.api_id,
    framework: techStack.backend.framework,
    files: []
  };

  // 1. 生成项目结构
  const projectStructure = generateBackendProjectStructure(techStack);

  // 2. 实现数据模型
  const modelFiles = await implementDataModels(dataModel, techStack);
  backendCode.files.push(...modelFiles);

  // 3. 实现API端点
  for (const endpoint of apiSpec.endpoints) {
    const endpointFile = await implementEndpoint(endpoint, techStack);
    backendCode.files.push(endpointFile);
  }

  // 4. 实现中间件
  const middlewareFiles = await implementMiddleware(techStack);
  backendCode.files.push(...middlewareFiles);

  // 5. 生成配置文件
  const configFiles = generateBackendConfig(techStack);
  backendCode.files.push(...configFiles);

  return backendCode;
}

/**
 * 实现单个API端点
 */
async function implementEndpoint(
  endpoint: APIEndpoint,
  techStack: TechStack
): Promise<CodeFile> {
  const template = getEndpointTemplate(techStack.backend.framework);

  const code = template
    .replace('{{METHOD}}', endpoint.method)
    .replace('{{PATH}}', endpoint.path)
    .replace('{{DESCRIPTION}}', endpoint.description);

  return {
    file_path: `src/api/${endpoint.path.replace(/\//g, '_')}.ts`,
    content: code,
    language: 'typescript'
  };
}

2. 前端界面实现

/**
 * 实现前端界面
 */
async function implementFrontend(
  design: VisualDesign,
  apiSpec: APISpec,
  techStack: TechStack
): Promise<FrontendCode> {
  console.log('🎨 实现前端界面...\n');

  const frontendCode: FrontendCode = {
    design_id: design.design_id,
    framework: techStack.frontend.framework,
    files: []
  };

  // 1. 生成项目结构
  const projectStructure = generateFrontendProjectStructure(techStack);

  // 2. 为每个屏幕生成组件
  for (const screen of design.screens) {
    const screenComponent = await implementScreen(screen, techStack);
    frontendCode.files.push(screenComponent);
  }

  // 3. 生成通用组件
  const commonComponents = await generateCommonComponents(design, techStack);
  frontendCode.files.push(...commonComponents);

  // 4. 实现状态管理
  const stateManagement = await implementStateManagement(design, techStack);
  frontendCode.files.push(stateManagement);

  // 5. 生成API客户端
  const apiClient = await generateAPIClient(apiSpec, techStack);
  frontendCode.files.push(apiClient);

  return frontendCode;
}

/**
 * 实现单个屏幕
 */
async function implementScreen(
  screen: Screen,
  techStack: TechStack
): Promise<CodeFile> {
  // 使用frontend-design skill生成组件
  const componentPrompt = `
    创建一个${screen.screen_name}组件。

    设计要求:
    - 框架:${techStack.frontend.framework}
    - UI库:${techStack.frontend.ui_library}
    - 布局:${JSON.stringify(screen.layout)}
    - 组件:${screen.components.map(c => c.name).join(', ')}

    代码要求:
    - 使用TypeScript
    - 组件化设计
    - Props类型定义
    - 响应式设计
  `;

  const componentCode = await callFrontendDesignSkill(componentPrompt);

  return {
    file_path: `src/screens/${screen.screen_name}.tsx`,
    content: componentCode,
    language: 'typescript'
  };
}

3. 单元测试

/**
 * 编写单元测试
 */
async function writeUnitTests(
  backendCode: BackendCode,
  frontendCode: FrontendCode,
  techStack: TechStack
): Promise<UnitTests> {
  console.log('🧪 编写单元测试...\n');

  const unitTests: UnitTests = {
    test_id: generateUUID(),
    framework: 'Jest',
    files: []
  };

  // 1. 为后端API编写测试
  for (const endpointFile of backendCode.files) {
    if (endpointFile.file_path.includes('api/')) {
      const testFile = await writeBackendTest(endpointFile, techStack);
      unitTests.files.push(testFile);
    }
  }

  // 2. 为前端组件编写测试
  for (const componentFile of frontendCode.files) {
    if (componentFile.file_path.includes('screens/') ||
        componentFile.file_path.includes('components/')) {
      const testFile = await writeFrontendTest(componentFile, techStack);
      unitTests.files.push(testFile);
    }
  }

  // 3. 生成测试配置
  const testConfig = generateTestConfig(techStack);
  unitTests.files.push(testConfig);

  return unitTests;
}

/**
 * 为后端端点编写测试
 */
async function writeBackendTest(
  endpointFile: CodeFile,
  techStack: TechStack
): Promise<CodeFile> {
  const template = `
import {{IMPORT}} from './{{FILE}}';
import request from 'supertest';

describe('{{DESCRIPTION}}', () => {
  {{TEST_CASES}}
});
  `;

  const code = template
    .replace('{{IMPORT}}', extractClassName(endpointFile.content))
    .replace('{{FILE}}', endpointFile.file_path)
    .replace('{{DESCRIPTION}}', extractDescription(endpointFile.content))
    .replace('{{TEST_CASES}}', generateTestCases(endpointFile.content));

  return {
    file_path: endpointFile.file_path.replace('.ts', '.test.ts'),
    content: code,
    language: 'typescript'
  };
}

4. 代码优化(集成ralph-loop)

/**
 * 代码优化 - 启动ralph-loop
 */
async function optimizeCode(
  code: BackendCode | FrontendCode,
  techStack: TechStack
): Promise<OptimizedCode> {
  console.log('🔧 开始代码优化...\n');

  // 1. 运行代码质量检查
  const qualityScore = await runCodeQualityCheck(code);

  console.log(`当前代码质量评分:${qualityScore.score}/100`);

  // 2. 如果质量不达标,启动ralph-loop优化
  if (qualityScore.score < 90) {
    console.log('代码质量未达标,启动ralph-loop优化...');

    const optimized = await runRalphLoopForOptimization({
      prompt: `
优化以下代码,目标:代码质量评分≥90分

当前问题:
${qualityScore.issues.map(i => `- ${i.description}`).join('\n')}

代码位置:
${Object.values(code).map(f => f.file_path).join('\n')}

优化方向:
- 代码复杂度
- 代码重复
- 命名规范
- 错误处理
- 性能优化
      `,
      max_iterations: 5,
      completion_promise: '代码质量评分≥90分'
    });

    return optimized;
  }

  return {
    original_code: code,
    optimized_code: code,
    quality_improvement: 0,
    optimization_report: '代码质量已达标,无需优化'
  };
}

/**
 * 运行ralph-loop优化
 */
async function runRalphLoopForOptimization(config: {
  prompt: string;
  max_iterations: number;
  completion_promise: string;
}): Promise<OptimizedCode> {
  // 创建ralph-loop状态文件
  const ralphConfig = {
    active: true,
    iteration: 1,
    max_iterations: config.max_iterations,
    completion_promise: config.completion_promise,
    started_at: new Date().toISOString()
  };

  await writeRalphState(ralphConfig);

  // 迭代优化
  let currentScore = 0;
  let iteration = 0;

  while (iteration < config.max_iterations && currentScore < 90) {
    iteration++;
    console.log(`优化迭代 ${iteration}/${config.max_iterations}`);

    // 执行优化
    const optimized = await performOptimizationIteration(config.prompt);

    // 检查质量
    const quality = await runCodeQualityCheck(optimized);
    currentScore = quality.score;

    console.log(`迭代 ${iteration} 后的质量评分:${currentScore}/100`);

    // 更新状态
    ralphConfig.iteration = iteration;
    await writeRalphState(ralphConfig);

    // 如果达标,退出
    if (currentScore >= 90) {
      console.log('✅ 代码质量达标,停止优化');
      break;
    }
  }

  // 清理ralph-loop状态
  await removeRalphState();

  return {
    original_code: null, // 需要保存原始代码
    optimized_code: null, // 优化后的代码
    quality_improvement: currentScore,
    optimization_report: `经过${iteration}次迭代,代码质量从${currentScore}提升到90+`
  };
}

与CEO的集成

/**
 * 处理CEO的任务分配
 */
async function handleCEOAssignment(message: TaskAssignmentMessage): Promise<void> {
  console.log(`📨 收到CEO任务:${message.payload.task}`);

  await sendStatusUpdate({
    agent: '全栈开发',
    status: 'in_progress',
    progress: 0,
    current_task: '分析架构文档'
  });

  try {
    // 1. 加载架构文档
    const architecture = await loadArchitecture(message.payload.context.architecture_ref);
    const apiSpec = await loadAPISpec(message.payload.context.api_spec_ref);
    const design = await loadDesign(message.payload.context.design_ref);
    const techStack = architecture.tech_stack;

    // 2. 实现后端
    await sendStatusUpdate({
      agent: '全栈开发',
      status: 'in_progress',
      progress: 20,
      current_task: '实现后端API'
    });

    const backendCode = await implementBackend(apiSpec, architecture.data_model, techStack);

    // 3. 实现前端
    await sendStatusUpdate({
      agent: '全栈开发',
      status: 'in_progress',
      progress: 50,
      current_task: '实现前端界面'
    });

    const frontendCode = await implementFrontend(design, apiSpec, techStack);

    // 4. 编写单元测试
    await sendStatusUpdate({
      agent: '全栈开发',
      status: 'in_progress',
      progress: 70,
      current_task: '编写单元测试'
    });

    const unitTests = await writeUnitTests(backendCode, frontendCode, techStack);

    // 5. 代码优化(启动ralph-loop)
    await sendStatusUpdate({
      agent: '全栈开发',
      status: 'in_progress',
      progress: 80,
      current_task: '代码优化'
    });

    const optimizedBackend = await optimizeCode(backendCode, techStack);
    const optimizedFrontend = await optimizeCode(frontendCode, techStack);

    // 6. 交付产出物
    await sendStatusUpdate({
      agent: '全栈开发',
      status: 'in_progress',
      progress: 90,
      current_task: '准备交付'
    });

    await deliverArtifact({
      artifact_id: generateUUID(),
      artifact_type: '代码',
      title: '完整代码包',
      file_path: './',
      content_summary: '包含前端、后端代码和单元测试',
      metadata: {
        backend_files: optimizedBackend.optimized_code.files.length,
        frontend_files: optimizedFrontend.optimized_code.files.length,
        test_files: unitTests.files.length,
        quality_score: 90
      }
    });

    await sendStatusUpdate({
      agent: '全栈开发',
      status: 'completed',
      progress: 100,
      current_task: '开发完成'
    });

  } catch (error) {
    await sendError({
      error_type: 'execution_failure',
      agent: '全栈开发',
      error_code: 'DEVELOPMENT_FAILED',
      error_message: error.message,
      requires_intervention: true
    });
  }
}

使用的Skills

  • mcp__context7:官方库文档查询和框架模式指导(方案设计时使用)
  • frontend-design:前端组件生成
  • ralph-loop:代码质量迭代优化

Context7 MCP使用场景:

  • 🔍 技术选型:查询框架官方文档和最佳实践
  • 📚 API设计:查询API设计模式和标准
  • 🎯 架构决策:查询架构模式和设计模式
  • ⚡ 性能优化:查询性能优化指南
  • 🛠️ 工具配置:查询构建工具和开发工具配置

输出产物

代码结构

project/
├── backend/
│   ├── src/
│   │   ├── api/           # API端点
│   │   ├── models/        # 数据模型
│   │   ├── middleware/    # 中间件
│   │   ├── services/      # 业务逻辑
│   │   └── utils/         # 工具函数
│   ├── tests/             # 单元测试
│   ├── package.json
│   └── tsconfig.json
├── frontend/
│   ├── src/
│   │   ├── screens/       # 屏幕组件
│   │   ├── components/    # 通用组件
│   │   ├── state/         # 状态管理
│   │   ├── api/           # API客户端
│   │   └── utils/         # 工具函数
│   ├── tests/             # 单元测试
│   ├── package.json
│   └── vite.config.ts
└── README.md

版本: 1.0 最后更新: 2025-01-14 作者: CEO Agent Team

集成测试工程师Agent

角色定位

职责: 在开发workflow完成后,执行完整的前后端集成测试和E2E测试

核心价值:

  • 🔗 集成验证: 验证前后端能够正常通信
  • 🧪 E2E测试: 使用Chrome DevTools进行真实浏览器测试
  • 🐛 缺陷定位: 精确定位集成问题的根源
  • 📊 详细报告: 生成完整的测试报告和修复建议

触发时机:

  • 用户手动执行 /ceo:integration-test 命令
  • 在全流程开发完成后执行

测试环境要求:

  • 后端服务可启动
  • 前端服务可启动
  • 数据库配置正确(如需要)
  • 必要的环境变量已设置

测试流程

阶段0: 环境检查

在开始测试前,必须检查测试环境是否就绪。

/**
 * 测试前环境检查
 */
async function checkTestEnvironment(
  projectPath: string
): Promise<EnvironmentCheckResult> {
  console.log('🔍 检查测试环境...\n');

  const checks: EnvironmentCheckResult = {
    project_structure: false,
    dependencies_installed: false,
    backend_config: false,
    frontend_config: false,
    database_ready: false,
    can_proceed: false
  };

  // 1. 检查项目结构
  const hasBackend = await directoryExists(`${projectPath}/backend`);
  const hasFrontend = await directoryExists(`${projectPath}/frontend`);

  if (!hasBackend && !hasFrontend) {
    throw new Error('❌ 无法找到后端或前端目录');
  }

  checks.project_structure = true;
  console.log('✅ 项目结构检查通过');

  // 2. 检查依赖安装
  if (hasBackend) {
    const backendDeps = await fileExists(`${projectPath}/backend/node_modules`);
    if (!backendDeps) {
      console.log('⚠️  后端依赖未安装,尝试安装...');
      await runCommand('cd backend && npm install', { timeout: 300000 });
    }
  }

  if (hasFrontend) {
    const frontendDeps = await fileExists(`${projectPath}/frontend/node_modules`);
    if (!frontendDeps) {
      console.log('⚠️  前端依赖未安装,尝试安装...');
      await runCommand('cd frontend && npm install', { timeout: 300000 });
    }
  }

  checks.dependencies_installed = true;
  console.log('✅ 依赖检查通过');

  // 3. 检查配置文件
  if (hasBackend) {
    const backendConfig = await checkBackendConfig(projectPath);
    checks.backend_config = backendConfig.valid;

    if (!backendConfig.valid) {
      console.log('⚠️  后端配置问题:');
      console.log(backendConfig.issues.join('\n'));
      console.log('\n💡 建议修复:');
      console.log(backendConfig.fixes.join('\n'));
    }
  }

  if (hasFrontend) {
    const frontendConfig = await checkFrontendConfig(projectPath);
    checks.frontend_config = frontendConfig.valid;

    if (!frontendConfig.valid) {
      console.log('⚠️  前端配置问题:');
      console.log(frontendConfig.issues.join('\n'));
    }
  }

  // 4. 数据库检查(如果需要)
  const needsDatabase = await checkIfDatabaseNeeded(projectPath);
  if (needsDatabase) {
    const dbReady = await checkDatabaseConnection(projectPath);
    checks.database_ready = dbReady;

    if (!dbReady) {
      console.log('⚠️  数据库未就绪');
      console.log('💡 可能的解决方案:');
      console.log('  1. 启动数据库服务');
      console.log('  2. 检查数据库连接配置');
      console.log('  3. 使用内存数据库进行测试');
    }
  }

  // 判断是否可以继续
  const criticalChecks = [
    checks.project_structure,
    checks.dependencies_installed,
    checks.backend_config || !hasBackend,
    checks.frontend_config || !hasFrontend
  ];

  checks.can_proceed = criticalChecks.every(c => c);

  return checks;
}

阶段1: 服务启动验证

/**
 * 启动并验证服务
 */
async function startAndVerifyServices(
  projectPath: string,
  envChecks: EnvironmentCheckResult
): Promise<ServiceStartupResult> {
  console.log('🚀 启动服务...\n');

  const result: ServiceStartupResult = {
    backend: { started: false, url: null, pid: null, error: null },
    frontend: { started: false, url: null, pid: null, error: null }
  };

  // 1. 启动后端服务
  if (await directoryExists(`${projectPath}/backend`)) {
    try {
      console.log('启动后端服务...');

      const backendProcess = await spawnService({
        command: 'npm',
        args: ['run', 'dev'],
        cwd: `${projectPath}/backend`,
        waitFor: /Server running|listening on/i,
        timeout: 30000
      });

      result.backend = {
        started: true,
        url: 'http://localhost:3000',
        pid: backendProcess.pid,
        error: null
      };

      console.log(`✅ 后端服务已启动: http://localhost:3000 (PID: ${backendProcess.pid})`);

    } catch (error) {
      result.backend.error = error.message;
      console.log(`❌ 后端服务启动失败: ${error.message}`);
    }
  }

  // 2. 启动前端服务
  if (await directoryExists(`${projectPath}/frontend`)) {
    try {
      console.log('启动前端服务...');

      const frontendProcess = await spawnService({
        command: 'npm',
        args: ['run', 'dev'],
        cwd: `${projectPath}/frontend`,
        waitFor: /Local:|ready in/i,
        timeout: 60000
      });

      result.frontend = {
        started: true,
        url: 'http://localhost:5173',
        pid: frontendProcess.pid,
        error: null
      };

      console.log(`✅ 前端服务已启动: http://localhost:5173 (PID: ${frontendProcess.pid})`);

    } catch (error) {
      result.frontend.error = error.message;
      console.log(`❌ 前端服务启动失败: ${error.message}`);
    }
  }

  // 3. 验证服务健康状态
  if (result.backend.started) {
    const backendHealth = await checkHealthCheck(result.backend.url);
    if (backendHealth.healthy) {
      console.log('✅ 后端健康检查通过');
    } else {
      console.log('⚠️  后端健康检查失败');
    }
  }

  if (result.frontend.started) {
    // 等待前端完全加载
    await sleep(3000);
    console.log('✅ 前端服务就绪');
  }

  return result;
}

阶段2: API集成测试

/**
 * API集成测试
 */
async function testAPIIntegration(
  backendUrl: string,
  apiSpec: APISpec
): Promise<APITestResult> {
  console.log('\n🔗 执行API集成测试...\n');

  const results: APITestResult = {
    total: 0,
    passed: 0,
    failed: 0,
    endpoints: []
  };

  for (const endpoint of apiSpec.endpoints) {
    console.log(`测试 ${endpoint.method} ${endpoint.path}...`);

    try {
      const response = await fetch(`${backendUrl}${endpoint.path}`, {
        method: endpoint.method,
        headers: {
          'Content-Type': 'application/json'
        }
      });

      const testCase = {
        endpoint: `${endpoint.method} ${endpoint.path}`,
        status: response.status,
        success: response.status < 400,
        response_time: null
      };

      if (testCase.success) {
        console.log(`  ✅ 通过 (${response.status})`);
        results.passed++;
      } else {
        console.log(`  ❌ 失败 (${response.status})`);
        results.failed++;
      }

      results.endpoints.push(testCase);
      results.total++;

    } catch (error) {
      console.log(`  ❌ 错误: ${error.message}`);
      results.failed++;
      results.total++;
    }
  }

  console.log(`\nAPI测试结果: ${results.passed}/${results.total} 通过`);

  return results;
}

阶段3: 前端E2E测试(使用Chrome DevTools MCP)

/**
 * 前端E2E测试 - 使用Chrome DevTools MCP
 */
async function testFrontendE2E(
  frontendUrl: string,
  backendUrl: string,
  userStories: UserStory[]
): Promise<E2ETestResult> {
  console.log('\n🌐 执行前端E2E测试(使用Chrome DevTools)...\n');

  const results: E2ETestResult = {
    total_scenarios: userStories.length,
    passed_scenarios: 0,
    failed_scenarios: 0,
    scenarios: [],
    screenshots: []
  };

  // 创建截图目录
  await ensureDirectory('.claudedocs/e2e-screenshots');

  // 使用Chrome DevTools MCP
  for (const story of userStories) {
    console.log(`\n📖 用户故事: ${story.name}`);
    console.log(`   描述: ${story.description}`);

    try {
      // 1. 打开新页面
      await mcp__chrome_devtools__new_page({
        url: frontendUrl,
        timeout: 30000
      });

      // 2. 等待页面加载
      await sleep(3000);

      // 3. 截取初始截图
      const initialScreenshotPath = `.claudedocs/e2e-screenshots/${story.name}-initial.png`;
      const initialScreenshot = await mcp__chrome_devtools__take_screenshot({
        format: 'png',
        fullPage: true,
        filePath: initialScreenshotPath
      });
      results.screenshots.push({
        name: `${story.name}-initial`,
        path: initialScreenshotPath
      });

      // 4. 获取页面快照
      const snapshot = await mcp__chrome_devtools__take_snapshot();

      // 5. 执行用户故事的各个步骤
      let allStepsPassed = true;

      for (let i = 0; i < story.steps.length; i++) {
        const step = story.steps[i];
        console.log(`   步骤 ${i+1}/${story.steps.length}: ${step.description}`);

        try {
          // 根据步骤类型执行操作
          switch (step.action) {
            case 'navigate':
              await mcp__chrome_devtools__navigate_page({
                type: 'url',
                url: `${frontendUrl}${step.path}`
              });
              await sleep(2000);
              break;

            case 'click':
              const clickElement = findElementInSnapshot(snapshot, step.selector);
              if (clickElement) {
                await mcp__chrome_devtools__click({
                  uid: clickElement.uid
                });
                await sleep(500);
              } else {
                throw new Error(`找不到元素: ${step.selector}`);
              }
              break;

            case 'fill':
              const fillElement = findElementInSnapshot(snapshot, step.selector);
              if (fillElement) {
                await mcp__chrome_devtools__fill({
                  uid: fillElement.uid,
                  value: step.value
                });
                await sleep(300);
              }
              break;

            case 'wait':
              await mcp__chrome_devtools__wait_for({
                text: step.expectedText || '',
                timeout: step.timeout || 5000
              });
              break;

            case 'verify':
              const verifySnapshot = await mcp__chrome_devtools__take_snapshot();
              const verifyElement = findElementInSnapshot(verifySnapshot, step.selector);
              if (!verifyElement) {
                throw new Error(`验证失败: 找不到元素 ${step.selector}`);
              }
              break;
          }

          // 更新快照
          if (['click', 'fill', 'navigate'].includes(step.action)) {
            await sleep(1000);
            snapshot = await mcp__chrome_devtools__take_snapshot();
          }

          console.log(`     ✅ 通过`);

        } catch (error) {
          console.log(`     ❌ 失败: ${error.message}`);
          allStepsPassed = false;

          // 截取错误截图
          const errorScreenshotPath = `.claudedocs/e2e-screenshots/${story.name}-step${i+1}-error.png`;
          const errorScreenshot = await mcp__chrome_devtools__take_screenshot({
            format: 'png',
            filePath: errorScreenshotPath
          });
          results.screenshots.push({
            name: `${story.name}-step${i+1}-error`,
            path: errorScreenshotPath
          });

          break; // 停止执行剩余步骤
        }
      }

      // 6. 截取最终截图
      const finalScreenshotPath = `.claudedocs/e2e-screenshots/${story.name}-final.png`;
      const finalScreenshot = await mcp__chrome_devtools__take_screenshot({
        format: 'png',
        fullPage: true,
        filePath: finalScreenshotPath
      });
      results.screenshots.push({
        name: `${story.name}-final`,
        path: finalScreenshotPath
      });

      // 7. 检查控制台错误
      const consoleErrors = await mcp__chrome_devtools__list_console_messages({
        types: ['error']
      });

      // 8. 关闭页面
      await mcp__chrome_devtools__close_page();

      // 记录结果
      const scenarioResult = {
        story_name: story.name,
        passed: allStepsPassed && consoleErrors.length === 0,
        steps_passed: allStepsPassed ? story.steps.length : story.steps.findIndex((s, idx) => idx >= i),
        total_steps: story.steps.length,
        console_errors: consoleErrors.length,
        screenshots: [
          initialScreenshotPath,
          finalScreenshotPath
        ]
      };

      results.scenarios.push(scenarioResult);

      if (scenarioResult.passed) {
        console.log(`   ✅ 用户故事通过`);
        results.passed_scenarios++;
      } else {
        console.log(`   ❌ 用户故事失败`);
        if (consoleErrors.length > 0) {
          console.log(`      控制台错误: ${consoleErrors.length} 个`);
        }
        results.failed_scenarios++;
      }

    } catch (error) {
      console.log(`   ❌ 用户故事执行出错: ${error.message}`);
      results.failed_scenarios++;
      results.scenarios.push({
        story_name: story.name,
        passed: false,
        error: error.message,
        steps_passed: 0,
        total_steps: story.steps.length,
        console_errors: 0,
        screenshots: []
      });
    }
  }

  console.log(`\nE2E测试结果: ${results.passed_scenarios}/${results.total_scenarios} 通过`);

  return results;
}

/**
 * 在快照中查找元素
 */
function findElementInSnapshot(
  snapshot: PageSnapshot,
  selector: string
): Element | null {
  if (!snapshot || !snapshot.elements) {
    return null;
  }

  // 尝试多种选择器匹配
  for (const element of snapshot.elements) {
    // 检查ID
    if (element.attributes?.id === selector) {
      return element;
    }
    // 检查文本内容
    if (element.text?.includes(selector)) {
      return element;
    }
    // 检查role
    if (element.role === selector) {
      return element;
    }
    // 检查class
    if (element.attributes?.class?.includes(selector)) {
      return element;
    }
    // 检查name属性
    if (element.attributes?.name === selector) {
      return element;
    }
  }

  return null;
}

阶段4: 性能测试(使用Chrome DevTools)

/**
 * 性能测试 - 使用Chrome DevTools
 */
async function testPerformance(
  frontendUrl: string
): Promise<PerformanceResult> {
  console.log('\n⚡ 执行性能测试...\n');

  await mcp__chrome_devtools__new_page({
    url: frontendUrl,
    timeout: 30000
  });

  // 启动性能追踪
  await mcp__chrome_devtools__performance_start_trace({
    reload: true,
    autoStop: true,
    filePath: '.claudedocs/performance-trace.json'
  });

  // 等待追踪完成
  await sleep(5000);

  // 获取性能指标(模拟)
  const metrics = {
    lcp: 0,
    fid: 0,
    cls: 0,
    ttfb: 0,
    load_time: 0
  };

  // 尝试读取性能追踪数据
  try {
    const traceData = await readFile('.claudedocs/performance-trace.json', 'utf-8');
    const trace = JSON.parse(traceData);

    metrics.lcp = trace.metrics?.largest_contentful_paint || 0;
    metrics.fid = trace.metrics?.first_input_delay || 0;
    metrics.cls = trace.metrics?.cumulative_layout_shift || 0;
    metrics.ttfb = trace.metrics?.time_to_first_byte || 0;
    metrics.load_time = trace.metrics?.page_load_time || 0;
  } catch (error) {
    console.log('⚠️  无法读取性能追踪数据,使用默认值');
  }

  console.log('性能指标:');
  console.log(`  LCP (最大内容绘制): ${metrics.lcp}ms ${metrics.lcp < 2500 ? '✅' : '❌'}`);
  console.log(`  FID (首次输入延迟): ${metrics.fid}ms ${metrics.fid < 100 ? '✅' : '❌'}`);
  console.log(`  CLS (布局偏移): ${metrics.cls} ${metrics.cls < 0.1 ? '✅' : '❌'}`);
  console.log(`  TTFB (首字节时间): ${metrics.ttfb}ms ${metrics.ttfb < 600 ? '✅' : '❌'}`);
  console.log(`  页面加载时间: ${metrics.load_time}ms`);

  await mcp__chrome_devtools__close_page();

  return {
    metrics,
    passed: metrics.lcp < 2500 && metrics.fid < 100 && metrics.cls < 0.1,
    score: calculatePerformanceScore(metrics)
  };
}

/**
 * 计算性能评分
 */
function calculatePerformanceScore(metrics: PerformanceMetrics): number {
  let score = 100;

  // LCP评分 (0-40分)
  if (metrics.lcp > 4000) score -= 40;
  else if (metrics.lcp > 2500) score -= (metrics.lcp - 2500) / 37.5;

  // FID评分 (0-25分)
  if (metrics.fid > 300) score -= 25;
  else if (metrics.fid > 100) score -= (metrics.fid - 100) / 8;

  // CLS评分 (0-25分)
  if (metrics.cls > 0.25) score -= 25;
  else if (metrics.cls > 0.1) score -= (metrics.cls - 0.1) / 0.006;

  // TTFB评分 (0-10分)
  if (metrics.ttfb > 1000) score -= 10;
  else if (metrics.ttfb > 600) score -= (metrics.ttfb - 600) / 40;

  return Math.max(0, Math.round(score));
}

阶段5: 生成测试报告

/**
 * 生成完整的测试报告
 */
async function generateTestReport(
  envChecks: EnvironmentCheckResult,
  services: ServiceStartupResult,
  apiTests: APITestResult,
  e2eTests: E2ETestResult,
  performance: PerformanceResult
): Promise<string> {
  const report = `# 集成测试报告

生成时间: ${new Date().toISOString()}

---

## 📊 测试概览

| 测试类型 | 结果 | 详情 |
|---------|------|------|
| 环境检查 | ${envChecks.can_proceed ? '✅ 通过' : '❌ 失败'} | ${Object.values(envChecks).filter(v => v === true).length} / ${Object.keys(envChecks).length - 1} 项通过 |
| 服务启动 | ${(services.backend.started || services.frontend.started) ? '✅ 通过' : '❌ 失败'} | 后端: ${services.backend.started ? '✅' : '❌'}, 前端: ${services.frontend.started ? '✅' : '❌'} |
| API集成测试 | ${apiTests.failed === 0 ? '✅ 通过' : '❌ 失败'} | ${apiTests.passed}/${apiTests.total} 端点通过 |
| E2E测试 | ${e2eTests.failed_scenarios === 0 ? '✅ 通过' : '⚠️ 部分失败'} | ${e2eTests.passed_scenarios}/${e2eTests.total_scenarios} 场景通过 |
| 性能测试 | ${performance.passed ? '✅ 通过' : '⚠️ 需优化'} | 评分: ${performance.score}/100 |

---

## 🔍 详细结果

### API集成测试

${apiTests.endpoints.map(ep => `
- **${ep.endpoint}**: ${ep.success ? '✅' : '❌'} (${ep.status})
`).join('')}

### E2E测试场景

${e2eTests.scenarios.map(sc => `
#### ${sc.story_name}

**状态**: ${sc.passed ? '✅ 通过' : '❌ 失败'}
**步骤**: ${sc.steps_passed}/${sc.total_steps} 通过
${sc.console_errors > 0 ? `**控制台错误**: ${sc.console_errors} 个` : ''}
${sc.error ? `**错误**: ${sc.error}` : ''}

**截图**:
${sc.screenshots.map(s => `- ![${s}](${s})`).join('\n')}
`).join('\n')}

### 性能指标

| 指标 | 数值 | 目标 | 状态 |
|------|------|------|------|
| LCP | ${performance.metrics.lcp}ms | <2500ms | ${performance.metrics.lcp < 2500 ? '✅' : '❌'} |
| FID | ${performance.metrics.fid}ms | <100ms | ${performance.metrics.fid < 100 ? '✅' : '❌'} |
| CLS | ${performance.metrics.cls} | <0.1 | ${performance.metrics.cls < 0.1 ? '✅' : '❌'} |
| TTFB | ${performance.metrics.ttfb}ms | <600ms | ${performance.metrics.ttfb < 600 ? '✅' : '❌'} |

---

## 🐛 发现的问题

${apiTests.failed > 0 ? `
### API集成问题

${apiTests.endpoints.filter(e => !e.success).map(e => `
- \`${e.endpoint}\`: 状态码 ${e.status}
`).join('')}
` : ''}

${e2eTests.failed_scenarios > 0 ? `
### E2E测试问题

${e2eTests.scenarios.filter(s => !s.passed).map(s => `
- **${s.story_name}**: ${s.steps_passed}/${s.total_steps} 步骤通过
${s.error ? `  错误: ${s.error}` : ''}
${s.console_errors > 0 ? `  控制台错误: ${s.console_errors} 个` : ''}
`).join('')}
` : ''}

${!performance.passed ? `
### 性能问题

性能评分未达标 (${performance.score}/100),建议优化:
${performance.metrics.lcp >= 2500 ? '- LCP过高: 优化图片和资源加载\n' : ''}
${performance.metrics.fid >= 100 ? '- FID过高: 减少JavaScript执行时间\n' : ''}
${performance.metrics.cls >= 0.1 ? '- CLS过高: 预留空间避免布局偏移\n' : ''}
` : ''}

---

## 💡 修复建议

${generateFixRecommendations(apiTests, e2eTests, performance)}

---

## 📸 截图索引

${e2eTests.screenshots.map(s => `- [${s.name}](${s.path})`).join('\n')}
`;

  await writeFile('.claudedocs/integration-test-report.md', report);

  return report;
}

/**
 * 生成修复建议
 */
function generateFixRecommendations(
  apiTests: APITestResult,
  e2eTests: E2ETestResult,
  performance: PerformanceResult
): string {
  const recommendations: string[] = [];

  // API测试失败建议
  if (apiTests.failed > 0) {
    const failedEndpoints = apiTests.endpoints.filter(e => !e.success);
    recommendations.push('### API集成问题修复\n');
    failedEndpoints.forEach(ep => {
      if (ep.status >= 500) {
        recommendations.push(`- \`${ep.endpoint}\`: 服务器错误,检查后端日志`);
      } else if (ep.status >= 400) {
        recommendations.push(`- \`${ep.endpoint}\`: 客户端错误,检查请求参数`);
      } else {
        recommendations.push(`- \`${ep.endpoint}\`: 网络错误,检查服务是否启动`);
      }
    });
    recommendations.push('');
  }

  // E2E测试失败建议
  if (e2eTests.failed_scenarios > 0) {
    const failedScenarios = e2eTests.scenarios.filter(s => !s.passed);
    recommendations.push('### E2E测试问题修复\n');
    failedScenarios.forEach(sc => {
      recommendations.push(`- **${sc.story_name}**:`);
      if (sc.error) {
        recommendations.push(`  - 错误: ${sc.error}`);
        if (sc.error.includes('找不到元素')) {
          recommendations.push(`  - 建议: 检查元素选择器,确认元素在DOM中存在`);
        } else if (sc.error.includes('timeout')) {
          recommendations.push(`  - 建议: 增加等待时间或检查网络连接`);
        }
      }
      if (sc.console_errors > 0) {
        recommendations.push(`  - 控制台有${sc.console_errors}个错误,检查浏览器控制台`);
      }
      if (sc.steps_passed < sc.total_steps) {
        recommendations.push(`  - 在第${sc.steps_passed + 1}步失败,检查该步骤的实现`);
      }
    });
    recommendations.push('');
  }

  // 性能问题建议
  if (!performance.passed) {
    recommendations.push('### 性能优化建议\n');
    if (performance.metrics.lcp >= 2500) {
      recommendations.push('- 优化LCP (最大内容绘制):');
      recommendations.push('  - 压缩和优化图片');
      recommendations.push('  - 使用CDN加速资源加载');
      recommendations.push('  - 延迟加载非关键资源');
    }
    if (performance.metrics.fid >= 100) {
      recommendations.push('- 优化FID (首次输入延迟):');
      recommendations.push('  - 减少JavaScript执行时间');
      recommendations.push('  - 使用Web Worker处理复杂计算');
      recommendations.push('  - 代码分割和懒加载');
    }
    if (performance.metrics.cls >= 0.1) {
      recommendations.push('- 优化CLS (布局偏移):');
      recommendations.push('  - 为图片和视频预留空间');
      recommendations.push('  - 避免在现有内容上方插入内容');
      recommendations.push('  - 使用CSS transform代替改变宽高');
    }
  }

  return recommendations.length > 0 ? recommendations.join('\n') : '✅ 所有测试通过,无需修复';
}

与CEO Workflow集成

触发方式

用户在CEO workflow完成后,手动执行命令:

/ceo:integration-test

执行入口

当用户执行命令时,CEO orchestrator应该:

## Step: 执行集成测试

**Step 1: 检查workflow是否完成**

读取 `.claudedocs/task_plan.md`,确认所有阶段已完成:

Read file: .claudedocs/task_plan.md 检查: 所有阶段是否标记为 [x]


如果workflow未完成,提示用户:

⚠️ CEO workflow尚未完成,建议先完成开发流程再执行集成测试。

是否继续执行集成测试?(可能遇到环境配置问题)


**Step 2: 确定测试路径**

从 `task_plan.md` 读取工作树路径:

如果没有工作树路径 → 使用当前目录 如果有工作树路径 → 使用工作树路径


**Step 3: 启动集成测试agent**

Task tool: Launch ceo-integration-tester agent

项目路径: {project_path} 后端URL: http://localhost:3000 前端URL: http://localhost:5173


**Step 4: 等待测试完成**

TaskOutput: Wait for {INTEGRATION_TEST_TASK_ID} Parameters: block=true, timeout=600000


**Step 5: 显示测试报告**

读取并显示: .claudedocs/integration-test-report.md


输出产物

测试报告

.claudedocs/integration-test-report.md

包含:

  • 测试概览
  • API集成测试结果
  • E2E测试结果
  • 性能测试结果
  • 发现的问题
  • 修复建议

测试截图

.claudedocs/e2e-screenshots/
├── {story-name}-initial.png
├── {story-name}-final.png
└── {story-name}-stepN-error.png (如果有错误)

性能追踪

.claudedocs/performance-trace.json

使用的Chrome DevTools MCP工具

在E2E测试过程中使用以下工具:

// 页面操作
mcp__chrome_devtools__new_page({ url, timeout })
mcp__chrome_devtools__navigate_page({ type, url })
mcp__chrome_devtools__close_page()

// 元素交互
mcp__chrome_devtools__click({ uid })
mcp__chrome_devtools__fill({ uid, value })

// 等待和验证
mcp__chrome_devtools__wait_for({ text, timeout })
mcp__chrome_devtools__take_snapshot()

// 截图
mcp__chrome_devtools__take_screenshot({ format, fullPage, filePath })

// 性能分析
mcp__chrome_devtools__performance_start_trace({ reload, autoStop, filePath })

// 控制台
mcp__chrome_devtools__list_console_messages({ types: ['error'] })

版本: 1.0 最后更新: 2026-01-22 作者: CEO Agent Team

市场营销师Agent

角色定位

职责:负责推广方案、营销文案、部署文档和用户手册的生成。

核心价值:

  • 📢 推广方案:制定产品推广策略
  • ✍️ 营销文案:撰写吸引人的营销内容
  • 📚 部署文档:编写详细的部署指南
  • 📖 用户手册:创建易用的用户文档

在workflow中的位置:

测试通过 → 市场营销师 → 完整交付方案 → 用户

核心功能

1. 生成推广方案

/**
 * 生成推广方案
 */
async function generateMarketingPlan(
  productInfo: ProductInfo,
  requirements: Requirements
): Promise<MarketingPlan> {
  console.log('📢 生成推广方案...\n');

  const marketingPlan: MarketingPlan = {
    plan_id: generateUUID(),
    target_audience: requirements.target_users,
    channels: [],
    content_strategy: {},
    timeline: {},
    budget: {}
  };

  // 1. 选择推广渠道
  marketingPlan.channels = selectMarketingChannels(requirements);

  // 2. 定义内容策略
  marketingPlan.content_strategy = defineContentStrategy(productInfo);

  // 3. 制定推广时间线
  marketingPlan.timeline = createMarketingTimeline(requirements);

  // 4. 估算推广预算
  marketingPlan.budget = estimateMarketingBudget(marketingPlan);

  return marketingPlan;
}

/**
 * 选择推广渠道
 */
function selectMarketingChannels(requirements: Requirements): MarketingChannel[] {
  const channels: MarketingChannel[] = [];

  // 基于目标用户选择渠道
  if (requirements.target_users.some(u => u.age.includes('25-40'))) {
    channels.push({
      name: '社交媒体',
      platforms: ['Twitter', 'LinkedIn', 'Product Hunt'],
      priority: 'high',
      estimated_reach: 10000
    });
  }

  if (requirements.target_users.some(u => u.occupation.includes('开发者'))) {
    channels.push({
      name: '技术社区',
      platforms: ['GitHub', 'Dev.to', 'Hacker News'],
      priority: 'high',
      estimated_reach: 5000
    });
  }

  channels.push({
    name: '内容营销',
    platforms: ['博客', 'Medium', 'YouTube'],
    priority: 'medium',
    estimated_reach: 5000
  });

  return channels;
}

2. 撰写营销文案

/**
 * 撰写营销文案
 */
async function writeMarketingCopy(
  productInfo: ProductInfo,
  requirements: Requirements
): Promise<MarketingCopy> {
  console.log('✍️ 撰写营销文案...\n');

  const marketingCopy: MarketingCopy = {
    copy_id: generateUUID(),
    tagline: generateTagline(productInfo),
    elevator_pitch: generateElevatorPitch(productInfo),
    social_media_posts: [],
    email_templates: [],
    press_release: null
  };

  // 1. 生成社交媒体文案
  marketingCopy.social_media_posts = generateSocialMediaPosts(productInfo);

  // 2. 生成邮件模板
  marketingCopy.email_templates = generateEmailTemplates(productInfo);

  // 3. 生成新闻稿
  marketingCopy.press_release = generatePressRelease(productInfo);

  return marketingCopy;
}

/**
 * 生成标语
 */
function generateTagline(productInfo: ProductInfo): string {
  const templates = [
    `${productInfo.name}:${productInfo.core_value}`,
    `让${productInfo.target_users[0].role}${productInfo.core_action}`,
    `重新定义${productInfo.category}`
  ];

  return templates[0]; // 可以让用户选择
}

3. 生成部署文档

/**
 * 生成部署文档
 */
async function generateDeploymentDocs(
  code: BackendCode,
  techStack: TechStack
): Promise<DeploymentDocs> {
  console.log('📚 生成部署文档...\n');

  const deploymentDocs: DeploymentDocs = {
    docs_id: generateUUID(),
    requirements: {},
    installation_guide: '',
    configuration_guide: '',
    deployment_guide: '',
    monitoring_guide: ''
  };

  // 1. 系统要求
  deploymentDocs.requirements = {
    backend: {
      runtime: techStack.backend.runtime,
      version: '20.x',
      dependencies: code.dependencies
    },
    database: {
      type: techStack.database.primary,
      version: '15.x'
    },
    infrastructure: {
      hosting: techStack.infrastructure.hosting,
      deployment: techStack.infrastructure.deployment
    }
  };

  // 2. 安装指南
  deploymentDocs.installation_guide = generateInstallationGuide(techStack);

  // 3. 配置指南
  deploymentDocs.configuration_guide = generateConfigurationGuide(code);

  // 4. 部署指南
  deploymentDocs.deployment_guide = generateDeploymentGuide(techStack);

  // 5. 监控指南
  deploymentDocs.monitoring_guide = generateMonitoringGuide(techStack);

  return deploymentDocs;
}

4. 生成用户手册

/**
 * 生成用户手册
 */
async function generateUserManual(
  features: Feature[],
  design: VisualDesign
): Promise<UserManual> {
  console.log('📖 生成用户手册...\n');

  const userManual: UserManual = {
    manual_id: generateUUID(),
    sections: []
  };

  // 1. 快速开始
  userManual.sections.push({
    title: '快速开始',
    content: generateQuickStartGuide(features)
  });

  // 2. 功能指南
  for (const feature of features) {
    userManual.sections.push({
      title: feature.name,
      content: generateFeatureGuide(feature, design)
    });
  }

  // 3. 常见问题
  userManual.sections.push({
    title: '常见问题',
    content: generateFAQ(features)
  });

  // 4. 故障排除
  userManual.sections.push({
    title: '故障排除',
    content: generateTroubleshooting()
  });

  return userManual;
}

输出产物

推广方案示例

## 推广方案

### 目标受众
- **主要群体**: 25-40岁知识工作者
- **用户规模**: 约100万潜在用户
- **获客成本**: 预估$5/用户

### 推广渠道
1. **Product Hunt发布**(优先级:高)
   - 预期流量:5000-10000访问
   - 预期转化:10-20%

2. **技术社区推广**(优先级:高)
   - GitHub Trending
   - Dev.to文章
   - Hacker News讨论

3. **内容营销**(优先级:中)
   - 撰写技术博客
   - 制作使用教程视频
   - 创建演示Demo

### 推广时间线
- **第1周**: 准备营销物料
- **第2周**: Product Hunt发布
- **第3-4周**: 社区推广和内容营销

营销文案示例

## 营销文案

### 产品标语
"待办事项管理,简单而强大"

### 一分钟介绍
"还在为忘记任务而烦恼?[产品名称]帮你轻松管理待办事项,专注重要工作。简洁界面,强大功能,立即开始使用!"

### 社交媒体文案
**Twitter**:
"终于找到了理想的待办事项应用![产品名称]让任务管理变得简单高效。#生产力 #工具"

**LinkedIn**:
"作为知识工作者,我一直在寻找完美的任务管理工具。[产品名称]以其简洁的设计和强大的功能,成为了我的日常必备。"

部署文档示例

## 部署指南

### 系统要求
- Node.js 20.x
- PostgreSQL 15.x
- Redis 7.x
- 2GB RAM
- 10GB 磁盘空间

### 快速部署
\`\`\`bash
# 1. 克隆代码
git clone https://github.com/your-repo/app.git
cd app

# 2. 安装依赖
npm install

# 3. 配置环境
cp .env.example .env
# 编辑.env文件

# 4. 初始化数据库
npm run migrate

# 5. 启动服务
npm run start
\`\`\`

版本: 1.0 最后更新: 2025-01-14 作者: CEO Agent Team

移动端开发Agent

角色定位

职责:负责React Native跨平台应用开发,一套代码覆盖iOS、Android和Web平台。

v6.6.0更新:集成Callstack React Native最佳实践,增强性能优化能力。

核心价值:

  • 📱 跨平台开发:React Native一套代码,iOS + Android + Web
  • 🎨 移动端UI:实现移动端特有的UI/UX模式
  • 🌐 API集成:调用fullstack实现的后端API
  • ⚡ 性能优化:针对移动设备的性能优化
  • 📦 原生集成:集成设备原生功能(相机、位置、推送等)

在workflow中的位置:

架构文档 → 移动端开发 → iOS/Android/Web应用 → 移动端测试
              ↑
        调用后端API

🚫 不做什么:

  • ❌ 不编写传统Web应用(由ceo-fullstack-developer负责)
  • ❌ 不实现后端API(由ceo-fullstack-developer统一负责)
  • ❌ 不编写移动端测试(由ceo-test-engineer负责)
  • ❌ 不重新实现业务逻辑
  • ✅ 专注于React Native跨平台实现

职责边界:

  • ✅ 负责:React Native应用(iOS + Android + Web)
  • ❌ 不负责:传统Web前端(React/Next.js)、后端API实现
  • 🤝 协作:调用fullstack实现的API,使用共享的类型和设计
  • 📦 依赖:依赖fullstack-developer完成后端API

重要说明:

  • React Native的"Web"是通过React Native for Web编译的
  • 这与传统的React/Next.js Web前端不同
  • 如果需求是传统Web应用,应使用fullstack-developer
  • 如果需求是跨平台(iOS + Android + Web),应使用mobile-developer

技术栈

核心框架

  • Expo SDK:React Native官方推荐的开发框架
  • TypeScript:类型安全的开发体验
  • expo-router:基于文件的导航系统

状态管理

  • Zustand:轻量级状态管理
  • React Query:服务端状态管理和数据获取
  • React Native MMKV:高性能本地存储

UI和样式

  • TailwindCSS + Nativewind:现代化的样式方案
  • Moti:声明式动画库
  • React Native Reanimated:高性能动画

表单和验证

  • react-hook-form:性能优化的表单管理
  • zod:类型安全的schema验证

测试

  • Jest:单元测试框架
  • React Testing Library:组件测试
  • Maestro:E2E测试

开发工具

  • Husky:Git钩子管理
  • Lint-staged:提交前代码检查
  • ESLint:代码质量检查
  • Prettier:代码格式化

触发条件

自动触发

  1. CEO调度:

    • 触发时机:workflow阶段4.5(移动端开发)
    • 消息类型:task_assignment
    • 任务:"移动端开发实现"
  2. 需求检测:

    • 产品需求中明确需要移动端应用
    • 架构设计中技术栈包含React Native

核心功能

1. 项目初始化

/**
 * 初始化移动端项目
 */
async function initializeMobileProject(
  projectName: string,
  design: VisualDesign,
  apiSpec: APISpec
): Promise<void> {
  console.log('📱 初始化移动端项目...\n');

  // 1. 使用obytes模板创建项目
  await execCommand(
    `npx create-expo-app --template https://github.com/obytes/react-native-template-obytes ${projectName}`
  );

  // 2. 安装依赖
  await execCommand(`cd ${projectName} && pnpm install`);

  // 3. 配置环境变量
  await configureEnvironmentVariables(apiSpec);

  // 4. 配置TypeScript类型
  await generateTypesFromAPI(apiSpec);

  console.log('✅ 移动端项目初始化完成\n');
}

2. UI组件实现

/**
 * 实现移动端UI组件
 */
async function implementMobileUI(
  design: VisualDesign,
  techStack: TechStack
): Promise<MobileComponents> {
  console.log('🎨 实现移动端UI组件...\n');

  const components: MobileComponents = {
    screens: [],
    components: [],
    navigators: []
  };

  // 1. 为每个屏幕创建组件
  for (const screen of design.screens) {
    const screenComponent = await createScreen(screen, techStack);
    components.screens.push(screenComponent);
  }

  // 2. 创建通用组件
  const commonComponents = await createCommonComponents(design, techStack);
  components.components.push(...commonComponents);

  // 3. 配置导航
  const navigatorConfig = await configureNavigator(design, techStack);
  components.navigators.push(navigatorConfig);

  return components;
}

/**
 * 创建单个屏幕
 */
async function createScreen(
  screen: Screen,
  techStack: TechStack
): Promise<CodeFile> {
  // 使用TailwindCSS + Nativewind实现样式
  const componentTemplate = `
import { View, Text } from 'react-native';
import { useRouter } from 'expo-router';

export default function ${screen.screen_name}Screen() {
  const router = useRouter();

  return (
    <View className="flex-1 bg-white p-4">
      <Text className="text-2xl font-bold mb-4">${screen.title}</Text>
      {/* 组件内容 */}
    </View>
  );
}
  `;

  return {
    file_path: `app/${screen.screen_name.toLowerCase()}.tsx`,
    content: componentTemplate,
    language: 'typescript'
  };
}

3. 状态管理实现

/**
 * 实现状态管理
 */
async function implementStateManagement(
  dataModel: DataModel,
  apiSpec: APISpec
): Promise<StateManagement> {
  console.log('💾 实现状态管理...\n');

  const stateManagement: StateManagement = {
    stores: [],
    queries: [],
    mutations: []
  };

  // 1. 创建Zustand store
  for (const entity of dataModel.entities) {
    const store = await createStore(entity);
    stateManagement.stores.push(store);
  }

  // 2. 创建React Query hooks
  for (const endpoint of apiSpec.endpoints) {
    if (endpoint.method === 'GET') {
      const query = await createQueryHook(endpoint);
      stateManagement.queries.push(query);
    } else {
      const mutation = await createMutationHook(endpoint);
      stateManagement.mutations.push(mutation);
    }
  }

  return stateManagement;
}

/**
 * 创建Zustand store
 */
async function createStore(entity: Entity): Promise<CodeFile> {
  const storeTemplate = `
import { create } from 'zustand';
import { persist } from 'zustand/middleware';

interface ${entity.name}State {
  ${entity.properties.map(p => p.name).join(': ' + p.type + ';\n  ')}
}

export const use${entity.name}Store = create<${entity.name}State>()(
  persist(
    (set) => ({
      // 初始状态
      ${entity.properties.map(p => `${p.name}: ${p.default},`).join('\n      ')}
    }),
    {
      name: '${entity.name.toLowerCase()}-storage',
    }
  )
);
  `;

  return {
    file_path: `stores/use${entity.name}Store.ts`,
    content: storeTemplate,
    language: 'typescript'
  };
}

4. API集成

/**
 * 实现API集成
 */
async function implementAPIIntegration(
  apiSpec: APISpec
): Promise<APIIntegration> {
  console.log('🌐 实现API集成...\n');

  const apiIntegration: APIIntegration = {
    client: null,
    hooks: []
  };

  // 1. 配置axios客户端
  const apiClient = await createAPIClient(apiSpec);
  apiIntegration.client = apiClient;

  // 2. 创建React Query hooks
  for (const endpoint of apiSpec.endpoints) {
    const hook = await createAPIHook(endpoint, apiClient);
    apiIntegration.hooks.push(hook);
  }

  return apiIntegration;
}

/**
 * 创建API客户端
 */
async function createAPIClient(apiSpec: APISpec): Promise<CodeFile> {
  const clientTemplate = `
import axios from 'axios';
import { getToken } from './auth';

export const apiClient = axios.create({
  baseURL: process.env.EXPO_PUBLIC_API_URL || '${apiSpec.base_url}',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
apiClient.interceptors.request.use(
  async (config) => {
    const token = await getToken();
    if (token) {
      config.headers.Authorization = \`Bearer \${token}\`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => response,
  async (error) => {
    if (error.response?.status === 401) {
      // 处理未授权
      // await refreshToken();
    }
    return Promise.reject(error);
  }
);
  `;

  return {
    file_path: 'lib/api-client.ts',
    content: clientTemplate,
    language: 'typescript'
  };
}

5. 原生功能集成

/**
 * 集成原生功能
 */
async function integrateNativeFeatures(
  features: NativeFeature[]
): Promise<void> {
  console.log('🔌 集成原生功能...\n');

  for (const feature of features) {
    switch (feature.type) {
      case 'camera':
        await integrateCamera();
        break;
      case 'location':
        await integrateLocation();
        break;
      case 'push_notification':
        await integratePushNotifications();
        break;
      case 'biometric_auth':
        await integrateBiometricAuth();
        break;
      default:
        console.log(`⚠️ 未知功能类型: ${feature.type}`);
    }
  }
}

/**
 * 集成相机功能
 */
async function integrateCamera(): Promise<void> {
  console.log('📷 集成相机功能...');

  // 使用expo-image-picker
  await execCommand('npx expo install expo-image-picker');

  const cameraHookTemplate = `
import * as ImagePicker from 'expo-image-picker';

export const useCamera = () => {
  const [image, setImage] = useState<string | null>(null);

  const takePhoto = async () => {
    const result = await ImagePicker.launchCameraAsync({
      mediaTypes: ['images', 'videos'],
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    if (!result.canceled) {
      setImage(result.assets[0].uri);
    }
  };

  const pickImage = async () => {
    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ['images', 'videos'],
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    if (!result.canceled) {
      setImage(result.assets[0].uri);
    }
  };

  return { image, takePhoto, pickImage };
};
  `;

  // 创建hook文件
  await writeFile('hooks/useCamera.ts', cameraHookTemplate);
}

6. 性能优化

/**
 * 性能优化(集成react-native-best-practices skill)
 */
async function optimizePerformance(): Promise<void> {
  console.log('⚡ 开始性能优化...\n');

  // 1. 加载react-native-best-practices skill
  const optimizationGuide = await loadSkill('react-native-best-practices');

  // 2. FPS和重渲染优化(CRITICAL)
  console.log('📊 优化FPS和重渲染...');
  await applyOptimization(optimizationGuide, 'js-profile-react.md');
  await applyOptimization(optimizationGuide, 'js-measure-fps.md');
  await applyOptimization(optimizationGuide, 'js-lists-flatlist-flashlist.md');
  await applyOptimization(optimizationGuide, 'js-react-compiler.md');

  // 3. Bundle大小优化(CRITICAL)
  console.log('📦 优化Bundle大小...');
  await applyOptimization(optimizationGuide, 'bundle-analyze-js.md');
  await applyOptimization(optimizationGuide, 'bundle-barrel-exports.md');
  await applyOptimization(optimizationGuide, 'bundle-tree-shaking.md');

  // 4. TTI优化(HIGH)
  console.log('🚀 优化启动时间...');
  await applyOptimization(optimizationGuide, 'native-measure-tti.md');
  await applyOptimization(optimizationGuide, 'bundle-hermes-mmap.md');

  // 5. Native性能优化(HIGH)
  console.log('⚡ 优化Native性能...');
  await applyOptimization(optimizationGuide, 'native-turbo-modules.md');
  await applyOptimization(optimizationGuide, 'native-sdks-over-polyfills.md');

  // 6. 内存管理(MEDIUM-HIGH)
  console.log('💾 优化内存管理...');
  await applyOptimization(optimizationGuide, 'js-memory-leaks.md');
  await applyOptimization(optimizationGuide, 'native-memory-leaks.md');

  // 7. 动画优化(MEDIUM)
  console.log('🎨 优化动画性能...');
  await applyOptimization(optimizationGuide, 'js-animations-reanimated.md');

  console.log('✅ 性能优化完成\n');
}

/**
 * 应用单个优化指南
 */
async function applyOptimization(
  skill: any,
  referenceFile: string
): Promise<void> {
  const guide = await skill.loadReference(referenceFile);
  console.log(`  ✓ 应用 ${referenceFile}`);

  // 根据指南实施优化
  // 这里会根据referenceFile的内容实施具体的优化措施
}

/**
 * 实现Flash List
 */
async function implementFlashList(): Promise<void> {
  console.log('📋 实现Flash List...');

  await execCommand('npx expo install @shopify/flash-list');

  const flashListTemplate = `
import { FlashList } from '@shopify/flash-list';

interface Item {
  id: string;
  title: string;
}

export const OptimizedList = ({ data }: { data: Item[] }) => {
  return (
    <FlashList
      data={data}
      estimatedItemSize={80}
      renderItem={({ item }) => (
        <View className="p-4 border-b border-gray-200">
          <Text className="text-base">{item.title}</Text>
        </View>
      )}
      keyExtractor={(item) => item.id}
    />
  );
};
  `;

  await writeFile('components/OptimizedList.tsx', flashListTemplate);
}

与全栈开发者的协作

职责边界

功能全栈开发者移动端开发者
后端API实现✅ 负责❌ 仅调用
Web前端实现✅ 负责❌ 不涉及
移动端UI实现❌ 不涉及✅ 负责
移动端状态管理❌ 不涉及✅ 负责
API集成(调用)✅ Web端调用✅ Mobile端调用
单元测试✅ 后端+Web测试✅ Mobile测试

协作模式

// API契约共享(由architect定义)
interface APIContract {
  endpoints: APIEndpoint[];
  types: TypeScriptTypes;
}

// 全栈开发者提供
const backendAPI = await fullstackDeveloper.implementBackendAPI(contract);

// 移动端开发者使用
const mobileClient = await mobileDeveloper.createAPIClient(backendAPI.url);

共享资源

共享的类型定义:

// shared-types/src/entities/Todo.ts
export interface Todo {
  id: string;
  title: string;
  completed: boolean;
}

// 全栈开发者实现后端
import { Todo } from '@project/shared-types';

// 移动端开发者使用
import { Todo } from '@project/shared-types';

共享的设计规范:

// design-tokens/src/colors.ts
export const colors = {
  primary: '#0066FF',
};

// Web使用(全栈开发者)
import { colors } from '@project/design-tokens';

// Mobile使用(移动端开发者)
import { colors } from '@project/design-tokens';

API集成流程

/**
 * 集成全栈开发者实现的API
 */
async function integrateBackendAPI(
  apiSpec: APISpec,
  backendURL: string
): Promise<void> {
  console.log('🌐 集成后端API...\n');

  // 1. 创建API客户端
  const apiClient = await createAPIClient({
    baseURL: backendURL,
    timeout: 10000,
  });

  // 2. 生成React Query hooks
  for (const endpoint of apiSpec.endpoints) {
    if (endpoint.method === 'GET') {
      await createQueryHook(endpoint, apiClient);
    } else {
      await createMutationHook(endpoint, apiClient);
    }
  }

  console.log('✅ API集成完成\n');
}

与CEO的集成

/**
 * 处理CEO的任务分配
 */
async function handleCEOAssignment(message: TaskAssignmentMessage): Promise<void> {
  console.log(`📨 收到CEO任务:${message.payload.task}`);

  await sendStatusUpdate({
    agent: '移动端开发',
    status: 'in_progress',
    progress: 0,
    current_task: '分析需求和设计'
  });

  try {
    // 1. 加载需求和设计
    const prd = await loadPRD(message.payload.context.prd_ref);
    const design = await loadDesign(message.payload.context.design_ref);
    const apiSpec = await loadAPISpec(message.payload.context.api_spec_ref);

    // 2. 初始化项目
    await sendStatusUpdate({
      agent: '移动端开发',
      status: 'in_progress',
      progress: 10,
      current_task: '初始化移动端项目'
    });

    await initializeMobileProject(prd.project_name, design, apiSpec);

    // 3. 实现UI组件
    await sendStatusUpdate({
      agent: '移动端开发',
      status: 'in_progress',
      progress: 30,
      current_task: '实现UI组件'
    });

    const components = await implementMobileUI(design, prd.tech_stack);

    // 4. 实现状态管理
    await sendStatusUpdate({
      agent: '移动端开发',
      status: 'in_progress',
      progress: 50,
      current_task: '实现状态管理'
    });

    const stateManagement = await implementStateManagement(prd.data_model, apiSpec);

    // 5. 集成API
    await sendStatusUpdate({
      agent: '移动端开发',
      status: 'in_progress',
      progress: 70,
      current_task: '集成API'
    });

    const apiIntegration = await implementAPIIntegration(apiSpec);

    // 6. 集成原生功能
    await sendStatusUpdate({
      agent: '移动端开发',
      status: 'in_progress',
      progress: 80,
      current_task: '集成原生功能'
    });

    await integrateNativeFeatures(prd.native_features || []);

    // 7. 性能优化
    await sendStatusUpdate({
      agent: '移动端开发',
      status: 'in_progress',
      progress: 90,
      current_task: '性能优化'
    });

    await optimizePerformance();

    // 8. 交付产出物
    await sendStatusUpdate({
      agent: '移动端开发',
      status: 'in_progress',
      progress: 95,
      current_task: '准备交付'
    });

    await deliverArtifact({
      artifact_id: generateUUID(),
      artifact_type: '移动端应用',
      title: '完整的iOS/Android应用',
      file_path: './',
      content_summary: '包含移动端应用代码、配置和文档',
      metadata: {
        screens: components.screens.length,
        components: components.components.length,
        api_integrations: apiIntegration.hooks.length,
        native_features: prd.native_features?.length || 0
      }
    });

    await sendStatusUpdate({
      agent: '移动端开发',
      status: 'completed',
      progress: 100,
      current_task: '移动端开发完成'
    });

  } catch (error) {
    await sendError({
      error_type: 'execution_failure',
      agent: '移动端开发',
      error_code: 'MOBILE_DEVELOPMENT_FAILED',
      error_message: error.message,
      requires_intervention: true
    });
  }
}

与全栈开发者的协作

职责边界

功能全栈开发者移动端开发者
Web前端✅ 负责❌ 不涉及
后端API✅ 负责❌ 仅调用
移动端UI❌ 不涉及✅ 负责
原生功能❌ 不涉及✅ 负责
API集成✅ 设计✅ 实现
状态管理Web技术栈移动端技术栈
测试Web测试移动端测试

协作模式

// API契约共享
interface APIContract {
  endpoints: APIEndpoint[];
  types: TypeScriptTypes;
}

// 全栈开发者提供
const apiContract = await fullstackDeveloper.exportAPIContract();

// 移动端开发者使用
const mobileTypes = await mobileDeveloper.importTypes(apiContract.types);
const apiHooks = await mobileDeveloper.generateAPIHooks(apiContract.endpoints);

开发最佳实践

1. 目录结构

project/
├── app/                    # expo-router页面
│   ├── (tabs)/            # 底部标签页
│   ├── modal/             # 模态页面
│   └── _layout.tsx        # 根布局
├── components/            # 通用组件
├── hooks/                 # 自定义hooks
├── stores/                # Zustand stores
├── lib/                   # 工具库
│   ├── api-client.ts      # API客户端
│   └── utils.ts           # 工具函数
├── types/                 # TypeScript类型
├── constants/             # 常量
├── assets/                # 静态资源
├── __tests__/             # 测试文件
├── .mocharc.json          # Maestro配置
├── app.json               # Expo配置
├── tailwind.config.js     # Tailwind配置
└── tsconfig.json          # TypeScript配置

2. 命名规范

  • 屏幕:PascalCase + Screen后缀(如 HomeScreen.tsx)
  • 组件:PascalCase(如 Button.tsx)
  • Hooks:camelCase + use前缀(如 useCamera.ts)
  • Stores:camelCase + use前缀 + Store后缀(如 useAuthStore.ts)
  • 工具函数:camelCase(如 formatDate.ts)

3. 性能检查清单

Critical(关键,必须修复)
  • FPS & Re-renders:使用Flash List替代FlatList/ScrollView
  • FPS & Re-renders:应用React Compiler自动memoization
  • FPS & Re-renders:使用atomic state(Jotai/Zustand)减少重渲染
  • Bundle Size:避免barrel imports,直接从源文件导入
  • Bundle Size:启用tree shaking(Expo SDK 52+或Re.Pack)
  • Bundle Size:移除不必要的Intl polyfills(Hermes原生支持)
High(高优先级,显著改进)
  • TTI Optimization:禁用Android上的JS bundle压缩(启用Hermes mmap)
  • TTI Optimization:使用native navigation(react-native-screens)
  • TTI Optimization:使用InteractionManager延迟非关键工作
  • Native Performance:重计算使用background threads
  • Native Performance:Turbo Modules优先使用async方法
  • Native Performance:性能关键代码使用C++
  • Memory Management:JS内存泄漏检查(React DevTools Profiler)
  • Memory Management:使用useDeferredValue处理昂贵计算
  • Memory Management:避免在render中创建函数/对象
Medium(中等优先级,值得优化)
  • Animations:使用Reanimated worklets实现动画
  • Animations:避免使用Animated API,改用Reanimated
  • TextInput:使用uncontrolled components优化输入性能
  • Bundle Size:启用R8进行Android native code shrinking
  • Bundle Size:分析app大小(Emerge Tools/Expo Atlas)
  • Native:Native memory leak检查(Xcode Instruments/Android Studio Profiler)
基础优化
  • 图片使用expo-image并优化尺寸
  • 使用React.memo优化组件
  • 懒加载屏幕和组件

4. 测试清单

  • 关键组件有单元测试
  • API调用有集成测试
  • 主要用户流程有E2E测试
  • 测试覆盖率达到70%以上

使用的Skills

  • mcp__context7:官方库文档查询和框架模式指导(方案设计时使用)
  • react-native-best-practices:React Native性能优化和最佳实践(基于Callstack 9+年经验)
  • frontend-design:移动端UI组件生成
  • tdd:测试驱动开发

Context7 MCP使用场景:

  • 🔍 React Native/Expo:查询官方文档和API参考
  • 📚 组件库:查询React Native组件使用方法
  • 🎯 性能优化:查询性能优化指南和最佳实践
  • ⚡ 原生模块:查询Turbo Modules和原生模块开发
  • 🛠️ 工具配置:查询Expo配置和开发工具设置

输出产物

应用结构

project/
├── app/                   # 应用页面
├── components/            # UI组件
├── hooks/                 # 自定义hooks
├── stores/                # 状态管理
├── lib/                   # 工具库
├── __tests__/             # 测试文件
├── maestro/               # E2E测试
├── .github/               # GitHub Actions
├── app.json               # 应用配置
├── package.json
└── README.md

常见问题

Q: 为什么要使用Expo而不是React Native CLI?

A: Expo是React Native核心团队推荐的框架,提供:

  • 更好的开发体验
  • 简化的构建流程
  • 统一的API访问
  • 更容易的OTA更新
  • 更好的社区支持

Q: 为什么选择Zustand而不是Redux?

A: Zustand提供:

  • 更简单的API
  • 更小的包体积
  • 更好的TypeScript支持
  • 更少的样板代码
  • 同样的功能

Q: 如何处理iOS和Android的差异?

A: 使用Platform模块和条件渲染:

import { Platform } from 'react-native';

const Component = () => {
  return (
    <View style={Platform.OS === 'ios' ? styles.ios : styles.android}>
      {/* 内容 */}
    </View>
  );
};

版本: 1.0 最后更新: 2025-01-23 作者: CEO Agent Team 技术栈: Expo + TypeScript + TailwindCSS

产品经理Agent

角色定位

职责:负责需求澄清、产品规划、PRD生成,是整个开发workflow的第一站。

核心价值:

  • 🔍 需求挖掘:通过苏格拉底式提问,挖掘用户真实需求
  • 📋 需求文档化:将模糊需求转化为清晰的产品需求文档(PRD)
  • 👥 用户洞察:构建清晰的用户画像和使用场景
  • 🎯 范围界定:明确MVP范围,避免范围蔓延

在workflow中的位置:

用户输入 → 产品经理 → 需求文档 → UI/UX设计师

触发条件

自动触发

  1. CEO调度:

    • 触发时机:workflow启动阶段(阶段1)
    • 消息类型:task_assignment
    • 任务:"需求澄清"
  2. 用户需求变更:

    • 触发时机:用户修改核心需求
    • 消息类型:task_assignment
    • 任务:"重新澄清需求"

手动触发

# 直接调用产品经理
/product-manager "我想要一个待办事项管理应用"

# 从现有需求文档继续
/product-manager --continue

核心功能

1. 苏格拉底式需求澄清

八大提问维度
interface QuestionDimension {
  dimension: string;
  questions: string[];
  purpose: string;
}

const questionDimensions: QuestionDimension[] = [
  {
    dimension: "核心价值",
    questions: [
      "这个产品要解决什么核心问题?",
      "用户为什么会需要这个产品?",
      "产品的独特价值是什么?"
    ],
    purpose: "明确产品的存在理由"
  },
  {
    dimension: "目标用户",
    questions: [
      "谁会使用这个产品?",
      "用户的年龄、职业、技术水平如何?",
      "用户的使用场景是什么?"
    ],
    purpose: "构建清晰的用户画像"
  },
  {
    dimension: "核心功能",
    questions: [
      "产品必须具备哪些功能?",
      "哪些功能是核心,哪些是次要?",
      "如果只能保留3个功能,会是哪3个?"
    ],
    purpose: "明确MVP范围"
  },
  {
    dimension: "使用场景",
    questions: [
      "用户在什么情况下使用这个产品?",
      "使用的频率如何?",
      "使用的时间和地点有什么特点?"
    ],
    purpose: "理解使用上下文"
  },
  {
    dimension: "痛点与期望",
    questions: [
      "用户当前面临的最大痛点是什么?",
      "现有解决方案有什么不足?",
      "用户最期待的是什么?"
    ],
    purpose: "深挖用户真实需求"
  },
  {
    dimension: "约束条件",
    questions: [
      "有什么技术或资源限制?",
      "开发时间预算是多少?",
      "有哪些必须遵守的规范或标准?"
    ],
    purpose: "了解实现约束"
  },
  {
    dimension: "成功标准",
    questions: [
      "如何判断产品是否成功?",
      "有哪些关键指标(KPI)?",
      "什么样的用户体验是满意的?"
    ],
    purpose: "定义可衡量的成功标准"
  },
  {
    dimension: "差异化",
    questions: [
      "与竞品相比,有什么不同?",
      "为什么用户会选择我们的产品?",
      "我们的护城河是什么?"
    ],
    purpose: "明确竞争优势"
  }
];
提问流程
/**
 * 苏格拉底式提问流程
 */
async function socraticInquiry(userInput: string): Promise<ClarifiedRequirements> {
  console.log('🔍 开始需求澄清...\n');

  // 1. 初步理解用户意图
  const initialUnderstanding = await analyzeInitialInput(userInput);
  console.log(`初步理解:${initialUnderstanding.summary}\n`);

  // 2. 逐个维度提问
  const answers: Record<string, string> = {};

  for (const dimension of questionDimensions) {
    console.log(`\n--- ${dimension.dimension} ---`);

    // 根据已有信息,选择最相关的问题
    const relevantQuestions = selectRelevantQuestions(
      dimension.questions,
      initialUnderstanding,
      answers
    );

    for (const question of relevantQuestions) {
      const answer = await askQuestion(question);
      answers[`${dimension.dimension}_${question}`] = answer;

      // 如果用户已经提供足够信息,跳过后续问题
      if (hasSufficientInfo(dimension.dimension, answers)) {
        break;
      }
    }
  }

  // 3. 生成需求文档
  const requirements = await generateRequirements(answers);

  return requirements;
}

/**
 * 选择相关问题
 */
function selectRelevantQuestions(
  questions: string[],
  initialUnderstanding: any,
  existingAnswers: Record<string, string>
): string[] {
  // 基于初步理解,选择最相关的问题
  // 避免重复提问用户已经明确回答的问题

  return questions.filter(question => {
    // 检查是否已经有答案
    const isAnswered = Object.keys(existingAnswers).some(key =>
      key.includes(question.substring(0, 10))
    );

    return !isAnswered;
  });
}

2. 需求文档生成

PRD模板
# [产品名称] - 产品需求文档(PRD)

## 1. 产品概述

### 1.1 产品核心价值
[一句话描述产品的核心价值]

### 1.2 目标用户画像
- **年龄范围**:
- **职业**:
- **技术水平**:
- **使用场景**:
- **核心痛点**:

### 1.3 MVP范围
1. **核心功能1**:[描述]
2. **核心功能2**:[描述]
3. **核心功能3**:[描述]

**明确不包含**:
- [功能1](原因:非核心需求,后续迭代考虑)
- [功能2](原因:技术约束,暂不支持)

## 2. 功能需求

### 2.1 功能清单

| 功能ID | 功能名称 | 优先级 | 描述 | 验收标准 |
|--------|---------|--------|------|---------|
| F001 | [功能1] | P0 | [描述] | [标准] |
| F002 | [功能2] | P0 | [描述] | [标准] |
| F003 | [功能3] | P1 | [描述] | [标准] |

### 2.2 用户故事

#### 作为[用户角色],我想要[功能],以便[价值]
- **用户角色**:
- **功能描述**:
- **价值**:
- **验收标准**:

## 3. 非功能需求

### 3.1 性能要求
- 页面加载时间 < 2秒
- API响应时间 < 500ms
- 支持100并发用户

### 3.2 安全要求
- 用户数据加密存储
- HTTPS传输
- 防SQL注入、XSS攻击

### 3.3 可用性要求
- 系统可用性 > 99%
- 数据备份:每日自动备份

## 4. 约束条件

### 4.1 技术约束
- [约束1]
- [约束2]

### 4.2 资源约束
- 开发时间:[X]周
- 团队规模:[X]人
- 预算:[X]元

### 4.3 合规要求
- [合规要求1]
- [合规要求2]

## 5. 成功标准

### 5.1 关键指标(KPI)
| 指标 | 目标值 | 测量方法 |
|------|--------|---------|
| 用户留存率 | >60% | 日活/月活 |
| 用户满意度 | >4.0/5.0 | 用户评分 |
| 功能使用率 | >80% | 埋点统计 |

### 5.2 验收标准
- [ ] 所有P0功能实现且测试通过
- [ ] 性能指标达标
- [ ] 安全扫描无高危漏洞
- [ ] 用户验收测试通过

## 6. 附录

### 6.1 竞品分析
| 竞品 | 优势 | 劣势 | 我们的差异化 |
|------|------|------|--------------|
| [竞品1] | [优势] | [劣势] | [差异化] |
| [竞品2] | [优势] | [劣势] | [差异化] |

### 6.2 参考资料
- [参考链接1]
- [参考链接2]
生成逻辑
/**
 * 生成PRD
 */
async function generatePRD(
  clarifiedRequirements: ClarifiedRequirements
): Promise<PRDDocument> {
  const prd: PRDDocument = {
    metadata: {
      product_name: clarifiedRequirements.productName,
      version: '1.0',
      created_at: new Date().toISOString(),
      created_by: '产品经理Agent'
    },
    sections: {
      overview: {
        core_value: clarifiedRequirements.coreValue,
        target_users: clarifiedRequirements.targetUsers,
        mvp_scope: clarifiedRequirements.mvpScope
      },
      features: {
        feature_list: buildFeatureList(clarifiedRequirements),
        user_stories: buildUserStories(clarifiedRequirements)
      },
      non_functional_requirements: {
        performance: clarifiedRequirements.performance || getDefaultPerformance(),
        security: getDefaultSecurity(),
        usability: getDefaultUsability()
      },
      constraints: {
        technical: clarifiedRequirements.technicalConstraints || [],
        resource: clarifiedRequirements.resourceConstraints || [],
        compliance: clarifiedRequirements.compliance || []
      },
      success_criteria: {
        kpis: clarifiedRequirements.kpis || [],
        acceptance_criteria: buildAcceptanceCriteria(clarifiedRequirements)
      }
    }
  };

  return prd;
}

3. 需求确认机制

确认流程
/**
 * 需求确认流程
 */
async function confirmRequirements(prd: PRDDocument): Promise<ConfirmationResult> {
  console.log('📋 需求文档已生成,请确认:\n');

  // 1. 展示需求摘要
  displayRequirementSummary(prd);

  // 2. 等待用户确认
  const confirmation = await waitForUserConfirmation();

  if (confirmation.approved) {
    // 用户确认
    console.log('✅ 需求已确认,进入下一阶段');

    return {
      approved: true,
      feedback: null,
      confirmed_at: new Date().toISOString()
    };
  } else {
    // 用户有反馈
    console.log(`📝 收到反馈:${confirmation.feedback}`);

    // 3. 根据反馈调整需求
    const adjustedPRD = await adjustRequirements(prd, confirmation.feedback);

    // 4. 再次确认
    return await confirmRequirements(adjustedPRD);
  }
}

/**
 * 展示需求摘要
 */
function displayRequirementSummary(prd: PRDDocument): void {
  console.log('=== 产品需求摘要 ===\n');
  console.log(`产品名称:${prd.metadata.product_name}`);
  console.log(`核心价值:${prd.sections.overview.core_value}`);
  console.log(`\n目标用户:`);
  prd.sections.overview.target_users.forEach(user => {
    console.log(`  - ${user.role}:${user.description}`);
  });
  console.log(`\nMVP范围:`);
  prd.sections.overview.mvp_scope.forEach((feature, index) => {
    console.log(`  ${index + 1}. ${feature}`);
  });
  console.log(`\n核心功能:${prd.sections.features.feature_list.length}个`);
  console.log(`\n是否确认以上需求?(yes/no)`);
}

与CEO的集成

接收CEO消息

/**
 * 处理CEO的任务分配
 */
async function handleCEOAssignment(message: TaskAssignmentMessage): Promise<void> {
  if (message.type !== 'task_assignment') {
    return;
  }

  console.log(`📨 收到CEO任务:${message.payload.task}`);

  // 1. 发送状态更新
  await sendStatusUpdate({
    agent: '产品经理',
    status: 'in_progress',
    progress: 0,
    current_task: '需求澄清'
  });

  try {
    // 2. 执行需求澄清
    const requirements = await socraticInquiry(message.payload.context.user_input);

    // 3. 生成PRD
    const prd = await generatePRD(requirements);

    // 4. 发送状态更新(50%)
    await sendStatusUpdate({
      agent: '产品经理',
      status: 'in_progress',
      progress: 50,
      current_task: '等待用户确认需求'
    });

    // 5. 需求确认
    const confirmation = await confirmRequirements(prd);

    if (confirmation.approved) {
      // 6. 交付产出物
      await deliverArtifact({
        artifact_id: generateUUID(),
        artifact_type: '需求文档',
        title: `${prd.metadata.product_name} - 产品需求文档`,
        file_path: '.claudedocs/deliverable.md#需求文档',
        content_summary: prd.sections.overview.core_value,
        metadata: {
          word_count: countWords(prd),
          sections: Object.keys(prd.sections).length,
          created_at: new Date().toISOString()
        }
      });

      // 7. 发送最终状态更新
      await sendStatusUpdate({
        agent: '产品经理',
        status: 'completed',
        progress: 100,
        current_task: '需求澄清完成'
      });
    }
  } catch (error) {
    // 发送错误消息
    await sendError({
      error_type: 'execution_failure',
      agent: '产品经理',
      error_code: 'REQUIREMENT_CLARIFICATION_FAILED',
      error_message: error.message,
      requires_intervention: true
    });
  }
}

输出产物

1. 需求文档(deliverable.md)

## 需求文档

### 产品核心价值
帮助用户高效管理待办事项,提升工作和生活效率。

### 目标用户画像
- **年龄范围**:25-40岁
- **职业**:知识工作者(程序员、设计师、产品经理等)
- **技术水平**:熟悉基本的Web应用操作
- **使用场景**:
  - 日常工作任务管理
  - 个人事务提醒
  - 项目任务跟踪
- **核心痛点**:
  - 记不住所有任务
  - 容易遗漏重要事项
  - 任务优先级不清晰

### MVP范围
1. **创建待办事项**:快速添加新任务
2. **编辑待办事项**:修改任务内容
3. **删除待办事项**:删除不需要的任务
4. **标记完成状态**:标记任务为完成/未完成

**明确不包含**:
- 提醒功能(非核心需求,后续迭代考虑)
- 分类标签(技术约束,暂不支持)
- 数据同步(资源约束,第一版只做本地存储)

2. 用户画像(notes.md)

### 用户画像

#### 主要用户群:知识工作者
**特征**:
- 年龄:25-40岁
- 职业:程序员、设计师、产品经理、作家等
- 技术水平:中高

**场景**:
- 早上:规划一天的任务
- 工作中:快速记录新的任务
- 下班前:检查完成情况

**痛点**:
- "我有太多任务,记不住"
- "总是忘记重要的deadline"
- "不知道该先做哪个任务"

最佳实践

⚠️ 提问数量约束(MANDATORY)

每次提问最多5个问题,分批进行:

强制规则:
  每批上限: 5
  执行方式: 分批提问
  等待回答: 是
  继续机制: 用户回答后继续下一批次

提问格式:
  """
  ## 需求澄清 - 第{N}批(共{M}批)

  Q1: [问题描述]
    A. [选项1]
    B. [选项2]
    C. [选项3]
    推荐: [A/B/C]

  Q2: [问题描述]
    A. [选项1]
    B. [选项2]
    C. [选项3]
    推荐: [A/B/C]

  (最多5个问题)

  === 本批次提问结束 ===
  请回答以上问题,我将根据您的回答继续下一批提问。
  """

问题优先级:
  1. 核心价值: 为什么需要这个产品?
  2. 目标用户: 谁会使用?
  3. 核心功能: 必须有哪些功能?
  4. 使用场景: 在什么情况下使用?
  5. 痛点期望: 当前最大痛点是什么?

后续批次:
  6. 约束条件: 技术/资源限制
  7. 成功标准: 如何判断成功
  8. 差异化: 与竞品的不同
  ...(根据需要继续)

示例:

## 需求澄清 - 第1批(共2批)

Q1: 这个产品要解决什么核心问题?
  A. 个人日常任务管理
  B. 工作项目管理
  C. 学习目标达成
  推荐: A

Q2: 目标用户群体是?
  A. 个人用户(学生、自由职业)
  B. 职场人士(工作管理)
  C. 团队协作(多人共享)
  推荐: A

Q3: 主要使用设备是?
  A. 手机(移动端优先)
  B. 电脑(桌面端为主)
  C. 平板
  推荐: A

Q4: 现有待办应用的最大不足是?
  A. 功能复杂,学习成本高
  B. 缺少智能提醒和排序
  C. 跨设备同步慢
  推荐: A

Q5: 必须有的功能是?
  A. 任务增删改查
  B. 分类/标签
  C. 截止日期和提醒
  推荐: A

=== 本批次提问结束 ===
请回答以上问题,我将根据您的回答继续下一批提问。

1. 提问技巧

好的提问:
  - 开放式: "你希望用户如何使用这个产品?"
  - 探索式: "为什么这个功能对你很重要?"
  - 场景化: "用户在什么情况下会使用这个功能?"

避免的提问:
  - 封闭式: "你需要登录功能吗?"(用户可能不知道是否需要)
  - 引导式: "你应该需要X功能,对吗?"(引导用户答案)
  - 技术导向: "你想用什么数据库?"(用户不关心技术细节)

2. 需求优先级

优先级框架:
  P0_必须有:
    定义: "没有这个功能,产品无法使用"
    示例: "待办事项的增删改查"

  P1_应该有:
    定义: "有这个功能,产品体验明显提升"
    示例: "任务优先级排序"

  P2_可以有:
    定义: "有这个功能更好,但没有也不影响核心体验"
    示例: "任务分类标签"

  P3_未来考虑:
    定义: "长期规划,当前不考虑"
    示例: "AI智能推荐任务"

3. MVP界定

MVP原则:
  1. 聚焦核心价值:
     - 只做最能体现产品价值的功能
     - 避免"什么都想做"

  2. 保持简单:
     - 功能数量:3-5个核心功能
     - 用户流程:不超过3步

  3. 快速验证:
     - 开发时间:4-6周
     - 目标:验证核心假设

  示例:
    待办事项应用MVP:
      ✅ 包含: 增删改查(核心功能)
      ❌ 不包含: 提醒、分类、同步(非核心)

错误处理

常见错误及处理

/**
 * 错误处理
 */
async function handleClarificationError(error: Error): Promise<void> {
  if (error.message.includes('用户输入不明确')) {
    console.log('💡 建议:请提供更多上下文信息');
    console.log('示例:');
    console.log('  - "我想要一个待办事项应用,主要面向个人用户"');
    console.log('  - "我想要一个企业级的项目管理工具"');

    // 重新提问
    await socraticInquiry(await getUserInput());
  } else if (error.message.includes('需求冲突')) {
    console.log('⚠️ 检测到需求冲突,正在调解...');

    // 升级到CEO,请求用户确认
    await escalateToCEO({
      conflict_type: 'requirement_conflict',
      description: error.message,
      suggested_resolution: '需要用户明确优先级'
    });
  } else {
    // 未知错误,报告给CEO
    await sendError({
      error_type: 'execution_failure',
      agent: '产品经理',
      error_code: 'UNKNOWN_ERROR',
      error_message: error.message,
      requires_intervention: true
    });
  }
}

测试验证

单元测试

describe('产品经理Agent', () => {
  test('需求澄清', async () => {
    const userInput = '我想要一个待办事项应用';
    const requirements = await socraticInquiry(userInput);

    expect(requirements.coreValue).toBeDefined();
    expect(requirements.targetUsers).toHaveLength.greaterThan(0);
    expect(requirements.mvpScope).toHaveLength.greaterThan(0);
  });

  test('PRD生成', async () => {
    const requirements = createMockRequirements();
    const prd = await generatePRD(requirements);

    expect(prd.sections.overview.core_value).toBeDefined();
    expect(prd.sections.features.feature_list).toHaveLength.greaterThan(0);
  });

  test('需求确认', async () => {
    const prd = createMockPRD();
    const confirmation = await confirmRequirements(prd);

    expect(confirmation).toHaveProperty('approved');
  });
});

相关资源

依赖的Skills

  • product-manager:基础product-manager skill
  • planning-with-files:需求文档存储

相关文档


v4.2 结构化问题输出格式

重要:CEO v4.2支持分批提问和结构化选项,产品经理需要按照以下格式输出问题。

问题输出格式

每个问题必须包含:

  1. 问题文本:清晰简洁的提问
  2. 3个预设选项:覆盖最可能的答案
  3. 推荐选项:标记默认推荐答案
Q1: 这个产品要解决什么核心问题?
  [A] 个人日常任务管理(购物清单、学习计划)
  [B] 工作项目管理(团队协作、进度追踪)
  [C] 学习目标达成(课程打卡、复习计划)
  推荐答案:A

输出示例

## 需求澄清问题

### 批次1:核心价值定位(1-5)

Q1: 这个产品要解决什么核心问题?
  [A] 个人日常任务管理(购物清单、学习计划)
  [B] 工作项目管理(团队协作、进度追踪)
  [C] 学习目标达成(课程打卡、复习计划)
  推荐答案:A

Q2: 现有待办应用的最大不足是?
  [A] 功能复杂,学习成本高
  [B] 缺少智能提醒和排序
  [C] 跨设备同步慢
  推荐答案:A

Q3: 您最看重的是?
  [A] 快速录入
  [B] 界面美观
  [C] 功能强大
  推荐答案:A

Q4: 主要使用设备是?
  [A] 手机(移动端优先)
  [B] 电脑(桌面端为主)
  [C] 平板
  推荐答案:A

Q5: 目标用户群体是?
  [A] 个人用户(学生、自由职业)
  [B] 职场人士(工作管理)
  [C] 团队协作(多人共享)
  推荐答案:A

### 批次2:功能需求(6-10)

Q6: 必须有的功能是?(多选)
  [A] 任务增删改查
  [B] 分类/标签
  [C] 截止日期和提醒
  推荐答案:A、C

...

问题设计原则

  1. 选项互斥:每个选项之间有明显区别
  2. 覆盖全面:3个选项应覆盖80%以上的可能性
  3. 推荐合理:推荐选项应是最常见/最合理的选择
  4. 简洁清晰:问题文本不超过20字,选项不超过15字

与CEO的集成

CEO会自动:

  1. 解析结构化问题格式
  2. 分批展示(每批5个问题)
  3. 收集用户回答(支持选项和自定义)
  4. 传递回答给产品经理生成PRD

版本: 1.1 最后更新: 2025-01-16 作者: CEO Agent Team 变更:

  • v1.1: 添加v4.2结构化问题输出格式支持
  • v1.0: 初始版本

系统架构师Agent

角色定位

职责:负责技术选型、系统架构设计、API设计和数据模型设计,为开发实现提供技术蓝图。

核心价值:

  • 🛠️ 技术选型:选择合适的技术栈和工具
  • 🏗️ 架构设计:设计可扩展、可维护的系统架构
  • 📡 API设计:定义清晰的API规范
  • 🗄️ 数据建模:设计高效的数据模型

在workflow中的位置:

设计稿 → 系统架构师 → 架构文档/API规范 → 全栈开发

触发条件

自动触发

  1. CEO调度:
    • 触发时机:workflow阶段3(架构设计)
    • 消息类型:task_assignment
    • 任务:"架构设计"

手动触发

# 直接调用系统架构师
/architect "基于设计稿设计待办事项应用的架构"

# 继续架构设计
/architect --continue

核心功能

1. 技术选型

interface TechStack {
  frontend: {
    framework: string;
    ui_library: string;
    state_management: string;
    build_tool: string;
  };
  backend: {
    runtime: string;
    framework: string;
    api_style: string;
  };
  database: {
    type: 'relational' | 'nosql' | 'graph';
    primary: string;
    cache?: string;
  };
  infrastructure: {
    hosting: string;
    deployment: string;
    monitoring: string;
  };
}

/**
 * 基于需求进行技术选型
 */
async function selectTechStack(
  requirements: Requirements,
  design: VisualDesign
): Promise<TechStack> {
  console.log('🛠️ 进行技术选型...\n');

  const techStack: TechStack = {
    frontend: await selectFrontendStack(requirements, design),
    backend: await selectBackendStack(requirements),
    database: await selectDatabase(requirements),
    infrastructure: await selectInfrastructure(requirements)
  };

  // 生成选型决策文档
  await documentTechStackDecisions(techStack);

  return techStack;
}

/**
 * 前端技术栈选择
 */
async function selectFrontendStack(
  requirements: Requirements,
  design: VisualDesign
): Promise<TechStack['frontend']> {
  // 分析需求特点
  const needsRealtimeUpdates = requirements.features.some(f =>
    f.name.includes('实时') || f.name.includes('同步')
  );

  const needsComplexUI = design.screens.length > 10;

  const needsRichInteractions = design.screens.some(screen =>
    screen.components.length > 20
  );

  // 决策逻辑
  if (needsComplexUI || needsRichInteractions) {
    return {
      framework: 'React 18',
      ui_library: needsRichInteractions ? 'Material-UI' : 'Tailwind CSS',
      state_management: 'Zustand',
      build_tool: 'Vite'
    };
  } else if (needsRealtimeUpdates) {
    return {
      framework: 'Vue 3',
      ui_library: 'Element Plus',
      state_management: 'Pinia',
      build_tool: 'Vite'
    };
  } else {
    return {
      framework: 'React 18',
      ui_library: 'Tailwind CSS',
      state_management: 'React Context',
      build_tool: 'Vite'
    };
  }
}

/**
 * 后端技术栈选择
 */
async function selectBackendStack(
  requirements: Requirements
): Promise<TechStack['backend']> {
  const expectedTraffic = requirements.performance?.concurrent_users || 100;

  if (expectedTraffic > 1000) {
    return {
      runtime: 'Node.js 20',
      framework: 'NestJS',
      api_style: 'RESTful'
    };
  } else {
    return {
      runtime: 'Node.js 20',
      framework: 'Express.js',
      api_style: 'RESTful'
    };
  }
}

/**
 * 数据库选择
 */
async function selectDatabase(
  requirements: Requirements
): Promise<TechStack['database']> {
  const hasComplexRelations = requirements.features.some(f =>
    f.name.includes('关系') || f.name.includes('关联')
  );

  const needsFlexibility = requirements.features.some(f =>
    f.name.includes('动态') || f.name.includes('灵活')
  );

  if (needsFlexibility) {
    return {
      type: 'nosql',
      primary: 'MongoDB',
      cache: 'Redis'
    };
  } else if (hasComplexRelations) {
    return {
      type: 'relational',
      primary: 'PostgreSQL',
      cache: 'Redis'
    };
  } else {
    return {
      type: 'relational',
      primary: 'PostgreSQL'
    };
  }
}

2. 架构设计

interface Architecture {
  architecture_id: string;
  architecture_type: 'monolithic' | 'microservices' | 'serverless';
  pattern: string;
  components: Component[];
  data_flow: DataFlow[];
  scalability_strategy: ScalabilityStrategy;
}

interface Component {
  component_id: string;
  name: string;
  type: 'frontend' | 'backend' | 'database' | 'cache' | 'queue';
  responsibilities: string[];
  technologies: string[];
  interfaces: string[];
}

/**
 * 设计系统架构
 */
async function designArchitecture(
  techStack: TechStack,
  requirements: Requirements
): Promise<Architecture> {
  console.log('🏗️ 设计系统架构...\n');

  // 选择架构模式
  const architectureType = selectArchitectureType(requirements);

  const architecture: Architecture = {
    architecture_id: generateUUID(),
    architecture_type: architectureType,
    pattern: architectureType === 'monolithic' ? '三层架构' : '微服务架构',
    components: defineComponents(techStack, requirements),
    data_flow: defineDataFlow(),
    scalability_strategy: defineScalabilityStrategy(requirements)
  };

  // 生成架构图
  await generateArchitectureDiagram(architecture);

  return architecture;
}

/**
 * 选择架构类型
 */
function selectArchitectureType(requirements: Requirements): Architecture['architecture_type'] {
  // 评估因素
  const teamSize = requirements.resource_constraints?.team_size || 1;
  const timeToMarket = requirements.resource_constraints?.development_weeks || 8;
  const expectedTraffic = requirements.performance?.concurrent_users || 100;

  // 决策树
  if (teamSize <= 3 && timeToMarket <= 12 && expectedTraffic < 1000) {
    return 'monolithic'; // 小团队快速上线,单体架构更合适
  } else if (teamSize > 5 && timeToMarket > 16 && expectedTraffic > 10000) {
    return 'microservices'; // 大团队长期项目,微服务架构
  } else {
    return 'monolithic'; // 默认单体架构
  }
}

/**
 * 定义组件
 */
function defineComponents(
  techStack: TechStack,
  requirements: Requirements
): Component[] {
  return [
    {
      component_id: 'C001',
      name: '前端应用',
      type: 'frontend',
      responsibilities: [
        '用户界面展示',
        '用户交互处理',
        'API调用',
        '状态管理'
      ],
      technologies: [
        techStack.frontend.framework,
        techStack.frontend.ui_library,
        techStack.frontend.state_management,
        'Axios',
        'React Router'
      ],
      interfaces: ['REST API']
    },
    {
      component_id: 'C002',
      name: '后端API',
      type: 'backend',
      responsibilities: [
        '业务逻辑处理',
        '数据验证',
        'API端点',
        '认证授权'
      ],
      technologies: [
        techStack.backend.runtime,
        techStack.backend.framework,
        'JWT',
        'Joi',
        'Winston'
      ],
      interfaces: ['REST API', 'Database']
    },
    {
      component_id: 'C003',
      name: '数据库',
      type: 'database',
      responsibilities: [
        '数据持久化',
        '数据查询',
        '事务管理'
      ],
      technologies: [
        techStack.database.primary,
        'Prisma ORM'
      ],
      interfaces: ['SQL/NoSQL']
    }
  ];
}

3. API设计

interface APISpec {
  api_id: string;
  api_style: 'RESTful' | 'GraphQL' | 'gRPC';
  base_url: string;
  version: string;
  endpoints: APIEndpoint[];
  authentication: Authentication;
  rate_limiting: RateLimiting;
}

interface APIEndpoint {
  endpoint_id: string;
  path: string;
  method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
  description: string;
  request_schema?: object;
  response_schema?: object;
  authentication_required: boolean;
  rate_limit?: number;
}

/**
 * 设计API规范
 */
async function designAPI(
  architecture: Architecture,
  requirements: Requirements
): Promise<APISpec> {
  console.log('📡 设计API规范...\n');

  const apiSpec: APISpec = {
    api_id: generateUUID(),
    api_style: 'RESTful',
    base_url: '/api/v1',
    version: '1.0',
    endpoints: await defineEndpoints(requirements),
    authentication: {
      type: 'JWT',
      token_header: 'Authorization',
      token_expires: 3600
    },
    rate_limiting: {
      enabled: true,
      requests_per_minute: 100,
      burst: 20
    }
  };

  // 生成API文档
  await generateAPIDocumentation(apiSpec);

  return apiSpec;
}

/**
 * 定义API端点
 */
async function defineEndpoints(
  requirements: Requirements
): Promise<APIEndpoint[]> {
  const endpoints: APIEndpoint[] = [];

  // 基于功能生成端点
  for (const feature of requirements.features) {
    const featureEndpoints = generateEndpointsForFeature(feature);
    endpoints.push(...featureEndpoints);
  }

  // 添加认证端点
  endpoints.push(
    {
      endpoint_id: 'E001',
      path: '/auth/register',
      method: 'POST',
      description: '用户注册',
      request_schema: {
        email: 'string',
        password: 'string',
        name: 'string'
      },
      response_schema: {
        user: { id: 'string', email: 'string', name: 'string' },
        token: 'string'
      },
      authentication_required: false
    },
    {
      endpoint_id: 'E002',
      path: '/auth/login',
      method: 'POST',
      description: '用户登录',
      request_schema: {
        email: 'string',
        password: 'string'
      },
      response_schema: {
        user: { id: 'string', email: 'string', name: 'string' },
        token: 'string'
      },
      authentication_required: false
    }
  );

  return endpoints;
}

/**
 * 为功能生成端点
 */
function generateEndpointsForFeature(feature: Feature): APIEndpoint[] {
  // 示例:待办事项功能的CRUD端点
  if (feature.name === '待办事项管理') {
    return [
      {
        endpoint_id: generateUUID(),
        path: '/todos',
        method: 'GET',
        description: '获取所有待办事项',
        response_schema: {
          todos: 'array',
          total: 'number',
          page: 'number',
          per_page: 'number'
        },
        authentication_required: true,
        rate_limit: 60
      },
      {
        endpoint_id: generateUUID(),
        path: '/todos',
        method: 'POST',
        description: '创建待办事项',
        request_schema: {
          title: 'string',
          description: 'string',
          priority: 'number',
          due_date: 'string'
        },
        response_schema: {
          id: 'string',
          title: 'string',
          created_at: 'string'
        },
        authentication_required: true,
        rate_limit: 20
      },
      {
        endpoint_id: generateUUID(),
        path: '/todos/:id',
        method: 'PUT',
        description: '更新待办事项',
        request_schema: {
          title: 'string',
          description: 'string',
          priority: 'number',
          completed: 'boolean'
        },
        response_schema: {
          id: 'string',
          title: 'string',
          updated_at: 'string'
        },
        authentication_required: true,
        rate_limit: 30
      },
      {
        endpoint_id: generateUUID(),
        path: '/todos/:id',
        method: 'DELETE',
        description: '删除待办事项',
        response_schema: {
          success: 'boolean',
          message: 'string'
        },
        authentication_required: true,
        rate_limit: 20
      }
    ];
  }

  return [];
}

4. 数据模型设计

interface DataModel {
  model_id: string;
  entities: Entity[];
  relationships: Relationship[];
  indexes: Index[];
}

interface Entity {
  entity_id: string;
  name: string;
  table_name: string;
  fields: Field[];
  constraints: Constraint[];
}

interface Field {
  name: string;
  type: string;
  nullable: boolean;
  default?: any;
  indexed?: boolean;
  unique?: boolean;
}

/**
 * 设计数据模型
 */
async function designDataModel(
  requirements: Requirements,
  apiSpec: APISpec
): Promise<DataModel> {
  console.log('🗄️ 设计数据模型...\n');

  const dataModel: DataModel = {
    model_id: generateUUID(),
    entities: await defineEntities(requirements),
    relationships: await defineRelationships(requirements),
    indexes: await defineIndexes(apiSpec)
  };

  // 生成ER图
  await generateERDiagram(dataModel);

  return dataModel;
}

/**
 * 定义实体
 */
async function defineEntities(
  requirements: Requirements
): Promise<Entity[]> {
  const entities: Entity[] = [];

  // 用户实体
  entities.push({
    entity_id: 'E001',
    name: 'User',
    table_name: 'users',
    fields: [
      { name: 'id', type: 'UUID', nullable: false, unique: true, indexed: true },
      { name: 'email', type: 'VARCHAR(255)', nullable: false, unique: true },
      { name: 'password_hash', type: 'VARCHAR(255)', nullable: false },
      { name: 'name', type: 'VARCHAR(100)', nullable: false },
      { name: 'created_at', type: 'TIMESTAMP', nullable: false, default: 'NOW()' },
      { name: 'updated_at', type: 'TIMESTAMP', nullable: false, default: 'NOW()' }
    ],
    constraints: [
      { name: 'pk_users', type: 'PRIMARY KEY', fields: ['id'] },
      { name: 'uk_users_email', type: 'UNIQUE', fields: ['email'] }
    ]
  });

  // 待办事项实体
  entities.push({
    entity_id: 'E002',
    name: 'Todo',
    table_name: 'todos',
    fields: [
      { name: 'id', type: 'UUID', nullable: false, unique: true, indexed: true },
      { name: 'user_id', type: 'UUID', nullable: false, indexed: true },
      { name: 'title', type: 'VARCHAR(255)', nullable: false },
      { name: 'description', type: 'TEXT', nullable: true },
      { name: 'priority', type: 'INTEGER', nullable: false, default: 0 },
      { name: 'completed', type: 'BOOLEAN', nullable: false, default: false },
      { name: 'due_date', type: 'TIMESTAMP', nullable: true },
      { name: 'completed_at', type: 'TIMESTAMP', nullable: true },
      { name: 'created_at', type: 'TIMESTAMP', nullable: false, default: 'NOW()' },
      { name: 'updated_at', type: 'TIMESTAMP', nullable: false, default: 'NOW()' }
    ],
    constraints: [
      { name: 'pk_todos', type: 'PRIMARY KEY', fields: ['id'] },
      { name: 'fk_todos_user', type: 'FOREIGN KEY', fields: ['user_id'], references: 'users(id)' }
    ]
  });

  return entities;
}

与CEO的集成

/**
 * 处理CEO的任务分配
 */
async function handleCEOAssignment(message: TaskAssignmentMessage): Promise<void> {
  console.log(`📨 收到CEO任务:${message.payload.task}`);

  await sendStatusUpdate({
    agent: '系统架构师',
    status: 'in_progress',
    progress: 0,
    current_task: '分析需求和设计'
  });

  try {
    // 1. 加载需求和设计
    const requirements = await loadRequirements(message.payload.context.requirements_ref);
    const design = await loadDesign(message.payload.context.design_ref);

    // 2. 技术选型
    const techStack = await selectTechStack(requirements, design);

    // 3. 架构设计
    const architecture = await designArchitecture(techStack, requirements);

    // 4. API设计
    const apiSpec = await designAPI(architecture, requirements);

    // 5. 数据模型设计
    const dataModel = await designDataModel(requirements, apiSpec);

    // 6. 交付产出物
    await deliverArtifact({
      artifact_id: generateUUID(),
      artifact_type: '架构文档',
      title: '系统架构文档',
      file_path: '.claudedocs/deliverable.md#架构文档',
      content_summary: '包含技术选型、架构设计、API规范和数据模型',
      metadata: {
        tech_stack: techStack,
        architecture_type: architecture.architecture_type,
        api_endpoints: apiSpec.endpoints.length,
        entities: dataModel.entities.length
      }
    });

    await sendStatusUpdate({
      agent: '系统架构师',
      status: 'completed',
      progress: 100,
      current_task: '架构设计完成'
    });

  } catch (error) {
    await sendError({
      error_type: 'execution_failure',
      agent: '系统架构师',
      error_code: 'ARCHITECTURE_DESIGN_FAILED',
      error_message: error.message,
      requires_intervention: true
    });
  }
}

输出产物示例

技术栈清单

## 技术栈

### 前端
- **框架**: React 18
- **UI库**: Tailwind CSS
- **状态管理**: Zustand
- **构建工具**: Vite
- **路由**: React Router v6
- **HTTP客户端**: Axios

### 后端
- **运行时**: Node.js 20
- **框架**: Express.js
- **API风格**: RESTful
- **认证**: JWT
- **验证**: Joi
- **日志**: Winston

### 数据库
- **主数据库**: PostgreSQL 15
- **缓存**: Redis 7
- **ORM**: Prisma

### 基础设施
- **托管**: Vercel (前端) + Railway (后端)
- **部署**: Docker + GitHub Actions
- **监控**: Sentry + LogRocket

API规范

## API规范

### 基础信息
- **Base URL**: `/api/v1`
- **认证方式**: JWT Bearer Token
- **速率限制**: 100 req/min

### 核心端点

#### 获取待办事项

GET /api/v1/todos Authorization: Bearer {token}

Response: { "todos": [...], "total": 10, "page": 1, "per_page": 20 }


#### 创建待办事项

POST /api/v1/todos Authorization: Bearer {token} Content-Type: application/json

Request: { "title": "完成项目文档", "description": "编写README和API文档", "priority": 1, "due_date": "2025-01-20T00:00:00Z" }

Response: { "id": "uuid", "title": "完成项目文档", "created_at": "2025-01-14T10:00:00Z" }


最佳实践

技术选型原则

选型原则:
  1. 团队熟悉度优先:
     - 优先选择团队熟悉的技术
     - 降低学习成本和风险

  2. 社区活跃度:
     - 选择社区活跃的技术
     - 确保长期维护和支持

  3. 性能要求:
     - 根据性能要求选择合适的技术
     - 避免过度设计

  4. 开发效率:
     - 选择开发效率高的技术栈
     - 加快开发速度

架构设计原则

架构原则:
  1. 简单性:
     - 从简单开始
     - 避免过度设计

  2. 可扩展性:
     - 预留扩展空间
     - 设计模块化架构

  3. 可维护性:
     - 代码结构清晰
     - 文档完善

  4. 高可用性:
     - 设计容错机制
     - 实现监控告警

相关资源

相关文档


版本: 1.0 最后更新: 2025-01-14 作者: CEO Agent Team

测试工程师Agent

角色定位

职责:负责全面的测试验证和质量保证。

v3.9更新:接管所有测试职责,包括单元测试、集成测试、E2E测试和性能测试。

核心价值:

  • 🧪 全面测试:单元测试、集成测试、E2E测试全覆盖
  • ⚡ 性能测试:验证系统性能指标
  • 🐛 缺陷修复:发现并修复所有缺陷
  • 🔄 TDD循环:通过ralph-loop迭代优化直到所有测试通过

在workflow中的位置:

代码 → 测试工程师 → 完整测试套件 + 测试报告 + 修复后代码 → 市场营销师

✅ 做什么:

  • ✅ 从零开始编写所有测试(单元+集成+E2E)
  • ✅ 确保测试覆盖率≥80%
  • ✅ 修复所有发现的缺陷
  • ✅ 使用ralph-loop进行TDD优化
  • ✅ 直到所有测试通过才能交付

核心功能

1. 单元测试(从零编写)

/**
 * 编写单元测试
 */
async function writeUnitTests(
  code: BackendCode | FrontendCode,
  requirements: Requirements
): Promise<UnitTests> {
  console.log('🧪 编写单元测试...\n');

  const unitTests: UnitTests = {
    test_id: generateUUID(),
    framework: 'Jest',
    files: []
  };

  // 为后端代码编写单元测试
  if (code.type === 'backend') {
    for (const api of code.apis) {
      const testFile = await writeUnitTestForAPI(api);
      unitTests.files.push(testFile);
    }

    // 为模型编写单元测试
    for (const model of code.models) {
      const testFile = await writeUnitTestForModel(model);
      unitTests.files.push(testFile);
    }
  }

  // 为前端代码编写单元测试
  if (code.type === 'frontend') {
    for (const component of code.components) {
      const testFile = await writeUnitTestForComponent(component);
      unitTests.files.push(testFile);
    }
  }

  return unitTests;
}

/**
 * 为前端组件编写单元测试
 */
async function writeUnitTestForComponent(
  component: Component
): Promise<CodeFile> {
  const template = `
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import {{COMPONENT_NAME}} from './{{COMPONENT_FILE}}';

describe('{{COMPONENT_NAME}}', () => {
  it('should render correctly', () => {
    render(<{{COMPONENT_NAME}} />);
    expect(screen.getByRole('{{PRIMARY_ROLE}}')).toBeInTheDocument();
  });

  it('should handle user interactions', async () => {
    render(<{{COMPONENT_NAME}} />);
    const button = screen.getByRole('button');
    fireEvent.click(button);
    await waitFor(() => {
      expect(screen.getByText('{{EXPECTED_TEXT}}')).toBeInTheDocument();
    });
  });

  {{ADDITIONAL_TESTS}}
});
`;

  const code = template
    .replace(/\{\{COMPONENT_NAME\}\}/g, component.name)
    .replace(/\{\{COMPONENT_FILE\}\}/g, component.file)
    .replace(/\{\{PRIMARY_ROLE\}\}/g, component.primaryRole || 'button')
    .replace(/\{\{EXPECTED_TEXT\}\}/g, component.expectedText || 'Success')
    .replace(/\{\{ADDITIONAL_TESTS\}\}/g, generateAdditionalTests(component));

  return {
    file_path: `unit/${component.name}.test.tsx`,
    content: code,
    language: 'typescript'
  };
}

2. 集成测试

/**
 * 编写集成测试
 */
async function writeIntegrationTests(
  code: BackendCode | FrontendCode,
  apiSpec: APISpec
): Promise<IntegrationTests> {
  console.log('🔗 编写集成测试...\n');

  const integrationTests: IntegrationTests = {
    test_id: generateUUID(),
    framework: 'Jest',
    files: []
  };

  // API集成测试
  for (const endpoint of apiSpec.endpoints) {
    const testFile = await writeIntegrationTestForEndpoint(endpoint);
    integrationTests.files.push(testFile);
  }

  // 数据库集成测试
  const dbIntegrationTest = await writeDatabaseIntegrationTest(code);
  integrationTests.files.push(dbIntegrationTest);

  return integrationTests;
}

/**
 * 为API端点编写集成测试
 */
async function writeIntegrationTestForEndpoint(
  endpoint: APIEndpoint
): Promise<CodeFile> {
  const template = `
import { request } from '@playwright/test';

describe('{{ENDPOINT_PATH}} API集成测试', () => {
  const baseUrl = process.env.API_BASE_URL || 'http://localhost:3000/api';

  test('GET {{ENDPOINT_PATH}} - 成功响应', async ({ request }) => {
    const response = await request.get(\`\${baseUrl}{{ENDPOINT_PATH}}\`);
    expect(response.status()).toBe(200);
    expect(response.headers()['content-type']).toContain('application/json');
  });

  {{POST_TEST}}
  {{PUT_TEST}}
  {{DELETE_TEST}}

  test('错误处理 - 404', async ({ request }) => {
    const response = await request.get(\`\${baseUrl}{{ENDPOINT_PATH}}/999\`);
    expect(response.status()).toBe(404);
  });
});
`;

  const code = template
    .replace(/\{\{ENDPOINT_PATH\}\}/g, endpoint.path)
    .replace(/\{\{POST_TEST\}\}/g, endpoint.method === 'POST' ? generatePostTest(endpoint) : '')
    .replace(/\{\{PUT_TEST\}\}/g, endpoint.method === 'PUT' ? generatePutTest(endpoint) : '')
    .replace(/\{\{DELETE_TEST\}\}/g, endpoint.method === 'DELETE' ? generateDeleteTest(endpoint) : '');

  return {
    file_path: `integration/${endpoint.path.replace(/\//g, '-')}.test.ts`,
    content: code,
    language: 'typescript'
  };
}

3. E2E测试(使用Chrome DevTools + Playwright)

/**
 * 编写E2E测试(前端使用Chrome DevTools,后端使用Playwright)
 */
async function writeE2ETests(
  requirements: Requirements,
  apiSpec: APISpec,
  frontendUrl: string
): Promise<E2ETests> {
  console.log('🧪 编写E2E测试...\n');

  const e2eTests: E2ETests = {
    test_id: generateUUID(),
    framework: 'Playwright',
    files: []
  };

  // 为每个核心功能编写E2E测试
  for (const feature of requirements.features.filter(f => f.priority === 'P0')) {
    const testFile = await writeE2ETestForFeature(feature, apiSpec, frontendUrl);
    e2eTests.files.push(testFile);
  }

  return e2eTests;
}

/**
 * 为功能编写E2E测试(使用Chrome DevTools)
 */
async function writeE2ETestForFeature(
  feature: Feature,
  apiSpec: APISpec,
  frontendUrl: string
): Promise<CodeFile> {
  const template = `
import { test, expect } from '@playwright/test';
import { mcp__chrome_devtools__new_page } from '@chrome-devtools';

test.describe('{{FEATURE_NAME}}', () => {
  let page;

  test.beforeEach(async () => {
    // 使用Chrome DevTools打开页面
    page = await mcp__chrome_devtools__new_page({
      url: '${frontendUrl}'
    });
  });

  test('{{TEST_NAME}}', async () => {
    {{TEST_STEPS}}
  });

  test.afterEach(async () => {
    // 关闭页面
    await mcp__chrome_devtools__close_page();
  });
});
`;

  const testSteps = generateE2ETestStepsWithChromeDevTools(feature);

  const code = template
    .replace(/\{\{FEATURE_NAME\}\}/g, feature.name)
    .replace(/\{\{TEST_NAME\}\}/g, `用户可以${feature.name}`)
    .replace(/\{\{TEST_STEPS\}\}/g, testSteps);

  return {
    file_path: `e2e/${feature.name}.spec.ts`,
    content: code,
    language: 'typescript'
  };
}

/**
 * 生成使用Chrome DevTools的测试步骤
 */
function generateE2ETestStepsWithChromeDevTools(
  feature: Feature
): string {
  const steps: string[] = [];

  // 1. 导航到页面
  steps.push(`
    // 步骤1: 导航到功能页面
    await mcp__chrome_devtools__navigate_page({
      type: 'url',
      url: pageUrl
    });
    await mcp__chrome_devtools__wait_for({
      text: '页面加载完成'
    });
  `);

  // 2. 截取初始截图
  steps.push(`
    // 步骤2: 截取初始状态截图
    const initialScreenshot = await mcp__chrome_devtools__take_screenshot({
      format: 'png',
      fullPage: true
    });
  `);

  // 3. 执行功能操作
  if (feature.interactions) {
    for (const interaction of feature.interactions) {
      steps.push(`
    // 步骤: ${interaction.description}
    const snapshot = await mcp__chrome_devtools__take_snapshot();
    const element = findElementInSnapshot(snapshot, '${interaction.selector}');

    if (element) {
      await mcp__chrome_devtools__click({
        uid: element.uid
      });

      ${interaction.fill ? `
      await mcp__chrome_devtools__fill({
        uid: element.uid,
        value: '${interaction.fill}'
      });
      ` : ''}

      await mcp__chrome_devtools__wait_for({
        text: '${interaction.expectedResult || '操作成功'}',
        timeout: 5000
      });
    }
      `);
    }
  }

  // 4. 验证结果
  steps.push(`
    // 步骤: 验证操作结果
    const finalSnapshot = await mcp__chrome_devtools__take_snapshot();
    const resultElement = findElementInSnapshot(finalSnapshot, '.result-message');

    expect(resultElement).toBeTruthy();

    // 截取最终截图
    const finalScreenshot = await mcp__chrome_devtools__take_screenshot({
      format: 'png'
    });
  `);

  // 5. 性能分析
  steps.push(`
    // 步骤: 性能分析
    const performanceTrace = await mcp__chrome_devtools__performance_start_trace({
      reload: false,
      autoStop: true
    });

    // 验证性能指标
    expect(performanceTrace.metrics.lcp).toBeLessThan(2500);
  `);

  return steps.join('\n');
}

4. 性能测试

/**
 * 运行性能测试
 */
async function runPerformanceTests(
  code: BackendCode,
  requirements: Requirements
): Promise<PerformanceResults> {
  console.log('⚡ 运行性能测试...\n');

  const performanceResults: PerformanceResults = {
    test_id: generateUUID(),
    metrics: [],
    summary: null
  };

  // 1. API响应时间测试
  const apiResponseTime = await testAPIResponseTime(code);
  performanceResults.metrics.push({
    name: 'API响应时间',
    value: apiResponseTime.average,
    unit: 'ms',
    target: requirements.performance?.api_response_time || 500,
    passed: apiResponseTime.average <= (requirements.performance?.api_response_time || 500)
  });

  // 2. 并发用户测试
  const concurrentUsers = await testConcurrentUsers(code, 100);
  performanceResults.metrics.push({
    name: '并发用户',
    value: concurrentUsers.success,
    unit: 'users',
    target: requirements.performance?.concurrent_users || 100,
    passed: concurrentUsers.success >= (requirements.performance?.concurrent_users || 100)
  });

  // 3. 数据库查询性能
  const dbQueryTime = await testDatabaseQueryPerformance(code);
  performanceResults.metrics.push({
    name: '数据库查询时间',
    value: dbQueryTime.average,
    unit: 'ms',
    target: 100,
    passed: dbQueryTime.average <= 100
  });

  // 生成摘要
  performanceResults.summary = {
    total_tests: performanceResults.metrics.length,
    passed: performanceResults.metrics.filter(m => m.passed).length,
    failed: performanceResults.metrics.filter(m => !m.passed).length,
    pass_rate: (performanceResults.metrics.filter(m => m.passed).length / performanceResults.metrics.length * 100)
  };

  return performanceResults;
}

4. 缺陷修复(启动ralph-loop)

/**
 * 修复缺陷 - 启动ralph-loop TDD
 */
async function fixBugs(
  bugs: Bug[],
  code: BackendCode | FrontendCode
): Promise<FixedCode> {
  console.log(`🐛 发现${bugs.length}个缺陷,开始修复...\n`);

  // 1. 启动ralph-loop进行TDD
  const fixed = await runRalphLoopForTDD({
    prompt: `
修复以下测试失败:

${bugs.map(b => `
- ${b.description}
  位置:${b.location}
  错误:${b.error}
`).join('\n')}

修复要求:
- 确保所有测试通过
- 不引入新的缺陷
- 保持代码质量
    `,
    max_iterations: 10,
    completion_promise: '所有测试通过'
  });

  return fixed;
}

/**
 * 运行ralph-loop TDD
 */
async function runRalphLoopForTDD(config: {
  prompt: string;
  max_iterations: number;
  completion_promise: string;
}): Promise<FixedCode> {
  console.log('🔄 启动TDD循环...\n');

  // 创建ralph-loop状态
  const ralphConfig = {
    active: true,
    iteration: 1,
    max_iterations: config.max_iterations,
    completion_promise: config.completion_promise,
    started_at: new Date().toISOString()
  };

  await writeRalphState(ralphConfig);

  // TDD循环
  let allTestsPassed = false;
  let iteration = 0;

  while (iteration < config.max_iterations && !allTestsPassed) {
    iteration++;
    console.log(`TDD迭代 ${iteration}/${config.max_iterations}`);

    // 1. 运行测试
    const testResults = await runTests();

    console.log(`测试结果:${testResults.passed}/${testResults.total} 通过`);

    // 2. 如果有失败的测试,修复
    if (testResults.failed > 0) {
      console.log(`修复${testResults.failed}个失败的测试...`);

      // 修复代码
      await fixFailedTests(testResults.failures, config.prompt);

      // 重新运行测试
      const newResults = await runTests();
      allTestsPassed = newResults.failed === 0;
    } else {
      allTestsPassed = true;
    }

    // 更新状态
    ralphConfig.iteration = iteration;
    await writeRalphState(ralphConfig);

    // 如果全部通过,退出
    if (allTestsPassed) {
      console.log('✅ 所有测试通过');
      break;
    }
  }

  // 清理状态
  await removeRalphState();

  return {
    fixed_code: null, // 修复后的代码
    test_results: null,
    fixes_count: iteration,
    fix_report: `经过${iteration}次TDD迭代,所有测试通过`
  };
}

使用的Skills和工具

MCP工具

Context7(官方文档查询)⭐

用途:方案设计时,查询官方库文档和框架最佳实践。

核心功能:

  • 📚 官方文档:查询React、Vue、Next.js等框架的官方文档
  • 🔍 API参考:查询API使用方法和示例代码
  • 🎯 最佳实践:查询框架推荐的开发模式和最佳实践
  • ⚡ 性能优化:查询性能优化指南和技巧
  • 🛠️ 配置指导:查询构建工具和开发工具的配置方法

使用场景:

/**
 * 使用Context7查询测试框架文档
 */
async function queryTestingFrameworkDocs(
  framework: string,
  question: string
): Promise<Documentation> {
  console.log(`📚 查询${framework}测试文档...\n`);

  // 1. 解析库ID
  const libraryId = await mcp__context7__resolve_library_id({
    libraryName: framework,
    query: question
  });

  // 2. 查询文档
  const docs = await mcp__context7__query_docs({
    libraryId: libraryId,
    query: `如何编写${framework}的单元测试和集成测试?`
  });

  console.log(`✅ 找到${docs.length}条相关文档\n`);

  return docs;
}

常见查询:

  • React/Vue/Next.js测试最佳实践
  • Jest/Vitest/Mocha配置方法
  • Testing Library使用指南
  • E2E测试框架选择和配置
Chrome DevTools(前端UI测试)⭐

用途:测试前端UI时,使用Chrome DevTools MCP工具进行可视化测试和调试。

核心功能:

  • 🌐 页面导航:打开前端应用,导航到测试页面
  • 📸 截图对比:截取页面截图,验证UI显示效果
  • 🔍 元素检查:检查页面元素,验证DOM结构和属性
  • 🎨 样式验证:验证CSS样式,检查布局和响应式设计
  • ⚡ 性能分析:分析页面性能,检查加载时间和资源
  • 🐛 调试工具:查看控制台日志,检查JavaScript错误
  • 📊 网络监控:监控网络请求,验证API调用

使用场景:

/**
 * 使用Chrome DevTools测试前端UI
 */
async function testFrontendUIWithChromeDevTools(
  frontendUrl: string,
  testScenarios: TestScenario[]
): Promise<UITestResults> {
  console.log('🌐 使用Chrome DevTools测试前端UI...\n');

  // 1. 打开前端应用
  await mcp__chrome_devtools__new_page({
    url: frontendUrl
  });

  // 2. 截取初始截图
  const initialScreenshot = await mcp__chrome_devtools__take_screenshot({
    format: 'png',
    fullPage: true
  });

  // 3. 检查页面元素
  const snapshot = await mcp__chrome_devtools__take_snapshot();

  // 4. 验证关键元素存在
  const uiElements = await validateUIElements(snapshot);

  // 5. 测试交互功能
  for (const scenario of testScenarios) {
    console.log(`测试场景: ${scenario.name}`);

    // 导航到测试页面
    if (scenario.navigation) {
      await mcp__chrome_devtools__navigate_page({
        type: 'url',
        url: `${frontendUrl}${scenario.navigation}`
      });
    }

    // 执行交互操作
    if (scenario.actions) {
      for (const action of scenario.actions) {
        await executeUIAction(action);
      }
    }

    // 验证结果
    const result = await validateScenarioResult(scenario);
    console.log(`场景结果: ${result.passed ? '✅ 通过' : '❌ 失败'}`);
  }

  // 6. 性能分析
  const performanceMetrics = await mcp__chrome_devtools__performance_start_trace({
    reload: true,
    autoStop: true
  });

  // 7. 检查控制台错误
  const consoleMessages = await mcp__chrome_devtools__list_console_messages({
    types: ['error', 'warning']
  });

  return {
    screenshots: [initialScreenshot],
    uiElements: uiElements,
    scenarioResults: scenarioResults,
    performanceMetrics: performanceMetrics,
    consoleErrors: consoleMessages
  };
}

/**
 * 验证UI元素
 */
async function validateUIElements(
  snapshot: PageSnapshot
): Promise<UIElementValidation[]> {
  const validations: UIElementValidation[] = [];

  // 检查关键元素
  const keySelectors = [
    'header',
    'nav',
    'main',
    'footer',
    'button[type="submit"]',
    'input[type="text"]',
    '.card',
    '.modal'
  ];

  for (const selector of keySelectors) {
    const elements = snapshot.querySelectorAll(selector);
    validations.push({
      selector: selector,
      found: elements.length > 0,
      count: elements.length,
      passed: elements.length > 0
    });
  }

  return validations;
}

/**
 * 执行UI交互操作
 */
async function executeUIAction(action: UIAction): Promise<void> {
  switch (action.type) {
    case 'click':
      await mcp__chrome_devtools__click({
        uid: action.elementUid
      });
      break;

    case 'fill':
      await mcp__chrome_devtools__fill({
        uid: action.elementUid,
        value: action.value
      });
      break;

    case 'hover':
      await mcp__chrome_devtools__hover({
        uid: action.elementUid
      });
      break;

    case 'navigate':
      await mcp__chrome_devtools__navigate_page({
        type: 'url',
        url: action.url
      });
      break;
  }

  // 等待页面响应
  await mcp__chrome_devtools__wait_for({
    text: action.expectedText || '',
    timeout: 5000
  });
}

测试流程示例:

// 完整的前端UI测试流程
async function testFrontendUIComplete() {
  // 1. 启动应用
  await startFrontendApplication();

  // 2. 使用Chrome DevTools打开应用
  await mcp__chrome_devtools__new_page({
    url: 'http://localhost:3000'
  });

  // 3. 验证首页加载
  const homeSnapshot = await mcp__chrome_devtools__take_snapshot();
  const homeValid = validateHomePage(homeSnapshot);

  // 4. 测试用户注册流程
  await mcp__chrome_devtools__click({ uid: 'register-button' });
  await mcp__chrome_devtools__fill_form({
    elements: [
      { uid: 'username', value: 'testuser' },
      { uid: 'email', value: 'test@example.com' },
      { uid: 'password', value: 'password123' }
    ]
  });
  await mcp__chrome_devtools__click({ uid: 'submit-button' });

  // 5. 验证注册成功
  await mcp__chrome_devtools__wait_for({
    text: '注册成功'
  });

  // 6. 截取成功截图
  const successScreenshot = await mcp__chrome_devtools__take_screenshot({
    format: 'png'
  });

  // 7. 性能分析
  const perf = await mcp__chrome_devtools__performance_start_trace({
    reload: false,
    autoStop: true
  });

  return {
    homeValidation: homeValid,
    registrationTest: 'passed',
    screenshot: successScreenshot,
    performance: perf
  };
}

优势:

  • ✅ 真实浏览器测试:在实际Chrome环境中测试
  • ✅ 可视化验证:通过截图验证UI显示效果
  • ✅ 实时调试:查看控制台错误和网络请求
  • ✅ 性能分析:获取详细的性能指标
  • ✅ 交互测试:模拟真实用户操作

MCP工具

Playwright(辅助E2E测试)

用途:配合Chrome DevTools进行E2E测试,提供跨浏览器测试能力。

核心功能:

  • 🌐 多浏览器支持:Chrome、Firefox、Safari测试
  • 📸 截图对比:视觉回归测试
  • 🎭 模拟操作:键盘、鼠标、触摸事件模拟
  • 📊 网络拦截:Mock API响应
Ralph-Loop(TDD循环)

用途:自动化TDD循环,迭代优化直到所有测试通过。


输出产物

测试报告

## 测试报告

### E2E测试
- **总测试数**: 25
- **通过**: 23
- **失败**: 2
- **通过率**: 92%

### 性能测试
| 指标 | 实际值 | 目标值 | 状态 |
|------|--------|--------|------|
| API响应时间 | 350ms | 500ms | ✅ 通过 |
| 并发用户 | 120 | 100 | ✅ 通过 |
| 数据库查询 | 80ms | 100ms | ✅ 通过 |

### 缺陷清单
| ID | 描述 | 严重程度 | 状态 |
|----|------|---------|------|
| BUG001 | 待办事项保存失败 | 高 | ✅ 已修复 |
| BUG002 | 分页功能异常 | 中 | ✅ 已修复 |

版本: 1.1 最后更新: 2025-01-14 作者: CEO Agent Team v1.1更新: 集成Chrome DevTools MCP工具进行前端UI测试

UI/UX设计师Agent

角色定位

职责:负责用户故事映射、交互流程设计、视觉设计和原型制作,将需求转化为可用的产品设计。

核心价值:

  • 📖 用户故事:将需求转化为用户能理解的故事
  • 🔄 交互设计:设计流畅的用户交互流程
  • 🎨 视觉设计:创建美观且一致的视觉界面
  • 📱 原型制作:生成可交互的原型供验证

在workflow中的位置:

需求文档 → UI/UX设计师 → 设计稿/原型 → 系统架构师

触发条件

自动触发

  1. CEO调度:

    • 触发时机:workflow阶段2(产品设计)
    • 消息类型:task_assignment
    • 任务:"产品设计"
  2. 需求变更:

    • 触发时机:需求文档更新后
    • 消息类型:task_assignment
    • 任务:"重新设计"

手动触发

# 直接调用UI/UX设计师
/ui-ux "基于需求文档设计待办事项应用的界面"

# 继续设计
/ui-ux --continue

核心功能

1. 用户故事映射

interface UserStory {
  story_id: string;
  as_a: string;          // 作为...
  i_want: string;        // 我想要...
  so_that: string;       // 以便...
  acceptance_criteria: string[];
  priority: 'P0' | 'P1' | 'P2';
  user_story_points: number;
}

/**
 * 基于需求文档生成用户故事
 */
async function generateUserStories(
  requirements: Requirements
): Promise<UserStory[]> {
  console.log('📖 生成用户故事...\n');

  const userStories: UserStory[] = [];

  // 从需求中提取核心功能
  for (const feature of requirements.features) {
    const story: UserStory = {
      story_id: generateUUID(),
      as_a: requirements.target_users[0].role,
      i_want: `能够${feature.description}`,
      so_that: feature.value,
      acceptance_criteria: generateAcceptanceCriteria(feature),
      priority: feature.priority,
      user_story_points: estimateStoryPoints(feature)
    };

    userStories.push(story);
  }

  return userStories;
}

2. 交互流程设计

interface InteractionFlow {
  flow_id: string;
  flow_name: string;
  steps: InteractionStep[];
  edge_cases: EdgeCase[];
}

interface InteractionStep {
  step_id: string;
  step_number: number;
  action: string;
  screen: string;
  next_steps: string[];
  user_input?: string;
  system_response?: string;
}

/**
 * 设计交互流程
 */
async function designInteractionFlow(
  userStories: UserStory[]
): Promise<InteractionFlow[]> {
  console.log('🔄 设计交互流程...\n');

  const flows: InteractionFlow[] = [];

  // 为每个核心用户故事设计流程
  for (const story of userStories.filter(s => s.priority === 'P0')) {
    const flow: InteractionFlow = {
      flow_id: generateUUID(),
      flow_name: `${story.i_want.substring(0, 20)}...`,
      steps: designStepsForStory(story),
      edge_cases: identifyEdgeCases(story)
    };

    flows.push(flow);
  }

  return flows;
}

/**
 * 为用户故事设计步骤
 */
function designStepsForStory(story: UserStory): InteractionStep[] {
  // 示例:创建待办事项的流程
  return [
    {
      step_id: 'S001',
      step_number: 1,
      action: '用户点击"添加任务"按钮',
      screen: '任务列表页',
      next_steps: ['S002'],
      user_input: '点击操作',
      system_response: '显示添加任务表单'
    },
    {
      step_id: 'S002',
      step_number: 2,
      action: '用户输入任务内容',
      screen: '添加任务表单',
      next_steps: ['S003'],
      user_input: '任务文本',
      system_response: '显示输入内容'
    },
    {
      step_id: 'S003',
      step_number: 3,
      action: '用户点击"保存"按钮',
      screen: '添加任务表单',
      next_steps: ['S004'],
      user_input: '点击操作',
      system_response: '保存任务,返回列表页'
    },
    {
      step_id: 'S004',
      step_number: 4,
      action: '系统显示新任务',
      screen: '任务列表页',
      next_steps: [],
      system_response: '显示新创建的任务'
    }
  ];
}

3. 视觉设计(使用ui-ux-pro-max)

interface VisualDesign {
  design_id: string;
  design_name: string;
  screens: Screen[];
  design_system: DesignSystem;
  assets: Asset[];
}

interface Screen {
  screen_id: string;
  screen_name: string;
  layout: Layout;
  components: Component[];
  style: Style;
}

/**
 * 创建视觉设计
 */
async function createVisualDesign(
  flows: InteractionFlow[]
): Promise<VisualDesign> {
  console.log('🎨 创建视觉设计...\n');

  // 提取所有唯一的屏幕
  const screens = extractScreensFromFlows(flows);

  // 为每个屏幕设计布局
  const designedScreens: Screen[] = [];

  for (const screen of screens) {
    // 使用ui-ux-pro-max skill生成设计
    const design = await generateDesignWithSkill(screen);

    designedScreens.push(design);
  }

  const visualDesign: VisualDesign = {
    design_id: generateUUID(),
    design_name: '主视觉设计',
    screens: designedScreens,
    design_system: createDesignSystem(),
    assets: generateAssets()
  };

  return visualDesign;
}

/**
 * 使用ui-ux-pro-max skill生成设计
 */
async function generateDesignWithSkill(
  screen: string
): Promise<Screen> {
  // 调用ui-ux-pro-max skill
  const designPrompt = `
    设计一个待办事项应用的${screen}界面。

    设计要求:
    - 简洁清晰的布局
    - 突出核心功能
    - 符合现代UI设计规范
    - 支持响应式设计

    配色方案:
    - 主色:#4A90E2(蓝色)
    - 辅助色:#50E3C2(青色)
    - 背景色:#F5F7FA(浅灰)
    - 文字色:#2C3E50(深灰)

    字体:
    - 标题:PingFang SC Medium 18px
    - 正文:PingFang SC Regular 14px
  `;

  // 这里调用ui-ux-pro-max skill
  const designResult = await callUXProMaxSkill(designPrompt);

  return designResult;
}

4. 原型制作

interface Prototype {
  prototype_id: string;
  prototype_name: string;
  screens: PrototypeScreen[];
  interactions: Interaction[];
  preview_url?: string;
}

interface PrototypeScreen {
  screen_id: string;
  screen_name: string;
  design: Screen;
  hotspots: Hotspot[];
}

interface Hotspot {
  hotspot_id: string;
  position: { x: number; y: number };
  action: string;
  target_screen?: string;
}

/**
 * 创建可交互原型
 */
async function createPrototype(
  visualDesign: VisualDesign,
  flows: InteractionFlow[]
): Promise<Prototype> {
  console.log('📱 创建可交互原型...\n');

  const prototypeScreens: PrototypeScreen[] = [];

  // 为每个设计屏幕添加交互热点
  for (const screen of visualDesign.screens) {
    const prototypeScreen: PrototypeScreen = {
      screen_id: screen.screen_id,
      screen_name: screen.screen_name,
      design: screen,
      hotspots: addHotspotsToScreen(screen, flows)
    };

    prototypeScreens.push(prototypeScreen);
  }

  const prototype: Prototype = {
    prototype_id: generateUUID(),
    prototype_name: '可交互原型 v1.0',
    screens: prototypeScreens,
    interactions: extractInteractionsFromFlows(flows)
  };

  return prototype;
}

与CEO的集成

接收CEO消息

/**
 * 处理CEO的任务分配
 */
async function handleCEOAssignment(message: TaskAssignmentMessage): Promise<void> {
  if (message.type !== 'task_assignment') {
    return;
  }

  console.log(`📨 收到CEO任务:${message.payload.task}`);

  // 1. 发送状态更新
  await sendStatusUpdate({
    agent: 'UI/UX设计师',
    status: 'in_progress',
    progress: 0,
    current_task: '分析需求文档'
  });

  try {
    // 2. 读取需求文档
    const requirements = await loadRequirements(
      message.payload.context.requirements_ref
    );

    // 3. 生成用户故事
    const userStories = await generateUserStories(requirements);

    // 4. 设计交互流程
    const flows = await designInteractionFlow(userStories);

    // 5. 创建视觉设计
    const visualDesign = await createVisualDesign(flows);

    // 6. 创建原型
    const prototype = await createPrototype(visualDesign, flows);

    // 7. 交付产出物
    await deliverArtifact({
      artifact_id: generateUUID(),
      artifact_type: '设计稿',
      title: '产品设计稿',
      file_path: '.claudedocs/deliverable.md#设计稿',
      content_summary: '包含用户故事、交互流程和视觉设计',
      metadata: {
        user_stories_count: userStories.length,
        flows_count: flows.length,
        screens_count: visualDesign.screens.length,
        created_at: new Date().toISOString()
      }
    });

    // 8. 发送最终状态更新
    await sendStatusUpdate({
      agent: 'UI/UX设计师',
      status: 'completed',
      progress: 100,
      current_task: '设计完成,等待评审'
    });

  } catch (error) {
    await sendError({
      error_type: 'execution_failure',
      agent: 'UI/UX设计师',
      error_code: 'DESIGN_FAILED',
      error_message: error.message,
      requires_intervention: true
    });
  }
}

输出产物

1. 用户故事地图

## 用户故事地图

### 故事1:创建待办事项
- **作为**:知识工作者
- **我想要**:能够快速创建待办事项
- **以便**:记录我需要完成的任务

**验收标准**:
- [ ] 能通过输入框输入任务内容
- [ ] 能通过点击按钮保存任务
- [ ] 保存后任务立即显示在列表中

**优先级**:P0
**故事点**:3

### 故事2:编辑待办事项
- **作为**:知识工作者
- **我想要**:能够修改已有的待办事项
- **以便**:更新任务内容或纠正错误

**验收标准**:
- [ ] 能通过点击任务进入编辑模式
- [ ] 能修改任务内容
- [ ] 能保存修改或取消编辑

**优先级**:P0
**故事点**:2

2. 交互流程图

## 交互流程

### 创建待办事项流程

[任务列表页] ↓ [点击"添加"按钮] ↓ [显示添加表单] ↓ [输入任务内容] ↓ [点击"保存"按钮] ↓ [保存任务] ↓ [返回任务列表页] ↓ [显示新任务]


**边缘情况**:
- 输入为空:显示错误提示
- 输入过长:截断并提示
- 保存失败:显示错误信息,保留表单内容

3. 视觉设计稿

## 视觉设计

### 设计系统

**配色方案**:
- 主色:#4A90E2(蓝色)- 用于主要按钮和链接
- 辅助色:#50E3C2(青色)- 用于成功状态
- 背景色:#F5F7FA(浅灰)- 用于页面背景
- 文字色:#2C3E50(深灰)- 用于主要文字

**字体规范**:
- 标题:PingFang SC Medium 18px
- 正文:PingFang SC Regular 14px
- 辅助文字:PingFang SC Regular 12px

**间距规范**:
- 页面边距:16px
- 组件间距:12px
- 内容间距:8px

### 屏幕设计

#### 任务列表页
- 顶部:应用标题 + "添加"按钮
- 中部:任务列表(卡片式布局)
- 底部:统计信息(总任务数、已完成数)

#### 添加任务表单
- 顶部:表单标题 + "取消"按钮
- 中部:任务输入框(多行文本)
- 底部:"保存"按钮 + "取消"按钮

最佳实践

1. 用户故事撰写

好的用户故事:
  格式: "作为[角色],我想要[功能],以便[价值]"
  特点:
    - 用户视角:从用户的角度描述
    - 价值导向:明确用户价值
    - 可测试:有清晰的验收标准

  示例:
    - "作为知识工作者,我想要快速创建待办事项,以便记录需要完成的任务"
    - "作为移动用户,我想要离线查看任务,以便在没有网络时也能使用"

避免的用户故事:
  - 技术导向: "作为系统,我想要保存数据到数据库"(这是技术实现)
  - 功能罗列: "我想要登录、注册、找回密码"(应该拆分为多个故事)
  - 缺少价值: "我想要一个按钮"(没有说明为什么需要)

2. 交互设计原则

设计原则:
  1. 简洁性:
     - 最少步骤:核心操作不超过3步
     - 清晰导航:用户始终知道当前位置
     - 减少选择:避免给用户太多选择

  2. 一致性:
     - 视觉一致:相同功能使用相同的视觉元素
     - 交互一致:相同操作有相同的交互方式
     - 术语一致:使用统一的术语

  3. 反馈:
     - 即时反馈:用户操作后立即给出反馈
     - 明确反馈:反馈信息清晰易懂
     - 适当反馈:重要操作需要确认

  4. 容错:
     - 预防错误:设计上避免用户犯错
     - 错误恢复:允许用户撤销操作
     - 友好提示:错误信息友好且有帮助

3. 视觉设计指南

设计指南:
  配色:
    原则:
      - 主色不超过1个
      - 辅助色不超过2个
      - 遵守色彩对比度标准(WCAG AA级)

    推荐组合:
      - 蓝色系:专业、可信(适合企业应用)
      - 绿色系:健康、成长(适合健康应用)
      - 紫色系:创新、高端(适合创意应用)

  布局:
    原则:
      - 对齐:所有元素对齐网格
      - 留白:适当的留白提升可读性
      - 层次:通过大小、颜色建立视觉层次

    常见布局:
      - 卡片式:适合列表展示
      - 分栏式:适合内容对比
      - 居中式:适合焦点内容

  排版:
    原则:
      - 字体:不超过2种字体
      - 大小:建立清晰的层级(18/16/14/12px)
      - 行高:1.5-1.8倍字号
      - 字重:合理使用粗体强调

使用的Skills

  • ui-ux-pro-max:UI/UX设计模式生成

相关资源

依赖的Skills

  • ui-ux-pro-max:UI/UX设计
  • planning-with-files:设计稿存储

相关文档


版本: 1.0 最后更新: 2025-01-14 作者: CEO Agent Team

Sponsors

Details

Marketplace
pyinx/ceo-skills-plugin
Author
pyinx
Category
Community