optimize
Run 15 parallel quality gates (core checks, E2E/visual, pre-CI validation, plus contracts/load/integrity for epics) with auto-retry for transient failures
mkdir -p ~/.claude/commands && curl -fsSL https://raw.githubusercontent.com/marcusgoll/Spec-Flow/HEAD/.claude/commands/phases/optimize.md -o ~/.claude/commands/optimize.mdoptimize.md
# /optimize — Quality Gates Runner (Thin Wrapper)
> **v11.0 Architecture**: This command spawns the isolated `optimize-phase-agent` via Task(). All quality gate logic runs in isolated context.
<context>
**User Input**: $ARGUMENTS
**Active Feature**: !`ls -td specs/[0-9]*-* 2>/dev/null | head -1 || echo "none"`
**Interaction State**: !`cat specs/*/interaction-state.yaml 2>/dev/null | head -10 || echo "none"`
</context>
<objective>
Spawn isolated optimize-phase-agent to run production-readiness quality gates.
**Architecture (v11.0 - Phase Isolation):**
```
/optimize → Task(optimize-phase-agent) → optimization-report.md
```
**Agent responsibilities:**
- Run 15 parallel quality checks
- Auto-retry transient failures (2-3 times)
- Generate optimization-report.md
- Return blocking issues or completion status
**Quality Gates** (15 checks, expandable to 18 for epics):
1-7: Core (performance, security, a11y, code review, migrations, docker, E2E)
8-15: Pre-CI (licenses, env vars, circular deps, dead code, dockerfile, deps, bundle, health)
16-18: Epic-only (contracts, load testing, migration integrity)
**Auto-Retry Logic**:
- Transient failures auto-retry with progressive delays
- Critical failures (security, breaking changes) block immediately
**Prerequisites**: `/implement` phase complete
**Workflow position**: `spec → clarify → plan → tasks → implement → optimize → ship`
</objective>
## Legacy Context (for agent reference)
<legacy_context>
Workflow Detection: Auto-detected via workspace files, branch pattern, or state.yaml
Current phase: Auto-detected from ${BASE_DIR}/\*/state.yaml
Implementation status: Auto-detected from ${BASE_DIR}/\*/state.yaml
Quality targets: Auto-detected from ${BASE_DIR}/\*/plan.md
</legacy_context>
<process>
### Step 0: WORKFLOW DETECTION
**Detect workflow using centralized skill** (see `.claude/skills/workflow-detection/SKILL.md`):
1. Run detection: `bash .spec-flow/scripts/utils/detect-workflow-paths.sh`
2. Parse JSON: Extract `type`, `base_dir`, `slug` from output
3. If detection fails: Use default (feature workflow with 6 gates)
4. Set gate count:
- Feature: 6 core gates
- Epic: 10 gates (core + enhanced)
5. Set `WORKFLOW_STATE="${BASE_DIR}/${SLUG}/state.yaml"`
---
### Step 0.1: LOAD USER PREFERENCES
**Load user preferences that affect quality gate behavior:**
```bash
# Load preference utility functions
source .spec-flow/scripts/utils/load-preferences.sh 2>/dev/null || true
# Load E2E visual testing preferences
E2E_ENABLED=$(get_preference_value --key "e2e_visual.enabled" --default "true")
E2E_FAILURE_MODE=$(get_preference_value --key "e2e_visual.failure_mode" --default "blocking")
E2E_THRESHOLD=$(get_preference_value --key "e2e_visual.threshold" --default "0.1")
E2E_AUTO_COMMIT=$(get_preference_value --key "e2e_visual.auto_commit_baselines" --default "true")
# Load automation preferences
AUTO_APPROVE_MINOR=$(get_preference_value --key "automation.auto_approve_minor_changes" --default "false")
CI_MODE=$(get_preference_value --key "automation.ci_mode_default" --default "false")
echo "User Preferences Loaded:"
echo " E2E Testing: $( [ "$E2E_ENABLED" = "true" ] && echo "enabled" || echo "disabled" )"
echo " E2E Failure Mode: $E2E_FAILURE_MODE"
echo " Visual Threshold: ${E2E_THRESHOLD}%"
echo " Auto-approve Minor: $AUTO_APPROVE_MINOR"
echo " CI Mode: $CI_MODE"
```
**Preferences affecting quality gates:**
| Preference | Gate | Effect |
|------------|------|--------|
| `e2e_visual.enabled` | Gate 7 (E2E + Visual) | Skip gate if false |
| `e2e_visual.failure_mode` | Gate 7 | blocking=hard fail, warning=continue |
| `e2e_visual.threshold` | Gate 7 (Visual) | Pixel diff allowed (0.1=10%) |
| `automation.auto_approve_minor` | Code Review | Auto-approve formatting-only changes |
| `automation.ci_mode_default` | All gates | Non-interactive, assumes defaults |
---
### Step 0.5: ITERATION DETECTION (v3.0 - Feedback Loop Support)
**NEW**: Check if workflow is in iteration mode and adjust quality gate focus.
```bash
# Read workflow state to check iteration
if [ -f "$WORKFLOW_STATE" ]; then
CURRENT_ITERATION=$(yq eval '.iteration.current' "$WORKFLOW_STATE" 2>/dev/null || echo "1")
TOTAL_ITERATIONS=$(yq eval '.iteration.total_iterations' "$WORKFLOW_STATE" 2>/dev/null || echo "0")
if [ "$CURRENT_ITERATION" -gt 1 ]; then
echo "🔄 Iteration Mode Detected"
echo " Current iteration: $CURRENT_ITERATION"
echo " Previous iterations: $TOTAL_ITERATIONS"
echo " Quality gates will focus on:"
echo " - New code from iteration $CURRENT_ITERATION"
echo " - Regression checks for iteration 1-$((CURRENT_ITERATION - 1))"
# Set iteration flag for focused testing
ITERATION_MODE=true
ITERATION_NUMBER=$CURRENT_ITERATION
# Get list of files changed in current iteration
# (Compare current HEAD with commit from iteration start)
ITERATION_START_COMMIT=$(yq eval ".iteration.history[-1].completed_at" "$WORKFLOW_STATE" 2>/dev/null)
if [ -n "$ITERATION_START_COMMIT" ]; then
# Find commit closest to iteration start time
BASELINE_COMMIT=$(git log --until="$ITERATION_START_COMMIT" --format="%H" -1)
CHANGED_FILES=$(git diff --name-only "$BASELINE_COMMIT" HEAD)
echo ""
echo "Changed files in iteration $CURRENT_ITERATION:"
echo "$CHANGED_FILES" | sed 's/^/ /'
fi
else
echo " Iteration: 1 (initial implementation)"
ITERATION_MODE=false
ITERATION_NUMBER=1
fi
else
# No workflow state file - default to iteration 1
ITERATION_MODE=false
ITERATION_NUMBER=1
fi
```
**Iteration-specific quality gates:**
When `ITERATION_MODE=true`, quality gates adjust their focus:
1. **Performance**:
- Run benchmarks on **new code only** (iteration N functions/endpoints)
- Check for performance **regressions** in iteration 1 code
- CompareExecute multiple sprints in parallel based on dependency graph from sprint-plan.md
Build and validate locally for projects without remote deployment (prototypes, experiments, local-only dev)
Execute multi-sprint epic workflow from interactive scoping through deployment with parallel sprint execution and self-improvement
Execute feature development workflow from specification through production deployment with automated quality gates
Analyze workflow state and provide context-aware guidance with visual progress indicators and recommended next steps
Initialize project documentation, preferences, or design tokens
Implement small bug fixes and features (<100 LOC) without full workflow. Use for single-file changes, bug fixes, refactors, and minor enhancements that can be completed in under 30 minutes.
Enter deep craftsman mode - question everything, plan like Da Vinci, craft insanely great solutions, then materialize to roadmap