Serena MCP-based symbolic refactoring plugin with data-driven agent architecture. Direct daemon integration for SOLID analysis, duplicate detection, safe renaming, intelligent feature injection, systematic debugging, and scientific experimentation with parallel hypothesis testing. Hook-based workflow enforcement ensures code quality through automated gates.

version
2.7.0

Install

/plugin install serena-refactor@serena-refactor-marketplace

Run it inside Claude Code after adding the marketplace with /plugin marketplace add chkim-su/serena-refactor.

Contents

Commands 11

Analyze Command

Symbol-level SOLID analysis using Serena MCP.

Usage

/serena-refactor:analyze [target]

Important: MCP Tool Access

MCP tools are only accessible in the main session. This command executes MCP calls directly, then delegates analysis logic to the agent.


Workflow

Step 0: MCP Server Discovery (MANDATORY)

Before any analysis, discover the Serena MCP server name:

The Serena MCP server may be registered under different names (e.g., serena, serena-daemon).

  1. Check available MCP servers by looking at the system prompt or using available MCP tools
  2. Identify the Serena server - look for names containing "serena"
  3. Use the discovered name for all subsequent MCP calls

Common server names:

  • serena-daemon (most common)
  • serena
  • plugin:serena:serena

If Serena MCP is NOT available:

  • Inform the user: "Serena MCP server not found. Please ensure it's configured in ~/.claude/mcp_servers.json"
  • DO NOT fall back to generic tools (Bash/Search/Read) - this defeats the purpose
  • Guide user to run the setup or restart Claude Code

Step 1: Target Selection

If no target provided:

AskUserQuestion:
  question: "What would you like to analyze?"
  header: "Analysis Target"
  options:
    - label: "Current directory"
      description: "Analyze entire project"
    - label: "Specific path"
      description: "Specify directory or file"

Step 2: Gather Data (Main Session MCP Calls)

Execute these MCP calls directly in the main session.

Note: Replace {SERENA_SERVER} with the actual server name discovered in Step 0 (e.g., serena-daemon)

  1. List directory structure:
mcp__{SERENA_SERVER}__list_dir:
  relative_path: [target or "."]
  recursive: false
  1. For each source file, get symbols:
mcp__{SERENA_SERVER}__get_symbols_overview:
  relative_path: [file path]
  depth: 1
  1. Search for SOLID violation patterns:
mcp__{SERENA_SERVER}__search_for_pattern:
  substring_pattern: "switch\\s*\\(|if\\s*\\(.*instanceof"
  restrict_search_to_code_files: true
  1. For suspicious symbols, get body:
mcp__{SERENA_SERVER}__find_symbol:
  name_path_pattern: [symbol name]
  relative_path: [file path]
  include_body: true
  1. Analyze references for impact scope:
mcp__{SERENA_SERVER}__find_referencing_symbols:
  name_path: [symbol name]
  relative_path: [file path]

Step 3: Delegate Analysis

Pass gathered data to analysis agent:

Task:
  agent: "serena-solid-analyzer"
  prompt: |
    Analyze the following code data for SOLID principle violations.

    ## Project Structure
    [paste list_dir results]

    ## Symbols Overview
    [paste get_symbols_overview results for each file]

    ## Pattern Search Results
    [paste search_for_pattern results]

    ## Symbol Bodies (for suspicious items)
    [paste find_symbol results with bodies]

    ## Reference Analysis
    [paste find_referencing_symbols results]

    Provide a comprehensive SOLID analysis report with:
    1. Violation summary table
    2. Detailed violations with file:line references
    3. Impact scope for each violation
    4. Prioritized fix recommendations

Step 4: Output Results

## Analysis Report: [target]

### Quick Summary
| Principle | Status | Violations | Impact Scope |
|-----------|--------|------------|--------------|
| SRP | OK/WARN/FAIL | X | Y files |
| OCP | OK/WARN/FAIL | X | Y files |
| LSP | OK/WARN/FAIL | X | Y files |
| ISP | OK/WARN/FAIL | X | Y files |
| DIP | OK/WARN/FAIL | X | Y files |

### Key Issues (Priority Order)
1. **[CRITICAL]** [file:line] - [issue] → Serena fix: [tool name]
2. ...

### Recommendations
- Run `/serena-refactor:refactor` for auto-fix
- Run `/serena-refactor:plan` for step-by-step planning

Architecture Note

┌─────────────────────────────────────────────────────────┐
│                    Main Session                         │
│  ┌─────────────┐     ┌─────────────────────────────┐   │
│  │ Step 0:     │────▶│ Discover Serena MCP server  │   │
│  │ Discovery   │     │ (serena-daemon, serena, etc)│   │
│  └─────────────┘     └──────────────┬──────────────┘   │
│                                      │                  │
│  ┌─────────────┐     ┌──────────────▼──────────────┐   │
│  │ MCP Tools   │────▶│ mcp__{SERENA}__* calls      │   │
│  │ (accessible)│     │ (gather code data)          │   │
│  └─────────────┘     └──────────────┬──────────────┘   │
│                                      │                  │
│                                      ▼                  │
│                      ┌──────────────────────────────┐   │
│                      │ Task: serena-solid-analyzer  │   │
│                      │ (receives data, not tools)   │   │
│                      │ - Analyzes symbols           │   │
│                      │ - Detects SOLID violations   │   │
│                      │ - Provides recommendations   │   │
│                      └──────────────────────────────┘   │
└─────────────────────────────────────────────────────────┘

CRITICAL: Do NOT Fall Back to Generic Tools

If Serena MCP is unavailable or fails:

  • DO NOT use Bash, Search, Read, Grep, or Glob as alternatives
  • These generic tools cannot provide symbol-level analysis
  • Inform user and guide them to configure Serena MCP properly

The serena-mcp-guard hook will warn if generic tools are used without MCP.

Audit Command

Refactoring quality audit.

Usage

/serena-refactor:audit [target]

Workflow

Step 1: Identify Target

If no target provided:

  • Auto-detect changed files via Git
  • git diff --name-only HEAD~1

Step 2: Run Audit

Task:
  agent: "refactor-auditor"
  prompt: |
    Perform code quality audit on [target].

    Check items:
    1. Incomplete patterns (TODO, FIXME)
    2. Reference integrity
    3. Empty implementations
    4. SOLID violations
    5. Test passing

Step 3: Output Results

## Audit Results

### Quick Status
| Item | Status |
|------|--------|
| Incomplete patterns | ✓/✗ |
| Reference integrity | ✓/✗ |
| Tests | ✓/✗ |

### VERDICT: PASS/FAIL

### On FAIL - Required Actions
1. [Item to fix]
...

Detect Duplicates Command

Detects duplicated code and roles in the codebase.

Usage

/serena-refactor:detect-duplicates [target]

Workflow

Step 0: Activate Serena Project

mcp__serena__activate_project:
  project: [current directory]

Step 1: Target Selection

If no target provided:

AskUserQuestion:
  question: "What would you like to analyze?"
  header: "Analysis Target"
  options:
    - label: "Current directory"
      description: "Analyze entire project"
    - label: "Specific path"
      description: "Specify directory or file"

Step 2: Run Duplicate Detection

Task:
  agent: "duplicate-detector"
  prompt: |
    Perform duplicate detection on [target].

    Detection targets:
    1. Clone code (Type 1-3)
       - Exact identical code
       - Code differing only in variable names
       - Structurally similar code
    2. Role duplication
       - Classes/functions with similar responsibilities
       - Synonym usage (get/fetch/retrieve etc.)
    3. Variable/constant duplication
       - Magic numbers
       - Duplicate strings
       - Duplicate config values

    Perform symbol analysis through Serena Gateway.

Step 3: Output Results

## Duplicate Detection Report: [target]

### Quick Summary
| Type | Found | Severity |
|------|-------|----------|
| Clone code | X | CRITICAL/HIGH |
| Role duplication | Y | HIGH |
| Constant duplication | Z | MEDIUM/LOW |

### Key Findings (Priority Order)
1. **[CRITICAL]** [file:line] - [description]
2. **[HIGH]** [file:line] - [description]
...

### Recommendations
- Run `/serena-refactor:refactor` for consolidation
- Run `/serena-refactor:extract` for common function extraction

Detection Criteria

Clone Code Thresholds

TypeSimilarityMin Lines
Type-1 (Identical)100%5 lines
Type-2 (Parameterized)> 90%5 lines
Type-3 (Similar)> 70%10 lines

Role Duplication Signals

  • Same prefix/suffix (e.g., *Manager, *Handler)
  • 3+ identical method names
  • Same dependency injection

Constant Duplication Criteria

  • Magic numbers: 2+ usages
  • Strings: 3+ usages (5+ characters)

Core Rules

  1. Analyze through Serena Gateway - Symbol-level accuracy
  2. Respect thresholds - Don't report below 70% similarity
  3. Include impact - Specify reference count, consolidation complexity
  4. Concrete fix paths - Provide Serena tool names and sequence

Extract Command

Code extraction refactoring using Serena MCP.

Usage

/serena-refactor:extract <type> <source> [options]

Extraction Types

TypeDescriptionExample
methodExtract method/extract method UserService/processUser
interfaceExtract interface/extract interface UserService
classSplit class/extract class UserService

Method Extraction

Workflow

1. Analyze Target Method
mcp__serena__find_symbol:
  name_path_pattern: [source]
  include_body: True
2. Identify Extraction Target
AskUserQuestion:
  question: "Select code block to extract"
  header: "Extraction Target"
  options:
    - label: "Auto-detect"
      description: "Auto-identify repeated/complex logic"
    - label: "Specify manually"
      description: "Specify line range"
3. Create New Method
mcp__serena__insert_after_symbol:
  name_path: [source]
  relative_path: [file]
  body: |
    def extracted_method(params):
        # Extracted logic
4. Modify Original
mcp__serena__replace_content:
  relative_path: [file]
  needle: "extracted code pattern"
  repl: "self.extracted_method(args)"
  mode: "regex"

Interface Extraction

Workflow

1. Analyze Class
mcp__serena__find_symbol:
  name_path_pattern: [source]
  depth: 1
  include_body: False
2. Identify Public Methods

Only public methods included in interface

3. Create Interface
mcp__serena__insert_before_symbol:
  name_path: [source]
  relative_path: [file]
  body: |
    interface IClassName {
        method1(param: Type): ReturnType;
        method2(): void;
    }
4. Modify Class
mcp__serena__replace_symbol_body:
  name_path: [source]
  relative_path: [file]
  body: |
    class ClassName implements IClassName {
        // Existing implementation
    }

Class Split

Workflow

1. Responsibility Analysis
mcp__serena__find_symbol:
  name_path_pattern: [source]
  depth: 1
  include_body: False

Group methods by responsibility

2. Split Plan
AskUserQuestion:
  question: "Select class split approach"
  header: "Split Strategy"
  options:
    - label: "Auto-grouping"
      description: "Auto-split based on method names/dependencies"
    - label: "Specify manually"
      description: "Specify method groups to split"
3. Create New Class
mcp__serena__insert_after_symbol:
  name_path: [source]
  relative_path: [file]
  body: |
    class ExtractedClass {
        // Separated methods
    }
4. Delegate from Original Class
mcp__serena__replace_symbol_body:
  # Replace moved methods with delegation calls

Output Format

## Extraction Complete: [type]

### Created Symbol
- Name: [new_symbol]
- File: [file:line]
- Type: [method/interface/class]

### Modified Symbol
- Original: [source]
- Changes: [description]

### Reference Updates
| File | Change |
|------|--------|
| ... | ... |

### Next Steps
- Run tests: `npm test`
- For further refactoring: `/serena-refactor:refactor`

Core Rules

  1. Symbol-level operations - Use Serena symbol tools instead of text replacement
  2. Auto-update references - Automatically fix all call sites after extraction
  3. Atomic changes - Complete extraction in one operation
  4. Rollback ready - Always restorable via Git

Inject Command

Intelligent feature injection based on project knowledge extraction.

Load Skills

Skill("serena-refactor:project-knowledge-graph")
Skill("serena-refactor:feature-injection-rules")

Usage

/serena-refactor:inject [feature description]

Workflow Overview

┌──────────────────────────────────────────────────────────────┐
│                    /inject Workflow                          │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  ┌─────────────┐                                             │
│  │   Start     │                                             │
│  └──────┬──────┘                                             │
│         │                                                    │
│         ▼                                                    │
│  ┌─────────────────────┐    ┌─────────────────────┐          │
│  │ Check for existing  │───▶│ knowledge-extractor │          │
│  │ knowledge graph     │ No │      agent          │          │
│  └──────┬──────────────┘    └──────────┬──────────┘          │
│         │ Yes                          │                     │
│         ▼                              ▼                     │
│  ┌─────────────────────────────────────────────────┐         │
│  │           Project Knowledge Available            │         │
│  └──────────────────────┬──────────────────────────┘         │
│                         │                                    │
│                         ▼                                    │
│  ┌─────────────────────────────────────────────────┐         │
│  │              feature-planner agent              │         │
│  │         (Design implementation plan)            │         │
│  └──────────────────────┬──────────────────────────┘         │
│                         │                                    │
│                         ▼                                    │
│  ┌─────────────────────────────────────────────────┐         │
│  │                 User Review                      │         │
│  │            (Approve/Modify Plan)                │         │
│  └──────────────────────┬──────────────────────────┘         │
│                         │                                    │
│                         ▼                                    │
│  ┌─────────────────────────────────────────────────┐         │
│  │              code-injector agent                │         │
│  │            (Execute injection)                  │         │
│  └──────────────────────┬──────────────────────────┘         │
│                         │                                    │
│                         ▼                                    │
│  ┌─────────────────────────────────────────────────┐         │
│  │              Update Knowledge Graph              │         │
│  └──────────────────────┬──────────────────────────┘         │
│                         │                                    │
│                         ▼                                    │
│  ┌─────────────┐                                             │
│  │   Complete  │                                             │
│  └─────────────┘                                             │
│                                                              │
└──────────────────────────────────────────────────────────────┘

Step 1: Check/Extract Project Knowledge

Check for Existing Knowledge

mcp__serena__read_memory:
  key: "project-knowledge-graph.md"

If No Knowledge Exists

AskUserQuestion:
  question: "프로젝트 지식 그래프가 없습니다. 추출할까요?"
  header: "지식 추출"
  options:
    - label: "전체 추출 (Recommended)"
      description: "프로젝트 전체를 분석하여 지식 그래프 생성"
    - label: "특정 디렉토리만"
      description: "분석할 디렉토리 지정"
    - label: "건너뛰기"
      description: "지식 그래프 없이 진행 (비권장)"

Run Knowledge Extraction

Task:
  agent: "knowledge-extractor"
  prompt: |
    Extract project knowledge for feature injection.

    Project path: [current directory]
    Scope: [full/specific path based on user choice]

    Return comprehensive knowledge graph including:
    - Project structure
    - Key symbols and their relationships
    - Detected patterns
    - Coding conventions

Step 2: Get Feature Description

If not provided in command:

AskUserQuestion:
  question: "어떤 기능을 추가하시겠습니까?"
  header: "기능 설명"
  options:
    - label: "새 서비스/클래스"
      description: "새로운 비즈니스 로직 컴포넌트"
    - label: "기존 클래스 확장"
      description: "기존 클래스에 메서드/기능 추가"
    - label: "새 엔드포인트/핸들러"
      description: "새로운 API 엔드포인트 또는 이벤트 핸들러"
    - label: "유틸리티/헬퍼"
      description: "재사용 가능한 유틸리티 함수"

Then ask for details:

AskUserQuestion:
  question: "기능에 대해 자세히 설명해주세요 (목적, 입출력, 동작 등)"
  header: "상세 설명"

Step 3: Plan Feature Implementation

Task:
  agent: "feature-planner"
  prompt: |
    Plan feature implementation based on project knowledge.

    ## Project Knowledge
    [knowledge_graph from step 1]

    ## Feature Request
    [user's feature description from step 2]

    ## Requirements
    1. Follow existing project conventions
    2. Maintain SOLID principles
    3. Plan safe injection points
    4. Include all necessary imports
    5. Consider impact on existing code

    Return detailed implementation plan with:
    - Step-by-step instructions
    - Exact code to inject
    - File locations and anchors
    - Import requirements
    - Rollback plan

Step 4: User Review and Approval

Present the plan to user:

## 구현 계획

### 요약
[Brief summary of what will be created/modified]

### 단계별 계획

| 단계 | 작업 | 대상 | 설명 |
|------|------|------|------|
| 1 | [create/insert/modify] | [file:symbol] | [description] |
| 2 | ... | ... | ... |

### 코드 미리보기

[Code preview for each step]

### 영향 분석

- 영향받는 파일: [count]
- 생성할 심볼: [count]
- 수정할 심볼: [count]
- Breaking changes: [yes/no]
AskUserQuestion:
  question: "이 계획대로 진행할까요?"
  header: "승인"
  options:
    - label: "승인 및 실행"
      description: "계획대로 코드 삽입 진행"
    - label: "Dry Run 먼저"
      description: "실제 변경 없이 시뮬레이션"
    - label: "계획 수정 필요"
      description: "요구사항 변경 또는 추가 설명"
    - label: "취소"
      description: "작업 취소"

Step 5: Execute Injection

If Dry Run Selected

Task:
  agent: "code-injector"
  prompt: |
    Perform dry run of injection plan.

    ## Plan
    [implementation plan from step 3]

    ## Mode
    dry_run: true

    Validate all steps without making changes.
    Report any potential issues.

If Approved

Task:
  agent: "code-injector"
  prompt: |
    Execute injection plan.

    ## Plan
    [implementation plan from step 3]

    ## Mode
    dry_run: false

    Execute all steps in order.
    Verify each step before proceeding.
    Report results and any issues.

Step 6: Post-Injection Actions

Verify Results

  1. Syntax Check Run appropriate linter/compiler for the language

  2. Symbol Verification Confirm all new symbols are accessible

  3. Reference Check Ensure no broken references

Update Knowledge Graph

# 1. Read existing graph
mcp__serena__read_memory:
  key: "project-knowledge-graph.md"

# 2. Merge updates and write back
mcp__serena__write_memory:
  key: "project-knowledge-graph.md"
  content: |
    [Updated knowledge graph with new additions:
    - New symbols: [list]
    - New dependencies: [list]
    - Updated patterns: [list]]

Suggest Next Steps

## 완료!

### 추가된 항목
- [list of created/modified items]

### 다음 단계 제안

1. **테스트 작성**
   ```bash
   # 새 기능에 대한 테스트 추가
   [test command suggestion]
  1. 변경사항 검토

    git diff
    
  2. 커밋 (만족스러운 경우)

    git add . && git commit -m "feat: [feature description]"
    
  3. 추가 기능 /serena-refactor:inject 로 더 많은 기능 추가


---

## Error Handling

### Knowledge Extraction Failed

```markdown
지식 추출 중 오류가 발생했습니다.

**가능한 원인:**
- Serena 프로젝트가 활성화되지 않음
- 지원되지 않는 언어/프레임워크
- 파일 접근 권한 문제

**해결 방법:**
1. `/serena-refactor:analyze` 로 프로젝트 상태 확인
2. Serena 설정 확인

Planning Failed

구현 계획 생성 중 오류가 발생했습니다.

**가능한 원인:**
- 기능 설명이 모호함
- 일치하는 패턴을 찾을 수 없음
- 프로젝트 구조와 맞지 않는 요청

**해결 방법:**
1. 더 구체적인 기능 설명 제공
2. 예시 코드나 참조할 기존 코드 지정

Injection Failed

코드 삽입 중 오류가 발생했습니다.

**오류 상세:**
[error details]

**롤백 상태:**
[rollback status]

**복구 방법:**
1. `git status` 로 변경된 파일 확인
2. `git checkout [file]` 로 원복
3. 계획 수정 후 재시도

Examples

Example 1: Add New Service

/serena-refactor:inject 사용자 알림을 처리하는 NotificationService 추가

Expected flow:

  1. Extract knowledge (if needed)
  2. Analyze existing service patterns
  3. Plan NotificationService following conventions
  4. Insert in appropriate location
  5. Update exports and registrations

Example 2: Extend Existing Class

/serena-refactor:inject UserRepository에 findByEmail 메서드 추가

Expected flow:

  1. Load existing knowledge
  2. Find UserRepository symbol
  3. Analyze existing methods for style
  4. Plan new method following patterns
  5. Insert after existing methods

Example 3: Add New Endpoint

/serena-refactor:inject POST /api/orders 엔드포인트 추가, 주문 생성 처리

Expected flow:

  1. Load knowledge
  2. Identify controller/handler patterns
  3. Plan new handler with validation, service call, response
  4. Insert following existing endpoint patterns
  5. Update route registrations

Plan Command

Refactoring plan creation command.

Usage

/serena-refactor:plan [target]

Workflow

Step 1: Activate Serena Project

mcp__serena__activate_project:
  project: [target directory]

Step 2: Analysis (Brief)

Task:
  agent: "serena-solid-analyzer"
  prompt: |
    Perform SOLID analysis on [target].
    Collect only key information needed for planning.

Step 3: Create Plan

Task:
  agent: "refactor-planner"
  prompt: |
    Create detailed refactoring plan based on analysis results.

    Include:
    1. Dependency graph
    2. Steps defined by priority
    3. Serena tool execution plan for each step
    4. Impact scope and risks
    5. Rollback paths

Step 4: Output and Save Plan

## Refactoring Plan: [target]

[Detailed plan content]

---

Plan saved to file: .refactor-plan.md

To execute: `/serena-refactor:refactor --plan .refactor-plan.md`

Refactor Command

Full refactoring workflow using Serena MCP.

Usage

/serena-refactor:refactor [target]

Workflow Overview

╔═══════════════════════════════════════════════════════════════════════════╗
║                     SERENA REFACTORING WORKFLOW                            ║
╠═══════════════════════════════════════════════════════════════════════════╣
║                                                                           ║
║  ┌─────────────────┐                                                      ║
║  │ 0. INITIALIZE   │ ← Activate Serena project + Git backup               ║
║  └────────┬────────┘                                                      ║
║           ▼                                                               ║
║  ┌─────────────────┐                                                      ║
║  │ 1. SOLID ANAL.  │ ← serena-solid-analyzer                              ║
║  └────────┬────────┘                                                      ║
║           ▼                                                               ║
║  ┌─────────────────┐                                                      ║
║  │ 2. PLAN         │ ← refactor-planner                                   ║
║  └────────┬────────┘                                                      ║
║           ▼                                                               ║
║  ╔═════════════════════════════════════════════════════════════════════╗  ║
║  ║  GATE: User Plan Approval                                           ║  ║
║  ╚═══════════════════════════════╤═════════════════════════════════════╝  ║
║                                  ▼                                        ║
║  ┌─────────────────────────────────────────────────────────────────┐     ║
║  │ 3. STEP-BY-STEP EXECUTION                                        │     ║
║  │    ┌────────────────────────────────────────────────────────┐   │     ║
║  │    │ FOR each step:                                          │   │     ║
║  │    │   3.1 Execute serena-refactor-executor                 │   │     ║
║  │    │   3.2 Verify with refactor-auditor                     │   │     ║
║  │    │   3.3 PASS → next step / FAIL → fix                    │   │     ║
║  │    │   [LOOP until all steps complete]                       │   │     ║
║  │    └────────────────────────────────────────────────────────┘   │     ║
║  └────────────────────────────────┬────────────────────────────────┘     ║
║                                   ▼                                       ║
║  ┌─────────────────┐                                                      ║
║  │ 4. FINAL VERIFY │ ← refactor-auditor (full)                            ║
║  └────────┬────────┘                                                      ║
║           ▼                                                               ║
║  ┌─────────────────┐                                                      ║
║  │ 5. REPORT       │                                                      ║
║  └─────────────────┘                                                      ║
║                                                                           ║
╚═══════════════════════════════════════════════════════════════════════════╝

Step 0: Initialize

Activate Serena Project

mcp__serena__activate_project:
  project: [target directory]

Create Git Backup

git stash push -m "pre-refactor-backup-$(date +%Y%m%d-%H%M%S)"

Step 1: SOLID Analysis

Task:
  agent: "serena-solid-analyzer"
  prompt: |
    Perform SOLID analysis on [target].

    Using Serena symbol tools:
    1. Analyze all class/function structures
    2. Map reference relationships
    3. Detect SOLID violations
    4. Provide auto-fix paths for each violation

Display analysis summary


Step 2: Refactoring Plan

Task:
  agent: "refactor-planner"
  prompt: |
    Create refactoring plan based on SOLID analysis results.

    Requirements:
    1. Define steps by priority
    2. Serena tool execution plan for each step
    3. Impact scope analysis
    4. Specify rollback paths

User Approval

AskUserQuestion:
  question: "Reviewed the refactoring plan. Proceed?"
  header: "Plan Approval"
  options:
    - label: "Approve - Proceed"
      description: "Execute refactoring as planned"
    - label: "Needs modification"
      description: "Adjust plan and re-review"
    - label: "Cancel"
      description: "Abort refactoring"

Step 3: Step-by-Step Execution

For each step:

3.1 Execute
Task:
  agent: "serena-refactor-executor"
  prompt: |
    Execute refactoring Step [N].

    Goal: [step goal]
    Target: [symbol path]

    Serena tool execution order:
    1. [tool and parameters]
    2. [tool and parameters]
    ...
3.2 Verify
Task:
  agent: "refactor-auditor"
  prompt: |
    Verify Step [N] refactoring results.

    Check items:
    1. Incomplete patterns (TODO, FIXME)
    2. Reference integrity
    3. SOLID improvement
    4. Test passing
3.3 Handle Results

If PASS:

  • Proceed to next step
  • Update progress

If FAIL:

AskUserQuestion:
  question: "Step [N] verification failed. What to do?"
  header: "Verification Failed"
  options:
    - label: "Fix issues and re-verify"
      description: "Fix discovered issues"
    - label: "Skip this step"
      description: "Proceed to next step (not recommended)"
    - label: "Rollback"
      description: "Undo this step's changes"

Step 4: Final Verification

Task:
  agent: "refactor-auditor"
  prompt: |
    Perform final verification of all refactoring results.

    Scope: All changed files

    Check items:
    1. Overall SOLID improvement
    2. All tests passing
    3. No new violations
    4. Reference integrity

Step 5: Completion Report

## Refactoring Completion Report

### Summary
- Total steps: [N]
- Successful steps: [M]
- Changed files: [X]

### SOLID Improvement
| Principle | Before | After | Improvement |
|-----------|--------|-------|-------------|
| SRP | X | Y | +Z% |
| OCP | X | Y | +Z% |
| ... | ... | ... | ... |

### Major Changes
1. [Change 1]
2. [Change 2]
...

### Test Results
✓ All tests passed

### Next Steps
- `git commit` to commit changes
- `git stash drop` to delete backup (optional)

Rollback

Rollback available anytime:

# Full rollback
git stash pop

# Or specific files only
git checkout -- [file]

Core Rules

  1. Symbol tools first - Serena symbol tools are always priority
  2. Step-by-step verification - Must verify after each step
  3. User consent - Major decisions require user approval
  4. Rollback ready - Always maintain restorable state
  5. No incomplete code - Leaving TODO/FIXME means failure

Rename Command

Safe symbol renaming using Serena MCP.

Usage

/serena-refactor:rename <symbol> <new-name>

Examples

/serena-refactor:rename UserService/getUser fetchUserById
/serena-refactor:rename OldClassName NewClassName

Workflow

Step 1: Verify Symbol

mcp__serena__find_symbol:
  name_path_pattern: [symbol]
  include_body: False

If symbol not found:

AskUserQuestion:
  question: "Symbol '[symbol]' not found. Please enter the correct path."
  header: "Symbol Path"

Step 2: Impact Analysis

mcp__serena__find_referencing_symbols:
  name_path: [symbol]
  relative_path: [file]

Step 3: Change Preview

## Rename Preview

### Target Symbol
- Name: [symbol]
- File: [file:line]
- Type: [class/method/function/variable]

### Impact Scope
| File | References | Code Snippet |
|------|------------|--------------|
| src/service.ts | 3 | `userService.getUser()` |
| src/controller.ts | 2 | `getUser(id)` |
| ... | ... | ... |

**Total references: N**

Step 4: User Confirmation

AskUserQuestion:
  question: "Proceed with [symbol] → [new-name]? (N references to update)"
  header: "Rename"
  options:
    - label: "Proceed"
      description: "Auto-update all references"
    - label: "Cancel"
      description: "Cancel change"

Step 5: Execute Rename

mcp__serena__rename_symbol:
  name_path: [symbol]
  relative_path: [file]
  new_name: [new-name]

Step 6: Verify Results

## Rename Complete

✓ [symbol] → [new-name]
✓ [N] references updated

### Changed Files
- src/service.ts
- src/controller.ts
- ...

### Next Steps
- Recommended: Run tests `npm test`
- On issues: Rollback with `git checkout -- .`

Core Rules

  1. Trust symbol tools - Serena rename_symbol auto-updates all references
  2. Preview required - Verify impact scope before change
  3. User confirmation - Explicit consent before execution
  4. Recommend tests - Recommend test run after change

E2E Test Command

Execute real user behavior simulation tests using Playwright MCP tools.

Load Skills

Skill("serena-refactor:user-simulation-test")

Usage

/serena-refactor:e2e-test [options]

Options

  • --type=ui|api|integration|scenario - Test type (default: auto-detect)
  • --url=<url> - Target URL (default: auto-detect from project)
  • --scenario=<name> - Run specific scenario only
  • --env=local|staging|production - Environment (default: local)
  • --screenshots - Capture screenshots on failure
  • --verbose - Detailed output
  • --dry-run - Show test plan without execution

Workflow Overview

┌──────────────────────────────────────────────────────────────┐
│                    /e2e-test Workflow                        │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  ┌─────────────┐                                             │
│  │   Start     │                                             │
│  └──────┬──────┘                                             │
│         │                                                    │
│         ▼                                                    │
│  ┌─────────────────────┐                                     │
│  │ Environment Check   │                                     │
│  │ - Playwright MCP?   │                                     │
│  │ - Dev server?       │                                     │
│  │ - Project type?     │                                     │
│  └──────┬──────────────┘                                     │
│         │                                                    │
│         ▼                                                    │
│  ┌─────────────────────────────────────────────────┐         │
│  │              Test Type Selection                 │         │
│  │     (UI / API / Integration / Scenario)         │         │
│  └──────────────────────┬──────────────────────────┘         │
│                         │                                    │
│                         ▼                                    │
│  ┌─────────────────────────────────────────────────┐         │
│  │           Scenario Generation/Load               │         │
│  │       (Auto-generate or load from file)         │         │
│  └──────────────────────┬──────────────────────────┘         │
│                         │                                    │
│                         ▼                                    │
│  ┌─────────────────────────────────────────────────┐         │
│  │                User Review                       │         │
│  │           (Approve test plan)                   │         │
│  └──────────────────────┬──────────────────────────┘         │
│                         │                                    │
│                         ▼                                    │
│  ┌─────────────────────────────────────────────────┐         │
│  │              e2e-test-runner agent              │         │
│  │             (Execute tests)                     │         │
│  └──────────────────────┬──────────────────────────┘         │
│                         │                                    │
│                         ▼                                    │
│  ┌─────────────────────────────────────────────────┐         │
│  │              Results & Report                    │         │
│  └──────────────────────┬──────────────────────────┘         │
│                         │                                    │
│                         ▼                                    │
│  ┌─────────────┐                                             │
│  │   Complete  │                                             │
│  └─────────────┘                                             │
│                                                              │
└──────────────────────────────────────────────────────────────┘

Step 1: Environment Check

Check Playwright MCP Availability

Look for these tools in available MCP tools:

  • mcp__plugin_playwright_playwright__browser_navigate
  • mcp__plugin_playwright_playwright__browser_snapshot
  • mcp__plugin_playwright_playwright__browser_click

If not available:

## Playwright MCP 필요

E2E 테스트를 실행하려면 Playwright MCP 서버가 필요합니다.

### 설치 방법

1. `~/.claude/mcp_servers.json`에 추가:

```json
{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["@anthropic-ai/mcp-playwright"]
    }
  }
}
  1. Claude Code 재시작

### Check Dev Server

```bash
# Try common development ports
curl -s -o /dev/null -w "%{http_code}" http://localhost:3000
curl -s -o /dev/null -w "%{http_code}" http://localhost:8000
curl -s -o /dev/null -w "%{http_code}" http://localhost:5173  # Vite
curl -s -o /dev/null -w "%{http_code}" http://localhost:4200  # Angular

If no server running:

AskUserQuestion:
  question: "개발 서버가 실행 중이지 않습니다. 어떻게 할까요?"
  header: "서버 상태"
  options:
    - label: "서버 시작 명령어 제공"
      description: "npm run dev, python manage.py runserver 등"
    - label: "외부 URL 사용"
      description: "staging 또는 production URL 입력"
    - label: "테스트 취소"
      description: "서버 시작 후 다시 시도"

Step 2: Test Type Selection

If not specified in command:

AskUserQuestion:
  question: "어떤 유형의 테스트를 실행하시겠습니까?"
  header: "테스트 유형"
  options:
    - label: "UI E2E 테스트 (Recommended)"
      description: "Playwright로 브라우저 상호작용 테스트"
    - label: "API 시퀀스 테스트"
      description: "HTTP 요청 시퀀스로 API 플로우 테스트"
    - label: "통합 테스트"
      description: "UI + API 조합 테스트"
    - label: "시나리오 기반"
      description: "미리 정의된 시나리오 파일 실행"
  multiSelect: false

Step 3: Scenario Generation

Auto-Generate Scenarios

  1. Discover Project Routes

    Grep: "path=|Route|router\." in src/**/*.{js,jsx,ts,tsx,py}
    
  2. Identify Key User Flows

    • Look for authentication (login, logout, register)
    • Look for CRUD operations
    • Look for forms and submissions
  3. Generate Test Plan

    ## 자동 생성된 테스트 계획
    
    ### 발견된 플로우
    
    | 플로우 | 페이지/엔드포인트 | 예상 단계 |
    |--------|-------------------|-----------|
    | 로그인 | /login | 3 |
    | 회원가입 | /register | 5 |
    | 대시보드 | /dashboard | 2 |
    
    ### 제안 시나리오
    
    1. **인증 플로우**
       - 로그인 → 대시보드 확인 → 로그아웃
    
    2. **주요 기능 플로우**
       - [프로젝트별 기능 기반 생성]
    

Load Existing Scenarios

If scenario file exists (e.g., e2e/scenarios.yaml, tests/e2e/*.spec.ts):

Read: e2e/scenarios.yaml
# or
Read: tests/e2e/login.spec.ts

Step 4: User Review

Present test plan:

## 테스트 계획

### 환경
- **URL**: http://localhost:3000
- **Environment**: local
- **Test Type**: UI E2E

### 실행할 시나리오

| # | 시나리오 | 단계 수 | 예상 시간 |
|---|----------|---------|-----------|
| 1 | 로그인 플로우 | 4 | ~10s |
| 2 | 메인 기능 테스트 | 8 | ~30s |
| 3 | 에러 핸들링 | 3 | ~10s |

### 예상 리소스 사용
- 브라우저 세션: 1개
- 스크린샷: 실패 시만
- 예상 소요 시간: ~1분
AskUserQuestion:
  question: "이 테스트 계획을 실행할까요?"
  header: "실행 승인"
  options:
    - label: "실행"
      description: "테스트 시작"
    - label: "시나리오 수정"
      description: "특정 시나리오만 선택하거나 수정"
    - label: "취소"
      description: "테스트 취소"

Step 5: Execute Tests

Task:
  agent: "e2e-test-runner"
  prompt: |
    Execute E2E tests with the following configuration:

    ## Test Configuration
    - Type: ${test_type}
    - URL: ${target_url}
    - Environment: ${environment}
    - Options:
      - screenshots: ${screenshots}
      - verbose: ${verbose}
      - fail_fast: ${fail_fast}

    ## Scenarios
    ${scenarios_yaml}

    Execute all scenarios and report results.

Step 6: Results & Report

Success Report

## E2E 테스트 완료!

### 결과 요약

| 항목 | 결과 |
|------|------|
| 총 시나리오 | 5 |
| 성공 | 5 |
| 실패 | 0 |
| 소요 시간 | 45.2초 |

### 시나리오별 결과

- [x] 로그인 플로우 (8.1s)
- [x] 회원가입 플로우 (12.3s)
- [x] 대시보드 네비게이션 (5.2s)
- [x] 프로필 수정 (10.1s)
- [x] 로그아웃 (2.5s)

### 다음 단계

모든 테스트가 통과했습니다! 이제:
- `git add . && git commit -m "feat: ..."` 로 커밋
- 또는 추가 기능 개발 진행

Failure Report

## E2E 테스트 완료 (일부 실패)

### 결과 요약

| 항목 | 결과 |
|------|------|
| 총 시나리오 | 5 |
| 성공 | 3 |
| 실패 | 2 |
| 소요 시간 | 62.5초 |

### 실패한 테스트

#### 회원가입 플로우
- **실패 단계**: 3/5 (이메일 입력)
- **에러**: `Element [data-testid='email-input'] not found`
- **스크린샷**: register_step3_fail.png

**가능한 원인**:
- data-testid가 변경됨
- 페이지 로딩 지연

**제안 수정**:
```typescript
// 기존 selector 확인
await page.getByTestId('email-input')
// 또는 대안 사용
await page.getByPlaceholder('이메일')

결제 플로우
  • 실패 단계: 6/8 (결제 버튼 클릭)
  • 에러: Button disabled due to validation error
  • 콘솔 에러: Invalid card number format

가능한 원인:

  • 테스트 카드 번호 형식 오류
  • 유효성 검사 로직 변경

다음 단계

  1. 실패한 테스트 원인 분석
  2. 코드 또는 테스트 시나리오 수정
  3. /serena-refactor:e2e-test --scenario=register 로 재실행

---

## Error Handling

### Playwright Not Available

```markdown
## Playwright MCP를 찾을 수 없습니다

E2E 테스트에는 Playwright MCP 서버가 필요합니다.

### 설정 방법

1. MCP 서버 설정 파일 열기:
   ```bash
   code ~/.claude/mcp_servers.json
  1. Playwright 추가:

    {
      "mcpServers": {
        "playwright": {
          "command": "npx",
          "args": ["@anthropic-ai/mcp-playwright"]
        }
      }
    }
    
  2. Claude Code 재시작

API 테스트 대안

브라우저 테스트 없이 API 테스트만 실행하려면:

/serena-refactor:e2e-test --type=api

### Server Not Running

```markdown
## 개발 서버가 실행 중이지 않습니다

테스트 대상 서버를 찾을 수 없습니다.

### 서버 시작 방법

프로젝트 유형에 따라:

```bash
# Node.js/React/Vue
npm run dev

# Python/FastAPI
uvicorn main:app --reload

# Django
python manage.py runserver

# Next.js
npm run dev

외부 URL 사용

이미 배포된 환경을 테스트하려면:

/serena-refactor:e2e-test --url=https://staging.example.com

### Browser Installation Required

```markdown
## 브라우저 설치 필요

Playwright 브라우저가 설치되지 않았습니다.

### 자동 설치 시도

mcp__plugin_playwright_playwright__browser_install


### 수동 설치

```bash
npx playwright install chromium

---

## Examples

### Example 1: Quick Smoke Test

/serena-refactor:e2e-test


Auto-detects project, generates basic scenarios, runs tests.

### Example 2: Specific URL

/serena-refactor:e2e-test --url=http://localhost:3000


### Example 3: API Only

/serena-refactor:e2e-test --type=api --url=http://localhost:8000


### Example 4: With Screenshots

/serena-refactor:e2e-test --screenshots --verbose


### Example 5: Staging Environment

/serena-refactor:e2e-test --env=staging --url=https://staging.example.com


### Example 6: Dry Run

/serena-refactor:e2e-test --dry-run


Shows what would be tested without actually running.

Debug Command

Systematic 6-phase debugging workflow with parallel agent exploration.

Load Skills

Skill("serena-refactor:debugging-workflow")

Usage

/serena-refactor:debug [bug description or error message]

Workflow Overview

┌──────────────────────────────────────────────────────────────┐
│                    /debug Workflow                           │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  Phase 1: DISCOVERY                                          │
│  ┌─────────────────────────────────────────────────┐         │
│  │ Gather bug symptoms, reproduction steps,        │         │
│  │ error messages, and context                     │         │
│  └──────────────────────┬──────────────────────────┘         │
│                         │                                    │
│  Phase 2: EXPLORATION (Parallel Agents)                      │
│  ┌─────────────────────────────────────────────────┐         │
│  │  ┌──────────┐  ┌──────────┐  ┌──────────┐       │         │
│  │  │ Explorer │  │ Explorer │  │ Explorer │       │         │
│  │  │ (Path)   │  │ (Data)   │  │ (Deps)   │       │         │
│  │  └──────────┘  └──────────┘  └──────────┘       │         │
│  └──────────────────────┬──────────────────────────┘         │
│                         │                                    │
│  Phase 3: ROOT CAUSE ANALYSIS                                │
│  ┌─────────────────────────────────────────────────┐         │
│  │ Synthesize exploration findings,                │         │
│  │ identify true root cause                        │         │
│  └──────────────────────┬──────────────────────────┘         │
│                         │                                    │
│  Phase 4: FIX STRATEGY (Parallel Agents)                     │
│  ┌─────────────────────────────────────────────────┐         │
│  │  ┌───────────┐  ┌─────────────┐  ┌───────────┐  │         │
│  │  │ Minimal   │  │Comprehensive│  │ Defensive │  │         │
│  │  │ Strategy  │  │  Strategy   │  │ Strategy  │  │         │
│  │  └───────────┘  └─────────────┘  └───────────┘  │         │
│  └──────────────────────┬──────────────────────────┘         │
│                         │                                    │
│                    USER APPROVAL                             │
│                         │                                    │
│  Phase 5: IMPLEMENTATION                                     │
│  ┌─────────────────────────────────────────────────┐         │
│  │ Apply chosen fix strategy                       │         │
│  └──────────────────────┬──────────────────────────┘         │
│                         │                                    │
│  Phase 6: VERIFICATION (Parallel Agents)                     │
│  ┌─────────────────────────────────────────────────┐         │
│  │  ┌──────────┐  ┌───────────┐  ┌───────────┐     │         │
│  │  │ Direct   │  │Regression │  │ Edge Case │     │         │
│  │  │ Verify   │  │  Check    │  │  Check    │     │         │
│  │  └──────────┘  └───────────┘  └───────────┘     │         │
│  └──────────────────────┬──────────────────────────┘         │
│                         │                                    │
│                    COMPLETE                                  │
│                                                              │
└──────────────────────────────────────────────────────────────┘

Phase 1: Bug Discovery

Goal

Gather complete information about the bug before investigation.

Questions to Answer

AskUserQuestion:
  questions:
    - question: "버그의 증상을 자세히 설명해주세요"
      header: "증상"
      options:
        - label: "에러 발생"
          description: "에러 메시지, 예외, 크래시"
        - label: "잘못된 동작"
          description: "기능이 예상과 다르게 동작"
        - label: "성능 문제"
          description: "느림, 메모리 증가, 응답 없음"
        - label: "데이터 문제"
          description: "잘못된 데이터, 손실, 불일치"

    - question: "버그를 재현할 수 있나요?"
      header: "재현"
      options:
        - label: "항상 재현"
          description: "동일 조건에서 100% 재현"
        - label: "가끔 재현"
          description: "특정 조건에서만 재현"
        - label: "드물게 재현"
          description: "재현이 어려움"
        - label: "재현 불가"
          description: "한 번 발생 후 재현 안됨"

Collect Information

## Bug Report

### Symptom
[What is happening]

### Expected Behavior
[What should happen]

### Reproduction Steps
1. [Step 1]
2. [Step 2]
3. [Step 3]

### Error Output

[Error message, stack trace, logs]


### Context
- Environment: [dev/staging/prod]
- Version: [app version]
- First occurred: [date/time]
- Frequency: [always/sometimes/rare]

### Recent Changes
[Any relevant recent changes]

Phase 2: Codebase Exploration

Goal

Trace execution paths and understand affected code areas.

Launch Parallel Agents

Launch 2-3 debug-explorer agents with different focuses:

Agent 1 - Execution Path:
  Task:
    agent: "debug-explorer"
    prompt: |
      Focus: execution_path
      Bug: [description]
      Error location: [file:line if known]

      Trace the complete execution path from entry point to error.
      Identify all functions called, conditions evaluated, and branches taken.

Agent 2 - Data Flow:
  Task:
    agent: "debug-explorer"
    prompt: |
      Focus: data_flow
      Bug: [description]
      Error location: [file:line if known]

      Track data from its source to the error point.
      Identify all transformations, mutations, and handoffs.

Agent 3 - Dependencies:
  Task:
    agent: "debug-explorer"
    prompt: |
      Focus: dependencies
      Bug: [description]
      Error location: [file:line if known]

      Map all related components, shared state, and integrations.
      Identify potential interaction issues.

Serena MCP Integration

Use Serena MCP tools for symbol-level investigation:

# Find the symbol at error location
mcp__serena-daemon__find_symbol:
  name_path_pattern: "[function_name]"
  relative_path: "[file_path]"
  include_body: true

# Find all callers
mcp__serena-daemon__find_referencing_symbols:
  name_path: "[symbol_name]"
  relative_path: "[file_path]"

# Search for error patterns
mcp__serena-daemon__search_for_pattern:
  substring_pattern: "[error_text]"

Phase 3: Root Cause Analysis

Goal

Synthesize exploration findings to identify true root cause.

Analysis Template

## Root Cause Analysis

### Exploration Summary
[Key findings from Phase 2 agents]

### Immediate Cause
[What directly triggers the error]

### Underlying Cause
[Why this condition exists]

### Contributing Factors
- [Factor 1]
- [Factor 2]

### Root Cause Statement
**The bug occurs because [root cause] which leads to [immediate cause] resulting in [symptom].**

### Confidence: [X]%
[Justification for confidence level]

User Confirmation

AskUserQuestion:
  question: "분석된 근본 원인이 맞는 것 같나요?"
  header: "확인"
  options:
    - label: "맞음, 계속 진행"
      description: "근본 원인 분석에 동의"
    - label: "부분적으로 맞음"
      description: "추가 조사 필요"
    - label: "틀림, 재조사 필요"
      description: "다른 방향으로 조사"

Phase 4: Fix Strategy Design

Goal

Design multiple fix approaches with risk assessment.

Launch Parallel Agents

Launch 2-3 debug-strategist agents with different approaches:

Agent 1 - Minimal:
  Task:
    agent: "debug-strategist"
    prompt: |
      Approach: minimal
      Root Cause: [from Phase 3]
      Findings: [from Phase 2]

      Design the smallest possible fix that addresses the immediate problem.
      Minimize risk and touched files.

Agent 2 - Comprehensive:
  Task:
    agent: "debug-strategist"
    prompt: |
      Approach: comprehensive
      Root Cause: [from Phase 3]
      Findings: [from Phase 2]

      Design a thorough fix that addresses the root cause and prevents recurrence.
      Include related improvements if appropriate.

Agent 3 - Defensive:
  Task:
    agent: "debug-strategist"
    prompt: |
      Approach: defensive
      Root Cause: [from Phase 3]
      Findings: [from Phase 2]

      Design defensive measures: input validation, error boundaries, fallbacks.
      Focus on graceful failure and robust error handling.

Present Options

## Fix Strategy Options

### Option 1: Minimal Fix
- **Changes:** [count] files, [count] lines
- **Risk:** Low
- **Pros:** Quick, safe, minimal impact
- **Cons:** May not prevent recurrence

### Option 2: Comprehensive Fix
- **Changes:** [count] files, [count] lines
- **Risk:** Medium
- **Pros:** Addresses root cause, improves quality
- **Cons:** More testing needed

### Option 3: Defensive Fix
- **Changes:** [count] files, [count] lines
- **Risk:** Low-Medium
- **Pros:** Handles unknown edge cases
- **Cons:** May hide underlying issues

User Selection

AskUserQuestion:
  question: "어떤 수정 전략을 선택하시겠습니까?"
  header: "전략 선택"
  options:
    - label: "Minimal Fix (Recommended for hotfix)"
      description: "가장 작은 변경으로 증상 해결"
    - label: "Comprehensive Fix"
      description: "근본 원인 해결, 재발 방지"
    - label: "Defensive Fix"
      description: "방어 로직 추가, 안전한 실패"
    - label: "Combine approaches"
      description: "여러 전략 조합"

Phase 5: Implementation

Pre-Implementation Gate

Explicit user approval required before making changes.

AskUserQuestion:
  question: "선택한 전략으로 수정을 진행할까요?"
  header: "구현 승인"
  options:
    - label: "승인 - 수정 진행"
      description: "선택한 전략대로 코드 수정"
    - label: "Dry run 먼저"
      description: "변경 내용 미리보기만"
    - label: "전략 재검토"
      description: "Phase 4로 돌아가기"
    - label: "취소"
      description: "디버깅 세션 종료"

Implementation

Apply the chosen fix:

  1. Make code changes as specified
  2. Add defensive checks if applicable
  3. Update comments/documentation
  4. Stage changes for review
## Implementation Log

### Changes Made
| File | Lines | Description |
|------|-------|-------------|
| `file1.ts` | 45-50 | [change description] |

### Code Diff
[Show git diff or before/after]

Phase 6: Verification

Goal

Confirm the fix works and doesn't introduce new issues.

Launch Parallel Agents

Launch 2-3 debug-verifier agents with different focuses:

Agent 1 - Direct:
  Task:
    agent: "debug-verifier"
    prompt: |
      Focus: direct
      Original bug: [description]
      Fix applied: [description]
      Changed files: [list]

      Verify the original bug no longer occurs.
      Test the exact reproduction steps.

Agent 2 - Regression:
  Task:
    agent: "debug-verifier"
    prompt: |
      Focus: regression
      Original bug: [description]
      Fix applied: [description]
      Changed files: [list]

      Check for any new issues introduced by the fix.
      Review code for unintended side effects.

Agent 3 - Edge Cases:
  Task:
    agent: "debug-verifier"
    prompt: |
      Focus: edge_cases
      Original bug: [description]
      Fix applied: [description]
      Changed files: [list]

      Test boundary conditions and edge cases.
      Verify robust handling of unusual inputs.

Verification Summary

## Verification Results

### Direct Verification
- Original bug: [Fixed/Not Fixed]
- Confidence: [X]%

### Regression Check
- New issues found: [None/List]
- Confidence: [X]%

### Edge Case Check
- Edge cases handled: [Yes/Partial/No]
- Confidence: [X]%

### Final Verdict: [PASS/FAIL/CONDITIONAL]

Post-Verification Decision

AskUserQuestion:
  question: "검증 결과를 검토한 후 어떻게 할까요?"
  header: "다음 단계"
  options:
    - label: "커밋 및 완료"
      description: "수정 사항 커밋"
    - label: "추가 수정 필요"
      description: "발견된 이슈 수정"
    - label: "롤백"
      description: "변경 사항 되돌리기"

Workflow State Management

State files track progress:

FilePhasePurpose
.debug-discovery-done1Bug info collected
.debug-exploration-done2Exploration complete
.debug-rootcause-done3Root cause identified
.debug-strategy-approved4Strategy selected
.debug-fix-applied5Fix implemented
.debug-verified6Verification passed

Examples

Example 1: Simple Error

/serena-refactor:debug "TypeError: Cannot read property 'name' of undefined in UserService"

Example 2: Performance Issue

/serena-refactor:debug "API response takes 10+ seconds for large datasets"

Example 3: Intermittent Bug

/serena-refactor:debug "Login sometimes fails with 'session expired' even for new sessions"

Error Handling

Exploration Timeout

If exploration takes too long:

  • Summarize partial findings
  • Ask user to narrow scope
  • Continue with available information

No Root Cause Found

If root cause unclear:

  • Present best hypotheses
  • Suggest additional investigation
  • Offer defensive fix option

Fix Fails Verification

If fix doesn't work:

  • Document what was tried
  • Return to Phase 4
  • Consider alternative approach

Laboratory Command

Scientific experimentation workflow for exploring implementation approaches.

Load Skills

Skill("serena-refactor:laboratory-patterns")

Usage

/serena-refactor:laboratory [problem description]

Philosophy

"Apply scientific methodology to code implementation"

  • Problem decomposition -> Hypothesis formation -> Parallel experimentation -> Rigorous verification
  • Record and learn from failures
  • Balance between existing solutions and creative approaches

Trigger Scenarios

ModeSituationExample
ExplorationDon't know how to implement"How do I implement OAuth?"
BreakthroughStandard approach doesn't work"Need to bypass API limitations"
OptimizationLooking for better methods"Any performance improvements?"

7-Stage Workflow

+---------------------------------------------------------------------+
|  1. Problem Decomposition --[User Approval]--> 2. Existing Approaches |
|        |                                              |               |
|        |                                   [LLM Consult Available]    |
|        v                                              v               |
|  3. Creative Approaches ---------------> 4. Hypothesis Formation --[Approval]|
|                                               |                       |
|        +--------------------------------------+                       |
|        v                                                              |
|  5. PoC Experiments --[Approval]--> Parallel Execution (max 5)        |
|        |                                                              |
|   +----+----+--------+--------+--------+                              |
|   v         v        v        v        v                              |
| Hyp.A    Hyp.B    Hyp.C    Hyp.D    Hyp.E                             |
|   |         |        |        |        |                              |
|   +----+----+--------+--------+--------+                              |
|        v                                                              |
|  6. Verification --[LLM Consult on Failure]--> 7. Result Report       |
+---------------------------------------------------------------------+

Phase 1: Problem Decomposition

Goal

Break down the problem into smaller, testable units.

Steps

  1. Understand the full problem context
  2. Identify core requirements and constraints
  3. Decompose into sub-problems
  4. Define success criteria for each

User Approval Required

AskUserQuestion:
  questions:
    - question: "문제를 이렇게 분해했습니다. 맞나요?"
      header: "분해 확인"
      options:
        - label: "맞음, 계속 진행"
          description: "분해가 올바름"
        - label: "수정 필요"
          description: "일부 조정 필요"
        - label: "다시 분석"
          description: "완전히 다시 분석"
      multiSelect: false

Output Template

## Problem Decomposition

### Original Problem
[User's problem description]

### Core Constraints
- [Constraint 1]
- [Constraint 2]

### Sub-Problems
1. **[Sub-problem 1]**
   - Scope: [description]
   - Success Criteria: [criteria]

2. **[Sub-problem 2]**
   - Scope: [description]
   - Success Criteria: [criteria]

### Dependencies
- [Sub-problem 1] must be solved before [Sub-problem 2]

Phase 2: Existing Approaches Collection

Goal

Gather verified solutions from external sources.

Information Sources (Priority Order)

  1. GitHub Issues/Discussions - Real developer problem-solving cases
  2. Stack Overflow - Community-vetted solutions
  3. Official Docs + Context7 - Standard methods, API usage

Launch Helper Agent

Task:
  subagent_type: "serena-refactor:source-fetcher"
  prompt: |
    Problem: [description]
    Constraints: [list]

    Search for existing solutions from:
    1. GitHub Issues (search for similar problems)
    2. Stack Overflow (search for verified answers)
    3. Official documentation via Context7

    Return structured findings with source links.

LLM Consultant Available

If existing sources are insufficient, consult external LLMs:

Task:
  subagent_type: "serena-refactor:llm-consultant"
  prompt: |
    ## Project Context
    - Language/Framework: [e.g., TypeScript, Next.js 14]
    - Dependencies: [e.g., prisma, zod]
    - Architecture: [e.g., App Router]

    ## Problem
    [Detailed problem description]

    ## Constraints
    [List all constraints]

    ## Question
    What approaches would you recommend for solving this problem?

Phase 3: Creative Approaches Generation

Goal

Generate novel approaches beyond documented solutions.

Creative Approach Types

TypeDescription
API BypassImplement features not officially supported
Technology CombinationNovel combinations of libraries/patterns
Constraint-IgnoringTry things assumed impossible

Launch Helper Agent

Task:
  subagent_type: "serena-refactor:creative-generator"
  prompt: |
    Problem: [description]
    Existing Approaches: [from Phase 2]
    Constraints: [list]

    Generate creative approaches:
    1. API bypass/workarounds
    2. Unexpected technology combinations
    3. Constraint-ignoring experiments

    Consider patterns from skillmaker (isolated daemons, prompt injection, CLI tricks).

Phase 4: Hypothesis Formation

Goal

Structure approaches into testable hypotheses.

Launch Core Agent

Task:
  subagent_type: "serena-refactor:lab-analyst"
  prompt: |
    Existing Approaches: [from Phase 2]
    Creative Approaches: [from Phase 3]
    Constraints: [list]

    Form up to 5 testable hypotheses:
    - Expected outcome
    - Risks and limitations
    - Required resources
    - Success criteria

User Approval Required

AskUserQuestion:
  questions:
    - question: "이 가설들로 실험을 진행할까요?"
      header: "가설 승인"
      options:
        - label: "승인 - 모두 실험"
          description: "제시된 모든 가설 테스트"
        - label: "일부만 선택"
          description: "특정 가설만 테스트"
        - label: "가설 수정"
          description: "가설 조정 후 재검토"
        - label: "접근법 재수집"
          description: "Phase 2-3로 돌아가기"
      multiSelect: false

Hypothesis Card Template

### Hypothesis [A-E]: [Name]

**Approach**: [description]
**Source**: Existing / Creative / LLM Suggestion

**Expected Outcome**
[What should happen if this works]

**Risks**
- [Risk 1]
- [Risk 2]

**Limitations**
- [Limitation 1]

**Resources Required**
- [Library/tool 1]
- [API/service 1]

**Success Criteria**
- [ ] [Criterion 1]
- [ ] [Criterion 2]

Phase 5: PoC Experiments

Goal

Implement and run parallel proof-of-concept experiments.

User Approval Required

AskUserQuestion:
  questions:
    - question: "PoC 코드 작성을 시작할까요?"
      header: "실험 승인"
      options:
        - label: "승인 - 실험 시작"
          description: "선택된 가설들의 PoC 구현"
        - label: "Dry run 먼저"
          description: "코드 구조만 미리보기"
        - label: "가설 재검토"
          description: "Phase 4로 돌아가기"
        - label: "취소"
          description: "실험 세션 종료"
      multiSelect: false

Launch Parallel Experiments

# Launch up to 5 parallel experimenter agents
Agent 1 - Hypothesis A:
  Task:
    subagent_type: "serena-refactor:lab-experimenter"
    run_in_background: true
    prompt: |
      Hypothesis: A - [name]
      Approach: [description]
      Success Criteria: [list]

      Implement PoC and run initial tests.
      Return: code location, test results, issues found.

Agent 2 - Hypothesis B:
  Task:
    subagent_type: "serena-refactor:lab-experimenter"
    run_in_background: true
    prompt: |
      Hypothesis: B - [name]
      ...

# Continue for all selected hypotheses (max 5)

Collect Results

# Wait for all experiments to complete
TaskOutput:
  task_id: [experimenter-A-id]
  block: true

TaskOutput:
  task_id: [experimenter-B-id]
  block: true

# ... for all experiments

Phase 6: Verification

Goal

Rigorously verify experimental results.

Verification Criteria

  • Test Pass/Fail: All tests must pass
  • Edge Case Coverage: Handle boundary conditions
  • Reproducibility: Same results on repeat

Launch Verification Agents

Task:
  subagent_type: "serena-refactor:lab-verifier"
  prompt: |
    Hypothesis: [name]
    PoC Location: [path]
    Expected: [criteria]

    Verify:
    1. Run all tests
    2. Check edge cases
    3. Confirm reproducibility

    Return: PASS/FAIL with confidence score.

Edge Case Analysis

Task:
  subagent_type: "serena-refactor:edge-case-hunter"
  prompt: |
    Implementation: [description]
    Code Location: [path]

    Identify edge cases:
    1. Boundary conditions
    2. Error scenarios
    3. Concurrent access
    4. Resource limits

On Verification Failure

If verification fails, consult external LLMs:

Task:
  subagent_type: "serena-refactor:llm-consultant"
  prompt: |
    ## Context
    [Full project context]

    ## What We Tried
    [Hypothesis and implementation]

    ## Failure Details
    [Test results, error messages]

    ## Questions
    1. Why might this have failed?
    2. What alternatives exist?

Phase 7: Result Report

Goal

Document findings and recommendations.

Generate Reports

  1. Markdown Report: docs/lab-reports/YYYY-MM-DD-{topic}.md
  2. Serena Memory: .serena/memories/lab-{topic}.md

Report Template

# Experiment Report: [Topic]

**Date**: [YYYY-MM-DD HH:mm]
**Problem**: [Original problem description]

## 1. Problem Decomposition
- Sub-problem 1: ...
- Sub-problem 2: ...

## 2. Explored Approaches

### Existing Solutions
| Source | Approach | Summary |
|--------|----------|---------|
| GitHub Issue #123 | ... | ... |
| Stack Overflow | ... | ... |

### Creative Attempts
| Approach | Idea | Risk |
|----------|------|------|
| API Bypass | ... | ... |

## 3. Tested Hypotheses

### Hypothesis A: [Name]
- **Result**: [Success/Failure/Partial]
- **Tests Passed**: X/Y
- **Edge Cases**: X/Y
- **Reproducibility**: [Confirmed/Issues]

### Hypothesis B: [Name]
- **Result**: [Failure]
- **Failure Reason**: [Analysis]
- **Partial Success Conditions**: [When it worked]

## 4. LLM Consultation Log
| LLM | Question | Key Advice |
|-----|----------|------------|
| Gemini | ... | ... |
| Codex | ... | ... |

## 5. Final Recommendation
**Selection**: Hypothesis [X]
**Reason**: [Justification]

## 6. Lessons Learned
- [Insight for future problems]

Serena Memory Template

# Lab: [Topic]

## Key Findings
- [Summary]

## Working Approaches
- [Verified solutions]

## Approaches to Avoid
- [Failed methods and reasons]

## Related Resources
- [Useful links]

Workflow State Management

State files track progress:

FilePhasePurpose
.lab-problem-defined1Problem decomposed
.lab-approaches-collected2-3Approaches gathered
.lab-hypotheses-approved4Hypotheses confirmed
.lab-experiments-running5Experiments in progress
.lab-experiments-done5Experiments complete
.lab-verified6Verification done
.lab-report-generated7Report created

Examples

Example 1: Implementation Exploration

/serena-refactor:laboratory "How should I implement rate limiting for my API?"

Example 2: Breakthrough Mode

/serena-refactor:laboratory "The official SDK doesn't support batch operations, need alternative"

Example 3: Optimization Research

/serena-refactor:laboratory "Current image processing takes 10 seconds, need faster approach"

Error Handling

No Viable Approaches Found

If Phase 2-3 finds nothing:

  • Expand search scope
  • Try different keywords
  • Consult LLMs with broader context
  • Report limitation to user

All Hypotheses Fail

If all experiments fail:

  • Document failure reasons
  • Analyze partial successes
  • Suggest alternative problem framing
  • Save learnings for future

Resource Constraints

If experiments exceed resources:

  • Prioritize by expected success
  • Run sequentially instead of parallel
  • Suggest scope reduction

Agents 19

SOLID Analyzer Agent

ultrathink

Analyzes code symbols and patterns to detect SOLID principle violations. This agent receives pre-fetched data from the main session and focuses purely on analysis logic.

Important: Data-Driven Analysis

This agent does NOT call MCP tools directly. It receives:

  • Symbol overviews from get_symbols_overview
  • Pattern search results from search_for_pattern
  • Symbol bodies from find_symbol
  • Reference data from find_referencing_symbols

Analysis Protocol

SRP Analysis (Single Responsibility Principle)

Violation Indicators:

  • Class with > 10 methods
  • Class with > 5 external dependencies
  • Method with > 20 lines
  • Class name contains "And", "Manager", "Handler", "Utils"
  • Method that does multiple unrelated things

Severity Scoring:

  • HIGH: > 15 methods OR > 30 line methods
  • MEDIUM: 10-15 methods OR 20-30 line methods
  • LOW: Naming concerns only

OCP Analysis (Open-Closed Principle)

Violation Patterns (from search results):

  • switch(type) or switch(kind) patterns
  • if (x instanceof Y) chains
  • if (obj.type === "X") branching
  • Adding new behavior requires modifying existing code

Fix Recommendations:

  • Strategy pattern for type-based switching
  • Polymorphism for instanceof chains
  • Factory pattern for object creation

LSP Analysis (Liskov Substitution Principle)

Violation Patterns:

  • Empty method implementations (pass, return;, throw NotImplemented)
  • Methods that throw for unsupported operations
  • Subclasses that break parent contracts

Severity:

  • HIGH: Throws exception in override
  • MEDIUM: Empty implementation
  • LOW: Partial implementation

ISP Analysis (Interface Segregation Principle)

Violation Indicators:

  • Interface with > 5 methods
  • Implementations that don't use all interface methods
  • Fat interfaces that force unnecessary dependencies

Fix Recommendations:

  • Split into focused interfaces
  • Role interfaces pattern
  • Composition over inheritance

DIP Analysis (Dependency Inversion Principle)

Violation Patterns:

  • new Database(), new HttpClient() in business logic
  • Direct infrastructure imports in domain layer
  • Framework annotations (@Entity, @Table) in domain

Fix Recommendations:

  • Extract interfaces for infrastructure
  • Dependency injection
  • Ports and adapters pattern

Output Format

# SOLID Analysis Report

## Analysis Metadata
- Analysis timestamp: [timestamp]
- Files analyzed: [count]
- Symbols analyzed: [count]

## Summary
| Principle | Violations | Severity | Impact Scope |
|-----------|------------|----------|--------------|
| SRP | X | HIGH/MEDIUM/LOW | Y files |
| OCP | X | HIGH/MEDIUM/LOW | Y files |
| LSP | X | HIGH/MEDIUM/LOW | Y files |
| ISP | X | HIGH/MEDIUM/LOW | Y files |
| DIP | X | HIGH/MEDIUM/LOW | Y files |

## Detailed Violations

### SRP Violations
| File:Line | Symbol | Issue | Ref Count | Suggested Fix |
|-----------|--------|-------|-----------|---------------|
| src/service.ts:45 | UserService | 15 methods | 23 refs | Split into UserAuthService, UserProfileService |

### OCP Violations
| File:Line | Pattern | Issue | Suggested Fix |
|-----------|---------|-------|---------------|
| src/handler.ts:120 | switch(type) | 5 type branches | Strategy pattern |

### LSP Violations
| File:Line | Symbol | Issue | Suggested Fix |
|-----------|--------|-------|---------------|
| src/impl.ts:30 | NoOpHandler.handle | Empty implementation | Remove or implement properly |

### ISP Violations
| File:Line | Interface | Method Count | Suggested Fix |
|-----------|-----------|--------------|---------------|
| src/types.ts:10 | IRepository | 12 methods | Split into IReader, IWriter, IQueryable |

### DIP Violations
| File:Line | Symbol | Direct Dependency | Suggested Fix |
|-----------|--------|-------------------|---------------|
| src/service.ts:30 | UserService | new Database() | Inject IDatabase interface |

## Serena Fix Operations

For each violation, the recommended Serena MCP operation:

| Violation | Serena Operation | Parameters |
|-----------|------------------|------------|
| Rename class | `rename_symbol` | name_path, new_name |
| Extract method | `insert_after_symbol` + `replace_content` | body, replacement |
| Extract interface | `insert_before_symbol` | interface definition |
| Move method | `replace_symbol_body` | new location |

## Refactoring Priority

1. **[HIGH IMPACT]** [description] - affects X files
2. **[MEDIUM IMPACT]** [description] - affects Y files
3. ...

Core Rules

  1. Analyze provided data only - Do not request additional MCP calls
  2. Precise file:line references - Use locations from symbol data
  3. Include impact scope - Reference counts show modification scope
  4. Actionable recommendations - Specific Serena operations for each fix
  5. Prioritize by impact - High reference count = high priority

Serena Refactor Executor Agent

ultrathink

Provides refactoring execution guidance for the main session to execute via Serena MCP.

Load Skills

Skill("serena-refactor:solid-design-rules")
Skill("serena-refactor:serena-refactoring-patterns")

Architecture: Data-Driven Execution Guidance

This agent does NOT call MCP tools directly. It receives pre-fetched data and provides execution plans.

The main session:

  1. Gathers code data using Serena MCP tools
  2. Passes data to this agent for analysis
  3. Receives execution plan
  4. Executes MCP calls based on the plan

Execution Principles

  1. Symbol tools are reliable - No verification needed if no errors
  2. Check references first - Assess impact scope before modification
  3. Atomic modifications - Each step completes independently
  4. Rollback capability - Check git status and create commit points

Refactoring Patterns

Pattern 1: Rename Symbol

Safest refactoring - Serena auto-updates all references

Main session executes:

# 1. Check impact scope
mcp__serena__find_referencing_symbols(
    name_path="[original name]",
    relative_path="[file path]"
)

# 2. Execute rename
mcp__serena__rename_symbol(
    name_path="[original name]",
    relative_path="[file path]",
    new_name="[new name]"
)
# No verification needed - Serena is reliable

Pattern 2: Extract Method

Split long methods into shorter methods

Main session executes:

# 1. Read original method
mcp__serena__find_symbol(
    name_path_pattern="[class/method]",
    include_body=True
)

# 2. Create new method
mcp__serena__insert_after_symbol(
    name_path="[class/existing_method]",
    relative_path="[file]",
    body='''
def new_helper_method(params):
    # extracted logic
'''
)

# 3. Replace original with call
mcp__serena__replace_content(
    relative_path="[file]",
    needle="extracted code block pattern.*?end",
    repl="self.new_helper_method(args)",
    mode="regex"
)

Pattern 3: Extract Interface

Abstraction for DIP violation resolution

Main session executes:

# 1. Analyze class methods
mcp__serena__find_symbol(
    name_path_pattern="[class name]",
    depth=1,
    include_body=False
)

# 2. Generate interface definition
mcp__serena__insert_before_symbol(
    name_path="[class name]",
    relative_path="[file]",
    body='''
interface IClassName {
    method1(param: Type): ReturnType;
    method2(): void;
}
'''
)

Pattern 4: Move Method

Responsibility redistribution for SRP violation resolution

Main session executes:

# 1. Read original method
mcp__serena__find_symbol(
    name_path_pattern="[original_class/method]",
    include_body=True
)

# 2. Check references
mcp__serena__find_referencing_symbols(
    name_path="[original_class/method]",
    relative_path="[original file]"
)

# 3. Add method to target class
mcp__serena__insert_after_symbol(
    name_path="[target_class/last_method]",
    relative_path="[target file]",
    body="[method body]"
)

# 4. Update all call sites
mcp__serena__replace_content(
    relative_path="[each reference file]",
    needle="original_class\\.method",
    repl="target_class.method",
    mode="regex",
    allow_multiple_occurrences=True
)

Pattern 5: Replace Conditional with Polymorphism

OCP violation resolution

Main session executes:

# 1. Detect switch/if patterns
mcp__serena__search_for_pattern(
    substring_pattern="switch\\s*\\([^)]+\\)\\s*\\{[^}]+\\}",
    restrict_search_to_code_files=True
)

# 2. Extract each case to strategy class
mcp__serena__insert_after_symbol(
    name_path="[original class]",
    body='''
class ConcreteStrategyA implements Strategy {
    execute() { /* case A logic */ }
}
'''
)

# 3. Replace switch with strategy call
mcp__serena__replace_content(
    needle="switch.*?\\{.*?\\}",
    repl="strategyMap[type].execute()",
    mode="regex"
)

Pre-execution Checklist

# Check git status
git status --porcelain

# Create rollback point
git stash push -m 'pre-refactor-backup'

Post-execution Verification

# Run lint
npm run lint

# Type check
npm run typecheck

# Run tests
npm test

Error Handling

ErrorCauseResolution
Symbol not foundIncorrect name pathUse find_symbol to verify
Multiple matchesOverload or duplicateAdd index (e.g., method[0])
File not foundPath errorUse list_dir to verify

Core Rules

  1. Provide execution guidance - MCP calls are made by main session
  2. One refactoring at a time - Atomic changes
  3. References first - No modification without knowing impact scope
  4. Tests required - Verification mandatory after refactoring
  5. Keep records - Save history with write_memory

Refactor Planner Agent

ultrathink

Develops safe, incremental refactoring plans based on SOLID analysis results.

Load Skills

Skill("serena-refactor:solid-design-rules")
Skill("serena-refactor:serena-refactoring-patterns")

Architecture: Data-Driven Planning

This agent receives pre-fetched data from the main session. It does NOT call MCP tools directly.

The main session gathers data using Serena MCP tools and passes it to this agent:

  • Symbol overviews from get_symbols_overview
  • Reference data from find_referencing_symbols
  • Pattern matches from search_for_pattern

Planning Principles

  1. Change isolation - Each step is independent of others
  2. Testable - Verifiable after each step completion
  3. Rollback-capable - Can restore to previous state anytime
  4. Incremental improvement - Progress safely in small units

Planning Protocol

Step 1: Assess Current State

# Main session MCP call:
    type: MEMORY
    operation: list_memories

    Check if previous analysis results exist.
# Main session MCP call:
    type: QUERY
    operation: get_symbols_overview
    params:
      relative_path: [target path]
      depth: 2

    Understand code structure.

Step 2: Build Dependency Graph

For each major symbol:

# Main session MCP call:
    type: ANALYZE
    operation: find_referencing_symbols
    params:
      name_path: [symbol name]
      relative_path: [file]

    Map dependency relationships.

Create dependency map:

ComponentA
├── depends on: [B, C]
├── depended by: [D, E]
└── circular dependency: [yes/no]

Step 3: Determine Refactoring Priority

Priority Criteria:

PriorityConditionReason
1Circular dependency resolutionBlocks other refactoring
2Leaf nodes (no dependents)Minimal impact scope
3High violation densityEfficient improvement
4Low reference countSafe modification

Step 4: Create Step-by-Step Plan

For each refactoring step:

  1. Goal - What is being improved
  2. Target symbol - Exact symbol path
  3. Serena MCP calls - Tools and sequence for main session
  4. Affected files - List of files to be modified
  5. Verification method - Tests and checks
  6. Rollback method - Restoration procedure on failure

Output Format

# Refactoring Plan

## Metadata
- Creation timestamp: [timestamp]
- Target scope: [directory/files]
- Total steps: [N]
- Expected affected files: [M]

## Dependency Analysis

### Dependency Graph
```mermaid
graph TD
    A[ComponentA] --> B[ComponentB]
    A --> C[ComponentC]
    D[ComponentD] --> A

Circular Dependencies

  • [yes/no]
  • Resolution needed: [list]

Refactoring Steps

Phase 1: Foundation Cleanup

Step 1.1: [Action Name]

Goal: [Improvement description] SOLID Principle: [Violation being resolved]

Target:

  • Symbol: ClassName/methodName
  • File: src/path/to/file.ts:45
  • Reference count: X

Main Session MCP Execution Plan:

# 1. Query symbol (main session executes):
     type: QUERY
     operation: find_symbol
     params:
       name_path_pattern: "ClassName/methodName"
       include_body: true

# 2. Insert method (main session executes):
     type: MODIFY
     operation: insert_after_symbol
     params:
       name_path: "ClassName/existingMethod"
       body: "..."

# 3. Replace content (main session executes):
     type: MODIFY
     operation: replace_content
     params:
       needle: "..."
       repl: "..."
       mode: "regex"

Affected Files:

  • src/file1.ts (modification)
  • src/file2.ts (reference update)

Verification:

npm run lint && npm run typecheck && npm test

Rollback:

git checkout -- src/file1.ts src/file2.ts

Step 1.2: [Next Action]

...

Phase 2: Structure Improvement

Step 2.1: [Action Name]

...

Checkpoints

PhaseCompletion CriteriaVerification Method
1Foundation cleanup completeTests pass
2Structure improvement completeSOLID re-analysis
.........

Risk Assessment

StepRiskMitigation
1.1Low-
2.1MediumAdd unit tests
.........

Rollback Strategy

Full Rollback

git reset --hard HEAD~[N]

Partial Rollback (per Phase)

git checkout [commit-hash] -- [files]

Next Actions

  1. Request user plan approval
  2. Execute with serena-refactor-executor upon approval
  3. Verify with refactor-auditor after each step completion

---

## Planning Rules

1. **Circular dependencies first** - Resolve before other refactoring
2. **Leaf nodes priority** - Start with minimal impact scope
3. **One step = one concern** - No simultaneous multiple violation fixes
4. **No tests = tests first** - Add tests before refactoring
5. **Rollback path required** - Specify rollback method for all steps
6. **Analyze pre-fetched data only** - MCP calls are made by main session

Refactor Auditor Agent

ultrathink

Verifies refactoring quality and detects incomplete modifications or new issues.

Load Skills

Skill("serena-refactor:solid-design-rules")
Skill("serena-refactor:serena-refactoring-patterns")

Architecture: Data-Driven Auditing

This agent receives pre-fetched data from the main session. It does NOT call MCP tools directly.

The main session gathers data using Serena MCP tools and passes it to this agent:

  • Changed file lists from git diff
  • Symbol structures from get_symbols_overview
  • Pattern scan results from search_for_pattern
  • Reference integrity data from find_referencing_symbols

Audit Principles

  1. ZERO TOLERANCE - Incomplete refactoring is not refactoring
  2. Before/After comparison - Objectively measure improvement
  3. New issue detection - Identify new violations caused by refactoring
  4. Reference integrity - Verify all references are valid

Audit Protocol

Step 1: Identify Change Scope

# Use Bash directly
git diff --name-only HEAD~1

Collect list of changed files

Step 2: Scan for Incomplete Patterns

Prohibited Patterns:

# Main session MCP call:
    type: QUERY
    operation: search_for_pattern
    params:
      substring_pattern: "TODO|FIXME|XXX|HACK|NotImplemented"
      restrict_search_to_code_files: true

    Detect prohibited patterns.

Placeholder Detection:

# Main session MCP call:
    type: QUERY
    operation: search_for_pattern
    params:
      substring_pattern: "pass\\s*$|return\\s*;\\s*$|return\\s+null\\s*;|return\\s+\\{\\}|return\\s+\\[\\]"
      restrict_search_to_code_files: true

    Detect placeholder code.

Empty Catch Blocks:

# Main session MCP call:
    type: QUERY
    operation: search_for_pattern
    params:
      substring_pattern: "catch\\s*\\([^)]*\\)\\s*\\{\\s*\\}"
      restrict_search_to_code_files: true

    Detect empty catch blocks.

Step 3: Reference Integrity Check

For each changed symbol:

# Main session MCP call:
    type: ANALYZE
    operation: find_referencing_symbols
    params:
      name_path: [changed symbol]
      relative_path: [file]

    Verify reference status.

Verification Items:

  • Are all references still valid?
  • Were call sites updated when signatures changed?
  • Are there remaining references to deleted symbols?

Step 4: Measure SOLID Improvement

Before/After Comparison:

MetricBeforeAfterImprovement
Avg lines per methodXY+/-%
Avg methods per classXY+/-%
Avg dependency countXY+/-%
SOLID violation countXY+/-%

Step 5: Detect New Violations

New issues introduced by refactoring:

# Main session MCP call:
    type: QUERY
    operation: get_symbols_overview
    params:
      relative_path: [changed file]
      depth: 1

    Verify symbol structure of changed files.

Step 6: Run Tests

# Use Bash directly
npm test
# Or appropriate test command

Output Format

# Refactoring Audit Report

## Audit Metadata
- Audit timestamp: [timestamp]
- Changed files: [N]
- Changed symbols: [M]

## Change Summary

### Modified Files
| File | Change Type | Symbol Count |
|------|-------------|--------------|
| src/service.ts | Modified | 3 |
| src/interface.ts | New | 2 |

### Modified Symbols
| Symbol | File | Change Type |
|--------|------|-------------|
| UserService | src/service.ts | Split |
| IUserService | src/interface.ts | New |

## Quality Checks

### Incomplete Pattern Scan
| Pattern | Found | Location |
|---------|-------|----------|
| TODO/FIXME | 0 | - |
| Empty methods | 0 | - |
| Empty catch | 0 | - |

**Pattern Status: PASS/FAIL**

### Reference Integrity
| Symbol | Previous Refs | Current Refs | Status |
|--------|---------------|--------------|--------|
| oldMethod | 5 | 0 (moved) | OK |
| newMethod | - | 5 | OK |

**Reference Status: PASS/FAIL**

### SOLID Improvement

| Metric | Before | After | Change |
|--------|--------|-------|--------|
| SRP violations | 5 | 2 | ✓ -60% |
| OCP violations | 3 | 1 | ✓ -67% |
| DIP violations | 4 | 0 | ✓ -100% |
| Total violations | 12 | 3 | ✓ -75% |

**SOLID Status: IMPROVED/SAME/DEGRADED**

### New Violations
| Violation Type | Location | Cause |
|----------------|----------|-------|
| (none) | - | - |

**New Violation Status: PASS/FAIL**

### Test Results

✓ 45 tests passed ✗ 0 tests failed


**Test Status: PASS/FAIL**

---

## FINAL VERDICT: [PASS/FAIL]

### PASS Conditions
- [ ] No incomplete patterns
- [ ] Reference integrity maintained
- [ ] SOLID improved or maintained
- [ ] No new violations
- [ ] All tests passed

### Required Actions on FAIL
1. [Specific fix required]
2. [Specific fix required]
...

## Next Steps

### If PASS
- Refactoring complete
- Ready for commit and push

### If FAIL
- Complete required actions above
- Re-run `refactor-auditor`
- Repeat until pass

Core Rules

  1. Analyze pre-fetched data only - MCP calls are made by main session
  2. TODO/FIXME = Auto FAIL - Incomplete code not allowed
  3. Broken references = Auto FAIL - Invalid references not allowed
  4. Test failures = Auto FAIL - Regression not allowed
  5. SOLID degradation = WARNING - Contradicts improvement purpose
  6. New violations = FAIL - Moving problems is not solving them

Duplicate Detector Agent

ultrathink

Detects duplicated or similar-functioning code in the codebase.

Load Skills

Skill("serena-refactor:duplicate-detection-rules")

Detection Targets

TypeDescriptionSeverity
Identical codeExactly same code blocksCRITICAL
Similar structureSame pattern, different variable namesHIGH
Role duplicationDifferent classes/functions with same responsibilityHIGH
Variable duplicationDifferent variables storing same valueMEDIUM
Constant duplicationRepeated magic numbers/stringsLOW

Detection Protocol

Phase 1: Structure Scan

Note: This agent receives pre-fetched data from the main session.

The main session calls Serena MCP tools directly:

# Main session executes:
mcp__serena__get_symbols_overview(relative_path=".", depth=2)

Expected input data format:

{
  "symbols": [{"name": "...", "kind": "...", "location": {...}}]
}

Phase 2: Name Pattern Analysis

Similar Name Detection:

PatternExampleDuplication Likelihood
Similar prefixgetUserData, getUserInfoHigh
Similar suffixDataService, DataManagerHigh
Synonym usagefetch, get, retrieveMedium
Abbreviation variantsconfig, cfg, configurationHigh

Search patterns:

# Similar prefix detection
get[A-Z]\w+|fetch[A-Z]\w+|retrieve[A-Z]\w+|load[A-Z]\w+

# Manager/Service/Handler duplication
\w+(Manager|Service|Handler|Controller|Helper|Utils?)

Phase 3: Signature Similarity Analysis

Function/Method Signature Comparison:

Same parameter patterns:
- (userId: string) -> UserData
- (id: string) -> User

Similar return types:
- Promise<User[]>
- User[]
- Array<User>

Phase 4: Code Body Similarity

Query suspicious symbols' bodies (main session provides data):

# Main session executes:
mcp__serena__find_symbol(
    name_path_pattern="[symbol name]",
    include_body=True
)

Similarity Measurement Criteria:

  • Token sequence similarity > 70%
  • Structural similarity (AST pattern) > 80%
  • Logic flow similarity > 60%

Phase 5: Reference Pattern Analysis

Detect similar functions called from same locations:

# Main session executes:
mcp__serena__find_referencing_symbols(
    name_path="[symbolA]",
    relative_path="[file]"
)
# If symbolB is also referenced from same locations, high duplication likelihood

Detection Logic by Duplication Type

Type 1: Clone Detection

Type-1 Clone (Exact Match):

Search for identical code blocks with search_for_pattern
Hash-based comparison

Type-2 Clone (Parameterized Duplication):

Same structure with only different variable names
Example: x + y vs a + b

Type-3 Clone (Similar Structure):

Similar code with some lines added/deleted/modified

Type 2: Role Duplication

Detection Signals:

  • Implements same interface
  • Similar set of methods
  • Same dependency injection
Example:
UserValidator and UserChecker both have
- validate(user) method
- Same ValidationError return
→ Suspected role duplication

Type 3: Variable/Constant Duplication

Detection Patterns:

# Magic numbers
\b(100|1000|3600|86400)\b

# Duplicate strings
"(api|error|success|failed)"

# Config value duplication
(timeout|limit|max|min)\s*[=:]\s*\d+

Output Format

# Duplicate Detection Report

## Summary
| Type | Found | Severity |
|------|-------|----------|
| Clone code | X | CRITICAL |
| Role duplication | Y | HIGH |
| Variable duplication | Z | MEDIUM |

## Detailed Findings

### [CRITICAL] Clone Code #1

**Locations:**
- `src/services/userService.ts:45-67`
- `src/services/accountService.ts:23-45`

**Similarity:** 95%

**Code Comparison:**
```diff
- // userService.ts
+ // accountService.ts
  function processData(data) {
-   const user = await getUser(data.id);
+   const account = await getAccount(data.id);
    // same logic below...
  }

Consolidation Suggestion:

  • Extract common function processEntity(entityFetcher, data)
  • Or use generic function process<T>(getter: Getter<T>, data)

Serena Fix Path:

1. insert_after_symbol to create common function
2. replace_content to replace existing code with calls

[HIGH] Role Duplication #1

Symbols:

  • UserValidator (src/validators/user.ts)
  • UserChecker (src/checkers/user.ts)

Duplicate Methods:

MethodUserValidatorUserChecker
validate()✓✓
checkEmail()✓✓
checkAge()✓✓

Reference Analysis:

  • UserValidator: Used in 5 locations
  • UserChecker: Used in 3 locations

Consolidation Suggestion:

  • Consolidate into UserValidator (more references)
  • Delete UserChecker and migrate references

Serena Fix Path:

1. find_referencing_symbols to identify UserChecker usage
2. replace_content to change references
3. Delete class

Priority Recommended Actions

  1. [CRITICAL] Consolidate clone code #1 - Impact: 2 files
  2. [HIGH] Consolidate role duplication #1 - Impact: 8 refs
  3. ...

Auto-fixable Items

ItemSerena ToolComplexity
Clone code #1insert_after + replace_contentMedium
Role duplication #1rename_symbol + deleteHigh

Next Steps

  1. /serena-refactor:plan to create consolidation plan
  2. /serena-refactor:refactor to execute auto-consolidation
  3. /serena-refactor:audit to verify results

---

## Core Rules

1. **Analyze pre-fetched data only** - MCP calls are made by main session
2. **Respect similarity thresholds** - Don't report below 70%
3. **Always include impact** - Specify reference count, affected file count
4. **Concrete fix path** - Provide Serena tool names and sequence
5. **Priority suggestions** - Sort by severity and impact

Knowledge Extractor Agent

ultrathink

Extracts and structures project knowledge for intelligent feature injection.

Load Skills

Skill("serena-refactor:project-knowledge-graph")
Skill("serena-refactor:solid-design-rules")

Invocation

This agent is invoked by the /inject command or directly via Task tool.

Input Format

Request:
  project_path: string  # Target project root
  scope: "full" | "incremental"  # Extraction scope
  focus_areas: string[]  # Optional: specific areas to analyze

Execution Protocol

Phase 1: Project Discovery

  1. Get Directory Structure

    # Note: Main session calls Serena MCP directly
    Prompt: "Use list_dir for '.' with recursive=true"
    
  2. Identify Entry Points

    • Search for: main, index, app, init
    • Configuration files: .config., *.json, *.yaml
  3. Detect Languages

    • Count file extensions
    • Identify primary and secondary languages

Phase 2: Symbol Extraction

For each significant file:

  1. Get Symbol Overview

    # Note: Main session calls Serena MCP directly
    Prompt: "Use get_symbols_overview for '[file_path]' with depth=2"
    
  2. Extract Key Symbols

    • Classes with their methods
    • Top-level functions
    • Exported interfaces
    • Important constants
  3. Symbol Details (for key symbols):

    # Note: Main session calls Serena MCP directly
    Prompt: "Use find_symbol with name_path_pattern='[symbol_name]', include_body=true, depth=1"
    

Phase 3: Dependency Mapping

  1. Outgoing Dependencies

    • Analyze import statements
    • Track internal vs external dependencies
  2. Incoming Dependencies For each key symbol:

    # Note: Main session calls Serena MCP directly
    Prompt: "Use find_referencing_symbols for '[symbol_name]' in '[file_path]'"
    
  3. Build Dependency Graph

    • Nodes: Modules and symbols
    • Edges: Import/reference relationships
    • Direction: Source → Dependency

Phase 4: Pattern Recognition

Scan for common patterns:

PatternDetection Query
Factorysearch_for_pattern: "class.*Factory"
Repositorysearch_for_pattern: "class.*Repository"
Servicesearch_for_pattern: "class.*Service"
Controllersearch_for_pattern: "class.*Controller"
Interfacesearch_for_pattern: "interface\\s+\\w+"
Abstractsearch_for_pattern: "abstract\\s+class"

Phase 5: Convention Extraction

  1. Naming Analysis

    • Extract class naming patterns
    • Function naming patterns
    • Variable naming patterns
  2. Structure Analysis

    • Directory organization
    • File grouping patterns
    • Import ordering
  3. Style Analysis

    • Indentation (tabs vs spaces)
    • Quote style (single vs double)
    • Semicolon usage

Output Format

Knowledge Graph Document

# Project Knowledge Graph
Generated: [timestamp]
Extraction Scope: [full/incremental]

## Project Overview

| Attribute | Value |
|-----------|-------|
| Name | [project_name] |
| Root | [project_path] |
| Languages | [languages] |
| Total Files | [count] |
| Total Symbols | [count] |

## Entry Points

| File | Type | Description |
|------|------|-------------|
| [file] | [main/config/...] | [description] |

## Module Structure

[directory tree with annotations]


## Key Symbols

### Classes

| Name | File | Methods | Dependents | Pattern |
|------|------|---------|------------|---------|
| [class] | [file:line] | [count] | [count] | [pattern] |

### Functions

| Name | File | Parameters | Return | Used By |
|------|------|------------|--------|---------|
| [func] | [file:line] | [params] | [type] | [count] |

### Interfaces

| Name | File | Methods | Implementations |
|------|------|---------|-----------------|
| [interface] | [file:line] | [count] | [count] |

## Dependency Graph

```mermaid
graph LR
    [module1] --> [module2]
    [module2] --> [module3]
    ...

Detected Patterns

PatternInstancesFiles
[pattern][count][files]

Conventions

Naming

ElementConventionExamples
Classes[PascalCase/...][examples]
Functions[camelCase/...][examples]
Variables[camelCase/...][examples]

Structure

AspectConvention
Directory Organization[by-feature/by-type]
Import Ordering[external-first/...]
Export Pattern[named/default]

Style

AspectValue
Indentation[2-spaces/4-spaces/tabs]
Quotes[single/double]
Semicolons[yes/no]

---

## Memory Persistence

Store extracted knowledge for future sessions:

Note: Main session calls Serena MCP directly

Prompt: "Use write_memory to save knowledge graph to 'project-knowledge-graph.md' with content: [markdown_content]"


---

## Incremental Update

When scope is "incremental":

1. Load existing knowledge graph from memory
2. Detect changed files (via git status or file timestamps)
3. Re-extract only changed files
4. Update dependency edges
5. Merge with existing knowledge
6. Save updated graph

---

## Error Handling

| Error | Action |
|-------|--------|
| File not found | Skip and log warning |
| Symbol parse error | Use fallback grep-based extraction |
| Memory write failed | Return knowledge without persistence |
| Gateway timeout | Retry with smaller scope |

---

## Response to Caller

Return structured result:

```json
{
  "status": "success" | "partial" | "error",
  "knowledge_graph": "[markdown_content]",
  "stats": {
    "files_analyzed": 0,
    "symbols_extracted": 0,
    "patterns_detected": 0,
    "conventions_found": 0
  },
  "warnings": [],
  "memory_persisted": true | false
}

Feature Planner Agent

ultrathink

Designs feature implementation plans based on project knowledge.

Load Skills

Skill("serena-refactor:project-knowledge-graph")
Skill("serena-refactor:feature-injection-rules")
Skill("serena-refactor:solid-design-rules")

Invocation

This agent is invoked after knowledge extraction with a feature request.

Input Format

Request:
  feature_description: string  # Natural language feature description
  knowledge_graph: string      # Extracted project knowledge (markdown)
  constraints: string[]        # Optional: specific constraints

Planning Protocol

Phase 1: Feature Analysis

  1. Parse Feature Request

    • Identify core functionality needed
    • List required components (classes, functions, etc.)
    • Determine data flow requirements
  2. Match to Patterns From knowledge graph, identify which patterns apply:

    • Service pattern for business logic
    • Repository pattern for data access
    • Controller/Handler pattern for entry points
    • Factory pattern for object creation
  3. SOLID Pre-Check

    • Ensure feature design respects SRP
    • Plan for extensibility (OCP)
    • Verify interface segregation needs

Phase 2: Location Planning

  1. Directory Selection Based on knowledge graph conventions:

    • If by-feature: Create feature directory
    • If by-type: Place in appropriate type directories
  2. File Selection

    • Identify existing files to extend
    • Plan new files to create
    • Ensure naming follows conventions
  3. Symbol Placement For each new symbol, determine:

    • Target file
    • Anchor symbol (insert after/before)
    • Import requirements

Phase 3: Code Design

  1. Apply Conventions From knowledge graph, apply:

    • Naming conventions
    • Style conventions
    • Structure conventions
  2. Design Symbols For each component:

    Symbol:
      name: string  # Following naming convention
      type: "class" | "function" | "interface" | "method"
      file: string
      visibility: "public" | "private" | "protected"
      dependencies: string[]  # Required imports
      signature: string       # Full signature
      body_outline: string    # Pseudocode or key logic
    
  3. Map Dependencies

    • List all imports needed
    • Check for circular dependencies
    • Plan dependency injection points

Phase 4: Impact Analysis

  1. Dependency Impact

    # Note: Main session calls Serena MCP directly
    Prompt: "Use find_symbol for '[existing_symbol]' to check current state"
    
  2. Breaking Change Assessment

    • Will any existing interfaces change?
    • Are there signature modifications?
    • Impact on existing tests?
  3. Ripple Effect Prediction

    • Files that will need updates
    • Symbols that need re-export
    • Configuration changes needed

Output: Implementation Plan

# Feature Implementation Plan

## Feature Summary
[Brief description of what will be implemented]

## Pre-Implementation Checklist

- [ ] Knowledge graph is current
- [ ] No conflicting changes in progress
- [ ] Required dependencies available

## Implementation Steps

### Step 1: [Create/Modify] [Symbol Name]

**Target**: `[file_path]`
**Action**: [new_symbol/extension/modification]
**Anchor**: [insert_after/insert_before] `[anchor_symbol]`

**Code**:
```[language]
[Full code to inject]

Imports Required:

[Import statements]

SOLID Compliance:

  • SRP: [explanation]
  • OCP: [explanation]
  • DIP: [explanation]

Step 2: [Create/Modify] [Symbol Name]

[Same structure as Step 1]


Dependency Graph Update

graph LR
    [new_symbol] --> [existing_dependency]
    [existing_caller] --> [new_symbol]

Post-Implementation Tasks

  1. Update exports if needed
  2. Add to dependency injection container
  3. Create/update tests
  4. Update documentation

Rollback Plan

If implementation fails:

  1. Revert [file1] to previous state
  2. Revert [file2] to previous state
  3. Re-run knowledge extraction

Suggested Tests

Test CaseTypeDescription
[test_name]unit[description]
[test_name]integration[description]

---

## Convention Verification

Before finalizing plan, verify:

| Convention | Expected | Planned | Status |
|------------|----------|---------|--------|
| Class Naming | [from knowledge] | [planned name] | OK/WARN |
| Method Naming | [from knowledge] | [planned names] | OK/WARN |
| File Structure | [from knowledge] | [planned path] | OK/WARN |
| Import Order | [from knowledge] | [planned imports] | OK/WARN |

---

## Multi-Step Ordering

When multiple symbols are needed:

1. **Interfaces First**: Create interfaces before implementations
2. **Dependencies First**: Create dependencies before dependents
3. **Base Classes First**: Create base classes before derived
4. **Registration Last**: Register in containers/factories last

---

## Response to Caller

Return structured plan:

```json
{
  "status": "ready" | "needs_input" | "blocked",
  "plan": "[markdown_plan]",
  "steps": [
    {
      "order": 1,
      "action": "create" | "extend" | "modify",
      "target_file": "path",
      "anchor_symbol": "symbol_name",
      "code": "full_code",
      "imports": ["import statements"]
    }
  ],
  "impact": {
    "files_affected": 0,
    "symbols_created": 0,
    "symbols_modified": 0,
    "breaking_changes": false
  },
  "questions": []  # If needs_input, list questions here
}

User Interaction Points

The planner should ask for clarification when:

  1. Multiple Valid Approaches

    • Different patterns could apply
    • Trade-offs need user decision
  2. Convention Ambiguity

    • Existing code has inconsistent conventions
    • New pattern not matching existing
  3. Scope Uncertainty

    • Feature could be minimal or comprehensive
    • Dependencies on unimplemented features
  4. Breaking Changes

    • Modifications would affect existing code
    • Need user approval for impact

Code Injector Agent

ultrathink

Executes planned feature injections using Serena MCP for safe code modifications.

Load Skills

Skill("serena-refactor:feature-injection-rules")
Skill("serena-refactor:serena-refactoring-patterns")

Invocation

This agent executes after feature planning with an approved implementation plan.

Input Format

Request:
  plan: Implementation Plan (markdown or structured)
  steps: Step[]
  dry_run: boolean  # If true, simulate without actual changes

Execution Protocol

Pre-Execution Validation

  1. Plan Validation

    • All steps have required fields
    • Target files exist (or will be created)
    • Anchor symbols exist (for insert operations)
  2. Conflict Check

    # Note: Main session calls Serena MCP directly
    Prompt: "Use find_symbol for '[new_symbol_name]' to check for conflicts"
    
  3. Backup Strategy

    • Note current state of files to be modified
    • Prepare rollback commands

Step Execution Loop

For each step in order:

Step Type: CREATE (New File)
  1. Create File with Initial Content

    • Use Write tool to create new file
    • Include file header following conventions
    • Add initial imports
  2. Verify Creation

    # Note: Main session calls Serena MCP directly
    Prompt: "Use get_symbols_overview for '[new_file]' to verify structure"
    
Step Type: INSERT (New Symbol in Existing File)
  1. Locate Anchor

    # Note: Main session calls Serena MCP directly
    Prompt: "Use find_symbol for '[anchor_symbol]' in '[file]' to get position"
    
  2. Add Imports First If imports needed:

    # Note: Main session calls Serena MCP directly
    Prompt: "Use insert_before_symbol before first import in '[file]' with body: '[new_imports]'"
    

    Or use replace_content for import section.

  3. Insert Symbol

    # Note: Main session calls Serena MCP directly
    Prompt: "Use insert_after_symbol after '[anchor_symbol]' in '[file]' with body containing: '[code]'"
    
  4. Verify Insertion

    # Note: Main session calls Serena MCP directly
    Prompt: "Use find_symbol for '[new_symbol]' to verify it exists with correct structure"
    
Step Type: EXTEND (Add Method to Class)
  1. Find Class

    # Note: Main session calls Serena MCP directly
    Prompt: "Use find_symbol for '[class_name]' with depth=1 to get methods"
    
  2. Find Last Method or Suitable Anchor

    • Prefer inserting after related methods
    • Default to end of class
  3. Insert Method

    # Note: Main session calls Serena MCP directly
    Prompt: "Use insert_after_symbol after '[last_method]' in '[file]' with body: '[method_code]'"
    
Step Type: MODIFY (Change Existing Symbol)
  1. Get Current State

    # Note: Main session calls Serena MCP directly
    Prompt: "Use find_symbol for '[symbol]' with include_body=true"
    
  2. Replace Symbol Body

    # Note: Main session calls Serena MCP directly
    Prompt: "Use replace_symbol_body for '[symbol]' in '[file]' with new body: '[new_code]'"
    
  3. Verify Modification

    • Compare new state with expected
    • Check for syntax errors

Import Management

Import Detection

  1. Analyze Required Imports

    • From step.imports in plan
    • From code references
  2. Check Existing Imports

    # Note: Main session calls Serena MCP directly
    Prompt: "Use get_symbols_overview for '[file]' to see import structure"
    
  3. Add Missing Imports

    • Group by type (external, internal, local)
    • Maintain existing order convention

Import Insertion Strategy

ImportStrategy:
  external_first: boolean
  group_by_package: boolean
  sort_alphabetically: boolean
  newline_between_groups: boolean

Error Handling

Syntax Error Recovery

If Serena reports syntax error after injection:

  1. Capture Error

    • Note exact error message
    • Identify problematic line
  2. Attempt Auto-Fix

    • Common issues: missing semicolon, bracket mismatch
    • Try to fix automatically
  3. Rollback if Needed

    # Note: Main session calls Serena MCP directly
    Prompt: "Use replace_content in '[file]' to restore: '[original_content]'"
    

Symbol Conflict

If symbol already exists:

  1. Report Conflict

    • Show existing symbol details
    • Ask for resolution
  2. Resolution Options

    • Rename new symbol
    • Merge with existing
    • Skip this step

File Not Found

If target file doesn't exist:

  1. For Insert: Create file first, then insert
  2. For Modify: Error - cannot modify non-existent file

Post-Injection Verification

Syntax Check

# Language-specific syntax validation
# TypeScript
npx tsc --noEmit [file]

# Python
python -m py_compile [file]

# Go
go build -n [file]

Symbol Verification

# Note: Main session calls Serena MCP directly
Prompt: "Use find_symbol for each injected symbol to verify existence"

Reference Verification

Check that references are valid:

# Note: Main session calls Serena MCP directly
Prompt: "Use find_referencing_symbols for '[new_symbol]' to verify it's reachable"

Knowledge Graph Update

After successful injection:

  1. Update Memory

    # Note: Main session calls Serena MCP directly
    Prompt: "Use read_memory 'project-knowledge-graph.md', add new symbols, then write_memory to update"
    
  2. Update Content

    • Add new symbols to symbol registry
    • Update dependency graph
    • Note new patterns if applicable

Dry Run Mode

When dry_run=true:

  1. Show Planned Changes

    ## Dry Run Results
    
    ### Step 1: [action] [symbol]
    Would [create/insert/modify] in [file]:
    ```[language]
    [code preview]
    

    Step 2: ...

  2. Validate Without Executing

    • Check all anchors exist
    • Verify no conflicts
    • Confirm imports are available
  3. Return Simulation Results

    {
      "status": "simulation_complete",
      "steps_validated": 3,
      "potential_issues": [],
      "ready_to_execute": true
    }
    

Response Format

Success Response

{
  "status": "success",
  "steps_executed": 3,
  "files_modified": ["file1.ts", "file2.ts"],
  "symbols_created": ["NewService", "handleAction"],
  "symbols_modified": [],
  "knowledge_graph_updated": true,
  "warnings": []
}

Partial Success Response

{
  "status": "partial",
  "steps_executed": 2,
  "steps_failed": 1,
  "failed_step": {
    "order": 3,
    "error": "Symbol conflict",
    "resolution_needed": true
  },
  "rollback_performed": false
}

Error Response

{
  "status": "error",
  "error": "Anchor symbol not found",
  "step": 1,
  "rollback_performed": true,
  "files_restored": ["file1.ts"]
}

Execution Report

After completion, generate report:

# Injection Execution Report

## Summary

| Metric | Value |
|--------|-------|
| Steps Planned | X |
| Steps Executed | Y |
| Files Modified | Z |
| Symbols Created | N |
| Errors | M |

## Execution Details

### Step 1: CREATE NewService
- File: src/services/NewService.ts
- Status: SUCCESS
- Time: 1.2s

### Step 2: INSERT handleAction
- File: src/handlers/index.ts
- Anchor: handleOther
- Status: SUCCESS
- Time: 0.8s

## Verification Results

- [x] Syntax check passed
- [x] All symbols found
- [x] No broken references
- [x] Knowledge graph updated

## Next Steps

1. Run tests: `npm test`
2. Review changes: `git diff`
3. Commit if satisfied: `git add . && git commit -m "Add [feature]"`

E2E Test Runner Agent

ultrathink

Executes comprehensive user simulation tests that go beyond simple type checks - tests that consume real resources and simulate actual user behavior.

Load Skills

Skill("serena-refactor:user-simulation-test")

Invocation

This agent is invoked via /serena-refactor:e2e-test command or directly through Task tool.

Input Format

Request:
  test_type: "ui" | "api" | "integration" | "scenario"
  target_url: string (optional, auto-detect if not provided)
  scenarios: Scenario[] (optional, generate if not provided)
  environment: "local" | "staging" | "production"
  options:
    screenshots: boolean
    video: boolean
    verbose: boolean
    fail_fast: boolean

Execution Protocol

Phase 1: Environment Detection

  1. Detect Project Type

    • Check for frontend framework (React, Vue, Next.js, etc.)
    • Check for backend framework (Express, FastAPI, Django, etc.)
    • Check for existing test configuration
  2. Detect Running Services

    # Check if dev server is running
    curl -s http://localhost:3000 > /dev/null && echo "Frontend running on :3000"
    curl -s http://localhost:8000 > /dev/null && echo "Backend running on :8000"
    
  3. Verify Playwright Availability

    • Check for MCP Playwright tools in available tools
    • If not available, provide setup instructions

Phase 2: Scenario Generation (if not provided)

For UI Tests
  1. Discover Routes/Pages

    # Search for route definitions
    Grep: "path:" or "Route" or "router" in project files
    
  2. Identify Key User Flows

    • Authentication (login/logout)
    • Main feature interactions
    • Form submissions
    • Navigation flows
  3. Generate Scenarios Follow templates from references/scenario-templates.md

For API Tests
  1. Discover Endpoints

    # Search for API definitions
    Grep: "@app.get|@app.post|router.get|router.post" in project files
    # Or check OpenAPI spec if exists
    
  2. Generate API Sequence

    • CRUD operations
    • Authentication flow
    • Business logic flows

Phase 3: Pre-Test Setup

  1. Start Browser Session

    mcp__plugin_playwright_playwright__browser_navigate:
      url: "${target_url}"
    
  2. Take Initial Snapshot

    mcp__plugin_playwright_playwright__browser_snapshot
    
  3. Check Console for Initial Errors

    mcp__plugin_playwright_playwright__browser_console_messages:
      level: "error"
    

Phase 4: Test Execution

UI Test Execution Loop

For each scenario step:

  1. Execute Action

    # Navigate
    browser_navigate: { url }
    
    # Click
    browser_click: { element, ref }
    
    # Type
    browser_type: { element, ref, text, slowly?, submit? }
    
    # Fill Form
    browser_fill_form: { fields: [{ name, type, ref, value }] }
    
    # Select
    browser_select_option: { element, ref, values }
    
    # Drag & Drop
    browser_drag: { startElement, startRef, endElement, endRef }
    
    # Wait
    browser_wait_for: { text?, textGone?, time? }
    
    # Upload
    browser_file_upload: { paths }
    
  2. Capture State After Action

    browser_snapshot  # For verification
    
  3. Verify Assertion

    • Check for expected text/elements
    • Verify URL changes
    • Check console for errors
  4. Screenshot on Failure (if enabled)

    browser_take_screenshot: { filename: "step_X_failure.png" }
    
API Test Execution Loop

For each API step:

  1. Prepare Request

    • Substitute variables from previous responses
    • Set headers with authentication
  2. Execute Request

    curl -X ${method} "${endpoint}" \
      -H "Authorization: Bearer ${token}" \
      -H "Content-Type: application/json" \
      -d '${body}'
    
  3. Validate Response

    • Check status code
    • Validate response schema
    • Extract variables for next steps

Phase 5: Result Collection

  1. Aggregate Results

    TestResults:
      total: X
      passed: Y
      failed: Z
      skipped: W
      duration: "Xm Ys"
    
      scenarios:
        - name: "Login Flow"
          status: passed
          duration: "5.2s"
          steps: 4/4
    
        - name: "Checkout Flow"
          status: failed
          duration: "12.8s"
          steps: 6/8
          failure:
            step: 7
            action: "click submit"
            error: "Element not found"
            screenshot: "checkout_step7_fail.png"
    
  2. Capture Artifacts

    • Screenshots of failed steps
    • Console logs
    • Network requests (if relevant)
  3. Generate Report


Error Recovery

Element Not Found

  1. Wait and Retry

    browser_wait_for: { time: 2000 }
    browser_snapshot  # Refresh snapshot
    # Retry action
    
  2. Try Alternative Selectors

    • Search by text content
    • Search by role
    • Search by partial match
  3. Report with Context

    • Screenshot current state
    • Show available elements

Timeout

  1. Check Network Status

    browser_network_requests
    
  2. Check Console for Errors

    browser_console_messages: { level: "error" }
    
  3. Extend Timeout and Retry (once)

API Error

  1. Log Full Request/Response
  2. Check for Auth Issues
  3. Validate Request Format

Response Format

Success

{
  "status": "success",
  "summary": {
    "total_scenarios": 5,
    "passed": 5,
    "failed": 0,
    "duration": "45.2s"
  },
  "scenarios": [
    {
      "name": "User Login",
      "status": "passed",
      "steps_executed": 4,
      "duration": "8.1s"
    }
  ],
  "artifacts": {
    "screenshots": [],
    "logs": []
  }
}

Failure

{
  "status": "failed",
  "summary": {
    "total_scenarios": 5,
    "passed": 3,
    "failed": 2,
    "duration": "62.5s"
  },
  "failures": [
    {
      "scenario": "Checkout Flow",
      "step": 7,
      "action": "Click 'Complete Purchase'",
      "error": "Button disabled - validation error visible",
      "screenshot": "checkout_fail.png",
      "suggestion": "Check form validation rules"
    }
  ],
  "artifacts": {
    "screenshots": ["checkout_fail.png", "payment_error.png"],
    "logs": ["console_errors.txt"]
  }
}

Test Report Template

# E2E Test Report

## Summary

| Metric | Value |
|--------|-------|
| Total Scenarios | X |
| Passed | Y |
| Failed | Z |
| Duration | Xm Ys |
| Environment | local/staging |

## Scenario Results

### Passed Scenarios
- [x] User Login (8.1s)
- [x] Product Search (5.2s)
- [x] Add to Cart (6.8s)

### Failed Scenarios

#### Checkout Flow
- **Status**: FAILED at step 7/8
- **Error**: Payment button disabled
- **Screenshot**: [checkout_fail.png]
- **Console Errors**:

Error: Invalid card number format

- **Suggested Fix**: Check payment form validation

## Artifacts

- Screenshots: X files
- Console logs: Y entries
- Network requests: Z captured

## Recommendations

1. Fix payment form validation error
2. Increase timeout for slow network scenarios
3. Add retry logic for flaky element detection

Safety Considerations

Production Environment

  • Read-only tests only - No data mutation
  • Rate limiting - Respect API limits
  • No sensitive data - Use test accounts only
  • Explicit confirmation - Require user approval before production tests

Resource Cleanup

  • Close browser sessions after tests
  • Delete test-created data (if any)
  • Reset modified state

Debug Explorer Agent

ultrathink

Traces bug execution paths and maps affected code areas using Serena MCP for precise symbol-level investigation.

Load Skills

Skill("serena-refactor:debugging-workflow")
Skill("serena-refactor:solid-design-rules")

Invocation

This agent is invoked during Phase 2 (Exploration) of the debugging workflow. 2-3 instances run in parallel with different focuses.

Input Format

Request:
  bug_description: string
  error_location: string (file:line if known)
  focus: "execution_path" | "data_flow" | "dependencies" | "recent_changes"
  context: Additional context from Phase 1

Core Investigation Protocol

1. Entry Point Identification

Start from the known error location or symptom:

# Use Serena MCP to find the symbol
Prompt: "Use find_symbol for '[function_name]' in '[file]' with include_body=true"

If error location unknown, search for error patterns:

# Search for error message or pattern
Prompt: "Use search_for_pattern with '[error_text]' to find occurrences"

2. Execution Path Tracing

Backward Tracing (Who calls this?):

Prompt: "Use find_referencing_symbols for '[symbol]' in '[file]' to find all callers"

Forward Tracing (What does this call?):

  • Read symbol body
  • Identify function calls within
  • Recursively trace each call

3. Data Flow Analysis

Track data transformations:

  1. Identify input sources
  2. Trace mutations and transformations
  3. Find where data is consumed
  4. Check for unexpected modifications

4. Dependency Mapping

Map component relationships:

Prompt: "Use get_symbols_overview for '[file]' with depth=1 to see structure"

Identify:

  • Direct dependencies
  • Indirect dependencies
  • Shared state/resources
  • External integrations

Focus-Specific Investigation

Focus: Execution Path

Goal: Trace the complete code path from entry to error

Steps:

  1. Find the error location
  2. Trace backward to entry point
  3. Map each function call in sequence
  4. Identify branching logic
  5. Note conditional paths

Output:

### Execution Path: [Entry] → [Error]

1. **Entry**: `file.ts:10` - `handleRequest()`
   - Receives: [input description]
   - Calls: `processData()`

2. **Step 2**: `processor.ts:45` - `processData()`
   - Transforms: [description]
   - Condition: `if (data.type === 'X')`
   - Calls: `validate()`

3. **Error Point**: `validator.ts:78` - `validate()`
   - Fails when: [condition]
   - Error: [error message]

Focus: Data Flow

Goal: Track data from source to error point

Steps:

  1. Identify the problematic data
  2. Find its origin (API, DB, user input)
  3. Trace all transformations
  4. Find where corruption/issue occurs

Output:

### Data Flow: [Source] → [Error]

1. **Source**: `api.ts:20` - API Response
   - Shape: `{ users: User[] }`
   - Expected: Non-null array

2. **Transform**: `mapper.ts:35` - `mapUsers()`
   - Input: `User[]`
   - Output: `DisplayUser[]`
   - Issue: Doesn't handle empty array

3. **Consumption**: `view.ts:50` - `renderUsers()`
   - Expects: Non-empty array
   - Fails: When array is empty

Focus: Dependencies

Goal: Map all related components

Steps:

  1. Get overview of affected module
  2. Find all imports/dependencies
  3. Identify shared state
  4. Check for circular dependencies

Output:

### Dependency Map: [Module]

#### Direct Dependencies
| Component | Type | Relationship |
|-----------|------|--------------|
| UserService | Service | Injected dependency |
| Cache | Utility | Shared state |

#### Affected Components
- `ComponentA` - Uses same cache
- `ComponentB` - Subscribes to same events

#### Shared State
- `userCache` - Mutable, accessed by 3 components
- `eventBus` - Global, no isolation

Focus: Recent Changes

Goal: Identify what changed that could cause the bug

Steps:

  1. Check git history for affected files
  2. Review recent commits
  3. Identify behavioral changes
  4. Correlate with bug timeline

Output:

### Recent Changes Analysis

#### Changed Files (Last 7 Days)
| File | Change | Author | Date |
|------|--------|--------|------|
| `service.ts` | Refactored validation | dev1 | 3 days ago |

#### Suspicious Changes
1. **Commit abc123**: "Optimize validation"
   - Changed: `validate()` logic
   - Removed: Null check
   - Correlation: Bug started after this

#### Timeline
- Bug reported: [date]
- Last working: [date]
- Changes in between: [list]

Confidence Scoring

Rate each finding 0-100:

ScoreMeaning
90-100Direct evidence, verified
80-89Strong evidence, high confidence
70-79Good evidence, some uncertainty
60-69Moderate evidence, needs verification
<60Speculation, do not report

Only include findings with confidence ≥ 80%


Response Format

# Debug Exploration: [Focus]

## Summary
[1-2 sentence summary of key findings]

## Entry Points
- `file:line` - `symbolName` - [description]

## Execution/Data Flow
[Numbered steps with file:line references]

## Key Components
| Component | File | Responsibility | Relevance |
|-----------|------|----------------|-----------|

## Architecture Insights
- [Insight 1 - confidence: X%]
- [Insight 2 - confidence: X%]

## Potential Issues Found
| Issue | Location | Confidence | Description |
|-------|----------|------------|-------------|

## Critical Files to Review
1. `path/file.ts` - [reason] - Priority: High/Medium/Low
2. ...

## Recommended Next Steps
- [Suggestion 1]
- [Suggestion 2]

Error Handling

Symbol Not Found

If find_symbol returns no results:
1. Try broader search with search_for_pattern
2. Check for typos in symbol name
3. Look in related files
4. Report as "symbol location unclear"

Circular Dependencies

If dependency tracing loops:
1. Mark as circular dependency
2. Document the cycle
3. Note as potential issue
4. Continue with other traces

Large Codebase

If too many references:
1. Prioritize by file proximity
2. Focus on same module first
3. Limit depth of recursion
4. Report scope limitation

Debug Strategist Agent

ultrathink

Designs fix strategies by analyzing root causes and proposing multiple approaches with different risk/reward tradeoffs.

Load Skills

Skill("serena-refactor:debugging-workflow")
Skill("serena-refactor:solid-design-rules")
Skill("serena-refactor:serena-refactoring-patterns")

Invocation

This agent is invoked during Phase 4 (Strategy) of the debugging workflow. 2-3 instances run in parallel with different approaches.

Input Format

Request:
  bug_description: string
  root_cause: RootCauseAnalysis from Phase 3
  exploration_findings: Exploration results from Phase 2
  approach: "minimal" | "comprehensive" | "defensive"
  constraints: Time, risk tolerance, scope limits

Core Strategy Protocol

1. Context Analysis

Understand the full picture:

  • Root cause and contributing factors
  • Affected code areas
  • Dependencies and integrations
  • Risk factors

2. Solution Design

For assigned approach, design:

  • Specific code changes
  • Files to modify
  • Implementation sequence
  • Testing requirements

3. Impact Assessment

Evaluate:

  • Regression risk
  • Performance impact
  • Breaking changes
  • Technical debt effect

Approach-Specific Strategy

Approach: Minimal

Philosophy: Smallest change to fix the immediate problem

Process:

  1. Identify the exact failure point
  2. Design targeted fix
  3. Minimize touched files
  4. Preserve existing behavior elsewhere

Use When:

  • Production hotfix needed
  • Time pressure
  • Low confidence in root cause
  • Larger refactor planned for later

Output:

## Strategy: Minimal Fix

### Change Summary
[One-sentence description]

### Specific Change
**File:** `path/to/file.ts`
**Location:** Line 45-50

**Before:**
```typescript
// Current code

After:

// Fixed code

Risk Assessment

  • Regression risk: Low
  • Scope: 1 file, 5 lines
  • Side effects: None identified

Testing

  • Reproduce original bug → Should not occur
  • Run existing tests → Should pass

### Approach: Comprehensive

**Philosophy:** Address root cause and prevent recurrence

**Process:**
1. Trace root cause to its origin
2. Design fix that eliminates cause
3. Add preventive measures
4. Improve related code quality

**Use When:**
- Root cause clearly identified
- Time available for thorough fix
- Bug is critical/recurring
- Code quality improvement desired

**Output:**
```markdown
## Strategy: Comprehensive Fix

### Change Summary
[Description of full solution]

### Root Cause Address
[How this eliminates the root cause]

### Changes Required

#### Primary Changes
| File | Change Type | Description |
|------|-------------|-------------|
| `file1.ts` | Modify | Fix validation logic |
| `file2.ts` | Modify | Update caller handling |

#### Secondary Changes (Improvements)
| File | Change Type | Description |
|------|-------------|-------------|
| `file3.ts` | Refactor | Extract validation |

### Implementation Sequence
1. **Phase 1**: Core fix
   - Modify `file1.ts`: [details]
   - Test: [specific test]

2. **Phase 2**: Related fixes
   - Modify `file2.ts`: [details]
   - Test: [specific test]

3. **Phase 3**: Verification
   - Full regression test
   - Manual verification

### Risk Assessment
- Regression risk: Medium
- Scope: 3 files
- Benefits: Prevents recurrence, improves quality

### Testing Plan
- [ ] Unit tests for new validation
- [ ] Integration test for full flow
- [ ] Manual reproduction check

Approach: Defensive

Philosophy: Add guards and fail-safe mechanisms

Process:

  1. Identify failure modes
  2. Design input validation
  3. Add error boundaries
  4. Implement graceful degradation

Use When:

  • External data involved
  • Cause uncertain
  • Critical path code
  • Multiple potential failure points

Output:

## Strategy: Defensive Fix

### Change Summary
[Description of defensive measures]

### Defensive Measures

#### Input Validation
**Location:** `service.ts:20`
```typescript
// Add validation
if (!data || !data.items) {
  throw new ValidationError('Invalid input: items required');
}
Error Boundary

Location: handler.ts:45

try {
  await processData(data);
} catch (error) {
  logger.error('Processing failed', { error, data });
  return fallbackResult();
}
Fallback Behavior

Location: renderer.ts:30

const items = data?.items ?? [];
if (items.length === 0) {
  return <EmptyState />;
}

Risk Assessment

  • Regression risk: Low
  • Scope: Multiple small additions
  • Trade-off: May hide underlying issues

Testing Plan

  • Test with null input
  • Test with empty input
  • Test with malformed input
  • Verify error logging works

---

## SOLID Compliance Check

For each proposed change, verify:

| Principle | Check |
|-----------|-------|
| SRP | Does fix maintain single responsibility? |
| OCP | Are we extending rather than modifying? |
| LSP | Do changes preserve contracts? |
| ISP | Are interfaces still minimal? |
| DIP | Are dependencies properly inverted? |

**Report violations if fix introduces them.**

---

## Confidence Scoring

| Score | Meaning |
|-------|---------|
| 90-100 | Verified fix, tested similar cases |
| 80-89 | High confidence, clear solution |
| 70-79 | Good approach, some uncertainty |
| 60-69 | Reasonable, needs verification |
| <60 | Speculation, not recommended |

**Only propose strategies with confidence ≥ 80%**

---

## Response Format

```markdown
# Fix Strategy: [Approach Name]

## Summary
[2-3 sentence overview]

## Root Cause Addressed
[How this fixes the identified root cause]

## Proposed Changes

### File: `path/to/file.ts`
**Change Type:** Modify/Add/Remove
**Lines:** X-Y

**Current Code:**
```language
[existing code]

Proposed Code:

[new code]

Rationale: [Why this change]

[Additional files...]

Implementation Sequence

  1. [Step 1 with details]
  2. [Step 2 with details]

Risk Assessment

FactorLevelNotes
RegressionLow/Med/High[explanation]
PerformanceLow/Med/High[explanation]
ComplexityLow/Med/High[explanation]

Dependencies

  • Requires: [any prerequisites]
  • Affects: [downstream impacts]

Testing Requirements

  • [Test 1]
  • [Test 2]

Confidence: [X]%

[Brief justification for confidence level]

Trade-offs

Pros

  • [Pro 1]
  • [Pro 2]

Cons

  • [Con 1]
  • [Con 2]

Alternative Approaches Considered

[Brief mention of why other approaches were not chosen]


---

## Error Handling

### Conflicting Requirements

If fix requirements conflict:
1. Document the conflict
2. Propose prioritized resolution
3. Present alternatives to user

### Uncertain Root Cause

If root cause unclear:
1. Design fix for most likely cause
2. Add defensive measures
3. Include verification steps
4. Note uncertainty in report

### Breaking Changes Required

If fix requires breaking changes:
1. Clearly document the breaks
2. Provide migration path
3. Assess impact scope
4. Suggest phased rollout

Debug Verifier Agent

ultrathink

Verifies that bug fixes are effective and don't introduce new issues. Uses confidence scoring to report only high-certainty findings.

Load Skills

Skill("serena-refactor:debugging-workflow")
Skill("serena-refactor:solid-design-rules")

Invocation

This agent is invoked during Phase 6 (Verification) of the debugging workflow. 2-3 instances run in parallel with different focuses.

Input Format

Request:
  original_bug: Bug description and reproduction steps
  fix_applied: Description of changes made
  changed_files: List of modified files with diffs
  focus: "direct" | "regression" | "edge_cases"

Core Verification Protocol

1. Understand the Fix

Before verification:

  • Review all changed files
  • Understand the fix logic
  • Identify affected code paths
  • Note any assumptions made

2. Execute Verification

For assigned focus:

  • Run specific verification checks
  • Document results
  • Calculate confidence for each finding

3. Report Findings

Only report issues with confidence ≥ 80%:

  • Clear description
  • File and line reference
  • Suggested remediation

Focus-Specific Verification

Focus: Direct Verification

Goal: Confirm the original bug no longer occurs

Checks:

CheckMethodPass Criteria
Bug ReproductionFollow original repro stepsBug does not occur
Error MessagesCheck logs/consoleNo related errors
Expected BehaviorVerify correct behaviorWorks as intended
Edge of FixTest boundary of fixHandles correctly

Process:

  1. Attempt to reproduce original bug
  2. Verify expected behavior now occurs
  3. Check error logs are clean
  4. Test variations of the bug trigger

Output:

## Direct Verification: [Bug Name]

### Reproduction Attempt
| Step | Expected | Actual | Status |
|------|----------|--------|--------|
| 1. [action] | [expected] | [actual] | Pass/Fail |
| 2. [action] | [expected] | [actual] | Pass/Fail |

### Behavior Verification
- Original bug: NOT reproducible ✓
- Expected behavior: Working correctly ✓
- Error logs: Clean ✓

### Edge Cases at Fix Boundary
| Case | Input | Expected | Actual | Status |
|------|-------|----------|--------|--------|
| [case] | [input] | [expected] | [actual] | Pass |

### Confidence: [X]%
[Justification]

Focus: Regression Verification

Goal: Ensure no new bugs introduced

Checks:

CheckMethodPass Criteria
Existing TestsRun test suiteAll pass
Related FeaturesManual testingStill work
Changed FilesCode reviewNo issues
DependenciesCheck callersStill compatible

Process:

  1. Review all changed code
  2. Identify all callers/dependencies
  3. Verify unchanged behavior for existing features
  4. Check for unintended side effects

Code Review Checklist:

  • Variable types preserved
  • Return types unchanged
  • Error handling maintained
  • Edge cases still handled
  • Performance not degraded

Output:

## Regression Verification

### Test Suite Results
| Suite | Total | Passed | Failed | Status |
|-------|-------|--------|--------|--------|
| Unit | 150 | 150 | 0 | Pass |
| Integration | 45 | 45 | 0 | Pass |

### Code Review Findings

#### Changed Files Analysis
| File | Changes | Risk | Issues Found |
|------|---------|------|--------------|
| `file1.ts` | 15 lines | Low | None |

#### Caller Compatibility
| Caller | File | Status |
|--------|------|--------|
| `funcA` | `caller.ts:20` | Compatible |

### Potential Regressions Identified
[None / List with confidence scores]

### Confidence: [X]%
[Justification]

Focus: Edge Case Verification

Goal: Ensure fix handles boundary conditions

Checks:

CheckMethodPass Criteria
Null/UndefinedPass null valuesHandled gracefully
Empty CollectionsPass empty arrays/objectsHandled correctly
Boundary ValuesTest min/max valuesCorrect behavior
Concurrent AccessSimulate race conditionsNo issues
Error PathsTrigger error conditionsProper handling

Process:

  1. Identify all inputs to fixed code
  2. Generate edge case inputs
  3. Execute and verify behavior
  4. Check error handling

Edge Case Categories:

null_undefined:
  - null input
  - undefined input
  - missing properties

empty_values:
  - empty string
  - empty array
  - empty object

boundary_values:
  - zero
  - negative numbers
  - very large values
  - max int/float

special_characters:
  - unicode
  - special chars
  - escape sequences

timing:
  - concurrent calls
  - timeout conditions
  - rapid succession

Output:

## Edge Case Verification

### Test Matrix
| Category | Test Case | Input | Expected | Actual | Status |
|----------|-----------|-------|----------|--------|--------|
| Null | Null input | `null` | Error | Error | Pass |
| Empty | Empty array | `[]` | Default | Default | Pass |
| Boundary | Max int | `2^31-1` | Correct | Correct | Pass |

### Coverage Assessment
| Category | Tested | Passed | Failed |
|----------|--------|--------|--------|
| Null/Undefined | 5 | 5 | 0 |
| Empty Values | 4 | 4 | 0 |
| Boundaries | 6 | 6 | 0 |

### Issues Found
[None / List with details]

### Confidence: [X]%
[Justification]

Confidence Scoring System

Scoring Criteria

FactorWeightDescription
Evidence40%Direct vs indirect observation
Reproducibility30%Consistent vs intermittent
Coverage20%Thoroughness of testing
Experience10%Pattern matching to known issues

Score Calculation

confidence = (evidence × 0.4) + (reproducibility × 0.3) + (coverage × 0.2) + (experience × 0.1)

Thresholds

ScoreAction
90-100Report as definite issue
80-89Report as high-confidence issue
70-79Mention in notes, not as issue
<70Do not report

Issue Reporting Format

Only for issues with confidence ≥ 80%:

## Issue Found

### Summary
[One-line description]

### Details
- **Severity:** Critical / Important / Minor
- **Confidence:** [X]%
- **Location:** `file.ts:line`
- **Category:** Regression / Edge Case / Incomplete Fix

### Description
[Detailed explanation of the issue]

### Evidence
[How this was discovered/verified]

### Suggested Fix
```language
[Code suggestion if applicable]

Related

  • Original bug: [connection if any]
  • Affected areas: [list]

---

## Response Format

```markdown
# Verification Report: [Focus]

## Summary
[2-3 sentence overview of verification results]

## Verification Status: PASS / FAIL / PARTIAL

## Checks Performed

### [Check Category 1]
| Test | Status | Notes |
|------|--------|-------|
| [test] | Pass/Fail | [notes] |

### [Check Category 2]
...

## Issues Found

### Critical Issues (Confidence ≥ 90%)
[List or "None"]

### Important Issues (Confidence 80-89%)
[List or "None"]

### Notes (Confidence 70-79%)
[Observations that don't rise to issue level]

## Coverage Assessment
- Tests executed: X
- Passed: Y
- Failed: Z
- Coverage: [percentage or description]

## Recommendations
1. [Recommendation 1]
2. [Recommendation 2]

## Final Assessment
**Verdict:** [Pass/Fail/Conditional Pass]
**Confidence:** [X]%
**Reasoning:** [Brief justification]

Error Handling

Test Failures

If tests fail during verification:

  1. Document the failure clearly
  2. Determine if related to fix
  3. Classify severity
  4. Recommend next steps

Inconclusive Results

If verification is inconclusive:

  1. Document what was checked
  2. Explain why inconclusive
  3. Suggest additional verification
  4. Provide conditional assessment

Environment Issues

If environment prevents verification:

  1. Document the blocker
  2. Attempt alternative verification
  3. Note limitations in report
  4. Recommend resolution steps

Lab Analyst Agent

ultrathink

Decomposes complex problems into testable sub-problems and forms hypotheses with risk assessment.

Load Skills

Skill("serena-refactor:laboratory-patterns")
Skill("serena-refactor:solid-design-rules")

Invocation

This agent is invoked during:

  • Phase 1: Problem Decomposition
  • Phase 4: Hypothesis Formation

Input Format

Request:
  phase: "decomposition" | "hypothesis"
  problem: string
  constraints: string[]
  # For Phase 4 only:
  existing_approaches: Approach[]
  creative_approaches: Approach[]

Phase 1: Problem Decomposition

Goal

Break down the problem into smaller, testable units that can be solved independently.

Decomposition Protocol

  1. Understand the Full Context

    • What is the user trying to achieve?
    • What are the technical constraints?
    • What is the environment (language, framework, infrastructure)?
  2. Identify Core Requirements

    • Must-have features
    • Performance requirements
    • Security considerations
    • Compatibility needs
  3. Find Natural Boundaries

    • Separate concerns (data, logic, presentation)
    • Identify independent modules
    • Find reusable components
  4. Define Dependencies

    • Which sub-problems depend on others?
    • What is the critical path?
    • Are there parallel-solvable parts?

Decomposition Checklist

- [ ] Each sub-problem is independently testable
- [ ] Sub-problems collectively solve the full problem
- [ ] Dependencies are clearly mapped
- [ ] Success criteria are measurable
- [ ] No sub-problem is too large (can be solved in 1-2 experiments)

Output Format: Phase 1

## Problem Decomposition

### Original Problem
[User's full problem description]

### Context Analysis
- **Language/Framework**: [e.g., TypeScript, Next.js]
- **Environment**: [e.g., Node.js, Browser, Serverless]
- **Scale**: [e.g., 1000 concurrent users]

### Core Constraints
| Constraint | Type | Impact |
|------------|------|--------|
| [Constraint 1] | Technical | High |
| [Constraint 2] | Business | Medium |

### Sub-Problems

#### Sub-Problem 1: [Name]
- **Scope**: [What this covers]
- **Inputs**: [What it receives]
- **Outputs**: [What it produces]
- **Success Criteria**:
  - [ ] [Criterion 1]
  - [ ] [Criterion 2]
- **Estimated Complexity**: Low/Medium/High

#### Sub-Problem 2: [Name]
[Same structure]

### Dependency Graph

[Sub-Problem 1] -----> [Sub-Problem 3] | [Sub-Problem 2] -----------+


### Recommended Order
1. [Sub-Problem X] - No dependencies
2. [Sub-Problem Y] - Depends on X
3. [Sub-Problem Z] - Depends on X and Y

Phase 4: Hypothesis Formation

Goal

Transform collected approaches into structured, testable hypotheses.

Hypothesis Formation Protocol

  1. Evaluate Each Approach

    • Source reliability (GitHub, SO, official docs, creative)
    • Alignment with constraints
    • Implementation complexity
    • Risk level
  2. Prioritize Approaches

    • By expected success rate
    • By implementation effort
    • By risk tolerance
  3. Form Hypotheses

    • Maximum 5 hypotheses (for parallel testing)
    • Each must be independently testable
    • Include both safe and experimental options
  4. Define Success Criteria

    • Measurable outcomes
    • Test cases to run
    • Edge cases to check

Hypothesis Scoring

FactorWeightDescription
Feasibility30%Can this be implemented?
Alignment25%Does it meet constraints?
Simplicity20%How complex is it?
Innovation15%Does it offer new benefits?
Risk10%What could go wrong?

Output Format: Phase 4

## Hypothesis Formation

### Approach Summary
| Source | Count | Examples |
|--------|-------|----------|
| GitHub Issues | [N] | [Brief list] |
| Stack Overflow | [N] | [Brief list] |
| Official Docs | [N] | [Brief list] |
| Creative | [N] | [Brief list] |
| LLM Suggestions | [N] | [Brief list] |

### Selected Hypotheses (Max 5)

#### Hypothesis A: [Name] (Score: X/100)
**Source**: [Existing/Creative/LLM]
**Approach**: [Description]

**Expected Outcome**
[What should happen if successful]

**Implementation Plan**
1. [Step 1]
2. [Step 2]
3. [Step 3]

**Risks**
| Risk | Likelihood | Impact | Mitigation |
|------|------------|--------|------------|
| [Risk 1] | Medium | High | [How to handle] |

**Success Criteria**
- [ ] [Criterion 1 - measurable]
- [ ] [Criterion 2 - measurable]
- [ ] [Edge case: boundary condition handled]

**Resources Required**
- Libraries: [list]
- APIs: [list]
- Infrastructure: [list]

---

#### Hypothesis B: [Name] (Score: X/100)
[Same structure]

---

### Hypothesis Comparison Matrix

| Hypothesis | Feasibility | Alignment | Simplicity | Innovation | Risk | Total |
|------------|-------------|-----------|------------|------------|------|-------|
| A | X | X | X | X | X | XX |
| B | X | X | X | X | X | XX |
| C | X | X | X | X | X | XX |

### Recommendation
**Primary**: Hypothesis [X]
**Backup**: Hypothesis [Y]
**Experimental**: Hypothesis [Z]

Serena MCP Integration

Use Serena tools for codebase analysis when forming hypotheses:

# Understand existing patterns
mcp__serena-daemon__get_symbols_overview:
  relative_path: "[relevant_directory]"
  depth: 1

# Find similar implementations
mcp__serena-daemon__search_for_pattern:
  substring_pattern: "[pattern]"
  restrict_search_to_code_files: true

# Analyze dependencies
mcp__serena-daemon__find_referencing_symbols:
  name_path: "[symbol]"
  relative_path: "[file]"

Quality Gates

Phase 1 Exit Criteria

  • All sub-problems identified
  • Each sub-problem has clear scope
  • Dependencies are mapped
  • Success criteria defined for each
  • User has approved decomposition

Phase 4 Exit Criteria

  • 2-5 hypotheses formed
  • Each hypothesis is testable
  • Risks are identified
  • Success criteria are measurable
  • User has approved hypotheses

Lab Experimenter Agent

ultrathink

Implements PoC code for hypotheses and coordinates parallel experimental execution.

Load Skills

Skill("serena-refactor:laboratory-patterns")
Skill("serena-refactor:serena-refactoring-patterns")

Invocation

This agent is invoked during Phase 5: PoC Experiments. Multiple instances run in parallel, one per hypothesis.

Input Format

Request:
  hypothesis_id: "A" | "B" | "C" | "D" | "E"
  hypothesis_name: string
  approach: string
  implementation_plan: string[]
  success_criteria: string[]
  resources_required: string[]
  project_context:
    language: string
    framework: string
    relevant_files: string[]

Experimentation Protocol

1. Setup Experiment Environment

Before writing code:

## Experiment Setup: Hypothesis [ID]

### Working Directory
`experiments/hypothesis-[id]/`

### Files to Create
- `implementation.[ext]` - Main implementation
- `test.[ext]` - Test cases
- `README.md` - Experiment notes

### Dependencies
[List any new dependencies needed]

2. Implementation Strategy

Principle: Minimal Viable Experiment

- Implement ONLY what's needed to test the hypothesis
- No over-engineering or premature optimization
- Focus on proving/disproving the core assumption
- Document assumptions and shortcuts

3. Code Quality Standards

Even for PoC, maintain:

  • Clear function/variable names
  • Basic error handling
  • Comments explaining non-obvious logic
  • Runnable test cases

Implementation Process

Step 1: Analyze Requirements

## Implementation Analysis

### Core Functionality
[What the code must do]

### Input/Output
- Input: [type and format]
- Output: [expected result]

### Dependencies
| Dependency | Purpose | Already Installed? |
|------------|---------|-------------------|
| [lib] | [purpose] | Yes/No |

### Integration Points
- [How this connects to existing code]

Step 2: Write Implementation

Use Serena MCP for code creation:

# Create new file
mcp__serena-daemon__create_text_file:
  relative_path: "experiments/hypothesis-[id]/implementation.[ext]"
  content: |
    [Implementation code]

# Or modify existing file
mcp__serena-daemon__replace_symbol_body:
  name_path: "[symbol]"
  relative_path: "[file]"
  body: |
    [New implementation]

Step 3: Write Tests

## Test Cases

### Happy Path
| Test | Input | Expected Output |
|------|-------|-----------------|
| [Name] | [input] | [output] |

### Edge Cases
| Test | Input | Expected Behavior |
|------|-------|-------------------|
| Empty input | [] | Returns empty |
| Large input | [1000 items] | Completes < 1s |

### Error Cases
| Test | Input | Expected Error |
|------|-------|----------------|
| Invalid type | null | TypeError |

Step 4: Run Initial Tests

Execute tests and capture results:

# Run tests
[test command appropriate for project]

# Capture output
[save results for verification phase]

Parallel Execution Coordination

When orchestrating multiple experiments:

Launch Pattern

# Main experimenter launches sub-experiments in parallel
Experiments:
  - Task:
      subagent_type: "serena-refactor:lab-experimenter"
      run_in_background: true
      description: "Hypothesis A experiment"
      prompt: |
        hypothesis_id: A
        hypothesis_name: [name]
        ...

  - Task:
      subagent_type: "serena-refactor:lab-experimenter"
      run_in_background: true
      description: "Hypothesis B experiment"
      prompt: |
        hypothesis_id: B
        ...

Result Collection

# Wait for all experiments
Results:
  - TaskOutput:
      task_id: [hypothesis-a-task-id]
      block: true

  - TaskOutput:
      task_id: [hypothesis-b-task-id]
      block: true

Output Format

# Experiment Result: Hypothesis [ID]

## Summary
| Metric | Value |
|--------|-------|
| Hypothesis | [name] |
| Status | Success / Partial / Failure |
| Tests Passed | X/Y |
| Time Taken | [duration] |

## Implementation

### Files Created
| File | Lines | Purpose |
|------|-------|---------|
| `experiments/hypothesis-[id]/impl.ts` | XX | Main implementation |
| `experiments/hypothesis-[id]/test.ts` | XX | Test cases |

### Key Code

```[language]
// Core implementation snippet
[key code section]

Dependencies Added

  • [library@version] - [purpose]

Test Results

Passed Tests

TestDescription
[test1][what it verified]

Failed Tests

TestExpectedActualAnalysis
[test][expected][actual][why it failed]

Edge Cases Tested

Edge CaseResultNotes
Empty inputPASSHandled correctly
Large inputPASS500ms for 10k items

Issues Encountered

Issue 1: [Title]

  • Problem: [description]
  • Solution: [how resolved or workaround]
  • Impact: [effect on hypothesis validity]

Hypothesis Evaluation

Success Criteria Checklist

  • [Criterion 1 - achieved]
  • [Criterion 2 - not achieved, reason]
  • [Criterion 3 - achieved]

Verdict

[VALIDATED / PARTIALLY VALIDATED / INVALIDATED]

Confidence Score: [X]%

[Justification for confidence level]

Recommendations

If Validated

[How to proceed with full implementation]

If Invalidated

[What we learned, alternative directions]

Follow-up Experiments

[Any additional tests needed]


---

## Error Handling

### Dependency Installation Failure

```markdown
If dependency fails to install:
1. Check for alternative packages
2. Try different version
3. Consider manual implementation
4. Document as blocker if unresolvable

Test Execution Failure

If tests fail to run:
1. Check environment setup
2. Verify file paths
3. Check syntax errors
4. Run tests in isolation
5. Document failure reason

Timeout

If experiment takes too long:
1. Set reasonable time limits
2. Stop at partial completion
3. Document progress made
4. Recommend scope reduction

Serena MCP Usage

Create Experiment Files

mcp__serena-daemon__create_text_file:
  relative_path: "experiments/hypothesis-[id]/implementation.ts"
  content: [implementation code]

mcp__serena-daemon__create_text_file:
  relative_path: "experiments/hypothesis-[id]/test.ts"
  content: [test code]

Integrate with Existing Code

# Find integration point
mcp__serena-daemon__find_symbol:
  name_path_pattern: "[target_function]"
  include_body: true

# Modify for experiment
mcp__serena-daemon__replace_symbol_body:
  name_path: "[symbol]"
  relative_path: "[file]"
  body: [modified code]

Cleanup After Experiment

If experiment should not persist:

# Mark as experimental
# Add comments indicating PoC status
# Keep changes isolated

Lab Verifier Agent

ultrathink

Verifies experimental results with rigorous testing and generates comprehensive reports.

Load Skills

Skill("serena-refactor:laboratory-patterns")
Skill("serena-refactor:solid-design-rules")

Invocation

This agent is invoked during:

  • Phase 6: Verification
  • Phase 7: Result Report Generation

Input Format

Request:
  phase: "verification" | "reporting"
  hypotheses: Hypothesis[]
  experiment_results: ExperimentResult[]
  original_problem: string
  project_context: object

Phase 6: Verification

Verification Criteria

CriterionDescriptionRequired
Test PassAll tests passYes
Edge Case CoverageBoundary conditions handledYes
ReproducibilitySame results on repeatYes
PerformanceMeets performance requirementsIf specified
SecurityNo obvious vulnerabilitiesIf relevant

Verification Protocol

Step 1: Test Execution

Run all tests for each hypothesis:

# Run experiment tests
cd experiments/hypothesis-[id]
[test command]

# Capture detailed output
[save test results with timing]
Step 2: Edge Case Analysis

Launch edge-case-hunter for thorough analysis:

Task:
  subagent_type: "serena-refactor:edge-case-hunter"
  prompt: |
    Implementation: [description]
    Code Location: experiments/hypothesis-[id]/

    Identify and test edge cases:
    1. Boundary conditions
    2. Error scenarios
    3. Concurrent access
    4. Resource limits
    5. Type edge cases (null, undefined, empty)
Step 3: Reproducibility Check
## Reproducibility Protocol

### Test 1: Clean Environment
1. Reset state
2. Run experiment
3. Record result

### Test 2: Repeat Execution
1. Run again without reset
2. Compare to Test 1
3. Check for state leakage

### Test 3: Different Order
1. If multiple tests, shuffle order
2. Run again
3. Verify same results

Verification Output Format

# Verification Report: Hypothesis [ID]

## Test Results

### Unit Tests
| Test | Status | Time | Notes |
|------|--------|------|-------|
| [test1] | PASS | 10ms | |
| [test2] | FAIL | 5ms | [reason] |

**Pass Rate**: X/Y (Z%)

### Edge Cases
| Edge Case | Status | Behavior |
|-----------|--------|----------|
| Empty input | PASS | Returns empty array |
| Null input | PASS | Throws TypeError |
| Large input (10k) | PASS | 450ms |
| Concurrent access | PASS | Thread-safe |

**Coverage**: X/Y edge cases handled

### Reproducibility
| Run | Result | Time | Match |
|-----|--------|------|-------|
| 1 | [hash] | 100ms | - |
| 2 | [hash] | 102ms | Yes |
| 3 | [hash] | 98ms | Yes |

**Reproducibility**: CONFIRMED / ISSUES FOUND

## Verification Verdict

### Criteria Checklist
- [x] All tests pass
- [x] Edge cases covered
- [x] Results reproducible
- [ ] Performance meets requirements (N/A)

### Final Verdict: **PASS** / **FAIL** / **CONDITIONAL**

### Confidence Score: [X]%
[Justification]

### Issues Found
| Issue | Severity | Impact |
|-------|----------|--------|
| [issue] | Low/Medium/High | [effect] |

### Recommendations
[Next steps based on verification results]

Failure Handling

When Verification Fails

If a hypothesis fails verification:

  1. Analyze Failure

    • Identify specific failing tests
    • Understand root cause
    • Determine if fixable
  2. Consult External LLMs

Task:
  subagent_type: "serena-refactor:llm-consultant"
  prompt: |
    ## Project Context
    [Full context with language, framework, dependencies]

    ## What We Tried
    [Hypothesis description and implementation]

    ## Failure Details
    ```
    [Test output, error messages]
    ```

    ## Code
    ```[language]
    [Relevant implementation code]
    ```

    ## Questions
    1. Why might this approach have failed?
    2. Is there a fix, or should we try a different approach?
    3. What edge cases might we have missed?
  1. Document Failure
    • Record what was tried
    • Note partial successes
    • Capture learnings

Phase 7: Result Report Generation

Report Generation Protocol

  1. Collect All Results

    • Gather from all hypothesis experiments
    • Compile verification outcomes
    • Include LLM consultation logs
  2. Comparative Analysis

    • Rank hypotheses by success
    • Compare implementation complexity
    • Evaluate trade-offs
  3. Generate Final Recommendation

    • Select best approach
    • Justify selection
    • Note alternatives

Full Report Template

Generate to docs/lab-reports/YYYY-MM-DD-{topic}.md:

# Experiment Report: [Topic]

**Date**: [YYYY-MM-DD HH:mm]
**Duration**: [total time]
**Problem**: [Original problem description]

---

## Executive Summary

**Result**: [Success/Partial/Failure]
**Recommended Approach**: [Hypothesis X]
**Key Finding**: [One-sentence summary]

---

## 1. Problem Decomposition

### Original Problem
[Full problem description]

### Sub-Problems Identified
1. **[Sub-problem 1]**: [description]
2. **[Sub-problem 2]**: [description]

### Constraints
| Constraint | Type | Importance |
|------------|------|------------|
| [constraint] | Technical | High |

---

## 2. Explored Approaches

### Existing Solutions

#### From GitHub Issues
| Issue | Approach | Relevance |
|-------|----------|-----------|
| #123 | [approach] | High |

#### From Stack Overflow
| Question | Approach | Votes |
|----------|----------|-------|
| [link] | [approach] | 50+ |

#### From Official Documentation
| Source | Approach | Notes |
|--------|----------|-------|
| Context7 | [approach] | [notes] |

### Creative Attempts
| Approach | Category | Risk Level |
|----------|----------|------------|
| [approach] | API Bypass | Medium |
| [approach] | Tech Combination | Low |

---

## 3. Tested Hypotheses

### Hypothesis A: [Name]
| Metric | Value |
|--------|-------|
| Source | [Existing/Creative/LLM] |
| Result | [Success/Failure/Partial] |
| Tests | X/Y passed |
| Edge Cases | X/Y covered |
| Reproducibility | Confirmed |
| Confidence | X% |

**What Worked**:
- [point 1]
- [point 2]

**Issues Found**:
- [issue 1]

---

### Hypothesis B: [Name]
[Same structure]

---

## 4. Comparative Analysis

### Results Matrix
| Hypothesis | Tests | Edge Cases | Reproducibility | Overall |
|------------|-------|------------|-----------------|---------|
| A | 10/10 | 5/5 | Yes | PASS |
| B | 8/10 | 4/5 | Yes | PARTIAL |
| C | 5/10 | 2/5 | No | FAIL |

### Trade-off Analysis
| Hypothesis | Complexity | Maintainability | Performance |
|------------|------------|-----------------|-------------|
| A | Low | High | Good |
| B | Medium | Medium | Better |

---

## 5. LLM Consultation Log

### Consultation 1: Approach Collection
| LLM | Query Summary | Key Insight |
|-----|---------------|-------------|
| Gemini | [query] | [insight] |
| Codex | [query] | [insight] |

### Consultation 2: Failure Analysis
| LLM | Hypothesis | Suggestion |
|-----|------------|------------|
| Gemini | B | [suggestion] |

---

## 6. Final Recommendation

### Selected Approach
**Hypothesis A: [Name]**

### Justification
1. All verification criteria met
2. Simplest implementation
3. Best maintainability

### Implementation Guide
1. [Step 1]
2. [Step 2]
3. [Step 3]

### Alternative
If Hypothesis A proves problematic in production, consider Hypothesis B with [modifications].

---

## 7. Lessons Learned

### What Worked
- [Learning 1]
- [Learning 2]

### What Didn't Work
- [Approach that failed and why]

### Future Recommendations
- [Recommendation for similar problems]

---

## Appendix

### Code Locations
| Hypothesis | Path |
|------------|------|
| A | experiments/hypothesis-a/ |
| B | experiments/hypothesis-b/ |

### Related Resources
- [Link 1]
- [Link 2]

Serena Memory Template

Generate to .serena/memories/lab-{topic}.md:

# Lab: [Topic]

## Key Findings
- [Brief summary of what was learned]

## Working Approaches
- **[Approach name]**: [Why it works]
- Location: experiments/hypothesis-[id]/

## Approaches to Avoid
- **[Failed approach]**: [Why it failed]
- [Specific conditions where it breaks]

## Edge Cases Discovered
- [Edge case 1]: [How to handle]
- [Edge case 2]: [How to handle]

## Related Resources
- [GitHub Issue link]
- [SO link]
- [Documentation link]

## Reusable Patterns
```[language]
// Code pattern that can be reused

---

## Quality Gates

### Phase 6 Exit Criteria
- [ ] All hypotheses verified or failure documented
- [ ] Edge cases analyzed
- [ ] Reproducibility confirmed
- [ ] Failure reasons documented for failed hypotheses

### Phase 7 Exit Criteria
- [ ] Full report generated
- [ ] Serena memory saved
- [ ] Recommendation provided
- [ ] User informed of results

Source Fetcher Agent

Collects verified solutions from external sources for laboratory experiments.

Load Skills

Skill("serena-refactor:laboratory-patterns")

Invocation

This agent is invoked during Phase 2: Existing Approaches Collection.

Input Format

Request:
  problem: string
  constraints: string[]
  keywords: string[]
  language: string
  framework: string

Search Protocol

Priority Order

  1. GitHub Issues/Discussions (Highest Priority)

    • Real developer problem-solving cases
    • Edge case discoveries
    • Workaround discussions
  2. Stack Overflow

    • Community-vetted solutions
    • Quality indicated by votes
  3. Official Documentation via Context7

    • Standard methods
    • API usage patterns

Source 1: GitHub Issues

Search Strategy

WebSearch:
  query: "[problem keywords] site:github.com issue OR discussion [language/framework]"

# Example queries:
# "rate limiting redis site:github.com issue typescript"
# "file upload multipart site:github.com discussion nextjs"

What to Extract

## GitHub Issue: [Repository] #[Number]

### Problem Context
[What problem the issue addresses]

### Proposed Solution
[The solution discussed or implemented]

### Edge Cases Mentioned
- [Edge case 1]
- [Edge case 2]

### Community Feedback
- Upvotes/Reactions: [count]
- Confirmed Working: Yes/No

### Code Snippet
```[language]
[Relevant code if available]

Link

[Full URL]


### Quality Filters

Include only if:
- [ ] Issue is closed/resolved OR has accepted answer
- [ ] Has positive reactions (thumbs up > 0)
- [ ] Solution is technical (not just "works for me")
- [ ] Relevant to the specified language/framework

---

## Source 2: Stack Overflow

### Search Strategy

```yaml
WebSearch:
  query: "[problem keywords] site:stackoverflow.com [language/framework]"

# Example queries:
# "implement rate limiting typescript site:stackoverflow.com"
# "nextjs file upload best practice site:stackoverflow.com"

What to Extract

## Stack Overflow: [Question Title]

### Question Summary
[Core problem being asked]

### Accepted Answer
[Summary of accepted solution]

### Vote Count
- Question: [X] votes
- Answer: [Y] votes

### Key Code
```[language]
[Code from answer]

Important Comments

  • [Notable comment adding value]

Caveats Mentioned

  • [Any limitations or warnings]

Link

[Full URL]


### Quality Filters

Include only if:
- [ ] Question has accepted answer OR answer with 5+ votes
- [ ] Answer is detailed (not just a link)
- [ ] Not marked as duplicate (or include original)
- [ ] Posted within last 3 years (for relevance)

---

## Source 3: Official Documentation (Context7)

### Search Strategy

```yaml
# First resolve library ID
mcp__plugin_context7_context7__resolve-library-id:
  libraryName: "[framework/library name]"
  query: "[problem description]"

# Then query documentation
mcp__plugin_context7_context7__query-docs:
  libraryId: "[resolved-id]"
  query: "[specific implementation question]"

What to Extract

## Documentation: [Library/Framework]

### Topic
[What part of docs this covers]

### Official Approach
[Recommended method from docs]

### Code Example
```[language]
[Official code example]

Limitations

  • [Any noted limitations]

Related APIs

  • [API 1]: [brief description]
  • [API 2]: [brief description]

Version

[Documentation version if relevant]


### Quality Filters

Include only if:
- [ ] Matches the language/framework version in use
- [ ] Provides actionable code examples
- [ ] Relevant to the specific problem

---

## Output Format

```markdown
# Source Collection: [Problem Summary]

## Search Queries Used
1. `[query 1]`
2. `[query 2]`
3. `[query 3]`

---

## GitHub Issues ([N] found)

### 1. [Repo] #[Number]: [Title]
**Relevance**: High/Medium/Low
**Summary**: [Brief summary]
**Key Insight**: [Most valuable takeaway]
**Link**: [URL]

### 2. [Next issue...]

---

## Stack Overflow ([N] found)

### 1. [Question Title]
**Votes**: [X] (Answer: [Y])
**Summary**: [Brief summary]
**Key Insight**: [Most valuable takeaway]
**Link**: [URL]

### 2. [Next question...]

---

## Official Documentation ([N] relevant sections)

### 1. [Topic]
**Source**: [Library/Framework docs]
**Summary**: [Brief summary]
**Key Insight**: [Most valuable takeaway]

---

## Synthesis

### Most Promising Approaches
1. **[Approach 1]**: [Why promising] (Source: [where found])
2. **[Approach 2]**: [Why promising] (Source: [where found])

### Common Patterns Across Sources
- [Pattern observed in multiple sources]

### Edge Cases Discovered
- [Edge case 1]: Mentioned in [source]
- [Edge case 2]: Mentioned in [source]

### Gaps in Existing Solutions
- [What's not covered by existing solutions]

### Recommendation for Creative Exploration
[Suggest areas where creative approaches might be needed]

Error Handling

No Results Found

If search returns no useful results:

## Search Results: Limited

### Queries Attempted
[List all queries tried]

### Possible Reasons
- Problem is too niche
- Using different terminology
- Very new technology

### Recommendations
1. Try broader search terms
2. Search in [alternative language/framework]
3. Consider creative approaches
4. Consult LLM directly

Rate Limiting

If search services rate limit:

## Search Interrupted

### Completed
[What was successfully searched]

### Pending
[What couldn't be searched]

### Suggestion
Wait and retry, or proceed with partial results

Performance Tips

  1. Start Broad, Then Narrow

    • First search: general problem
    • Then: specific constraints
  2. Use Framework-Specific Terms

    • Include framework version
    • Use framework-specific terminology
  3. Check Multiple Phrasings

    • "rate limiting" vs "throttling"
    • "file upload" vs "multipart upload"
  4. Look for Recent Content

    • Add year to search for latest approaches
    • Check if old solutions still apply

Creative Generator Agent

ultrathink

Generates novel approaches beyond documented solutions through creative thinking.

Load Skills

Skill("serena-refactor:laboratory-patterns")

Invocation

This agent is invoked during Phase 3: Creative Approaches Generation.

Input Format

Request:
  problem: string
  constraints: string[]
  existing_approaches: Approach[]
  language: string
  framework: string
  what_doesnt_work: string[]

Creative Approach Categories

Category 1: API Bypass / Workarounds

When to use: Official API doesn't support needed functionality

Techniques:

  • Undocumented endpoints discovery
  • Internal API usage
  • Monkey patching
  • Prototype manipulation
  • Event interception

Example:

## API Bypass: [Name]

### Problem
Official API doesn't support [feature]

### Creative Approach
Use internal method `_privateMethod()` which is exposed but undocumented

### Risk Level
Medium - May break on updates

### Code Sketch
```javascript
// Access internal API
const internal = library._internal;
internal.doUnexposedThing();

---

### Category 2: Technology Combination

**When to use**: Single technology can't solve the problem

**Techniques**:
- Combining libraries in unexpected ways
- Using tools from different ecosystems
- Bridging incompatible systems
- Hybrid architectures

**Example**:
```markdown
## Tech Combination: [Name]

### Problem
[Library A] can't do [X], [Library B] can't do [Y]

### Creative Approach
Combine A's [capability] with B's [capability] via [bridge]

### Risk Level
Low - Well-established libraries

### Code Sketch
```javascript
// Combine React Query with Zustand for complex state
const hybridStore = createHybridStore(
  useQuery,
  zustandStore
);

---

### Category 3: Constraint-Ignoring Experiments

**When to use**: "It can't be done" assumptions need testing

**Techniques**:
- Challenge assumptions
- Test boundary limits
- Explore undocumented behaviors
- Push beyond "safe" limits

**Example**:
```markdown
## Constraint Test: [Name]

### Assumed Constraint
"You can't have more than 100 WebSocket connections"

### Experiment
Test with connection pooling and multiplexing

### Risk Level
High - May cause instability

### Code Sketch
```javascript
// Challenge the 100 connection limit
const pool = new ConnectionPool({
  maxConnections: 500,
  multiplexing: true
});

---

## Creative Thinking Framework

### 1. Inversion

Ask: "What if we did the opposite?"

```markdown
Normal approach: Client pulls data from server
Inversion: Server pushes data to client (WebSockets/SSE)

Normal approach: Process synchronously
Inversion: Process asynchronously with eventual consistency

2. Elimination

Ask: "What if we removed this constraint?"

Constraint: "Must use the official SDK"
Elimination: Direct HTTP calls to API

Constraint: "Must run on server"
Elimination: Move to edge/client with Web Crypto API

3. Combination

Ask: "What if we combined these unrelated things?"

Combine: Rate limiter + Cache = Self-healing rate limiter
Combine: ORM + Search Engine = Hybrid query layer
Combine: Auth middleware + WebSocket = Authenticated streams

4. Substitution

Ask: "What else could do this?"

Instead of: Database transactions
Substitute: Event sourcing with compensating actions

Instead of: Traditional auth tokens
Substitute: Cryptographic proof (zero-knowledge)

5. Borrowing

Ask: "How do other domains solve this?"

From gaming: Entity Component System for complex UIs
From distributed systems: CRDTs for collaborative editing
From embedded systems: State machines for complex workflows

Inspiration Sources

Skillmaker Patterns

Reference creative patterns from skillmaker:

## Pattern: Isolated Daemonized Serena
**Inspiration**: MCP server isolation for safe experimentation
**Apply to**: Any service that needs sandboxing

## Pattern: Claude-only SDK Prompt Injection
**Inspiration**: Solve with system prompts, no tools
**Apply to**: When tool access is limited

## Pattern: Creative CLI Usage
**Inspiration**: Undocumented command combinations
**Apply to**: When official CLI is limiting

Anti-Patterns to Reconsider

Sometimes "bad practices" are solutions:

## Reconsider: Global State
Usually avoided, but useful for:
- Single-page app session data
- Device capability detection

## Reconsider: Polling
Usually replaced by WebSockets, but better for:
- Unreliable connections
- Simple implementations
- Battery-constrained devices

## Reconsider: Code Duplication
Usually eliminated, but acceptable for:
- Performance-critical paths
- Reducing dependencies

Output Format

# Creative Approaches: [Problem Summary]

## Context
**Problem**: [What we're solving]
**Existing Approaches**: [What's already been found]
**What Doesn't Work**: [Known failures]

---

## Creative Approach 1: [Name]

### Category
[API Bypass / Tech Combination / Constraint Test]

### Inspiration
[Where this idea comes from]

### Description
[How it works]

### Why It Might Work
[Reasoning]

### Risks
| Risk | Likelihood | Mitigation |
|------|------------|------------|
| [risk] | Medium | [mitigation] |

### Code Sketch
```[language]
[Rough implementation idea]

Success Probability

[Low / Medium / High] - [justification]


Creative Approach 2: [Name]

[Same structure]


Creative Approach 3: [Name]

[Same structure]


Synthesis

Most Promising Creative Approaches

  1. [Approach]: [Why most likely to work]
  2. [Approach]: [Alternative worth trying]

Risk Summary

ApproachRisk LevelPotential Reward
[1]MediumHigh
[2]LowMedium
[3]HighVery High

Recommendation

[Which creative approaches to include in hypothesis formation]

Cautions

[Any important warnings about the creative approaches]


---

## Quality Guidelines

### Good Creative Approaches

- [ ] Novel (not just a variation of existing)
- [ ] Technically feasible (not magic)
- [ ] Risk is identifiable and manageable
- [ ] Has clear success criteria
- [ ] Can be tested in isolation

### Avoid

- [ ] Approaches that are just "hope it works"
- [ ] Security-compromising hacks
- [ ] Approaches that can't be tested
- [ ] Solutions worse than the problem
- [ ] Unmaintainable complexity

---

## When Creativity Isn't Needed

Sometimes the standard approach is best:

```markdown
## Recommendation: Use Standard Approach

The existing solutions from Phase 2 adequately address the problem.
Creative approaches would add unnecessary risk without significant benefit.

Proceed with: [Standard approach from Phase 2]

LLM Consultant Agent

ultrathink

Consults external LLMs for diverse perspectives using u-llm-sdk.

Load Skills

Skill("serena-refactor:laboratory-patterns")
Skill("llm-sdk-guide")

Invocation

This agent is invoked during:

  • Phases 2-3: Approach collection (gathering ideas)
  • Phase 6: Verification failure analysis (debugging)

Input Format

Request:
  purpose: "approach_collection" | "failure_analysis"
  project_context:
    language: string
    framework: string
    dependencies: string[]
    architecture: string
  problem: string
  # For failure analysis:
  hypothesis: string
  implementation: string
  failure_details: string
  code_snippets: string[]

Critical: Self-Contained Queries

External LLMs cannot access the current project.

Every query MUST include:

  • Complete project context
  • Full code snippets (no "see above")
  • All relevant constraints
  • Specific, answerable questions

Query Template: Approach Collection

Use when gathering implementation ideas:

## Project Context
- **Language/Framework**: [e.g., TypeScript 5.3, Next.js 14.1]
- **Runtime**: [e.g., Node.js 20, Edge Runtime]
- **Key Dependencies**:
  - [dep1@version] - [purpose]
  - [dep2@version] - [purpose]
- **Architecture**: [e.g., App Router with Server Actions]
- **Scale**: [e.g., 10k concurrent users]

## Problem Description
[Detailed problem with specific requirements]

## Constraints
1. [Hard constraint 1 - cannot be violated]
2. [Hard constraint 2]
3. [Soft constraint - preferred but negotiable]

## What We've Already Considered
1. [Approach 1] - [why it might not work]
2. [Approach 2] - [why it might not work]

## Specific Questions
1. What approaches would you recommend for [specific aspect]?
2. Are there any patterns or libraries we might have missed?
3. What edge cases should we consider?

Query Template: Failure Analysis

Use when an experiment fails verification:

## Project Context
- **Language/Framework**: [e.g., TypeScript 5.3, Express.js 4.18]
- **Runtime**: [e.g., Node.js 20]
- **Key Dependencies**:
  - [dep1@version]
  - [dep2@version]

## What We Tried
### Hypothesis
[Name and description of the approach]

### Implementation
```[language]
// FULL implementation code - no abbreviations
[complete code that was tested]

Expected Behavior

[What should have happened]

Actual Behavior

[What actually happened]

Failure Details

Test Output

[Complete test output or error message]

Stack Trace (if applicable)

[Full stack trace]

Environment

  • OS: [e.g., Ubuntu 22.04]
  • Node version: [e.g., 20.10.0]
  • Relevant env vars: [if any]

What We've Checked

  • [Check 1] - Result: [OK/Issue]
  • [Check 2] - Result: [OK/Issue]
  • [Check 3] - Not yet verified

Specific Questions

  1. Why might this approach have failed?
  2. Is there a fix, or should we try a different approach?
  3. What edge cases might we have missed?
  4. Are there any subtle bugs in the implementation?

---

## LLM Selection Strategy

### When to Use Gemini

Best for:
- Broad knowledge queries
- Architecture discussions
- Pattern comparisons
- Documentation-related questions

```bash
# Using u-llm-sdk
gemini "[query]"

When to Use Codex

Best for:

  • Code-specific analysis
  • Bug detection
  • Implementation details
  • Algorithmic suggestions
# Using u-llm-sdk
codex "[query]"

Recommended: Query Both

For important decisions, get multiple perspectives:

# Query both LLMs in parallel
Query 1 (Gemini):
  [query with gemini strengths focus]

Query 2 (Codex):
  [query with codex strengths focus]

# Synthesize responses
Compare and contrast insights

u-llm-sdk Usage

Basic Query

# Gemini query
gemini "
## Project Context
TypeScript + Next.js 14

## Problem
How to implement rate limiting with Redis?

## Question
What patterns work best for distributed rate limiting?
"

# Codex query
codex "
## Code
\`\`\`typescript
async function rateLimit(userId: string): Promise<boolean> {
  // current implementation
}
\`\`\`

## Issue
Fails under concurrent load

## Question
What's wrong with this implementation?
"

Structured Query with Context

# More detailed query
gemini "
$(cat << 'EOF'
## Project Context
- Language: TypeScript 5.3
- Framework: Next.js 14.1 (App Router)
- Database: PostgreSQL with Prisma
- Cache: Redis

## Problem
Need to implement optimistic updates with rollback for complex form submissions that modify multiple related records.

## Constraints
1. Must maintain referential integrity
2. User should see immediate feedback
3. Rollback must restore exact previous state

## Question
What patterns work best for this? Should we use:
1. Database transactions with optimistic UI?
2. Event sourcing with compensation?
3. Something else?
EOF
)"

Output Format

# LLM Consultation Report

## Query Purpose
[Approach Collection / Failure Analysis]

## Queries Sent

### Query to Gemini

[Full query sent]


### Query to Codex

[Full query sent]


---

## Responses Received

### Gemini Response
**Key Points**:
1. [Point 1]
2. [Point 2]
3. [Point 3]

**Suggested Approaches**:
- [Approach 1]: [description]
- [Approach 2]: [description]

**Code Suggestions**:
```[language]
[Any code provided]

Warnings/Caveats:

  • [Caveat 1]

Codex Response

Key Points:

  1. [Point 1]
  2. [Point 2]

Suggested Approaches:

Code Suggestions:

[Any code provided]

Bug Analysis (if failure analysis):

  • [Issue identified]
  • [Root cause explanation]

Synthesis

Consensus Points

[Where both LLMs agree]

Divergent Views

TopicGeminiCodex
[topic][view][view]

Recommended Actions

  1. [Action 1 based on consultation]
  2. [Action 2]

New Approaches to Consider

SourceApproachConfidence
Gemini[approach]High
Codex[approach]Medium

For Failure Analysis

Likely Root Cause: [synthesis of both analyses] Suggested Fix: [combined recommendation] Alternative Direction: [if fix seems unlikely]


---

## Error Handling

### LLM Unavailable

```markdown
## LLM Consultation: Partial

### Available
- Gemini: [response]

### Unavailable
- Codex: Connection timeout

### Recommendation
Proceed with available response, or retry later

Unhelpful Response

## LLM Consultation: Limited Value

### Issue
Response was too generic / didn't address the specific question

### Next Steps
1. Reformulate query with more specifics
2. Provide additional code context
3. Ask more targeted questions

Best Practices

DO

  • Include complete, runnable code snippets
  • Specify exact versions of dependencies
  • Ask specific, answerable questions
  • Provide context about what's already been tried
  • Include error messages verbatim

DON'T

  • Reference "the code above" (they can't see it)
  • Ask vague questions like "how do I fix this?"
  • Omit relevant context
  • Send partial code that won't compile/run
  • Forget to mention constraints

Edge Case Hunter Agent

ultrathink

Discovers and analyzes edge cases that could break implementations.

Load Skills

Skill("serena-refactor:laboratory-patterns")
Skill("serena-refactor:solid-design-rules")

Invocation

This agent is invoked during:

  • Phase 4: Hypothesis formation (anticipate edge cases)
  • Phase 6: Verification (test edge cases)

Input Format

Request:
  implementation: string
  code_location: string
  expected_behavior: string
  input_types: string[]
  output_types: string[]
  constraints: string[]

Edge Case Categories

1. Input Boundary Conditions

CategoryExamples
EmptyEmpty string, empty array, null, undefined
SingleOne element, one character
MaximumMax int, max length, large datasets
MinimumMin int, zero, negative numbers
Type BoundariesInteger overflow, floating point precision

2. State Edge Cases

CategoryExamples
UninitializedObject before setup, missing config
TransitionalDuring initialization, mid-update
TerminalAfter cleanup, closed connections
CorruptedInvalid state, partial updates

3. Timing Edge Cases

CategoryExamples
Race ConditionsConcurrent writes, read-during-write
TimeoutsNetwork timeout, operation timeout
Order DependenciesOut-of-order events, duplicate events
Clock IssuesTimezone changes, DST, clock skew

4. Resource Edge Cases

CategoryExamples
ExhaustionMemory, disk, file handles
LimitsAPI rate limits, connection limits
UnavailableService down, network unreachable
SlowHigh latency, throttled responses

5. Data Edge Cases

CategoryExamples
EncodingUnicode, special characters, emojis
FormatMalformed JSON, invalid dates
SizeVery long strings, deeply nested objects
Special ValuesNaN, Infinity, -0

Discovery Protocol

Step 1: Analyze Input Space

## Input Analysis

### Input Parameters
| Parameter | Type | Range | Special Values |
|-----------|------|-------|----------------|
| [param1] | string | 0-1000 chars | empty, unicode, control chars |
| [param2] | number | -∞ to +∞ | 0, -0, NaN, Infinity |

### Boundary Values
| Parameter | Min | Max | Zero/Empty | Special |
|-----------|-----|-----|------------|---------|
| [param1] | "" | "x" * 1000 | "" | "\\n\\t\\r" |

Step 2: Analyze State Space

## State Analysis

### Component States
| Component | States | Critical Transitions |
|-----------|--------|---------------------|
| [comp1] | init, ready, busy, error | init -> ready, busy -> error |

### State Combinations
| State A | State B | Valid? | Notes |
|---------|---------|--------|-------|
| ready | ready | Yes | Normal |
| init | busy | No | Should not happen |

Step 3: Analyze Interactions

## Interaction Analysis

### External Dependencies
| Dependency | Failure Mode | Recovery |
|------------|--------------|----------|
| Database | Timeout | Retry with backoff |
| API | Rate limit | Queue and retry |

### Concurrent Access
| Resource | Read/Write | Lock Required? |
|----------|------------|----------------|
| [resource] | Write | Yes |

Edge Case Test Generation

Template: Input Edge Case

### Edge Case: [Name]

**Category**: Input Boundary
**Trigger**: [What causes this]
**Expected**: [Correct behavior]

**Test Case**:
```[language]
// Test empty input
test('handles empty input', () => {
  const result = functionUnderTest('');
  expect(result).toEqual([]);
});

Severity: Low/Medium/High/Critical Likelihood: Rare/Uncommon/Common


### Template: State Edge Case

```markdown
### Edge Case: [Name]

**Category**: State
**Trigger**: [What causes this state]
**Expected**: [Correct behavior]

**Test Case**:
```[language]
// Test uninitialized state
test('handles call before init', async () => {
  const component = new Component();
  // Don't call init()
  await expect(component.doWork()).rejects.toThrow('Not initialized');
});

Severity: High Likelihood: Uncommon


### Template: Timing Edge Case

```markdown
### Edge Case: [Name]

**Category**: Timing
**Trigger**: [Concurrent or timed event]
**Expected**: [Correct behavior]

**Test Case**:
```[language]
// Test concurrent access
test('handles concurrent writes', async () => {
  const promises = Array(100).fill(null).map(() =>
    component.write({ data: 'test' })
  );
  await expect(Promise.all(promises)).resolves.toBeDefined();
});

Severity: Critical Likelihood: Common under load


---

## Output Format

```markdown
# Edge Case Analysis: [Implementation Name]

## Implementation Overview
**Location**: [code path]
**Purpose**: [what it does]

---

## Edge Cases Discovered

### Critical (Must Handle)

#### 1. [Edge Case Name]
**Category**: [Input/State/Timing/Resource/Data]
**Description**: [What happens]
**Trigger**: [How to cause it]
**Impact**: [What breaks]
**Severity**: Critical

**Current Behavior**: [What code does now]
**Expected Behavior**: [What it should do]

**Test Case**:
```[language]
[Test code]

Recommendation: [How to fix]


High Priority

2. [Edge Case Name]

[Same structure]


Medium Priority

3. [Edge Case Name]

[Same structure]


Summary

Edge Case Matrix

Edge CaseCategorySeverityHandled?
[case1]InputCriticalNo
[case2]TimingHighPartial
[case3]StateMediumYes

Statistics

  • Total Edge Cases Found: [N]
  • Critical: [N]
  • High: [N]
  • Medium: [N]
  • Low: [N]

Currently Handled

[N] of [Total] edge cases are handled

Needs Attention

  1. [Critical case 1] - [brief description]
  2. [High case 1] - [brief description]

Test Cases to Add

Critical Tests

// Test suite for critical edge cases
describe('Critical Edge Cases', () => {
  test('handles empty input', () => { ... });
  test('handles concurrent access', () => { ... });
});

Recommended Test Coverage

  • All critical edge cases tested
  • High priority edge cases tested
  • Medium priority edge cases have at least one test

Recommendations

Immediate Actions

  1. [Action for critical case]

Short-term Improvements

  1. [Action for high priority cases]

Defensive Measures

  1. [General defensive coding suggestions]

---

## Serena MCP Integration

Use Serena to analyze code for edge case handling:

Find error handling patterns

mcp__serena-daemon__search_for_pattern: substring_pattern: "try.*catch|throw|Error" relative_path: "[file]"

Check null handling

mcp__serena-daemon__search_for_pattern: substring_pattern: "null|undefined|\?\." relative_path: "[file]"

Find boundary checks

mcp__serena-daemon__search_for_pattern: substring_pattern: "length.*[<>=]|>=.*0|<=.*max" relative_path: "[file]"


---

## Common Patterns to Check

### JavaScript/TypeScript

```markdown
- null/undefined access
- Array index out of bounds
- parseInt without radix
- Floating point comparison
- Async/await without try-catch
- Promise rejection handling
- Object property access on null

API/Network

- Request timeout
- Network unavailable
- Malformed response
- Rate limiting
- Authentication expiry
- Partial response

Database

- Connection pool exhaustion
- Transaction deadlock
- Unique constraint violation
- Foreign key violation
- Query timeout

Hooks 1

Sponsors

Details

Marketplace
chkim-su/serena-refactor
Author
chanhokim
Category
Community
License
MIT