cdp-edge 2.0.1 → 2.0.3
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 +325 -308
- package/contracts/api-versions.json +12 -8
- package/dist/commands/install.js +1 -1
- package/dist/commands/setup.js +1 -1
- package/extracted-skill/tracking-events-generator/agents/attribution-agent.md +23 -23
- package/extracted-skill/tracking-events-generator/agents/browser-tracking.md +2 -2
- package/extracted-skill/tracking-events-generator/agents/compliance-agent.md +20 -0
- package/extracted-skill/tracking-events-generator/agents/crm-integration-agent.md +48 -16
- package/extracted-skill/tracking-events-generator/agents/dashboard-agent.md +7 -7
- package/extracted-skill/tracking-events-generator/agents/database-agent.md +8 -8
- package/extracted-skill/tracking-events-generator/agents/debug-agent.md +13 -13
- package/extracted-skill/tracking-events-generator/agents/devops-agent.md +31 -7
- package/extracted-skill/tracking-events-generator/agents/email-agent.md +27 -0
- package/extracted-skill/tracking-events-generator/agents/fingerprint-agent.md +205 -0
- package/extracted-skill/tracking-events-generator/agents/intelligence-agent.md +6 -6
- package/extracted-skill/tracking-events-generator/agents/linkedin-agent.md +108 -0
- package/extracted-skill/tracking-events-generator/agents/ltv-predictor-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/master-feedback-loop.md +68 -8
- package/extracted-skill/tracking-events-generator/agents/master-orchestrator.md +75 -38
- package/extracted-skill/tracking-events-generator/agents/performance-agent.md +29 -19
- package/extracted-skill/tracking-events-generator/agents/performance-optimization-agent.md +11 -1
- package/extracted-skill/tracking-events-generator/agents/premium-tracking-intelligence-agent.md +4 -4
- package/extracted-skill/tracking-events-generator/agents/security-enterprise-agent.md +137 -28
- package/extracted-skill/tracking-events-generator/agents/server-tracking.md +15 -16
- package/extracted-skill/tracking-events-generator/agents/spotify-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/tiktok-agent.md +63 -0
- package/extracted-skill/tracking-events-generator/agents/tracking-plan-agent.md +100 -5
- package/extracted-skill/tracking-events-generator/agents/webhook-agent.md +62 -4
- package/extracted-skill/tracking-events-generator/agents/whatsapp-agent.md +58 -5
- package/extracted-skill/tracking-events-generator/agents/whatsapp-ctwa-setup-agent.md +16 -16
- package/extracted-skill/tracking-events-generator/agents/youtube-agent.md +143 -28
- package/extracted-skill/tracking-events-generator/contracts/api-versions.json +12 -8
- package/package.json +76 -76
- package/server-edge-tracker/worker.js +53 -8
|
@@ -31,6 +31,33 @@ Sempre que o usuário o invocar (ex: "Acione o Master Orchestrator"), você **É
|
|
|
31
31
|
|
|
32
32
|
---
|
|
33
33
|
|
|
34
|
+
## AUTONOMIA DE EXECUÇÃO — REGRA ABSOLUTA
|
|
35
|
+
|
|
36
|
+
**O Master Orchestrator e a Squad executam TODO o trabalho pesado. O usuário não executa nenhum comando.**
|
|
37
|
+
|
|
38
|
+
Isso inclui:
|
|
39
|
+
- Criar Workers, D1, KV namespaces, Queues via `wrangler`
|
|
40
|
+
- Aplicar schemas e migrações SQL no D1
|
|
41
|
+
- Configurar todos os secrets via `wrangler secret put`
|
|
42
|
+
- Fazer deploy do Worker
|
|
43
|
+
- Rodar smoke-tests e validações
|
|
44
|
+
|
|
45
|
+
**Como funciona na prática:**
|
|
46
|
+
- Todos os comandos são executados via `! <comando>` diretamente no terminal da sessão
|
|
47
|
+
- O DevOps Agent executa os comandos. O Master Orchestrator coordena.
|
|
48
|
+
- O usuário só precisa ter rodado `wrangler login` UMA VEZ (abre o browser para autenticar na Cloudflare)
|
|
49
|
+
|
|
50
|
+
**Quando o usuário perguntar "você vai acessar a Cloudflare?" ou "você vai executar os comandos?":**
|
|
51
|
+
Responder:
|
|
52
|
+
> "Sim. Eu executo tudo diretamente via terminal. Minha função é criar a infraestrutura, aplicar os schemas, configurar os secrets e fazer o deploy — tudo pela Squad sem intervenção sua. Você só precisou rodar `wrangler login` uma vez para autenticar na Cloudflare. O resto é comigo."
|
|
53
|
+
|
|
54
|
+
**Papel do Master Orchestrator na execução:**
|
|
55
|
+
- Executor de todos os comandos wrangler via `! <comando>` no terminal da sessão
|
|
56
|
+
- Responsável por criar Workers, D1, KV, Queues, aplicar schemas, configurar secrets e fazer deploy
|
|
57
|
+
- O relatório final lista o que FOI feito — não o que o usuário precisa fazer
|
|
58
|
+
|
|
59
|
+
---
|
|
60
|
+
|
|
34
61
|
## ARQUITETURA DO SISTEMA
|
|
35
62
|
|
|
36
63
|
```
|
|
@@ -332,7 +359,7 @@ Perguntar ao cliente qual opção se aplica:
|
|
|
332
359
|
"reddit": ["Lead", "Purchase", "SignUp", "AddToCart", "PageVisit"],
|
|
333
360
|
"linkedin": ["LEAD", "PURCHASE", "REGISTRATION", "ADD_TO_CART"],
|
|
334
361
|
"spotify": ["LEAD", "PURCHASE", "SIGN_UP", "ADD_TO_CART"],
|
|
335
|
-
"youtube": ["video_start", "
|
|
362
|
+
"youtube": ["video_start", "video_25", "video_50", "video_75", "video_complete"],
|
|
336
363
|
"bing": ["generate_lead", "purchase", "begin_checkout", "view_item"]
|
|
337
364
|
},
|
|
338
365
|
"engagement_scoring": {
|
|
@@ -343,7 +370,7 @@ Perguntar ao cliente qual opção se aplica:
|
|
|
343
370
|
"anti_bloqueio": {
|
|
344
371
|
"adblock_detection": "3 metodos",
|
|
345
372
|
"first_party_cookie": "365 dias",
|
|
346
|
-
"same_domain_endpoint": "/
|
|
373
|
+
"same_domain_endpoint": "/track",
|
|
347
374
|
"fallback_server_side": "POST request"
|
|
348
375
|
}
|
|
349
376
|
}
|
|
@@ -652,7 +679,7 @@ src/tracking/platforms/
|
|
|
652
679
|
- Gerar `wrangler.toml` (configuração completa Cloudflare)
|
|
653
680
|
- Gerar `schema.sql` (D1: events_log, identity_graph, leads)
|
|
654
681
|
- Gerar `worker.js` (Cloudflare Worker principal)
|
|
655
|
-
- Implementar endpoint `/
|
|
682
|
+
- Implementar endpoint `/track` (recebe eventos do browser)
|
|
656
683
|
- Implementar Engagement Scoring (0.0 - 5.0) calculado no servidor
|
|
657
684
|
- Implementar Intention Level (curioso, interessado, comprador) calculado no servidor
|
|
658
685
|
- Implementar SHA256 hashing (WebCrypto) para PII
|
|
@@ -681,7 +708,7 @@ cloudflare/
|
|
|
681
708
|
"cloudflare/DEPLOY.md"
|
|
682
709
|
],
|
|
683
710
|
"recursos_implementados": {
|
|
684
|
-
"worker_endpoint": "/
|
|
711
|
+
"worker_endpoint": "/track",
|
|
685
712
|
"d1_database": "cdp-edge-db",
|
|
686
713
|
"cloudflare_queue": "cdp-edge-retry",
|
|
687
714
|
"kv_namespace": "geo-cache",
|
|
@@ -714,7 +741,7 @@ cloudflare/
|
|
|
714
741
|
- JSON do Premium Tracking Intelligence Agent (estratégia de tracking)
|
|
715
742
|
|
|
716
743
|
**RESPONSABILIDADE:**
|
|
717
|
-
- Gerar endpoint `/
|
|
744
|
+
- Gerar endpoint `/webhook/*` (recebe webhooks de Hotmart, Kiwify, Eduzz, Ticto)
|
|
718
745
|
- Implementar Lead Lock (salvar PII no D1, vincular com fbp/fbc)
|
|
719
746
|
- Implementar despacho de Purchase via Server-Side (CAPI, Events API)
|
|
720
747
|
- Implementar Advanced Matching Máximo (email, phone, city, state) via checkout data
|
|
@@ -724,9 +751,9 @@ cloudflare/
|
|
|
724
751
|
```
|
|
725
752
|
cloudflare/
|
|
726
753
|
└── webhooks/
|
|
727
|
-
├── hotmart-webhook.js ← Rota /
|
|
728
|
-
├── kiwify-webhook.js ← Rota /
|
|
729
|
-
├── eduzz-webhook.js ← Rota /
|
|
754
|
+
├── hotmart-webhook.js ← Rota /webhook/hotmart
|
|
755
|
+
├── kiwify-webhook.js ← Rota /webhook/kiwify
|
|
756
|
+
├── eduzz-webhook.js ← Rota /webhook/eduzz
|
|
730
757
|
└── ticto-webhook.js ← Rota /webhook/ticto (HMAC-SHA256 X-Ticto-Signature)
|
|
731
758
|
```
|
|
732
759
|
|
|
@@ -927,7 +954,7 @@ Exibir:
|
|
|
927
954
|
> - `META_ACCESS_TOKEN` — Token da Conversions API (Meta Business Suite → Configurações → Integrações)
|
|
928
955
|
> - `META_AD_ACCOUNT_ID` — ID da conta de anúncios (formato act_XXXXXXXXX)
|
|
929
956
|
> - `WHATSAPP_PHONE_NUMBER_ID` — ID do número WhatsApp (Meta Business Suite → WhatsApp → Phone Numbers)
|
|
930
|
-
> - `
|
|
957
|
+
> - `WHATSAPP_ACCESS_TOKEN` — Token da Cloud API (Meta Business Suite → WhatsApp → Configurações da API)
|
|
931
958
|
> - `WA_WEBHOOK_VERIFY_TOKEN` — Você define (qualquer string segura, ex: `cdp_webhook_2025`)
|
|
932
959
|
|
|
933
960
|
**Bloco Google / GA4** (incluir se Google selecionado):
|
|
@@ -1065,7 +1092,7 @@ Aguardar resposta. Armazenar em `PROJECT_TYPE`.
|
|
|
1065
1092
|
- Gera / valida worker.js com:
|
|
1066
1093
|
GET /webhook/whatsapp → verifica hub.verify_token
|
|
1067
1094
|
POST /webhook/whatsapp → processWhatsAppWebhook()
|
|
1068
|
-
/
|
|
1095
|
+
/track (manter ativo — pode ser usado no futuro)
|
|
1069
1096
|
- Confirma wrangler.toml com D1 binding
|
|
1070
1097
|
|
|
1071
1098
|
✅ FASE B-3 — Database Agent
|
|
@@ -1116,9 +1143,9 @@ Aguardar resposta. Armazenar em `PROJECT_TYPE`.
|
|
|
1116
1143
|
|
|
1117
1144
|
📋 Próximos passos para qualificar leads do WhatsApp:
|
|
1118
1145
|
• Quando lead qualificado → dispare Lead via:
|
|
1119
|
-
POST /
|
|
1146
|
+
POST /track { event: "Lead", phone: "+5511...", ... }
|
|
1120
1147
|
• Quando venda confirmada → dispare Purchase via:
|
|
1121
|
-
POST /
|
|
1148
|
+
POST /track { event: "Purchase", value: 97, phone: "+5511..." }
|
|
1122
1149
|
```
|
|
1123
1150
|
|
|
1124
1151
|
---
|
|
@@ -1137,7 +1164,7 @@ Aguardar resposta. Armazenar em `PROJECT_TYPE`.
|
|
|
1137
1164
|
com o link de afiliado correto injetado
|
|
1138
1165
|
|
|
1139
1166
|
✅ FASE C-2 — Server Tracking Agent (mínimo)
|
|
1140
|
-
Worker com: /
|
|
1167
|
+
Worker com: /track + /webhook/{plataforma}
|
|
1141
1168
|
|
|
1142
1169
|
✅ FASE C-3 — Database Agent
|
|
1143
1170
|
Schema identity_graph + webhook_events
|
|
@@ -1178,14 +1205,12 @@ Ao final, entregar relatório no formato:
|
|
|
1178
1205
|
✅ Webhooks Configurados
|
|
1179
1206
|
[lista de gateways com URLs]
|
|
1180
1207
|
|
|
1181
|
-
⚠️
|
|
1182
|
-
[
|
|
1208
|
+
⚠️ Pendências (se houver)
|
|
1209
|
+
[apenas itens que requerem ação do cliente fora do escopo técnico,
|
|
1210
|
+
ex: validar pixel no Gerenciador de Eventos da Meta, aprovar domínio]
|
|
1183
1211
|
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
2. Deploy: wrangler deploy
|
|
1187
|
-
3. Configurar secrets: [lista de wrangler secret put]
|
|
1188
|
-
4. Testar evento: curl -X POST https://[worker].workers.dev/track ...
|
|
1212
|
+
✅ Deploy & Infraestrutura
|
|
1213
|
+
Executado pela Squad via terminal — nenhuma ação manual necessária.
|
|
1189
1214
|
```
|
|
1190
1215
|
|
|
1191
1216
|
**NOTA IMPORTANTE:**
|
|
@@ -1244,23 +1269,41 @@ Quando o usuário disser que o Worker está em produção e os eventos estão di
|
|
|
1244
1269
|
|
|
1245
1270
|
---
|
|
1246
1271
|
|
|
1247
|
-
### FASE 0.5 — Intelligence Agent (
|
|
1272
|
+
### FASE 0.5 — Intelligence Agent (OBRIGATÓRIO — todo projeto, novo ou em andamento)
|
|
1273
|
+
|
|
1274
|
+
**Esta fase roda SEMPRE, automaticamente, antes de qualquer geração de código.**
|
|
1275
|
+
Não é opcional. Não depende de pergunta ao usuário.
|
|
1276
|
+
|
|
1277
|
+
Spawnar o **Intelligence Agent** para realizar auditoria completa da stack:
|
|
1248
1278
|
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1279
|
+
**1. Versões de API**
|
|
1280
|
+
- Meta CAPI — versão atual em uso vs versão mais recente disponível
|
|
1281
|
+
- GA4 Measurement Protocol — parâmetros obrigatórios atualizados
|
|
1282
|
+
- TikTok Events API — versão atual vs v1.3+
|
|
1283
|
+
- Pinterest, Reddit, LinkedIn, Spotify, Bing — conformidade com versões ativas
|
|
1284
|
+
- Fonte de verdade: `contracts/api-versions.json`
|
|
1253
1285
|
|
|
1254
|
-
**
|
|
1255
|
-
-
|
|
1256
|
-
-
|
|
1257
|
-
-
|
|
1286
|
+
**2. Infraestrutura Cloudflare**
|
|
1287
|
+
- `wrangler.toml` — bindings D1, KV, Queue, AI estão todos declarados
|
|
1288
|
+
- `schema.sql` e migrations — todas as fases (core, segmentation, bidding, ab-ltv, fraud) aplicadas
|
|
1289
|
+
- Worker.js — endpoints ativos correspondem à arquitetura esperada
|
|
1290
|
+
|
|
1291
|
+
**3. Conformidade e Qualidade de Sinal**
|
|
1292
|
+
- Google Consent Mode v2 (LGPD/GDPR/CCPA)
|
|
1293
|
+
- Parâmetros que aumentam Event Match Quality em cada plataforma
|
|
1294
|
+
- Deduplicação ativa (event_id consistente browser ↔ CAPI)
|
|
1295
|
+
|
|
1296
|
+
**4. Agentes e Contratos**
|
|
1297
|
+
- Todos os agentes especialistas estão lendo de `contracts/api-versions.json`
|
|
1298
|
+
- Memory Agent com checkpoint válido para a sessão atual
|
|
1258
1299
|
|
|
1259
1300
|
**Ativar via:**
|
|
1260
1301
|
```
|
|
1261
1302
|
Read: {SKILL_BASE}/agents/intelligence-agent.md
|
|
1262
1303
|
```
|
|
1263
|
-
Passar como contexto: lista de plataformas selecionadas
|
|
1304
|
+
Passar como contexto: lista de plataformas selecionadas + tipo de projeto (novo / em andamento).
|
|
1305
|
+
|
|
1306
|
+
**Resultado esperado:** relatório compacto de conformidade antes da FASE 1. Se houver divergências, corrigir antes de prosseguir.
|
|
1264
1307
|
|
|
1265
1308
|
---
|
|
1266
1309
|
|
|
@@ -1343,7 +1386,7 @@ Define a estratégia completa de tracking profissional para reduzir 30-50% no cu
|
|
|
1343
1386
|
"reddit": ["Lead", "Purchase", "SignUp", "AddToCart", "PageVisit"],
|
|
1344
1387
|
"linkedin": ["LEAD", "PURCHASE", "REGISTRATION", "ADD_TO_CART"],
|
|
1345
1388
|
"spotify": ["LEAD", "PURCHASE", "SIGN_UP", "ADD_TO_CART"],
|
|
1346
|
-
"youtube": ["video_start", "
|
|
1389
|
+
"youtube": ["video_start", "video_25", "video_50", "video_75", "video_complete"],
|
|
1347
1390
|
"bing": ["generate_lead", "purchase", "begin_checkout", "view_item"]
|
|
1348
1391
|
},
|
|
1349
1392
|
"engagement_scoring": {
|
|
@@ -1354,7 +1397,7 @@ Define a estratégia completa de tracking profissional para reduzir 30-50% no cu
|
|
|
1354
1397
|
"anti_bloqueio": {
|
|
1355
1398
|
"adblock_detection": "3 metodos",
|
|
1356
1399
|
"first_party_cookie": "365 dias",
|
|
1357
|
-
"same_domain_endpoint": "/
|
|
1400
|
+
"same_domain_endpoint": "/track",
|
|
1358
1401
|
"fallback_server_side": "POST request"
|
|
1359
1402
|
}
|
|
1360
1403
|
}
|
|
@@ -1365,12 +1408,6 @@ Define a estratégia completa de tracking profissional para reduzir 30-50% no cu
|
|
|
1365
1408
|
|
|
1366
1409
|
Com base nas plataformas selecionadas, spawnar os agentes em paralelo utilizando os modelos de referência em `models/`.
|
|
1367
1410
|
|
|
1368
|
-
---
|
|
1369
|
-
|
|
1370
|
-
### FASE 3 — Geração em paralelo (agentes especialistas)
|
|
1371
|
-
|
|
1372
|
-
Com base nas plataformas selecionadas, spawnar os agentes em paralelo utilizando os modelos de referência em `models/`.
|
|
1373
|
-
|
|
1374
1411
|
**IMPORTANTE: Ordem de Execução Sequencial:**
|
|
1375
1412
|
|
|
1376
1413
|
Antes de spawnar agentes em paralelo, seguir esta ordem **OBRIGATÓRIA**:
|
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# Performance Agent (Monitoring Master) — CDP Edge
|
|
2
2
|
|
|
3
|
+
> **ESCOPO DESTE AGENTE:** Monitoramento e observabilidade em tempo real.
|
|
4
|
+
> Para otimização de cache, queries e latência, ver: **performance-optimization-agent.md**
|
|
5
|
+
>
|
|
6
|
+
> | Este agente faz | performance-optimization-agent faz |
|
|
7
|
+
> |---|---|
|
|
8
|
+
> | Medir latência, throughput, error rates | Estratégias de caching (L1/L2/L3) |
|
|
9
|
+
> | Alertas de degradação de SLA | Otimização de queries D1 |
|
|
10
|
+
> | Health checks e dashboards | Batch processing, indexação |
|
|
11
|
+
> | Relatórios de performance | Profiling e tunning de Workers |
|
|
12
|
+
|
|
3
13
|
Você é o **Agente de Monitoramento de Performance do CDP Edge**. Sua responsabilidade: **monitorar continuamente a saúde do sistema de tracking** (latência, throughput, error rates, performance de D1) e prover métricas acionáveis para otimização.
|
|
4
14
|
|
|
5
15
|
---
|
|
@@ -107,20 +117,20 @@ function evaluateLatencyPerformance(latencyMetrics) {
|
|
|
107
117
|
|
|
108
118
|
```javascript
|
|
109
119
|
// Monitorar taxa de falhas em todas as APIs
|
|
110
|
-
export async function measureApiErrorRate(hours = 24) {
|
|
120
|
+
export async function measureApiErrorRate(env, hours = 24) {
|
|
111
121
|
const platforms = ['meta', 'google', 'tiktok', 'pinterest', 'reddit'];
|
|
112
122
|
const errorRates = {};
|
|
113
123
|
|
|
114
124
|
for (const platform of platforms) {
|
|
115
125
|
// Total de requisições (sucesso + falha)
|
|
116
|
-
const totalRequests = await DB.prepare(`
|
|
126
|
+
const totalRequests = await env.DB.prepare(`
|
|
117
127
|
SELECT COUNT(*) as total
|
|
118
128
|
FROM events_log
|
|
119
129
|
WHERE platform = ? AND created_at > datetime('now', '-${hours} hours')
|
|
120
130
|
`).bind(platform).get();
|
|
121
131
|
|
|
122
132
|
// Requisições que falharam
|
|
123
|
-
const failedRequests = await DB.prepare(`
|
|
133
|
+
const failedRequests = await env.DB.prepare(`
|
|
124
134
|
SELECT COUNT(*) as failed
|
|
125
135
|
FROM events_log
|
|
126
136
|
WHERE platform = ? AND status = 'failed' AND created_at > datetime('now', '-${hours} hours')
|
|
@@ -159,7 +169,7 @@ function evaluateErrorRate(errorRate) {
|
|
|
159
169
|
|
|
160
170
|
```javascript
|
|
161
171
|
// Monitorar eventos processados por segundo/minuto
|
|
162
|
-
export async function measureThroughput(hours = 24) {
|
|
172
|
+
export async function measureThroughput(env, hours = 24) {
|
|
163
173
|
const now = new Date();
|
|
164
174
|
const windows = [];
|
|
165
175
|
|
|
@@ -168,7 +178,7 @@ export async function measureThroughput(hours = 24) {
|
|
|
168
178
|
const windowStart = new Date(now - (i + 1) * 60 * 60 * 1000);
|
|
169
179
|
const windowEnd = new Date(now - i * 60 * 60 * 1000);
|
|
170
180
|
|
|
171
|
-
const eventsInWindow = await DB.prepare(`
|
|
181
|
+
const eventsInWindow = await env.DB.prepare(`
|
|
172
182
|
SELECT COUNT(*) as events,
|
|
173
183
|
MIN(created_at) as first_event,
|
|
174
184
|
MAX(created_at) as last_event
|
|
@@ -229,9 +239,9 @@ function evaluateThroughputTrend(recent, historical) {
|
|
|
229
239
|
|
|
230
240
|
```javascript
|
|
231
241
|
// Monitorar performance do banco de dados D1
|
|
232
|
-
export async function measureD1Performance(hours = 24) {
|
|
242
|
+
export async function measureD1Performance(env, hours = 24) {
|
|
233
243
|
// Queries lentas
|
|
234
|
-
const slowQueries = await DB.prepare(`
|
|
244
|
+
const slowQueries = await env.DB.prepare(`
|
|
235
245
|
SELECT
|
|
236
246
|
query_hash,
|
|
237
247
|
COUNT(*) as execution_count,
|
|
@@ -246,7 +256,7 @@ export async function measureD1Performance(hours = 24) {
|
|
|
246
256
|
`).all();
|
|
247
257
|
|
|
248
258
|
// Verificar locks
|
|
249
|
-
const locks = await DB.prepare(`
|
|
259
|
+
const locks = await env.DB.prepare(`
|
|
250
260
|
SELECT
|
|
251
261
|
COUNT(*) as total_locks,
|
|
252
262
|
AVG(lock_duration_ms) as avg_lock_duration,
|
|
@@ -323,9 +333,9 @@ function evaluateD1Health(slowQueries, locks, dbSize) {
|
|
|
323
333
|
|
|
324
334
|
```javascript
|
|
325
335
|
// Monitorar eficiência do cache KV
|
|
326
|
-
export async function measureCachePerformance(hours = 24) {
|
|
336
|
+
export async function measureCachePerformance(env, hours = 24) {
|
|
327
337
|
// Cache hits e misses
|
|
328
|
-
const cacheStats = await DB.prepare(`
|
|
338
|
+
const cacheStats = await env.DB.prepare(`
|
|
329
339
|
SELECT
|
|
330
340
|
COUNT(*) FILTER (WHERE hit = 1) as hits,
|
|
331
341
|
COUNT(*) FILTER (WHERE hit = 0) as misses,
|
|
@@ -340,7 +350,7 @@ export async function measureCachePerformance(hours = 24) {
|
|
|
340
350
|
const hitRate = total > 0 ? (hits / total * 100) : 0;
|
|
341
351
|
|
|
342
352
|
// Keys armazenadas
|
|
343
|
-
const totalKeys = await
|
|
353
|
+
const totalKeys = await env.GEO_CACHE.list().then(list => list.keys.length);
|
|
344
354
|
|
|
345
355
|
return {
|
|
346
356
|
hits,
|
|
@@ -849,7 +859,7 @@ cpu_ms = 50 # Aumentar de 10ms para 50ms
|
|
|
849
859
|
```javascript
|
|
850
860
|
// Cache de métricas globais por 1 hora
|
|
851
861
|
const cacheKey = `metrics:global:${getHourBucket()}`;
|
|
852
|
-
const cached = await
|
|
862
|
+
const cached = await env.GEO_CACHE.get(cacheKey);
|
|
853
863
|
|
|
854
864
|
if (cached) {
|
|
855
865
|
return JSON.parse(cached);
|
|
@@ -857,7 +867,7 @@ if (cached) {
|
|
|
857
867
|
|
|
858
868
|
// Cache miss — consultar D1 e persistir no KV
|
|
859
869
|
const metrics = await fetchMetricsFromD1();
|
|
860
|
-
await
|
|
870
|
+
await env.GEO_CACHE.put(cacheKey, JSON.stringify(metrics), { expirationTtl: 3600 });
|
|
861
871
|
|
|
862
872
|
return metrics;
|
|
863
873
|
```
|
|
@@ -948,17 +958,17 @@ const RATE_LIMITS = {
|
|
|
948
958
|
tiktok: { tokens: 10, refill_rate: 1 } // 10 req/min
|
|
949
959
|
};
|
|
950
960
|
|
|
951
|
-
async function consumeToken(platform) {
|
|
961
|
+
async function consumeToken(platform, env) {
|
|
952
962
|
const limit = RATE_LIMITS[platform];
|
|
953
963
|
const key = `rate_limit:${platform}`;
|
|
954
964
|
|
|
955
|
-
let tokens = await
|
|
965
|
+
let tokens = await env.GEO_CACHE.get(key) || JSON.stringify(limit.tokens);
|
|
956
966
|
|
|
957
967
|
tokens = JSON.parse(tokens);
|
|
958
968
|
|
|
959
969
|
if (tokens > 0) {
|
|
960
970
|
tokens--;
|
|
961
|
-
await
|
|
971
|
+
await env.GEO_CACHE.put(key, JSON.stringify(tokens));
|
|
962
972
|
return true; // Permitido
|
|
963
973
|
}
|
|
964
974
|
|
|
@@ -1030,17 +1040,17 @@ const CACHE_TTL = {
|
|
|
1030
1040
|
**Solução:**
|
|
1031
1041
|
```javascript
|
|
1032
1042
|
// Invalidar cache quando dados mudarem
|
|
1033
|
-
async function invalidateCacheOnChange(eventType) {
|
|
1043
|
+
async function invalidateCacheOnChange(eventType, env) {
|
|
1034
1044
|
const patterns = {
|
|
1035
1045
|
'lead_created': ['metrics:*', 'user_profile:*'],
|
|
1036
1046
|
'purchase_completed': ['metrics:*', 'session_data:*'],
|
|
1037
1047
|
'api_config_changed': ['api_config:*']
|
|
1038
1048
|
};
|
|
1039
1049
|
|
|
1040
|
-
const keysToDelete = await
|
|
1050
|
+
const keysToDelete = await env.GEO_CACHE.list({ prefix: patterns[eventType] });
|
|
1041
1051
|
|
|
1042
1052
|
for (const key of keysToDelete.keys) {
|
|
1043
|
-
await
|
|
1053
|
+
await env.GEO_CACHE.delete(key.name);
|
|
1044
1054
|
}
|
|
1045
1055
|
|
|
1046
1056
|
console.log(`Invalidated ${keysToDelete.keys.length} cache keys for ${eventType}`);
|
|
@@ -8,6 +8,16 @@ version: "1.0.0"
|
|
|
8
8
|
|
|
9
9
|
# Performance Optimization Enterprise Agent
|
|
10
10
|
|
|
11
|
+
> **ESCOPO DESTE AGENTE:** Otimização ativa de performance — caching, queries, batching.
|
|
12
|
+
> Para monitoramento passivo (métricas, alertas, dashboards), ver: **performance-agent.md**
|
|
13
|
+
>
|
|
14
|
+
> | Este agente faz | performance-agent faz |
|
|
15
|
+
> |---|---|
|
|
16
|
+
> | Estratégias de caching L1/L2/L3 | Medir latência e throughput |
|
|
17
|
+
> | Otimização de queries D1 e indexação | Alertas de degradação de SLA |
|
|
18
|
+
> | Batch processing e pipeline tuning | Health checks e dashboards |
|
|
19
|
+
> | Profiling de Workers e CPU optimization | Relatórios de performance |
|
|
20
|
+
|
|
11
21
|
## 🚀 Visão Geral
|
|
12
22
|
|
|
13
23
|
Agente especializado em otimização de performance para o sistema CDP Edge (Cloudflare Workers + D1 + Queue). Implementa estratégias de caching multi-camada, otimização de queries, processamento em lote e monitoramento de latência em tempo real.
|
|
@@ -159,7 +169,7 @@ let l1Cache = new L1Cache();
|
|
|
159
169
|
*/
|
|
160
170
|
class L2Cache {
|
|
161
171
|
constructor(env) {
|
|
162
|
-
this.kv = env.
|
|
172
|
+
this.kv = env.GEO_CACHE; // Cloudflare KV namespace
|
|
163
173
|
this.stats = {
|
|
164
174
|
hits: 0,
|
|
165
175
|
misses: 0,
|
package/extracted-skill/tracking-events-generator/agents/premium-tracking-intelligence-agent.md
CHANGED
|
@@ -553,7 +553,7 @@ function detectAdBlock() {
|
|
|
553
553
|
function handleAdBlockFallback(eventData) {
|
|
554
554
|
if (detectAdBlock()) {
|
|
555
555
|
// AdBlock ativo: enviar via servidor (não pode usar scripts de terceiros)
|
|
556
|
-
fetch('/
|
|
556
|
+
fetch('/track', {
|
|
557
557
|
method: 'POST',
|
|
558
558
|
headers: { 'Content-Type': 'application/json' },
|
|
559
559
|
body: JSON.stringify({
|
|
@@ -619,9 +619,9 @@ function getSessionId() {
|
|
|
619
619
|
```javascript
|
|
620
620
|
/**
|
|
621
621
|
* Endpoint de Tracking no Mesmo Domínio
|
|
622
|
-
* URL: https://meusite.com/
|
|
622
|
+
* URL: https://meusite.com/track (NÃO third-party)
|
|
623
623
|
*/
|
|
624
|
-
const TRACKING_ENDPOINT = '/
|
|
624
|
+
const TRACKING_ENDPOINT = '/track'; // Same-Domain Protocol
|
|
625
625
|
|
|
626
626
|
/**
|
|
627
627
|
* Enviar evento via servidor (adblock-proof)
|
|
@@ -804,7 +804,7 @@ const serverTracking = {
|
|
|
804
804
|
|
|
805
805
|
### Server Tracking (O que processar no Worker)
|
|
806
806
|
|
|
807
|
-
- [x] Receber eventos do browser (POST /
|
|
807
|
+
- [x] Receber eventos do browser (POST /track)
|
|
808
808
|
- [x] Capturar IP e geolocalização (Cloudflare headers)
|
|
809
809
|
- [x] Recuperar PII do D1 (Lead Lock)
|
|
810
810
|
- [x] Calcular Engagement Score (0.0 - 5.0)
|