cdp-edge 2.3.9 → 2.5.2
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 +54 -4
- package/bin/cdp-edge.js +3 -2
- package/contracts/agent-versions.json +383 -83
- package/dist/commands/validate.js +248 -84
- package/dist/sdk/cdpTrack.js +2095 -0
- package/dist/sdk/cdpTrack.min.js +64 -0
- package/dist/sdk/install-snippet.html +10 -0
- package/extracted-skill/tracking-events-generator/agents/ab-ltv-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/ab-testing-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/attribution-agent.md +18 -18
- package/extracted-skill/tracking-events-generator/agents/bidding-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/bing-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/code-guardian-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/compliance-agent.md +5 -5
- package/extracted-skill/tracking-events-generator/agents/crm-integration-agent.md +10 -10
- package/extracted-skill/tracking-events-generator/agents/dashboard-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/database-agent.md +17 -25
- package/extracted-skill/tracking-events-generator/agents/debug-agent.md +9 -9
- package/extracted-skill/tracking-events-generator/agents/devops-agent.md +18 -1
- package/extracted-skill/tracking-events-generator/agents/domain-setup-agent.md +5 -5
- package/extracted-skill/tracking-events-generator/agents/email-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/fingerprint-agent.md +4 -4
- package/extracted-skill/tracking-events-generator/agents/fraud-detection-agent.md +2 -0
- package/extracted-skill/tracking-events-generator/agents/google-agent.md +2 -2
- package/extracted-skill/tracking-events-generator/agents/intelligence-agent.md +23 -29
- package/extracted-skill/tracking-events-generator/agents/linkedin-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/localization-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/ltv-predictor-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/master-feedback-loop.md +16 -16
- package/extracted-skill/tracking-events-generator/agents/master-orchestrator.md +13 -13
- package/extracted-skill/tracking-events-generator/agents/memory-agent.md +14 -14
- package/extracted-skill/tracking-events-generator/agents/meta-agent.md +2 -2
- package/extracted-skill/tracking-events-generator/agents/ml-clustering-agent.md +9 -9
- package/extracted-skill/tracking-events-generator/agents/page-analyzer.md +1 -0
- package/extracted-skill/tracking-events-generator/agents/performance-agent.md +12 -12
- package/extracted-skill/tracking-events-generator/agents/performance-optimization-agent.md +7 -7
- package/extracted-skill/tracking-events-generator/agents/pinterest-agent.md +6 -6
- package/extracted-skill/tracking-events-generator/agents/premium-tracking-intelligence-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/r2-setup-agent.md +8 -8
- package/extracted-skill/tracking-events-generator/agents/reddit-agent.md +7 -7
- package/extracted-skill/tracking-events-generator/agents/security-enterprise-agent.md +21 -21
- package/extracted-skill/tracking-events-generator/agents/server-tracking.md +15 -15
- package/extracted-skill/tracking-events-generator/agents/spotify-agent.md +6 -6
- package/extracted-skill/tracking-events-generator/agents/tiktok-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/tracking-plan-agent.md +5 -5
- package/extracted-skill/tracking-events-generator/agents/validator-agent.md +9 -9
- package/extracted-skill/tracking-events-generator/agents/webhook-agent.md +4 -4
- package/extracted-skill/tracking-events-generator/agents/whatsapp-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/whatsapp-ctwa-setup-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/youtube-agent.md +9 -9
- package/extracted-skill/tracking-events-generator/anti-blocking.js +1 -1
- package/extracted-skill/tracking-events-generator/cdpTrack.js +0 -10
- package/extracted-skill/tracking-events-generator/engagement-scoring.js +2 -2
- package/extracted-skill/tracking-events-generator/micro-events.js +1 -1
- package/extracted-skill/tracking-events-generator/tracking.config.js +3 -3
- package/package.json +5 -1
- package/scripts/build-sdk.js +106 -0
- package/server-edge-tracker/index.ts +93 -0
- package/server-edge-tracker/schema-utm.sql +5 -3
- package/server-edge-tracker/wrangler.toml +1 -1
- package/extracted-skill/tracking-events-generator/agents/intelligence-scheduling.md +0 -10
|
@@ -26,7 +26,7 @@ Prover **ferramentas profissionais de diagnóstico** que permitam identificar, i
|
|
|
26
26
|
|
|
27
27
|
### 1.1 Log de Worker (Server-Side)
|
|
28
28
|
|
|
29
|
-
```
|
|
29
|
+
```typescript
|
|
30
30
|
// Funções de logging estruturado para Cloudflare Worker
|
|
31
31
|
export const WORKER_LOG_LEVELS = {
|
|
32
32
|
ERROR: 'ERROR',
|
|
@@ -276,7 +276,7 @@ CREATE INDEX IF NOT EXISTS idx_browser_logs_session ON browser_logs(session_id);
|
|
|
276
276
|
|
|
277
277
|
### 2.1 Endpoint `/debug` — Informações Gerais
|
|
278
278
|
|
|
279
|
-
```
|
|
279
|
+
```typescript
|
|
280
280
|
// Endpoint de diagnóstico geral do sistema
|
|
281
281
|
export async function handleDebugRequest(request, env) {
|
|
282
282
|
const debugInfo = {
|
|
@@ -360,7 +360,7 @@ async function getApiHealth(platform) {
|
|
|
360
360
|
|
|
361
361
|
### 2.2 Endpoint `/health` — Health Check Simplificado
|
|
362
362
|
|
|
363
|
-
```
|
|
363
|
+
```typescript
|
|
364
364
|
// Endpoint simplificado para monitoring externo
|
|
365
365
|
export async function handleHealthCheck(request, env) {
|
|
366
366
|
const checks = {
|
|
@@ -426,7 +426,7 @@ async function getSimpleApiHealth(platform) {
|
|
|
426
426
|
|
|
427
427
|
### 2.3 Endpoint `/events-log` — Logs de Eventos Recentes
|
|
428
428
|
|
|
429
|
-
```
|
|
429
|
+
```typescript
|
|
430
430
|
// Endpoint para consultar logs de eventos
|
|
431
431
|
export async function handleEventsLogRequest(request, env) {
|
|
432
432
|
const url = new URL(request.url);
|
|
@@ -630,7 +630,7 @@ export async function handleEventsLogRequest(request, env) {
|
|
|
630
630
|
|
|
631
631
|
### 4.1 Diagnóstico de Erros de Meta (400/401/429)
|
|
632
632
|
|
|
633
|
-
```
|
|
633
|
+
```typescript
|
|
634
634
|
// Análise de erros específicos de Meta API
|
|
635
635
|
export async function diagnoseMetaError(errorCode, errorContext) {
|
|
636
636
|
const errorMap = {
|
|
@@ -747,7 +747,7 @@ export async function diagnoseMetaError(errorCode, errorContext) {
|
|
|
747
747
|
|
|
748
748
|
### 4.2 Diagnóstico de Erros de Google (400/401/429)
|
|
749
749
|
|
|
750
|
-
```
|
|
750
|
+
```typescript
|
|
751
751
|
// Análise de erros específicos de Google API
|
|
752
752
|
export async function diagnoseGoogleError(errorCode, errorContext) {
|
|
753
753
|
const errorMap = {
|
|
@@ -847,7 +847,7 @@ export async function diagnoseGoogleError(errorCode, errorContext) {
|
|
|
847
847
|
|
|
848
848
|
### 4.3 Diagnóstico de Erros de TikTok (400/401/429)
|
|
849
849
|
|
|
850
|
-
```
|
|
850
|
+
```typescript
|
|
851
851
|
// Análise de erros específicos de TikTok API
|
|
852
852
|
export async function diagnoseTikTokError(errorCode, errorContext) {
|
|
853
853
|
const errorMap = {
|
|
@@ -967,9 +967,9 @@ export async function diagnoseTikTokError(errorCode, errorContext) {
|
|
|
967
967
|
|
|
968
968
|
## 🎯 FORMATO DE SAÍDA
|
|
969
969
|
|
|
970
|
-
### DELIVERABLE 1: `debug-endpoints.
|
|
970
|
+
### DELIVERABLE 1: `modules/debug-endpoints.ts`
|
|
971
971
|
|
|
972
|
-
```
|
|
972
|
+
```typescript
|
|
973
973
|
// Funções de diagnóstico para Cloudflare Worker
|
|
974
974
|
import { logWorker, WORKER_LOG_LEVELS } from './worker-logging.js';
|
|
975
975
|
import { getApiHealth, getSimpleApiHealth } from './api-health.js';
|
|
@@ -120,6 +120,10 @@ wrangler d1 execute cdp-edge-db --file=schema-indexes.sql --remote
|
|
|
120
120
|
# Fase 5: LTV Model (regressão logística) + Match Quality Log
|
|
121
121
|
wrangler d1 execute cdp-edge-db --file=migrate-v7.sql --remote
|
|
122
122
|
|
|
123
|
+
# Fase 5b: Colunas LTV Feedback em user_profiles (real_ltv_value, ltv_accuracy, ltv_feedback_at)
|
|
124
|
+
# OBRIGATÓRIO — sem isso recordLtvFeedback() falha silenciosamente em todo Purchase com value > 0
|
|
125
|
+
wrangler d1 execute cdp-edge-db --file=schema-ltv-feedback.sql --remote
|
|
126
|
+
|
|
123
127
|
# UTM Segmentação
|
|
124
128
|
wrangler d1 execute cdp-edge-db --file=schema-utm.sql --remote
|
|
125
129
|
|
|
@@ -141,6 +145,12 @@ Após cada migração: confirmar sucesso antes de prosseguir.
|
|
|
141
145
|
> - `match_quality_log` — registra flags de qualidade de dados (has_email, has_fbp, etc.) a cada CAPI dispatch
|
|
142
146
|
> Sem essas tabelas: o modelo LTV não persiste e o Match Quality Alert não funciona.
|
|
143
147
|
>
|
|
148
|
+
> **Fase 5b adiciona 3 colunas em `user_profiles` (ALTER TABLE):**
|
|
149
|
+
> - `real_ltv_value` — valor real de compra registrado após Purchase
|
|
150
|
+
> - `ltv_accuracy` — acurácia do modelo: `1 - |pred-real|/real` (0–1)
|
|
151
|
+
> - `ltv_feedback_at` — timestamp do último feedback
|
|
152
|
+
> **SEM ESSA MIGRAÇÃO:** `recordLtvFeedback()` falha silenciosamente em todo Purchase com value > 0 — ciclo preditivo nunca fecha.
|
|
153
|
+
>
|
|
144
154
|
> **Fase 6 (Lead Scoring) cria:**
|
|
145
155
|
> - `quiz_sessions` — qualificação por lead com breakdown dimensional auditável
|
|
146
156
|
> - `v_quiz_qualification_summary`, `v_quiz_dimension_impact` — VIEWs de análise
|
|
@@ -179,7 +189,11 @@ wrangler secret put WHATSAPP_PHONE_NUMBER_ID
|
|
|
179
189
|
wrangler secret put WA_NOTIFY_NUMBER
|
|
180
190
|
wrangler secret put WA_WEBHOOK_VERIFY_TOKEN
|
|
181
191
|
|
|
182
|
-
#
|
|
192
|
+
# Nurture Engine — email (obrigatório se Nurture habilitado)
|
|
193
|
+
wrangler secret put RESEND_API_KEY # API Key resend.com
|
|
194
|
+
wrangler secret put RESEND_FROM_EMAIL # ex: "CDP Edge <noreply@seudominio.com.br>"
|
|
195
|
+
|
|
196
|
+
# Plataformas de anúncio opcionais (conforme selecionadas)
|
|
183
197
|
wrangler secret put TIKTOK_ACCESS_TOKEN
|
|
184
198
|
wrangler secret put PINTEREST_ACCESS_TOKEN
|
|
185
199
|
wrangler secret put REDDIT_ACCESS_TOKEN
|
|
@@ -187,6 +201,9 @@ wrangler secret put LINKEDIN_ACCESS_TOKEN
|
|
|
187
201
|
wrangler secret put SPOTIFY_ACCESS_TOKEN
|
|
188
202
|
wrangler secret put CALLMEBOT_PHONE
|
|
189
203
|
wrangler secret put CALLMEBOT_APIKEY
|
|
204
|
+
|
|
205
|
+
# Webhooks de gateway de pagamento
|
|
206
|
+
wrangler secret put WEBHOOK_SECRET_TICTO # HMAC-SHA256 Ticto
|
|
190
207
|
```
|
|
191
208
|
|
|
192
209
|
---
|
|
@@ -139,13 +139,13 @@ SITE_DOMAIN = "clientdomain.com"
|
|
|
139
139
|
|
|
140
140
|
---
|
|
141
141
|
|
|
142
|
-
## Fase 4 — Verificar Cookie Domain no
|
|
142
|
+
## Fase 4 — Verificar Cookie Domain no index.ts
|
|
143
143
|
|
|
144
144
|
O cookie `_cdp_uid` precisa ser definido com `Domain=.clientdomain.com` (ponto antes = root domain = compartilhado entre subdomínios).
|
|
145
145
|
|
|
146
|
-
### Localizar no
|
|
146
|
+
### Localizar no index.ts a função de cookie:
|
|
147
147
|
|
|
148
|
-
```
|
|
148
|
+
```typescript
|
|
149
149
|
// Buscar por: Set-Cookie ou _cdp_uid
|
|
150
150
|
// Deve conter:
|
|
151
151
|
`_cdp_uid=${uid}; Max-Age=31536000; Path=/; Domain=.${env.SITE_DOMAIN}; SameSite=None; Secure`
|
|
@@ -155,7 +155,7 @@ Se o worker usa `env.SITE_DOMAIN` no Domain do cookie (correto), basta atualizar
|
|
|
155
155
|
|
|
156
156
|
Se o worker usa o domínio hardcoded ou `workers.dev`, atualizar manualmente:
|
|
157
157
|
|
|
158
|
-
```
|
|
158
|
+
```typescript
|
|
159
159
|
// Substituir:
|
|
160
160
|
`Domain=.workers.dev`
|
|
161
161
|
// Por:
|
|
@@ -224,7 +224,7 @@ const CDP_ENDPOINT = 'https://track.clientdomain.com/track';
|
|
|
224
224
|
| 522 Connection Timed Out | CNAME não-proxied ou worker offline | Verificar proxy status + `wrangler deploy` |
|
|
225
225
|
| Cookie Domain errado | SITE_DOMAIN antigo | Confirmar `wrangler.toml` + deploy |
|
|
226
226
|
| Worker Route não ativando | Route sem deploy | `wrangler deploy` novamente |
|
|
227
|
-
| CORS error no browser | Origin não permitido | Verificar headers CORS no
|
|
227
|
+
| CORS error no browser | Origin não permitido | Verificar headers CORS no index.ts |
|
|
228
228
|
|
|
229
229
|
---
|
|
230
230
|
|
|
@@ -19,8 +19,8 @@ Webhook Agent (Hotmart/Kiwify/Ticto)
|
|
|
19
19
|
|
|
20
20
|
**Assinatura da função que este agente gera:**
|
|
21
21
|
|
|
22
|
-
```
|
|
23
|
-
// Injetada no Worker principal (
|
|
22
|
+
```typescript
|
|
23
|
+
// Injetada no Worker principal (index.ts)
|
|
24
24
|
export async function sendEmail(env, type, payload) {
|
|
25
25
|
const { to, name, product, value } = payload;
|
|
26
26
|
// ... implementação completa abaixo
|
|
@@ -73,7 +73,7 @@ Sempre que o usuário precisar de automação de e-mail:
|
|
|
73
73
|
```json
|
|
74
74
|
{
|
|
75
75
|
"arquivos_criados": [
|
|
76
|
-
"
|
|
76
|
+
"modules/email-service.ts"
|
|
77
77
|
],
|
|
78
78
|
"tipos_de_email": {
|
|
79
79
|
"purchase_confirmation": "ativo",
|
|
@@ -21,11 +21,11 @@ Sempre que o usuário sangrar dinheiro por culpa de "Perda de Cookies/Atribuiç
|
|
|
21
21
|
|
|
22
22
|
---
|
|
23
23
|
|
|
24
|
-
## 💻 IMPLEMENTAÇÃO REAL —
|
|
24
|
+
## 💻 IMPLEMENTAÇÃO REAL — modules/fingerprint-middleware.ts
|
|
25
25
|
|
|
26
26
|
### Módulo completo para injetar no Worker
|
|
27
27
|
|
|
28
|
-
```
|
|
28
|
+
```typescript
|
|
29
29
|
/**
|
|
30
30
|
* Fingerprint Middleware — CDP Edge
|
|
31
31
|
* Edge-only signals: IP + Accept-Language + UA base + ASN
|
|
@@ -212,7 +212,7 @@ CREATE TABLE IF NOT EXISTS fingerprint_sessions (
|
|
|
212
212
|
CREATE INDEX IF NOT EXISTS idx_fp_last_seen ON fingerprint_sessions(last_seen_at);
|
|
213
213
|
```
|
|
214
214
|
|
|
215
|
-
### Uso no
|
|
215
|
+
### Uso no index.ts
|
|
216
216
|
|
|
217
217
|
```javascript
|
|
218
218
|
// No início do handler /track, ANTES do fraud gate:
|
|
@@ -246,7 +246,7 @@ payload = await fingerprintMiddleware(request, env, payload);
|
|
|
246
246
|
```json
|
|
247
247
|
{
|
|
248
248
|
"arquivos_criados": [
|
|
249
|
-
"
|
|
249
|
+
"modules/fingerprint-middleware.ts"
|
|
250
250
|
],
|
|
251
251
|
"sinais_utilizados": ["ip", "accept-language", "user-agent-base", "cf-asorg"],
|
|
252
252
|
"janela_restauracao_horas": 48,
|
|
@@ -35,6 +35,8 @@ checkFraudGate(env, request, payload)
|
|
|
35
35
|
logFraudSignal(env, ...) → D1: fraud_signals + fraud_alerts
|
|
36
36
|
```
|
|
37
37
|
|
|
38
|
+
**Implementação:** `modules/ml/fraud.ts` — `checkFraudGate(env: Env, request: Request, payload: TrackPayload)` (TypeScript)
|
|
39
|
+
|
|
38
40
|
**Integração automática com fluxo `/track`:**
|
|
39
41
|
- Executa ANTES do LTV, fingerprinting e CAPI
|
|
40
42
|
- Silent drop (retorna 200 ao browser para não vazar a detecção)
|
|
@@ -23,7 +23,7 @@ Especialista exclusivo em GA4 (Measurement Protocol) + Google Ads (Enhanced Conv
|
|
|
23
23
|
|
|
24
24
|
### PASSO 0 — Ler Versões Atuais
|
|
25
25
|
|
|
26
|
-
```
|
|
26
|
+
```typescript
|
|
27
27
|
// Ler versões do arquivo centralizado
|
|
28
28
|
const apiVersions = await readJSON('contracts/api-versions.json');
|
|
29
29
|
const googleVersions = apiVersions.google;
|
|
@@ -213,7 +213,7 @@ Gere payloads para o Worker seguir o protocolo oficial:
|
|
|
213
213
|
{
|
|
214
214
|
"arquivos_gerados": {
|
|
215
215
|
"browser": "cdpTrack.js (eventos GA4 injetados)",
|
|
216
|
-
"server": "
|
|
216
|
+
"server": "modules/dispatch/ga4.ts"
|
|
217
217
|
},
|
|
218
218
|
"versao_api": {
|
|
219
219
|
"ga4_mp": "latest",
|
|
@@ -51,40 +51,34 @@ O Master Orchestrator DEVE configurar o Intelligence Agent para rodar nos seguin
|
|
|
51
51
|
|
|
52
52
|
### IMPLEMENTAÇÃO DO SCHEDULING (No Worker)
|
|
53
53
|
|
|
54
|
-
Adicionar ao `wrangler.toml` e `
|
|
54
|
+
Adicionar ao `wrangler.toml` e `index.ts`:
|
|
55
55
|
|
|
56
56
|
```toml
|
|
57
57
|
# wrangler.toml — Adicionar triggers de cron
|
|
58
58
|
[[triggers.crons]]
|
|
59
59
|
cron = "0 2 * * 0" # Domingo 02:00 UTC — Semanal
|
|
60
|
-
schedule = "weekly-intelligence-check"
|
|
61
60
|
|
|
62
61
|
[[triggers.crons]]
|
|
63
62
|
cron = "0 3 1 * *" # 1º do mês 03:00 UTC — Mensal
|
|
64
|
-
schedule = "monthly-privacy-audit"
|
|
65
63
|
```
|
|
66
64
|
|
|
67
|
-
```
|
|
68
|
-
//
|
|
65
|
+
```typescript
|
|
66
|
+
// index.ts — Handler scheduled() (Cloudflare usa scheduled, não fetch para crons)
|
|
69
67
|
export default {
|
|
70
|
-
async fetch(request, env, ctx) {
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
if (url.pathname === '/track') {
|
|
75
|
-
return handleTracking(request, env, ctx);
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
// Handlers de Intelligence Agent (schedulados)
|
|
79
|
-
if (url.pathname === '/cron/intelligence-weekly') {
|
|
80
|
-
return await runIntelligenceWeekly(env, ctx);
|
|
81
|
-
}
|
|
68
|
+
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
|
|
69
|
+
// Handler principal de eventos
|
|
70
|
+
return handleRequest(request, env, ctx);
|
|
71
|
+
},
|
|
82
72
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
73
|
+
async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext) {
|
|
74
|
+
const cron = event.cron;
|
|
75
|
+
const isMonthly = cron === '0 3 1 * *';
|
|
86
76
|
|
|
87
|
-
|
|
77
|
+
ctx.waitUntil(
|
|
78
|
+
isMonthly
|
|
79
|
+
? runIntelligenceMonthly(env)
|
|
80
|
+
: runIntelligenceWeekly(env)
|
|
81
|
+
);
|
|
88
82
|
}
|
|
89
83
|
};
|
|
90
84
|
|
|
@@ -202,7 +196,7 @@ Quando o Intelligence Agent detectar API desatualizada, emitir alerta estruturad
|
|
|
202
196
|
],
|
|
203
197
|
"action_required": {
|
|
204
198
|
"urgency": "IMMEDIATO",
|
|
205
|
-
"files_to_update": ["
|
|
199
|
+
"files_to_update": ["index.ts", "meta-agent.md"],
|
|
206
200
|
"migration_guide": "https://developers.facebook.com/docs/graph-changelog",
|
|
207
201
|
"estimated_time": "30 minutos"
|
|
208
202
|
},
|
|
@@ -221,7 +215,7 @@ Quando o Intelligence Agent detectar API desatualizada, emitir alerta estruturad
|
|
|
221
215
|
|
|
222
216
|
O Intelligence Agent DEVE executar auditoria completa mensal de LGPD/GDPR/CCPA:
|
|
223
217
|
|
|
224
|
-
```
|
|
218
|
+
```typescript
|
|
225
219
|
async function auditPrivacyCompliance(env) {
|
|
226
220
|
const issues = [];
|
|
227
221
|
|
|
@@ -243,7 +237,7 @@ async function auditPrivacyCompliance(env) {
|
|
|
243
237
|
platform: 'meta/tiktok/pinterest/reddit',
|
|
244
238
|
issue: 'PII enviada sem SHA-256 hashing',
|
|
245
239
|
severity: 'CRITICAL',
|
|
246
|
-
fix: 'Usar crypto.subtle.digest para email/phone no
|
|
240
|
+
fix: 'Usar crypto.subtle.digest para email/phone no index.ts'
|
|
247
241
|
});
|
|
248
242
|
}
|
|
249
243
|
|
|
@@ -271,7 +265,7 @@ async function auditPrivacyCompliance(env) {
|
|
|
271
265
|
|
|
272
266
|
O Intelligence Agent DEVE verificar se alguma API está prestes a ser descontinuada:
|
|
273
267
|
|
|
274
|
-
```
|
|
268
|
+
```typescript
|
|
275
269
|
async function checkApiDepreciations(env) {
|
|
276
270
|
const deprecationSchedule = {
|
|
277
271
|
meta: {
|
|
@@ -337,7 +331,7 @@ Os dados são lidos da tabela `match_quality_log` (populada automaticamente pelo
|
|
|
337
331
|
|
|
338
332
|
O Intelligence Agent DEVE buscar novos parâmetros que melhoram a nota de atribuição:
|
|
339
333
|
|
|
340
|
-
```
|
|
334
|
+
```typescript
|
|
341
335
|
async function checkNewMatchQualityParams(env) {
|
|
342
336
|
const platforms = {
|
|
343
337
|
meta: 'https://developers.facebook.com/docs/marketing-api/conversions-api/parameters',
|
|
@@ -422,7 +416,7 @@ CREATE INDEX IF NOT EXISTS idx_intel_logs_created ON intelligence_logs(created_a
|
|
|
422
416
|
Antes de considerar o scheduling implementado, verificar:
|
|
423
417
|
|
|
424
418
|
- [ ] Cron triggers adicionados ao `wrangler.toml` (`0 2 * * 7` e `0 3 1 * *`)
|
|
425
|
-
- [ ] Handlers `scheduled()` adicionados ao `
|
|
419
|
+
- [ ] Handlers `scheduled()` adicionados ao `index.ts` (Cloudflare usa `scheduled`, não `fetch`)
|
|
426
420
|
- [ ] Schema D1 atualizado com tabela `intelligence_logs`
|
|
427
421
|
- [ ] Funções de check de versão implementadas com endpoints reais
|
|
428
422
|
- [ ] Funções de auditoria de privacidade implementadas
|
|
@@ -437,7 +431,7 @@ Antes de considerar o scheduling implementado, verificar:
|
|
|
437
431
|
## INPUTS RECEBIDOS
|
|
438
432
|
|
|
439
433
|
- `wrangler.toml` do Worker (para injetar Cron Triggers)
|
|
440
|
-
- `
|
|
434
|
+
- `index.ts` (para injetar handlers de `scheduled` events)
|
|
441
435
|
- `schema.sql` (para adicionar tabela `intelligence_logs`)
|
|
442
436
|
- Secrets: `WHATSAPP_PHONE_NUMBER_ID`, `WHATSAPP_ACCESS_TOKEN`, `ADMIN_PHONE_NUMBER` (para alertas)
|
|
443
437
|
- `contracts/api-versions.json` (fonte de verdade das versões atuais)
|
|
@@ -512,7 +506,7 @@ wrangler d1 execute cdp-edge-db --file=schema-sales-engine.sql --remote # Fase 7
|
|
|
512
506
|
{
|
|
513
507
|
"arquivos_modificados": [
|
|
514
508
|
"wrangler.toml (cron triggers adicionados)",
|
|
515
|
-
"
|
|
509
|
+
"index.ts (handler scheduled() adicionado)",
|
|
516
510
|
"schema.sql (tabela intelligence_logs adicionada)"
|
|
517
511
|
],
|
|
518
512
|
"crons_configurados": {
|
|
@@ -32,7 +32,7 @@ LinkedIn é tráfego B2B premium — o CPA é alto, mas o LTV também. Usar valo
|
|
|
32
32
|
|
|
33
33
|
### Como consumir o LTV Predictor no Worker
|
|
34
34
|
|
|
35
|
-
```
|
|
35
|
+
```typescript
|
|
36
36
|
// No handler de evento LinkedIn (Lead ou Purchase via webhook/track):
|
|
37
37
|
import { predictLtv } from './ltv-predictor.js';
|
|
38
38
|
|
|
@@ -153,7 +153,7 @@ Sempre que a integração LinkedIn B2B for selecionada:
|
|
|
153
153
|
|
|
154
154
|
- Redigir o payload JSON Server-Side no padrão rigoroso do LinkedIn CAPI.
|
|
155
155
|
- Enviar as propriedades de evento "Lead" ou "Purchase" acopladas ao LTV preditivo.
|
|
156
|
-
- Recusar-se a escrever implementações frontend pesadas; obrigar a camada `
|
|
156
|
+
- Recusar-se a escrever implementações frontend pesadas; obrigar a camada `index.ts` a herdar a responsabilidade.
|
|
157
157
|
- Despachar o Log de status HTTP do LinkedIn de volta para a tabela de acompanhamento no D1 (`events_log`).
|
|
158
158
|
|
|
159
159
|
## SAÍDA
|
|
@@ -161,7 +161,7 @@ Sempre que a integração LinkedIn B2B for selecionada:
|
|
|
161
161
|
```json
|
|
162
162
|
{
|
|
163
163
|
"arquivos_gerados": {
|
|
164
|
-
"server": "linkedin
|
|
164
|
+
"server": "modules/dispatch/linkedin.ts (módulo do Worker TypeScript)"
|
|
165
165
|
},
|
|
166
166
|
"tecnologia_alvo": "Cloudflare Worker (Server-Side)",
|
|
167
167
|
"api_endpoint": "https://api.linkedin.com/rest/conversionEvents",
|
|
@@ -40,7 +40,7 @@ Sempre que uma campanha Nacional for elevada a nível Global Internacional:
|
|
|
40
40
|
```json
|
|
41
41
|
{
|
|
42
42
|
"arquivos_criados": [
|
|
43
|
-
"
|
|
43
|
+
"modules/localization-rewriter.ts"
|
|
44
44
|
],
|
|
45
45
|
"paises_configurados": ["BR", "US", "PT"],
|
|
46
46
|
"estrategia": "HTMLRewriter — zero redirecionamento",
|
|
@@ -42,7 +42,7 @@ Sempre que o Orquestrador invocar a Otimização de Baleias (LTV Prediction):
|
|
|
42
42
|
```json
|
|
43
43
|
{
|
|
44
44
|
"arquivos_criados": [
|
|
45
|
-
"
|
|
45
|
+
"modules/ml/ltv.ts"
|
|
46
46
|
],
|
|
47
47
|
"modelo_ai": "@cf/ibm-granite/granite-4.0-h-micro",
|
|
48
48
|
"campo_substituido": "value",
|
|
@@ -50,7 +50,7 @@ Implementar um **ciclo virtuoso de melhoria contínua** onde o CDP Edge aprende
|
|
|
50
50
|
|
|
51
51
|
### 1.1 Fontes de Feedback
|
|
52
52
|
|
|
53
|
-
```
|
|
53
|
+
```typescript
|
|
54
54
|
// Coleta estruturada de feedback de todos os agentes
|
|
55
55
|
async function collectFeedback(env) {
|
|
56
56
|
const feedback = {
|
|
@@ -136,7 +136,7 @@ async function collectMemoryAgentFeedback() {
|
|
|
136
136
|
|
|
137
137
|
### 1.2 Coleta de Feedback de Plataformas
|
|
138
138
|
|
|
139
|
-
```
|
|
139
|
+
```typescript
|
|
140
140
|
// Feedback de agentes de plataforma (API versions, deprecations)
|
|
141
141
|
async function collectPlatformAgentFeedback(platform) {
|
|
142
142
|
const feedback = {
|
|
@@ -173,7 +173,7 @@ function calculatePlatformHealthScore(feedback) {
|
|
|
173
173
|
|
|
174
174
|
### 2.1 Identificação de Padrões Recorrentes
|
|
175
175
|
|
|
176
|
-
```
|
|
176
|
+
```typescript
|
|
177
177
|
// Analisar padrões de problemas
|
|
178
178
|
function analyzePatterns(feedback) {
|
|
179
179
|
const patterns = {
|
|
@@ -235,7 +235,7 @@ function calculateTrend(issues) {
|
|
|
235
235
|
|
|
236
236
|
### 2.2 Análise de Causa Raiz Sistêmica
|
|
237
237
|
|
|
238
|
-
```
|
|
238
|
+
```typescript
|
|
239
239
|
// Identificar causas raiz de problemas sistêmicos
|
|
240
240
|
function identifySystemicRootCauses(patterns) {
|
|
241
241
|
const rootCauses = [];
|
|
@@ -309,7 +309,7 @@ function priorityOrder(priority) {
|
|
|
309
309
|
|
|
310
310
|
### 3.1 Matriz de Priorização
|
|
311
311
|
|
|
312
|
-
```
|
|
312
|
+
```typescript
|
|
313
313
|
// Priorizar melhorias baseado em impacto × esforço
|
|
314
314
|
function prioritizeImprovements(rootCauses, feedback) {
|
|
315
315
|
const improvements = rootCauses.map(cause => ({
|
|
@@ -382,7 +382,7 @@ function calculateUrgencyScore(cause) {
|
|
|
382
382
|
|
|
383
383
|
### 3.2 Classificação de Melhorias
|
|
384
384
|
|
|
385
|
-
```
|
|
385
|
+
```typescript
|
|
386
386
|
// Classificar melhorias em categorias
|
|
387
387
|
function classifyImprovements(improvements) {
|
|
388
388
|
return {
|
|
@@ -400,7 +400,7 @@ function classifyImprovements(improvements) {
|
|
|
400
400
|
|
|
401
401
|
### 4.1 Roteamento de Melhorias para Agentes
|
|
402
402
|
|
|
403
|
-
```
|
|
403
|
+
```typescript
|
|
404
404
|
// Rotear melhorias para os agentes apropriados
|
|
405
405
|
async function routeImprovements(improvements) {
|
|
406
406
|
const routing = {
|
|
@@ -463,7 +463,7 @@ function calculateDeadline(priority) {
|
|
|
463
463
|
|
|
464
464
|
### 4.2 Orquestração Paralela de Correções
|
|
465
465
|
|
|
466
|
-
```
|
|
466
|
+
```typescript
|
|
467
467
|
// Executar correções em paralelo sempre que possível
|
|
468
468
|
async function orchestrateCorrections(routing) {
|
|
469
469
|
const results = {
|
|
@@ -533,7 +533,7 @@ async function executeCorrectionsForAgent(agent, tasks) {
|
|
|
533
533
|
|
|
534
534
|
### 5.1 Atualização de Base de Conhecimento
|
|
535
535
|
|
|
536
|
-
```
|
|
536
|
+
```typescript
|
|
537
537
|
// Atualizar knowledge-base.md com aprendizados
|
|
538
538
|
async function updateKnowledgeBase(corrections) {
|
|
539
539
|
const learnings = extractLearnings(corrections);
|
|
@@ -579,7 +579,7 @@ function calculateConfidenceScore(correction) {
|
|
|
579
579
|
|
|
580
580
|
### 5.2 Atualização de Templates e Contratos
|
|
581
581
|
|
|
582
|
-
```
|
|
582
|
+
```typescript
|
|
583
583
|
// Atualizar templates e contratos automaticamente
|
|
584
584
|
async function updateTemplatesAndContracts(corrections) {
|
|
585
585
|
const updates = [];
|
|
@@ -736,7 +736,7 @@ O Master Orchestrator deve salvar em `feedback-loop-cycle-{timestamp}.md` e atua
|
|
|
736
736
|
|
|
737
737
|
### Frequência de Execução
|
|
738
738
|
|
|
739
|
-
```
|
|
739
|
+
```typescript
|
|
740
740
|
// Configuração automática de ciclos de feedback loop
|
|
741
741
|
const FEEDBACK_LOOP_CONFIG = {
|
|
742
742
|
// Ciclo completo: Coleta → Análise → Correção → Atualização
|
|
@@ -809,7 +809,7 @@ CREATE INDEX IF NOT EXISTS idx_vl_severity ON validation_logs(severity);
|
|
|
809
809
|
CREATE INDEX IF NOT EXISTS idx_vl_status ON validation_logs(resolution_status);
|
|
810
810
|
|
|
811
811
|
-- Tabela: api_failures
|
|
812
|
-
-- Alimentada pelo Server Tracking Agent (
|
|
812
|
+
-- Alimentada pelo Server Tracking Agent (index.ts) quando um dispatch CAPI falha
|
|
813
813
|
CREATE TABLE IF NOT EXISTS api_failures (
|
|
814
814
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
815
815
|
platform TEXT NOT NULL, -- ex: 'meta', 'google', 'tiktok', 'linkedin'
|
|
@@ -829,14 +829,14 @@ CREATE INDEX IF NOT EXISTS idx_af_error_code ON api_failures(error_code);
|
|
|
829
829
|
|
|
830
830
|
### Como alimentar as tabelas
|
|
831
831
|
|
|
832
|
-
```
|
|
832
|
+
```typescript
|
|
833
833
|
// No Validator Agent — ao detectar um problema:
|
|
834
834
|
await env.DB.prepare(`
|
|
835
835
|
INSERT INTO validation_logs (agent_id, issue_type, severity, description)
|
|
836
836
|
VALUES (?, ?, ?, ?)
|
|
837
837
|
`).bind('validator-agent', issueType, severity, description).run();
|
|
838
838
|
|
|
839
|
-
// No
|
|
839
|
+
// No index.ts — ao falhar um dispatch CAPI (já em ctx.waitUntil):
|
|
840
840
|
await env.DB.prepare(`
|
|
841
841
|
INSERT INTO api_failures (platform, event_name, error_code, error_message, retry_count, final_status, event_id)
|
|
842
842
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
@@ -912,7 +912,7 @@ await env.DB.prepare(`
|
|
|
912
912
|
|
|
913
913
|
### Cron Triggers no Cloudflare Worker
|
|
914
914
|
|
|
915
|
-
```
|
|
915
|
+
```typescript
|
|
916
916
|
// Configurar triggers no wrangler.toml
|
|
917
917
|
[triggers]
|
|
918
918
|
crons = [
|
|
@@ -924,7 +924,7 @@ crons = [
|
|
|
924
924
|
|
|
925
925
|
### Handlers de Execução
|
|
926
926
|
|
|
927
|
-
```
|
|
927
|
+
```typescript
|
|
928
928
|
// Handler do ciclo completo
|
|
929
929
|
export async function scheduledFullCycle(event, env, ctx) {
|
|
930
930
|
const feedback = await collectFeedback(env);
|
|
@@ -749,7 +749,7 @@ src/tracking/platforms/
|
|
|
749
749
|
**RESPONSABILIDADE:**
|
|
750
750
|
- Gerar `wrangler.toml` (configuração completa Cloudflare)
|
|
751
751
|
- Gerar `schema.sql` (D1: events_log, identity_graph, leads)
|
|
752
|
-
- Gerar `
|
|
752
|
+
- Gerar `index.ts` (Cloudflare Worker principal — TypeScript nativo via wrangler/esbuild)
|
|
753
753
|
- Implementar endpoint `/track` (recebe eventos do browser)
|
|
754
754
|
- Implementar Engagement Scoring (0.0 - 5.0) calculado no servidor
|
|
755
755
|
- Implementar Intention Level (curioso, interessado, comprador) calculado no servidor
|
|
@@ -763,9 +763,9 @@ src/tracking/platforms/
|
|
|
763
763
|
**ARQUIVOS GERADOS:**
|
|
764
764
|
```
|
|
765
765
|
cloudflare/
|
|
766
|
-
├── wrangler.toml ← Configuração Cloudflare
|
|
766
|
+
├── wrangler.toml ← Configuração Cloudflare (main = "index.ts")
|
|
767
767
|
├── schema.sql ← Migrations D1
|
|
768
|
-
├──
|
|
768
|
+
├── index.ts ← Worker principal (TypeScript)
|
|
769
769
|
└── DEPLOY.md ← Guia de deploy
|
|
770
770
|
```
|
|
771
771
|
|
|
@@ -775,7 +775,7 @@ cloudflare/
|
|
|
775
775
|
"arquivos_criados": [
|
|
776
776
|
"cloudflare/wrangler.toml",
|
|
777
777
|
"cloudflare/schema.sql",
|
|
778
|
-
"cloudflare/
|
|
778
|
+
"cloudflare/index.ts",
|
|
779
779
|
"cloudflare/DEPLOY.md"
|
|
780
780
|
],
|
|
781
781
|
"recursos_implementados": {
|
|
@@ -896,7 +896,7 @@ FASE 5 (Geração em paralelo):
|
|
|
896
896
|
├─ FASE 5-I: Spotify Agent (Pixel + Conversions API v1)
|
|
897
897
|
├─ FASE 5-J: YouTube Agent (gclid/wbraid/gbraid + video milestones)
|
|
898
898
|
├─ FASE 5-K: Microsoft Ads Agent (UET Tag + Enhanced Conversions)
|
|
899
|
-
├─ FASE 5-D: Server Tracking Agent (
|
|
899
|
+
├─ FASE 5-D: Server Tracking Agent (index.ts — todos os platforms)
|
|
900
900
|
└─ FASE 5-E: Webhook Agent (gateways: Hotmart, Kiwify, Eduzz, Ticto, etc.)
|
|
901
901
|
```
|
|
902
902
|
|
|
@@ -1167,7 +1167,7 @@ Aguardar resposta. Armazenar em `PROJECT_TYPE`.
|
|
|
1167
1167
|
|
|
1168
1168
|
✅ FASE B-2 — Server Tracking Agent (configuração mínima)
|
|
1169
1169
|
Ler: agents/server-tracking.md
|
|
1170
|
-
- Gera / valida
|
|
1170
|
+
- Gera / valida index.ts com:
|
|
1171
1171
|
GET /webhook/whatsapp → verifica hub.verify_token
|
|
1172
1172
|
POST /webhook/whatsapp → processWhatsAppWebhook()
|
|
1173
1173
|
/track (manter ativo — pode ser usado no futuro)
|
|
@@ -1644,8 +1644,8 @@ Os agentes enterprise se integram ao Server Tracking Agent da seguinte forma:
|
|
|
1644
1644
|
- Registrar eventos de user journey para Attribution Agent
|
|
1645
1645
|
|
|
1646
1646
|
2. **Integration Pattern**:
|
|
1647
|
-
```
|
|
1648
|
-
// No Server Tracking Agent (
|
|
1647
|
+
```typescript
|
|
1648
|
+
// No Server Tracking Agent (index.ts)
|
|
1649
1649
|
import { SecurityMiddleware } from './enterprise/security';
|
|
1650
1650
|
import { CacheManager } from './enterprise/cache';
|
|
1651
1651
|
import { ConsentManager } from './enterprise/compliance';
|
|
@@ -1710,7 +1710,7 @@ Spawnar o Validator Agent para auditar todos os outputs gerados pelos agentes es
|
|
|
1710
1710
|
|
|
1711
1711
|
Após receber o relatório do Validator Agent, o Master Orchestrator DEVE implementar correções automáticas:
|
|
1712
1712
|
|
|
1713
|
-
```
|
|
1713
|
+
```typescript
|
|
1714
1714
|
// Master Orchestrator — Lógica de correção automática
|
|
1715
1715
|
async function applyValidatorCorrections(originalOutputs, validationReport) {
|
|
1716
1716
|
const corrections = validationReport.corrections || [];
|
|
@@ -1825,7 +1825,7 @@ async function escalateToUser(agent, issue, fix, error) {
|
|
|
1825
1825
|
|
|
1826
1826
|
**Integração com Validator Agent:**
|
|
1827
1827
|
|
|
1828
|
-
```
|
|
1828
|
+
```typescript
|
|
1829
1829
|
// Após execução do Validator Agent
|
|
1830
1830
|
const validationReport = await invokeValidatorAgent(allAgentOutputs);
|
|
1831
1831
|
|
|
@@ -1927,7 +1927,7 @@ Apresentar o resultado organizado com resumo de eventos e próximos passos.
|
|
|
1927
1927
|
- `consent.js` - Banner de consentimento (se Compliance habilitado)
|
|
1928
1928
|
|
|
1929
1929
|
### Server-Side:
|
|
1930
|
-
- `
|
|
1930
|
+
- `index.ts` - Cloudflare Worker principal (TypeScript)
|
|
1931
1931
|
- `schema.sql` - Migrations D1 (inclui schemas enterprise)
|
|
1932
1932
|
- `wrangler.toml` - Configuração Cloudflare
|
|
1933
1933
|
|
|
@@ -2005,7 +2005,7 @@ Após entregar o resultado ao usuário, o Master Orchestrator DEVE:
|
|
|
2005
2005
|
"timestamp": "{ISO_8601}",
|
|
2006
2006
|
"platforms_configured": ["meta", "google", "tiktok"],
|
|
2007
2007
|
"events_mapped": ["Lead", "Purchase", "InitiateCheckout"],
|
|
2008
|
-
"files_created": ["tracking.js", "
|
|
2008
|
+
"files_created": ["tracking.js", "index.ts", "schema.sql"],
|
|
2009
2009
|
"api_versions": {
|
|
2010
2010
|
"meta": "v22.0",
|
|
2011
2011
|
"tiktok": "v1.3",
|
|
@@ -2116,7 +2116,7 @@ Após entregar o resultado ao usuário, o Master Orchestrator DEVE:
|
|
|
2116
2116
|
|
|
2117
2117
|
8. **Enterprise Agents** — Recursos premium para tracking profissional:
|
|
2118
2118
|
- **Quando usar**: Apenas em infraestrutura Server-Side Cloudflare Native
|
|
2119
|
-
- **Integração**: Sempre integrar com Server Tracking Agent (
|
|
2119
|
+
- **Integração**: Sempre integrar com Server Tracking Agent (index.ts)
|
|
2120
2120
|
- **Migrations**: Executar D1 migrations para todos os schemas enterprise
|
|
2121
2121
|
- **API Routes**: Adicionar rotas enterprise ao worker principal
|
|
2122
2122
|
- **Opcional**: Não são obrigatórios para setups básicos
|