cdp-edge 2.5.5 → 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 +1 -1
- package/contracts/agent-versions.json +2 -2
- package/extracted-skill/tracking-events-generator/agents/evo-crm-agent.md +9 -0
- package/extracted-skill/tracking-events-generator/agents/ltv-predictor-agent.md +19 -0
- package/extracted-skill/tracking-events-generator/agents/master-orchestrator.md +300 -9
- package/extracted-skill/tracking-events-generator/agents/ml-clustering-agent.md +20 -0
- package/package.json +1 -1
- package/server-edge-tracker/modules/ml/fraud.ts +15 -3
- package/server-edge-tracker/types.ts +6 -0
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# 🚀 CDP Edge — Quantum Tracking Enterprise
|
|
2
2
|
**Padrão Quantum Tracking: 100% Cloudflare Edge.** Sem GTM. Sem Stape. Sem cookies de terceiros.
|
|
3
3
|
|
|
4
|
-
> **v2.5.
|
|
4
|
+
> **v2.5.6** — Fraud Gate parametrizável: geo-fence + datacenter kill-switch + threshold configurável (30 de Abril de 2026) 🛡️
|
|
5
5
|
|
|
6
6
|
---
|
|
7
7
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"_comment": "Fonte de verdade para versões dos agent files. Atualizar quando modules/ ou index.ts mudarem. Use scripts/validate-agents.js para detectar drifts.",
|
|
3
|
-
"worker_version": "2.5.
|
|
4
|
-
"worker_hash_date": "2026-04-
|
|
3
|
+
"worker_version": "2.5.6",
|
|
4
|
+
"worker_hash_date": "2026-04-30",
|
|
5
5
|
"agents": {
|
|
6
6
|
"master-orchestrator": {
|
|
7
7
|
"version": "2.0.7",
|
|
@@ -202,6 +202,15 @@ Cobertura:
|
|
|
202
202
|
3. `wrangler secret put` os 4 obrigatórios
|
|
203
203
|
4. Disparar lead via `/track` ou webhook → conferir contato + conversa + nota no painel EVO
|
|
204
204
|
|
|
205
|
+
## 🔑 ONDE ENCONTRAR AS 4 CREDENCIAIS (UI GUIDE)
|
|
206
|
+
|
|
207
|
+
Para orientar o usuário, siga este roteiro:
|
|
208
|
+
|
|
209
|
+
1. **`EVO_CRM_BASE_URL`**: A URL de acesso ao painel (ex: `https://api.seucrm.com`).
|
|
210
|
+
2. **`EVO_CRM_CLIENT_ID`**: Gerado em Administrador → Configurações → Aplicações → "Nova Aplicação".
|
|
211
|
+
3. **`EVO_CRM_CLIENT_SECRET`**: Gerado junto com o ID acima. *Atenção: Só aparece uma vez!*
|
|
212
|
+
4. **`EVO_CRM_INBOX_ID`**: Clique na Caixa de Entrada desejada e pegue o número final na URL do navegador (ex: `/inboxes/5`).
|
|
213
|
+
|
|
205
214
|
---
|
|
206
215
|
|
|
207
216
|
## 🔧 INTEGRAÇÃO COM OUTROS AGENTES
|
|
@@ -57,3 +57,22 @@ Sempre que o Orquestrador invocar a Otimização de Baleias (LTV Prediction):
|
|
|
57
57
|
"limite_diario": 10000
|
|
58
58
|
}
|
|
59
59
|
```
|
|
60
|
+
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
## COMANDO *new-ai-module — Ativação por módulo genérico
|
|
64
|
+
|
|
65
|
+
Este agente também é invocado pelo Master Orchestrator quando recebe o comando `*new-ai-module` com descrição do tipo:
|
|
66
|
+
**classificar, score, pontuar, prever, predizer, detectar, identificar, intenção, distribuir, rotear, priorizar, ranking**
|
|
67
|
+
|
|
68
|
+
### Responsabilidade no PASSO 1 do pipeline *new-ai-module
|
|
69
|
+
|
|
70
|
+
Entregar obrigatoriamente ao Master Orchestrator:
|
|
71
|
+
|
|
72
|
+
1. **Modelo escolhido** — justificado pelo caso de uso descrito
|
|
73
|
+
2. **System prompt calibrado** — instrução para o modelo retornar JSON puro com os campos: `class`, `confidence`, `score`, `reasoning`
|
|
74
|
+
3. **Contrato de features** — quais campos do payload `/track` alimentam o modelo como input
|
|
75
|
+
4. **TTL de cache KV recomendado** — padrão 3600s, ajustar se o módulo for sensível a tempo real
|
|
76
|
+
5. **Posição no pipeline `/track`** — se Modo A ou C, indicar após qual módulo existente este deve ser inserido
|
|
77
|
+
|
|
78
|
+
> **Regra:** Responder com o pacote completo em uma única mensagem. Sem perguntas de volta ao Orchestrator.
|
|
@@ -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
|
|
@@ -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 ──
|
|
@@ -916,6 +923,277 @@ FASE 6 (Enterprise Features — ordem de configuração):
|
|
|
916
923
|
|
|
917
924
|
---
|
|
918
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
|
+
|
|
919
1197
|
## COMANDO /setup — Fluxo principal de configuração
|
|
920
1198
|
|
|
921
1199
|
### MENSAGEM DE BOAS-VINDAS (disparar na ativação do agente)
|
|
@@ -1082,9 +1360,9 @@ Exibir:
|
|
|
1082
1360
|
|
|
1083
1361
|
**Bloco EVO CRM (OAuth2)** (incluir se CRM selecionado):
|
|
1084
1362
|
> - `EVO_CRM_BASE_URL` — URL base (ex: https://api-evocrm.dominio.com)
|
|
1085
|
-
> - `EVO_CRM_CLIENT_ID` — OAuth client_id
|
|
1086
|
-
> - `EVO_CRM_CLIENT_SECRET` — OAuth client_secret
|
|
1087
|
-
> - `EVO_CRM_INBOX_ID` — ID do inbox
|
|
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)
|
|
1088
1366
|
> - `EVO_CRM_DEFAULT_COUNTRY` — Dial code default (ex: 55)
|
|
1089
1367
|
> - `EVO_CRM_LOCALE` — Locale das notas (pt-BR | en-US | es-ES)
|
|
1090
1368
|
|
|
@@ -1595,7 +1873,15 @@ Spawnar os agentes enterprise em ordem:
|
|
|
1595
1873
|
- W-Shape
|
|
1596
1874
|
- Data-Driven (requer histórico de dados)
|
|
1597
1875
|
|
|
1598
|
-
|
|
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)
|
|
1599
1885
|
- Implementar rate limiting (IP, user, global)
|
|
1600
1886
|
- Configurar IP blacklist/whitelist
|
|
1601
1887
|
- Implementar input validation com Joi
|
|
@@ -1604,14 +1890,14 @@ Spawnar os agentes enterprise em ordem:
|
|
|
1604
1890
|
- Criar audit logging completo
|
|
1605
1891
|
- Criar D1 schemas: ip_blacklist, ip_whitelist, ip_violations, audit_logs
|
|
1606
1892
|
|
|
1607
|
-
|
|
1893
|
+
8. **Performance Optimization Agent** (performance-optimization-agent.md)
|
|
1608
1894
|
- Implementar caching multi-camada (L1 memory, L2 KV, L3 D1)
|
|
1609
1895
|
- Criar índices otimizados para D1
|
|
1610
1896
|
- Implementar batch processing para atribuição
|
|
1611
1897
|
- Configurar latency profiling
|
|
1612
1898
|
- Criar endpoints de monitoramento de performance
|
|
1613
1899
|
|
|
1614
|
-
|
|
1900
|
+
9. **Compliance Agent** (compliance-agent.md)
|
|
1615
1901
|
- Implementar consent management (GDPR, LGPD, CCPA)
|
|
1616
1902
|
- Configurar data rights (access, deletion, portability, rectification)
|
|
1617
1903
|
- Implementar data retention policies automatizadas
|
|
@@ -1630,6 +1916,7 @@ Usar `AskUserQuestion` com multi-select para permitir múltiplas seleções:
|
|
|
1630
1916
|
> - [ ] **Match Quality** (garante que só dado com valor real vai para as plataformas — EMQ Score)
|
|
1631
1917
|
> - [ ] **ROAS Feedback + Nurture** (ROAS real por campanha + follow-up automático pós-quiz)
|
|
1632
1918
|
> - [x] Multi-Touch Attribution
|
|
1919
|
+
> - [ ] **A/B LTV Testing** (testa variações do prompt LTV → aumenta precisão preditiva em até +25%)
|
|
1633
1920
|
> - [ ] Security Enterprise (rate limiting, IP blocking)
|
|
1634
1921
|
> - [ ] Performance Optimization (caching, query optimization)
|
|
1635
1922
|
> - [ ] Compliance (GDPR, LGPD, Consent Management)
|
|
@@ -1956,6 +2243,10 @@ Apresentar o resultado organizado com resumo de eventos e próximos passos.
|
|
|
1956
2243
|
wrangler secret put META_ACCESS_TOKEN
|
|
1957
2244
|
wrangler secret put GA4_API_SECRET
|
|
1958
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
|
|
1959
2250
|
```
|
|
1960
2251
|
|
|
1961
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
|
@@ -55,8 +55,11 @@ export async function checkFraudGate(env: Env, request: Request, payload: TrackP
|
|
|
55
55
|
result.score += 40; result.reasons.push('suspicious_user_agent');
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
// 4. Datacenter IP
|
|
58
|
+
// 4. Datacenter IP — kill-switch opcional (FRAUD_BLOCK_DATACENTERS=1 dropa direto)
|
|
59
59
|
if (ip && DATACENTER_PATTERNS.test(asn)) {
|
|
60
|
+
if (env.FRAUD_BLOCK_DATACENTERS === '1') {
|
|
61
|
+
return { allowed: false, score: 100, reasons: ['datacenter_ip_killswitch'], action: 'dropped' };
|
|
62
|
+
}
|
|
60
63
|
result.score += 35; result.reasons.push('datacenter_ip');
|
|
61
64
|
}
|
|
62
65
|
|
|
@@ -65,6 +68,14 @@ export async function checkFraudGate(env: Env, request: Request, payload: TrackP
|
|
|
65
68
|
result.score += 20; result.reasons.push('no_accept_language');
|
|
66
69
|
}
|
|
67
70
|
|
|
71
|
+
// 5b. Geo-fence — country fora de ALLOWED_COUNTRIES (vazio = sem geo-fence)
|
|
72
|
+
const allowed = (env.ALLOWED_COUNTRIES || '').toUpperCase().split(',').map(s => s.trim()).filter(Boolean);
|
|
73
|
+
if (allowed.length > 0 && country && !allowed.includes(country)) {
|
|
74
|
+
const penalty = parseInt(env.FRAUD_GEO_PENALTY || '50');
|
|
75
|
+
result.score += penalty;
|
|
76
|
+
result.reasons.push(`country_blocked:${country}`);
|
|
77
|
+
}
|
|
78
|
+
|
|
68
79
|
// 6. Velocity check via KV
|
|
69
80
|
if (env.GEO_CACHE && ip) {
|
|
70
81
|
const velKey1h = `fraud_velocity:${ip}:h`;
|
|
@@ -79,8 +90,9 @@ export async function checkFraudGate(env: Env, request: Request, payload: TrackP
|
|
|
79
90
|
|
|
80
91
|
result.score = Math.min(100, result.score);
|
|
81
92
|
|
|
82
|
-
// 8. Decisão final
|
|
83
|
-
|
|
93
|
+
// 8. Decisão final — threshold configurável via FRAUD_DROP_THRESHOLD (default 50)
|
|
94
|
+
const dropThreshold = parseInt(env.FRAUD_DROP_THRESHOLD || '50');
|
|
95
|
+
if (result.score >= dropThreshold) {
|
|
84
96
|
result.allowed = false;
|
|
85
97
|
result.action = 'dropped';
|
|
86
98
|
} else if (result.score >= 40) {
|
|
@@ -72,6 +72,12 @@ export interface Env {
|
|
|
72
72
|
EVO_CRM_INBOX_ID?: string; // ID do inbox onde as conversas serão criadas
|
|
73
73
|
EVO_CRM_DEFAULT_COUNTRY?: string; // Country dial code para phones locais (default "55" = Brasil)
|
|
74
74
|
EVO_CRM_LOCALE?: string; // Locale da nota interna: "pt-BR" | "en-US" | "es-ES" (default "pt-BR")
|
|
75
|
+
|
|
76
|
+
// Fraud Gate — defaults parametrizáveis por projeto (vazio = comportamento legado)
|
|
77
|
+
ALLOWED_COUNTRIES?: string; // CSV ISO-2, ex: "BR" ou "BR,PT,AO". Vazio = sem geo-fence
|
|
78
|
+
FRAUD_DROP_THRESHOLD?: string; // Score mínimo pra drop. Default "50" (antes era 80)
|
|
79
|
+
FRAUD_BLOCK_DATACENTERS?: string; // "1" = drop direto se ASN é datacenter (kill-switch)
|
|
80
|
+
FRAUD_GEO_PENALTY?: string; // Pontos somados quando country não está em ALLOWED_COUNTRIES. Default "50"
|
|
75
81
|
}
|
|
76
82
|
|
|
77
83
|
// ── Event Payload Types ───────────────────────────────────────────────────────
|