---
name: "dev-validate-e2e"
description: "Validation E2E parallela con Agent Team: test API e browser eseguiti simultaneamente in worktree separati. Più veloce di /dev-validate sequenziale (-60% wall-clock), copertura AC migliore. Usa quando l'utente dice 'validate e2e', 'test paralleli', 'verifica completa', 'validazione end-to-end', 'test concurrent', oppure dopo /dev-implement per validare una story con AC misti API+UI. Richiede CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 (con fallback sequenziale --no-team)."
---

# /dev-validate-e2e — Validation E2E Parallel (v0.12.0+)

Skill orchestrazione per validation end-to-end **parallela** con Agent Teams. Spawna 3 agenti specialisti:
- **Riccardo** (`test-orchestrate-lead`) — coordina + classifica AC
- **Cinzia** (`e2e-api-tester`) — test API con Supertest/httpx
- **Massimo** (`e2e-browser-tester`) — test UI con Playwright + screenshots
- **Bruno** (`test-aggregator`) — consolida report → `specs/08-validation.md`

**Performance**: ~90-120s wall-clock per 5 AC (vs 4-5min sequenziale). **Token**: ~70k per story.

**Backward compat**: `/dev-validate` legacy continua a funzionare invariato. `/dev-validate-e2e` è opt-in.

---

## Quando viene invocata

### Trigger espliciti dall'utente

- "Validate e2e di US-007"
- "Test paralleli su questa story"
- "Verifica completa parallela"
- "Genera 08-validation.md con coverage"

### Trigger automatici (futuri)

- Da `/dev-orchestrate` quando `_status.md` mostra "Phase 8 not-started" e env var Agent Teams attiva
- Da `/dev-implement` post-implementazione (configurabile in `.mucc/config.json`)

---

## Modalità

| Flag | Comportamento |
|------|---------------|
| _(default)_ | Parallel mode con Agent Teams (se disponibili) |
| `--story US-XXX` | Specifica story target (altrimenti usa ultima `done-pending-validation`) |
| `--no-team` | Forza modalità sequenziale (un agente alla volta, ~4-5min) |
| `--api-only` | Salta browser tests (utile se UI non automatizzabile) |
| `--browser-only` | Salta API tests (utile se backend è una black-box) |
| `--auto` | No domande interattive, usa default |
| `--dry-run` | Mostra cosa verrebbe fatto, no spawn agenti |
| `--keep-worktrees` | Non rimuove worktree dopo aggregator (debug) |
| `--asr` | (NEW v0.25.1) Forza Bruno (test-aggregator) a calcolare Workflow Fidelity / ASR anche per story senza tag obbligatori |
| `--no-asr` | (NEW v0.25.1) Disabilita ASR anche per story con tag `#payment` / `#auth` / `#consent` / `#gdpr` / `#kyc` (override esplicito) |

### Trigger automatico ASR (NEW v0.25.1)

Bruno (`test-aggregator`) attiva automaticamente lo **Sequence Fidelity Check (ASR)** se la story corrente ha almeno uno dei tag nel frontmatter di `specs/03-user-stories.md`:
- `#payment` — pagamenti, bonifici, checkout
- `#auth` — login, sessioni, token refresh
- `#consent` — GDPR consent management, opt-in/opt-out
- `#gdpr` — esportazione dati, cancellazione, audit log
- `#kyc` — verifica identità, double-opt-in

Razionale: il paper AI-Radar id 607 documenta che **10 LLM su 18 saltano checkpoint procedurali** invisibili a metriche outcome standard. Per dominio regolamentato (banking/insurance), ASR è il segnale necessario per audit-readiness PCI-DSS / DORA. Per altre story il check resta opt-in via `--asr` (zero overhead default).

### Classificazione AC — terza categoria "transactional" (NEW v0.26.0)

Storicamente Riccardo (`test-orchestrate-lead`) classifica ogni AC come:
- **API** → assegnata a Cinzia (`e2e-api-tester`)
- **UI** → assegnata a Massimo (`e2e-browser-tester`)

Da v0.26.0 una terza categoria è disponibile:

- **Transactional** → l'AC tocca una transazione multi-step con audit obbligatorio (es. pagamento, KYC, consent withdrawal, claim handling assicurativo). Cinzia + Massimo collaborano: **entrambi** loggano ogni call con `timestamp` + `ordine` come bigram per ASR check.

**Trigger automatico** per `transactional`:
- L'AC contiene parole chiave: "paga", "addebita", "consenso", "firma", "conferma identità", "transfer", "settle"
- OPPURE la story ha tag `#payment` / `#kyc` / `#consent` / `#gdpr` nel frontmatter
- OPPURE l'AC è esplicitamente marcato `@transactional` in `.feature` Gherkin

**Workflow transactional**:

1. Cinzia esegue chiamate API tracciando ordine + timestamp + correlation_id (header `X-Correlation-Id`)
2. Massimo esegue UI flow tracciando click + screenshot + timestamp + DOM state snapshot
3. Bruno aggrega in **bigram sequence** condivisa (API + UI interleaved per correlation_id)
4. ASR check (Step 3.5 di Bruno) valida la sequenza completa

**Esempio AC transactional**:

```gherkin
@transactional @payment
Scenario: Conferma pagamento con double-opt-in
  DATO utente loggato con MFA attivo
  QUANDO inizio pagamento > inserisce importo > clicca "Conferma" > riceve SMS > inserisce OTP
  ALLORA pagamento approvato + audit_log scritto + email confermata
```

Bruno verifica i bigram: `[start_payment → enter_amount] → [enter_amount → confirm] → [confirm → otp_request] → [otp_request → otp_validate] → [otp_validate → approve] → [approve → audit_log] → [audit_log → email]`. Mancando 1 bigram (es. audit_log) → 🔴 FAIL fidelity.

**Backward compat**: se la story non triggera `transactional`, il routing API/UI resta invariato.

---

## Prerequisiti

### Hard requirements (skill stops se mancano)

1. `specs/03-user-stories.md` esiste e contiene story target
2. `specs/04-tech-spec.md` ha sezione Service Matrix + Test Strategy
3. `specs/07-implementation.md` mostra story con status `in-progress` o `done-pending-validation`
4. Codice della story implementato (non vuoto)

### Soft requirements (skill warns ma procede)

1. `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` env var attiva (altrimenti suggerisce `--no-team`)
2. `git` repo (per worktree isolation; fallback in-place se assente)
3. App running per E2E browser (altrimenti skill chiede di avviare o usa MANUAL_PENDING)
4. Playwright MCP installato (altrimenti browser tester scrive solo manual instructions)

---

## Workflow

### Step 1 — Pre-flight check

```bash
# Verifica file required
test -f specs/03-user-stories.md || error "Missing user stories"
test -f specs/04-tech-spec.md || error "Missing tech spec"
test -f specs/07-implementation.md || error "Missing implementation status"

# Verifica env var
[ "$CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS" = "1" ] || warn "Agent Teams off — uso --no-team"

# Verifica git
git status &>/dev/null || warn "Not a git repo — no worktree isolation"
```

### Step 2 — Identifica story target

Se `--story US-XXX` specificato → usa quella.
Altrimenti:
- Leggi `specs/_status.md`
- Cerca prima story con status `done-pending-validation` o `in-progress` con AC senza test
- Se nessuna trovata → mostra elenco e chiedi

### Step 3 — Pre-context (opzionale, NEW v0.12.0+)

Se `~/.claude/skills/dev-codesearch/` esiste:
- Esegui `/dev-codesearch --query "<story-description>" --json --limit 5`
- Passa risultati come pre-context a `test-orchestrate-lead` (aiuta a classificare AC)
- Skip silenzioso se la skill non è installata

### Step 4 — Spawn `test-orchestrate-lead`

#### Modalità parallel (default)

Se `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`:

```
Teammate.spawnTeam({
  lead: "test-orchestrate-lead",
  members: [
    { name: "api-tester",     subagent_type: "e2e-api-tester",     isolation: "worktree" },
    { name: "browser-tester", subagent_type: "e2e-browser-tester", isolation: "worktree" }
  ],
  timeout_minutes: 10
})
```

Prompt al lead:
```
Story target: US-{id}
File: specs/03-user-stories.md, specs/04-tech-spec.md
Pre-context (se disponibile): {dev-codesearch results}
Eseguì: classifica AC → spawn teammate paralleli → aggrega tramite test-aggregator
Output finale atteso: specs/08-validation.md
Modalità: {api-only | browser-only | full}
```

#### Modalità --no-team (fallback sequenziale)

Se Agent Teams disabilitati o `--no-team`:

```
Agent({ subagent_type: "test-orchestrate-lead", prompt: "... + use sequential mode" })
```

Lead spawnerà sequenzialmente con `Agent` invece di `Teammate.spawnTeam`. Stessa qualità output, solo wall-clock peggiore (~4-5min vs 90-120s).

### Step 5 — Monitor team progress

Polling ogni 30s sulla TaskList condivisa (`specs/testing/e2e-tasklist-{story-id}.json`):

```
🏃 Validation in corso (US-007 — 5 AC)
   ✅ AC-001 done (api-tester, 18s)
   🔄 AC-002 in-progress (browser-tester, 45s)
   ⏸  AC-003 todo
   ⏸  AC-004 todo
   ⏸  AC-005 todo
   ⏱️  Elapsed: 1m 12s
```

**Timeout safety**: se >10min totali e qualcosa è ancora `in-progress` → hook SubagentStop interviene + lead marca come TIMEOUT, prosegue con aggregator parziale.

### Step 6 — Aggregator

Quando tutti task in stato terminale, lead spawna `test-aggregator`:

```
Agent({
  subagent_type: "test-aggregator",
  prompt: "Aggrega report-api.md + report-browser.md per US-{id}.
           Genera specs/08-validation.md unificato.
           Embedda screenshots in sprint-reviews/{id}/screenshots/.
           Calcola coverage AC effettiva (PASS+FLAKY/total).
           Suggerisci fix per failing."
})
```

### Step 7 — Cleanup

- Rimuovi worktree: `git worktree remove ../validation-api-{id}` e `../validation-browser-{id}`
- (se `--keep-worktrees`: skippa cleanup)
- Sposta artifact dai worktree a directory main:
  - `tests/api/` → `tests/api/`
  - `tests/browser/` → `tests/browser/`
  - `screenshots/` → `sprint-reviews/{story-id}/screenshots/`

### Step 8 — Aggiorna `_status.md`

In base al verdict del aggregator:
- `100% PASS` → story status = `done`
- `coverage ≥80%, 0 FAIL, ≥1 FLAKY` → `done-pending-flaky-fix`
- `≥1 FAIL` → `validation-failed`

### Step 9 — Output finale al user

```
📊 Validation E2E completata — US-007

⏱️  Wall-clock: 1m 47s (vs ~4m 30s sequenziale, -60%)
🤖 Team: 3 agenti (Riccardo + Cinzia + Massimo + aggregator Bruno)

Coverage AC: 5/5 (100%)
   ✅ PASS:  4 (AC-001, AC-002, AC-003, AC-005)
   ⚠️  FLAKY: 1 (AC-004 — passes 4/5 runs)
   ❌ FAIL:  0

📂 Artifacts:
   - specs/08-validation.md (dashboard ready-to-publish)
   - tests/api/tasks.api.test.ts
   - tests/browser/login.browser.spec.ts
   - sprint-reviews/US-007/screenshots/ (8 screenshot)

💡 Action items:
   1. [HIGH] AC-004 flaky: investiga timing assertion
   2. [LOW] Documentare strategy "test paralleli con DB" in KB

🔁 Story status: done-pending-flaky-fix
```

---

## Esempi

### Esempio 1 — happy path full parallel

```
User: /dev-validate-e2e --story US-007

Skill:
  📋 Pre-flight: tutti i prerequisiti OK
  🎯 Story: US-007 — "Crea task con assegnatario" (5 AC)
  🔍 Pre-context: 3 file rilevanti via /dev-codesearch (semantic)
  🏃 Spawn team paralleli (Agent Teams attivo)
     - Riccardo (lead) classifica AC: 3 API + 2 UI
     - Cinzia (api-tester) inizia su 3 AC
     - Massimo (browser-tester) inizia su 2 AC
  ⏱️  1m 47s elapsed
  ✅ Aggregator (Bruno) genera 08-validation.md
  📊 4 PASS + 1 FLAKY = 100% coverage
```

### Esempio 2 — fallback no-team

```
User: /dev-validate-e2e --no-team --story US-008

Skill:
  📋 Modalità sequenziale forzata
  🏃 Spawn 1 agente alla volta:
     - Cinzia (api-tester) → 47s
     - Massimo (browser-tester) → 1m 12s
     - Bruno (aggregator) → 18s
  ⏱️  Total wall-clock: 2m 17s
  ✅ Coverage 100%
```

### Esempio 3 — dry-run

```
User: /dev-validate-e2e --story US-009 --dry-run

Skill:
  📋 Plan:
     - Story: US-009 (8 AC)
     - Classificazione preview: 5 API + 3 UI
     - Worktrees da creare: 2
     - Tempo stimato parallel: ~2-3 min
     - Tempo stimato sequenziale: ~6-7 min
     - Token stimati: ~85k
  💡 Esegui senza --dry-run per procedere
```

### Esempio 4 — gestione fallimento teammate

```
User: /dev-validate-e2e --story US-010

Skill:
  🏃 Team spawnato
     - Cinzia OK → 5/5 AC API done
     - Massimo crash al minuto 3 (Playwright timeout)
     - SubagentStop hook intercetta crash
     - Lead marca 3 AC UI come TIMEOUT
     - Aggregator procede con 5 PASS API + 3 TIMEOUT UI
  📊 Coverage parziale: 5/8 (62.5%)
  ⚠️  Story status: validation-incomplete
  💡 Re-run /dev-validate-e2e --browser-only per recuperare i 3 UI
```

---

## Hook integration

La skill sfrutta gli hook v0.12.0+:
- **SubagentStop** (`quality-gate.ts --check post-subagent`) → verifica che ogni teammate abbia prodotto i suoi artifact attesi (test files + report)
- **Stop** (`quality-gate.ts --check completion`) → al termine della skill, verifica coverage globale + flaky count

I hook sono `decision: warn`, non bloccano. Output silenzioso se OK.

---

## Knowledge Base hook (post-esecuzione)

Se `~/mucc-knowledge-base/` esiste e la validation ha rivelato pattern interessanti:
- `pattern/testing/`: scrivi nota se la classificazione AC ha trovato edge case ricorrenti
- `errori/`: scrivi nota se >2 test FLAKY con stessa root cause (es. "race condition su DB cleanup parallelo")
- Skip silenzioso se KB assente

---

## Troubleshooting

### "Agent Teams non spawnano teammate"

- Verifica `echo $CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` ritorna `1`
- Verifica versione Claude Code: `claude --version` (richiede 0.5+)
- Fallback: `--no-team`

### "Worktree creation fallisce"

- Verifica che il progetto sia un git repo (`git status`)
- Verifica che non ci siano già worktree con lo stesso nome (`git worktree list`)
- Cleanup manuale: `git worktree prune`

### "Playwright MCP non installato"

- `e2e-browser-tester` autodetecta e scrive `MANUAL_PENDING` con istruzioni
- Per attivare Playwright MCP: `claude mcp add playwright --command "npx" --args "@playwright/mcp"`

### "Test FLAKY al primo run"

- Tipicamente race condition o timing issue
- `e2e-api-tester` rilancia 3x prima di marcare FLAKY (riduce false positive)
- Screenshot e console log nei report dovrebbero rivelare la causa

---

## Riferimenti

- Agenti: `dev-methodology/agents/test-orchestrate-lead.md`, `e2e-api-tester.md`, `e2e-browser-tester.md`, `test-aggregator.md`
- Skill correlate: `/dev-validate` (legacy sequenziale), `/dev-implement`, `/dev-codesearch`
- Hook quality gate: `dev-methodology/scripts/quality-gate.ts --check post-subagent` (su pattern `e2e-api-tester|e2e-browser-tester|test-orchestrate-lead`)
- Pattern: Agent Teams (Anthropic sperimentale), Pattern D (Parallel + Worktree)
- Output canonico: `specs/08-validation.md`
