---
name: ppa-continuous-optimization
description: >
  Monitors PPA performance in real time and triggers automatic adjustments based
  on early-warning alerts. Trigger when asked to: monitor PPA post-launch, detect
  market share drops, identify competitive response, update price-pack architecture
  by zone/channel/segment, run continuous optimization cycles, or redesign PPA
  based on new data. Also trigger for: "monitoreo PPA", "optimización continua",
  "alerta temprana", "ajuste automático de precio", "semáforo de SKUs",
  "rediseño de arquitectura", "KPI por canal", "PPA por zona", "CUSUM PPA",
  "rendimiento en tiempo real". TomTom MCP always activates — maps zone-level
  KPI performance, competitive pressure by location, and priority action zones.
  Always renders complete inline HTML dashboard with traffic-light SKU scorecards,
  zone map, alert log, and auto-pricing recommendations.
---

# ppa-continuous-optimization

Closes the PPA loop: monitors KPIs by SKU × channel × zone × segment, fires CUSUM
early-warning alerts, applies auto-pricing business rules, and triggers ppa-design-optimizer
for full redesign when structural shifts are detected. TomTom MCP is core — every
alert is geo-located and prioritized by zone.

---

## The Continuous Optimization Loop

```
DESIGN (ppa-design-optimizer)
        ↓ launch
MONITOR (channel_kpis.py + early_warning_system.py)
    ├── Minor deviation → auto_pricing_rules.py → tactical adjustment
    ├── Major deviation → trigger ppa-design-optimizer → architecture update
    └── Geographic deviation → TomTom zone map → zone-specific intervention
        ↓ 4-week cycle
REPORT (optimization_dashboard.py + alert_logger.py)
        ↓
REDESIGN (when structural shift detected: new competitor, channel reset, inflation)
```

**Key insight:**
PPA is not a one-time exercise. It decays within 8–16 weeks as competitors respond,
inflation erodes price tiers, and shopper behavior shifts. The continuous loop converts
PPA from a project into an operating system.

---

## Core Equations

### KPI tracking
```python
# Market share by volume:
share_vol_i = vol_i / Σ_j vol_j  (across competitive set)

# Relative price index:
RPI_i = price_i / weighted_avg_competitor_price

# Velocity (sell-out per point of distribution):
velocity_i = vol_i / distribution_numeric_i

# SKU profitability index:
profit_idx_i = (price_i - cost_i) × velocity_i / category_avg_profitability
```

### CUSUM early warning
```python
# Standard CUSUM on weekly KPI residuals:
S_t = max(0, S_{t-1} + (x_t - μ₀ - k))
Alert when: S_t > h  (h = 4σ decision interval)

# Shewhart control chart (faster for large shifts):
Alert when: |x_t - μ₀| > 3σ  (3-sigma rule)

# Combined: CUSUM for gradual drift, Shewhart for sudden shocks
```

### Auto-pricing rules engine
```python
# Rule structure:
IF  KPI_delta(metric, sku, channel, zone) < threshold
AND consecutive_periods >= n_periods
AND NOT already_adjusted_in_last(cooldown_weeks)
THEN  apply_action(action_type, magnitude, sku, channel, zone)

# Actions available:
# "price_down_pct": reduce shelf price by X%
# "promo_activate": trigger trade promotion
# "channel_delist": flag for channel removal
# "escalate_redesign": trigger ppa-design-optimizer
```

### Zone priority scoring (TomTom-enhanced)
```python
# Zone priority for intervention:
zone_priority = (alert_severity × channel_density) / distance_to_support

# TomTom inputs:
# - n_POIs by channel type per zone (tomtom-fuzzy-search)
# - Zone-level sell-out from client data
# - Competitor POI density (proxy for competitive pressure)
```

---

## Workflow

### Step 1 — Data input
```bash
# data-intake-normalizer: date, sku, channel, zone, volume, price,
#                         market_share, distribution_numeric
# From MCP: Supermetrics (digital), Adspirer (media), client ERP (sell-out)
```

### Step 2 — KPI computation
```bash
python scripts/channel_kpis.py \
    --data /mnt/user-data/uploads/ppa_performance.xlsx \
    --competitive-set /mnt/user-data/uploads/competitors.xlsx \
    --output results/kpis.json
```

### Step 3 — Early warning system
```bash
python scripts/early_warning_system.py \
    --kpis results/kpis.json \
    --thresholds '{"market_share":-0.10,"velocity":-0.15,"rpi":0.12}' \
    --n-periods 2 \
    --output results/alerts.json
```

### Step 4 — Auto-pricing rules
```bash
python scripts/auto_pricing_rules.py \
    --alerts results/alerts.json \
    --rules /mnt/user-data/uploads/pricing_rules.json \
    --output results/actions.json
```

### Step 5 — TomTom geo-intelligence (ALWAYS)
```
→ tomtom-fuzzy-search: supermarkets + convenience stores per zone
→ Cross: sell-out velocity per zone × POI density per zone
→ Compute zone_priority score
→ tomtom-dynamic-map: choropleth of alert severity by zone
  + markers for top-priority intervention points
→ If zone shows structural shift (competitive entry) → flag for redesign
```

### Step 6 — Dashboard + alert log
```bash
python scripts/optimization_dashboard.py \
    --kpis results/kpis.json \
    --alerts results/alerts.json \
    --actions results/actions.json \
    --output dashboard_data.json

python scripts/alert_logger.py \
    --alerts results/alerts.json \
    --actions results/actions.json \
    --output results/alert_log.json
```

### Step 7 — Redesign trigger (if structural shift)
```
IF structural_shift_detected:
  → sendPrompt("RUN ppa-design-optimizer with updated competitive landscape")
  → Full architecture redesign cycle
```

**Output sequence:**
```
1. [bash_tool] channel_kpis.py → early_warning_system.py → auto_pricing_rules.py
2. [TomTom MCP] ALWAYS — zone KPI map + POI density + priority zones
3. [web_search] "competitive price changes [category] [market] last 4 weeks"
4. [show_widget] Complete inline dashboard — traffic-light scorecards + zone map
5. [text] NBA by zone/channel/SKU/segment
6. [text] Escalation recommendation if structural shift
```

---

## Dashboard Panels (all visible inline)

1. **KPI bar** — overall portfolio health score, active alerts count, zones in red,
   avg RPI drift, SKUs below velocity threshold, auto-actions taken
2. **Traffic-light SKU scorecard** — red/yellow/green per SKU × channel
3. **Alert timeline** — waterfall of alerts this cycle with severity + auto-action
4. **Zone performance map** — TomTom choropleth: green/yellow/red zones by KPI
   + POI markers for priority intervention locations
5. **Auto-pricing action log** — rules triggered, magnitude, expected impact
6. **Trend panel** — 12-week rolling KPIs by SKU (market share + velocity + RPI)
7. **Redesign trigger meter** — distance from structural-shift threshold

---

## Optimization Cycle Cadence

| Frequency | Activity | Trigger |
|---|---|---|
| **Weekly** | KPI pull + CUSUM check + zone map refresh | Automated (batch/MCP) |
| **Bi-weekly** | Auto-pricing rules execution | Alert level ≥ MEDIUM |
| **Monthly** | Full PPA performance review | Standing calendar |
| **Quarterly** | Architecture redesign assessment | Structural shift or QBR |
| **Ad-hoc** | Emergency redesign | Alert level = CRITICAL |

---

## Marketer Insights Layer (MANDATORY)

### Search before benchmarking
```
web_search: "PPA continuous optimization FMCG real-time pricing [year]"
web_search: "price monitoring competitive intelligence [category] [market] [year]"
web_search: "dynamic pricing consumer goods LATAM [year]"
```

### Translate to business language

| Technical | Business meaning |
|---|---|
| CUSUM alert S_t=6.2 (h=4) | "Market share has been drifting down for 3 weeks — not random noise" |
| zone_priority = 0.91 | "Zone Cuauhtémoc needs immediate intervention — high traffic, red KPIs" |
| RPI drift = +0.14 | "We are now 14% more expensive than competitors — above the 10% threshold" |
| velocity_delta = -18% | "This SKU sells 18% fewer units per store per week vs 4 weeks ago" |
| structural_shift = TRUE | "The pattern cannot be fixed with a price tweak — full redesign needed" |

### NBA
- **Zone-first prioritization:** "Focus on Zone [X] first — highest POI density + worst KPIs = maximum impact"
- **Tactical adjustment:** "Auto-rule fired: reduce [SKU] price 3% in TT for 4 weeks — expected +[N]% velocity"
- **Competitive alert:** "RPI crossed 10% threshold — competitor may have launched promo. Activate cross-check"
- **Velocity floor:** "[SKU] below minimum velocity threshold for [N] weeks → flag for channel delist or promo activation"
- **Redesign signal:** "4 of 6 KPIs in RED for 3+ consecutive periods — trigger ppa-design-optimizer full cycle"
- **Geographic insight:** "Zone TT-dense (Tepito, Neza) shows -22% velocity — entry SKU price may need zone-specific adjustment"

---

## Redesign Trigger Conditions

Escalate from tactical adjustment to full `ppa-design-optimizer` redesign when:

```python
TRIGGER redesign IF ANY:
  - market_share_drop > 15% sustained 4+ weeks
  - new_competitor_entry detected in TomTom POI data
  - category_inflation > 8% cumulative (thresholds have shifted)
  - channel_restructuring (major retailer policy change)
  - n_red_alerts >= 4 simultaneously
  - structural_break detected in CUSUM (F-stat > critical value)
```

---

## Integration with OS

| Skill | Direction | Purpose |
|---|---|---|
| `ppa-design-optimizer` | → calls when redesign triggered | Full architecture update |
| `price-threshold-detection` | pulls thresholds | Validates if RPI crossed danger zone |
| `price-elasticity-modeling` | pulls elasticity | Updates auto-pricing magnitude |
| `ppa-financial-model` | cross-checks P&L | Validates auto-action won't destroy margin |
| `trade-promotion-roi` | activation layer | Converts alert into promo plan |
| `weekly-control-tower` | receives alerts | Feeds OS-wide monitoring cycle |
| `executive-growth-memo` | receives summary | C-level escalation when critical |
| `measurement-incrementality` | validates auto-actions | Did the auto-pricing actually work? |

---

## References

- `references/cusum_ppa_calibration.md` — CUSUM parameters for PPA KPIs
- `references/auto_pricing_rule_library.md` — Predefined business rules
- `references/zone_scoring_model.md` — TomTom POI density → zone priority
- `references/redesign_trigger_framework.md` — When to escalate vs adjust
