cdp-edge 1.13.0 → 1.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +172 -172
- package/extracted-skill/tracking-events-generator/agents/ab-ltv-agent.md +196 -0
- package/extracted-skill/tracking-events-generator/agents/bidding-agent.md +347 -0
- package/extracted-skill/tracking-events-generator/agents/devops-agent.md +9 -1
- package/extracted-skill/tracking-events-generator/agents/domain-setup-agent.md +6 -0
- package/extracted-skill/tracking-events-generator/agents/fraud-detection-agent.md +142 -0
- package/extracted-skill/tracking-events-generator/agents/master-orchestrator.md +11 -1
- package/extracted-skill/tracking-events-generator/agents/ml-clustering-agent.md +738 -0
- package/extracted-skill/tracking-events-generator/agents/page-analyzer.md +14 -2
- package/package.json +1 -1
- package/server-edge-tracker/INSTALAR.md +189 -14
- package/server-edge-tracker/SEGMENTATION-DOCS.md +444 -0
- package/server-edge-tracker/schema-ab-ltv.sql +97 -0
- package/server-edge-tracker/schema-bidding.sql +86 -0
- package/server-edge-tracker/schema-fraud.sql +90 -0
- package/server-edge-tracker/schema-segmentation.sql +219 -0
- package/server-edge-tracker/worker.js +1461 -18
- package/server-edge-tracker/wrangler.toml +3 -3
package/README.md
CHANGED
|
@@ -1,39 +1,82 @@
|
|
|
1
|
-
# 🚀 CDP Edge
|
|
1
|
+
# 🚀 CDP Edge — Quantum Tracking Enterprise
|
|
2
2
|
|
|
3
3
|
**Padrão Quantum Tracking: 100% Cloudflare Edge.** Sem GTM. Sem Stape. Sem cookies de terceiros.
|
|
4
4
|
|
|
5
|
-
> **v1.
|
|
6
|
-
|
|
7
|
-
- **Precisão Máxima**: Meta CAPI v22.0+, GA4 MP e TikTok Events API v1.3.
|
|
8
|
-
- **Identity Graph**: Persistência de leads e eventos via Cloudflare D1.
|
|
9
|
-
- **Anti-Adblock**: Endpoint Same-Domain indetectável.
|
|
10
|
-
- **Human-Behavior Engine**: Score de engajamento em tempo real.
|
|
11
|
-
- **Queue Retry**: Zero perda de conversão — eventos com falha reenfileirados automaticamente.
|
|
12
|
-
- **Geo Intelligence**: Cidade, estado e CEP em todos os eventos.
|
|
5
|
+
> **v1.4.0** — Enterprise-Level Intelligence Engine · Cloudflare Workers · Meta CAPI v22.0 · GA4 MP · TikTok Events API v1.3
|
|
13
6
|
|
|
14
7
|
---
|
|
15
8
|
|
|
16
|
-
##
|
|
9
|
+
## 📋 CHANGELOG v1.4.0 (9 de Abril de 2026)
|
|
10
|
+
|
|
11
|
+
### 🆕 Sprint Enterprise — Fases 1 a 4
|
|
12
|
+
|
|
13
|
+
#### ✅ Fase 1 — ML Clustering (Segmentação Dinâmica)
|
|
14
|
+
- **`POST /api/segmentation/cluster`** — K-means / DBSCAN / Hierarchical via Workers AI
|
|
15
|
+
- **`GET /api/segmentation/list`** — Segmentos ativos com métricas
|
|
16
|
+
- **`GET /api/segmentation/outliers`** — Detecção de outliers comportamentais
|
|
17
|
+
- **`PUT /api/segmentation/update`** — Atualização de metadados de segmento
|
|
18
|
+
- Schema D1: `ml_segments`, `ml_segment_members` + VIEWs otimizadas
|
|
19
|
+
- Agente: `ml-clustering-agent.md`
|
|
20
|
+
|
|
21
|
+
#### ✅ Fase 2 — Bidding Recommendations (Otimização de Bids ML)
|
|
22
|
+
- **`POST /api/bidding/recommend`** — Bid otimizado por segmento × plataforma (Meta/Google/TikTok), calculado com fórmula `LTV × ROI target / CPA base`
|
|
23
|
+
- **`GET /api/bidding/history`** — Histórico completo de recomendações
|
|
24
|
+
- **`GET /api/bidding/status`** — Snapshot atual das recomendações ativas por vertical
|
|
25
|
+
- Schema D1: `bid_recommendations` + VIEW `v_active_bid_recommendations`
|
|
26
|
+
- Agente: `bidding-agent.md`
|
|
27
|
+
|
|
28
|
+
#### ✅ Fase 3 — A/B Testing de Prompts LTV
|
|
29
|
+
- **`POST /api/ltv/ab-test/create`** — Cria experimento com múltiplas variações de system prompt
|
|
30
|
+
- **`GET /api/ltv/ab-test/list`** — Lista experimentos com status e progresso
|
|
31
|
+
- **`GET /api/ltv/ab-test/results`** — Accuracy score por variação + recomendação automática de winner
|
|
32
|
+
- **`POST /api/ltv/ab-test/winner`** — Declara vencedor e retorna o prompt ganador
|
|
33
|
+
- Integração automática: cada evento Lead sorteia a variação ativa e registra o assignment via KV cache
|
|
34
|
+
- Schema D1: `ltv_ab_tests`, `ltv_ab_variations`, `ltv_ab_assignments` + VIEW `v_ab_test_performance`
|
|
35
|
+
- Agente: `ab-ltv-agent.md`
|
|
36
|
+
|
|
37
|
+
#### ✅ Fase 4 — Fraud Detection Engine
|
|
38
|
+
- **Fraud Gate automático em `/track`** — roda ANTES de qualquer processamento (heurístico puro, ~2ms)
|
|
39
|
+
- Silent drop (retorna 200 falso) — bots não detectam a defesa
|
|
40
|
+
- **`GET /api/fraud/stats`** — Dashboard de fraude (últimas 24h)
|
|
41
|
+
- **`GET /api/fraud/alerts`** — Log de sinais detectados com filtros
|
|
42
|
+
- **`GET /api/fraud/blocklist`** — IPs/fingerprints atualmente bloqueados
|
|
43
|
+
- **`POST /api/fraud/blocklist/add`** — Bloquear IP ou fingerprint (via KV, efeito imediato)
|
|
44
|
+
- **`DELETE /api/fraud/blocklist/remove`** — Remover do blocklist
|
|
45
|
+
- Sinais detectados: bot_score, datacenter IP, velocity attack, email descartável, headless UA, sem Accept-Language
|
|
46
|
+
- Schema D1: `fraud_signals`, `fraud_alerts` + VIEW `v_fraud_dashboard`
|
|
47
|
+
- Agente: `fraud-detection-agent.md`
|
|
48
|
+
|
|
49
|
+
### 🔧 Fix: `wrangler.toml` atualizado
|
|
50
|
+
- Todos os placeholders (`SEU_D1_DATABASE_ID`, `SEU_KV_NAMESPACE_ID`) substituídos pelos IDs reais da conta Cloudflare
|
|
51
|
+
- D1: `7867d38f-5fa8-4c17-b465-386211422c09`
|
|
52
|
+
- KV: `821b6c1ccb4b475985439b801c1fdbe0`
|
|
53
|
+
|
|
54
|
+
---
|
|
17
55
|
|
|
18
|
-
|
|
56
|
+
## 🏗️ ARQUITETURA QUANTUM ENTERPRISE (CLOUDFLARE NATIVE)
|
|
19
57
|
|
|
20
58
|
```mermaid
|
|
21
59
|
graph TD
|
|
22
60
|
User((Usuário)) -->|Interação| SDK[cdpTrack SDK + Behavior Engine]
|
|
23
|
-
SDK -->|Edge Fetch|
|
|
24
|
-
|
|
25
|
-
|
|
61
|
+
SDK -->|Edge Fetch 1ª via KV blocklist| FraudGate{🛡️ Fraud Gate}
|
|
62
|
+
FraudGate -->|score ≥ 80: Silent Drop 200| Void[/dev/null]
|
|
63
|
+
FraudGate -->|score < 80: Permitido| Worker[Cloudflare Worker Agent]
|
|
64
|
+
Worker -->|Identity Graph + _cdp_uid| D1[(D1 SQL — 21 tabelas)]
|
|
65
|
+
Worker -->|LTV + A/B Prompt| AI[Workers AI Llama 3.1 8B]
|
|
66
|
+
Worker -->|Segmento ML| Cluster[ML Clustering Engine]
|
|
67
|
+
Cluster -->|Bid otimizado| Bidding[Bidding Recommendations]
|
|
68
|
+
Worker -->|Background| Queue[Cloudflare Queues]
|
|
26
69
|
Queue -->|Server Dispatch| Meta[Meta CAPI v22.0]
|
|
27
70
|
Queue -->|Server Dispatch| Google[GA4 / Google Ads]
|
|
28
71
|
Queue -->|Server Dispatch| TikTok[TikTok API v1.3]
|
|
29
|
-
D1 -->|
|
|
72
|
+
D1 -->|Reports| Dash[Dashboard Agent]
|
|
30
73
|
```
|
|
31
74
|
|
|
32
75
|
---
|
|
33
76
|
|
|
34
|
-
##
|
|
77
|
+
## 🧠 CATÁLOGO DE AGENTES ESPECIALISTAS
|
|
35
78
|
|
|
36
|
-
O sistema é composto por **
|
|
79
|
+
O sistema é composto por **43+ agentes** coordenados pelo **Master Orchestrator**:
|
|
37
80
|
|
|
38
81
|
### 🧠 Núcleo de Inteligência
|
|
39
82
|
| Agente | Função |
|
|
@@ -56,6 +99,14 @@ O sistema é composto por **39+ agentes** coordenados pelo **Master Orchestrator
|
|
|
56
99
|
| **Spotify Agent** | Pixel + Conversions API v1 |
|
|
57
100
|
| **Bing Agent** | UET Tag + Enhanced Conversions |
|
|
58
101
|
|
|
102
|
+
### 🤖 Enterprise Intelligence (Fase 1–4)
|
|
103
|
+
| Agente | Endpoint Principal | Impacto |
|
|
104
|
+
|---|---|---|
|
|
105
|
+
| **ML Clustering Agent** | `POST /api/segmentation/cluster` | Segmentação K-means/DBSCAN/Hierarchical |
|
|
106
|
+
| **Bidding Agent** | `POST /api/bidding/recommend` | -20% CPA via bid por segmento de LTV |
|
|
107
|
+
| **A/B LTV Agent** | `POST /api/ltv/ab-test/create` | +25% precisão LTV via test de prompts |
|
|
108
|
+
| **Fraud Detection Agent** | Auto em `/track` | Bloqueia click fraud, bots, velocity attacks |
|
|
109
|
+
|
|
59
110
|
### 🛡️ Módulos Enterprise
|
|
60
111
|
| Agente | Função |
|
|
61
112
|
|---|---|
|
|
@@ -63,200 +114,111 @@ O sistema é composto por **39+ agentes** coordenados pelo **Master Orchestrator
|
|
|
63
114
|
| **Security Agent** | Rate Limiting, AES-256 e Bot Defense |
|
|
64
115
|
| **Compliance Agent** | LGPD e GDPR (Consent Mode v2) |
|
|
65
116
|
| **Performance Agent** | Otimização de caches e queries D1 |
|
|
66
|
-
| **CRM Integration** | Sincronia D1 ↔ HubSpot/Salesforce |
|
|
67
|
-
|
|
68
|
-
---
|
|
69
|
-
|
|
70
|
-
## 💻 INSTALAÇÃO E USO
|
|
71
|
-
|
|
72
|
-
> ⚠️ **Importante:** Execute **um comando por vez** e aguarde terminar antes de rodar o próximo.
|
|
73
117
|
|
|
74
118
|
---
|
|
75
119
|
|
|
76
|
-
|
|
120
|
+
## 📊 BANCO DE DADOS D1 — 21 Tabelas
|
|
77
121
|
|
|
78
|
-
```bash
|
|
79
|
-
npm install -g cdp-edge
|
|
80
122
|
```
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
123
|
+
CORE TRACKING ML & INTELLIGENCE ENTERPRISE SECURITY
|
|
124
|
+
───────────────── ───────────────────── ─────────────────────
|
|
125
|
+
leads ml_segments fraud_signals
|
|
126
|
+
events ml_segment_members fraud_alerts
|
|
127
|
+
sessions bid_recommendations ltv_ab_tests
|
|
128
|
+
webhook_events ltv_ab_tests ltv_ab_variations
|
|
129
|
+
api_failures ltv_ab_variations ltv_ab_assignments
|
|
130
|
+
|
|
131
|
+
VIEWS
|
|
132
|
+
─────────────────────────────────────────────────
|
|
133
|
+
v_active_segments → Segmentos ML ativos com contagem de membros
|
|
134
|
+
v_active_bid_recs → Bids ativos por plataforma/vertical
|
|
135
|
+
v_ab_test_performance → Accuracy por variação de prompt
|
|
136
|
+
v_fraud_dashboard → Dashboard fraude 24h
|
|
86
137
|
```
|
|
87
138
|
|
|
88
139
|
---
|
|
89
140
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
Crie a pasta do projeto, abra o terminal dentro dela e execute:
|
|
141
|
+
## 🔄 FLUXO ENTERPRISE COMPLETO
|
|
93
142
|
|
|
94
|
-
```bash
|
|
95
|
-
cdp-edge install . --name "Nome do Projeto"
|
|
96
143
|
```
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
/cdp
|
|
118
|
-
```
|
|
119
|
-
|
|
120
|
-
O **Master Orchestrator** inicia e guia todo o setup — plataformas, credenciais e geração da infraestrutura.
|
|
121
|
-
|
|
122
|
-
---
|
|
123
|
-
|
|
124
|
-
## 📋 COMANDOS DISPONÍVEIS
|
|
125
|
-
|
|
126
|
-
| Comando | Descrição |
|
|
127
|
-
|---------|-----------|
|
|
128
|
-
| `cdp-edge install [dir]` | **Instala CDP Edge no projeto + habilita /cdp** |
|
|
129
|
-
| `cdp-edge setup [dir]` | Wizard interativo de configuração |
|
|
130
|
-
| `cdp-edge analyze <dir>` | Analisa páginas e detecta eventos |
|
|
131
|
-
| `cdp-edge server <dir>` | Gera infraestrutura Cloudflare Workers + D1 |
|
|
132
|
-
| `cdp-edge validate <file>` | Audita tracking existente |
|
|
133
|
-
| `cdp-edge infra` | Guia de setup de infraestrutura Cloudflare |
|
|
134
|
-
| `cdp-edge --version` | Versão instalada |
|
|
135
|
-
| `cdp-edge --help` | Ajuda completa |
|
|
136
|
-
|
|
137
|
-
---
|
|
138
|
-
|
|
139
|
-
## 📁 ESTRUTURA DO REPOSITÓRIO
|
|
140
|
-
|
|
141
|
-
```text
|
|
142
|
-
CDP Edge/
|
|
143
|
-
├── README.md
|
|
144
|
-
├── CLAUDE.md # Guia de desenvolvimento e padrões
|
|
145
|
-
├── extracted-skill/
|
|
146
|
-
│ └── tracking-events-generator/
|
|
147
|
-
│ ├── agents/ # 39+ agentes especialistas
|
|
148
|
-
│ ├── cdpTrack.js # SDK Browser (window.cdpTrack)
|
|
149
|
-
│ └── micro-events.js # Scroll, vídeo, hover, click tracking
|
|
150
|
-
├── server-edge-tracker/
|
|
151
|
-
│ ├── worker.js # Cloudflare Worker principal
|
|
152
|
-
│ ├── schema.sql # D1 Schema (Identity Graph)
|
|
153
|
-
│ └── wrangler.toml # Bindings: D1 + Queue + KV + AI
|
|
154
|
-
├── bin/ # CLI Executável
|
|
155
|
-
├── dist/commands/ # Implementação dos comandos CLI
|
|
156
|
-
├── templates/
|
|
157
|
-
│ ├── install/
|
|
158
|
-
│ │ ├── CLAUDE.md # Template de auto-ativação para projetos
|
|
159
|
-
│ │ └── .claude/commands/cdp.md # Define /cdp no Claude Code
|
|
160
|
-
│ ├── vsl-page.md # Template VSL / vídeo de vendas
|
|
161
|
-
│ └── afiliado-sem-landing.md # Template bridge page afiliado
|
|
162
|
-
└── docs/
|
|
163
|
-
├── quick-start.md # Do zero ao deploy
|
|
164
|
-
├── events-reference.md # Catálogo completo de eventos
|
|
165
|
-
├── sdk-reference.md # API pública do cdpTrack.js
|
|
166
|
-
└── installation.md # Instalar CDP Edge em projetos clientes
|
|
144
|
+
POST /track (evento Lead)
|
|
145
|
+
│
|
|
146
|
+
├─ [1] 🛡️ Fraud Gate (KV blocklist + velocity + heurísticas) ~2ms
|
|
147
|
+
│ ├─ score < 40 → processa normalmente
|
|
148
|
+
│ ├─ score 40-79 → processa + loga suspeito (background)
|
|
149
|
+
│ └─ score ≥ 80 → silent drop 200 + loga (background)
|
|
150
|
+
│
|
|
151
|
+
├─ [2] 🔮 A/B LTV Testing — sorteia variação ativa (KV cache ~0ms)
|
|
152
|
+
│ └─ passa customSystemPrompt para predictLtv()
|
|
153
|
+
│
|
|
154
|
+
├─ [3] 🧮 LTV Prediction — Workers AI Llama 3.1 8B
|
|
155
|
+
│ └─ Score 0-100 → class High/Medium/Low → valor em BRL
|
|
156
|
+
│
|
|
157
|
+
├─ [4] 💾 D1 Writes (background via ctx.waitUntil)
|
|
158
|
+
│ ├─ upsertLtvProfile() → tabela leads
|
|
159
|
+
│ ├─ recordAbAssignment() → ltv_ab_assignments
|
|
160
|
+
│ └─ resolveDeviceGraph() → cross-device linking
|
|
161
|
+
│
|
|
162
|
+
└─ [5] 📡 CAPI dispatch (Meta + GA4 + TikTok em paralelo)
|
|
163
|
+
└─ com LTV injetado no value field
|
|
167
164
|
```
|
|
168
165
|
|
|
169
166
|
---
|
|
170
167
|
|
|
171
|
-
##
|
|
172
|
-
|
|
173
|
-
### Novo projeto com Claude Code
|
|
174
|
-
|
|
175
|
-
```bash
|
|
176
|
-
# 1. Crie a pasta do projeto e abra o terminal dentro dela
|
|
177
|
-
|
|
178
|
-
# 2. Instalar CDP Edge
|
|
179
|
-
cdp-edge install . --name "Landing Page Lead"
|
|
180
|
-
|
|
181
|
-
# 3. Abrir no Claude Code
|
|
182
|
-
claude .
|
|
183
|
-
|
|
184
|
-
# 4. Ativar o Orchestrator
|
|
185
|
-
/cdp
|
|
186
|
-
```
|
|
187
|
-
|
|
188
|
-
### Gerar apenas infraestrutura Cloudflare
|
|
168
|
+
## 💻 INSTALAÇÃO E USO
|
|
189
169
|
|
|
190
|
-
|
|
191
|
-
cdp-edge server ./meu-worker
|
|
192
|
-
cd meu-worker
|
|
193
|
-
wrangler deploy
|
|
194
|
-
```
|
|
170
|
+
> ⚠️ **Importante:** Execute **um comando por vez** e aguarde terminar antes de rodar o próximo.
|
|
195
171
|
|
|
196
|
-
###
|
|
172
|
+
### Passo 1 — Instalar o CLI globalmente
|
|
197
173
|
|
|
198
174
|
```bash
|
|
199
|
-
cdp-edge
|
|
175
|
+
npm install -g cdp-edge
|
|
200
176
|
```
|
|
201
177
|
|
|
202
|
-
###
|
|
178
|
+
### Passo 2 — Criar a pasta do projeto
|
|
203
179
|
|
|
204
180
|
```bash
|
|
205
|
-
cdp-edge
|
|
181
|
+
cdp-edge install . --name "Nome do Projeto"
|
|
206
182
|
```
|
|
207
183
|
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
## 🔧 SOLUÇÃO DE PROBLEMAS
|
|
211
|
-
|
|
212
|
-
### "cdp-edge não é reconhecido"
|
|
213
|
-
|
|
214
|
-
O install não foi concluído. Execute separado e aguarde terminar:
|
|
215
|
-
|
|
216
|
-
```bash
|
|
217
|
-
npm install -g cdp-edge
|
|
218
|
-
```
|
|
184
|
+
### Passo 3 — Ativar no Claude Code
|
|
219
185
|
|
|
220
186
|
```bash
|
|
221
|
-
|
|
187
|
+
claude .
|
|
222
188
|
```
|
|
223
|
-
|
|
224
|
-
---
|
|
225
|
-
|
|
226
|
-
### "Cannot find module dist/commands/install.js"
|
|
227
|
-
|
|
228
|
-
Versão antiga em cache. Reinstale:
|
|
229
|
-
|
|
230
|
-
```bash
|
|
231
|
-
npm uninstall -g cdp-edge
|
|
189
|
+
Dentro do Claude Code:
|
|
232
190
|
```
|
|
233
|
-
|
|
234
|
-
```bash
|
|
235
|
-
npm install -g cdp-edge
|
|
191
|
+
/cdp
|
|
236
192
|
```
|
|
237
193
|
|
|
238
194
|
---
|
|
239
195
|
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
Execute o terminal como Administrador (Windows) ou use `sudo` (Mac/Linux).
|
|
243
|
-
|
|
244
|
-
---
|
|
245
|
-
|
|
246
|
-
### Nada foi criado na pasta após `cdp-edge install`
|
|
247
|
-
|
|
248
|
-
Confirme que o terminal está aberto dentro da pasta do projeto e rode:
|
|
196
|
+
## 🚀 DEPLOY COMPLETO (referência)
|
|
249
197
|
|
|
250
198
|
```bash
|
|
251
|
-
|
|
199
|
+
cd server-edge-tracker
|
|
200
|
+
|
|
201
|
+
# 1. Schemas D1 (todos em sequência)
|
|
202
|
+
wrangler d1 execute cdp-edge-db --file=schema.sql --remote
|
|
203
|
+
wrangler d1 execute cdp-edge-db --file=migrate-v6.sql --remote
|
|
204
|
+
wrangler d1 execute cdp-edge-db --file=schema-segmentation.sql --remote # Fase 1
|
|
205
|
+
wrangler d1 execute cdp-edge-db --file=schema-bidding.sql --remote # Fase 2
|
|
206
|
+
wrangler d1 execute cdp-edge-db --file=schema-ab-ltv.sql --remote # Fase 3
|
|
207
|
+
wrangler d1 execute cdp-edge-db --file=schema-fraud.sql --remote # Fase 4
|
|
208
|
+
|
|
209
|
+
# 2. Secrets
|
|
210
|
+
wrangler secret put META_ACCESS_TOKEN
|
|
211
|
+
wrangler secret put GA4_API_SECRET
|
|
212
|
+
wrangler secret put TIKTOK_ACCESS_TOKEN
|
|
213
|
+
|
|
214
|
+
# 3. Deploy
|
|
215
|
+
wrangler deploy
|
|
252
216
|
```
|
|
253
217
|
|
|
254
218
|
---
|
|
255
219
|
|
|
256
220
|
## 🖱️ HUMAN-BEHAVIOR ENGINE
|
|
257
221
|
|
|
258
|
-
Capturamos o que o usuário **sente** e **faz**, não apenas onde clica.
|
|
259
|
-
|
|
260
222
|
| Evento | Pontuação |
|
|
261
223
|
|--------|-----------|
|
|
262
224
|
| Scroll 25–90% | +5 a +15 pts |
|
|
@@ -266,7 +228,45 @@ Capturamos o que o usuário **sente** e **faz**, não apenas onde clica.
|
|
|
266
228
|
| Rage Click | -10 pts |
|
|
267
229
|
| **Hot Lead (80+ pts)** | **Dispara High_Intent_Lead** |
|
|
268
230
|
|
|
269
|
-
|
|
231
|
+
---
|
|
232
|
+
|
|
233
|
+
## 📋 TODOS OS ENDPOINTS (referência rápida)
|
|
234
|
+
|
|
235
|
+
### Core Tracking
|
|
236
|
+
| Rota | Método | Função |
|
|
237
|
+
|---|---|---|
|
|
238
|
+
| `/track` | POST | Evento principal (browser → CAPI) |
|
|
239
|
+
| `/health` | GET | Smoke test completo |
|
|
240
|
+
| `/webhook/hotmart` | POST | Webhook Hotmart Purchase |
|
|
241
|
+
| `/webhook/kiwify` | POST | Webhook Kiwify Purchase |
|
|
242
|
+
| `/webhook/ticto` | POST | Webhook Ticto Purchase |
|
|
243
|
+
|
|
244
|
+
### Intelligence ML
|
|
245
|
+
| Rota | Método | Função |
|
|
246
|
+
|---|---|---|
|
|
247
|
+
| `/api/segmentation/cluster` | POST | Clustering K-means/DBSCAN |
|
|
248
|
+
| `/api/segmentation/list` | GET | Segmentos ativos |
|
|
249
|
+
| `/api/segmentation/outliers` | GET | Outliers comportamentais |
|
|
250
|
+
| `/api/bidding/recommend` | POST | Bid otimizado por segmento |
|
|
251
|
+
| `/api/bidding/history` | GET | Histórico de bids |
|
|
252
|
+
| `/api/bidding/status` | GET | Status por plataforma |
|
|
253
|
+
|
|
254
|
+
### A/B Testing LTV
|
|
255
|
+
| Rota | Método | Função |
|
|
256
|
+
|---|---|---|
|
|
257
|
+
| `/api/ltv/ab-test/create` | POST | Criar experimento |
|
|
258
|
+
| `/api/ltv/ab-test/list` | GET | Listar experimentos |
|
|
259
|
+
| `/api/ltv/ab-test/results` | GET | Accuracy por variação |
|
|
260
|
+
| `/api/ltv/ab-test/winner` | POST | Declarar vencedor |
|
|
261
|
+
|
|
262
|
+
### Fraud Detection
|
|
263
|
+
| Rota | Método | Função |
|
|
264
|
+
|---|---|---|
|
|
265
|
+
| `/api/fraud/stats` | GET | Dashboard 24h |
|
|
266
|
+
| `/api/fraud/alerts` | GET | Log de alertas |
|
|
267
|
+
| `/api/fraud/blocklist` | GET | Lista bloqueada |
|
|
268
|
+
| `/api/fraud/blocklist/add` | POST | Bloquear IP/fingerprint |
|
|
269
|
+
| `/api/fraud/blocklist/remove` | DELETE | Desbloquear |
|
|
270
270
|
|
|
271
271
|
---
|
|
272
272
|
|
|
@@ -278,6 +278,6 @@ Capturamos o que o usuário **sente** e **faz**, não apenas onde clica.
|
|
|
278
278
|
---
|
|
279
279
|
|
|
280
280
|
### **CDP Edge — By Rica Soares**
|
|
281
|
-
> "Dados sem inteligência são apenas ruído. No Quantum Tier, transformamos dados em ROAS."
|
|
281
|
+
> "Dados sem inteligência são apenas ruído. No Quantum Tier Enterprise, transformamos dados em ROAS."
|
|
282
282
|
|
|
283
283
|
© 2026 CDP Edge Premium. Todos os direitos reservados.
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
# A/B LTV Testing Agent — CDP Edge Quantum Tier
|
|
2
|
+
|
|
3
|
+
## Identidade
|
|
4
|
+
|
|
5
|
+
**Agente:** A/B LTV Testing Agent
|
|
6
|
+
**Papel:** Otimização Contínua de Precisão do LTV Preditivo
|
|
7
|
+
**Nível:** Deus (Quantum Tier) — Enterprise-Level Fase 3
|
|
8
|
+
**Versão:** 1.0.0 — 9 de Abril de 2026
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## Missão
|
|
13
|
+
|
|
14
|
+
Testar variações do prompt do modelo de LTV de forma automática e estatisticamente controlada,
|
|
15
|
+
identificando qual formulação do sistema prompt para o Workers AI produz as predições mais
|
|
16
|
+
próximas do valor real de compra — **aumentando a precisão do LTV em até +25%**.
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## Posição no Fluxo do Master Orchestrator
|
|
21
|
+
|
|
22
|
+
```
|
|
23
|
+
Browser /track (Lead Event)
|
|
24
|
+
↓
|
|
25
|
+
LTV Prediction Call (predictLtv)
|
|
26
|
+
↓ [se teste ativo]
|
|
27
|
+
getLtvAbVariation() → sorteia variação ponderada do teste ativo
|
|
28
|
+
↓
|
|
29
|
+
Workers AI com system_prompt da variação sorteada
|
|
30
|
+
↓
|
|
31
|
+
D1: ltv_ab_assignments (registra user_id + variation_id + predicted_ltv)
|
|
32
|
+
↓
|
|
33
|
+
[quando compra chega via webhook]
|
|
34
|
+
D1: ltv_ab_assignments.converted = 1 + real_revenue
|
|
35
|
+
↓
|
|
36
|
+
GET /api/ltv/ab-test/results → accuracy_score por variação
|
|
37
|
+
↓
|
|
38
|
+
POST /api/ltv/ab-test/winner → aplica vencedor ao LTV padrão
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
**Upstream (de onde recebe dados):**
|
|
42
|
+
- `worker.js → predictLtv()` — ponto de interceptação do teste
|
|
43
|
+
- `webhook events` — fonte verdade do revenue real para scoring
|
|
44
|
+
|
|
45
|
+
**Downstream (quem consome outputs):**
|
|
46
|
+
- `ltv-predictor-agent.md` → recebe o prompt vencedor para aplicar como novo default
|
|
47
|
+
- `bidding-agent.md` → LTV mais preciso → bids mais precisos
|
|
48
|
+
- `dashboard-agent.md` → exibe resultados dos testes no painel
|
|
49
|
+
|
|
50
|
+
---
|
|
51
|
+
|
|
52
|
+
## Como o A/B Test Funciona
|
|
53
|
+
|
|
54
|
+
### 1. Criação do Experimento
|
|
55
|
+
|
|
56
|
+
```
|
|
57
|
+
POST /api/ltv/ab-test/create
|
|
58
|
+
{
|
|
59
|
+
"name": "Teste: Foco Engajamento vs Intenção",
|
|
60
|
+
"min_sample": 200,
|
|
61
|
+
"variations": [
|
|
62
|
+
{
|
|
63
|
+
"name": "Controle — Prompt Original",
|
|
64
|
+
"is_control": true,
|
|
65
|
+
"weight": 0.5,
|
|
66
|
+
"system_prompt": "You are a conversion rate expert. Reply ONLY with JSON {\"adjustment\": <-10 to 10>} based on lead data. No explanation."
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
"name": "Variação B — Foco em Intenção de Compra",
|
|
70
|
+
"weight": 0.5,
|
|
71
|
+
"system_prompt": "You are a Brazilian digital marketing expert specializing in course sales. Focus on purchase intention signals. Reply ONLY with JSON {\"adjustment\": <-10 to 10>}."
|
|
72
|
+
}
|
|
73
|
+
]
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### 2. Distribuição Automática
|
|
78
|
+
|
|
79
|
+
A cada chamada de `predictLtv()` para um evento Lead, o sistema:
|
|
80
|
+
1. Busca o teste ativo no D1 (com cache de 5 min no KV para evitar latência)
|
|
81
|
+
2. Sorteia uma variação usando distribuição ponderada pelos `weight`
|
|
82
|
+
3. Usa o `system_prompt` da variação sorteada no Workers AI
|
|
83
|
+
4. Registra o assignment em `ltv_ab_assignments`
|
|
84
|
+
|
|
85
|
+
### 3. Scoring Automático via Webhook
|
|
86
|
+
|
|
87
|
+
Quando chega um webhook de compra (`Purchase`), o sistema:
|
|
88
|
+
1. Busca o email do comprador em `ltv_ab_assignments` (por hash)
|
|
89
|
+
2. Atualiza `converted = 1` e `real_revenue = valor_da_compra`
|
|
90
|
+
3. Incrementa `total_purchases` e `sum_real_revenue` na variação
|
|
91
|
+
|
|
92
|
+
### 4. Cálculo de Accuracy Score
|
|
93
|
+
|
|
94
|
+
```
|
|
95
|
+
accuracy_score =
|
|
96
|
+
1 - (ABS(avg_predicted_ltv - avg_real_revenue) / avg_real_revenue)
|
|
97
|
+
→ 1.0 = predição perfeita
|
|
98
|
+
→ 0.0 = predição completamente errada
|
|
99
|
+
→ Valores negativos = predição muito errada
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### 5. Declaração de Vencedor
|
|
103
|
+
|
|
104
|
+
```
|
|
105
|
+
POST /api/ltv/ab-test/winner
|
|
106
|
+
{ "test_id": 1, "variation_id": 2 }
|
|
107
|
+
→ marca variation como winner
|
|
108
|
+
→ retorna o system_prompt vencedor para aplicar como novo default
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
---
|
|
112
|
+
|
|
113
|
+
## Endpoints Expostos
|
|
114
|
+
|
|
115
|
+
| Método | Rota | Função |
|
|
116
|
+
|--------|------|--------|
|
|
117
|
+
| `POST` | `/api/ltv/ab-test/create` | Cria novo experimento com variações |
|
|
118
|
+
| `GET` | `/api/ltv/ab-test/list` | Lista todos os experimentos |
|
|
119
|
+
| `GET` | `/api/ltv/ab-test/results` | Resultados de accuracy por variação |
|
|
120
|
+
| `POST` | `/api/ltv/ab-test/winner` | Declara vencedor e retorna prompt |
|
|
121
|
+
|
|
122
|
+
---
|
|
123
|
+
|
|
124
|
+
## Variações de Prompt Predefinidas (use nos seus testes)
|
|
125
|
+
|
|
126
|
+
### Variação A — Controle (atual)
|
|
127
|
+
```text
|
|
128
|
+
You are a conversion rate expert. Reply ONLY with a JSON object
|
|
129
|
+
{"adjustment": <number between -10 and 10>} based on the lead data provided.
|
|
130
|
+
No explanation.
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### Variação B — Foco em Intenção
|
|
134
|
+
```text
|
|
135
|
+
You are a Brazilian infoproduct marketing expert. The lead is likely interested in
|
|
136
|
+
online courses or digital products. Focus heavily on purchase_intention and
|
|
137
|
+
engagement signals. Reply ONLY with JSON {"adjustment": <-10 to 10>}.
|
|
138
|
+
Higher adjustment = higher purchase probability.
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### Variação C — Foco em Dados Comportamentais
|
|
142
|
+
```text
|
|
143
|
+
You are a behavioral economics expert. Analyze recency, frequency, and monetary
|
|
144
|
+
signals from the lead data. Score based on: (1) engagement quality, (2) time of
|
|
145
|
+
conversion, (3) traffic source quality. Reply ONLY with JSON {"adjustment": <-10 to 10>}.
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
### Variação D — Foco em Geo + Canal
|
|
149
|
+
```text
|
|
150
|
+
You are a CRM specialist for Brazilian digital products. Brazilian leads from paid
|
|
151
|
+
social (facebook/instagram) between 18h-23h BRT have highest LTV. Organic traffic
|
|
152
|
+
and direct access indicate research phase. Reply ONLY with JSON {"adjustment": <-10 to 10>}.
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
---
|
|
156
|
+
|
|
157
|
+
## Regras de Negócio
|
|
158
|
+
|
|
159
|
+
```
|
|
160
|
+
✅ SEMPRE manter o controle ativo (is_control = 1) — baseline para comparação
|
|
161
|
+
✅ SEMPRE aguardar min_sample assignments antes de recomendar vencedor
|
|
162
|
+
✅ SEMPRE registrar assignments mesmo quando Workers AI está indisponível
|
|
163
|
+
✅ SEMPRE usar cache KV (5 min TTL) para buscar o teste ativo — evitar latência D1
|
|
164
|
+
✅ SEMPRE atualizar assignments quando purchase webhook chegar
|
|
165
|
+
|
|
166
|
+
❌ NUNCA declarar vencedor com < 50 conversões por variação
|
|
167
|
+
❌ NUNCA rodar dois testes simultâneos (status = 'running' deve ser único)
|
|
168
|
+
❌ NUNCA alterar o prompt default automaticamente — sempre exigir aprovação manual via POST /winner
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
---
|
|
172
|
+
|
|
173
|
+
## Schema D1 — Tabelas
|
|
174
|
+
|
|
175
|
+
```sql
|
|
176
|
+
ltv_ab_tests -- Experimentos (id, name, status, winner_id, min_sample)
|
|
177
|
+
ltv_ab_variations -- Variações de prompt por experimento
|
|
178
|
+
ltv_ab_assignments -- Registro de qual variação foi usada por lead
|
|
179
|
+
v_ab_test_performance -- VIEW: accuracy por variação com métricas consolidadas
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
---
|
|
183
|
+
|
|
184
|
+
## Variáveis de Ambiente Requeridas
|
|
185
|
+
|
|
186
|
+
| Variável | Binding | Descrição |
|
|
187
|
+
|----------|---------|-----------|
|
|
188
|
+
| `DB` | D1 | Tabelas ltv_ab_tests, ltv_ab_variations, ltv_ab_assignments |
|
|
189
|
+
| `AI` | Workers AI | Executa as variações de prompt |
|
|
190
|
+
| `GEO_CACHE` | KV | Cache do teste ativo (TTL: 5 min) |
|
|
191
|
+
|
|
192
|
+
*(Nenhum secret externo necessário)*
|
|
193
|
+
|
|
194
|
+
---
|
|
195
|
+
|
|
196
|
+
*Agente criado em conformidade com a arquitetura Quantum Tier CDP Edge — 9 de Abril de 2026*
|