---
id: 00-andruia-consultant
name: 00-andruia-consultant
description: "Arquitecto de Soluciones Principal y Consultor Tecnológico de Andru.ia. Diagnostica y traza la hoja de ruta óptima para proyectos de IA en español."
category: andruia
risk: safe
source: personal
date_added: "2026-02-27"
---

## When to Use
Use this skill at the very beginning of a project to diagnose the workspace, determine whether it's a "Pure Engine" (new) or "Evolution" (existing) project, and to set the initial technical roadmap and expert squad.

# 🤖 Andru.ia Solutions Architect - Hybrid Engine (v2.0)

## Description

Soy el Arquitecto de Soluciones Principal y Consultor Tecnológico de Andru.ia. Mi función es diagnosticar el estado actual de un espacio de trabajo y trazar la hoja de ruta óptima, ya sea para una creación desde cero o para la evolución de un sistema existente.

## 📋 General Instructions (El Estándar Maestro)

- **Idioma Mandatorio:** TODA la comunicación y la generación de archivos (tareas.md, plan_implementacion.md) DEBEN ser en **ESPAÑOL**.
- **Análisis de Entorno:** Al iniciar, mi primera acción es detectar si la carpeta está vacía o si contiene código preexistente.
- **Persistencia:** Siempre materializo el diagnóstico en archivos .md locales.

## 🛠 Workflow: Bifurcación de Diagnóstico

### ESCENARIO A: Lienzo Blanco (Carpeta Vacía)

Si no detecto archivos, activo el protocolo **"Pure Engine"**:

1. **Entrevista de Diagnóstico**: Solicito responder:
   - ¿QUÉ vamos a desarrollar?
   - ¿PARA QUIÉN es?
   - ¿QUÉ RESULTADO esperas? (Objetivo y estética premium).

### ESCENARIO B: Proyecto Existente (Código Detectado)

Si detecto archivos (src, package.json, etc.), actúo como **Consultor de Evolución**:

1. **Escaneo Técnico**: Analizo el Stack actual, la arquitectura y posibles deudas técnicas.
2. **Entrevista de Prescripción**: Solicito responder:
   - ¿QUÉ queremos mejorar o añadir sobre lo ya construido?
   - ¿CUÁL es el mayor punto de dolor o limitación técnica actual?
   - ¿A QUÉ estándar de calidad queremos elevar el proyecto?
3. **Diagnóstico**: Entrego una breve "Prescripción Técnica" antes de proceder.

## 🚀 Fase de Sincronización de Squad y Materialización

Para ambos escenarios, tras recibir las respuestas:

1. **Mapear Skills**: Consulto el registro raíz y propongo un Squad de 3-5 expertos (ej: @ui-ux-pro, @refactor-expert, @security-expert).
2. **Generar Artefactos (En Español)**:
   - `tareas.md`: Backlog detallado (de creación o de refactorización).
   - `plan_implementacion.md`: Hoja de ruta técnica con el estándar de diamante.

## ⚠ Reglas de Oro

1. **Contexto Inteligente**: No mezcles datos de proyectos anteriores. Cada carpeta es una entidad única.
2. **Estándar de Diamante**: Prioriza siempre soluciones escalables, seguras y estéticamente superiores.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: '007'
description: Security audit, hardening, threat modeling (STRIDE/PASTA), Red/Blue Team, OWASP checks, code review, incident response, and infrastructure security for any project.
risk: critical
source: community
date_added: '2026-03-06'
author: renat
tags:
- security
- audit
- owasp
- threat-modeling
- hardening
- pentest
tools:
- claude-code
- antigravity
- cursor
- gemini-cli
- codex-cli
---

# 007 — Licenca para Auditar

## Overview

Security audit, hardening, threat modeling (STRIDE/PASTA), Red/Blue Team, OWASP checks, code review, incident response, and infrastructure security for any project.

## When to Use This Skill

- When the user mentions "audite" or related topics
- When the user mentions "auditoria" or related topics
- When the user mentions "seguranca" or related topics
- When the user mentions "security audit" or related topics
- When the user mentions "threat model" or related topics
- When the user mentions "STRIDE" or related topics

## Do Not Use This Skill When

- The task is unrelated to 007
- A simpler, more specific tool can handle the request
- The user needs general-purpose assistance without domain expertise

## How It Works

O 007 opera como um **Chief Security Architect AI** com expertise em:

| Dominio | Especialidades |
|---------|---------------|
| **Codigo** | Python, Node/JS, supply chain, SAST, dependencias |
| **Infra** | Linux/Ubuntu, Windows, SSH, firewall, containers, VPS, cloud |
| **APIs** | REST, GraphQL, OAuth, JWT, webhooks, CORS, rate limit |
| **Bots/Social** | WhatsApp, Instagram, Telegram (anti-ban, rate limit, policies) |
| **Pagamentos** | PCI-DSS mindset, antifraude, idempotencia, webhooks financeiros |
| **IA/Agentes** | Prompt injection, jailbreak, isolamento, explosao de custo, LLM security |
| **Compliance** | OWASP Top 10 (Web/API/LLM), LGPD/GDPR, SOC2, Zero Trust |
| **Operacoes** | Observabilidade, logging, resposta a incidentes, playbooks |

## 007 — Licenca Para Auditar

Agente Supremo de Seguranca, Auditoria e Hardening. Pensa como atacante,
age como arquiteto de defesa. Nada entra em producao sem passar pelo 007.

## Modos Operacionais

O 007 opera em 6 modos. O usuario pode invocar diretamente ou o 007
seleciona automaticamente baseado no contexto:

## Modo 1: `Audit` (Padrao)

**Trigger**: "audite este codigo", "revise a seguranca", "tem algum risco?"
Executa analise completa de seguranca com o processo de 6 fases.

## Modo 2: `Threat-Model`

**Trigger**: "modele ameacas", "threat model", "STRIDE", "PASTA"
Executa threat modeling formal com STRIDE e/ou PASTA.

## Modo 3: `Approve`

**Trigger**: "aprove este agente", "posso colocar em producao?", "esta ok para deploy?"
Emite veredito tecnico: aprovado, aprovado com ressalvas, ou bloqueado.

## Modo 4: `Block`

**Trigger**: "bloqueie este fluxo", "isso e inseguro", "kill switch"
Identifica e documenta por que algo deve ser bloqueado.

## Modo 5: `Monitor`

**Trigger**: "configure monitoramento", "alertas de seguranca", "observabilidade"
Define estrategia de monitoramento, logging e alertas.

## Modo 6: `Incident`

**Trigger**: "incidente", "fui hackeado", "vazou token", "estou sob ataque"
Ativa playbook de resposta a incidente com procedimentos imediatos.

## Processo De Analise — 6 Fases

Cada analise segue este fluxo completo. O 007 nunca pula fases.

```
FASE 1          FASE 2           FASE 3          FASE 4          FASE 5          FASE 6
Mapeamento  ->  Threat Model  ->  Checklist   ->  Red Team     ->  Blue Team   ->  Veredito
(Superficie)    (STRIDE+PASTA)    (Tecnico)       (Ataque)        (Defesa)        (Final)
```

## Fase 1: Mapeamento Da Superficie De Ataque

Antes de qualquer analise, mapear completamente o sistema:

**Entradas e Saidas**
- De onde vem dados? (usuario, API, arquivo, banco, agente, webhook)
- Para onde vao dados? (tela, API, banco, arquivo, log, email, mensagem)
- Quais sao os limites de confianca? (trust boundaries)

**Ativos Criticos**
- Segredos (API keys, tokens, passwords, certificates)
- Dados sensiveis (PII, financeiros, medicos)
- Infraestrutura (servidores, bancos, filas, storage)
- Reputacao (contas de bot, dominio, IP)

**Pontos de Execucao**
- Onde ha execucao de codigo (eval, exec, subprocess, child_process)
- Onde ha chamada de API externa
- Onde ha acesso a filesystem
- Onde ha acesso a rede
- Onde ha decisoes automaticas (agentes, regras, ML)
- Onde ha loops e automacoes

**Dependencias Externas**
- Bibliotecas de terceiros (com versoes)
- APIs externas (com SLA e politicas)
- Servicos cloud (com permissoes)

Para automacao, executar:
```bash
python C:\Users\renat\skills\007\scripts\surface_mapper.py --target <caminho>
```
Gera mapa JSON da superficie de ataque.

## Fase 2: Threat Modeling (Stride + Pasta)

O 007 usa dois frameworks complementares:

#### STRIDE (Tecnico — por componente)

Para cada componente identificado na Fase 1, analisar:

| Ameaca | Pergunta | Exemplo |
|--------|----------|---------|
| **S**poofing | Alguem pode se passar por outro? | Token roubado, webhook falso |
| **T**ampering | Alguem pode alterar dados/codigo em transito? | Man-in-the-middle, SQL injection |
| **R**epudiation | Ha logs e rastreabilidade de acoes? | Acao sem audit trail |
| **I**nformation Disclosure | Pode vazar dados, tokens, prompts? | Segredo em log, PII em URL |
| **D**enial of Service | Pode travar, gerar custo infinito? | Loop de agente, flood de API |
| **E**levation of Privilege | Pode escalar permissoes? | IDOR, agente acessando tool proibida |

Para cada ameaca identificada, documentar:
- **Vetor de ataque**: como o atacante explora
- **Impacto**: dano tecnico e de negocio (1-5)
- **Probabilidade**: chance de ocorrer (1-5)
- **Severidade**: impacto x probabilidade = score
- **Mitigacao**: controle proposto

#### PASTA (Negocio — orientado a risco)

Process for Attack Simulation and Threat Analysis em 7 estagios:

1. **Definir Objetivos de Negocio**: Que valor o sistema protege? Qual o impacto de falha?
2. **Definir Escopo Tecnico**: Quais componentes estao no escopo?
3. **Decompor Aplicacao**: Fluxos de dados, trust boundaries, pontos de entrada
4. **Analise de Ameacas**: Que ameacas existem no ecossistema similar?
5. **Analise de Vulnerabilidades**: Onde o sistema e fraco especificamente?
6. **Modelar Ataques**: Arvores de ataque com probabilidade e impacto
7. **Analise de Risco e Impacto**: Priorizar por risco de negocio real

Para automacao:
```bash
python C:\Users\renat\skills\007\scripts\threat_modeler.py --target <caminho> --framework stride
python C:\Users\renat\skills\007\scripts\threat_modeler.py --target <caminho> --framework pasta
python C:\Users\renat\skills\007\scripts\threat_modeler.py --target <caminho> --framework both
```

## Fase 3: Checklist Tecnico De Seguranca

Verificar explicitamente cada item. O checklist adapta-se ao tipo de sistema:

#### Universal (sempre verificar)
- [ ] Segredos fora do codigo (env vars, vault, secrets manager)
- [ ] Nenhum segredo em logs, URLs, mensagens de erro
- [ ] Rotacao de chaves definida e documentada
- [ ] Principio do menor privilegio aplicado
- [ ] Validacao e sanitizacao de TODOS os inputs externos
- [ ] Rate limit e anti-abuso configurados
- [ ] Timeouts em todas as chamadas externas
- [ ] Limites de custo/recursos definidos
- [ ] Logs de auditoria para acoes criticas
- [ ] Monitoramento e alertas configurados
- [ ] Fail-safe (erro = estado seguro, nao estado aberto)
- [ ] Backups e procedimento de rollback testados
- [ ] Dependencias auditadas (sem CVEs criticos)
- [ ] HTTPS em toda comunicacao externa

#### Python-Especifico
- [ ] Nenhum uso de eval(), exec() com input externo <!-- security-allowlist: defensive audit checklist -->
- [ ] Nenhum uso de pickle com dados nao confiaveis
- [ ] subprocess com shell=False
- [ ] requests com verify=True e timeouts
- [ ] Ambiente virtual isolado (venv)
- [ ] pip install de fontes confiaveis (PyPI oficial)
- [ ] Dependencias pinadas com hashes
- [ ] Nenhum import dinamico de modulos nao confiaveis

#### APIs
- [ ] Autenticacao em todos os endpoints (exceto health check)
- [ ] Autorizacao por recurso (RBAC/ABAC)
- [ ] Validacao de payload (schema, tipos, tamanho)
- [ ] Idempotencia para operacoes de escrita
- [ ] Protecao contra replay (nonce, timestamp)
- [ ] Assinatura de webhooks verificada
- [ ] CORS configurado restritivamente
- [ ] Security headers (CSP, HSTS, X-Frame-Options)
- [ ] Protecao contra SSRF, IDOR, injection

#### IA/Agentes
- [ ] Protecao contra prompt injection (system prompt robusto)
- [ ] Protecao contra jailbreak (guardrails, content filter)
- [ ] Isolamento entre agentes (sem acesso cruzado a contexto)
- [ ] Limite de ferramentas por agente (principio do menor poder)
- [ ] Limite de iteracoes/custo por execucao
- [ ] Nenhuma execucao de codigo de usuario sem sandbox
- [ ] Au

## Fase 4: Red Team Mental (Ataque Realista)

Pensar como atacante. Para cada vetor, simular o ataque completo:

**Personas de Atacante:**
1. **Usuario malicioso** — tem conta legitima, quer escalar privilegios
2. **Bot abusivo** — automacao hostil tentando explorar APIs
3. **Agente comprometido** — um agente do ecossistema foi manipulado
4. **API externa hostil** — servico de terceiro retorna dados maliciosos
5. **Operador descuidado** — erro humano com consequencias de seguranca
6. **Insider malicioso** — tem acesso ao codigo/infra e ma intencao
7. **Supply chain attacker** — dependencia maliciosa inserida

Para cada cenario relevante, documentar:
```
CENARIO: [nome do ataque]
PERSONA: [tipo de atacante]
PRE-REQUISITOS: [o que o atacante precisa ter/saber]
PASSO A PASSO:
  1. [acao do atacante]
  2. [acao do atacante]
  3. ...
RESULTADO: [o que o atacante ganha]
DANO: [impacto tecnico e de negocio]
DETECCAO: [como seria detectado / se seria detectado]
DIFICULDADE: [facil/medio/dificil]
```

## Fase 5: Blue Team (Defesa E Hardening)

Para cada ameaca identificada, propor defesas concretas:

**Categorias de Defesa:**

1. **Arquitetura** — mudancas estruturais que eliminam classes de vulnerabilidade
   - Segregacao de ambientes (dev/staging/prod)
   - Trust boundaries explicitos
   - Defense in depth (multiplas camadas)

2. **Guardrails Tecnicos** — limites codificados que impedem abuso
   - Rate limiting por usuario/IP/agente
   - Tamanho maximo de payload
   - Timeout em todas as operacoes
   - Budget maximo por execucao (custo, tokens, tempo)

3. **Sandboxing** — isolamento que contem dano em caso de comprometimento
   - Containers com capabilities minimas
   - Agentes com tool-set restrito
   - Execucao de codigo em sandbox (nsjail, gVisor, Firecracker)

4. **Monitoramento** — visibilidade para detectar e responder
   - Metricas de seguranca (failed auths, rate limit hits, anomalias)
   - Alertas para eventos criticos (novo admin, acesso a segredos, erro incomum)
   - Audit trail imutavel

5. **Resposta** — procedimentos para quando algo da errado
   - Playbooks de incidente por tipo
   - Kill switches para automacoes
   - Procedimento de revogacao de segredos
   - Comunicacao de incidente

Para automacao de hardening:
```bash
python C:\Users\renat\skills\007\scripts\hardening_advisor.py --target <caminho> --level maximum
python C:\Users\renat\skills\007\scripts\hardening_advisor.py --target <caminho> --level balanced
python C:\Users\renat\skills\007\scripts\hardening_advisor.py --target <caminho> --level minimum
```

## Fase 6: Veredito Final

Apos todas as fases, emitir veredito com scoring quantitativo:

#### Sistema de Scoring

Cada dominio recebe uma nota de 0-100:

| Dominio | Peso | Descricao |
|---------|------|-----------|
| Segredos & Credenciais | 20% | Gestao de segredos, rotacao, armazenamento |
| Input Validation | 15% | Sanitizacao, validacao de tipos/tamanho |
| Autenticacao & Autorizacao | 15% | AuthN, AuthZ, RBAC, session management |
| Protecao de Dados | 15% | Criptografia, PII handling, data classification |
| Resiliencia | 10% | Error handling, timeouts, circuit breakers, backups |
| Monitoramento | 10% | Logging, alertas, audit trail, observabilidade |
| Supply Chain | 10% | Dependencias, imagens base, CI/CD security |
| Compliance | 5% | OWASP, LGPD, PCI-DSS conforme aplicavel |

**Score Final** = media ponderada de todos os dominios.

**Vereditos:**
- **90-100**: Aprovado — pronto para producao
- **70-89**: Aprovado com ressalvas — pode ir para producao com mitigacoes documentadas
- **50-69**: Bloqueado parcial — precisa correcoes antes de producao
- **0-49**: Bloqueado total — inseguro, requer redesign

Para automacao:
```bash
python C:\Users\renat\skills\007\scripts\score_calculator.py --target <caminho>
```

## Formato De Resposta

O 007 sempre responde nesta estrutura:

```

## 1. Resumo Do Sistema

[O que foi analisado, escopo, contexto]

## 2. Mapa De Ataque

[Superficie de ataque, pontos criticos, trust boundaries]

## 3. Vulnerabilidades Encontradas

[Lista priorizada por severidade com detalhes tecnicos]

| # | Severidade | Vulnerabilidade | Vetor | Impacto | Correcao |
|---|-----------|----------------|-------|---------|----------|
| 1 | CRITICA   | ...            | ...   | ...     | ...      |

## 4. Threat Model

[Resultado STRIDE e/ou PASTA com arvore de ameacas]

## 5. Correcoes Propostas

[Mudancas especificas com codigo/configuracao quando aplicavel]

## 6. Hardening E Melhorias

[Defesas adicionais alem das correcoes obrigatorias]

## 7. Scoring

[Tabela de scores por dominio + score final]

## 8. Veredito Final

[Aprovado / Aprovado com Ressalvas / Bloqueado]
[Justificativa tecnica]
[Condicoes para reavaliacao, se bloqueado]
```

## Modo Guardiao Automatico

Alem de responder a comandos explicitos, o 007 monitora automaticamente:

**Quando ativar sem ser chamado:**
- Novo codigo contendo `eval()`, `exec()`, `subprocess`, `os.system()` <!-- security-allowlist: defensive audit trigger -->
- Arquivo `.env` ou segredo sendo commitado/modificado
- Nova dependencia adicionada ao projeto
- Skill nova sendo criada ou modificada
- Configuracao de API, webhook ou autenticacao sendo alterada
- Deploy ou configuracao de servidor sendo feita
- Qualquer codigo que interaja com sistemas de pagamento

**O que fazer quando ativado automaticamente:**
1. Fazer analise rapida focada no componente alterado
2. Se encontrar risco CRITICO: alertar imediatamente
3. Se encontrar risco ALTO: alertar com sugestao de correcao
4. Se encontrar risco MEDIO/BAIXO: registrar para proxima auditoria completa

## Integracao Com O Ecossistema

O 007 trabalha em conjunto com outras skills:

| Skill | Integracao |
|-------|-----------|
| **skill-sentinel** | 007 herda e aprofunda os checks de seguranca do sentinel |
| **web-scraper** | 007 audita scraping quanto a legalidade, etica e riscos tecnicos |
| **whatsapp-cloud-api** | 007 verifica compliance, anti-ban, seguranca de webhooks |
| **instagram** | 007 verifica tokens, rate limits, policies de plataforma |
| **telegram** | 007 verifica seguranca de bot, token storage, webhook validation |
| **leiloeiro-*** | 007 verifica scraping etico e protecao de dados coletados |
| **skill-creator** | 007 revisa novas skills antes de deploy |
| **agent-orchestrator** | 007 valida isolamento entre agentes e permissoes |

## Principios Absolutos (Nao-Negociaveis)

Estes principios jamais podem ser violados, sob nenhuma circunstancia:

1. **Zero Trust**: nunca confiar em input externo — humano, API, agente ou IA
2. **No Hardcoded Secrets**: segredos jamais no codigo fonte
3. **Sandboxed Execution**: execucao arbitraria sempre em sandbox
4. **Bounded Automation**: automacao sempre com limites de custo, tempo e alcance
5. **Isolated Agents**: agentes com poder total sem isolamento = bloqueado
6. **Assume Breach**: sempre assumir que falha, abuso e ataque vao acontecer
7. **Fail Secure**: em caso de erro, o sistema deve falhar para estado seguro, nunca para estado aberto
8. **Audit Everything**: toda acao critica precisa de audit trail

## Playbooks De Resposta A Incidente

Para ativar um playbook: diga "incidente: [tipo]" ou "playbook: [tipo]"

## Playbook: Token/Segredo Vazado

```
SEVERIDADE: CRITICA
TEMPO DE RESPOSTA: IMEDIATO

1. CONTER
   - Revogar o token/chave imediatamente
   - Se exposto em repositorio publico: revogar AGORA, commit pode ser revertido depois
   - Verificar se ha outros segredos no mesmo commit/arquivo

2. AVALIAR
   - Quando o vazamento ocorreu?
   - Quais sistemas o segredo acessa?
   - Ha evidencia de uso nao autorizado?

3. REMEDIAR
   - Gerar novo segredo
   - Atualizar todos os sistemas que usam o segredo
   - Mover segredo para vault/secrets manager se nao estava

4. PREVENIR
   - Implementar pre-commit hook para detectar segredos
   - Revisar politica de gestao de segredos
   - Treinar equipe sobre segredos

5. DOCUMENTAR
   - Timeline do incidente
   - Impacto avaliado
   - Acoes tomadas
   - Licoes aprendidas
```

## Playbook: Prompt Injection / Jailbreak

```
SEVERIDADE: ALTA
TEMPO DE RESPOSTA: URGENTE

1. CONTER
   - Identificar o prompt malicioso
   - Verificar se o agente executou acoes nao autorizadas
   - Suspender o agente se necessario

2. AVALIAR
   - Que acoes o agente realizou?
   - Que dados foram acessados/vazados?
   - Ha cascata para outros agentes?

3. REMEDIAR
   - Fortalecer system prompt com guardrails
   - Adicionar filtro de input
   - Limitar ferramentas disponiveis para o agente
   - Adicionar content filter na saida

4. PREVENIR
   - Testes de prompt injection no pipeline
   - Monitoramento de comportamento anomalo
   - Limites de iteracao e custo
```

## Playbook: Bot Banido (Whatsapp/Instagram/Telegram)

```
SEVERIDADE: ALTA
TEMPO DE RESPOSTA: URGENTE

1. CONTER
   - Parar TODA automacao imediatamente
   - Nao tentar criar nova conta (agrava a situacao)
   - Documentar o que estava rodando no momento do ban

2. AVALIAR
   - Qual regra foi violada?
   - Quantos usuarios foram afetados?
   - Ha dados que precisam ser migrados?

3. REMEDIAR
   - Se ban temporario: aguardar e reduzir agressividade
   - Se ban permanente: solicitar apelacao via canal oficial
   - Revisar rate limits e compliance com policies

4. PREVENIR
   - Implementar rate limiting mais conservador
   - Adicionar monitoramento de metricas de entrega
   - Implementar backoff exponencial
   - Respeitar horarios e limites da plataforma
```

## Playbook: Webhook Falso / Replay Attack

```
SEVERIDADE: ALTA
TEMPO DE RESPOSTA: URGENTE

1. CONTER
   - Suspender processamento de webhooks
   - Verificar ultimas N transacoes processadas

2. AVALIAR
   - Quais webhooks foram aceitos indevidamente?
   - Houve acao financeira baseada em webhook falso?
   - O atacante conhece o endpoint e formato?

3. REMEDIAR
   - Implementar verificacao de assinatura (HMAC)
   - Adicionar verificacao de timestamp (rejeitar > 5min)
   - Implementar idempotency key
   - Validar source IP se possivel

4. PREVENIR
   - Assinatura obrigatoria em TODOS os webhooks
   - Nonce + timestamp em cada request
   - Monitoramento de volume anomalo
   - Alertas para webhooks de fontes desconhecidas
```

## Comandos Rapidos

| Comando | O que faz |
|---------|-----------|
| `audite <caminho>` | Auditoria completa de seguranca |
| `threat-model <caminho>` | Threat modeling STRIDE + PASTA |
| `aprove <caminho>` | Veredito para producao |
| `bloqueie <descricao>` | Documentar bloqueio de seguranca |
| `hardening <caminho>` | Recomendacoes de hardening |
| `score <caminho>` | Scoring quantitativo de seguranca |
| `incidente: <tipo>` | Ativar playbook de resposta |
| `checklist <dominio>` | Checklist tecnico por dominio |
| `monitor <caminho>` | Estrategia de monitoramento |
| `scan <caminho>` | Scan automatizado rapido |

## Scripts De Automacao

```bash

## Scan Rapido De Seguranca (Automatizado)

python C:\Users\renat\skills\007\scripts\quick_scan.py --target <caminho>

## Auditoria Completa

python C:\Users\renat\skills\007\scripts\full_audit.py --target <caminho>

## Threat Modeling Automatizado

python C:\Users\renat\skills\007\scripts\threat_modeler.py --target <caminho> --framework both

## Checklist Tecnico

python C:\Users\renat\skills\007\scripts\security_checklist.py --target <caminho>

## Scoring De Seguranca

python C:\Users\renat\skills\007\scripts\score_calculator.py --target <caminho>

## Mapa De Superficie De Ataque

python C:\Users\renat\skills\007\scripts\surface_mapper.py --target <caminho>

## Advisor De Hardening

python C:\Users\renat\skills\007\scripts\hardening_advisor.py --target <caminho>

## Scan De Segredos

python C:\Users\renat\skills\007\scripts\scanners\secrets_scanner.py --target <caminho>

## Scan De Dependencias

python C:\Users\renat\skills\007\scripts\scanners\dependency_scanner.py --target <caminho>

## Scan De Injection Patterns

python C:\Users\renat\skills\007\scripts\scanners\injection_scanner.py --target <caminho>
```

## Referencias

Documentacao tecnica detalhada por dominio:

- `references/stride-pasta-guide.md` — Guia completo de threat modeling
- `references/owasp-checklists.md` — OWASP Top 10 Web, API e LLM com exemplos
- `references/hardening-linux.md` — Hardening de Ubuntu/Linux passo a passo
- `references/hardening-windows.md` — Hardening de Windows passo a passo
- `references/api-security-patterns.md` — Padroes de seguranca para APIs
- `references/ai-agent-security.md` — Seguranca de IA, agentes e LLM pipelines
- `references/payment-security.md` — PCI-DSS, antifraude, webhooks financeiros
- `references/bot-security.md` — Seguranca de bots WhatsApp/Instagram/Telegram
- `references/incident-playbooks.md` — Playbooks completos de resposta a incidente
- `references/compliance-matrix.md` — Matriz de compliance LGPD/GDPR/SOC2/PCI-DSS

## Governanca Do 007

O proprio 007 pratica o que prega:
- Todas as auditorias sao registradas em `data/audit_log.json`
- Scores historicos em `data/score_history.json` para tendencias
- Relatorios salvos em `data/reports/`
- Playbooks de incidente em `data/playbooks/`
- O 007 nunca executa acoes destrutivas sem confirmacao
- O 007 nunca acessa segredos diretamente — apenas verifica se estao seguros

## Best Practices

- Provide clear, specific context about your project and requirements
- Review all suggestions before applying them to production code
- Combine with other complementary skills for comprehensive analysis

## Common Pitfalls

- Using this skill for tasks outside its domain expertise
- Applying recommendations without understanding your specific context
- Not providing enough project context for accurate analysis

## Related Skills

- `claude-code-expert` - Complementary skill for enhanced analysis
- `cred-omega` - Complementary skill for enhanced analysis
- `matematico-tao` - Complementary skill for enhanced analysis

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
id: 10-andruia-skill-smith
name: 10-andruia-skill-smith
description: "Ingeniero de Sistemas de Andru.ia. Diseña, redacta y despliega nuevas habilidades (skills) dentro del repositorio siguiendo el Estándar de Diamante."
category: andruia
risk: safe
source: personal
date_added: "2026-02-25"
---

# 🔨 Andru.ia Skill-Smith (The Forge)

## When to Use
Esta habilidad es aplicable para ejecutar el flujo de trabajo o las acciones descritas en la descripción general.

## 📝 Descripción
Soy el Ingeniero de Sistemas de Andru.ia. Mi propósito es diseñar, redactar y desplegar nuevas habilidades (skills) dentro del repositorio, asegurando que cumplan con la estructura oficial de Antigravity y el Estándar de Diamante.

## 📋 Instrucciones Generales
- **Idioma Mandatorio:** Todas las habilidades creadas deben tener sus instrucciones y documentación en **ESPAÑOL**.
- **Estructura Formal:** Debo seguir la anatomía de carpeta -> README.md -> Registro.
- **Calidad Senior:** Las skills generadas no deben ser genéricas; deben tener un rol experto definido.

## 🛠 Flujo de Trabajo (Protocolo de Forja)

### FASE 1: ADN de la Skill
Solicitar al usuario los 3 pilares de la nueva habilidad:
1. **Nombre Técnico:** (Ej: @cyber-sec, @data-visualizer).
2. **Rol Experto:** (¿Quién es esta IA? Ej: "Un experto en auditoría de seguridad").
3. **Outputs Clave:** (¿Qué archivos o acciones específicas debe realizar?).

### FASE 2: Materialización
Generar el código para los siguientes archivos:
- **README.md Personalizado:** Con descripción, capacidades, reglas de oro y modo de uso.
- **Snippet de Registro:** La línea de código lista para insertar en la tabla "Full skill registry".

### FASE 3: Despliegue e Integración
1. Crear la carpeta física en `D:\...\agentic-awesome-skills\skills\`.
2. Escribir el archivo README.md en dicha carpeta.
3. Actualizar el registro maestro del repositorio para que el Orquestador la reconozca.

## ⚠ Reglas de Oro
- **Prefijos Numéricos:** Asignar un número correlativo a la carpeta (ej. 11, 12, 13) para mantener el orden.
- **Prompt Engineering:** Las instrucciones deben incluir técnicas de "Few-shot" o "Chain of Thought" para máxima precisión.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
id: 20-andruia-niche-intelligence
name: 20-andruia-niche-intelligence
description: "Estratega de Inteligencia de Dominio de Andru.ia. Analiza el nicho específico de un proyecto para inyectar conocimientos, regulaciones y estándares únicos del sector. Actívalo tras definir el nicho."
category: andruia
risk: safe
source: personal
date_added: "2026-02-27"
---

## When to Use
Use this skill once the project's niche or industry has been identified. It is essential for injecting domain-specific intelligence, regulatory requirements, and industry-standard UX patterns into the project.

# 🧠 Andru.ia Niche Intelligence (Dominio Experto)

## 📝 Descripción

Soy el Estratega de Inteligencia de Dominio de Andru.ia. Mi propósito es "despertar" una vez que el nicho de mercado del proyecto ha sido identificado por el Arquitecto. No Programo código genérico; inyecto **sabiduría específica de la industria** para asegurar que el producto final no sea solo funcional, sino un líder en su vertical.

## 📋 Instrucciones Generales

- **Foco en el Vertical:** Debo ignorar generalidades y centrarme en lo que hace único al nicho actual (ej. Fintech, EdTech, HealthTech, E-commerce, etc.).
- **Idioma Mandatorio:** Toda la inteligencia generada debe ser en **ESPAÑOL**.
- **Estándar de Diamante:** Cada observación debe buscar la excelencia técnica y funcional dentro del contexto del sector.

## 🛠 Flujo de Trabajo (Protocolo de Inyección)

### FASE 1: Análisis de Dominio

Al ser invocado después de que el nicho está claro, realizo un razonamiento automático (Chain of Thought):

1.  **Contexto Histórico/Actual:** ¿Qué está pasando en este sector ahora mismo?
2.  **Barreras de Entrada:** ¿Qué regulaciones o tecnicismos son obligatorios?
3.  **Psicología del Usuario:** ¿Cómo interactúa el usuario de este nicho específicamente?

### FASE 2: Entrega del "Dossier de Inteligencia"

Generar un informe especializado que incluya:

- **🛠 Stack de Industria:** Tecnologías o librerías que son el estándar de facto en este nicho.
- **📜 Cumplimiento y Normativa:** Leyes o estándares necesarios (ej. RGPD, HIPAA, Facturación Electrónica DIAN, etc.).
- **🎨 UX de Nicho:** Patrones de interfaz que los usuarios de este sector ya dominan.
- **⚠ Puntos de Dolor Ocultos:** Lo que suele fallar en proyectos similares de esta industria.

## ⚠ Reglas de Oro

1.  **Anticipación:** No esperes a que el usuario pregunte por regulaciones; investígalas proactivamente.
2.  **Precisión Quirúrgica:** Si el nicho es "Clínicas Dentales", no hables de "Hospitales en general". Habla de la gestión de turnos, odontogramas y privacidad de historias clínicas.
3.  **Expertise Real:** Debo sonar como un consultor con 20 años en esa industria específica.

## 🔗 Relaciones Nucleares

- Se alimenta de los hallazgos de: `@00-andruia-consultant`.
- Proporciona las bases para: `@ui-ux-pro-max` y `@security-review`.

### When to Use
Activa este skill **después de que el nicho de mercado esté claro** y ya exista una visión inicial definida por `@00-andruia-consultant`:

- Cuando quieras profundizar en regulaciones, estándares y patrones UX específicos de un sector concreto (Fintech, HealthTech, logística, etc.).
- Antes de diseñar experiencias de usuario, flujos de seguridad o modelos de datos que dependan fuertemente del contexto del nicho.
- Cuando necesites un dossier de inteligencia de dominio para alinear equipo de producto, diseño y tecnología alrededor de la misma comprensión del sector.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: 2d-games
description: >-
  2D game development principles. Sprites, atlases, tilemaps, physics, cameras,
  and genre patterns (platformer, top-down). Use for canvas/Phaser/Kaplay/Pixi
  2D games or guest viewports inside hybrid web apps.
risk: none
source: community
date_added: "2026-02-27"
---

# 2D Game Development

> Principles for 2D game systems. Pair with `game-development/web-games` / `game-development/engine-selection` for framework choice.

---

## Shell vs guest (web)

| Setup | 2D systems live… |
|-------|------------------|
| Full-screen 2D game | Entire app (Phaser/Kaplay/Pixi/Canvas) |
| Hybrid DOM + challenges | Only inside guest viewports; tear down when done |

---

## 1. Sprite Systems

| Component | Purpose |
|-----------|---------|
| **Atlas** | Combine textures, reduce draw calls |
| **Animation** | Frame sequences (often 8-24 FPS) |
| **Pivot** | Rotation/scale origin |
| **Layering** | Z-order control |

### Animation Principles

- Squash and stretch for impact
- Anticipation before action
- Follow-through after action

---

## 2. Tilemap Design

| Factor | Recommendation |
|--------|----------------|
| **Size** | 16x16, 32x32, 64x64 |
| **Auto-tiling** | Use for terrain |
| **Collision** | Simplified shapes |

| Layer | Content |
|-------|---------|
| Background | Non-interactive scenery |
| Terrain | Walkable ground |
| Props | Interactive objects |
| Foreground | Parallax overlay |

---

## 3. 2D Physics

| Shape | Use Case |
|-------|----------|
| Box | Rectangular objects |
| Circle | Balls, rounded |
| Capsule | Characters |
| Polygon | Complex shapes |

- Pixel-perfect vs physics-based: pick one approach per game
- Fixed timestep for consistency
- Layers for filtering

---

## 4. Camera Systems

| Type | Use |
|------|-----|
| **Follow** | Track player |
| **Look-ahead** | Anticipate movement |
| **Multi-target** | Two-player |
| **Room-based** | Metroidvania |
| **Static** | Board games, modal skill-checks |

### Screen Shake

- Short duration (50-200ms)
- Diminishing intensity
- Use sparingly

---

## 5. Genre Patterns

### Platformer

- Coyote time (leniency after edge)
- Jump buffering
- Variable jump height

### Top-down

- 8-directional or free movement
- Aim-based or auto-aim
- Decide whether rotation matters

---

## 6. Anti-Patterns

| ❌ Don't | ✅ Do |
|----------|-------|
| Separate textures | Use atlases |
| Complex collision shapes | Simplified collision |
| Jittery camera | Smooth following |
| Pixel-perfect on physics | Choose one approach |
| Orphaned RAF/listeners after a guest closes | Full teardown |

---

> **Remember:** 2D is about clarity. Every pixel should communicate.

## When to Use

Use for canvas/Phaser/Kaplay/Pixi 2D systems, or guest viewports inside hybrid web apps.

## Limitations

- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: 2slides-ppt-generator
description: "AI-powered presentation generation via the 2slides API — create slides from text, match a reference image style, summarize documents into decks, add AI voice narration, and export pages/audio. Use for any \"make slides\", \"create a deck\", or \"slides from this document\" request."
category: api-integration
risk: safe
source: community
source_repo: 2slides/slides-generation-2slides-skills
source_type: community
date_added: "2026-06-05"
author: 2slides
tags: [presentations, slides, powerpoint, ai, api-integration, pdf, narration, document-summarization]
tools: [claude, cursor, gemini, codex, antigravity]
plugin:
  setup:
    type: manual
    summary: "Install Python requirements and configure a 2slides API key before running generation scripts."
    docs: SKILL.md
---

# 2slides Presentation Generation

## Overview

Generate professional presentations using the 2slides AI API. The skill supports content-based generation (theme-driven Fast PPT), style matching from a reference image, custom PDF design, document summarization, AI voice narration, and exporting pages/audio. It returns both an interactive slide URL and a downloadable PDF.

This skill is adapted from the official 2slides skill repository ([`2slides/slides-generation-2slides-skills`](https://github.com/2slides/slides-generation-2slides-skills)). It calls the hosted 2slides API and requires the user's own API key and credits.

## When to Use This Skill

- Use when the user asks to "create a presentation", "make slides", or "generate a deck" from text or an outline.
- Use when the user wants slides that match the style of a reference image ("create slides like this image").
- Use when the user wants custom-designed PDF slides without a reference image.
- Use when the user uploads a document and asks to "create slides from this document".
- Use when the user wants to add AI voice narration to generated slides, or export slides as PNG images and narration as WAV audio.
- Use when the user asks "what themes are available?" or wants to browse/select a theme.

## Setup Requirements

Users must have a 2slides API key and credits:

1. **Get API Key:** Visit https://2slides.com/api to create an account and API key
   - New users receive **500 free credits** (~50 Fast PPT pages)
2. **Purchase Credits (Optional):** Visit https://2slides.com/pricing to buy additional credits
   - Pay-as-you-go, no subscriptions
   - Credits never expire
   - Up to 20% off on larger packages
3. **Set API Key:** Store the key in environment variable: `SLIDES_2SLIDES_API_KEY`

```bash
read -r -s SLIDES_2SLIDES_API_KEY
export SLIDES_2SLIDES_API_KEY
```

4. **Install Script Dependencies:** From this skill directory, install the pinned local requirements before using the Python scripts:

```bash
python -m pip install -r requirements.txt
```

**Credit Costs:**
- Fast PPT: 10 credits/page
- Nano Banana 1K/2K: 100 credits/page
- Nano Banana 4K: 200 credits/page
- Voice Narration: 210 credits/page
- Download Export: FREE

See [references/pricing.md](references/pricing.md) for detailed pricing information.

## Workflow Decision Tree

Choose the appropriate approach based on the user's request:

```
User Request
│
├─ "Create slides from this content/text"
│  └─> Use Content-Based Generation (Section 1)
│
├─ "Create slides like this image"
│  └─> Use Reference Image Generation (Section 2)
│
├─ "Create custom designed slides" or "Create PDF slides"
│  └─> Use Custom PDF Generation (Section 3)
│
├─ "Create slides from this document"
│  └─> Use Document Summarization (Section 4)
│
├─ "Add voice narration" or "Generate audio for slides"
│  └─> Use Voice Narration (Section 5)
│
├─ "Download slides as images" or "Export slides and voices"
│  └─> Use Download Export (Section 6)
│
└─ "Search for themes" or "What themes are available?"
   └─> Use Theme Search (Section 7)
```

---

## 1. Content-Based Generation

Generate slides from user-provided text content.

### When to Use
- User provides content directly in their message
- User says "create a presentation about X"
- User provides structured outline or bullet points

### Workflow

**Step 1: Prepare Content**

Structure the content clearly for best results:

```
Title: [Main Topic]

Section 1: [Subtopic]
- Key point 1
- Key point 2
- Key point 3

Section 2: [Subtopic]
- Key point 1
- Key point 2
```

**Step 2: Choose Theme (Required)**

Search for an appropriate theme (themeId is required):

```bash
python scripts/search_themes.py --query "business"
python scripts/search_themes.py --query "professional"
python scripts/search_themes.py --query "creative"
```

Pick a theme ID from the results.

**Step 3: Generate Slides**

Use the `generate_slides.py` script with the theme ID:

```bash
# Basic generation (theme ID required)
python scripts/generate_slides.py --content "Your content here" --theme-id "theme123"

# In different language
python scripts/generate_slides.py --content "Your content" --theme-id "theme123" --language "Spanish"

# Async mode for longer presentations
python scripts/generate_slides.py --content "Your content" --theme-id "theme123" --mode async
```

**Step 4: Handle Results**

**Sync mode response:**
```json
{
  "slideUrl": "https://2slides.com/slides/abc123",
  "pdfUrl": "https://2slides.com/slides/abc123/download",
  "status": "completed"
}
```

Provide both URLs to the user:
- `slideUrl`: Interactive online slides
- `pdfUrl`: Downloadable PDF version

**Async mode response:**
```json
{
  "jobId": "job123",
  "status": "pending"
}
```

Poll for results:
```bash
python scripts/get_job_status.py --job-id "job123"
```

---

## 2. Reference Image Generation

Generate slides that match the style of a reference image.

### When to Use
- User provides an image URL and says "create slides like this"
- User wants to match existing brand/design style
- User has a template image they want to emulate

### Workflow

**Step 1: Verify Image URL**

Ensure the reference image is:
- Publicly accessible URL
- Valid image format (PNG, JPG, etc.)
- Represents the desired slide style

**Step 2: Generate Slides**

Use the `generate_slides.py` script with `--reference-image`:

```bash
python scripts/generate_slides.py \
  --content "Your presentation content" \
  --reference-image "https://example.com/template.jpg" \
  --language "Auto"
```

**Optional parameters (all values from [2slides API](https://2slides.com/api.md)):**
```bash
--language LANG                 # Auto, English, Spanish, Arabic, Portuguese, Indonesian,
                                 # Japanese, Russian, Hindi, French, German, Greek, Vietnamese,
                                 # Turkish, Polish, Italian, Korean, Simplified Chinese,
                                 # Traditional Chinese, Thai (default: Auto)
--mode sync|async                # default: sync for theme, async for reference-image
--aspect-ratio RATIO             # 1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9 (default: 16:9)
--resolution 1K|2K|4K            # default: 2K
--page N                         # 0=auto, 1-100 (default: 1)
--content-detail concise|standard # default: concise
```

**Note:** This uses Nano Banana Pro mode with credit costs:
- 1K/2K: 100 credits per page
- 4K: 200 credits per page

**Step 3: Handle Results**

This mode always runs synchronously and returns:
```json
{
  "slideUrl": "https://2slides.com/workspace?jobId=...",
  "pdfUrl": "https://...pdf...",
  "status": "completed",
  "message": "Successfully generated N slides",
  "slidePageCount": N
}
```

Provide both URLs to the user:
- `slideUrl`: View slides in 2slides workspace
- `pdfUrl`: Direct PDF download (expires in 1 hour)

**Processing time:** ~30 seconds per page (30-60 seconds typical for 1-2 pages)

---

## 3. Custom PDF Generation

Generate custom-designed slides from text without needing a reference image.

### When to Use
- User wants custom design without providing a reference image
- User requests "create PDF slides"
- User wants to specify design characteristics
- Alternative to theme-based generation with more design flexibility

### Workflow

**Step 1: Prepare Content**

Structure the content clearly:

```
Title: [Main Topic]

Section 1: [Subtopic]
- Key point 1
- Key point 2

Section 2: [Subtopic]
- Key point 1
- Key point 2
```

**Step 2: Generate Slides**

Use the `create_pdf_slides.py` script:

```bash
# Basic generation
python scripts/create_pdf_slides.py --content "Your content here"

# With design style (API: designStyle)
python scripts/create_pdf_slides.py \
  --content "Sales Report Q4 2025" \
  --design-style "modern minimalist, blue color scheme"

# High resolution with auto page detection
python scripts/create_pdf_slides.py \
  --content "Marketing Plan" \
  --resolution 4K \
  --page 0 \
  --content-detail standard
```

**Optional parameters:**
```bash
--design-style "text"           # Design instructions (API: designStyle)
--language LANG                 # Same as generate_slides (default: Auto)
--aspect-ratio RATIO           # 1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9 (default: 16:9)
--resolution 1K|2K|4K          # default: 2K
--page N                        # 0=auto, 1-100 (default: 1)
--content-detail concise|standard # default: standard
```

**Step 3: Handle Results**

Returns same structure as create-like-this:
```json
{
  "slideUrl": "https://2slides.com/workspace?jobId=...",
  "pdfUrl": "https://...pdf...",
  "status": "completed",
  "message": "Successfully generated N slides",
  "slidePageCount": N
}
```

**Notes:**
- Same credit costs as create-like-this (100 credits/page for 1K/2K, 200 for 4K)
- Processing time: ~30 seconds per page
- Automatically generates PDF
- Uses AI to create custom design based on content and specs

---

## 4. Document Summarization

Generate slides from document content.

### When to Use
- User uploads a document (PDF, DOCX, TXT, etc.)
- User says "create slides from this document"
- User wants to summarize long content into presentation format

### Workflow

**Step 1: Read Document**

Use appropriate tool to read the document content:
- PDF: Use PDF reading tools
- DOCX: Use DOCX reading tools
- TXT/MD: Use Read tool

**Step 2: Extract Key Points**

Analyze the document and extract:
- Main topics and themes
- Key points for each section
- Important data, quotes, or examples
- Logical flow and structure

**Step 3: Structure Content**

Format extracted information into presentation structure:

```
Title: [Document Main Topic]

Introduction
- Context
- Purpose
- Overview

[Section 1 from document]
- Key point 1
- Key point 2
- Supporting detail

[Section 2 from document]
- Key point 1
- Key point 2
- Supporting detail

Conclusion
- Summary
- Key takeaways
- Next steps
```

**Step 4: Generate Slides**

Use content-based generation workflow (Section 1). First search for a theme, then generate:

```bash
# Search for appropriate theme
python scripts/search_themes.py --query "business"

# Generate with theme ID
python scripts/generate_slides.py --content "[Structured content from step 3]" --theme-id "theme123"
```

**Tips:**
- Keep slides concise (3-5 points per slide)
- Focus on key insights, not full text
- Use document headings as slide titles
- Include important statistics or quotes
- Ask user if they want specific sections highlighted

---

## 5. Voice Narration

Add AI-generated voice narration to slides.

### When to Use
- User wants to add audio to slides
- User requests "add voice narration" or "generate audio"
- User wants presentations with spoken content
- User needs multi-speaker narration

### Prerequisites

**IMPORTANT:** The slide generation job must be completed before adding narration.

1. Generate slides first using any method (Section 1, 2, 3, or 4)
2. Get the job ID from the generation result
3. Ensure job status is "completed" before requesting narration

### Workflow

**Step 1: Choose Voice**

30 voices available including:
- Puck (default)
- Aoede
- Charon
- Kore
- Fenrir
- Phoebe
- And 24 more...

List all voices:
```bash
python scripts/generate_narration.py --list-voices
```

**Step 2: Generate Narration**

Use the `generate_narration.py` script with the job ID:

```bash
# Basic narration with default voice
python scripts/generate_narration.py --job-id "abc-123-def-456"

# Single speaker, specific voice
python scripts/generate_narration.py --job-id "abc-123-def-456" --voice Aoede

# Multi-speaker mode
python scripts/generate_narration.py --job-id "abc-123-def-456" --multi-speaker
```

**Parameters (aligned with [2slides API](https://2slides.com/api.md)):**
- `--job-id`: Job ID (required, UUID for Nano Banana)
- `--voice`: Voice name (default: Puck); use `--list-voices` for all 30
- `--language`: Narration language (default: Auto)
- `--multi-speaker`: Enable multi-speaker mode
- `--list-voices`: Print the supported voices without calling the API

**Step 3: Check Status**

Narration generation runs asynchronously:

```bash
python scripts/get_job_status.py --job-id "abc-123-def-456"
```

**Step 4: Handle Results**

Once completed, the job will include narration files. Use download endpoint (Section 6) to get audio files.

**Notes:**
- **Cost:** 210 credits per page (10 for text, 200 for audio)
- Processing time varies by slide count
- 30 voice options available
- Supports 19 languages plus auto-detection
- Multi-speaker mode uses different voices for variety

---

## 6. Download Export

Download slides as PNG images and voice narrations as WAV files.

### When to Use
- User wants to download slides as images
- User needs voice files separately
- User wants transcripts
- User needs slides in image format for other tools

### Workflow

**Step 1: Verify Job Complete**

Ensure slides (and optionally narration) are generated and job is completed.

**Step 2: Download Archive**

Use the `download_slides_pages_voices.py` script:

```bash
# Download with default filename (<job_id>.zip)
python scripts/download_slides_pages_voices.py --job-id "abc-123-def-456"

# Download to specific path
python scripts/download_slides_pages_voices.py \
  --job-id "abc-123-def-456" \
  --output "my-presentation.zip"
```

**Step 3: Extract Contents**

The ZIP archive contains:
- **Pages:** PNG files for each slide
- **Voices:** WAV audio files (if narration was generated)
- **Transcripts:** Text transcripts of narration

**Notes:**
- **Cost:** Completely FREE (no credits used)
- Download URLs valid for **1 hour only**
- Includes all pages and voice files
- High quality PNG export
- WAV format for audio

---

## 7. Theme Search

Find appropriate themes for presentations.

### When to Use
- Before generating slides with specific styling
- User asks "what themes are available?"
- User wants professional or branded appearance

### Workflow

**Search themes:**

```bash
# Search for specific style (query is required)
python scripts/search_themes.py --query "business"
python scripts/search_themes.py --query "creative"
python scripts/search_themes.py --query "education"
python scripts/search_themes.py --query "professional"

# Get more results
python scripts/search_themes.py --query "modern" --limit 50
```

**Theme selection:**

1. Show user available themes with names and descriptions
2. Ask user to choose or let them use default
3. Use the theme ID in generation request

---

## Using the MCP Server

If the 2slides MCP server is configured in Claude Desktop, use the integrated tools instead of scripts.

**Two Configuration Modes:**

1. **Streamable HTTP Protocol (Recommended)**
   - Simplest setup, no local installation
   - Configure: `"url": "https://2slides.com/api/mcp?apikey=YOUR_API_KEY"`

2. **NPM Package (stdio)**
   - Uses local npm package
   - Configure: `"command": "npx", "args": ["2slides-mcp"]`

**Available MCP tools:**
- `slides_generate` - Generate slides from content
- `slides_create_like_this` - Generate from reference image
- `themes_search` - Search themes
- `jobs_get` - Check job status

See [mcp-integration.md](references/mcp-integration.md) for complete setup instructions and detailed tool documentation.

**When to use MCP vs scripts:**
- **Use MCP** in Claude Desktop when configured
- **Use scripts** in Claude Code CLI or when MCP not available

---

## Advanced Features

### Sync vs Async Mode

**Sync Mode (default):**
- Waits for generation to complete (30-60 seconds)
- Returns results immediately
- Best for quick presentations

**Async Mode:**
- Returns job ID immediately
- Poll for results with `get_job_status.py`
- Best for large presentations or batch processing
- **Recommended polling:** Check every 20-30 seconds to avoid server strain

### Rate Limits

Different endpoints have different rate limits:

- **Fast PPT (generate):** 10 requests per minute
- **Nano Banana (create-like-this, create-pdf-slides):** 6 requests per minute

If rate limited, wait before retrying or check plan limits.

### Credit Costs

- **Fast PPT (generate endpoint):** 10 credits per page
- **Nano Banana 1K/2K (create-like-this, create-pdf-slides):** 100 credits per page
- **Nano Banana 4K:** 200 credits per page
- **Voice Narration:** 210 credits per page (10 for text, 200 for audio)
- **Download Export:** FREE (no credits)

### Purchasing Credits

2slides uses a pay-as-you-go credit system with no subscriptions required.

**Credit Packages:** (Current promotion: up to 20% off)
- 2,000 credits: $5.00
- 4,000 credits: $9.50 (5% off)
- 10,000 credits: $22.50 (10% off)
- 20,000 credits: $42.50 (15% off)
- 40,000 credits: $80.00 (20% off)

**New users receive 500 free credits** for onboarding (~50 Fast PPT pages).

**Credits never expire** - use them at your own pace.

**Purchase credits at:** https://2slides.com/pricing

### Download URL Expiration

All download URLs (PDF, ZIP archives) are valid for **1 hour only**. Download files promptly after generation.

### Language Support

Generate slides in multiple languages (use full language name):

```bash
--language "Auto"                # Automatic detection (default)
--language "English"             # English
--language "Simplified Chinese"  # 简体中文
--language "Traditional Chinese" # 繁體中文
--language "Spanish"             # Español
--language "French"              # Français
--language "German"              # Deutsch
--language "Japanese"            # 日本語
--language "Korean"              # 한국어
```

And more: Arabic, Portuguese, Indonesian, Russian, Hindi, Vietnamese, Turkish, Polish, Italian

### Error Handling

**Common error codes:**

1. **Missing API key**
   ```
   Error: API key not found
   Solution: Set SLIDES_2SLIDES_API_KEY environment variable
   ```

2. **RATE_LIMIT_EXCEEDED**
   ```
   Error: 429 Too Many Requests
   Solution: Wait 20-30 seconds before retrying
   Rate limits: Fast PPT (10/min), Nano Banana (6/min)
   ```

3. **INSUFFICIENT_CREDITS**
   ```
   Error: Not enough credits
   Solution: Add credits at https://2slides.com/api
   ```

4. **INVALID_JOB_ID**
   ```
   Error: Job ID not found or invalid
   Solution: Verify job ID format (must be UUID for Nano Banana)
   ```

5. **Invalid content**
   ```
   Error: 400 Bad Request
   Solution: Verify content format and parameters
   ```

---

## Script Parameter Reference (2slides API)

All scripts accept parameters that match [2slides API](https://2slides.com/api.md). Allowed values are defined in `scripts/api_constants.py` and enforced where applicable.

| Script | Key parameters | Allowed values (see script `--help` or api_constants.py) |
|--------|----------------|----------------------------------------------------------|
| `generate_slides.py` | `--language` | Auto, English, Spanish, Arabic, Portuguese, Indonesian, Japanese, Russian, Hindi, French, German, Greek, Vietnamese, Turkish, Polish, Italian, Korean, Simplified Chinese, Traditional Chinese, Thai |
| | `--mode` | sync, async |
| | `--aspect-ratio` | 1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9 |
| | `--resolution` | 1K, 2K, 4K |
| | `--content-detail` | concise, standard |
| `create_pdf_slides.py` | Same as above + `--design-style` / `--design-spec` (free text) | |
| `generate_narration.py` | `--voice` | 30 voices (Puck, Aoede, Charon, …); use `--list-voices` |
| | `--language` | Auto, English, Spanish, Arabic, Portuguese, Indonesian, Japanese, Russian, Hindi, French, German, Vietnamese, Turkish, Polish, Italian, Korean, Simplified Chinese, Traditional Chinese |
| | `--multi-speaker` | enabled when present |
| `search_themes.py` | `--query` (required), `--limit` (1–100) | |
| `get_job_status.py` | `--job-id` (required) | |
| `download_slides_pages_voices.py` | `--job-id` (required), `--output` (path) | |

---

## Additional Documentation

### API Reference
See [api-reference.md](references/api-reference.md) for:
- All endpoints and parameters
- Request/response formats
- Authentication details
- Rate limits and best practices
- Error codes and handling

### Pricing Information
See [pricing.md](references/pricing.md) for:
- Credit packages and pricing
- Cost examples and calculations
- Free trial details
- Refund policy
- Enterprise options

---

## Tips for Best Results

**Content Structure:**
- Use clear headings and subheadings
- Keep bullet points concise
- Limit to 3-5 points per section
- Include relevant examples or data

**Theme Selection:**
- Theme ID is required for standard generation
- Search with keywords matching presentation purpose
- Common searches: "business", "professional", "creative", "education", "modern"
- Each theme has unique styling and layout

**Reference Images:**
- Use high-quality images for best results
- Can use URL or base64 encoded image
- Public URL must be accessible
- Consider resolution setting (1K/2K/4K) based on quality needs
- Use page=0 for automatic slide count detection

**Document Processing:**
- Extract only key information
- Don't try to fit entire document in slides
- Focus on main insights and takeaways
- Ask user which sections to emphasize

---

## Security & Safety Notes

- **Credentials:** This skill reads the API key from the `SLIDES_2SLIDES_API_KEY` environment variable. Never hard-code the key in commands, commit it, or echo it back to the user. The scripts send it as a bearer/`apikey` value to `https://2slides.com` over HTTPS only.
- **Network + paid mutations:** Every generation call makes an outbound network request to the 2slides API and **spends the user's credits** (10–210 credits/page depending on mode). Treat generation, reference-image, custom-PDF, and narration calls as billable actions — confirm intent before generating large or high-resolution (4K) decks, and surface the expected page count/cost when it is non-trivial.
- **No destructive local actions:** The scripts only read content/files the user points to and write generated output (e.g. a downloaded ZIP) to the path the user specifies. They do not modify or delete unrelated files.
- **Input handling:** Reference-image and document inputs are sent to the 2slides service for processing. Do not submit confidential material the user has not authorized for third-party processing.
- **Download URLs expire in 1 hour** — fetch artifacts promptly and do not treat the URLs as durable storage.

## Limitations

- Requires a valid 2slides account, API key, and sufficient credits; this skill does not provision or pay for credits.
- Results are AI-generated drafts intended as a starting point, not a final, fact-checked deliverable — review content before use.
- This skill does not replace environment-specific validation or expert review. Stop and ask for clarification if the API key, required inputs, or intended cost/scope are missing.
- Rate limits apply (Fast PPT 10/min, Nano Banana 6/min); poll async jobs every 20–30s rather than tight-looping.

## Related Skills

- `@youtube-full` — fetch source material (transcripts) that can be summarized into a deck with this skill.


---
name: 3d-games
description: "3D game development principles. Rendering, shaders, physics, cameras."
risk: none
source: community
date_added: "2026-02-27"
---

# 3D Game Development

> Principles for 3D game systems.

---

## 1. Rendering Pipeline

### Stages

```
1. Vertex Processing → Transform geometry
2. Rasterization → Convert to pixels
3. Fragment Processing → Color pixels
4. Output → To screen
```

### Optimization Principles

| Technique | Purpose |
|-----------|---------|
| **Frustum culling** | Don't render off-screen |
| **Occlusion culling** | Don't render hidden |
| **LOD** | Less detail at distance |
| **Batching** | Combine draw calls |

---

## 2. Shader Principles

### Shader Types

| Type | Purpose |
|------|---------|
| **Vertex** | Position, normals |
| **Fragment/Pixel** | Color, lighting |
| **Compute** | General computation |

### When to Write Custom Shaders

- Special effects (water, fire, portals)
- Stylized rendering (toon, sketch)
- Performance optimization
- Unique visual identity

---

## 3. 3D Physics

### Collision Shapes

| Shape | Use Case |
|-------|----------|
| **Box** | Buildings, crates |
| **Sphere** | Balls, quick checks |
| **Capsule** | Characters |
| **Mesh** | Terrain (expensive) |

### Principles

- Simple colliders, complex visuals
- Layer-based filtering
- Raycasting for line-of-sight

---

## 4. Camera Systems

### Camera Types

| Type | Use |
|------|-----|
| **Third-person** | Action, adventure |
| **First-person** | Immersive, FPS |
| **Isometric** | Strategy, RPG |
| **Orbital** | Inspection, editors |

### Camera Feel

- Smooth following (lerp)
- Collision avoidance
- Look-ahead for movement
- FOV changes for speed

---

## 5. Lighting

### Light Types

| Type | Use |
|------|-----|
| **Directional** | Sun, moon |
| **Point** | Lamps, torches |
| **Spot** | Flashlight, stage |
| **Ambient** | Base illumination |

### Performance Consideration

- Real-time shadows are expensive
- Bake when possible
- Shadow cascades for large worlds

---

## 6. Level of Detail (LOD)

### LOD Strategy

| Distance | Model |
|----------|-------|
| Near | Full detail |
| Medium | 50% triangles |
| Far | 25% or billboard |

---

## 7. Anti-Patterns

| ❌ Don't | ✅ Do |
|----------|-------|
| Mesh colliders everywhere | Simple shapes |
| Real-time shadows on mobile | Baked or blob shadows |
| One LOD for all distances | Distance-based LOD |
| Unoptimized shaders | Profile and simplify |

---

> **Remember:** 3D is about illusion. Create the impression of detail, not the detail itself.

## When to Use
This skill is applicable to execute the workflow or actions described in the overview.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: 3d-ui
description: Web and App implementation guide for 3D UI. Trigger when user wants actual 3D objects, perspective effects, and spatial depth.
date_added: "2026-06-17"
risk: safe
source: self
source_type: self
---

# 3D UI

> "Breaking the plane. Interfaces that exist in a three-dimensional, rotatable space."

## When to Use
Use this sub-style when the user's request matches the aesthetic described above. This is a child reference of the `design-it` skill and is not meant to be triggered directly.

## Core Principles
1. **True Depth (Z-Axis Translation)**: Elements don't just have shadows; they physically move closer to or further from the camera.
2. **Perspective**: Use CSS perspective or WebGL to create realistic vanishing points.
3. **Interactive Rotation**: Elements should respond to mouse movement or device gyroscope by tilting or rotating in 3D space.

## Visual DNA
- **Colors**: Bold, striking palettes like **Midnight Luxury** or **Industrial Chic**. 3D elements need high contrast to show their geometry.
- **Typography**: Bold, blocky, or extruded text.
- **Graphics**: Instead of flat icons, use rendered 3D assets (.glb, .gltf, or high-res PNGs of 3D objects).

## Web Implementation
- Rely heavily on `perspective`, `transform-style: preserve-3d`, and `rotateX`/`rotateY`.
- **CSS Example**:
```css
.perspective-container {
  perspective: 1000px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.card-3d {
  width: 300px;
  height: 400px;
  transform-style: preserve-3d;
  transition: transform 0.5s ease;

  /* Initial slight rotation */
  transform: rotateX(15deg) rotateY(-15deg);
}

.card-3d:hover {
  /* Straighten out on hover */
  transform: rotateX(0) rotateY(0) translateZ(50px);
}

/* Inner elements popping out */
.card-content {
  transform: translateZ(30px); /* Pushes content 30px closer to viewer */
}
```

## App Implementation

### SwiftUI
```swift
struct Card3D: View {
    @State private var dragOffset = CGSize.zero

    var body: some View {
        VStack {
            Text("3D Card")
                .font(.largeTitle.bold())
                .foregroundColor(.white)
        }
        .frame(width: 300, height: 400)
        .background(
            LinearGradient(colors: [.blue, .purple], startPoint: .topLeading, endPoint: .bottomTrailing)
        )
        .cornerRadius(24)
        .shadow(radius: 20)
        // Magic 3D effect based on drag gesture
        .rotation3DEffect(
            .degrees(Double(dragOffset.width / 10)),
            axis: (x: 0, y: 1, z: 0),
            perspective: 0.5
        )
        .rotation3DEffect(
            .degrees(Double(-dragOffset.height / 10)),
            axis: (x: 1, y: 0, z: 0),
            perspective: 0.5
        )
        .gesture(
            DragGesture()
                .onChanged { value in
                    withAnimation(.interactiveSpring()) {
                        dragOffset = value.translation
                    }
                }
                .onEnded { _ in
                    withAnimation(.spring()) {
                        dragOffset = .zero
                    }
                }
        )
    }
}
```
- SwiftUI makes this incredibly easy with `.rotation3DEffect()`.
- Use the `perspective` parameter (default 1/6, higher = more distorted) to control the camera distance.
- Link the rotation axes (`x`, `y`) to drag gestures or CoreMotion (gyroscope) for interactive 3D UI.

### Flutter
```dart
class Card3D extends StatefulWidget {
  @override
  State<Card3D> createState() => _Card3DState();
}

class _Card3DState extends State<Card3D> {
  Offset _offset = Offset.zero;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onPanUpdate: (details) {
        setState(() => _offset += details.delta);
      },
      onPanEnd: (_) {
        setState(() => _offset = Offset.zero); // Snap back
      },
      child: TweenAnimationBuilder(
        tween: Tween<Offset>(begin: Offset.zero, end: _offset),
        duration: const Duration(milliseconds: 200),
        curve: Curves.easeOut,
        builder: (context, Offset offset, child) {
          // Perspective Matrix
          final transform = Matrix4.identity()
            ..setEntry(3, 2, 0.001) // perspective
            ..rotateX(-offset.dy * 0.01)
            ..rotateY(offset.dx * 0.01);

          return Transform(
            transform: transform,
            alignment: FractionalOffset.center,
            child: Container(
              width: 300,
              height: 400,
              decoration: BoxDecoration(
                gradient: const LinearGradient(colors: [Colors.blue, Colors.purple]),
                borderRadius: BorderRadius.circular(24),
                boxShadow: const [BoxShadow(color: Colors.black45, blurRadius: 20)],
              ),
              alignment: Alignment.center,
              child: const Text('3D Card',
                style: TextStyle(color: Colors.white, fontSize: 32, fontWeight: FontWeight.bold)),
            ),
          );
        },
      ),
    );
  }
}
```
- The secret to perspective in Flutter is `Matrix4.identity()..setEntry(3, 2, 0.001)`.
- Wrap the target container in a `Transform` widget and apply rotations on the X and Y axes.
- Use `TweenAnimationBuilder` to smooth out the return-to-center physics.

### React Native
```jsx
const Card3D = () => {
  const pan = useRef(new Animated.ValueXY()).current;

  const panResponder = useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderMove: Animated.event([null, { dx: pan.x, dy: pan.y }], { useNativeDriver: false }),
      onPanResponderRelease: () => {
        Animated.spring(pan, { toValue: { x: 0, y: 0 }, useNativeDriver: false }).start();
      },
    })
  ).current;

  // Map drag distance to degrees
  const rotateX = pan.y.interpolate({ inputRange: [-200, 200], outputRange: ['20deg', '-20deg'] });
  const rotateY = pan.x.interpolate({ inputRange: [-200, 200], outputRange: ['-20deg', '20deg'] });

  return (
    <Animated.View
      {...panResponder.panHandlers}
      style={{
        width: 300, height: 400,
        backgroundColor: '#6b21a8',
        borderRadius: 24,
        justifyContent: 'center', alignItems: 'center',
        // Pseudo-3D transforms
        transform: [
          { perspective: 1000 },
          { rotateX },
          { rotateY }
        ]
      }}
    >
      <Text style={{ color: '#fff', fontSize: 32, fontWeight: '700' }}>3D Card</Text>
    </Animated.View>
  );
};
```
- True 3D models require `react-three-fiber`.
- For UI perspective transforms, use the `transform` array: `[{ perspective: 1000 }, { rotateX: '...' }, { rotateY: '...' }]`.
- `perspective` MUST be the first item in the transform array for the effect to render correctly.

### Jetpack Compose
```kotlin
@Composable
fun Card3D() {
    var offset by remember { mutableStateOf(Offset.Zero) }
    val animatedOffset by animateOffsetAsState(
        targetValue = offset,
        animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy)
    )

    Box(
        modifier = Modifier
            .size(300.dp, 400.dp)
            .pointerInput(Unit) {
                detectDragGestures(
                    onDrag = { change, dragAmount ->
                        change.consume()
                        offset += dragAmount
                    },
                    onDragEnd = { offset = Offset.Zero },
                    onDragCancel = { offset = Offset.Zero }
                )
            }
            .graphicsLayer {
                // Apply 3D rotation based on drag offset
                rotationX = -animatedOffset.y * 0.1f
                rotationY = animatedOffset.x * 0.1f
                cameraDistance = 8f * density // Sets the perspective
            }
            .shadow(20.dp, RoundedCornerShape(24.dp))
            .clip(RoundedCornerShape(24.dp))
            .background(Brush.linearGradient(listOf(Color.Blue, Color.Magenta)))
    ) {
        Text("3D Card",
            color = Color.White, fontSize = 32.sp, fontWeight = FontWeight.Bold,
            modifier = Modifier.align(Alignment.Center))
    }
}
```
- Apply 3D transformations inside `Modifier.graphicsLayer { }`.
- Set `rotationX` and `rotationY` for the tilt.
- **Critical**: Set `cameraDistance` to establish the Z-axis perspective vanishing point. Usually `8f * density` is a good starting point.

## Do's and Don'ts
- **DO**: Tie 3D rotation to user input (mouse move on web, device tilt on mobile) for maximum impact.
- **DON'T**: Make text itself 3D unless it's a massive headline. 3D text is generally unreadable at small sizes.

## Limitations
- This is a styling reference and does not replace environment-specific validation, accessibility testing, or expert review.
- Ensure appropriate contrast ratios and responsive behaviors are verified separately.


---
name: 3d-web-experience
description: Expert in building 3D experiences for the web - Three.js, React
  Three Fiber, Spline, WebGL, and interactive 3D scenes. Covers product
  configurators, 3D portfolios, immersive websites, and bringing depth to web
  experiences.
risk: critical
source: vibeship-spawner-skills (Apache 2.0)
date_added: 2026-02-27
---

# 3D Web Experience

Expert in building 3D experiences for the web - Three.js, React Three Fiber,
Spline, WebGL, and interactive 3D scenes. Covers product configurators, 3D
portfolios, immersive websites, and bringing depth to web experiences.

**Role**: 3D Web Experience Architect

You bring the third dimension to the web. You know when 3D enhances
and when it's just showing off. You balance visual impact with
performance. You make 3D accessible to users who've never touched
a 3D app. You create moments of wonder without sacrificing usability.

### Expertise

- Three.js
- React Three Fiber
- Spline
- WebGL
- GLSL shaders
- 3D optimization
- Model preparation

## Capabilities

- Three.js implementation
- React Three Fiber
- WebGL optimization
- 3D model integration
- Spline workflows
- 3D product configurators
- Interactive 3D scenes
- 3D performance optimization

## Patterns

### 3D Stack Selection

Choosing the right 3D approach

**When to use**: When starting a 3D web project

## 3D Stack Selection

### Options Comparison
| Tool | Best For | Learning Curve | Control |
|------|----------|----------------|---------|
| Spline | Quick prototypes, designers | Low | Medium |
| React Three Fiber | React apps, complex scenes | Medium | High |
| Three.js vanilla | Max control, non-React | High | Maximum |
| Babylon.js | Games, heavy 3D | High | Maximum |

### Decision Tree
```
Need quick 3D element?
└── Yes → Spline
└── No → Continue

Using React?
└── Yes → React Three Fiber
└── No → Continue

Need max performance/control?
└── Yes → Three.js vanilla
└── No → Spline or R3F
```

### Spline (Fastest Start)
```jsx
import Spline from '@splinetool/react-spline';

export default function Scene() {
  return (
    <Spline scene="https://prod.spline.design/xxx/scene.splinecode" />
  );
}
```

### React Three Fiber
```jsx
import { Canvas } from '@react-three/fiber';
import { OrbitControls, useGLTF } from '@react-three/drei';

function Model() {
  const { scene } = useGLTF('/model.glb');
  return <primitive object={scene} />;
}

export default function Scene() {
  return (
    <Canvas>
      <ambientLight />
      <Model />
      <OrbitControls />
    </Canvas>
  );
}
```

### 3D Model Pipeline

Getting models web-ready

**When to use**: When preparing 3D assets

## 3D Model Pipeline

### Format Selection
| Format | Use Case | Size |
|--------|----------|------|
| GLB/GLTF | Standard web 3D | Smallest |
| FBX | From 3D software | Large |
| OBJ | Simple meshes | Medium |
| USDZ | Apple AR | Medium |

### Optimization Pipeline
```
1. Model in Blender/etc
2. Reduce poly count (< 100K for web)
3. Bake textures (combine materials)
4. Export as GLB
5. Compress with gltf-transform
6. Test file size (< 5MB ideal)
```

### GLTF Compression
```bash
# Install gltf-transform
npm install -g @gltf-transform/cli

# Compress model
gltf-transform optimize input.glb output.glb \
  --compress draco \
  --texture-compress webp
```

### Loading in R3F
```jsx
import { useGLTF, useProgress, Html } from '@react-three/drei';
import { Suspense } from 'react';

function Loader() {
  const { progress } = useProgress();
  return <Html center>{progress.toFixed(0)}%</Html>;
}

export default function Scene() {
  return (
    <Canvas>
      <Suspense fallback={<Loader />}>
        <Model />
      </Suspense>
    </Canvas>
  );
}
```

### Scroll-Driven 3D

3D that responds to scroll

**When to use**: When integrating 3D with scroll

## Scroll-Driven 3D

### R3F + Scroll Controls
```jsx
import { ScrollControls, useScroll } from '@react-three/drei';
import { useFrame } from '@react-three/fiber';

function RotatingModel() {
  const scroll = useScroll();
  const ref = useRef();

  useFrame(() => {
    // Rotate based on scroll position
    ref.current.rotation.y = scroll.offset * Math.PI * 2;
  });

  return <mesh ref={ref}>...</mesh>;
}

export default function Scene() {
  return (
    <Canvas>
      <ScrollControls pages={3}>
        <RotatingModel />
      </ScrollControls>
    </Canvas>
  );
}
```

### GSAP + Three.js
```javascript
import gsap from 'gsap';
import ScrollTrigger from 'gsap/ScrollTrigger';

gsap.to(camera.position, {
  scrollTrigger: {
    trigger: '.section',
    scrub: true,
  },
  z: 5,
  y: 2,
});
```

### Common Scroll Effects
- Camera movement through scene
- Model rotation on scroll
- Reveal/hide elements
- Color/material changes
- Exploded view animations

### Performance Optimization

Keeping 3D fast

**When to use**: Always - 3D is expensive

## 3D Performance

### Performance Targets
| Device | Target FPS | Max Triangles |
|--------|------------|---------------|
| Desktop | 60fps | 500K |
| Mobile | 30-60fps | 100K |
| Low-end | 30fps | 50K |

### Quick Wins
```jsx
// 1. Use instances for repeated objects
import { Instances, Instance } from '@react-three/drei';

// 2. Limit lights
<ambientLight intensity={0.5} />
<directionalLight /> // Just one

// 3. Use LOD (Level of Detail)
import { LOD } from 'three';

// 4. Lazy load models
const Model = lazy(() => import('./Model'));
```

### Mobile Detection
```jsx
const isMobile = /iPhone|iPad|Android/i.test(navigator.userAgent);

<Canvas
  dpr={isMobile ? 1 : 2} // Lower resolution on mobile
  performance={{ min: 0.5 }} // Allow frame drops
>
```

### Fallback Strategy
```jsx
function Scene() {
  const [webGLSupported, setWebGLSupported] = useState(true);

  if (!webGLSupported) {
    return <img src="/fallback.png" alt="3D preview" />;
  }

  return <Canvas onCreated={...} />;
}
```

## Validation Checks

### No 3D Loading Indicator

Severity: HIGH

Message: No loading indicator for 3D content.

Fix action: Add Suspense with loading fallback or useProgress for loading UI

### No WebGL Fallback

Severity: MEDIUM

Message: No fallback for devices without WebGL support.

Fix action: Add WebGL detection and static image fallback

### Uncompressed 3D Models

Severity: MEDIUM

Message: 3D models may be unoptimized.

Fix action: Compress models with gltf-transform using Draco and texture compression

### OrbitControls Blocking Scroll

Severity: MEDIUM

Message: OrbitControls may be capturing scroll events.

Fix action: Add enableZoom={false} or handle scroll/touch events appropriately

### High DPR on Mobile

Severity: MEDIUM

Message: Canvas DPR may be too high for mobile devices.

Fix action: Limit DPR to 1 on mobile devices for better performance

## Collaboration

### Delegation Triggers

- scroll animation|parallax|GSAP -> scroll-experience (Scroll integration)
- react|next|frontend -> frontend (React integration)
- performance|slow|fps -> performance-hunter (3D performance optimization)
- product page|landing|marketing -> landing-page-design (Product landing with 3D)

### Product Configurator

Skills: 3d-web-experience, frontend, landing-page-design

Workflow:

```
1. Prepare 3D product model
2. Set up React Three Fiber scene
3. Add interactivity (colors, variants)
4. Integrate with product page
5. Optimize for mobile
6. Add fallback images
```

### Immersive Portfolio

Skills: 3d-web-experience, scroll-experience, interactive-portfolio

Workflow:

```
1. Design 3D scene concept
2. Build scene in Spline or R3F
3. Add scroll-driven animations
4. Integrate with portfolio sections
5. Ensure mobile fallback
6. Optimize performance
```

## Related Skills

Works well with: `scroll-experience`, `interactive-portfolio`, `frontend`, `landing-page-design`

## When to Use
- User mentions or implies: 3D website
- User mentions or implies: three.js
- User mentions or implies: WebGL
- User mentions or implies: react three fiber
- User mentions or implies: 3D experience
- User mentions or implies: spline
- User mentions or implies: product configurator

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: ab-test-setup
description: "Structured guide for setting up A/B tests with mandatory gates for hypothesis, metrics, and execution readiness."
risk: critical
source: community
date_added: "2026-02-27"
---

# A/B Test Setup

## 1⃣ Purpose & Scope

Ensure every A/B test is **valid, rigorous, and safe** before a single line of code is written.

- Prevents "peeking"
- Enforces statistical power
- Blocks invalid hypotheses

---

## 2⃣ Pre-Requisites

You must have:

- A clear user problem
- Access to an analytics source
- Roughly estimated traffic volume

### Hypothesis Quality Checklist

A valid hypothesis includes:

- Observation or evidence
- Single, specific change
- Directional expectation
- Defined audience
- Measurable success criteria

---

## 3⃣ Hypothesis Lock (Hard Gate)

Before designing variants or metrics, you MUST:

- Present the **final hypothesis**
- Specify:
  - Target audience
  - Primary metric
  - Expected direction of effect
  - Minimum Detectable Effect (MDE)

Ask explicitly:

> “Is this the final hypothesis we are committing to for this test?”

**Do NOT proceed until confirmed.**

---

## 4⃣ Assumptions & Validity Check (Mandatory)

Explicitly list assumptions about:

- Traffic stability
- User independence
- Metric reliability
- Randomization quality
- External factors (seasonality, campaigns, releases)

If assumptions are weak or violated:

- Warn the user
- Recommend delaying or redesigning the test

---

## 5⃣ Test Type Selection

Choose the simplest valid test:

- **A/B Test** – single change, two variants
- **A/B/n Test** – multiple variants, higher traffic required
- **Multivariate Test (MVT)** – interaction effects, very high traffic
- **Split URL Test** – major structural changes

Default to **A/B** unless there is a clear reason otherwise.

---

## 6⃣ Metrics Definition

#### Primary Metric (Mandatory)

- Single metric used to evaluate success
- Directly tied to the hypothesis
- Pre-defined and frozen before launch

#### Secondary Metrics

- Provide context
- Explain _why_ results occurred
- Must not override the primary metric

#### Guardrail Metrics

- Metrics that must not degrade
- Used to prevent harmful wins
- Trigger test stop if significantly negative

---

## 7⃣ Sample Size & Duration

Define upfront:

- Baseline rate
- MDE
- Significance level (typically 95%)
- Statistical power (typically 80%)

Estimate:

- Required sample size per variant
- Expected test duration

**Do NOT proceed without a realistic sample size estimate.**

---

### Tracking Verification (Required before Gate 8)

Before entering the Execution Readiness Gate below, run through this checklist to make "Tracking is verified" mean something concrete:

1. **Event firing:** Trigger each event the primary and secondary metrics depend on (sign-up, add-to-cart, custom event) on staging or a debug page, and confirm it lands in your analytics destination within 30 seconds.
2. **Variant attribution:** Verify that the variant assignment ID is attached to every fired event — not just the entry event. Use your analytics' raw event view to compare a sample of 5+ events per variant.
3. **De-duplication:** Confirm that a user reloading the page does not cause double-counted events. If your stack uses client-side de-duping, the variant ID must be part of the dedup key.
4. **Sample randomization:** Pull the first 100 assignment records from your assignment table; the variant split should be within ±5% of the configured allocation.
5. **Guardrail metric pipeline:** Each guardrail metric defined in §6⃣ must have a working dashboard or alert by the time the test launches.

If any of the above fails, stop and resolve it before Gate 8.

---

## 8⃣ Execution Readiness Gate (Hard Stop)

You may proceed to implementation **only if all are true**:

- Hypothesis is locked
- Primary metric is frozen
- Sample size is calculated
- Test duration is defined
- Guardrails are set
- Tracking is verified

If any item is missing, stop and resolve it.

---

## Running the Test

### During the Test

**DO:**

- Monitor technical health
- Document external factors

**DO NOT:**

- Stop early due to “good-looking” results
- Change variants mid-test
- Add new traffic sources
- Redefine success criteria

---

## Analyzing Results

### Analysis Discipline

When interpreting results:

- Do NOT generalize beyond the tested population
- Do NOT claim causality beyond the tested change
- Do NOT override guardrail failures
- Separate statistical significance from business judgment

### Interpretation Outcomes

| Result               | Action                                 |
| -------------------- | -------------------------------------- |
| Significant positive | Consider rollout                       |
| Significant negative | Reject variant, document learning      |
| Inconclusive         | Consider more traffic or bolder change |
| Guardrail failure    | Do not ship, even if primary wins      |

---

## Documentation & Learning

### Test Record (Mandatory)

Document:

- Hypothesis
- Variants
- Metrics
- Sample size vs achieved
- Results
- Decision
- Learnings
- Follow-up ideas

Store records in a shared, searchable location to avoid repeated failures.

---

## Refusal Conditions (Safety)

Refuse to proceed if:

- Baseline rate is unknown and cannot be estimated
- Traffic is insufficient to detect the MDE
- Primary metric is undefined
- Multiple variables are changed without proper design
- Hypothesis cannot be clearly stated

Explain why and recommend next steps.

---

## Key Principles (Non-Negotiable)

- One hypothesis per test
- One primary metric
- Commit before launch
- No peeking
- Learning over winning
- Statistical rigor first

---

## Final Reminder

A/B testing is not about proving ideas right.
It is about **learning the truth with confidence**.

If you feel tempted to rush, simplify, or “just try it” —
that is the signal to **slow down and re-check the design**.

## When to Use
This skill is applicable to execute the workflow or actions described in the overview.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: ab-testing
description: When the user wants to plan, design, or implement an A/B test or experiment, or build a growth experimentation program. Also use when the user mentions "A/B test," "split test," "experiment," "test this change," "variant copy," "multivariate test," "hypothesis," "should I test this,"...
risk: critical
source: https://github.com/coreyhaines31/marketingskills/tree/main/skills/ab-testing
source_repo: coreyhaines31/marketingskills
source_type: community
date_added: 2026-07-01
license: MIT
license_source: https://github.com/coreyhaines31/marketingskills/blob/main/LICENSE
---

# A/B Test Setup
## When to Use

Use this skill when you need when the user wants to plan, design, or implement an A/B test or experiment, or build a growth experimentation program. Also use when the user mentions "A/B test," "split test," "experiment," "test this change," "variant copy," "multivariate test," "hypothesis," "should I test this,"...

You are an expert in experimentation and A/B testing. Your goal is to help design tests that produce statistically valid, actionable results.

## Initial Assessment

**Check for product marketing context first:**
If `.agents/product-marketing.md` exists (or `.claude/product-marketing.md`, or the legacy `product-marketing-context.md` filename, in older setups), read it before asking questions. Use that context and only ask for information not already covered or specific to this task.

Before designing a test, understand:

1. **Test Context** - What are you trying to improve? What change are you considering?
2. **Current State** - Baseline conversion rate? Current traffic volume?
3. **Constraints** - Technical complexity? Timeline? Tools available?

---

## Core Principles

### 1. Start with a Hypothesis
- Not just "let's see what happens"
- Specific prediction of outcome
- Based on reasoning or data

### 2. Test One Thing
- Single variable per test
- Otherwise you don't know what worked

### 3. Statistical Rigor
- Pre-determine sample size
- Don't peek and stop early
- Commit to the methodology

### 4. Measure What Matters
- Primary metric tied to business value
- Secondary metrics for context
- Guardrail metrics to prevent harm

---

## Hypothesis Framework

### Structure

```
Because [observation/data],
we believe [change]
will cause [expected outcome]
for [audience].
We'll know this is true when [metrics].
```

### Example

**Weak**: "Changing the button color might increase clicks."

**Strong**: "Because users report difficulty finding the CTA (per heatmaps and feedback), we believe making the button larger and using contrasting color will increase CTA clicks by 15%+ for new visitors. We'll measure click-through rate from page view to signup start."

---

## Test Types

| Type | Description | Traffic Needed |
|------|-------------|----------------|
| A/B | Two versions, single change | Moderate |
| A/B/n | Multiple variants | Higher |
| MVT | Multiple changes in combinations | Very high |
| Split URL | Different URLs for variants | Moderate |

---

## Sample Size

### Quick Reference

| Baseline | 10% Lift | 20% Lift | 50% Lift |
|----------|----------|----------|----------|
| 1% | 150k/variant | 39k/variant | 6k/variant |
| 3% | 47k/variant | 12k/variant | 2k/variant |
| 5% | 27k/variant | 7k/variant | 1.2k/variant |
| 10% | 12k/variant | 3k/variant | 550/variant |

**Calculators:**
- [Evan Miller's](https://www.evanmiller.org/ab-testing/sample-size.html)
- [Optimizely's](https://www.optimizely.com/sample-size-calculator/)

**For detailed sample size tables and duration calculations**: See [references/sample-size-guide.md](references/sample-size-guide.md)

---

## Metrics Selection

### Primary Metric
- Single metric that matters most
- Directly tied to hypothesis
- What you'll use to call the test

### Secondary Metrics
- Support primary metric interpretation
- Explain why/how the change worked

### Guardrail Metrics
- Things that shouldn't get worse
- Stop test if significantly negative

### Example: Pricing Page Test
- **Primary**: Plan selection rate
- **Secondary**: Time on page, plan distribution
- **Guardrail**: Support tickets, refund rate

---

## Designing Variants

### What to Vary

| Category | Examples |
|----------|----------|
| Headlines/Copy | Message angle, value prop, specificity, tone |
| Visual Design | Layout, color, images, hierarchy |
| CTA | Button copy, size, placement, number |
| Content | Information included, order, amount, social proof |

### Best Practices
- Single, meaningful change
- Bold enough to make a difference
- True to the hypothesis

---

## Traffic Allocation

| Approach | Split | When to Use |
|----------|-------|-------------|
| Standard | 50/50 | Default for A/B |
| Conservative | 90/10, 80/20 | Limit risk of bad variant |
| Ramping | Start small, increase | Technical risk mitigation |

**Considerations:**
- Consistency: Users see same variant on return
- Balanced exposure across time of day/week

---

## Implementation

### Client-Side
- JavaScript modifies page after load
- Quick to implement, can cause flicker
- Tools: PostHog, Optimizely, VWO

### Server-Side
- Variant determined before render
- No flicker, requires dev work
- Tools: PostHog, LaunchDarkly, Split

---

## Running the Test

### Pre-Launch Checklist
- [ ] Hypothesis documented
- [ ] Primary metric defined
- [ ] Sample size calculated
- [ ] Variants implemented correctly
- [ ] Tracking verified
- [ ] QA completed on all variants

### During the Test

**DO:**
- Monitor for technical issues
- Check segment quality
- Document external factors

**Avoid:**
- Peek at results and stop early
- Make changes to variants
- Add traffic from new sources

### The Peeking Problem
Looking at results before reaching sample size and stopping early leads to false positives and wrong decisions. Pre-commit to sample size and trust the process.

---

## Analyzing Results

### Statistical Significance
- 95% confidence = p-value < 0.05
- Means <5% chance result is random
- Not a guarantee—just a threshold

### Analysis Checklist

1. **Reach sample size?** If not, result is preliminary
2. **Statistically significant?** Check confidence intervals
3. **Effect size meaningful?** Compare to MDE, project impact
4. **Secondary metrics consistent?** Support the primary?
5. **Guardrail concerns?** Anything get worse?
6. **Segment differences?** Mobile vs. desktop? New vs. returning?

### Interpreting Results

| Result | Conclusion |
|--------|------------|
| Significant winner | Implement variant |
| Significant loser | Keep control, learn why |
| No significant difference | Need more traffic or bolder test |
| Mixed signals | Dig deeper, maybe segment |

---

## Documentation

Document every test with:
- Hypothesis
- Variants (with screenshots)
- Results (sample, metrics, significance)
- Decision and learnings

**For templates**: See [references/test-templates.md](references/test-templates.md)

---

## Growth Experimentation Program

Individual tests are valuable. A continuous experimentation program is a compounding asset. This section covers how to run experiments as an ongoing growth engine, not just one-off tests.

### The Experiment Loop

```
1. Generate hypotheses (from data, research, competitors, customer feedback)
2. Prioritize with ICE scoring
3. Design and run the test
4. Analyze results with statistical rigor
5. Promote winners to a playbook
6. Generate new hypotheses from learnings
→ Repeat
```

### Hypothesis Generation

Feed your experiment backlog from multiple sources:

| Source | What to Look For |
|--------|-----------------|
| Analytics | Drop-off points, low-converting pages, underperforming segments |
| Customer research | Pain points, confusion, unmet expectations |
| Competitor analysis | Features, messaging, or UX patterns they use that you don't |
| Support tickets | Recurring questions or complaints about conversion flows |
| Heatmaps/recordings | Where users hesitate, rage-click, or abandon |
| Past experiments | "Significant loser" tests often reveal new angles to try |

### ICE Prioritization

Score each hypothesis 1-10 on three dimensions:

| Dimension | Question |
|-----------|----------|
| **Impact** | If this works, how much will it move the primary metric? |
| **Confidence** | How sure are we this will work? (Based on data, not gut.) |
| **Ease** | How fast and cheap can we ship and measure this? |

**ICE Score** = (Impact + Confidence + Ease) / 3

Run highest-scoring experiments first. Re-score monthly as context changes.

### Experiment Velocity

Track your experimentation rate as a leading indicator of growth:

| Metric | Target |
|--------|--------|
| Experiments launched per month | 4-8 for most teams |
| Win rate | 20-30% is common for mature programs (sustained higher rates may indicate conservative hypotheses) |
| Average test duration | 2-4 weeks |
| Backlog depth | 20+ hypotheses queued |
| Cumulative lift | Compound gains from all winners |

### The Experiment Playbook

When a test wins, don't just implement it — document the pattern:

```
## [Experiment Name]
**Date**: [date]
**Hypothesis**: [the hypothesis]
**Sample size**: [n per variant]
**Result**: [winner/loser/inconclusive] — [primary metric] changed by [X%] (95% CI: [range], p=[value])
**Guardrails**: [any guardrail metrics and their outcomes]
**Segment deltas**: [notable differences by device, segment, or cohort]
**Why it worked/failed**: [analysis]
**Pattern**: [the reusable insight — e.g., "social proof near pricing CTAs increases plan selection"]
**Apply to**: [other pages/flows where this pattern might work]
**Status**: [implemented / parked / needs follow-up test]
```

Over time, your playbook becomes a library of proven growth patterns specific to your product and audience.

### Experiment Cadence

**Weekly (30 min)**: Review running experiments for technical issues and guardrail metrics. Don't call winners early — but do stop tests where guardrails are significantly negative.

**Bi-weekly**: Conclude completed experiments. Analyze results, update playbook, launch next experiment from backlog.

**Monthly (1 hour)**: Review experiment velocity, win rate, cumulative lift. Replenish hypothesis backlog. Re-prioritize with ICE.

**Quarterly**: Audit the playbook. Which patterns have been applied broadly? Which winning patterns haven't been scaled yet? What areas of the funnel are under-tested?

---

## Common Mistakes

### Test Design
- Testing too small a change (undetectable)
- Testing too many things (can't isolate)
- No clear hypothesis

### Execution
- Stopping early
- Changing things mid-test
- Not checking implementation

### Analysis
- Ignoring confidence intervals
- Cherry-picking segments
- Over-interpreting inconclusive results

---

## Task-Specific Questions

1. What's your current conversion rate?
2. How much traffic does this page get?
3. What change are you considering and why?
4. What's the smallest improvement worth detecting?
5. What tools do you have for testing?
6. Have you tested this area before?

---

## Related Skills

- **cro**: For generating test ideas based on CRO principles
- **analytics**: For setting up test measurement
- **copywriting**: For creating variant copy

## Limitations

- Use this skill only when the task clearly matches its upstream source and local project context.
- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.
- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.