---
name: gsd-rlm-optimize
description: Run RLM optimization (DSPy MIPROv2, R-Zero self-refinement)
argument-hint: "[--force] [--traces N]"
allowed-tools:
  - read
  - bash
  - question
---

<objective>
Run RLM optimization to improve agent performance.

**Optimization Methods:**
- DSPy MIPROv2: Prompt optimization using execution traces
- R-Zero: Self-refinement through challenger-solver loops

**Triggers:**
- Threshold: 50 execution traces collected
- Interval: 1 hour since last optimization
- Force: Use --force to bypass thresholds

**Usage:**
- `/gsd-rlm-optimize` — Run if thresholds met
- `/gsd-rlm-optimize --force` — Force optimization
- `/gsd-rlm-optimize --traces 100` — Custom trace threshold
</objective>

<context>
**Flags:**
- `--force` — Bypass threshold checks
- `--traces N` — Minimum traces required (default: 50)
</context>

<process>

## 1. Check Trace Count

```bash
TRACE_DB=~/.gsd-rlm/traces.db
if [ -f "$TRACE_DB" ]; then
  COUNT=$(sqlite3 "$TRACE_DB" "SELECT COUNT(*) FROM execution_traces WHERE success=1;" 2>/dev/null || echo "0")
  echo "Successful traces: $COUNT"
else
  echo "No traces database found"
  COUNT=0
fi
```

## 2. Check Last Optimization

```bash
OPT_FILE=~/.gsd-rlm/optimization_history.json
if [ -f "$OPT_FILE" ]; then
  LAST=$(python -c "import json; d=json.load(open('$OPT_FILE')); print(d.get('last_run', 'never'))" 2>/dev/null || echo "never")
  echo "Last optimization: $LAST"
else
  echo "No optimization history"
fi
```

## 3. Decision Point

If traces < threshold AND not --force:
- Show current stats
- Suggest running more executions
- Exit

If traces >= threshold OR --force:
- Proceed to optimization

## 4. Run Optimization

Ask user to confirm optimization run.

If confirmed:
```bash
python -c "
from gsd_rlm.optimization.scheduler import OptimizationScheduler
scheduler = OptimizationScheduler()
result = scheduler.force_run()
print(f'Optimization result: {result}')
"
```

## 5. Display Results

Show improvement metrics:
- Tasks success rate before/after
- Average latency before/after
- Composite score change

</process>

<success_criteria>
- [ ] Trace count checked
- [ ] Last optimization checked
- [ ] User confirmation obtained
- [ ] Optimization executed
- [ ] Results displayed
</success_criteria>
