cdp-edge 2.5.1 → 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 +21 -1
- package/contracts/agent-versions.json +383 -83
- 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/package.json +1 -1
- 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
|
@@ -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
|
|
@@ -17,7 +17,7 @@ O CDP Edge é uma fábrica. Você é a memória **temporária** da sessão de tr
|
|
|
17
17
|
| Pixel IDs e credenciais de plataformas | Apenas em memória | Ao final do projeto |
|
|
18
18
|
|
|
19
19
|
**NUNCA** persista dados reais do cliente em arquivos do projeto CDP Edge.
|
|
20
|
-
**NUNCA** salve IDs, tokens ou URLs reais no `wrangler.toml`, `
|
|
20
|
+
**NUNCA** salve IDs, tokens ou URLs reais no `wrangler.toml`, `index.ts` ou qualquer arquivo do repositório.
|
|
21
21
|
**SEMPRE** apague o `memory-agent.json` ao encerrar o projeto.
|
|
22
22
|
|
|
23
23
|
O destino final de todos os dados reais é exclusivamente dentro da **Cloudflare** — via `wrangler secret put` e `wrangler.toml` do projeto do cliente, nunca aqui.
|
|
@@ -58,7 +58,7 @@ Quando o Master Orchestrator solicitar um deploy, você fornece os dados ao DevO
|
|
|
58
58
|
|
|
59
59
|
Qualquer agente pode consultar o Memory Agent com a seguinte chamada:
|
|
60
60
|
|
|
61
|
-
```
|
|
61
|
+
```typescript
|
|
62
62
|
// Consultar qualquer dado salvo na memória da sessão
|
|
63
63
|
const memoryQuery = async (query) => {
|
|
64
64
|
const checkpoint = await readMemoryCheckpoint(); // lê memory-agent.json
|
|
@@ -328,7 +328,7 @@ O Memory Agent não é só um conceito — ele tem uma implementação técnica
|
|
|
328
328
|
"generated_at": "2025-03-27T15:00:00.000Z"
|
|
329
329
|
},
|
|
330
330
|
{
|
|
331
|
-
"file": "
|
|
331
|
+
"file": "index.ts",
|
|
332
332
|
"agent": "server-tracking-agent",
|
|
333
333
|
"status": "generated",
|
|
334
334
|
"size_bytes": 28456,
|
|
@@ -387,7 +387,7 @@ Quando o Master Orchestrator invocar o Memory Agent na FASE 0, seguir este fluxo
|
|
|
387
387
|
|
|
388
388
|
### PASSO 1 — Ler Checkpoint Atual
|
|
389
389
|
|
|
390
|
-
```
|
|
390
|
+
```typescript
|
|
391
391
|
// Master Orchestrator — FASE 0
|
|
392
392
|
const memoryCheckpoint = await readMemoryCheckpoint();
|
|
393
393
|
|
|
@@ -404,7 +404,7 @@ if (memoryCheckpoint) {
|
|
|
404
404
|
|
|
405
405
|
### PASSO 2 — Carregar Contexto para Outros Agentes
|
|
406
406
|
|
|
407
|
-
```
|
|
407
|
+
```typescript
|
|
408
408
|
// Quando spawnar qualquer agente, passar contexto do Memory Agent
|
|
409
409
|
const agentContext = {
|
|
410
410
|
api_versions: memoryCheckpoint.api_versions,
|
|
@@ -423,7 +423,7 @@ await spawnAgent('meta-agent', {
|
|
|
423
423
|
|
|
424
424
|
### PASSO 3 — Verificar Consistência
|
|
425
425
|
|
|
426
|
-
```
|
|
426
|
+
```typescript
|
|
427
427
|
// Memory Agent deve verificar inconsistências no checkpoint
|
|
428
428
|
function validateCheckpointConsistency(checkpoint) {
|
|
429
429
|
const warnings = [];
|
|
@@ -461,7 +461,7 @@ Quando o Master Orchestrator finalizar a FASE 5, seguir este fluxo de escrita:
|
|
|
461
461
|
|
|
462
462
|
### PASSO 1 — Compilar Resumo da Sessão
|
|
463
463
|
|
|
464
|
-
```
|
|
464
|
+
```typescript
|
|
465
465
|
// Master Orchestrator — FASE 5
|
|
466
466
|
const sessionSummary = {
|
|
467
467
|
session_metadata: {
|
|
@@ -488,7 +488,7 @@ const sessionSummary = {
|
|
|
488
488
|
|
|
489
489
|
### PASSO 2 — Atualizar Arquivo de Checkpoint
|
|
490
490
|
|
|
491
|
-
```
|
|
491
|
+
```typescript
|
|
492
492
|
// Escrever no arquivo principal de memória
|
|
493
493
|
await writeMemoryCheckpoint(sessionSummary);
|
|
494
494
|
|
|
@@ -504,7 +504,7 @@ await cleanupOldSessions(10);
|
|
|
504
504
|
|
|
505
505
|
Se o projeto tiver Cloudflare Worker configurado:
|
|
506
506
|
|
|
507
|
-
```
|
|
507
|
+
```typescript
|
|
508
508
|
// Master Orchestrator — Persistência em KV para próxima sessão
|
|
509
509
|
async function persistToCloudflareKV(summary) {
|
|
510
510
|
const key = `memory_session_${summary.session_metadata.session_id}`;
|
|
@@ -529,7 +529,7 @@ Outros agentes podem consultar o Memory Agent para obter informações específi
|
|
|
529
529
|
|
|
530
530
|
### API de Consulta (para outros agentes)
|
|
531
531
|
|
|
532
|
-
```
|
|
532
|
+
```typescript
|
|
533
533
|
// Qualquer agente pode chamar:
|
|
534
534
|
const memoryQuery = async (query) => {
|
|
535
535
|
const checkpoint = await readMemoryCheckpoint();
|
|
@@ -768,7 +768,7 @@ Quando os testes passarem, o Master Orchestrator executa:
|
|
|
768
768
|
|
|
769
769
|
**Se usuário confirmar (SIM):**
|
|
770
770
|
|
|
771
|
-
```
|
|
771
|
+
```typescript
|
|
772
772
|
async function purgeCredentials() {
|
|
773
773
|
// 1. Zerar secrets_configured no checkpoint
|
|
774
774
|
checkpoint.secrets_configured = {};
|
|
@@ -809,7 +809,7 @@ async function purgeCredentials() {
|
|
|
809
809
|
|
|
810
810
|
### Função de Formatação de Data
|
|
811
811
|
|
|
812
|
-
```
|
|
812
|
+
```typescript
|
|
813
813
|
function formatDate(date) {
|
|
814
814
|
const d = new Date(date);
|
|
815
815
|
const year = d.getFullYear();
|
|
@@ -821,7 +821,7 @@ function formatDate(date) {
|
|
|
821
821
|
|
|
822
822
|
### Função de Mask de Segredos
|
|
823
823
|
|
|
824
|
-
```
|
|
824
|
+
```typescript
|
|
825
825
|
function maskSecret(secret) {
|
|
826
826
|
if (!secret || secret.length < 10) return 'NOT_SET';
|
|
827
827
|
const visibleChars = 4;
|
|
@@ -836,7 +836,7 @@ function maskSecret(secret) {
|
|
|
836
836
|
|
|
837
837
|
### Função de Cleanup de Histórico
|
|
838
838
|
|
|
839
|
-
```
|
|
839
|
+
```typescript
|
|
840
840
|
async function cleanupOldSessions(maxSessions) {
|
|
841
841
|
const historyDir = 'agents/memory-agent/history';
|
|
842
842
|
const files = await listFiles(historyDir);
|
|
@@ -23,7 +23,7 @@ Especialista exclusivo em Meta Pixel (browser via cdpTrack) + Meta Conversions A
|
|
|
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 metaVersion = apiVersions.meta;
|
|
@@ -99,7 +99,7 @@ Gere payloads para o Worker seguir a API oficial da Meta:
|
|
|
99
99
|
{
|
|
100
100
|
"arquivos_gerados": {
|
|
101
101
|
"browser": "cdpTrack.js (eventos Meta injetados)",
|
|
102
|
-
"server": "
|
|
102
|
+
"server": "modules/dispatch/meta.ts"
|
|
103
103
|
},
|
|
104
104
|
"versao_api": "v22.0",
|
|
105
105
|
"eventos_implementados": ["PageView", "Lead", "InitiateCheckout", "Purchase", "ViewContent"],
|
|
@@ -155,7 +155,7 @@ is_business_hours = 1 if 9 <= hour_of_day <= 18 else 0
|
|
|
155
155
|
|
|
156
156
|
### 2.3 Perfil textual por lead (input para embedding)
|
|
157
157
|
|
|
158
|
-
```
|
|
158
|
+
```typescript
|
|
159
159
|
function _buildLeadProfile(l) {
|
|
160
160
|
return [
|
|
161
161
|
`LTV: ${l.predicted_ltv_class || 'desconhecido'}`,
|
|
@@ -173,7 +173,7 @@ function _buildLeadProfile(l) {
|
|
|
173
173
|
|
|
174
174
|
### 2.4 Chamada de embeddings em batch
|
|
175
175
|
|
|
176
|
-
```
|
|
176
|
+
```typescript
|
|
177
177
|
// Embeds até 100 perfis em uma única chamada
|
|
178
178
|
const embRes = await env.AI.run('@cf/baai/bge-m3', { text: profiles });
|
|
179
179
|
const vectors = embRes.data; // float32[][] — shape [N, 768]
|
|
@@ -181,15 +181,15 @@ const vectors = embRes.data; // float32[][] — shape [N, 768]
|
|
|
181
181
|
|
|
182
182
|
### 2.5 K-means vetorial (cosine distance)
|
|
183
183
|
|
|
184
|
-
```
|
|
184
|
+
```typescript
|
|
185
185
|
// Inicialização K-means++ → iterações até convergência → assignments finais
|
|
186
|
-
const { assignments } = _kmeansRun(vectors, nClusters); // implementado em
|
|
186
|
+
const { assignments } = _kmeansRun(vectors, nClusters); // implementado em index.ts
|
|
187
187
|
const silhouetteScore = _silhouette(vectors, assignments, nClusters); // score real
|
|
188
188
|
```
|
|
189
189
|
|
|
190
190
|
### 2.6 Naming dos clusters via Granite (único uso de LLM)
|
|
191
191
|
|
|
192
|
-
```
|
|
192
|
+
```typescript
|
|
193
193
|
// Granite recebe apenas as estatísticas agregadas por cluster
|
|
194
194
|
// Retorna nome descritivo + recomendação de campanha em português
|
|
195
195
|
const nameRes = await env.AI.run('@cf/ibm-granite/granite-4.0-h-micro', {
|
|
@@ -200,7 +200,7 @@ const nameRes = await env.AI.run('@cf/ibm-granite/granite-4.0-h-micro', {
|
|
|
200
200
|
|
|
201
201
|
### 2.2 Features para K-Means
|
|
202
202
|
|
|
203
|
-
```
|
|
203
|
+
```typescript
|
|
204
204
|
// Features recomendadas para clustering (com base na análise D1)
|
|
205
205
|
|
|
206
206
|
const RECOMMENDED_FEATURES = [
|
|
@@ -461,7 +461,7 @@ CREATE INDEX IF NOT EXISTS idx_ml_segment_members_lead ON ml_segment_members(lea
|
|
|
461
461
|
|
|
462
462
|
### 7.1 Endpoint de Clustering
|
|
463
463
|
|
|
464
|
-
```
|
|
464
|
+
```typescript
|
|
465
465
|
// server-edge-tracker/functions/api/segmentation/cluster.ts
|
|
466
466
|
|
|
467
467
|
export async function onRequestGet(context: EventContext<Env>) {
|
|
@@ -515,7 +515,7 @@ export async function onRequestGet(context: EventContext<Env>) {
|
|
|
515
515
|
|
|
516
516
|
### 7.2 Endpoint de Consulta de Segmentos
|
|
517
517
|
|
|
518
|
-
```
|
|
518
|
+
```typescript
|
|
519
519
|
// server-edge-tracker/functions/api/segmentation/list.ts
|
|
520
520
|
|
|
521
521
|
export async function onRequestGet(context: EventContext<Env>) {
|
|
@@ -546,7 +546,7 @@ export async function onRequestGet(context: EventContext<Env>) {
|
|
|
546
546
|
|
|
547
547
|
### 7.3 Endpoint de Anomalias (DBSCAN)
|
|
548
548
|
|
|
549
|
-
```
|
|
549
|
+
```typescript
|
|
550
550
|
// server-edge-tracker/functions/api/segmentation/outliers.ts
|
|
551
551
|
|
|
552
552
|
export async function onRequestGet(context: EventContext<Env>) {
|
|
@@ -12,6 +12,7 @@ Toda a sua análise deve ser baseada na infraestrutura nativa da Cloudflare.
|
|
|
12
12
|
- Eventos de formulário servem para captura de PII direto para o **D1 Database**.
|
|
13
13
|
- Conversões externas cruzam dados via Webhook + D1.
|
|
14
14
|
- **Human-Behavior Engine**: Micro-eventos são obrigatórios em TODA página.
|
|
15
|
+
- **Worker:** `server-edge-tracker/index.ts` (TypeScript nativo, compilado via wrangler/esbuild)
|
|
15
16
|
|
|
16
17
|
---
|
|
17
18
|
|