feat(dialer): CPS Limiter + Predictive Dialer Engine

Fecha agente.md secao 72-86 (motor preditivo) e 77-79 (CPS distribuido,
reserva de leads, lock de campanha). Uma campanha RUNNING agora origina
chamadas sozinha, respeitando capacidade de agentes, CPS hierarquico e
taxa de abandono — sem intervencao manual.

Deliberadamente fora do escopo (agente.md secao 72: "nao e' so' `for lead
-> originate`"): mod_avmd (opcional), callbacks agendados, disposicoes de
agente — ficam pra fase CDR.

## Novo servico apps/predictive-dialer

Mesmo padrao arquitetural de fs-events/fs-config: Node standalone em
Docker, ESL propria, tick a cada 2s sobre tenants ativos x campanhas
RUNNING/WAITING_SCHEDULE.

- Lock de campanha (dialer:campaign:{id}, secao 79): TTL/ownership/
  renewal/safe-release via Lua compare-and-delete.
- CPS distribuido (secao 77, 62): token bucket janela 1s, hierarquia
  GLOBAL/TENANT/TRUNK/CAMPAIGN numa unica chamada Lua atomica — nivel
  esgotado bloqueia todos SEM incremento parcial dos que passariam.
- Reserva atomica de leads (secao 78): FOR UPDATE SKIP LOCKED dentro da
  mesma transacao withTenantContext.
- CallAttempt/CampaignStats (schema novo): state machine da chamada
  (secao 82) + EWMA (secao 75) de answer_probability/average_answer_delay/
  average_talk_time/abandon_rate por campanha.
- Capacidade em tempo real + pacing (secao 73-76, 84-85): conta agentes
  por estado via Tier->Agent.state, previsao de liberacao (horizonte
  unico de 15s, simplificacao documentada dos 4 buckets da especificacao),
  controle de abandono reduz pacing progressivamente, nunca origina sem
  capacidade prevista.

## Modo simulacao (secao 185-186)

DIALER_SIMULATION=true (default, ja estava no .env desde o inicio da
sessao) sorteia ANSWER/BUSY/NO_ANSWER/FAILED em software, sem PSTN real.
So' quando ANSWERED e' que uma chamada sintetica (null/dummy, sem PSTN)
entra na fila real via mod_callcenter de verdade — escolha deliberada pra
maximizar codigo real exercitado em vez de simular tudo em memoria. Os
identificadores da secao 81 (b2bcall_tenant_id/call_id/attempt_id/
campaign_id/lead_id) vao como channel variables nessa perna, entregando
tenantId real no WebSocket sem fan-out.

Real Outbound Safety (secao 186): as duas flags checadas no boot, nunca
ativadas automaticamente — caminho PSTN real implementado mas nunca
exercitado (sem trunk/operadora real neste laboratorio).

## Dois bugs reais achados e corrigidos testando esta fase

- Perna sintetica (null/dummy) nao tem midia do outro lado — nunca
  desligava sozinha depois de bridgear com um agente. Corrigido com
  hangup agendado via uuid_kill no talk_time simulado.
- Corrida entre queue:sync e tier:sync (dois canais Redis independentes,
  sem ordem garantida): atribuir tier logo depois de criar a fila podia
  rodar tier add antes do queue reload terminar ("-ERR Queue not found!",
  erro real, diferente do ja conhecido "already exist"). Corrigido com
  retry curto (ate 3 tentativas) em agent-sync.ts::addTierWithRetry.

## GET /campaigns/:id/stats

Secao 227.7 "visualizar pacing" — CampaignStats + agentes por estado +
calls em andamento, sem esperar a fase Frontend.

Verificado ponta a ponta: campanha RUNNING originando 3 tentativas por
tick, outcomes simulados corretos com retry agendado (BUSY 15min/
NO_ANSWER 60min/FAILED 30min), uma tentativa ANSWERED completando o ciclo
real inteiro (fila -> agente -> bridge -> hangup -> EWMA atualizada),
stop nao derruba chamada ativa (secao 66), calls_answered=3 confirmado no
`queue list` do FreeSWITCH. CPS limiter e lock de campanha testados
isoladamente (hierarquia sem incremento parcial, ownership nunca
roubado). typecheck do workspace inteiro limpo.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X1HxY46WGU4G1zmVDNKcWw
This commit is contained in:
2026-08-28 13:31:31 -03:00
parent 7b62ad3d82
commit cb6d343b2e
29 changed files with 1851 additions and 28 deletions

View File

@@ -0,0 +1,60 @@
-- CreateEnum
CREATE TYPE "call_attempt_status" AS ENUM ('CREATED', 'RESERVED', 'ORIGINATING', 'ORIGINATED', 'RINGING', 'ANSWERED', 'QUEUEING', 'AGENT_CONNECTED', 'COMPLETED', 'BUSY', 'NO_ANSWER', 'FAILED', 'ABANDONED');
-- CreateTable
CREATE TABLE "call_attempts" (
"id" UUID NOT NULL,
"tenant_id" UUID NOT NULL,
"campaign_id" UUID NOT NULL,
"lead_id" UUID NOT NULL,
"agent_id" UUID,
"origination_uuid" UUID,
"status" "call_attempt_status" NOT NULL DEFAULT 'CREATED',
"simulated" BOOLEAN NOT NULL DEFAULT false,
"hangup_cause" TEXT,
"talk_time_seconds" INTEGER,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"ringing_at" TIMESTAMP(3),
"answered_at" TIMESTAMP(3),
"bridged_at" TIMESTAMP(3),
"ended_at" TIMESTAMP(3),
CONSTRAINT "call_attempts_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "campaign_stats" (
"campaign_id" UUID NOT NULL,
"answer_probability" DOUBLE PRECISION NOT NULL DEFAULT 0.4,
"average_answer_delay" DOUBLE PRECISION NOT NULL DEFAULT 5,
"average_talk_time" DOUBLE PRECISION NOT NULL DEFAULT 180,
"abandon_rate" DOUBLE PRECISION NOT NULL DEFAULT 0,
"pacing_factor" DOUBLE PRECISION NOT NULL DEFAULT 1.0,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "campaign_stats_pkey" PRIMARY KEY ("campaign_id")
);
-- CreateIndex
CREATE UNIQUE INDEX "call_attempts_origination_uuid_key" ON "call_attempts"("origination_uuid");
-- CreateIndex
CREATE INDEX "call_attempts_tenant_id_idx" ON "call_attempts"("tenant_id");
-- CreateIndex
CREATE INDEX "call_attempts_campaign_id_status_idx" ON "call_attempts"("campaign_id", "status");
-- AddForeignKey
ALTER TABLE "call_attempts" ADD CONSTRAINT "call_attempts_tenant_id_fkey" FOREIGN KEY ("tenant_id") REFERENCES "tenants"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "call_attempts" ADD CONSTRAINT "call_attempts_campaign_id_fkey" FOREIGN KEY ("campaign_id") REFERENCES "campaigns"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "call_attempts" ADD CONSTRAINT "call_attempts_lead_id_fkey" FOREIGN KEY ("lead_id") REFERENCES "leads"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "call_attempts" ADD CONSTRAINT "call_attempts_agent_id_fkey" FOREIGN KEY ("agent_id") REFERENCES "agents"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "campaign_stats" ADD CONSTRAINT "campaign_stats_campaign_id_fkey" FOREIGN KEY ("campaign_id") REFERENCES "campaigns"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

View File

@@ -0,0 +1,14 @@
/*
Warnings:
- Added the required column `tenant_id` to the `campaign_stats` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "campaign_stats" ADD COLUMN "tenant_id" UUID NOT NULL;
-- CreateIndex
CREATE INDEX "campaign_stats_tenant_id_idx" ON "campaign_stats"("tenant_id");
-- AddForeignKey
ALTER TABLE "campaign_stats" ADD CONSTRAINT "campaign_stats_tenant_id_fkey" FOREIGN KEY ("tenant_id") REFERENCES "tenants"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

View File

@@ -0,0 +1,10 @@
-- Tabelas de negocio tenant-scoped: RLS obrigatorio em todas (ver docs/TENANT_ISOLATION.md).
ALTER TABLE "call_attempts" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "call_attempts" FORCE ROW LEVEL SECURITY;
CREATE POLICY "tenant_isolation" ON "call_attempts"
USING (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid);
ALTER TABLE "campaign_stats" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "campaign_stats" FORCE ROW LEVEL SECURITY;
CREATE POLICY "tenant_isolation" ON "campaign_stats"
USING (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid);

View File

@@ -50,6 +50,8 @@ model Tenant {
campaigns Campaign[]
leads Lead[]
suppressionEntries SuppressionEntry[]
callAttempts CallAttempt[]
campaignStats CampaignStats[]
@@map("tenants")
}
@@ -532,13 +534,14 @@ model Agent {
updatedAt DateTime @updatedAt @map("updated_at")
deletedAt DateTime? @map("deleted_at")
tenant Tenant @relation(fields: [tenantId], references: [id])
user User @relation(fields: [userId], references: [id])
extension Extension? @relation(fields: [extensionId], references: [id])
tiers Tier[]
sessions AgentSession[]
stateEvents AgentStateEvent[]
pauseEvents AgentPauseEvent[]
tenant Tenant @relation(fields: [tenantId], references: [id])
user User @relation(fields: [userId], references: [id])
extension Extension? @relation(fields: [extensionId], references: [id])
tiers Tier[]
sessions AgentSession[]
stateEvents AgentStateEvent[]
pauseEvents AgentPauseEvent[]
callAttempts CallAttempt[]
@@unique([tenantId, userId])
@@index([tenantId])
@@ -711,10 +714,12 @@ model Campaign {
updatedAt DateTime @updatedAt @map("updated_at")
deletedAt DateTime? @map("deleted_at")
tenant Tenant @relation(fields: [tenantId], references: [id])
queue Queue @relation(fields: [queueId], references: [id])
trunk Trunk @relation(fields: [trunkId], references: [id])
leads Lead[]
tenant Tenant @relation(fields: [tenantId], references: [id])
queue Queue @relation(fields: [queueId], references: [id])
trunk Trunk @relation(fields: [trunkId], references: [id])
leads Lead[]
callAttempts CallAttempt[]
campaignStats CampaignStats[]
@@unique([tenantId, name])
@@index([tenantId])
@@ -776,8 +781,9 @@ model Lead {
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
tenant Tenant @relation(fields: [tenantId], references: [id])
campaign Campaign @relation(fields: [campaignId], references: [id])
tenant Tenant @relation(fields: [tenantId], references: [id])
campaign Campaign @relation(fields: [campaignId], references: [id])
callAttempts CallAttempt[]
@@unique([campaignId, phoneNormalized])
@@index([tenantId])
@@ -803,3 +809,93 @@ model SuppressionEntry {
@@index([tenantId])
@@map("suppression_entries")
}
enum CallAttemptStatus {
CREATED
RESERVED
ORIGINATING
ORIGINATED
RINGING
ANSWERED
QUEUEING
AGENT_CONNECTED
COMPLETED
BUSY
NO_ANSWER
FAILED
ABANDONED
@@map("call_attempt_status")
}
// Uma tentativa de discagem de um lead (agente.md secao 81-82). Os
// identificadores daqui (id, campaignId, leadId, originationUuid) viram
// channel variables b2bcall_* no originate (secao 81) — é assim que
// b2bcall-fs-events consegue popular NormalizedEvent.tenantId/b2bcallCallId
// pra chamadas do discador, diferente das chamadas internas (extension a
// extension) que não carregam esses vars ainda.
model CallAttempt {
id String @id @default(uuid()) @db.Uuid
tenantId String @map("tenant_id") @db.Uuid
campaignId String @map("campaign_id") @db.Uuid
leadId String @map("lead_id") @db.Uuid
agentId String? @map("agent_id") @db.Uuid
// UUID do channel no FreeSWITCH (real ou simulado) — null até o originate
// de fato rodar (status ainda CREATED/RESERVED).
originationUuid String? @unique @map("origination_uuid") @db.Uuid
status CallAttemptStatus @default(CREATED)
// agente.md secao 185: em modo simulação, nenhuma chamada PSTN real
// acontece — answer/busy/no_answer/failed/ringing/delay/talk_time são
// sorteados em software, nunca originados de verdade pro trunk.
simulated Boolean @default(false)
hangupCause String? @map("hangup_cause")
talkTimeSeconds Int? @map("talk_time_seconds")
createdAt DateTime @default(now()) @map("created_at")
ringingAt DateTime? @map("ringing_at")
answeredAt DateTime? @map("answered_at")
bridgedAt DateTime? @map("bridged_at")
endedAt DateTime? @map("ended_at")
tenant Tenant @relation(fields: [tenantId], references: [id])
campaign Campaign @relation(fields: [campaignId], references: [id])
lead Lead @relation(fields: [leadId], references: [id])
agent Agent? @relation(fields: [agentId], references: [id])
@@index([tenantId])
@@index([campaignId, status])
@@map("call_attempts")
}
// Estatísticas EWMA por campanha (agente.md secao 73-76), consultadas e
// atualizadas a cada tick do PredictiveDialerEngine — persistidas pra
// sobreviver a reinícios do worker (não é cache descartável). Valores
// iniciais são estimativas conservadoras (secao 74: "não precisa Machine
// Learning, preferir algoritmo estatístico determinístico e explicável"),
// convergem conforme tentativas reais completam.
model CampaignStats {
campaignId String @id @map("campaign_id") @db.Uuid
tenantId String @map("tenant_id") @db.Uuid
answerProbability Float @default(0.4) @map("answer_probability")
averageAnswerDelay Float @default(5) @map("average_answer_delay")
averageTalkTime Float @default(180) @map("average_talk_time")
abandonRate Float @default(0) @map("abandon_rate")
// Fator de pacing aplicado no cálculo de quantas chamadas originar por
// tick (secao 76) — começa em Campaign.pacingInitial, ajustado pelo
// controle de abandono (secao 84), sempre dentro de [pacingMin, pacingMax].
pacingFactor Float @default(1.0) @map("pacing_factor")
updatedAt DateTime @updatedAt @map("updated_at")
tenant Tenant @relation(fields: [tenantId], references: [id])
campaign Campaign @relation(fields: [campaignId], references: [id])
@@index([tenantId])
@@map("campaign_stats")
}

View File

@@ -11,6 +11,7 @@ function baseFields(headers: RawHeaders, extra: Record<string, unknown> = {}) {
callUuid: headers["Unique-ID"],
tenantId: channelVar(headers, "b2bcall_tenant_id"),
b2bcallCallId: channelVar(headers, "b2bcall_call_id"),
b2bcallAttemptId: channelVar(headers, "b2bcall_attempt_id"),
b2bcallCampaignId: channelVar(headers, "b2bcall_campaign_id"),
b2bcallLeadId: channelVar(headers, "b2bcall_lead_id"),
data: { ...extra },

View File

@@ -70,10 +70,12 @@ export interface NormalizedEvent {
occurredAt: string;
/** UUID do channel/call quando aplicável. */
callUuid?: string;
/** Channel variables b2bcall_* quando presentes (secao 81) — ainda não
* populadas nesta fase (só existirão a partir do Predictive Engine). */
/** Channel variables b2bcall_* (secao 81) — populadas pra chamadas
* originadas pelo PredictiveDialerEngine (fase Predictive Engine);
* chamadas internas (extensão a extensão) ainda não carregam esses vars. */
tenantId?: string;
b2bcallCallId?: string;
b2bcallAttemptId?: string;
b2bcallCampaignId?: string;
b2bcallLeadId?: string;
data: Record<string, unknown>;