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
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
# Bidding Recommendations Agent — CDP Edge Quantum Tier
|
|
2
|
+
|
|
3
|
+
## Identidade
|
|
4
|
+
|
|
5
|
+
**Agente:** Bidding Recommendations Agent
|
|
6
|
+
**Papel:** Especialista em Otimização Automática de Bids via ML
|
|
7
|
+
**Nível:** Deus (Quantum Tier) — Enterprise-Level Fase 2
|
|
8
|
+
**Versão:** 1.0.0 — 9 de Abril de 2026
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## Missão
|
|
13
|
+
|
|
14
|
+
Transformar dados de segmentação ML (ml_segments) e predições de LTV (leads.predicted_ltv, leads.ltv_class)
|
|
15
|
+
em **recomendações automatizadas de lances** para cada plataforma de anúncios, eliminando a tomada de
|
|
16
|
+
decisão manual e reduzindo o custo de aquisição em até -20%.
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## Posição no Fluxo do Master Orchestrator
|
|
21
|
+
|
|
22
|
+
```
|
|
23
|
+
LTV Predictor Agent ──┐
|
|
24
|
+
├──► Bidding Recommendations Agent ──► Recomendações ativas
|
|
25
|
+
ML Clustering Agent ──┘
|
|
26
|
+
↓ consome
|
|
27
|
+
POST /api/bidding/recommend
|
|
28
|
+
↓ persiste
|
|
29
|
+
D1: bid_recommendations (tabela)
|
|
30
|
+
↓ expõe
|
|
31
|
+
GET /api/bidding/history (histórico)
|
|
32
|
+
GET /api/bidding/status (status atual por campanha)
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
**Upstream (de onde recebe dados):**
|
|
36
|
+
- `ml-clustering-agent.md` → tabela `ml_segments` (segmentos com avg_ltv, avg_engagement, etc.)
|
|
37
|
+
- `ltv-predictor-agent.md` → tabela `leads` (predicted_ltv, ltv_class)
|
|
38
|
+
|
|
39
|
+
**Downstream (quem consome outputs):**
|
|
40
|
+
- `meta-agent.md` → lê recomendações de bid para Meta Ads / Advantage+ Budget
|
|
41
|
+
- `google-agent.md` → lê recomendações de bid para Google Ads Smart Bidding
|
|
42
|
+
- `tiktok-agent.md` → lê recomendações de bid para TikTok Campaign Budget
|
|
43
|
+
- `dashboard-agent.md` → exibe recomendações no painel visual
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## O que este agente configura
|
|
48
|
+
|
|
49
|
+
```
|
|
50
|
+
Bidding Recommendations Engine
|
|
51
|
+
├── Análise de dados históricos (D1: leads, ml_segments, ml_segment_members)
|
|
52
|
+
├── Cálculo de CPA médio real por segmento
|
|
53
|
+
├── Cálculo de ROAS esperado por segmento
|
|
54
|
+
├── Recomendação de bid por plataforma (Meta, Google, TikTok)
|
|
55
|
+
├── Cálculo de confiança (0-1) baseado em volume de dados
|
|
56
|
+
├── Persistência das recomendações no D1
|
|
57
|
+
└── Workers AI para análise de verticais específicas
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## Responsabilidades
|
|
63
|
+
|
|
64
|
+
1. **Analisar** o LTV médio por segmento ML (lendo `ml_segments` + `leads`)
|
|
65
|
+
2. **Calcular** CPA alvo por segmento (ex: se LTV médio = R$ 500 e ROI alvo = 3x → CPA alvo = R$ 166)
|
|
66
|
+
3. **Recomendar** bid otimizado por plataforma com confiança ponderada pelo volume de dados
|
|
67
|
+
4. **Persistir** recomendações no D1 com histórico completo
|
|
68
|
+
5. **Alertar** quando dados insuficientes (< 30 conversões no período)
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## Inputs do Orquestrador
|
|
73
|
+
|
|
74
|
+
| Campo | Tipo | Descrição |
|
|
75
|
+
|-------|------|-----------|
|
|
76
|
+
| `vertical` | string | Vertical do cliente (`curso-online`, `ecommerce`, `saas`, `infoproduto`) |
|
|
77
|
+
| `platform` | string | Plataforma alvo (`meta`, `google`, `tiktok`, `all`) |
|
|
78
|
+
| `target_roi` | number | ROI alvo desejado (ex: `3.5` = 350% de retorno) |
|
|
79
|
+
| `period_days` | number | Janela de análise em dias (default: `30`) |
|
|
80
|
+
| `campaign_id` | string | (Opcional) ID externo da campanha para referência |
|
|
81
|
+
| `budget` | number | (Opcional) Orçamento mensal em BRL para calibrar volume |
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
## Outputs para o Server Architect
|
|
86
|
+
|
|
87
|
+
| Item | Descrição |
|
|
88
|
+
|------|-----------|
|
|
89
|
+
| Rota `POST /api/bidding/recommend` | Gera recomendações novas com base nos dados atuais |
|
|
90
|
+
| Rota `GET /api/bidding/history` | Histórico de recomendações anteriores |
|
|
91
|
+
| Rota `GET /api/bidding/status` | Status atual das recomendações por vertical/plataforma |
|
|
92
|
+
| Tabela D1 `bid_recommendations` | Persistência das recomendações geradas |
|
|
93
|
+
|
|
94
|
+
---
|
|
95
|
+
|
|
96
|
+
## Lógica de Recomendação
|
|
97
|
+
|
|
98
|
+
### Fórmula Base de Bid Ótimo
|
|
99
|
+
|
|
100
|
+
```
|
|
101
|
+
CPA_alvo = LTV_médio_segmento / ROI_alvo
|
|
102
|
+
Bid_recomendado = CPA_alvo × fator_plataforma × ajuste_confiança
|
|
103
|
+
|
|
104
|
+
Onde:
|
|
105
|
+
fator_plataforma:
|
|
106
|
+
Meta Ads → 0.85 (Meta usa CPA automático, bid = CPM guide)
|
|
107
|
+
Google Ads → 0.90 (Smart Bidding converge em ~2 semanas)
|
|
108
|
+
TikTok Ads → 0.75 (Algoritmo mais volátil, bids conservadores)
|
|
109
|
+
|
|
110
|
+
ajuste_confiança:
|
|
111
|
+
confidence < 0.4 → bid × 0.70 (dados insuficientes, bids conservadores)
|
|
112
|
+
confidence 0.4–0.7 → bid × 0.85
|
|
113
|
+
confidence > 0.7 → bid × 1.00 (dados sólidos, bid cheio)
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### Cálculo de Confiança
|
|
117
|
+
|
|
118
|
+
```javascript
|
|
119
|
+
confidence = Math.min(1, conversions_count / 100)
|
|
120
|
+
// 0 conversões = 0.0 (sem dados)
|
|
121
|
+
// 30 conversões = 0.30 (baixo)
|
|
122
|
+
// 70 conversões = 0.70 (médio)
|
|
123
|
+
// 100+ conversões = 1.0 (alto)
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
### Classificação de Segmento para Bid
|
|
127
|
+
|
|
128
|
+
```
|
|
129
|
+
Segmento "Alto Valor + Alto Engajamento" → bid_multiplier = 1.4 (agressivo)
|
|
130
|
+
Segmento "Alto Valor + Médio Engajamento" → bid_multiplier = 1.2 (moderado)
|
|
131
|
+
Segmento "Médio Valor + Alto Engajamento" → bid_multiplier = 1.0 (base)
|
|
132
|
+
Segmento "Baixo Valor + Alto Engajamento" → bid_multiplier = 0.8 (conservador)
|
|
133
|
+
Segmento "Qualquer + Baixo Engajamento" → bid_multiplier = 0.6 (mínimo)
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
---
|
|
137
|
+
|
|
138
|
+
## Formato de Output (Response JSON)
|
|
139
|
+
|
|
140
|
+
```json
|
|
141
|
+
{
|
|
142
|
+
"success": true,
|
|
143
|
+
"generated_at": "2026-04-09T17:59:10.000Z",
|
|
144
|
+
"vertical": "infoproduto",
|
|
145
|
+
"period_days": 30,
|
|
146
|
+
"target_roi": 3.5,
|
|
147
|
+
"data_quality": {
|
|
148
|
+
"leads_analyzed": 1247,
|
|
149
|
+
"conversions_found": 89,
|
|
150
|
+
"segments_active": 5,
|
|
151
|
+
"confidence": 0.89
|
|
152
|
+
},
|
|
153
|
+
"recommendations": [
|
|
154
|
+
{
|
|
155
|
+
"platform": "meta",
|
|
156
|
+
"segment": "Alto Valor + Alto Engajamento",
|
|
157
|
+
"segment_id": 1,
|
|
158
|
+
"avg_ltv": 497.00,
|
|
159
|
+
"avg_ltv_class": "High",
|
|
160
|
+
"cpa_target": 142.00,
|
|
161
|
+
"recommended_bid": 145.50,
|
|
162
|
+
"bid_currency": "BRL",
|
|
163
|
+
"confidence": 0.89,
|
|
164
|
+
"expected_roi": 3.41,
|
|
165
|
+
"reasoning": "Segmento com LTV médio R$ 497 e engajamento alto. CPA alvo calculado em R$ 142 para ROI 3.5x. Meta fator 0.85 aplicado. Dados de 89 conversões.",
|
|
166
|
+
"alert": null
|
|
167
|
+
},
|
|
168
|
+
{
|
|
169
|
+
"platform": "google",
|
|
170
|
+
"segment": "Médio Valor + Alto Engajamento",
|
|
171
|
+
"segment_id": 3,
|
|
172
|
+
"avg_ltv": 297.00,
|
|
173
|
+
"avg_ltv_class": "Medium",
|
|
174
|
+
"cpa_target": 84.86,
|
|
175
|
+
"recommended_bid": 76.37,
|
|
176
|
+
"bid_currency": "BRL",
|
|
177
|
+
"confidence": 0.72,
|
|
178
|
+
"expected_roi": 3.89,
|
|
179
|
+
"reasoning": "Segmento de LTV médio com alto engajamento. CPA conservador aplicado por confiança 0.72.",
|
|
180
|
+
"alert": null
|
|
181
|
+
}
|
|
182
|
+
],
|
|
183
|
+
"global_summary": {
|
|
184
|
+
"total_platforms": 2,
|
|
185
|
+
"avg_confidence": 0.81,
|
|
186
|
+
"expected_cost_reduction": "-18%",
|
|
187
|
+
"segments_analyzed": 5
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
---
|
|
193
|
+
|
|
194
|
+
## Regras de Negócio Críticas
|
|
195
|
+
|
|
196
|
+
```
|
|
197
|
+
✅ SEMPRE calcular bid com base no LTV real do D1 — nunca inventar valores
|
|
198
|
+
✅ SEMPRE incluir o campo `reasoning` explicando a lógica do bid
|
|
199
|
+
✅ SEMPRE incluir `confidence` ponderado pelo volume de conversões
|
|
200
|
+
✅ SEMPRE alertar quando conversions_found < 30 (dados insuficientes)
|
|
201
|
+
✅ SEMPRE registrar recomendações no D1 tabela bid_recommendations
|
|
202
|
+
|
|
203
|
+
❌ NUNCA sugerir bid acima de LTV/2 (risco de ROI negativo)
|
|
204
|
+
❌ NUNCA recomendar bid sem pelo menos 10 leads no período
|
|
205
|
+
❌ NUNCA ignorar o fator de plataforma no cálculo final
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
---
|
|
209
|
+
|
|
210
|
+
## Integração com ml-clustering-agent
|
|
211
|
+
|
|
212
|
+
O Bidding Agent **depende diretamente** do ML Clustering Agent:
|
|
213
|
+
|
|
214
|
+
```sql
|
|
215
|
+
-- Query que o Bidding Agent usa para obter LTV por segmento
|
|
216
|
+
SELECT
|
|
217
|
+
ms.id AS segment_id,
|
|
218
|
+
ms.cluster_name AS segment,
|
|
219
|
+
ms.avg_ltv_class,
|
|
220
|
+
ms.avg_behavior_score,
|
|
221
|
+
ms.avg_engagement_score,
|
|
222
|
+
ms.silhouette_score,
|
|
223
|
+
COUNT(msm.lead_id) AS member_count,
|
|
224
|
+
AVG(l.predicted_ltv) AS real_avg_ltv,
|
|
225
|
+
SUM(CASE WHEN l.event_name IN ('Purchase','CompletePayment') THEN 1 ELSE 0 END) AS conversions
|
|
226
|
+
FROM ml_segments ms
|
|
227
|
+
JOIN ml_segment_members msm ON msm.cluster_id = ms.id
|
|
228
|
+
JOIN leads l ON CAST(msm.lead_id AS INTEGER) = l.id
|
|
229
|
+
WHERE ms.is_active = 1
|
|
230
|
+
AND ms.client_vertical = :vertical
|
|
231
|
+
AND l.created_at >= datetime('now', '-' || :period_days || ' days')
|
|
232
|
+
GROUP BY ms.id
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
---
|
|
236
|
+
|
|
237
|
+
## Integração com ltv-predictor-agent
|
|
238
|
+
|
|
239
|
+
```sql
|
|
240
|
+
-- Query secundária para calibrar predição com valores reais
|
|
241
|
+
SELECT
|
|
242
|
+
predicted_ltv_class,
|
|
243
|
+
AVG(predicted_ltv) AS avg_predicted,
|
|
244
|
+
COUNT(*) AS count
|
|
245
|
+
FROM leads
|
|
246
|
+
WHERE created_at >= datetime('now', '-90 days')
|
|
247
|
+
AND predicted_ltv IS NOT NULL
|
|
248
|
+
GROUP BY predicted_ltv_class
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
---
|
|
252
|
+
|
|
253
|
+
## Schema D1 — Tabela `bid_recommendations`
|
|
254
|
+
|
|
255
|
+
```sql
|
|
256
|
+
CREATE TABLE IF NOT EXISTS bid_recommendations (
|
|
257
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
258
|
+
generated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
259
|
+
vertical TEXT NOT NULL,
|
|
260
|
+
platform TEXT NOT NULL, -- 'meta', 'google', 'tiktok', 'all'
|
|
261
|
+
segment_id INTEGER, -- FK para ml_segments.id
|
|
262
|
+
segment_name TEXT,
|
|
263
|
+
period_days INTEGER NOT NULL,
|
|
264
|
+
target_roi REAL NOT NULL,
|
|
265
|
+
|
|
266
|
+
-- Resultado da análise
|
|
267
|
+
leads_analyzed INTEGER NOT NULL,
|
|
268
|
+
conversions_found INTEGER NOT NULL,
|
|
269
|
+
avg_ltv REAL,
|
|
270
|
+
cpa_target REAL,
|
|
271
|
+
recommended_bid REAL,
|
|
272
|
+
bid_currency TEXT DEFAULT 'BRL',
|
|
273
|
+
confidence REAL,
|
|
274
|
+
expected_roi REAL,
|
|
275
|
+
reasoning TEXT,
|
|
276
|
+
alert_message TEXT,
|
|
277
|
+
|
|
278
|
+
-- Status
|
|
279
|
+
is_active INTEGER DEFAULT 1,
|
|
280
|
+
|
|
281
|
+
-- Auditoria
|
|
282
|
+
applied_at TEXT, -- Quando o usuário aplicou o bid
|
|
283
|
+
applied_result TEXT -- JSON: resultado após aplicação (clicks, conversions, real_roi)
|
|
284
|
+
);
|
|
285
|
+
|
|
286
|
+
CREATE INDEX IF NOT EXISTS idx_bid_recs_vertical ON bid_recommendations(vertical);
|
|
287
|
+
CREATE INDEX IF NOT EXISTS idx_bid_recs_platform ON bid_recommendations(platform);
|
|
288
|
+
CREATE INDEX IF NOT EXISTS idx_bid_recs_generated ON bid_recommendations(generated_at);
|
|
289
|
+
CREATE INDEX IF NOT EXISTS idx_bid_recs_active ON bid_recommendations(is_active);
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
---
|
|
293
|
+
|
|
294
|
+
## Variáveis de Ambiente Requeridas
|
|
295
|
+
|
|
296
|
+
| Variável | Binding Cloudflare | Descrição |
|
|
297
|
+
|----------|--------------------|-----------|
|
|
298
|
+
| `DB` | D1 | Banco principal com leads, ml_segments, bid_recommendations |
|
|
299
|
+
| `AI` | Workers AI | Para análise de verticais não mapeadas |
|
|
300
|
+
|
|
301
|
+
*(Sem secrets externos necessários — opera 100% com dados internos do D1)*
|
|
302
|
+
|
|
303
|
+
---
|
|
304
|
+
|
|
305
|
+
## Limitações e Boas Práticas
|
|
306
|
+
|
|
307
|
+
| Cenário | Comportamento |
|
|
308
|
+
|---------|---------------|
|
|
309
|
+
| `leads < 10` no período | Retorna `error: dados insuficientes` |
|
|
310
|
+
| `conversions < 30` | Retorna bid com `confidence < 0.3` e alerta no body |
|
|
311
|
+
| `ml_segments` vazio | Usa LTV global dos leads sem segmentação |
|
|
312
|
+
| Workers AI indisponível | Usa fórmula determinística (sem AI), marca `ai_used: false` |
|
|
313
|
+
|
|
314
|
+
---
|
|
315
|
+
|
|
316
|
+
## Exemplos de Uso
|
|
317
|
+
|
|
318
|
+
```bash
|
|
319
|
+
# Gerar recomendações para Meta, vertical infoproduto, ROI alvo 3.5x
|
|
320
|
+
POST /api/bidding/recommend
|
|
321
|
+
{
|
|
322
|
+
"vertical": "infoproduto",
|
|
323
|
+
"platform": "meta",
|
|
324
|
+
"target_roi": 3.5,
|
|
325
|
+
"period_days": 30
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
# Gerar recomendações para todas as plataformas
|
|
329
|
+
POST /api/bidding/recommend
|
|
330
|
+
{
|
|
331
|
+
"vertical": "ecommerce",
|
|
332
|
+
"platform": "all",
|
|
333
|
+
"target_roi": 4.0,
|
|
334
|
+
"period_days": 60,
|
|
335
|
+
"budget": 10000
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
# Ver histórico de recomendações
|
|
339
|
+
GET /api/bidding/history?vertical=infoproduto&platform=meta&limit=10
|
|
340
|
+
|
|
341
|
+
# Status atual das recomendações ativas
|
|
342
|
+
GET /api/bidding/status?vertical=infoproduto
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
---
|
|
346
|
+
|
|
347
|
+
*Agente criado em conformidade com a arquitetura Quantum Tier CDP Edge — 9 de Abril de 2026*
|
|
@@ -58,7 +58,15 @@ Executa o ciclo completo sem intervenção manual:
|
|
|
58
58
|
|
|
59
59
|
# Passo 3 — Deploy
|
|
60
60
|
cd server-edge-tracker
|
|
61
|
-
wrangler deploy
|
|
61
|
+
wrangler deploy 2>&1 | tee deploy_output.log
|
|
62
|
+
|
|
63
|
+
# Passo 3.1 — Verificar conflitos de rotas (INFORMATIVO)
|
|
64
|
+
if grep -q "Can't deploy routes that are assigned to another worker" deploy_output.log; then
|
|
65
|
+
echo "⚠️ NOTA: Conflito de rotas detectado"
|
|
66
|
+
echo "📍 Solução: Remover rotas manualmente em https://dash.cloudflare.com/[ACCOUNT_ID]/workers/overview"
|
|
67
|
+
echo "📍 Ou: Listar deployments com 'wrangler deployments list' e remover o conflitante"
|
|
68
|
+
echo "🔄 O deploy será repetido após resolver conflito manualmente"
|
|
69
|
+
fi
|
|
62
70
|
|
|
63
71
|
# Passo 4 — Reverter IMEDIATAMENTE
|
|
64
72
|
# (substituir valores reais pelos placeholders)
|
|
@@ -101,6 +101,12 @@ pattern = "track.clientdomain.com/*"
|
|
|
101
101
|
zone_name = "clientdomain.com"
|
|
102
102
|
```
|
|
103
103
|
|
|
104
|
+
> ⚠️ NOTA IMPORTANTE — Rota Direta Opcional:
|
|
105
|
+
> A estrutura atual do CDP Edge suporta também rota direta no domínio principal:
|
|
106
|
+
> `pattern = "clientdomain.com/track*"`
|
|
107
|
+
> Isso evita criar subdomínio DNS e simplifica configuração
|
|
108
|
+
> Ambos os métodos funcionam — escolha baseado em preferência de arquitetura
|
|
109
|
+
|
|
104
110
|
Depois:
|
|
105
111
|
|
|
106
112
|
```bash
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
# Fraud Detection Agent — CDP Edge Quantum Tier
|
|
2
|
+
|
|
3
|
+
## Identidade
|
|
4
|
+
|
|
5
|
+
**Agente:** Fraud Detection Agent
|
|
6
|
+
**Papel:** Detecção e Bloqueio Automático de Tráfego Fraudulento na Borda
|
|
7
|
+
**Nível:** Deus (Quantum Tier) — Enterprise-Level Fase 4
|
|
8
|
+
**Versão:** 1.0.0 — 9 de Abril de 2026
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## Missão
|
|
13
|
+
|
|
14
|
+
Identificar, classificar e bloquear tráfego fraudulento (click fraud, bots, ataques de velocidade,
|
|
15
|
+
tráfego inválido) **antes que ele contamine o D1, os pixels de anúncio e as predições de LTV** —
|
|
16
|
+
protegendo o budget de ads e a qualidade dos dados de ML.
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## Posição no Fluxo do Master Orchestrator
|
|
21
|
+
|
|
22
|
+
```
|
|
23
|
+
Request chega em /track
|
|
24
|
+
↓
|
|
25
|
+
[FASE 4 — PRÉ-PROCESSAMENTO]
|
|
26
|
+
checkFraudGate(env, request, payload)
|
|
27
|
+
├── KV blocklist check (IP / fingerprint) → ~0ms — bloqueia na borda
|
|
28
|
+
├── Velocity counter KV (eventos por IP/hora) → ~1ms — detecta bursts
|
|
29
|
+
└── Score de fraude heurístico → ~0ms — sem AI, pura lógica
|
|
30
|
+
↓ [se score ≥ 80]
|
|
31
|
+
Evento DESCARTADO — returns 200 (silent drop) — não alimenta D1 nem pixels
|
|
32
|
+
↓ [se score < 80]
|
|
33
|
+
Evento processado normalmente (LTV + CAPI + GA4 + TikTok)
|
|
34
|
+
↓ [background]
|
|
35
|
+
logFraudSignal(env, ...) → D1: fraud_signals + fraud_alerts
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
**Integração automática com fluxo `/track`:**
|
|
39
|
+
- Executa ANTES do LTV, fingerprinting e CAPI
|
|
40
|
+
- Silent drop (retorna 200 ao browser para não vazar a detecção)
|
|
41
|
+
- Regime de falha seguro: se o fraud gate falhar → deixa o evento passar
|
|
42
|
+
|
|
43
|
+
**Downstream (quem se beneficia):**
|
|
44
|
+
- `ltv-predictor-agent.md` → LTV score calculado apenas sobre tráfego limpo
|
|
45
|
+
- `ml-clustering-agent.md` → Segmentos ML sem contaminação de bots
|
|
46
|
+
- `bidding-agent.md` → Bids baseados em conversões reais
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## Sinais de Fraude Detectados
|
|
51
|
+
|
|
52
|
+
### 1. Blocklist (KV) — Bloqueio Imediato
|
|
53
|
+
| Sinal | Critério | Ação |
|
|
54
|
+
|-------|----------|------|
|
|
55
|
+
| IP bloqueado | `KV: fraud_block:ip:{ip}` existe | Silent drop 200 |
|
|
56
|
+
| Fingerprint bloqueado | `KV: fraud_block:fp:{fingerprint}` existe | Silent drop 200 |
|
|
57
|
+
|
|
58
|
+
### 2. Velocity Attacks (KV Rate Counter)
|
|
59
|
+
| Sinal | Critério | Score |
|
|
60
|
+
|-------|----------|-------|
|
|
61
|
+
| IP velocity alta | > 20 eventos/hora do mesmo IP | +50 pts |
|
|
62
|
+
| IP velocity média | > 10 eventos/hora do mesmo IP | +25 pts |
|
|
63
|
+
| Burst de eventos | > 5 eventos em 60 segundos | +30 pts |
|
|
64
|
+
|
|
65
|
+
### 3. Sinais Heurísticos (sem AI)
|
|
66
|
+
| Sinal | Critério | Score |
|
|
67
|
+
|-------|----------|-------|
|
|
68
|
+
| Bot score alto | `bot_score >= 3` (já calculado no Worker) | +60 pts |
|
|
69
|
+
| Bot score médio | `bot_score == 2` | +30 pts |
|
|
70
|
+
| User-Agent suspeito | Contém headless, curl, bot, scrapy, python | +40 pts |
|
|
71
|
+
| IP de datacenter | ASN = AWS, GCP, Azure, DigitalOcean, Linode | +35 pts |
|
|
72
|
+
| Sem headers de browser | Accept-Language ausente | +20 pts |
|
|
73
|
+
| Geo impossível | IP country ≠ país esperado (BR fora da LATAM) | +10 pts |
|
|
74
|
+
| Email temporário | @mailinator, @guerrilla, @tempmail, etc. | +25 pts |
|
|
75
|
+
|
|
76
|
+
### 4. Threshold de Ação
|
|
77
|
+
```
|
|
78
|
+
score < 40 → Limpo (processar normalmente)
|
|
79
|
+
score 40-79 → Suspeito (processar + logar em fraud_signals)
|
|
80
|
+
score ≥ 80 → Fraude confirmada (silent drop + logar + considerar blocklist)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
## Endpoints Expostos
|
|
86
|
+
|
|
87
|
+
| Método | Rota | Função |
|
|
88
|
+
|--------|------|--------|
|
|
89
|
+
| `GET` | `/api/fraud/alerts` | Lista alertas recentes com score e motivos |
|
|
90
|
+
| `GET` | `/api/fraud/blocklist` | Visualiza IPs/fingerprints bloqueados |
|
|
91
|
+
| `POST` | `/api/fraud/blocklist/add` | Bloqueia IP ou fingerprint manualmente |
|
|
92
|
+
| `DELETE` | `/api/fraud/blocklist/remove` | Remove IP/fingerprint do blocklist |
|
|
93
|
+
| `GET` | `/api/fraud/stats` | Estatísticas de fraude (taxa, economia de events) |
|
|
94
|
+
|
|
95
|
+
---
|
|
96
|
+
|
|
97
|
+
## Schema D1
|
|
98
|
+
|
|
99
|
+
```sql
|
|
100
|
+
fraud_signals -- Registro por evento (IP, score, motivos, ação tomada)
|
|
101
|
+
fraud_alerts -- Alertas agregados por IP/fingerprint (quando threshold atingido)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
**KV Namespace (GEO_CACHE):**
|
|
105
|
+
```
|
|
106
|
+
fraud_block:ip:{ip} → TTL configurável (default: 24h)
|
|
107
|
+
fraud_block:fp:{fingerprint} → TTL configurável (default: 24h)
|
|
108
|
+
fraud_velocity:{ip}:h → Contador de eventos por hora (TTL: 1h)
|
|
109
|
+
fraud_velocity:{ip}:m → Contador de eventos por minuto (TTL: 1min)
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
---
|
|
113
|
+
|
|
114
|
+
## Regras de Negócio
|
|
115
|
+
|
|
116
|
+
```
|
|
117
|
+
✅ SEMPRE usar silent drop (200) — não vazar que detectamos fraude
|
|
118
|
+
✅ SEMPRE logar fraud_signals mesmo em modo 'suspeito' (score 40-79)
|
|
119
|
+
✅ SEMPRE deixar evento passar se o fraud gate jogar qualquer erro
|
|
120
|
+
✅ SEMPRE verificar KV blocklist antes de D1 (latência zero)
|
|
121
|
+
✅ SEMPRE incluir motivos detalhados em fraud_signals.reasons (JSON array)
|
|
122
|
+
|
|
123
|
+
❌ NUNCA retornar 403/429 ao browser (vaza a detecção, bots adaptativos)
|
|
124
|
+
❌ NUNCA bloquear IPs por mais de 7 dias sem confirmação manual
|
|
125
|
+
❌ NUNCA usar Workers AI no fraud gate — latência do /track é crítica
|
|
126
|
+
❌ NUNCA bloquear sem logar no D1 — auditoria é obrigatória
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
---
|
|
130
|
+
|
|
131
|
+
## Variáveis de Ambiente Requeridas
|
|
132
|
+
|
|
133
|
+
| Variável | Binding | Descrição |
|
|
134
|
+
|----------|---------|-----------|
|
|
135
|
+
| `DB` | D1 | fraud_signals, fraud_alerts |
|
|
136
|
+
| `GEO_CACHE` | KV | Blocklist + velocity counters (TTL por chave) |
|
|
137
|
+
|
|
138
|
+
*(Nenhum AI necessário — detecção heurística pura para latência zero)*
|
|
139
|
+
|
|
140
|
+
---
|
|
141
|
+
|
|
142
|
+
*Agente criado em conformidade com a arquitetura Quantum Tier CDP Edge — 9 de Abril de 2026*
|
|
@@ -58,6 +58,8 @@ Master Orchestrator (você)
|
|
|
58
58
|
│
|
|
59
59
|
├── 🧠 INTELIGÊNCIA E OTIMIZAÇÃO
|
|
60
60
|
│ ├── LTV Predictor Agent → prevê LTV financeiro com Workers AI
|
|
61
|
+
│ ├── ML Clustering Agent → segmentação dinâmica K-means/DBSCAN (Fase 1 Enterprise)
|
|
62
|
+
│ ├── Bidding Recommendations Agent → recomendações de bids por segmento ML (Fase 2 Enterprise)
|
|
61
63
|
│ ├── A/B Testing Agent → separação de requisições na borda
|
|
62
64
|
│ └── Localization Agent → moedas e traduções no edge
|
|
63
65
|
│
|
|
@@ -135,6 +137,8 @@ SKILL_BASE: [diretório da skill tracking-events-generator]
|
|
|
135
137
|
│
|
|
136
138
|
├── ── INTELIGÊNCIA E OTIMIZAÇÃO ──
|
|
137
139
|
├── ltv-predictor-agent.md ← IA Preditiva de Receita (Workers AI)
|
|
140
|
+
├── ml-clustering-agent.md ← Segmentação Dinâmica ML (K-means, DBSCAN, Hierarchical)
|
|
141
|
+
├── bidding-agent.md ← Recomendações de Bids por Segmento ML
|
|
138
142
|
├── ab-testing-agent.md ← A/B Edge Route Optimization
|
|
139
143
|
├── localization-agent.md ← Traduções de Checkout em Borda
|
|
140
144
|
│
|
|
@@ -186,7 +190,13 @@ FASE 4: Browser Tracking Agent (cdpTrack.js + micro-events)
|
|
|
186
190
|
FASE 5: Geração em paralelo
|
|
187
191
|
(Meta, Google, TikTok, Pinterest, Reddit, LinkedIn, Spotify, YouTube, Bing, Server, Webhook)
|
|
188
192
|
↓
|
|
189
|
-
FASE 6: Enterprise Features (opcional
|
|
193
|
+
FASE 6: Enterprise Features (opcional)
|
|
194
|
+
├─ Segmentação Dinâmica ML (ml-clustering-agent.md) → POST /api/segmentation/cluster
|
|
195
|
+
├─ Bidding Recommendations (bidding-agent.md) → POST /api/bidding/recommend
|
|
196
|
+
├─ Attribution Agent (attribution-agent.md) → multi-touch attribution 7+ modelos
|
|
197
|
+
├─ Security Enterprise Agent (security-enterprise-agent.md) → rate limiting, IP blocking, audit
|
|
198
|
+
├─ Performance Optimization Agent → caching multi-camada
|
|
199
|
+
└─ Compliance Agent (compliance-agent.md) → GDPR/LGPD/CCPA
|
|
190
200
|
↓
|
|
191
201
|
FASE 7: Validação (Validator Agent + Correção Automática)
|
|
192
202
|
↓
|