Skill Editor
Comprehensive multi-agent workflow system for editing Claude Code skills with structured phases, quality gates, and expert review.
When to Use This Skill
Use this skill when:
- Creating new skills: User wants to add a new skill to the repository
- Modifying existing skills: User wants to update, enhance, or refactor a skill
- Complex skill changes: Change involves multiple files, agents, or architectural decisions
- Quality assurance needed: Change requires thorough review and validation
This skill provides:
- Structured 4-phase workflow
- Interactive requirements refinement
- Parallel expert analysis (4 simultaneous agents)
- Adversarial review before implementation
- Automated validation and testing
- Integration with sync-config.py and planning journal
When NOT to Use This Skill
Do NOT use this skill when:
- Simple documentation fixes: Typo fixes, minor documentation updates (edit directly)
- Non-skill changes: Modifying agents, settings, or other configuration
- Urgent hotfixes: Emergency fixes that can't wait for full workflow
- Exploratory work: Just browsing or understanding skills (use Read or Explore agent)
Delegation Mandate
You are an orchestrator. You coordinate specialist agents -- you do not perform specialist analysis, research, or implementation yourself.
You ARE the coordinator who ensures analysis, research, review, and implementation happen through delegation to specialist agents via Task tool.
You are NOT an analyst, researcher, reviewer, or implementor. You do not perform best-practices analysis, external research, edge-case simulation, knowledge-engineering analysis, adversarial review, or code implementation yourself.
Orchestrator-owned tasks (you DO perform these yourself):
- Session setup, directory creation, state file management
- Mode detection and user interaction for mode selection
- Quality gate evaluation (checking that agent outputs meet criteria)
- User communication (presenting options, gathering decisions)
- Workflow routing (determining which phase to execute next)
- Pre-flight validation (git checks, file existence)
- Orchestrator detection (determining if target skill is an orchestrator)
When You Might Be Resisting Delegation
| Rationalization | Reality |
|---|---|
| "This analysis is too simple to delegate" | Simple tasks still consume context window. Delegate. |
| "I can do it faster myself" | Speed is not the goal; context isolation and specialist quality are. |
| "The agent will just repeat what I already know" | The agent provides independent verification. Your knowledge may be incomplete. |
| "It's just a quick read of the file" | Reading specialist content to make specialist decisions IS specialist work. |
Self-check before every action: "Am I about to load specialist instructions into my context so I can do their work? If yes, use Task tool instead."
State Anchoring
Start every response with a phase indicator:
[Phase N/4 - {phase_name}] {brief status}
Examples:
[Phase 1/4 - Refinement] Gathering requirements from user[Phase 2/4 - Analysis] 3/4 agents completed, waiting for external-researcher[Phase 3/4 - Decision] Synthesizing 4 analysis reports[Phase 4/4 - Execution] Implementing change 3/12
Protocol:
- Before starting any phase: Read
${SESSION_DIR}/session-state.json. Confirm current_phase matches expectations. - After any user interaction: Answer the user, then re-anchor with phase indicator.
- If phase indicator and state file disagree: Trust state file, not memory.
Tool Selection
| Situation | Tool | Reason |
|---|---|---|
| Phase 2 parallel analysis (4 agents) | Task tool | Context isolation, parallel execution |
| Phase 2.5 strategic review | Task tool | Separate specialist context |
| Phase 3 synthesis | Task tool | Independent decision-making context |
| Phase 3 adversarial review | Task tool | Independent, skeptical review |
| Phase 4 implementation | Task tool | Isolated execution environment |
| Loading reference docs for YOUR routing decisions | Read tool | Orchestrator decision support |
| Loading skill instructions to decide WHICH specialist to invoke | Read tool (brief scan) | Routing information, not specialist work |
| User interaction (questions, approvals, options) | AskUserQuestion | Structured user communication |
| File operations (create, modify files) | Write tool (via executor agent) | Delegated to executor specialist |
| Validation scripts, git operations | Bash tool | Infrastructure commands |
Self-check: "Am I about to load specialist instructions into my context so I can do their work? If yes, use Task tool instead."
Workflow Overview
SIMPLE MODE (15-45 min)
├── Phase 1: Refinement (5-15 min)
├── Mode Selection: User confirms SIMPLE
├── [SKIP Phase 2: No parallel analysis]
├── [SKIP Phase 2.5: No strategic review]
├── Phase 3: Lightweight Decision (10-20 min)
│ └── Minimal synthesis from specification only
└── Phase 4: Execution (10-20 min)
└── Gates 4 & 5 always run
STANDARD MODE (1.5-3 hours) [Current default]
├── Phase 1: Refinement (10-30 min)
├── Mode Selection: User confirms STANDARD
├── Phase 2: Parallel Analysis (30-60 min, 4 agents)
├── [Phase 2.5: Strategic Review - conditional, stricter triggers]
├── Phase 3: Decision & Review (45-90 min)
│ └── Full synthesis + adversarial review
└── Phase 4: Execution (60-120 min)
└── Gates 4 & 5 always run
EXPERIMENTAL MODE (10-30 min) [User-requested]
├── Phase 1: Quick Refinement (5-10 min)
├── Mode Selection: User explicitly requests EXPERIMENTAL
├── [SKIP Phase 2]
├── [SKIP Phase 2.5]
├── Phase 3: Minimal Decision (5-10 min)
│ └── Direct implementation plan with experimental tags
└── Phase 4: Execution with rollback plan (5-15 min)
└── Gates 4 & 5 always run + experimental tagging
Workflow
Pre-Workflow: Safety Checks
Before starting workflow:
# Strict git pre-flight checks
echo "=== Git Safety Checks ==="
# Check for uncommitted changes
if [ -n "$(git status --porcelain)" ]; then
echo "✗ Git working directory is not clean"
git status --short
echo ""
echo "Please commit or stash changes before running skill-editor"
exit 1
fi
# Check for merge/rebase in progress
if [ -d .git/rebase-merge ] || [ -d .git/rebase-apply ]; then
echo "✗ Rebase in progress"
exit 1
fi
if [ -f .git/MERGE_HEAD ]; then
echo "✗ Merge in progress"
exit 1
fi
# Check for detached HEAD
if ! git symbolic-ref HEAD &>/dev/null; then
echo "⚠ WARNING: Detached HEAD state"
read -p "Continue anyway? (y/n): " CONTINUE
[ "$CONTINUE" != "y" ] && exit 1
fi
echo "✓ Git working directory is clean"
# Check sync status
./sync-config.py status
# Should show "No changes detected" or expected divergence
# Verify in correct directory
pwd
# Should be repo root: /Users/davidangelesalbores/repos/claude
# Archival Awareness Check
# After git safety checks, detect archival guidelines for awareness (not enforcement).
# skill-editor writes to claude-config/skills/, which is typically not covered by
# archival guidelines. This check provides awareness so the request-refiner agent
# can factor archival conventions into the specification if relevant.
REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || pwd)
ARCHIVE_METADATA="${REPO_ROOT}/.archive-metadata.yaml"
if [ -f "$ARCHIVE_METADATA" ]; then
echo "Archival guidelines detected (.archive-metadata.yaml present)"
echo "These will be available to the request-refiner for specification context"
# Reference: ~/.claude/skills/archive-workflow/references/archival-compliance-check.md
# Step 1 (detection) applied; Steps 2-5 not enforced for skill-editor output
ARCHIVAL_GUIDELINES_PRESENT=true
else
ARCHIVAL_GUIDELINES_PRESENT=false
fi
# Add trap for graceful interrupt handling
trap 'echo ""; echo "Session paused. Resume with: /skill-editor"; jq ".status = \"paused\"" "${SESSION_DIR}/session-state.json" > "${SESSION_DIR}/session-state.tmp.json" && mv "${SESSION_DIR}/session-state.tmp.json" "${SESSION_DIR}/session-state.json"; exit 130' INT TERM
# Session management commands
if [ "$1" = "--list-sessions" ]; then
echo "=== All Sessions ==="
ls -d /tmp/skill-editor-session/session-* 2>/dev/null | while read SESSION_PATH; do
SESSION_ID=$(basename "$SESSION_PATH")
if [ -f "${SESSION_PATH}/session-state.json" ]; then
PHASE=$(jq -r .phase "${SESSION_PATH}/session-state.json" 2>/dev/null || echo "unknown")
STATUS=$(jq -r .status "${SESSION_PATH}/session-state.json" 2>/dev/null || echo "unknown")
TIMESTAMP=$(jq -r .timestamp "${SESSION_PATH}/session-state.json" 2>/dev/null || echo "unknown")
echo " ${SESSION_ID}"
echo " Status: ${STATUS} | Phase: ${PHASE} | ${TIMESTAMP}"
fi
done
exit 0
fi
if [ "$1" = "--cleanup" ]; then
echo "Scanning for completed sessions..."
COMPLETED_SESSIONS=($(ls -d /tmp/skill-editor-session/session-* 2>/dev/null | while read SESSION_PATH; do
STATUS=$(jq -r .status "${SESSION_PATH}/session-state.json" 2>/dev/null)
if [ "$STATUS" = "completed" ]; then
echo "$SESSION_PATH"
fi
done))
if [ ${#COMPLETED_SESSIONS[@]} -eq 0 ]; then
echo "No completed sessions found"
exit 0
fi
echo "Found ${#COMPLETED_SESSIONS[@]} completed session(s):"
for SESSION_PATH in "${COMPLETED_SESSIONS[@]}"; do
SESSION_ID=$(basename "$SESSION_PATH")
TIMESTAMP=$(jq -r .completed_at "${SESSION_PATH}/session-state.json" 2>/dev/null || echo "unknown")
echo " ${SESSION_ID} - Completed: ${TIMESTAMP}"
done
read -p "Remove these completed sessions? (yes/no): " CONFIRM
if [ "$CONFIRM" = "yes" ]; then
for SESSION_PATH in "${COMPLETED_SESSIONS[@]}"; do
rm -rf "$SESSION_PATH"
done
echo "✅ ${#COMPLETED_SESSIONS[@]} completed session(s) removed"
fi
exit 0
fi
# Resume protocol with multi-session support
SESSIONS=($(ls -d /tmp/skill-editor-session/session-* 2>/dev/null | sort -r))
if [ ${#SESSIONS[@]} -gt 0 ]; then
echo "Found ${#SESSIONS[@]} existing session(s):"
echo ""
echo "Active/Paused Sessions:"
for SESSION_PATH in "${SESSIONS[@]}"; do
SESSION_ID=$(basename "$SESSION_PATH")
if [ -f "${SESSION_PATH}/session-state.json" ]; then
TIMESTAMP=$(jq -r .timestamp "${SESSION_PATH}/session-state.json")
PHASE=$(jq -r .phase "${SESSION_PATH}/session-state.json")
STATUS=$(jq -r .status "${SESSION_PATH}/session-state.json")
# Only show non-completed sessions by default
if [ "$STATUS" != "completed" ]; then
echo " ${SESSION_ID}"
echo " Status: ${STATUS} | Phase: ${PHASE} | ${TIMESTAMP}"
fi
fi
done
echo ""
echo "Options:"
echo " - Enter session ID to resume"
echo " - Enter 'list-all' to see completed sessions"
echo " - Enter 'n' to start new session"
read -p "Choice: " RESUME_CHOICE
if [ "$RESUME_CHOICE" = "list-all" ]; then
echo ""
echo "All Sessions (including completed):"
for SESSION_PATH in "${SESSIONS[@]}"; do
SESSION_ID=$(basename "$SESSION_PATH")
if [ -f "${SESSION_PATH}/session-state.json" ]; then
TIMESTAMP=$(jq -r .timestamp "${SESSION_PATH}/session-state.json")
PHASE=$(jq -r .phase "${SESSION_PATH}/session-state.json")
STATUS=$(jq -r .status "${SESSION_PATH}/session-state.json")
echo " ${SESSION_ID} - ${STATUS} - Phase ${PHASE} - ${TIMESTAMP}"
fi
done
echo ""
read -p "Resume a session? Enter session ID or 'n' for new: " RESUME_CHOICE
fi
if [ "$RESUME_CHOICE" != "n" ]; then
SESSION_ID="$RESUME_CHOICE"
SESSION_DIR="/tmp/skill-editor-session/${SESSION_ID}"
echo "Resuming ${SESSION_ID}"
else
# Create new session
SESSION_ID="session-$(date -u +%Y%m%d-%H%M%S)-$$"
SESSION_DIR="/tmp/skill-editor-session/${SESSION_ID}"
fi
else
# Check for legacy session format
LEGACY_STATE="/tmp/skill-editor-session/session-state.json"
if [ -f "$LEGACY_STATE" ]; then
echo "Detected legacy session format"
LEGACY_TIMESTAMP=$(jq -r .timestamp "$LEGACY_STATE")
LEGACY_SESSION_ID="session-legacy-$(echo $LEGACY_TIMESTAMP | tr -d ':TZ-')"
read -p "Migrate to new format as ${LEGACY_SESSION_ID}? (y/n): " MIGRATE
if [ "$MIGRATE" = "y" ]; then
mkdir -p "/tmp/skill-editor-session/${LEGACY_SESSION_ID}"
mv /tmp/skill-editor-session/*.{json,md} "/tmp/skill-editor-session/${LEGACY_SESSION_ID}/" 2>/dev/null
SESSION_ID="$LEGACY_SESSION_ID"
SESSION_DIR="/tmp/skill-editor-session/${SESSION_ID}"
echo "Migration complete. Resuming as ${SESSION_ID}"
else
# Create new session
SESSION_ID="session-$(date -u +%Y%m%d-%H%M%S)-$$"
SESSION_DIR="/tmp/skill-editor-session/${SESSION_ID}"
fi
else
# Create new session
SESSION_ID="session-$(date -u +%Y%m%d-%H%M%S)-$$"
SESSION_DIR="/tmp/skill-editor-session/${SESSION_ID}"
fi
fi
# Create session directory and initialize state if new session
mkdir -p "${SESSION_DIR}"
echo "Session directory: ${SESSION_DIR}"
echo "Session ID: ${SESSION_ID}"
if [ ! -f "${SESSION_DIR}/session-state.json" ]; then
# Initialize session state with lifecycle status
jq -n \
--arg phase "0" \
--arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
--arg session_id "$SESSION_ID" \
--arg status "in_progress" \
'{
phase: $phase,
timestamp: $timestamp,
session_id: $session_id,
status: $status,
agents_completed: []
}' > "${SESSION_DIR}/session-state.json"
echo "Starting new session"
else
echo "Resuming from Phase $(jq -r .phase ${SESSION_DIR}/session-state.json)"
fi
If checks fail: Ask user to resolve before proceeding.
If User Cancels (Ctrl+C)
Session state is preserved in ${SESSION_DIR}/session-state.json.
On next invocation:
- Offer to resume from last phase
- If declined, session remains in /tmp/skill-editor-session/{session-id}
- Re-sync if needed:
./sync-config.py push
Phase 1: Refinement (Interactive)
Objective: Transform user's request into detailed, unambiguous specification.
Agent: skill-editor-request-refiner
Model: Opus 4.5
Process:
- Launch request-refiner agent via Task tool
- Agent asks clarifying questions to understand:
- What user wants to change
- Why they want this change
- What success looks like
- What's in scope vs. out of scope
- Agent reads existing skill (if modifying)
- Agent establishes clear boundaries and success criteria
- Agent presents refined specification to user
Output File: ${SESSION_DIR}/refined-specification.md containing:
- Objective (one sentence)
- Scope (IN/OUT lists)
- Success criteria (measurable)
- Files affected
- User approval
Quality Gate 1: Specification Approval
User must approve:
- Specification matches intent
- Scope is appropriate
- Success criteria are clear
- Ready to proceed to analysis
If Gate 1 fails: Return to request-refiner for more refinement.
If Gate 1 passes: Update session state and proceed to Mode Selection.
Post-Gate 1: Orchestrator Detection
After specification approval, determine if the target skill is an orchestrator:
- Read target SKILL.md (if editing an existing skill)
- Score against detection criteria:
| Signal | Score | Check |
|---|---|---|
| Name contains orchestrator keyword (pm, coordinator, orchestrator, pipeline, architect) | +1 | Check skill name |
| Description mentions coordination terms (coordinate, orchestrate, multi-agent, pipeline) | +1 | Check description field |
| Delegates to other skills via Task tool | +2 | Search for Task tool usage |
| Has named phases/stages with sequential progression | +1 | Search for Phase/Stage headers |
| Has quality gates between phases | +1 | Search for Gate references |
| Manages session state across phases | +1 | Search for state file management |
Apply thresholds:
- Score >= 4:
"Detected as orchestrator (confidence: high). Apply orchestrator analysis? [Y/n]" - Score 2-3:
"May be an orchestrator (confidence: medium). Apply orchestrator analysis? [y/N]" - Score 0-1: Not an orchestrator. Skip orchestrator analysis.
- Always append:
"If this IS an orchestrator, reply 'orchestrator' to enable pattern analysis."
- Score >= 4:
If creating a new skill: Ask directly: "Will this skill orchestrate other skills? [y/N]"
Record detection result in session state (add to the session-state.json update):
"orchestrator_detected": true/false, "orchestrator_confidence": "high"/"medium"/"none", "orchestrator_user_confirmed": true/false
# Update session state
jq -n \
--arg phase "1.5" \
--arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
--argjson agents_completed '["request-refiner"]' \
'{phase: $phase, timestamp: $timestamp, agents_completed: $agents_completed}' \
> ${SESSION_DIR}/session-state.json
Mode Selection (After Phase 1)
Objective: Select workflow execution mode based on complexity detection and user preference.
Trigger: After Quality Gate 1 passes (specification approved)
Step 1: Run Three-Tier Detection
echo "=== Mode Selection ==="
echo ""
SPEC_FILE="${SESSION_DIR}/refined-specification.md"
# Source detection function (see references/complexity-detection-criteria.md)
# Inline detection for robustness
# Extract metrics (POSIX-compatible - no grep -oP)
FILES_CHANGED=$(grep -c "File:" "$SPEC_FILE" 2>/dev/null || echo 0)
# [FIX: Adversarial Issue #4] Use POSIX-compatible grep instead of grep -oP
LINES_CHANGED=$(grep -o 'Lines: [0-9]*' "$SPEC_FILE" 2>/dev/null | grep -o '[0-9]*' | awk '{sum+=$1} END {print sum+0}')
[ -z "$LINES_CHANGED" ] && LINES_CHANGED=0
SCOPE=$(grep -A10 "^## Scope" "$SPEC_FILE")
# Initialize
DETECTED_TIER="STANDARD"
CONFIDENCE="low"
REASON=""
# === FAIL-SAFE DEFAULT ===
if [ ! -f "$SPEC_FILE" ] || [ ! -s "$SPEC_FILE" ]; then
echo "WARNING: Mode detection encountered an error (spec file issue)."
echo "Defaulting to STANDARD mode for safety."
DETECTED_TIER="STANDARD"
CONFIDENCE="error"
REASON="Spec file unreadable, defaulting to STANDARD (safest option)"
fi
# === COMPLEX DETECTION (Phase 2.5 triggers) ===
if grep -qi "Create new skill" "$SPEC_FILE" 2>/dev/null; then
DETECTED_TIER="COMPLEX"
CONFIDENCE="high"
REASON="New skill creation"
elif [ "$FILES_CHANGED" -gt 4 ]; then
DETECTED_TIER="COMPLEX"
CONFIDENCE="high"
REASON="Multiple files affected (>4)"
elif [ "$LINES_CHANGED" -gt 300 ]; then
DETECTED_TIER="COMPLEX"
CONFIDENCE="high"
REASON="Large change (>300 lines)"
elif grep -qi "strategic review\|architectural assessment" "$SPEC_FILE" 2>/dev/null; then
DETECTED_TIER="COMPLEX"
CONFIDENCE="high"
REASON="User explicitly requested strategic review"
elif grep -qi "refactor\|reorganize\|restructure\|migrate" "$SPEC_FILE" 2>/dev/null; then
if [ "$FILES_CHANGED" -gt 2 ] || [ "$LINES_CHANGED" -gt 150 ]; then
DETECTED_TIER="COMPLEX"
CONFIDENCE="high"
REASON="Refactoring with moderate+ scope"
fi
fi
# === SIMPLE DETECTION ===
if [ "$CONFIDENCE" != "high" ]; then
if echo "$SCOPE" | grep -qi "documentation\|typo\|comment\|example"; then
if [ "$FILES_CHANGED" -le 1 ] && [ "$LINES_CHANGED" -le 50 ]; then
DETECTED_TIER="SIMPLE"
CONFIDENCE="high"
REASON="Documentation-only change"
fi
fi
if echo "$SCOPE" | grep -qi "fix bug\|fix typo\|fix error"; then
if [ "$FILES_CHANGED" -le 1 ] && [ "$LINES_CHANGED" -le 50 ]; then
DETECTED_TIER="SIMPLE"
CONFIDENCE="high"
REASON="Minor bug fix"
fi
fi
fi
# === STANDARD DETECTION (default) ===
if [ "$CONFIDENCE" != "high" ]; then
if grep -qi "agent\|workflow\|phase\|quality gate" "$SPEC_FILE" 2>/dev/null; then
if [ "$FILES_CHANGED" -le 2 ] && [ "$LINES_CHANGED" -le 100 ]; then
DETECTED_TIER="STANDARD"
CONFIDENCE="medium"
REASON="Keywords detected but change is small"
else
DETECTED_TIER="STANDARD"
CONFIDENCE="medium"
REASON="Workflow keywords with moderate change size"
fi
fi
fi
# === WARNING ZONE (soft thresholds) ===
if [ "$FILES_CHANGED" -ge 3 ] && [ "$FILES_CHANGED" -le 4 ]; then
if [ "$DETECTED_TIER" = "STANDARD" ]; then
CONFIDENCE="medium"
REASON="$REASON (near Phase 2.5 file threshold: $FILES_CHANGED files)"
fi
fi
if [ "$LINES_CHANGED" -ge 200 ] && [ "$LINES_CHANGED" -le 300 ]; then
if [ "$DETECTED_TIER" = "STANDARD" ]; then
CONFIDENCE="medium"
REASON="$REASON (near Phase 2.5 line threshold: $LINES_CHANGED lines)"
fi
fi
# === EXPERIMENTAL OVERRIDE (user keywords) ===
if grep -qi "experimental\|quick\|try\|test this\|prototype" "$SPEC_FILE" 2>/dev/null; then
DETECTED_TIER="EXPERIMENTAL"
CONFIDENCE="high"
REASON="User requested experimental/quick mode"
fi
# === DEFAULT for unclear ===
if [ "$CONFIDENCE" = "low" ]; then
if [ "$FILES_CHANGED" -ge 2 ] || [ "$LINES_CHANGED" -ge 100 ]; then
DETECTED_TIER="STANDARD"
CONFIDENCE="low"
REASON="Moderate size with unclear scope"
else
DETECTED_TIER="SIMPLE"
CONFIDENCE="medium"
REASON="Small change with unclear scope"
fi
fi
echo "Detected tier: $DETECTED_TIER (confidence: $CONFIDENCE)"
echo "Reason: $REASON"
echo ""
Step 2: Display Mode Selection Prompt
cat << EOF
================================================================================
SPECIFICATION APPROVED - SELECT WORKFLOW MODE
================================================================================
Detected complexity: $DETECTED_TIER (confidence: $CONFIDENCE)
Reason: $REASON
Select workflow mode:
[A] SIMPLE MODE ~30 min Skip analysis, direct implementation
Best for: typos, documentation, single-file fixes
Quality: Basic validation only (Gates 4, 5 always run)
Skips: Phase 2 (4 agents), Phase 2.5 (strategic review)
[B] STANDARD MODE ~2-3 hrs Full analysis and expert review
Best for: workflow changes, features, refactoring
Quality: 4-agent analysis + adversarial review
Runs: All phases (current default behavior)
[C] EXPERIMENTAL MODE ~15 min Minimal process, quick iteration
Best for: prototypes, testing ideas, will iterate
Quality: REDUCED - plan to iterate
WARNING: Creates experimental-tagged output
Skips: Phase 2, Phase 2.5, full adversarial review
Recommended: [$DETECTED_TIER]
Enter choice [A/B/C] (default based on detection, 60s timeout):
EOF
read -t 60 USER_CHOICE
# Handle timeout
if [ $? -ne 0 ]; then
echo ""
echo "No selection made. Using recommended mode: $DETECTED_TIER"
case "$DETECTED_TIER" in
SIMPLE) USER_CHOICE="A" ;;
STANDARD) USER_CHOICE="B" ;;
COMPLEX) USER_CHOICE="B" ;; # COMPLEX uses STANDARD mode
EXPERIMENTAL) USER_CHOICE="C" ;;
*) USER_CHOICE="B" ;;
esac
fi
# Normalize input
USER_CHOICE=$(echo "$USER_CHOICE" | tr '[:lower:]' '[:upper:]')
# Map selection to mode
case "$USER_CHOICE" in
A) SELECTED_MODE="SIMPLE" ;;
B) SELECTED_MODE="STANDARD" ;;
C) SELECTED_MODE="EXPERIMENTAL" ;;
*) SELECTED_MODE="STANDARD" ;; # Default
esac
Step 3: User Override Confirmation
# Check for risky overrides
USER_OVERRIDE=false
if [ "$SELECTED_MODE" != "$DETECTED_TIER" ]; then
USER_OVERRIDE=true
# Additional confirmation for risky overrides
if [ "$DETECTED_TIER" = "STANDARD" ] || [ "$DETECTED_TIER" = "COMPLEX" ]; then
if [ "$SELECTED_MODE" = "SIMPLE" ] || [ "$SELECTED_MODE" = "EXPERIMENTAL" ]; then
echo ""
echo "WARNING: You selected $SELECTED_MODE but detection recommended $DETECTED_TIER."
echo "This change may be more complex than $SELECTED_MODE mode handles."
read -p "Confirm override? (yes/no): " CONFIRM
if [ "$CONFIRM" != "yes" ]; then
SELECTED_MODE="STANDARD"
USER_OVERRIDE=false
echo "Using recommended mode: $SELECTED_MODE"
fi
fi
fi
fi
# Experimental mode warning
if [ "$SELECTED_MODE" = "EXPERIMENTAL" ]; then
echo ""
echo "=========================================="
echo " EXPERIMENTAL MODE SELECTED"
echo "=========================================="
echo ""
echo " WARNING: Reduced quality assurance"
echo " - No Phase 2 analysis agents"
echo " - Minimal decision synthesis"
echo " - Output will be tagged as experimental"
echo " - NOT production-ready without further review"
echo ""
read -p "Acknowledge and proceed? (yes/no): " ACK
if [ "$ACK" != "yes" ]; then
echo "Returning to mode selection..."
# Re-run mode selection
fi
fi
Step 4: Record Mode Selection
# Record mode selection in session state
jq -n \
--arg workflow_mode "$SELECTED_MODE" \
--arg detected_tier "$DETECTED_TIER" \
--arg confidence "$CONFIDENCE" \
--arg reason "$REASON" \
--argjson user_override "$USER_OVERRIDE" \
'{
workflow_mode: $workflow_mode,
detected_tier: $detected_tier,
confidence: $confidence,
reason: $reason,
user_override: $user_override,
timestamp: (now | strftime("%Y-%m-%dT%H:%M:%SZ"))
}' \
> ${SESSION_DIR}/mode-selection.json
# Update main session state
jq --arg mode "$SELECTED_MODE" \
'. + {workflow_mode: $mode}' \
${SESSION_DIR}/session-state.json > ${SESSION_DIR}/session-state.tmp.json && \
mv ${SESSION_DIR}/session-state.tmp.json ${SESSION_DIR}/session-state.json
echo ""
echo "[$SELECTED_MODE MODE] Mode selected. Proceeding..."
echo ""
Step 5: Mode-Based Branching
case "$SELECTED_MODE" in
SIMPLE)
echo "[$SIMPLE MODE] Skipping Phase 2 (no analysis agents)"
echo "[$SIMPLE MODE] Skipping Phase 2.5 (no strategic review)"
echo "[$SIMPLE MODE] Proceeding to Phase 3 (lightweight synthesis)"
# Skip to Phase 3 Lightweight section
;;
STANDARD)
echo "[STANDARD MODE] Running full workflow"
echo "[STANDARD MODE] Proceeding to Phase 2 (4 parallel agents)"
# Continue to Phase 2 (existing behavior)
;;
EXPERIMENTAL)
echo "[EXPERIMENTAL MODE] Minimal workflow with experimental tagging"
echo "[EXPERIMENTAL MODE] Skipping Phase 2 (no analysis agents)"
echo "[EXPERIMENTAL MODE] Skipping Phase 2.5 (no strategic review)"
echo "[EXPERIMENTAL MODE] Proceeding to Phase 3 (minimal synthesis)"
# Skip to Phase 3 Minimal section
;;
esac
Phase 2: Parallel Analysis (4 Simultaneous Agents)
Objective: Analyze proposed change from multiple expert perspectives.
Agents (all run in parallel):
skill-editor-best-practices-reviewer(Opus 4.5) - Criticalskill-editor-external-researcher(Opus 4.5) - Supplementaryskill-editor-edge-case-simulator(Opus 4.5) - Criticalskill-editor-knowledge-engineer(Opus 4.5) - Critical [NEW]
Process:
Launch all 4 agents with wave-based execution to reduce resource contention:
Wave 1 (T=0s): Launch critical analysis agents
Task 1: best-practices-reviewer
- Reviews against Anthropic guidelines
- Checks skill structure specification
- Identifies architectural concerns
Task 2: edge-case-simulator
- Simulates failure scenarios
- Identifies edge cases
- Proposes handling strategies
Wave 2 (T=30s): Launch structural analysis agent
Task 3: knowledge-engineer [NEW]
- Analyzes structural completeness via domain frameworks
- Identifies missing elements using professional standards
- Provides cross-domain pattern recommendations
Wave 3 (T=60s): Launch supplementary research agent
Task 4: external-researcher
- Searches community patterns and forums
- Finds relevant documentation and examples
- Identifies recommended approaches
Rationale for wave-based execution: Staggering launches by 30-60 seconds reduces system resource contention and improves reliability for parallel agent execution.
Important: All 4 agents run in parallel (waves overlap). Wait for all to complete before proceeding to Phase 3.
Orchestrator Analysis (conditional -- only when orchestrator_detected is true in session state):
When the target skill is an orchestrator, Phase 2 agents perform additional analysis:
best-practices-reviewer (evaluates REQUIRED patterns):
- Use Read tool to read
/Users/davidangelesalbores/repos/claude/claude-config/skills/skill-editor/references/orchestrator-checklist.md(REQUIRED section only) - Evaluate the 6 REQUIRED patterns against the target skill
- For each pattern: report PRESENT / PARTIAL / ABSENT with one-sentence evidence citation
- Do NOT sacrifice general best-practices review depth for orchestrator checklist completeness
knowledge-engineer (evaluates RECOMMENDED patterns):
- Use Read tool to read
/Users/davidangelesalbores/repos/claude/claude-config/skills/skill-editor/references/orchestrator-checklist.md(RECOMMENDED section only) - Evaluate the 4 RECOMMENDED patterns as part of structural completeness analysis
- For each pattern: report PRESENT / PARTIAL / ABSENT / N/A with evidence
- N/A is valid when architectural mismatch exists (e.g., event-driven orchestrator lacks phases)
Neither agent evaluates all 11 patterns. Division of labor prevents cognitive overload.
external-researcher and edge-case-simulator: No additional orchestrator-specific tasks.
Agent Timeouts and Retry Logic: Each agent has a 10-minute timeout. If any agent exceeds this:
For Critical Agents (best-practices-reviewer, edge-case-simulator, knowledge-engineer):
- Automatic retry (wait 30 seconds, retry once)
- If second failure: Ask user
- Proceed with placeholder report
- Abort workflow
For Supplementary Agent (external-researcher):
- No automatic retry
- Proceed without this analysis (note in synthesis)
Retry Protocol:
- First failure → Wait 30s → Retry automatically
- Second failure → User decision required
- Maximum 2 attempts per critical agent
Note: Task tool calls do not currently support explicit timeout parameters. Monitor agent progress and manually intervene if agents run longer than 10 minutes.
Output Files (must be created before proceeding to Phase 3):
${SESSION_DIR}/best-practices-review.md${SESSION_DIR}/external-research.md${SESSION_DIR}/edge-cases.md${SESSION_DIR}/knowledge-engineering-analysis.md[NEW]
Verification: Before Phase 3, verify all output files exist:
ls -lh ${SESSION_DIR}/*.md
# Should show all 4 files with content
Quality Gate 2: Analysis Completion
Check agent completion status:
- best-practices-review.md exists and is >100 words
- edge-cases.md exists and is >100 words
- knowledge-engineering-analysis.md exists and is >100 words [NEW]
- external-research.md exists and is >100 words
Gate 2 Decision Logic:
| Completed Agents | Critical Agents Status | Action |
|---|---|---|
| 4/4 | All critical complete | ✅ PASS - Proceed to Phase 3 |
| 3/4 | All critical complete (only external-researcher failed) | ✅ PASS - Proceed with note |
| 3/4 | 1 critical failed (first attempt) | 🔄 RETRY - Retry failed critical agent once |
| 3/4 | 1 critical failed (after retry) | ⚠️ ASK USER - Proceed with placeholder or abort? |
| 2/4 or fewer | Multiple critical failed | ❌ FAIL - Retry all failed critical agents or abort |
Critical Agents: best-practices-reviewer, edge-case-simulator, knowledge-engineer Supplementary: external-researcher
Retry Protocol (for critical agent failure):
- First failure → Automatic retry (wait 30s, retry once)
- Second failure → Ask user: "Proceed with placeholder report or abort?"
- User chooses proceed → Create placeholder noting timeout/failure
- User chooses abort → Stop workflow, rollback changes
Graceful Degradation (if user approves proceeding after retry):
- Create placeholder report noting timeout/failure
- Proceed to Phase 3 with 3 complete analyses
- decision-synthesizer acknowledges missing perspective in synthesis
Additional checks:
- No critical blocking issues flagged
- No conflicting recommendations (or conflicts documented for synthesis)
- Sufficient information for decision-making
If Gate 2 passes: Update session state and proceed to Phase 3.
# Update session state
jq -n \
--arg phase "3" \
--arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
--argjson agents_completed '["request-refiner", "best-practices-reviewer", "external-researcher", "edge-case-simulator", "knowledge-engineer"]' \
'{phase: $phase, timestamp: $timestamp, agents_completed: $agents_completed}' \
> ${SESSION_DIR}/session-state.json
Phase 2.5: STRATEGIC REVIEW [CONDITIONAL]
Purpose: Strategic architectural assessment for complex changes using cross-domain pattern matching to detect fundamental mismatches and major refactoring opportunities before synthesis.
When: Conditionally executed based on complexity detection. Skipped for simple changes (<100 lines, single file, documentation).
Duration: 10-30 minutes (for complex changes), ~0 seconds (for simple changes)
Agent: strategy-consultant (Opus 4.5)
Step 1: Complexity Detection
Determine whether strategic review is needed:
# Run complexity detection function
# See /Users/davidangelesalbores/repos/claude/claude-config/skills/skill-editor/references/complexity-detection-criteria.md
SPEC_FILE="${SESSION_DIR}/refined-specification.md"
COMPLEX=false
CONFIDENCE="low"
REASON=""
# Extract metrics from spec
FILES_CHANGED=$(grep -c "File:" "$SPEC_FILE" 2>/dev/null || echo 0)
LINES_CHANGED=$(grep -oP "Lines: \K[0-9]+" "$SPEC_FILE" 2>/dev/null | awk '{sum+=$1} END {print sum}')
[ -z "$LINES_CHANGED" ] && LINES_CHANGED=0
SCOPE=$(grep -A10 "^## Scope" "$SPEC_FILE")
# High-confidence complex triggers
if grep -qi "Create new skill" "$SPEC_FILE"; then
COMPLEX=true
CONFIDENCE="high"
REASON="New skill creation"
elif [ "$FILES_CHANGED" -gt 3 ]; then
COMPLEX=true
CONFIDENCE="high"
REASON="Multiple files affected (>3)"
elif [ "$LINES_CHANGED" -gt 200 ]; then
COMPLEX=true
CONFIDENCE="high"
REASON="Large change (>200 lines)"
elif grep -qi "strategic review\|architectural assessment" "$SPEC_FILE"; then
COMPLEX=true
CONFIDENCE="high"
REASON="User explicitly requested strategic review"
fi
# High-confidence simple (override complex if both match)
if [ "$CONFIDENCE" != "high" ]; then
if echo "$SCOPE" | grep -qi "documentation\|typo\|comment\|example"; then
if [ "$FILES_CHANGED" -le 1 ] && [ "$LINES_CHANGED" -le 50 ]; then
COMPLEX=false
CONFIDENCE="high"
REASON="Documentation-only change"
fi
fi
if echo "$SCOPE" | grep -qi "fix bug\|fix typo\|fix error"; then
if [ "$FILES_CHANGED" -le 1 ] && [ "$LINES_CHANGED" -le 50 ]; then
COMPLEX=false
CONFIDENCE="high"
REASON="Minor bug fix"
fi
fi
fi
# Medium-confidence detection
if [ "$CONFIDENCE" != "high" ]; then
if grep -qi "agent\|workflow\|phase\|quality gate\|multi-agent" "$SPEC_FILE"; then
if [ "$FILES_CHANGED" -le 2 ] && [ "$LINES_CHANGED" -le 100 ]; then
COMPLEX=false
CONFIDENCE="medium"
REASON="Keywords detected but change is small (user confirmation recommended)"
else
COMPLEX=true
CONFIDENCE="medium"
REASON="Workflow/agent keywords with moderate change size"
fi
fi
fi
# Default for unclear cases
if [ "$CONFIDENCE" = "low" ]; then
if [ "$FILES_CHANGED" -ge 2 ] || [ "$LINES_CHANGED" -ge 100 ]; then
COMPLEX=true
CONFIDENCE="low"
REASON="Moderate size with unclear scope (user confirmation recommended)"
else
COMPLEX=false
CONFIDENCE="medium"
REASON="Small change with unclear scope"
fi
fi
echo "=== Phase 2.5: Complexity Detection ==="
echo "Result: $COMPLEX (confidence: $CONFIDENCE)"
echo "Reason: $REASON"
echo ""
# High-confidence decisions
PROCEED_TO_STRATEGY_CONSULTANT=false
if [ "$CONFIDENCE" = "high" ]; then
if [ "$COMPLEX" = "true" ]; then
echo "→ Complex change detected: Launching strategy consultant"
PROCEED_TO_STRATEGY_CONSULTANT=true
else
echo "→ Simple change detected: Skipping Phase 2.5"
echo " Proceeding directly to Phase 3 (decision synthesis)"
PROCEED_TO_STRATEGY_CONSULTANT=false
fi
else
# Medium/low confidence: User confirmation
echo "Confidence is $CONFIDENCE. User confirmation recommended."
echo ""
read -p "Do you want strategic architectural review (Phase 2.5)?
(Y) Yes - run strategic assessment (adds 10-30 min)
(N) No - skip Phase 2.5 (proceed to synthesis)
Choice [Y/n]: " USER_CHOICE
if [ "$USER_CHOICE" = "n" ] || [ "$USER_CHOICE" = "N" ]; then
PROCEED_TO_STRATEGY_CONSULTANT=false
echo "→ Skipping Phase 2.5 (user override)"
else
PROCEED_TO_STRATEGY_CONSULTANT=true
echo "→ Running Phase 2.5 (user confirmed)"
fi
fi
# Record decision
jq -n \
--argjson complex "$COMPLEX" \
--arg confidence "$CONFIDENCE" \
--arg reason "$REASON" \
--argjson proceed "$PROCEED_TO_STRATEGY_CONSULTANT" \
'{
complexity_detected: $complex,
confidence: $confidence,
reason: $reason,
proceed_to_phase_2_5: $proceed,
timestamp: (now | strftime("%Y-%m-%dT%H:%M:%SZ"))
}' \
> ${SESSION_DIR}/complexity-detection.json
# Branch logic
if [ "$PROCEED_TO_STRATEGY_CONSULTANT" = "false" ]; then
echo ""
echo "✓ Phase 2.5 skipped (simple change)"
echo "→ Proceeding to Phase 3: Decision Synthesis"
# Continue to Phase 3
fi
# If PROCEED_TO_STRATEGY_CONSULTANT is true, continue to Step 2
Step 2: Launch Strategy Consultant
If complexity detection triggered Phase 2.5:
if [ "$PROCEED_TO_STRATEGY_CONSULTANT" = "true" ]; then
echo "=== Phase 2.5: Strategic Architectural Assessment ==="
echo ""
echo "Launching strategy-consultant agent (Opus 4.5)..."
echo "Expected duration: 10-30 minutes"
echo ""
echo "This agent will:"
echo " - Read all Phase 2 analysis reports"
echo " - Perform cross-domain pattern matching"
echo " - Assess architectural fit"
echo " - Classify recommendations (minor/major)"
echo " - Detect major refactoring opportunities"
echo ""
# Launch agent with 30-minute timeout
TIMEOUT_SECONDS=1800
START_TIME=$(date +%s)
timeout ${TIMEOUT_SECONDS} claude-agent skill-editor-strategy-consultant
EXIT_CODE=$?
END_TIME=$(date +%s)
ELAPSED=$((END_TIME - START_TIME))
echo ""
echo "Strategy consultant completed in ${ELAPSED} seconds"
# Handle timeout
if [ $EXIT_CODE -eq 124 ]; then
echo "⚠ WARNING: Strategy consultant timed out after 30 minutes"
# Check for partial report
if [ -f "${SESSION_DIR}/strategic-review.md" ]; then
WORD_COUNT=$(wc -w < ${SESSION_DIR}/strategic-review.md)
if [ $WORD_COUNT -gt 50 ]; then
echo "Partial report found (${WORD_COUNT} words)"
echo "" >> ${SESSION_DIR}/strategic-review.md
echo "## INCOMPLETE REPORT" >> ${SESSION_DIR}/strategic-review.md
echo "Note: Strategic review timed out. This is a partial analysis." >> ${SESSION_DIR}/strategic-review.md
else
rm ${SESSION_DIR}/strategic-review.md
fi
fi
# User decision on timeout
read -p "Strategy consultant timed out. Options:
(A) Proceed without strategic review
(B) Retry with extended timeout (60 minutes)
(C) Abort workflow
Choice: " TIMEOUT_CHOICE
case $TIMEOUT_CHOICE in
A)
echo "Proceeding without strategic review"
rm -f ${SESSION_DIR}/strategic-review.md
;;
B)
echo "Retrying with 60-minute timeout..."
timeout 3600 claude-agent skill-editor-strategy-consultant
;;
C)
echo "Aborting workflow"
exit 1
;;
esac
elif [ $EXIT_CODE -ne 0 ]; then
echo "✗ ERROR: Strategy consultant failed with exit code $EXIT_CODE"
read -p "Proceed without strategic re
…(truncated)