cdp-edge 2.5.4 → 2.5.6
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 +7 -2
- package/contracts/agent-versions.json +12 -9
- package/extracted-skill/tracking-events-generator/agents/evo-crm-agent.md +253 -0
- package/extracted-skill/tracking-events-generator/agents/ltv-predictor-agent.md +19 -0
- package/extracted-skill/tracking-events-generator/agents/master-orchestrator.md +308 -11
- package/extracted-skill/tracking-events-generator/agents/ml-clustering-agent.md +20 -0
- package/package.json +1 -1
- package/server-edge-tracker/INSTALAR.md +2 -2
- package/server-edge-tracker/index.ts +39 -0
- package/server-edge-tracker/modules/dispatch/crm.ts +382 -0
- package/server-edge-tracker/modules/dispatch/whatsapp.ts +17 -0
- package/server-edge-tracker/modules/ml/fraud.ts +15 -3
- package/server-edge-tracker/types.ts +14 -0
- package/server-edge-tracker/wrangler.toml +11 -7
- package/extracted-skill/tracking-events-generator/agents/crm-integration-agent.md +0 -1459
|
@@ -91,7 +91,7 @@ Master Orchestrator (você)
|
|
|
91
91
|
│ ├── Database Agent → migrações D1, schema, índices
|
|
92
92
|
│ ├── Domain Setup Agent → conecta track.clientdomain.com + cookie first-party
|
|
93
93
|
│ ├── R2 Setup Agent → habilita R2, cria bucket, ativa audit log imutável
|
|
94
|
-
│ └── CRM
|
|
94
|
+
│ └── EVO CRM Agent → roteia leads p/ EVO CRM (OAuth2 Doorkeeper)
|
|
95
95
|
│
|
|
96
96
|
├── 💬 COMUNICAÇÃO E NOTIFICAÇÕES
|
|
97
97
|
│ ├── WhatsApp Agent → automação Meta Cloud API + CallMeBot
|
|
@@ -103,12 +103,18 @@ Master Orchestrator (você)
|
|
|
103
103
|
│ ├── LTV Predictor Agent → prevê LTV financeiro com Workers AI
|
|
104
104
|
│ ├── ML Clustering Agent → segmentação dinâmica K-means/DBSCAN (Fase 1 Enterprise)
|
|
105
105
|
│ ├── Bidding Recommendations Agent → recomendações de bids por segmento ML (Fase 2 Enterprise)
|
|
106
|
-
│ ├── A/B Testing Agent →
|
|
106
|
+
│ ├── A/B Testing Agent → split de tráfego invisível na borda (sem flicker)
|
|
107
|
+
│ ├── A/B LTV Testing Agent → otimização contínua da precisão do LTV preditivo (Fase 3 Enterprise)
|
|
107
108
|
│ └── Localization Agent → moedas e traduções no edge
|
|
108
109
|
│
|
|
109
110
|
├── 📈 DASHBOARD E RELATÓRIOS
|
|
110
111
|
│ ├── Dashboard Agent → gerencia meta-dashboard-full (React)
|
|
111
|
-
│
|
|
112
|
+
│ ├── Performance Agent → monitoramento em tempo real: latência, throughput, SLA alerts
|
|
113
|
+
│ └── Performance Optimization Agent → estratégias de cache L1/L2/L3, query D1, batch processing (Enterprise)
|
|
114
|
+
│
|
|
115
|
+
│ ⚠️ REGRA DE ROTEAMENTO — Performance:
|
|
116
|
+
│ • Invoke Performance Agent → quando precisar de métricas, health checks ou alertas de degradação
|
|
117
|
+
│ • Invoke Performance Optimization Agent → quando precisar otimizar cache, queries D1 ou latência estrutural
|
|
112
118
|
│
|
|
113
119
|
├── 🔍 QUALIDADE E SEGURANÇA
|
|
114
120
|
│ ├── Match Quality Agent → garante que só dado com valor real vai para as plataformas
|
|
@@ -173,7 +179,7 @@ SKILL_BASE: [diretório da skill tracking-events-generator]
|
|
|
173
179
|
├── database-agent.md ← migrações D1, schema, índices
|
|
174
180
|
├── domain-setup-agent.md ← track.clientdomain.com + Worker Route + cookie first-party
|
|
175
181
|
├── r2-setup-agent.md ← R2 bucket + audit log /events/YYYY-MM-DD/{uuid}.json
|
|
176
|
-
├── crm-
|
|
182
|
+
├── evo-crm-agent.md ← Agente EVO CRM (OAuth2)
|
|
177
183
|
│
|
|
178
184
|
├── ── COMUNICAÇÃO ──
|
|
179
185
|
├── whatsapp-agent.md ← Meta Cloud API + CallMeBot Bridge
|
|
@@ -185,7 +191,8 @@ SKILL_BASE: [diretório da skill tracking-events-generator]
|
|
|
185
191
|
├── ltv-predictor-agent.md ← IA Preditiva de Receita (Workers AI)
|
|
186
192
|
├── ml-clustering-agent.md ← Segmentação Dinâmica ML (K-means, DBSCAN, Hierarchical)
|
|
187
193
|
├── bidding-agent.md ← Recomendações de Bids por Segmento ML
|
|
188
|
-
├── ab-testing-agent.md ← A/B Edge Route Optimization
|
|
194
|
+
├── ab-testing-agent.md ← A/B Edge Route Optimization (split de tráfego invisível, sem flicker)
|
|
195
|
+
├── ab-ltv-agent.md ← A/B LTV Testing — otimização contínua da precisão preditiva (Fase 3 Enterprise)
|
|
189
196
|
├── localization-agent.md ← Traduções de Checkout em Borda
|
|
190
197
|
│
|
|
191
198
|
├── ── DASHBOARD E RELATÓRIOS ──
|
|
@@ -897,7 +904,8 @@ FASE 5 (Geração em paralelo):
|
|
|
897
904
|
├─ FASE 5-J: YouTube Agent (gclid/wbraid/gbraid + video milestones)
|
|
898
905
|
├─ FASE 5-K: Microsoft Ads Agent (UET Tag + Enhanced Conversions)
|
|
899
906
|
├─ FASE 5-D: Server Tracking Agent (index.ts — todos os platforms)
|
|
900
|
-
|
|
907
|
+
├─ FASE 5-E: Webhook Agent (gateways: Hotmart, Kiwify, Eduzz, Ticto, etc.)
|
|
908
|
+
└─ FASE 5-L: EVO CRM Agent (roteia leads p/ EVO CRM)
|
|
901
909
|
```
|
|
902
910
|
|
|
903
911
|
FASE 6 (Enterprise Features — ordem de configuração):
|
|
@@ -915,6 +923,277 @@ FASE 6 (Enterprise Features — ordem de configuração):
|
|
|
915
923
|
|
|
916
924
|
---
|
|
917
925
|
|
|
926
|
+
## COMANDO *new-ai-module — Criar novo módulo Workers AI
|
|
927
|
+
|
|
928
|
+
### TRIGGERS (qualquer uma das formas abaixo ativa este comando)
|
|
929
|
+
|
|
930
|
+
| Forma | Exemplo |
|
|
931
|
+
|---|---|
|
|
932
|
+
| `*new-ai-module [descrição]` | `*new-ai-module classifica leads por score do quiz` |
|
|
933
|
+
| `crie um worker ai para [descrição]` | `crie um worker ai para distribuir leads por pontuação` |
|
|
934
|
+
| `quero um módulo de IA que [descrição]` | `quero um módulo de IA que detecta intenção de compra` |
|
|
935
|
+
|
|
936
|
+
**REGRA:** O Master Orchestrator NÃO pede mais informações antes de agir. Infere tudo a partir da descrição e executa imediatamente.
|
|
937
|
+
|
|
938
|
+
---
|
|
939
|
+
|
|
940
|
+
### DECISÃO INICIAL — Tipo de módulo
|
|
941
|
+
|
|
942
|
+
Antes de spawnar agentes, classificar automaticamente:
|
|
943
|
+
|
|
944
|
+
| Descrição contém | Tipo | Agente primário |
|
|
945
|
+
|---|---|---|
|
|
946
|
+
| classificar, score, pontuar, prever, predizer, LTV, valor | **Scoring/Prediction** | LTV Predictor Agent |
|
|
947
|
+
| segmentar, agrupar, cluster, similaridade, perfil | **Clustering/Embedding** | ML Clustering Agent |
|
|
948
|
+
| detectar, identificar, intenção, comportamento, padrão | **Classification** | LTV Predictor Agent |
|
|
949
|
+
| distribuir, rotear, priorizar, fila, ranking | **Routing/Ranking** | LTV Predictor Agent |
|
|
950
|
+
|
|
951
|
+
---
|
|
952
|
+
|
|
953
|
+
### PERGUNTA OBRIGATÓRIA — Modo de execução
|
|
954
|
+
|
|
955
|
+
Antes de iniciar o pipeline, fazer UMA pergunta:
|
|
956
|
+
|
|
957
|
+
> **"Este módulo deve rodar:"**
|
|
958
|
+
> - **[A] Dentro do pipeline `/track`** — executa automaticamente a cada evento capturado
|
|
959
|
+
> - **[B] Sob demanda via API** — chamado explicitamente por outro sistema ou cron
|
|
960
|
+
> - **[C] Ambos** — rota API + integrado ao `/track`
|
|
961
|
+
|
|
962
|
+
A resposta define como o PASSO 3 (Server Tracking Agent) conecta o módulo.
|
|
963
|
+
|
|
964
|
+
---
|
|
965
|
+
|
|
966
|
+
### PIPELINE DE EXECUÇÃO (sempre nesta ordem, sem pular passos)
|
|
967
|
+
|
|
968
|
+
---
|
|
969
|
+
|
|
970
|
+
**PASSO 1 — Agente de IA (LTV Predictor Agent ou ML Clustering Agent)**
|
|
971
|
+
|
|
972
|
+
Responsabilidade: especificar o cérebro do módulo.
|
|
973
|
+
|
|
974
|
+
Entregar obrigatoriamente:
|
|
975
|
+
|
|
976
|
+
1. **Modelo escolhido** com justificativa:
|
|
977
|
+
|
|
978
|
+
| Caso de uso | Modelo |
|
|
979
|
+
|---|---|
|
|
980
|
+
| Classificação / scoring / raciocínio leve | `@cf/ibm-granite/granite-4.0-h-micro` |
|
|
981
|
+
| Embeddings / similaridade / clustering semântico | `@cf/baai/bge-m3` |
|
|
982
|
+
| Análise rica / respostas longas / contexto amplo | `@cf/meta/llama-3.1-8b-instruct` |
|
|
983
|
+
| Sentimento / classificação binária (rápido) | `@cf/huggingface/distilbert-sst-2-int8` |
|
|
984
|
+
|
|
985
|
+
2. **Contrato de input/output tipado:**
|
|
986
|
+
```typescript
|
|
987
|
+
// Exemplo para módulo de scoring de leads
|
|
988
|
+
interface AIModuleInput {
|
|
989
|
+
lead_id: string;
|
|
990
|
+
features: Record<string, string | number | boolean>;
|
|
991
|
+
context?: string; // contexto extra opcional
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
interface AIModuleOutput {
|
|
995
|
+
lead_id: string;
|
|
996
|
+
result_class: string; // ex: 'High' | 'Medium' | 'Low'
|
|
997
|
+
confidence: number; // 0.0 – 1.0
|
|
998
|
+
score: number; // 0 – 100
|
|
999
|
+
reasoning: string; // explicação do modelo (1 linha)
|
|
1000
|
+
model: string; // @cf/modelo-usado
|
|
1001
|
+
latency_ms: number;
|
|
1002
|
+
cached: boolean;
|
|
1003
|
+
}
|
|
1004
|
+
```
|
|
1005
|
+
|
|
1006
|
+
3. **System prompt do modelo** — calibrado ao caso de uso específico, com instrução de retornar JSON puro.
|
|
1007
|
+
|
|
1008
|
+
4. **Estratégia de cache** — resultado deve ser cacheado no KV (`GEO_CACHE`) por TTL definido pelo agente (padrão: 1h), usando `input_hash` como chave, para evitar rechamadas desnecessárias ao modelo.
|
|
1009
|
+
|
|
1010
|
+
---
|
|
1011
|
+
|
|
1012
|
+
**PASSO 2 — Database Agent**
|
|
1013
|
+
|
|
1014
|
+
Responsabilidade: criar schema D1 tipado e com índices corretos.
|
|
1015
|
+
|
|
1016
|
+
Schema obrigatório — **sem campos genéricos**:
|
|
1017
|
+
```sql
|
|
1018
|
+
-- Nomenclatura: schema-ai-[nome-do-módulo].sql
|
|
1019
|
+
CREATE TABLE IF NOT EXISTS ai_[nome] (
|
|
1020
|
+
id TEXT PRIMARY KEY, -- UUID v4
|
|
1021
|
+
lead_id TEXT NOT NULL,
|
|
1022
|
+
input_hash TEXT NOT NULL, -- SHA256 do input (usado como cache key)
|
|
1023
|
+
result_class TEXT NOT NULL, -- saída classificada do modelo
|
|
1024
|
+
confidence REAL NOT NULL DEFAULT 0, -- 0.0 – 1.0
|
|
1025
|
+
score INTEGER NOT NULL DEFAULT 0, -- 0 – 100
|
|
1026
|
+
reasoning TEXT, -- explicação do modelo
|
|
1027
|
+
model TEXT NOT NULL, -- @cf/modelo-usado
|
|
1028
|
+
latency_ms INTEGER, -- tempo de inferência
|
|
1029
|
+
cached INTEGER NOT NULL DEFAULT 0, -- 0 = fresh, 1 = from KV cache
|
|
1030
|
+
pipeline TEXT NOT NULL DEFAULT 'api', -- 'track' | 'api' | 'cron'
|
|
1031
|
+
created_at INTEGER NOT NULL DEFAULT (unixepoch())
|
|
1032
|
+
);
|
|
1033
|
+
|
|
1034
|
+
CREATE INDEX IF NOT EXISTS idx_ai_[nome]_lead ON ai_[nome](lead_id);
|
|
1035
|
+
CREATE INDEX IF NOT EXISTS idx_ai_[nome]_class ON ai_[nome](result_class);
|
|
1036
|
+
CREATE INDEX IF NOT EXISTS idx_ai_[nome]_created ON ai_[nome](created_at DESC);
|
|
1037
|
+
```
|
|
1038
|
+
|
|
1039
|
+
Após gerar o schema, o Database Agent passa o arquivo para o DevOps Agent aplicar — **não aplica diretamente**.
|
|
1040
|
+
|
|
1041
|
+
---
|
|
1042
|
+
|
|
1043
|
+
**PASSO 3 — Server Tracking Agent**
|
|
1044
|
+
|
|
1045
|
+
Responsabilidade: criar o módulo TypeScript + rotas REST + integração ao pipeline conforme resposta da PERGUNTA OBRIGATÓRIA.
|
|
1046
|
+
|
|
1047
|
+
**Estrutura do módulo gerado:**
|
|
1048
|
+
```typescript
|
|
1049
|
+
// server-edge-tracker/modules/ml/[nome].ts
|
|
1050
|
+
|
|
1051
|
+
export async function run[Nome](
|
|
1052
|
+
env: Env,
|
|
1053
|
+
input: AIModuleInput
|
|
1054
|
+
): Promise<AIModuleOutput> {
|
|
1055
|
+
|
|
1056
|
+
// 1. Verificar cache KV antes de chamar o modelo
|
|
1057
|
+
const cacheKey = `ai:[nome]:${input.input_hash}`;
|
|
1058
|
+
const cached = await env.GEO_CACHE.get(cacheKey, 'json');
|
|
1059
|
+
if (cached) return { ...cached, cached: true };
|
|
1060
|
+
|
|
1061
|
+
// 2. Chamar Workers AI
|
|
1062
|
+
const aiRes = await env.AI.run('[modelo-escolhido]', {
|
|
1063
|
+
messages: [
|
|
1064
|
+
{ role: 'system', content: '[system-prompt-gerado-no-passo-1]' },
|
|
1065
|
+
{ role: 'user', content: JSON.stringify(input.features) }
|
|
1066
|
+
],
|
|
1067
|
+
max_tokens: 64
|
|
1068
|
+
});
|
|
1069
|
+
|
|
1070
|
+
// 3. Parsear output do modelo (sempre JSON puro)
|
|
1071
|
+
const parsed = JSON.parse(aiRes.response);
|
|
1072
|
+
const output: AIModuleOutput = {
|
|
1073
|
+
lead_id: input.lead_id,
|
|
1074
|
+
result_class: parsed.class,
|
|
1075
|
+
confidence: parsed.confidence ?? 0,
|
|
1076
|
+
score: parsed.score ?? 0,
|
|
1077
|
+
reasoning: parsed.reasoning ?? '',
|
|
1078
|
+
model: '[modelo-escolhido]',
|
|
1079
|
+
latency_ms: 0, // preenchido pelo caller
|
|
1080
|
+
cached: false
|
|
1081
|
+
};
|
|
1082
|
+
|
|
1083
|
+
// 4. Salvar no KV (cache) e no D1 (persistência)
|
|
1084
|
+
await env.GEO_CACHE.put(cacheKey, JSON.stringify(output), { expirationTtl: 3600 });
|
|
1085
|
+
await env.DB.prepare(`
|
|
1086
|
+
INSERT INTO ai_[nome] (id, lead_id, input_hash, result_class, confidence, score, reasoning, model, pipeline)
|
|
1087
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1088
|
+
`).bind(crypto.randomUUID(), input.lead_id, input.input_hash, output.result_class,
|
|
1089
|
+
output.confidence, output.score, output.reasoning, output.model, input.pipeline ?? 'api')
|
|
1090
|
+
.run();
|
|
1091
|
+
|
|
1092
|
+
return output;
|
|
1093
|
+
}
|
|
1094
|
+
```
|
|
1095
|
+
|
|
1096
|
+
**Rotas REST criadas (sempre, independente do modo):**
|
|
1097
|
+
```
|
|
1098
|
+
POST /api/ai/[nome] → executa inferência ad-hoc
|
|
1099
|
+
GET /api/ai/[nome]/:lead_id → retorna último resultado salvo para o lead
|
|
1100
|
+
GET /api/ai/[nome]/stats → distribuição de classes + taxa de cache hit
|
|
1101
|
+
```
|
|
1102
|
+
|
|
1103
|
+
**Integração ao pipeline `/track` (somente se Modo A ou C):**
|
|
1104
|
+
```typescript
|
|
1105
|
+
// Em index.ts — dentro do handler POST /track, após Quiz Scoring e antes do CAPI Dispatch
|
|
1106
|
+
// Ordem runtime atualizada:
|
|
1107
|
+
// [1] Fraud Gate → [2] Quiz Scoring → [3] LTV → [3.x] [NOME] → [4] D1 → [5] CAPI
|
|
1108
|
+
|
|
1109
|
+
const [nomeResult] = await run[Nome](env, {
|
|
1110
|
+
lead_id: payload.userId,
|
|
1111
|
+
input_hash: await sha256(JSON.stringify(relevantFeatures)),
|
|
1112
|
+
features: relevantFeatures,
|
|
1113
|
+
pipeline: 'track'
|
|
1114
|
+
});
|
|
1115
|
+
|
|
1116
|
+
// Resultado disponível para enriquecer o CAPI dispatch
|
|
1117
|
+
payload.ai_[nome]_class = [nomeResult].result_class;
|
|
1118
|
+
payload.ai_[nome]_score = [nomeResult].score;
|
|
1119
|
+
```
|
|
1120
|
+
|
|
1121
|
+
---
|
|
1122
|
+
|
|
1123
|
+
**PASSO 4 — DevOps Agent**
|
|
1124
|
+
|
|
1125
|
+
Sequência de execução obrigatória:
|
|
1126
|
+
|
|
1127
|
+
```bash
|
|
1128
|
+
# 1. Verificar se binding [ai] já existe (não duplicar)
|
|
1129
|
+
! grep -c '\[ai\]' server-edge-tracker/wrangler.toml
|
|
1130
|
+
# Se retornar 0 → adicionar bloco [ai] binding = "AI"
|
|
1131
|
+
# Se retornar ≥1 → pular, já existe
|
|
1132
|
+
|
|
1133
|
+
# 2. Aplicar schema D1
|
|
1134
|
+
! wrangler d1 execute cdp-edge-db --file=server-edge-tracker/schema-ai-[nome].sql --remote
|
|
1135
|
+
|
|
1136
|
+
# 3. Deploy
|
|
1137
|
+
! wrangler deploy
|
|
1138
|
+
```
|
|
1139
|
+
|
|
1140
|
+
**Em caso de falha no deploy:** o DevOps Agent captura o erro, passa para o Debug Agent e tenta correção automática antes de escalar para o usuário.
|
|
1141
|
+
|
|
1142
|
+
---
|
|
1143
|
+
|
|
1144
|
+
**PASSO 5 — Validator Agent**
|
|
1145
|
+
|
|
1146
|
+
Smoke tests obrigatórios em sequência:
|
|
1147
|
+
|
|
1148
|
+
```bash
|
|
1149
|
+
# Test 1 — Inferência ad-hoc
|
|
1150
|
+
POST /api/ai/[nome]
|
|
1151
|
+
Body: { "lead_id": "smoke-test-001", "features": { [campo-principal]: [valor-teste] } }
|
|
1152
|
+
Esperado: 200 + { result_class, confidence, score, cached: false }
|
|
1153
|
+
|
|
1154
|
+
# Test 2 — Cache hit
|
|
1155
|
+
POST /api/ai/[nome] (mesmo payload)
|
|
1156
|
+
Esperado: 200 + { cached: true, latency_ms < 10 }
|
|
1157
|
+
|
|
1158
|
+
# Test 3 — Leitura do resultado
|
|
1159
|
+
GET /api/ai/[nome]/smoke-test-001
|
|
1160
|
+
Esperado: 200 + registro da tabela D1
|
|
1161
|
+
|
|
1162
|
+
# Test 4 — Stats
|
|
1163
|
+
GET /api/ai/[nome]/stats
|
|
1164
|
+
Esperado: 200 + { total, by_class: { ... }, cache_hit_rate }
|
|
1165
|
+
|
|
1166
|
+
# Test 5 — Pipeline /track (somente se Modo A ou C)
|
|
1167
|
+
POST /track com payload real
|
|
1168
|
+
Esperado: response contém ai_[nome]_class no resultado
|
|
1169
|
+
```
|
|
1170
|
+
|
|
1171
|
+
Se qualquer teste falhar: **bloquear** e escalar para Debug Agent antes de entregar ao usuário.
|
|
1172
|
+
|
|
1173
|
+
---
|
|
1174
|
+
|
|
1175
|
+
### SAÍDA FINAL AO USUÁRIO
|
|
1176
|
+
|
|
1177
|
+
```
|
|
1178
|
+
⚡ Módulo AI criado: [nome-do-módulo]
|
|
1179
|
+
|
|
1180
|
+
Modelo: @cf/[modelo]
|
|
1181
|
+
Tabela D1: ai_[nome] ([N] colunas tipadas + 3 índices)
|
|
1182
|
+
Cache KV: ai:[nome]:{hash} (TTL: 1h)
|
|
1183
|
+
|
|
1184
|
+
Rotas:
|
|
1185
|
+
POST /api/ai/[nome] → inferência
|
|
1186
|
+
GET /api/ai/[nome]/:lead_id → histórico
|
|
1187
|
+
GET /api/ai/[nome]/stats → métricas
|
|
1188
|
+
|
|
1189
|
+
Pipeline /track: [INTEGRADO na posição [3.x] | NÃO INTEGRADO]
|
|
1190
|
+
|
|
1191
|
+
Smoke tests: 5/5 ✅
|
|
1192
|
+
Deploy: OK — [worker-url]
|
|
1193
|
+
```
|
|
1194
|
+
|
|
1195
|
+
---
|
|
1196
|
+
|
|
918
1197
|
## COMANDO /setup — Fluxo principal de configuração
|
|
919
1198
|
|
|
920
1199
|
### MENSAGEM DE BOAS-VINDAS (disparar na ativação do agente)
|
|
@@ -1079,8 +1358,13 @@ Exibir:
|
|
|
1079
1358
|
**Bloco CartPanda** (incluir se CartPanda selecionado):
|
|
1080
1359
|
> - `CARTPANDA_TOKEN` — Token CartPanda webhook
|
|
1081
1360
|
|
|
1082
|
-
**Bloco
|
|
1083
|
-
> - `
|
|
1361
|
+
**Bloco EVO CRM (OAuth2)** (incluir se CRM selecionado):
|
|
1362
|
+
> - `EVO_CRM_BASE_URL` — URL base (ex: https://api-evocrm.dominio.com)
|
|
1363
|
+
> - `EVO_CRM_CLIENT_ID` — OAuth client_id (Configurações -> Aplicações)
|
|
1364
|
+
> - `EVO_CRM_CLIENT_SECRET` — OAuth client_secret (O segredo do app)
|
|
1365
|
+
> - `EVO_CRM_INBOX_ID` — ID numérico do inbox (final da URL da caixa)
|
|
1366
|
+
> - `EVO_CRM_DEFAULT_COUNTRY` — Dial code default (ex: 55)
|
|
1367
|
+
> - `EVO_CRM_LOCALE` — Locale das notas (pt-BR | en-US | es-ES)
|
|
1084
1368
|
|
|
1085
1369
|
**Sempre incluir:**
|
|
1086
1370
|
> - `SITE_URL` — URL do seu funil/site (ex: https://meusite.com.br)
|
|
@@ -1589,7 +1873,15 @@ Spawnar os agentes enterprise em ordem:
|
|
|
1589
1873
|
- W-Shape
|
|
1590
1874
|
- Data-Driven (requer histórico de dados)
|
|
1591
1875
|
|
|
1592
|
-
|
|
1876
|
+
6. **A/B LTV Testing Agent** (ab-ltv-agent.md)
|
|
1877
|
+
- Ativar experimentos A/B sobre o system prompt do Workers AI LTV
|
|
1878
|
+
- Aplicar `schema-ab-ltv.sql` no D1 (ltv_ab_tests + ltv_ab_assignments + ltv_ab_results)
|
|
1879
|
+
- Configurar rotas: `POST /api/ltv/ab-test/create`, `GET /api/ltv/ab-test/results`, `POST /api/ltv/ab-test/winner`
|
|
1880
|
+
- Integrar `getLtvAbVariation()` no fluxo `predictLtv()` do `index.ts`
|
|
1881
|
+
- Conectar resultado do webhook (compra real) ao `ltv_ab_assignments.converted` para scoring de acurácia
|
|
1882
|
+
- Downstream: ao detectar vencedor com `accuracy_improvement ≥ 5%`, notificar LTV Predictor Agent para atualizar o prompt padrão
|
|
1883
|
+
|
|
1884
|
+
7. **Security Enterprise Agent** (security-enterprise-agent.md)
|
|
1593
1885
|
- Implementar rate limiting (IP, user, global)
|
|
1594
1886
|
- Configurar IP blacklist/whitelist
|
|
1595
1887
|
- Implementar input validation com Joi
|
|
@@ -1598,14 +1890,14 @@ Spawnar os agentes enterprise em ordem:
|
|
|
1598
1890
|
- Criar audit logging completo
|
|
1599
1891
|
- Criar D1 schemas: ip_blacklist, ip_whitelist, ip_violations, audit_logs
|
|
1600
1892
|
|
|
1601
|
-
|
|
1893
|
+
8. **Performance Optimization Agent** (performance-optimization-agent.md)
|
|
1602
1894
|
- Implementar caching multi-camada (L1 memory, L2 KV, L3 D1)
|
|
1603
1895
|
- Criar índices otimizados para D1
|
|
1604
1896
|
- Implementar batch processing para atribuição
|
|
1605
1897
|
- Configurar latency profiling
|
|
1606
1898
|
- Criar endpoints de monitoramento de performance
|
|
1607
1899
|
|
|
1608
|
-
|
|
1900
|
+
9. **Compliance Agent** (compliance-agent.md)
|
|
1609
1901
|
- Implementar consent management (GDPR, LGPD, CCPA)
|
|
1610
1902
|
- Configurar data rights (access, deletion, portability, rectification)
|
|
1611
1903
|
- Implementar data retention policies automatizadas
|
|
@@ -1624,6 +1916,7 @@ Usar `AskUserQuestion` com multi-select para permitir múltiplas seleções:
|
|
|
1624
1916
|
> - [ ] **Match Quality** (garante que só dado com valor real vai para as plataformas — EMQ Score)
|
|
1625
1917
|
> - [ ] **ROAS Feedback + Nurture** (ROAS real por campanha + follow-up automático pós-quiz)
|
|
1626
1918
|
> - [x] Multi-Touch Attribution
|
|
1919
|
+
> - [ ] **A/B LTV Testing** (testa variações do prompt LTV → aumenta precisão preditiva em até +25%)
|
|
1627
1920
|
> - [ ] Security Enterprise (rate limiting, IP blocking)
|
|
1628
1921
|
> - [ ] Performance Optimization (caching, query optimization)
|
|
1629
1922
|
> - [ ] Compliance (GDPR, LGPD, Consent Management)
|
|
@@ -1950,6 +2243,10 @@ Apresentar o resultado organizado com resumo de eventos e próximos passos.
|
|
|
1950
2243
|
wrangler secret put META_ACCESS_TOKEN
|
|
1951
2244
|
wrangler secret put GA4_API_SECRET
|
|
1952
2245
|
wrangler secret put TIKTOK_ACCESS_TOKEN
|
|
2246
|
+
wrangler secret put EVO_CRM_BASE_URL
|
|
2247
|
+
wrangler secret put EVO_CRM_CLIENT_ID
|
|
2248
|
+
wrangler secret put EVO_CRM_CLIENT_SECRET
|
|
2249
|
+
wrangler secret put EVO_CRM_INBOX_ID
|
|
1953
2250
|
```
|
|
1954
2251
|
|
|
1955
2252
|
3. **Testar Eventos:**
|
|
@@ -744,6 +744,26 @@ curl "https://seudominio.com/api/segmentation/outliers?limit=20"
|
|
|
744
744
|
|
|
745
745
|
---
|
|
746
746
|
|
|
747
|
+
## COMANDO *new-ai-module — Ativação por módulo genérico
|
|
748
|
+
|
|
749
|
+
Este agente também é invocado pelo Master Orchestrator quando recebe o comando `*new-ai-module` com descrição do tipo:
|
|
750
|
+
**segmentar, agrupar, cluster, similaridade, perfil, embedding, distribuição**
|
|
751
|
+
|
|
752
|
+
### Responsabilidade no PASSO 1 do pipeline *new-ai-module
|
|
753
|
+
|
|
754
|
+
Entregar obrigatoriamente ao Master Orchestrator:
|
|
755
|
+
|
|
756
|
+
1. **Modelo escolhido** — para clustering semântico: `@cf/baai/bge-m3`; para auto-labeling de segmentos: `@cf/ibm-granite/granite-4.0-h-micro`
|
|
757
|
+
2. **Estratégia de clustering** — K-means (grupos fixos) ou DBSCAN (anomalias/fraude), com `n_clusters` recomendado
|
|
758
|
+
3. **Pipeline de features** — quais campos do payload ou da tabela D1 alimentam o vetor de embedding
|
|
759
|
+
4. **Contrato de output** — `{ segment_id, segment_label, similarity_score, cluster_method }`
|
|
760
|
+
5. **TTL de cache KV recomendado** — padrão 3600s; para segmentos comportamentais usar 1800s
|
|
761
|
+
6. **Posição no pipeline `/track`** — se Modo A ou C, este módulo entra após LTV Prediction
|
|
762
|
+
|
|
763
|
+
> **Regra:** Responder com o pacote completo em uma única mensagem. Sem perguntas de volta ao Orchestrator.
|
|
764
|
+
|
|
765
|
+
---
|
|
766
|
+
|
|
747
767
|
*ML Clustering Agent v1.0 — Segmentação Dinâmica ML*
|
|
748
768
|
*Versão: 1.0 — Criado em: 9 de Abril de 2026*
|
|
749
769
|
*Status: Ready para implementação*
|
package/package.json
CHANGED
|
@@ -366,8 +366,8 @@ pattern = "SEU_DOMINIO/track*" # ← Substituir pelo domínio real
|
|
|
366
366
|
zone_name = "SEU_DOMINIO" # ← Substituir pelo domínio real
|
|
367
367
|
|
|
368
368
|
# Exemplo real:
|
|
369
|
-
# pattern = "
|
|
370
|
-
# zone_name = "
|
|
369
|
+
# pattern = "cliente.com.br/track*"
|
|
370
|
+
# zone_name = "cliente.com.br"
|
|
371
371
|
```
|
|
372
372
|
|
|
373
373
|
#### 3. Fazer o deploy com as rotas
|
|
@@ -63,6 +63,9 @@ import {
|
|
|
63
63
|
processWhatsAppWebhook,
|
|
64
64
|
verifyHmac,
|
|
65
65
|
} from './modules/dispatch/whatsapp';
|
|
66
|
+
import {
|
|
67
|
+
pushLeadToCrm,
|
|
68
|
+
} from './modules/dispatch/crm';
|
|
66
69
|
|
|
67
70
|
// ── ML — LTV + A/B Testing ────────────────────────────────────────────────────
|
|
68
71
|
import {
|
|
@@ -239,6 +242,9 @@ export default {
|
|
|
239
242
|
WA_NOTIFY_NUMBER: env.WA_NOTIFY_NUMBER ? 'set' : 'not set (optional - only for auto-reply)',
|
|
240
243
|
TIKTOK_ACCESS_TOKEN: env.TIKTOK_ACCESS_TOKEN ? 'set' : 'not set (optional)',
|
|
241
244
|
CALLMEBOT_PHONE: env.CALLMEBOT_PHONE ? 'set' : 'not set (optional)',
|
|
245
|
+
EVO_CRM_BASE_URL: env.EVO_CRM_BASE_URL ? 'set' : 'not set (optional - EVO CRM)',
|
|
246
|
+
EVO_CRM_CLIENT_ID: env.EVO_CRM_CLIENT_ID ? 'set' : 'not set (optional - EVO CRM)',
|
|
247
|
+
EVO_CRM_INBOX_ID: env.EVO_CRM_INBOX_ID ? 'set' : 'not set (optional - EVO CRM)',
|
|
242
248
|
};
|
|
243
249
|
|
|
244
250
|
const hasMissing =
|
|
@@ -793,6 +799,39 @@ export default {
|
|
|
793
799
|
: []),
|
|
794
800
|
]);
|
|
795
801
|
|
|
802
|
+
// ── EVO CRM — cria contato + conversa + nota interna ─────────────────
|
|
803
|
+
// Silencioso se EVO_CRM_BASE_URL / EVO_CRM_CLIENT_ID não estiverem configurados.
|
|
804
|
+
const CRM_EVENTS = ['Lead', 'Contact', 'CompleteRegistration'];
|
|
805
|
+
if (CRM_EVENTS.includes(eventName) && trackPayload.phone) {
|
|
806
|
+
ctx.waitUntil(
|
|
807
|
+
pushLeadToCrm(env, {
|
|
808
|
+
phone: trackPayload.phone,
|
|
809
|
+
name: [trackPayload.firstName, trackPayload.lastName].filter(Boolean).join(' ') || null,
|
|
810
|
+
email: trackPayload.email || null,
|
|
811
|
+
fbclid: trackPayload.fbclid || null,
|
|
812
|
+
fbc: trackPayload.fbc || null,
|
|
813
|
+
fbp: trackPayload.fbp || null,
|
|
814
|
+
utmSource: trackPayload.utmSource || null,
|
|
815
|
+
utmMedium: trackPayload.utmMedium || null,
|
|
816
|
+
utmCampaign: trackPayload.utmCampaign || null,
|
|
817
|
+
utmContent: trackPayload.utmContent || null,
|
|
818
|
+
utmTerm: trackPayload.utmTerm || null,
|
|
819
|
+
pageUrl: trackPayload.pageUrl || null,
|
|
820
|
+
formName: trackPayload.contentName || trackPayload.productName || eventName,
|
|
821
|
+
eventName,
|
|
822
|
+
intentScore: typeof trackPayload.intent_score === 'number'
|
|
823
|
+
? trackPayload.intent_score
|
|
824
|
+
: typeof trackPayload.intentScoreNum === 'number'
|
|
825
|
+
? trackPayload.intentScoreNum
|
|
826
|
+
: null,
|
|
827
|
+
ltvClass: trackPayload.ltvClass || null,
|
|
828
|
+
funnelStage: trackPayload.funnel_stage || trackPayload.funnelDepth || null,
|
|
829
|
+
value: trackPayload.value ?? null,
|
|
830
|
+
currency: trackPayload.currency || null,
|
|
831
|
+
})
|
|
832
|
+
);
|
|
833
|
+
}
|
|
834
|
+
|
|
796
835
|
// Automação de mensagens
|
|
797
836
|
const AUTOMATION_EVENTS = ['Lead', 'Purchase', 'InitiateCheckout'];
|
|
798
837
|
if (AUTOMATION_EVENTS.includes(eventName) && env.DB) {
|