cdp-edge 2.0.0 → 2.0.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/contracts/api-versions.json +12 -8
- package/dist/commands/install.js +1 -2
- package/dist/commands/setup.js +1 -2
- package/extracted-skill/tracking-events-generator/agents/attribution-agent.md +23 -23
- package/extracted-skill/tracking-events-generator/agents/browser-tracking.md +172 -72
- 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/google-agent.md +118 -0
- package/extracted-skill/tracking-events-generator/agents/intelligence-agent.md +90 -4
- package/extracted-skill/tracking-events-generator/agents/intelligence-scheduling.md +8 -641
- 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 +61 -18
- package/extracted-skill/tracking-events-generator/agents/memory-agent.md +98 -0
- 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/security-enterprise-agent.md +137 -28
- package/extracted-skill/tracking-events-generator/agents/server-tracking.md +7 -8
- 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 +100 -0
- 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 +140 -25
- package/extracted-skill/tracking-events-generator/contracts/api-versions.json +12 -8
- package/package.json +2 -2
- package/server-edge-tracker/worker.js +53 -8
|
@@ -24,6 +24,114 @@ Para garantir que a conta B2B atrofie em custo e dispare em qualidade:
|
|
|
24
24
|
|
|
25
25
|
---
|
|
26
26
|
|
|
27
|
+
## 🤖 INTEGRAÇÃO COM LTV PREDICTOR + ML CLUSTERING
|
|
28
|
+
|
|
29
|
+
### Por que o LinkedIn precisa de LTV dinâmico
|
|
30
|
+
|
|
31
|
+
LinkedIn é tráfego B2B premium — o CPA é alto, mas o LTV também. Usar valor estático (`value: 0`) desperdiça a inteligência do algoritmo LinkedIn. O valor enviado deve refletir o LTV predito pelo ecossistema CDP Edge.
|
|
32
|
+
|
|
33
|
+
### Como consumir o LTV Predictor no Worker
|
|
34
|
+
|
|
35
|
+
```javascript
|
|
36
|
+
// No handler de evento LinkedIn (Lead ou Purchase via webhook/track):
|
|
37
|
+
import { predictLtv } from './ltv-predictor.js';
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Dispatcher LinkedIn CAPI com LTV dinâmico
|
|
41
|
+
* @param {Object} env - Cloudflare Worker env bindings
|
|
42
|
+
* @param {Object} leadData - dados do lead/compra
|
|
43
|
+
* @param {Request} request - request original
|
|
44
|
+
*/
|
|
45
|
+
async function dispatchLinkedIn(env, leadData, request) {
|
|
46
|
+
// 1. Obter LTV predito pelo ML (Workers AI — Llama 3.1 8B)
|
|
47
|
+
let conversionValue = 0;
|
|
48
|
+
try {
|
|
49
|
+
const ltvResult = await predictLtv(env, leadData, request);
|
|
50
|
+
// ltvResult = { score: 0-100, tier: 'High'|'Medium'|'Low', value_brl: number }
|
|
51
|
+
conversionValue = ltvResult.value_brl || 0;
|
|
52
|
+
} catch (err) {
|
|
53
|
+
console.warn('[LinkedIn] LTV prediction falhou, usando valor 0:', err.message);
|
|
54
|
+
// Fail-safe: continua sem LTV em vez de bloquear
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// 2. Obter segmento ML (ml-clustering — opcional mas melhora qualidade)
|
|
58
|
+
let segmentLabel = null;
|
|
59
|
+
try {
|
|
60
|
+
const profile = await env.DB.prepare(`
|
|
61
|
+
SELECT cohort_label, ltv_predicted
|
|
62
|
+
FROM user_profiles WHERE email_hash = ? LIMIT 1
|
|
63
|
+
`).bind(leadData.emailHash).first();
|
|
64
|
+
segmentLabel = profile?.cohort_label || null;
|
|
65
|
+
} catch (_) {}
|
|
66
|
+
|
|
67
|
+
// 3. SHA-256 de PII (obrigatório LinkedIn)
|
|
68
|
+
const hashedEmail = await sha256(leadData.email?.toLowerCase().trim());
|
|
69
|
+
const hashedFirstName = leadData.firstName ? await sha256(leadData.firstName.toLowerCase().trim()) : null;
|
|
70
|
+
const hashedLastName = leadData.lastName ? await sha256(leadData.lastName.toLowerCase().trim()) : null;
|
|
71
|
+
const hashedCompany = leadData.company ? await sha256(leadData.company.toLowerCase().trim()) : null;
|
|
72
|
+
|
|
73
|
+
// 4. Montar payload LinkedIn CAPI v2
|
|
74
|
+
const payload = {
|
|
75
|
+
conversion: `urn:li:conversion:${env.LINKEDIN_CONVERSION_ID}`,
|
|
76
|
+
conversionHappenedAt: Date.now(),
|
|
77
|
+
conversionValue: {
|
|
78
|
+
currencyCode: 'BRL',
|
|
79
|
+
amount: String(conversionValue.toFixed(2)) // LinkedIn exige string
|
|
80
|
+
},
|
|
81
|
+
eventId: leadData.eventId, // deduplicação
|
|
82
|
+
user: {
|
|
83
|
+
userIds: [
|
|
84
|
+
{ idType: 'SHA256_EMAIL', idValue: hashedEmail }
|
|
85
|
+
],
|
|
86
|
+
userInfo: {
|
|
87
|
+
firstName: hashedFirstName,
|
|
88
|
+
lastName: hashedLastName,
|
|
89
|
+
companyName: hashedCompany,
|
|
90
|
+
title: leadData.jobTitle ? await sha256(leadData.jobTitle.toLowerCase()) : null
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
// li_fat_id para correlação first-party (capturado via URL ?li_fat_id=)
|
|
94
|
+
...(leadData.liFatId && { liFatId: leadData.liFatId })
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
// 5. Dispatch para LinkedIn CAPI v2
|
|
98
|
+
const response = await fetch('https://api.linkedin.com/rest/conversionEvents', {
|
|
99
|
+
method: 'POST',
|
|
100
|
+
headers: {
|
|
101
|
+
'Content-Type': 'application/json',
|
|
102
|
+
'Authorization': `Bearer ${env.LINKEDIN_ACCESS_TOKEN}`,
|
|
103
|
+
'LinkedIn-Version': '202401',
|
|
104
|
+
'X-Restli-Protocol-Version': '2.0.0'
|
|
105
|
+
},
|
|
106
|
+
body: JSON.stringify(payload)
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
// 6. Log no D1
|
|
110
|
+
await env.DB.prepare(`
|
|
111
|
+
INSERT INTO events_log (platform, event_name, event_id, ltv_predicted, ml_segment, status, created_at)
|
|
112
|
+
VALUES ('linkedin', ?, ?, ?, ?, ?, datetime('now'))
|
|
113
|
+
`).bind(
|
|
114
|
+
leadData.eventName || 'Lead',
|
|
115
|
+
leadData.eventId,
|
|
116
|
+
conversionValue,
|
|
117
|
+
segmentLabel,
|
|
118
|
+
response.ok ? 'sent' : `error_${response.status}`
|
|
119
|
+
).run();
|
|
120
|
+
|
|
121
|
+
return response.ok;
|
|
122
|
+
}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### Captura de li_fat_id (URL parameter)
|
|
126
|
+
|
|
127
|
+
```javascript
|
|
128
|
+
// No cdpTrack.js (browser) — capturar li_fat_id da URL de cliques LinkedIn
|
|
129
|
+
const _lifattid = new URLSearchParams(window.location.search).get('li_fat_id') || null;
|
|
130
|
+
// Salvo no D1 junto com outros click IDs no handler /track
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
---
|
|
134
|
+
|
|
27
135
|
## 📦 SEU FORMATO DE ENTREGA
|
|
28
136
|
Sempre que a integração LinkedIn B2B for selecionada:
|
|
29
137
|
1. Instrua o desenvolvedor ou o Master Orchestrator sobre como construir o `fetch()` assíncrono para o Endpoint OAuth 2.0 da LinkedIn Conversions API (`/rest/conversionEvents`).
|
|
@@ -14,7 +14,7 @@ Sua única responsabilidade é instruir o Cloudflare Architect a imbuir modelos
|
|
|
14
14
|
|
|
15
15
|
## 📦 O PACOTE DE ENTREGA OBRIGATÓRIO
|
|
16
16
|
Sempre que o Orquestrador invocar a Otimização de Baleias (LTV Prediction):
|
|
17
|
-
1. **Snippet de Injeção de ML**: Entregue ao Server Architect o bloco `await env.AI.run('@cf/meta/llama-3-8b-instruct', ...)` ajustado para predição puramente matemática.
|
|
17
|
+
1. **Snippet de Injeção de ML**: Entregue ao Server Architect o bloco `await env.AI.run('@cf/meta/llama-3.1-8b-instruct', ...)` ajustado para predição puramente matemática.
|
|
18
18
|
2. **Override de Event Valuation**: Modifique como o evento `Lead` ou `Purchase` é envernizado com lucro preditivo antes do dispatch da CAPI.
|
|
19
19
|
|
|
20
20
|
> 👁️ "Não pague por cliques hoje. Compre os clientes de amanhã. Faça o algoritmo apostar sempre nas suas fichas vencedoras."
|
|
@@ -52,10 +52,10 @@ Implementar um **ciclo virtuoso de melhoria contínua** onde o CDP Edge aprende
|
|
|
52
52
|
|
|
53
53
|
```javascript
|
|
54
54
|
// Coleta estruturada de feedback de todos os agentes
|
|
55
|
-
async function collectFeedback() {
|
|
55
|
+
async function collectFeedback(env) {
|
|
56
56
|
const feedback = {
|
|
57
|
-
validator: await collectValidatorFeedback(),
|
|
58
|
-
server_tracking: await collectServerTrackingFeedback(),
|
|
57
|
+
validator: await collectValidatorFeedback(env),
|
|
58
|
+
server_tracking: await collectServerTrackingFeedback(env),
|
|
59
59
|
page_analyzer: await collectPageAnalyzerFeedback(),
|
|
60
60
|
memory_agent: await collectMemoryAgentFeedback(),
|
|
61
61
|
debug_agent: await collectDebugAgentFeedback(),
|
|
@@ -73,8 +73,8 @@ async function collectFeedback() {
|
|
|
73
73
|
}
|
|
74
74
|
|
|
75
75
|
// Feedback específico do Validator Agent
|
|
76
|
-
async function collectValidatorFeedback() {
|
|
77
|
-
const validations = await DB.prepare(`
|
|
76
|
+
async function collectValidatorFeedback(env) {
|
|
77
|
+
const validations = await env.DB.prepare(`
|
|
78
78
|
SELECT
|
|
79
79
|
agent_id,
|
|
80
80
|
issue_type,
|
|
@@ -97,8 +97,8 @@ async function collectValidatorFeedback() {
|
|
|
97
97
|
}
|
|
98
98
|
|
|
99
99
|
// Feedback de Server Tracking (falhas de API)
|
|
100
|
-
async function collectServerTrackingFeedback() {
|
|
101
|
-
const failures = await DB.prepare(`
|
|
100
|
+
async function collectServerTrackingFeedback(env) {
|
|
101
|
+
const failures = await env.DB.prepare(`
|
|
102
102
|
SELECT
|
|
103
103
|
platform,
|
|
104
104
|
event_name,
|
|
@@ -785,6 +785,66 @@ const FEEDBACK_LOOP_CONFIG = {
|
|
|
785
785
|
|
|
786
786
|
---
|
|
787
787
|
|
|
788
|
+
## 🗄️ D1 SCHEMA — TABELAS REQUERIDAS
|
|
789
|
+
|
|
790
|
+
As funções `collectValidatorFeedback()` e `collectServerTrackingFeedback()` dependem das seguintes tabelas. Executar no D1 antes do primeiro ciclo:
|
|
791
|
+
|
|
792
|
+
```sql
|
|
793
|
+
-- Tabela: validation_logs
|
|
794
|
+
-- Alimentada pelo Validator Agent após cada validação de tracking plan
|
|
795
|
+
CREATE TABLE IF NOT EXISTS validation_logs (
|
|
796
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
797
|
+
agent_id TEXT NOT NULL, -- ex: 'validator-agent', 'tracking-plan-agent'
|
|
798
|
+
issue_type TEXT NOT NULL, -- ex: 'missing_event', 'wrong_selector', 'pii_not_hashed'
|
|
799
|
+
severity TEXT NOT NULL CHECK (severity IN ('CRITICAL','HIGH','MEDIUM','LOW')),
|
|
800
|
+
description TEXT,
|
|
801
|
+
resolution_status TEXT NOT NULL DEFAULT 'pending' CHECK (resolution_status IN ('pending','resolved','wontfix')),
|
|
802
|
+
time_to_resolve_ms INTEGER, -- NULL enquanto pending
|
|
803
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
804
|
+
resolved_at TEXT
|
|
805
|
+
);
|
|
806
|
+
|
|
807
|
+
CREATE INDEX IF NOT EXISTS idx_vl_created ON validation_logs(created_at);
|
|
808
|
+
CREATE INDEX IF NOT EXISTS idx_vl_severity ON validation_logs(severity);
|
|
809
|
+
CREATE INDEX IF NOT EXISTS idx_vl_status ON validation_logs(resolution_status);
|
|
810
|
+
|
|
811
|
+
-- Tabela: api_failures
|
|
812
|
+
-- Alimentada pelo Server Tracking Agent (worker.js) quando um dispatch CAPI falha
|
|
813
|
+
CREATE TABLE IF NOT EXISTS api_failures (
|
|
814
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
815
|
+
platform TEXT NOT NULL, -- ex: 'meta', 'google', 'tiktok', 'linkedin'
|
|
816
|
+
event_name TEXT NOT NULL, -- ex: 'Purchase', 'Lead', 'ViewContent'
|
|
817
|
+
error_code TEXT, -- HTTP status ou código interno, ex: '429', 'TIMEOUT'
|
|
818
|
+
error_message TEXT,
|
|
819
|
+
retry_count INTEGER NOT NULL DEFAULT 0,
|
|
820
|
+
final_status TEXT NOT NULL DEFAULT 'failed' CHECK (final_status IN ('failed','success','dlq')),
|
|
821
|
+
event_id TEXT, -- para correlação com events_log
|
|
822
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
823
|
+
);
|
|
824
|
+
|
|
825
|
+
CREATE INDEX IF NOT EXISTS idx_af_platform ON api_failures(platform);
|
|
826
|
+
CREATE INDEX IF NOT EXISTS idx_af_created ON api_failures(created_at);
|
|
827
|
+
CREATE INDEX IF NOT EXISTS idx_af_error_code ON api_failures(error_code);
|
|
828
|
+
```
|
|
829
|
+
|
|
830
|
+
### Como alimentar as tabelas
|
|
831
|
+
|
|
832
|
+
```javascript
|
|
833
|
+
// No Validator Agent — ao detectar um problema:
|
|
834
|
+
await env.DB.prepare(`
|
|
835
|
+
INSERT INTO validation_logs (agent_id, issue_type, severity, description)
|
|
836
|
+
VALUES (?, ?, ?, ?)
|
|
837
|
+
`).bind('validator-agent', issueType, severity, description).run();
|
|
838
|
+
|
|
839
|
+
// No worker.js — ao falhar um dispatch CAPI (já em ctx.waitUntil):
|
|
840
|
+
await env.DB.prepare(`
|
|
841
|
+
INSERT INTO api_failures (platform, event_name, error_code, error_message, retry_count, final_status, event_id)
|
|
842
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
843
|
+
`).bind(platform, eventName, errorCode, errorMessage, retryCount, finalStatus, eventId).run();
|
|
844
|
+
```
|
|
845
|
+
|
|
846
|
+
---
|
|
847
|
+
|
|
788
848
|
## 📊 CHECKLIST DE IMPLEMENTAÇÃO
|
|
789
849
|
|
|
790
850
|
### Coleta de Feedback
|
|
@@ -867,7 +927,7 @@ crons = [
|
|
|
867
927
|
```javascript
|
|
868
928
|
// Handler do ciclo completo
|
|
869
929
|
export async function scheduledFullCycle(event, env, ctx) {
|
|
870
|
-
const feedback = await collectFeedback();
|
|
930
|
+
const feedback = await collectFeedback(env);
|
|
871
931
|
const patterns = await analyzePatterns(feedback);
|
|
872
932
|
const rootCauses = await identifySystemicRootCauses(patterns);
|
|
873
933
|
const improvements = await prioritizeImprovements(rootCauses, feedback);
|
|
@@ -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
|
```
|
|
@@ -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):
|
|
@@ -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
|
|
|
@@ -54,6 +54,52 @@ Quando o Master Orchestrator solicitar um deploy, você fornece os dados ao DevO
|
|
|
54
54
|
|
|
55
55
|
---
|
|
56
56
|
|
|
57
|
+
## ⚡ QUICK REFERENCE — API DE CONSULTA (para outros agentes)
|
|
58
|
+
|
|
59
|
+
Qualquer agente pode consultar o Memory Agent com a seguinte chamada:
|
|
60
|
+
|
|
61
|
+
```javascript
|
|
62
|
+
// Consultar qualquer dado salvo na memória da sessão
|
|
63
|
+
const memoryQuery = async (query) => {
|
|
64
|
+
const checkpoint = await readMemoryCheckpoint(); // lê memory-agent.json
|
|
65
|
+
|
|
66
|
+
switch (query.type) {
|
|
67
|
+
case 'get_secret':
|
|
68
|
+
// query: { type: 'get_secret', platform: 'meta', secret_name: 'access_token' }
|
|
69
|
+
return checkpoint.secrets_configured?.[query.platform]?.[query.secret_name];
|
|
70
|
+
|
|
71
|
+
case 'get_api_version':
|
|
72
|
+
// query: { type: 'get_api_version', platform: 'tiktok' }
|
|
73
|
+
return checkpoint.api_versions?.[query.platform];
|
|
74
|
+
|
|
75
|
+
case 'get_infra':
|
|
76
|
+
// query: { type: 'get_infra', key: 'd1_database_id' }
|
|
77
|
+
return checkpoint.cloudflare_infrastructure?.bindings?.[query.key];
|
|
78
|
+
|
|
79
|
+
case 'check_if_implemented':
|
|
80
|
+
// query: { type: 'check_if_implemented', item: 'meta_capi' }
|
|
81
|
+
return checkpoint.context_state?.platforms_configured?.includes(query.item);
|
|
82
|
+
|
|
83
|
+
case 'get_technical_decision':
|
|
84
|
+
// query: { type: 'get_technical_decision', decision_id: 'decision_001' }
|
|
85
|
+
return checkpoint.technical_decisions?.find(d => d.id === query.decision_id);
|
|
86
|
+
|
|
87
|
+
default:
|
|
88
|
+
throw new Error(`Query type desconhecido: ${query.type}. Tipos válidos: get_secret | get_api_version | get_infra | check_if_implemented | get_technical_decision`);
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
// Exemplo de uso em qualquer agente — NUNCA inventar credenciais:
|
|
93
|
+
const metaToken = await memoryQuery({ type: 'get_secret', platform: 'meta', secret_name: 'access_token' });
|
|
94
|
+
if (!metaToken || metaToken === 'NOT_SET') {
|
|
95
|
+
throw new Error('META_ACCESS_TOKEN não configurado. Solicite ao usuário antes de continuar.');
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
> **Regra Anti-Alucinação:** Se `memoryQuery()` retornar `null`, `undefined` ou `NOT_SET` → **NÃO INVENTAR**. Solicitar ao usuário explicitamente.
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
57
103
|
## 🧠 OBJETIVO PRINCIPAL: ELIMINAR RETRABALHO E ALUCINAÇÃO
|
|
58
104
|
|
|
59
105
|
Sua única função é registrar absolutamente TUDO o que importa. Você é o banco de dados centralizado da sessão de chat.
|
|
@@ -144,6 +190,30 @@ O Memory Agent não é só um conceito — ele tem uma implementação técnica
|
|
|
144
190
|
"pixel": "v2",
|
|
145
191
|
"conversions_api": "v2.0",
|
|
146
192
|
"verified_at": null
|
|
193
|
+
},
|
|
194
|
+
"linkedin": {
|
|
195
|
+
"insight_tag": "latest",
|
|
196
|
+
"conversions_api": "v2",
|
|
197
|
+
"verified_at": null
|
|
198
|
+
},
|
|
199
|
+
"spotify": {
|
|
200
|
+
"pixel": "v1",
|
|
201
|
+
"conversions_api": "v1",
|
|
202
|
+
"verified_at": null
|
|
203
|
+
},
|
|
204
|
+
"whatsapp": {
|
|
205
|
+
"cloud_api": "v22.0",
|
|
206
|
+
"verified_at": null
|
|
207
|
+
},
|
|
208
|
+
"bing": {
|
|
209
|
+
"uet": "latest",
|
|
210
|
+
"conversions_api": "v2",
|
|
211
|
+
"verified_at": null
|
|
212
|
+
},
|
|
213
|
+
"youtube": {
|
|
214
|
+
"ga4_integration": "latest",
|
|
215
|
+
"customer_match": "SHA-256",
|
|
216
|
+
"verified_at": null
|
|
147
217
|
}
|
|
148
218
|
},
|
|
149
219
|
|
|
@@ -181,6 +251,34 @@ O Memory Agent não é só um conceito — ele tem uma implementação técnica
|
|
|
181
251
|
"pixel_id": "NOT_SET",
|
|
182
252
|
"access_token": "NOT_SET",
|
|
183
253
|
"verified_at": null
|
|
254
|
+
},
|
|
255
|
+
"pinterest": {
|
|
256
|
+
"tag_id": "NOT_SET",
|
|
257
|
+
"access_token": "NOT_SET",
|
|
258
|
+
"ad_account_id": "NOT_SET",
|
|
259
|
+
"verified_at": null
|
|
260
|
+
},
|
|
261
|
+
"reddit": {
|
|
262
|
+
"pixel_id": "NOT_SET",
|
|
263
|
+
"access_token": "NOT_SET",
|
|
264
|
+
"ad_account_id": "NOT_SET",
|
|
265
|
+
"verified_at": null
|
|
266
|
+
},
|
|
267
|
+
"linkedin": {
|
|
268
|
+
"access_token": "NOT_SET",
|
|
269
|
+
"conversion_id": "NOT_SET",
|
|
270
|
+
"ad_account_id": "NOT_SET",
|
|
271
|
+
"verified_at": null
|
|
272
|
+
},
|
|
273
|
+
"spotify": {
|
|
274
|
+
"ad_account_id": "NOT_SET",
|
|
275
|
+
"access_token": "NOT_SET",
|
|
276
|
+
"verified_at": null
|
|
277
|
+
},
|
|
278
|
+
"whatsapp": {
|
|
279
|
+
"phone_number_id": "NOT_SET",
|
|
280
|
+
"token": "NOT_SET",
|
|
281
|
+
"verified_at": null
|
|
184
282
|
}
|
|
185
283
|
},
|
|
186
284
|
|
|
@@ -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,
|