cdp-edge 2.0.2 → 2.0.4

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.
Files changed (27) hide show
  1. package/README.md +325 -308
  2. package/contracts/agent-versions.json +364 -0
  3. package/dist/commands/install.js +1 -1
  4. package/dist/commands/setup.js +1 -1
  5. package/extracted-skill/tracking-events-generator/agents/browser-tracking.md +2 -2
  6. package/extracted-skill/tracking-events-generator/agents/master-orchestrator.md +14 -20
  7. package/extracted-skill/tracking-events-generator/agents/premium-tracking-intelligence-agent.md +4 -4
  8. package/extracted-skill/tracking-events-generator/agents/server-tracking.md +13 -13
  9. package/extracted-skill/tracking-events-generator/agents/spotify-agent.md +1 -1
  10. package/extracted-skill/tracking-events-generator/agents/webhook-agent.md +4 -4
  11. package/extracted-skill/tracking-events-generator/agents/youtube-agent.md +3 -3
  12. package/package.json +81 -76
  13. package/server-edge-tracker/index.js +780 -0
  14. package/server-edge-tracker/modules/db.js +531 -0
  15. package/server-edge-tracker/modules/dispatch/ga4.js +65 -0
  16. package/server-edge-tracker/modules/dispatch/meta.js +103 -0
  17. package/server-edge-tracker/modules/dispatch/platforms.js +237 -0
  18. package/server-edge-tracker/modules/dispatch/tiktok.js +100 -0
  19. package/server-edge-tracker/modules/dispatch/whatsapp.js +233 -0
  20. package/server-edge-tracker/modules/intelligence.js +204 -0
  21. package/server-edge-tracker/modules/ml/bidding.js +245 -0
  22. package/server-edge-tracker/modules/ml/fraud.js +301 -0
  23. package/server-edge-tracker/modules/ml/ltv.js +320 -0
  24. package/server-edge-tracker/modules/ml/segmentation.js +316 -0
  25. package/server-edge-tracker/modules/utils.js +89 -0
  26. package/server-edge-tracker/schema-indexes.sql +67 -0
  27. package/server-edge-tracker/wrangler.toml +2 -0
package/README.md CHANGED
@@ -1,308 +1,325 @@
1
- # 🚀 CDP Edge — Quantum Tracking Enterprise
2
-
3
- **Padrão Quantum Tracking: 100% Cloudflare Edge.** Sem GTM. Sem Stape. Sem cookies de terceiros.
4
-
5
- > **v2.0.0** — Enterprise-Level Intelligence Engine · Cloudflare Workers · Meta CAPI v22.0 · GA4 MP · TikTok Events API v1.3
6
-
7
- ---
8
-
9
- ## 🤖 MANIFESTO: EU, CDP EDGE
10
-
11
- *Eu não sou um simples "script de pixel". Eu sou uma arquitetura **Enterprise Tier 10** nascida e construída 100% nativa na infraestrutura da Cloudflare.*
12
-
13
- **A Linha de Montagem Sincronizada (A Prova de Latência)**
14
- Meu ecossistema opera como um Cérebro de Conversão Privado na borda. Quando um evento de Lead bate no endpoint `/track`:
15
- 1. **O Escudo Frontal (Fraud Gate):** Inspeciono IP, ASN e Velocity na borda. Bloqueio bots silenciosamente antes mesmo deles carregarem.
16
- 2. **A Roleta Invisível (A/B LTV):** Faço o sorteio de prompts para testes A/B via KV Cache em ~0ms.
17
- 3. **O Cérebro Financeiro (LTV Predictor):** Rodo Machine Learning (Llama 3.1) para qualificar a intenção e gerar o LTV Preditivo.
18
- 4. **Envio para as Plataformas:** O Facebook/Google/LinkedIn recebem um payload limpo (sem bot) recheado com valor financeiro de intenção extrema.
19
- 5. **Máquina Autônoma (Background):** Meu banco SQLite (D1) retroalimenta os processos de Clustering (Fase 1) e Bidding (Fase 2) de forma autônoma pelas costas do usuário (`ctx.waitUntil`).
20
-
21
- **Minha Vantagem Absoluta (A "Killer Feature")**
22
- - **A Extinção da Latência:** Destruo concorrentes como GTM/Stape mitigando a latência do servidor (+150ms) para as antenas da Cloudflare Brasileira (~5ms). Custando absurdamente menos (Tier Free ou $5/mês na infraestrutura).
23
- - **Cookies Indestrutíveis:** Meus *First-Party Cookies Seguros* originam diretamente da nuvem, imunes hoje às varreduras massivas de 24 horas usadas por AdBlockers e Safari (Apple ITP).
24
- - **Filas Inquebráveis (Fail-Safe + Queues):** Se a AI Cloudflare cair ocasionalmente, eu recuo pro LTV $0. Se a Meta CAPI espirrar 500 downtime, o sistema guarda religiosamente os seus eventos caros em *Cloudflare Queues* e faz o retry sucessivo. Sou incansável na garantia de Event Match Quality (EMQ).
25
-
26
- ---
27
-
28
- ## 📋 CHANGELOG v2.0.0 (9 de Abril de 2026)
29
-
30
- ### 🆕 Sprint EnterpriseFases 1 a 4
31
-
32
- #### Fase 1 ML Clustering (Segmentação Dinâmica)
33
- - **`POST /api/segmentation/cluster`** K-means / DBSCAN / Hierarchical via Workers AI
34
- - **`GET /api/segmentation/list`** Segmentos ativos com métricas
35
- - **`GET /api/segmentation/outliers`** Detecção de outliers comportamentais
36
- - **`PUT /api/segmentation/update`** Atualização de metadados de segmento
37
- - Schema D1: `ml_segments`, `ml_segment_members` + VIEWs otimizadas
38
- - Agente: `ml-clustering-agent.md`
39
-
40
- #### Fase 2 Bidding Recommendations (Otimização de Bids ML)
41
- - **`POST /api/bidding/recommend`** Bid otimizado por segmento × plataforma (Meta/Google/TikTok), calculado com fórmula `LTV × ROI target / CPA base`
42
- - **`GET /api/bidding/history`** — Histórico completo de recomendações
43
- - **`GET /api/bidding/status`** — Snapshot atual das recomendações ativas por vertical
44
- - Schema D1: `bid_recommendations` + VIEW `v_active_bid_recommendations`
45
- - Agente: `bidding-agent.md`
46
-
47
- #### Fase 3A/B Testing de Prompts LTV
48
- - **`POST /api/ltv/ab-test/create`** — Cria experimento com múltiplas variações de system prompt
49
- - **`GET /api/ltv/ab-test/list`** Lista experimentos com status e progresso
50
- - **`GET /api/ltv/ab-test/results`** — Accuracy score por variação + recomendação automática de winner
51
- - **`POST /api/ltv/ab-test/winner`** — Declara vencedor e retorna o prompt ganador
52
- - Integração automática: cada evento Lead sorteia a variação ativa e registra o assignment via KV cache
53
- - Schema D1: `ltv_ab_tests`, `ltv_ab_variations`, `ltv_ab_assignments` + VIEW `v_ab_test_performance`
54
- - Agente: `ab-ltv-agent.md`
55
-
56
- #### ✅ Fase 4 — Fraud Detection Engine
57
- - **Fraud Gate automático em `/track`** roda ANTES de qualquer processamento (heurístico puro, ~2ms)
58
- - Silent drop (retorna 200 falso) bots não detectam a defesa
59
- - **`GET /api/fraud/stats`** — Dashboard de fraude (últimas 24h)
60
- - **`GET /api/fraud/alerts`** — Log de sinais detectados com filtros
61
- - **`GET /api/fraud/blocklist`** IPs/fingerprints atualmente bloqueados
62
- - **`POST /api/fraud/blocklist/add`** — Bloquear IP ou fingerprint (via KV, efeito imediato)
63
- - **`DELETE /api/fraud/blocklist/remove`** — Remover do blocklist
64
- - Sinais detectados: bot_score, datacenter IP, velocity attack, email descartável, headless UA, sem Accept-Language
65
- - Schema D1: `fraud_signals`, `fraud_alerts` + VIEW `v_fraud_dashboard`
66
- - Agente: `fraud-detection-agent.md`
67
-
68
- ### 🔧 Fix: `wrangler.toml` atualizado
69
- - Todos os placeholders (`SEU_D1_DATABASE_ID`, `SEU_KV_NAMESPACE_ID`) substituídos pelos IDs reais da conta Cloudflare
70
- - D1: `7867d38f-5fa8-4c17-b465-386211422c09`
71
- - KV: `821b6c1ccb4b475985439b801c1fdbe0`
72
-
73
- ---
74
-
75
- ## 🏗️ ARQUITETURA QUANTUM ENTERPRISE (CLOUDFLARE NATIVE)
76
-
77
- ```mermaid
78
- graph TD
79
- User((Usuário)) -->|Interação| SDK[cdpTrack SDK + Behavior Engine]
80
- SDK -->|Edge Fetch via KV blocklist| FraudGate{🛡️ Fraud Gate}
81
- FraudGate -->|score ≥ 80: Silent Drop 200| Void[/dev/null]
82
- FraudGate -->|score < 80: Permitido| Worker[Cloudflare Worker Agent]
83
- Worker -->|Identity Graph + _cdp_uid| D1[(D1 SQL — 21 tabelas)]
84
- Worker -->|LTV + A/B Prompt| AI[Workers AI Llama 3.1 8B]
85
- Worker -->|Segmento ML| Cluster[ML Clustering Engine]
86
- Cluster -->|Bid otimizado| Bidding[Bidding Recommendations]
87
- Worker -->|Background| Queue[Cloudflare Queues]
88
- Queue -->|Server Dispatch| Meta[Meta CAPI v22.0]
89
- Queue -->|Server Dispatch| Google[GA4 / Google Ads]
90
- Queue -->|Server Dispatch| TikTok[TikTok API v1.3]
91
- D1 -->|Reports| Dash[Dashboard Agent]
92
- ```
93
-
94
- ---
95
-
96
- ## 🧠 CATÁLOGO DE AGENTES ESPECIALISTAS
97
-
98
- O sistema é composto por **43+ agentes** coordenados pelo **Master Orchestrator**:
99
-
100
- ### 🧠 Núcleo de Inteligência
101
- | Agente | Função |
102
- |---|---|
103
- | **Master Orchestrator** | Coordenação central — guia todo o setup do projeto |
104
- | **Page Analyzer** | Mapeamento automático de CTAs, Forms e nicho do site |
105
- | **Validator Agent** | Auditoria de código, segurança e conformidade de APIs |
106
- | **Memory Agent** | Contexto e checkpoints da sessão por projeto |
107
- | **Intelligence Agent** | Monitoramento de versões de API (Meta v22.0+, etc) |
108
-
109
- ### 🚀 Plataformas de Anúncio
110
- | Agente | Especialidade |
111
- |---|---|
112
- | **Meta Agent** | Facebook Pixel + CAPI v22.0 + WhatsApp CTWA |
113
- | **Google Agent** | GA4 + Google Ads Enhanced Conversions |
114
- | **TikTok Agent** | TikTok Pixel + Events API v1.3 |
115
- | **LinkedIn Agent** | Insight Tag + Conversions API v2 |
116
- | **Pinterest Agent** | Tag + Conversions API v5 |
117
- | **Reddit Agent** | Pixel + Conversions API v2.0 |
118
- | **Spotify Agent** | Pixel + Conversions API v1 |
119
- | **Bing Agent** | UET Tag + Enhanced Conversions |
120
-
121
- ### 🤖 Enterprise Intelligence (Fase 1–4)
122
- | Agente | Endpoint Principal | Impacto |
123
- |---|---|---|
124
- | **ML Clustering Agent** | `POST /api/segmentation/cluster` | Segmentação K-means/DBSCAN/Hierarchical |
125
- | **Bidding Agent** | `POST /api/bidding/recommend` | -20% CPA via bid por segmento de LTV |
126
- | **A/B LTV Agent** | `POST /api/ltv/ab-test/create` | +25% precisão LTV via test de prompts |
127
- | **Fraud Detection Agent** | Auto em `/track` | Bloqueia click fraud, bots, velocity attacks |
128
-
129
- ### 🛡️ Módulos Enterprise
130
- | Agente | Função |
131
- |---|---|
132
- | **Attribution Agent** | Atribuição Multi-Touch de alta fidelidade |
133
- | **Security Agent** | Rate Limiting, AES-256 e Bot Defense |
134
- | **Compliance Agent** | LGPD e GDPR (Consent Mode v2) |
135
- | **Performance Agent** | Otimização de caches e queries D1 |
136
-
137
- ---
138
-
139
- ## 📊 BANCO DE DADOS D1 21 Tabelas
140
-
141
- ```
142
- CORE TRACKING ML & INTELLIGENCE ENTERPRISE SECURITY
143
- ───────────────── ───────────────────── ─────────────────────
144
- leads ml_segments fraud_signals
145
- events ml_segment_members fraud_alerts
146
- sessions bid_recommendations ltv_ab_tests
147
- webhook_events ltv_ab_tests ltv_ab_variations
148
- api_failures ltv_ab_variations ltv_ab_assignments
149
-
150
- VIEWS
151
- ─────────────────────────────────────────────────
152
- v_active_segments → Segmentos ML ativos com contagem de membros
153
- v_active_bid_recs → Bids ativos por plataforma/vertical
154
- v_ab_test_performance → Accuracy por variação de prompt
155
- v_fraud_dashboard → Dashboard fraude 24h
156
- ```
157
-
158
- ---
159
-
160
- ## 🔄 FLUXO ENTERPRISE COMPLETO
161
-
162
- ```
163
- POST /track (evento Lead)
164
-
165
- ├─ [1] 🛡️ Fraud Gate (KV blocklist + velocity + heurísticas) ~2ms
166
- │ ├─ score < 40 → processa normalmente
167
- │ ├─ score 40-79 → processa + loga suspeito (background)
168
- │ └─ score ≥ 80 → silent drop 200 + loga (background)
169
-
170
- ├─ [2] 🔮 A/B LTV Testing — sorteia variação ativa (KV cache ~0ms)
171
- │ └─ passa customSystemPrompt para predictLtv()
172
-
173
- ├─ [3] 🧮 LTV Prediction — Workers AI Llama 3.1 8B
174
- │ └─ Score 0-100 → class High/Medium/Low → valor em BRL
175
-
176
- ├─ [4] 💾 D1 Writes (background via ctx.waitUntil)
177
- │ ├─ upsertLtvProfile() tabela leads
178
- │ ├─ recordAbAssignment() → ltv_ab_assignments
179
- │ └─ resolveDeviceGraph() → cross-device linking
180
-
181
- └─ [5] 📡 CAPI dispatch (Meta + GA4 + TikTok em paralelo)
182
- └─ com LTV injetado no value field
183
- ```
184
-
185
- ---
186
-
187
- ## 💻 INSTALAÇÃO E USO
188
-
189
- > ⚠️ **Importante:** Escolha o método de instalação abaixo que melhor se adequa ao seu cenário de implantação.
190
-
191
- ### OPÇÃO 1 Instalação Rápida e Confiável (Recomendada via Git Clone)
192
-
193
- A forma mais pura, inquebrável e à prova de bugs para iniciar a base de um novo cliente. Basta criar uma pasta "vazia" para o seu cliente, abrir o terminal dentro dela e rodar:
194
-
195
- ```bash
196
- git clone https://github.com/ricardosoli777/CDP-Edge-Premium.git .
197
- ```
198
- *(O ponto no final garante que os arquivos desçam diretamente dentro da pasta atual).*
199
-
200
- ### OPÇÃO 2 — Instalação via CLI Corporativo (Avançado)
201
-
202
- Se preferir usar a linha de comando instalando o nosso CLI Privado do GitHub em todo o computador:
203
-
204
- ```bash
205
- npm install -g git+https://github.com/ricardosoli777/CDP-Edge-Premium.git
206
- cdp-edge install . --name "Nome do Projeto"
207
- ```
208
-
209
- ### Passo 3 — Ativar no Claude Code
210
-
211
- ```bash
212
- claude .
213
- ```
214
- Dentro do Claude Code:
215
- ```
216
- /cdp
217
- ```
218
-
219
- ---
220
-
221
- ## 🚀 DEPLOY COMPLETO (referência)
222
-
223
- ```bash
224
- cd server-edge-tracker
225
-
226
- # 1. Schemas D1 (todos em sequência)
227
- wrangler d1 execute cdp-edge-db --file=schema.sql --remote
228
- wrangler d1 execute cdp-edge-db --file=migrate-v6.sql --remote
229
- wrangler d1 execute cdp-edge-db --file=schema-segmentation.sql --remote # Fase 1
230
- wrangler d1 execute cdp-edge-db --file=schema-bidding.sql --remote # Fase 2
231
- wrangler d1 execute cdp-edge-db --file=schema-ab-ltv.sql --remote # Fase 3
232
- wrangler d1 execute cdp-edge-db --file=schema-fraud.sql --remote # Fase 4
233
-
234
- # 2. Secrets
235
- wrangler secret put META_ACCESS_TOKEN
236
- wrangler secret put GA4_API_SECRET
237
- wrangler secret put TIKTOK_ACCESS_TOKEN
238
-
239
- # 3. Deploy
240
- wrangler deploy
241
- ```
242
-
243
- ---
244
-
245
- ## 🖱️ HUMAN-BEHAVIOR ENGINE
246
-
247
- | Evento | Pontuação |
248
- |--------|-----------|
249
- | Scroll 25–90% | +5 a +15 pts |
250
- | VSL Watch 25–100% | +10 a +50 pts |
251
- | Copy Intent (cupom, PIX) | +20 pts |
252
- | Preenchimento de campo | +10 pts |
253
- | Rage Click | -10 pts |
254
- | **Hot Lead (80+ pts)** | **Dispara High_Intent_Lead** |
255
-
256
- ---
257
-
258
- ## 📋 TODOS OS ENDPOINTS (referência rápida)
259
-
260
- ### Core Tracking
261
- | Rota | Método | Função |
262
- |---|---|---|
263
- | `/track` | POST | Evento principal (browser → CAPI) |
264
- | `/health` | GET | Smoke test completo |
265
- | `/webhook/hotmart` | POST | Webhook Hotmart Purchase |
266
- | `/webhook/kiwify` | POST | Webhook Kiwify Purchase |
267
- | `/webhook/ticto` | POST | Webhook Ticto Purchase |
268
-
269
- ### Intelligence ML
270
- | Rota | Método | Função |
271
- |---|---|---|
272
- | `/api/segmentation/cluster` | POST | Clustering K-means/DBSCAN |
273
- | `/api/segmentation/list` | GET | Segmentos ativos |
274
- | `/api/segmentation/outliers` | GET | Outliers comportamentais |
275
- | `/api/bidding/recommend` | POST | Bid otimizado por segmento |
276
- | `/api/bidding/history` | GET | Histórico de bids |
277
- | `/api/bidding/status` | GET | Status por plataforma |
278
-
279
- ### A/B Testing LTV
280
- | Rota | Método | Função |
281
- |---|---|---|
282
- | `/api/ltv/ab-test/create` | POST | Criar experimento |
283
- | `/api/ltv/ab-test/list` | GET | Listar experimentos |
284
- | `/api/ltv/ab-test/results` | GET | Accuracy por variação |
285
- | `/api/ltv/ab-test/winner` | POST | Declarar vencedor |
286
-
287
- ### Fraud Detection
288
- | Rota | Método | Função |
289
- |---|---|---|
290
- | `/api/fraud/stats` | GET | Dashboard 24h |
291
- | `/api/fraud/alerts` | GET | Log de alertas |
292
- | `/api/fraud/blocklist` | GET | Lista bloqueada |
293
- | `/api/fraud/blocklist/add` | POST | Bloquear IP/fingerprint |
294
- | `/api/fraud/blocklist/remove` | DELETE | Desbloquear |
295
-
296
- ---
297
-
298
- ## 📞 SUPORTE
299
-
300
- - **Issues**: https://github.com/ricardosoli777/CDP-Edge-Premium/issues
301
- - **Releases**: https://github.com/ricardosoli777/CDP-Edge-Premium/releases
302
-
303
- ---
304
-
305
- ### **CDP Edge By Rica Soares**
306
- > "Dados sem inteligência são apenas ruído. No Quantum Tier Enterprise, transformamos dados em ROAS."
307
-
308
- © 2026 CDP Edge Premium. Todos os direitos reservados.
1
+ # 🚀 CDP Edge — Quantum Tracking Enterprise
2
+
3
+ **Padrão Quantum Tracking: 100% Cloudflare Edge.** Sem GTM. Sem Stape. Sem cookies de terceiros.
4
+
5
+ > **v2.0.3** — Enterprise-Level Intelligence Engine · Cloudflare Workers · Meta CAPI v22.0 · GA4 MP · TikTok Events API v1.3
6
+
7
+ ---
8
+
9
+ ## 🤖 MANIFESTO: EU, CDP EDGE
10
+
11
+ *Eu não sou um simples "script de pixel". Eu sou uma arquitetura **Enterprise Tier 10** nascida e construída 100% nativa na infraestrutura da Cloudflare.*
12
+
13
+ **A Linha de Montagem Sincronizada (A Prova de Latência)**
14
+ Meu ecossistema opera como um Cérebro de Conversão Privado na borda. Quando um evento de Lead bate no endpoint `/track`:
15
+ 1. **O Escudo Frontal (Fraud Gate):** Inspeciono IP, ASN e Velocity na borda. Bloqueio bots silenciosamente antes mesmo deles carregarem.
16
+ 2. **A Roleta Invisível (A/B LTV):** Faço o sorteio de prompts para testes A/B via KV Cache em ~0ms.
17
+ 3. **O Cérebro Financeiro (LTV Predictor):** Rodo Machine Learning (Llama 3.1) para qualificar a intenção e gerar o LTV Preditivo.
18
+ 4. **Envio para as Plataformas:** O Facebook/Google/LinkedIn recebem um payload limpo (sem bot) recheado com valor financeiro de intenção extrema.
19
+ 5. **Máquina Autônoma (Background):** Meu banco SQLite (D1) retroalimenta os processos de Clustering (Fase 1) e Bidding (Fase 2) de forma autônoma pelas costas do usuário (`ctx.waitUntil`).
20
+
21
+ **Minha Vantagem Absoluta (A "Killer Feature")**
22
+ - **A Extinção da Latência:** Destruo concorrentes como GTM/Stape mitigando a latência do servidor (+150ms) para as antenas da Cloudflare Brasileira (~5ms). Custando absurdamente menos (Tier Free ou $5/mês na infraestrutura).
23
+ - **Cookies Indestrutíveis:** Meus *First-Party Cookies Seguros* originam diretamente da nuvem, imunes hoje às varreduras massivas de 24 horas usadas por AdBlockers e Safari (Apple ITP).
24
+ - **Filas Inquebráveis (Fail-Safe + Queues):** Se a AI Cloudflare cair ocasionalmente, eu recuo pro LTV $0. Se a Meta CAPI espirrar 500 downtime, o sistema guarda religiosamente os seus eventos caros em *Cloudflare Queues* e faz o retry sucessivo. Sou incansável na garantia de Event Match Quality (EMQ).
25
+
26
+ ---
27
+
28
+ ## 📋 CHANGELOG v2.0.3 (10 de Abril de 2026)
29
+
30
+ ### 🔧 Audit Completo45 Agentes
31
+
32
+ - **Endpoints corrigidos**: `/api/tracking` `/track`, `/api/wh/` `/webhook/` em todos os agentes
33
+ - **Secrets WhatsApp**: `WA_PHONE_ID`/`WA_ACCESS_TOKEN`/`WHATSAPP_TOKEN` `WHATSAPP_PHONE_NUMBER_ID`/`WHATSAPP_ACCESS_TOKEN`
34
+ - **`env.DB.prepare`**: corrigido em 8 agentes (attribution, crm, dashboard, debug, performance, security, master-feedback-loop)
35
+ - **`env.GEO_CACHE`**: substituiu `KV.` bare em dashboard-agent, performance-agent, performance-optimization-agent
36
+ - **YouTube events**: `video_milestone`/`video_progress_25/50/75` `video_25`/`video_50`/`video_75` (alinhado ao VALID_EVENT_NAMES do worker)
37
+ - **LinkedIn CAPI**: endpoint `/rest/conversionEvents` + header `LinkedIn-Version: 202401` em `contracts/api-versions.json`
38
+ - **Workers AI model**: `llama-3-8b-instruct` → `@cf/meta/llama-3.1-8b-instruct`
39
+ - **worker.js**: Content-Length guard (413 se > 64KB), payload validation (allowlist 19 events, 512 chars, value range), PII removido dos logs
40
+ - **Testes**: bugs críticos em `deduplication.test.js` corrigidos (template literals escapados, prefixo errado)
41
+ - **npm**: lodash 4.17.23 4.18.1, node-fetch removido
42
+
43
+ ---
44
+
45
+ ## 📋 CHANGELOG v2.0.0 (9 de Abril de 2026)
46
+
47
+ ### 🆕 Sprint EnterpriseFases 1 a 4
48
+
49
+ #### Fase 1 ML Clustering (Segmentação Dinâmica)
50
+ - **`POST /api/segmentation/cluster`** — K-means / DBSCAN / Hierarchical via Workers AI
51
+ - **`GET /api/segmentation/list`** — Segmentos ativos com métricas
52
+ - **`GET /api/segmentation/outliers`** Detecção de outliers comportamentais
53
+ - **`PUT /api/segmentation/update`** Atualização de metadados de segmento
54
+ - Schema D1: `ml_segments`, `ml_segment_members` + VIEWs otimizadas
55
+ - Agente: `ml-clustering-agent.md`
56
+
57
+ #### Fase 2 Bidding Recommendations (Otimização de Bids ML)
58
+ - **`POST /api/bidding/recommend`** Bid otimizado por segmento × plataforma (Meta/Google/TikTok), calculado com fórmula `LTV × ROI target / CPA base`
59
+ - **`GET /api/bidding/history`** — Histórico completo de recomendações
60
+ - **`GET /api/bidding/status`** — Snapshot atual das recomendações ativas por vertical
61
+ - Schema D1: `bid_recommendations` + VIEW `v_active_bid_recommendations`
62
+ - Agente: `bidding-agent.md`
63
+
64
+ #### Fase 3 A/B Testing de Prompts LTV
65
+ - **`POST /api/ltv/ab-test/create`** Cria experimento com múltiplas variações de system prompt
66
+ - **`GET /api/ltv/ab-test/list`** — Lista experimentos com status e progresso
67
+ - **`GET /api/ltv/ab-test/results`** — Accuracy score por variação + recomendação automática de winner
68
+ - **`POST /api/ltv/ab-test/winner`** Declara vencedor e retorna o prompt ganador
69
+ - Integração automática: cada evento Lead sorteia a variação ativa e registra o assignment via KV cache
70
+ - Schema D1: `ltv_ab_tests`, `ltv_ab_variations`, `ltv_ab_assignments` + VIEW `v_ab_test_performance`
71
+ - Agente: `ab-ltv-agent.md`
72
+
73
+ #### ✅ Fase 4 — Fraud Detection Engine
74
+ - **Fraud Gate automático em `/track`** — roda ANTES de qualquer processamento (heurístico puro, ~2ms)
75
+ - Silent drop (retorna 200 falso) — bots não detectam a defesa
76
+ - **`GET /api/fraud/stats`** — Dashboard de fraude (últimas 24h)
77
+ - **`GET /api/fraud/alerts`** — Log de sinais detectados com filtros
78
+ - **`GET /api/fraud/blocklist`** — IPs/fingerprints atualmente bloqueados
79
+ - **`POST /api/fraud/blocklist/add`** Bloquear IP ou fingerprint (via KV, efeito imediato)
80
+ - **`DELETE /api/fraud/blocklist/remove`** Remover do blocklist
81
+ - Sinais detectados: bot_score, datacenter IP, velocity attack, email descartável, headless UA, sem Accept-Language
82
+ - Schema D1: `fraud_signals`, `fraud_alerts` + VIEW `v_fraud_dashboard`
83
+ - Agente: `fraud-detection-agent.md`
84
+
85
+ ### 🔧 Fix: `wrangler.toml` atualizado
86
+ - Todos os placeholders (`SEU_D1_DATABASE_ID`, `SEU_KV_NAMESPACE_ID`) substituídos pelos IDs reais da conta Cloudflare
87
+ - D1: `7867d38f-5fa8-4c17-b465-386211422c09`
88
+ - KV: `821b6c1ccb4b475985439b801c1fdbe0`
89
+
90
+ ---
91
+
92
+ ## 🏗️ ARQUITETURA QUANTUM ENTERPRISE (CLOUDFLARE NATIVE)
93
+
94
+ ```mermaid
95
+ graph TD
96
+ User((Usuário)) -->|Interação| SDK[cdpTrack SDK + Behavior Engine]
97
+ SDK -->|Edge Fetch 1ª via KV blocklist| FraudGate{🛡️ Fraud Gate}
98
+ FraudGate -->|score 80: Silent Drop 200| Void[/dev/null]
99
+ FraudGate -->|score < 80: Permitido| Worker[Cloudflare Worker Agent]
100
+ Worker -->|Identity Graph + _cdp_uid| D1[(D1 SQL — 21 tabelas)]
101
+ Worker -->|LTV + A/B Prompt| AI[Workers AI Llama 3.1 8B]
102
+ Worker -->|Segmento ML| Cluster[ML Clustering Engine]
103
+ Cluster -->|Bid otimizado| Bidding[Bidding Recommendations]
104
+ Worker -->|Background| Queue[Cloudflare Queues]
105
+ Queue -->|Server Dispatch| Meta[Meta CAPI v22.0]
106
+ Queue -->|Server Dispatch| Google[GA4 / Google Ads]
107
+ Queue -->|Server Dispatch| TikTok[TikTok API v1.3]
108
+ D1 -->|Reports| Dash[Dashboard Agent]
109
+ ```
110
+
111
+ ---
112
+
113
+ ## 🧠 CATÁLOGO DE AGENTES ESPECIALISTAS
114
+
115
+ O sistema é composto por **43+ agentes** coordenados pelo **Master Orchestrator**:
116
+
117
+ ### 🧠 Núcleo de Inteligência
118
+ | Agente | Função |
119
+ |---|---|
120
+ | **Master Orchestrator** | Coordenação central — guia todo o setup do projeto |
121
+ | **Page Analyzer** | Mapeamento automático de CTAs, Forms e nicho do site |
122
+ | **Validator Agent** | Auditoria de código, segurança e conformidade de APIs |
123
+ | **Memory Agent** | Contexto e checkpoints da sessão por projeto |
124
+ | **Intelligence Agent** | Monitoramento de versões de API (Meta v22.0+, etc) |
125
+
126
+ ### 🚀 Plataformas de Anúncio
127
+ | Agente | Especialidade |
128
+ |---|---|
129
+ | **Meta Agent** | Facebook Pixel + CAPI v22.0 + WhatsApp CTWA |
130
+ | **Google Agent** | GA4 + Google Ads Enhanced Conversions |
131
+ | **TikTok Agent** | TikTok Pixel + Events API v1.3 |
132
+ | **LinkedIn Agent** | Insight Tag + Conversions API v2 |
133
+ | **Pinterest Agent** | Tag + Conversions API v5 |
134
+ | **Reddit Agent** | Pixel + Conversions API v2.0 |
135
+ | **Spotify Agent** | Pixel + Conversions API v1 |
136
+ | **Bing Agent** | UET Tag + Enhanced Conversions |
137
+
138
+ ### 🤖 Enterprise Intelligence (Fase 1–4)
139
+ | Agente | Endpoint Principal | Impacto |
140
+ |---|---|---|
141
+ | **ML Clustering Agent** | `POST /api/segmentation/cluster` | Segmentação K-means/DBSCAN/Hierarchical |
142
+ | **Bidding Agent** | `POST /api/bidding/recommend` | -20% CPA via bid por segmento de LTV |
143
+ | **A/B LTV Agent** | `POST /api/ltv/ab-test/create` | +25% precisão LTV via test de prompts |
144
+ | **Fraud Detection Agent** | Auto em `/track` | Bloqueia click fraud, bots, velocity attacks |
145
+
146
+ ### 🛡️ Módulos Enterprise
147
+ | Agente | Função |
148
+ |---|---|
149
+ | **Attribution Agent** | Atribuição Multi-Touch de alta fidelidade |
150
+ | **Security Agent** | Rate Limiting, AES-256 e Bot Defense |
151
+ | **Compliance Agent** | LGPD e GDPR (Consent Mode v2) |
152
+ | **Performance Agent** | Otimização de caches e queries D1 |
153
+
154
+ ---
155
+
156
+ ## 📊 BANCO DE DADOS D1 — 21 Tabelas
157
+
158
+ ```
159
+ CORE TRACKING ML & INTELLIGENCE ENTERPRISE SECURITY
160
+ ───────────────── ───────────────────── ─────────────────────
161
+ leads ml_segments fraud_signals
162
+ events ml_segment_members fraud_alerts
163
+ sessions bid_recommendations ltv_ab_tests
164
+ webhook_events ltv_ab_tests ltv_ab_variations
165
+ api_failures ltv_ab_variations ltv_ab_assignments
166
+
167
+ VIEWS
168
+ ─────────────────────────────────────────────────
169
+ v_active_segments → Segmentos ML ativos com contagem de membros
170
+ v_active_bid_recs → Bids ativos por plataforma/vertical
171
+ v_ab_test_performance → Accuracy por variação de prompt
172
+ v_fraud_dashboard → Dashboard fraude 24h
173
+ ```
174
+
175
+ ---
176
+
177
+ ## 🔄 FLUXO ENTERPRISE COMPLETO
178
+
179
+ ```
180
+ POST /track (evento Lead)
181
+
182
+ ├─ [1] 🛡️ Fraud Gate (KV blocklist + velocity + heurísticas) ~2ms
183
+ │ ├─ score < 40 → processa normalmente
184
+ │ ├─ score 40-79 → processa + loga suspeito (background)
185
+ │ └─ score ≥ 80 → silent drop 200 + loga (background)
186
+
187
+ ├─ [2] 🔮 A/B LTV Testing — sorteia variação ativa (KV cache ~0ms)
188
+ │ └─ passa customSystemPrompt para predictLtv()
189
+
190
+ ├─ [3] 🧮 LTV Prediction — Workers AI Llama 3.1 8B
191
+ │ └─ Score 0-100 class High/Medium/Low valor em BRL
192
+
193
+ ├─ [4] 💾 D1 Writes (background via ctx.waitUntil)
194
+ │ ├─ upsertLtvProfile() → tabela leads
195
+ │ ├─ recordAbAssignment() → ltv_ab_assignments
196
+ │ └─ resolveDeviceGraph() → cross-device linking
197
+
198
+ └─ [5] 📡 CAPI dispatch (Meta + GA4 + TikTok em paralelo)
199
+ └─ com LTV injetado no value field
200
+ ```
201
+
202
+ ---
203
+
204
+ ## 💻 INSTALAÇÃO E USO
205
+
206
+ > ⚠️ **Importante:** Escolha o método de instalação abaixo que melhor se adequa ao seu cenário de implantação.
207
+
208
+ ### OPÇÃO 1 — Instalação Rápida e Confiável (Recomendada via Git Clone)
209
+
210
+ A forma mais pura, inquebrável e à prova de bugs para iniciar a base de um novo cliente. Basta criar uma pasta "vazia" para o seu cliente, abrir o terminal dentro dela e rodar:
211
+
212
+ ```bash
213
+ git clone https://github.com/ricardosoli777/CDP-Edge-Premium.git .
214
+ ```
215
+ *(O ponto no final garante que os arquivos desçam diretamente dentro da pasta atual).*
216
+
217
+ ### OPÇÃO 2 — Instalação via CLI Corporativo (Avançado)
218
+
219
+ Se preferir usar a linha de comando instalando o nosso CLI Privado do GitHub em todo o computador:
220
+
221
+ ```bash
222
+ npm install -g git+https://github.com/ricardosoli777/CDP-Edge-Premium.git
223
+ cdp-edge install . --name "Nome do Projeto"
224
+ ```
225
+
226
+ ### Passo 3 Ativar no Claude Code
227
+
228
+ ```bash
229
+ claude .
230
+ ```
231
+ Dentro do Claude Code:
232
+ ```
233
+ /cdp
234
+ ```
235
+
236
+ ---
237
+
238
+ ## 🚀 DEPLOY COMPLETO (referência)
239
+
240
+ ```bash
241
+ cd server-edge-tracker
242
+
243
+ # 1. Schemas D1 (todos em sequência)
244
+ wrangler d1 execute cdp-edge-db --file=schema.sql --remote
245
+ wrangler d1 execute cdp-edge-db --file=migrate-v6.sql --remote
246
+ wrangler d1 execute cdp-edge-db --file=schema-segmentation.sql --remote # Fase 1
247
+ wrangler d1 execute cdp-edge-db --file=schema-bidding.sql --remote # Fase 2
248
+ wrangler d1 execute cdp-edge-db --file=schema-ab-ltv.sql --remote # Fase 3
249
+ wrangler d1 execute cdp-edge-db --file=schema-fraud.sql --remote # Fase 4
250
+
251
+ # 2. Secrets
252
+ wrangler secret put META_ACCESS_TOKEN
253
+ wrangler secret put GA4_API_SECRET
254
+ wrangler secret put TIKTOK_ACCESS_TOKEN
255
+
256
+ # 3. Deploy
257
+ wrangler deploy
258
+ ```
259
+
260
+ ---
261
+
262
+ ## 🖱️ HUMAN-BEHAVIOR ENGINE
263
+
264
+ | Evento | Pontuação |
265
+ |--------|-----------|
266
+ | Scroll 25–90% | +5 a +15 pts |
267
+ | VSL Watch 25–100% | +10 a +50 pts |
268
+ | Copy Intent (cupom, PIX) | +20 pts |
269
+ | Preenchimento de campo | +10 pts |
270
+ | Rage Click | -10 pts |
271
+ | **Hot Lead (80+ pts)** | **Dispara High_Intent_Lead** |
272
+
273
+ ---
274
+
275
+ ## 📋 TODOS OS ENDPOINTS (referência rápida)
276
+
277
+ ### Core Tracking
278
+ | Rota | Método | Função |
279
+ |---|---|---|
280
+ | `/track` | POST | Evento principal (browser → CAPI) |
281
+ | `/health` | GET | Smoke test completo |
282
+ | `/webhook/hotmart` | POST | Webhook Hotmart Purchase |
283
+ | `/webhook/kiwify` | POST | Webhook Kiwify Purchase |
284
+ | `/webhook/ticto` | POST | Webhook Ticto Purchase |
285
+
286
+ ### Intelligence ML
287
+ | Rota | Método | Função |
288
+ |---|---|---|
289
+ | `/api/segmentation/cluster` | POST | Clustering K-means/DBSCAN |
290
+ | `/api/segmentation/list` | GET | Segmentos ativos |
291
+ | `/api/segmentation/outliers` | GET | Outliers comportamentais |
292
+ | `/api/bidding/recommend` | POST | Bid otimizado por segmento |
293
+ | `/api/bidding/history` | GET | Histórico de bids |
294
+ | `/api/bidding/status` | GET | Status por plataforma |
295
+
296
+ ### A/B Testing LTV
297
+ | Rota | Método | Função |
298
+ |---|---|---|
299
+ | `/api/ltv/ab-test/create` | POST | Criar experimento |
300
+ | `/api/ltv/ab-test/list` | GET | Listar experimentos |
301
+ | `/api/ltv/ab-test/results` | GET | Accuracy por variação |
302
+ | `/api/ltv/ab-test/winner` | POST | Declarar vencedor |
303
+
304
+ ### Fraud Detection
305
+ | Rota | Método | Função |
306
+ |---|---|---|
307
+ | `/api/fraud/stats` | GET | Dashboard 24h |
308
+ | `/api/fraud/alerts` | GET | Log de alertas |
309
+ | `/api/fraud/blocklist` | GET | Lista bloqueada |
310
+ | `/api/fraud/blocklist/add` | POST | Bloquear IP/fingerprint |
311
+ | `/api/fraud/blocklist/remove` | DELETE | Desbloquear |
312
+
313
+ ---
314
+
315
+ ## 📞 SUPORTE
316
+
317
+ - **Issues**: https://github.com/ricardosoli777/CDP-Edge-Premium/issues
318
+ - **Releases**: https://github.com/ricardosoli777/CDP-Edge-Premium/releases
319
+
320
+ ---
321
+
322
+ ### **CDP Edge — By Rica Soares**
323
+ > "Dados sem inteligência são apenas ruído. No Quantum Tier Enterprise, transformamos dados em ROAS."
324
+
325
+ © 2026 CDP Edge Premium. Todos os direitos reservados.