anderson-ufrj
commited on
Commit
·
34c8d46
1
Parent(s):
4eafb23
docs(investigations): add comprehensive 24/7 auto-investigation documentation
Browse filesComplete guide for deploying and operating the autonomous investigation system.
Includes:
- Architecture overview and data flow
- Activation instructions (local, production, Docker)
- Configuration options and tuning
- Monitoring and troubleshooting
- Security considerations
- KPIs and metrics tracking
Author: Anderson Henrique da Silva
Date: 2025-10-07 18:11:37
docs/24-7-AUTO-INVESTIGATION-SYSTEM.md
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🤖 Sistema de Investigação Autônoma 24/7
|
| 2 |
+
|
| 3 |
+
**Autor**: Anderson Henrique da Silva
|
| 4 |
+
**Data**: 2025-10-07 18:11:37
|
| 5 |
+
**Status**: ✅ Implementado e Pronto para Produção
|
| 6 |
+
|
| 7 |
+
## 📋 Visão Geral
|
| 8 |
+
|
| 9 |
+
Sistema completamente autônomo que monitora contratos governamentais 24 horas por dia, 7 dias por semana, detectando automaticamente padrões suspeitos e criando investigações forenses detalhadas SEM intervenção humana.
|
| 10 |
+
|
| 11 |
+
## 🎯 O Que o Sistema Faz
|
| 12 |
+
|
| 13 |
+
### 1. Monitoramento Contínuo de Contratos Novos
|
| 14 |
+
- **Frequência**: A cada 6 horas
|
| 15 |
+
- **Lookback**: Últimas 6 horas de contratos
|
| 16 |
+
- **Fonte**: Portal da Transparência API
|
| 17 |
+
- **Ação**: Cria investigações automáticas para contratos suspeitos
|
| 18 |
+
|
| 19 |
+
### 2. Monitoramento Prioritário de Órgãos Críticos
|
| 20 |
+
- **Frequência**: A cada 4 horas
|
| 21 |
+
- **Fila**: High Priority
|
| 22 |
+
- **Órgãos**: Lista configurável de órgãos com histórico de irregularidades
|
| 23 |
+
- **Ação**: Análise mais frequente e detalhada
|
| 24 |
+
|
| 25 |
+
### 3. Reanálise de Contratos Históricos
|
| 26 |
+
- **Frequência**: Semanal (domingos 3h)
|
| 27 |
+
- **Lookback**: 6 meses
|
| 28 |
+
- **Propósito**: Encontrar anomalias previamente perdidas com modelos atualizados
|
| 29 |
+
- **Processamento**: Lotes de 100 contratos por vez
|
| 30 |
+
|
| 31 |
+
### 4. Health Check do Sistema
|
| 32 |
+
- **Frequência**: A cada hora
|
| 33 |
+
- **Verifica**: API Transparência, Investigation Service, Agent Pool
|
| 34 |
+
- **Alertas**: Logs de componentes com problemas
|
| 35 |
+
|
| 36 |
+
## 🔍 Critérios de Pré-Triagem (Suspicion Score)
|
| 37 |
+
|
| 38 |
+
O sistema calcula automaticamente um "suspicion score" baseado em:
|
| 39 |
+
|
| 40 |
+
| Critério | Pontos | Descrição |
|
| 41 |
+
|----------|--------|-----------|
|
| 42 |
+
| **Valor Alto** | +2 | Contratos acima de R$ 100.000 |
|
| 43 |
+
| **Processo Emergencial** | +3 | Dispensa ou inexigibilidade de licitação |
|
| 44 |
+
| **Licitante Único** | +2 | Apenas 1 proponente no processo |
|
| 45 |
+
| **Fornecedor em Watchlist** | +3 | Fornecedor com histórico de problemas |
|
| 46 |
+
| **Prazo Curto de Licitação** | +1 | Tempo insuficiente para competição |
|
| 47 |
+
|
| 48 |
+
**Threshold para Investigação**: Score ≥ 3 pontos
|
| 49 |
+
|
| 50 |
+
## 🏗️ Arquitetura
|
| 51 |
+
|
| 52 |
+
```
|
| 53 |
+
┌─────────────────────────────────────────────────────────────┐
|
| 54 |
+
│ Celery Beat Scheduler │
|
| 55 |
+
│ (Agenda e dispara tarefas periodicamente) │
|
| 56 |
+
└───────────────┬─────────────────────────────────────────────┘
|
| 57 |
+
│
|
| 58 |
+
┌───────────┼───────────┬────────────┬───────────────┐
|
| 59 |
+
│ │ │ │ │
|
| 60 |
+
▼ ▼ ▼ ▼ ▼
|
| 61 |
+
[6h Task] [4h Task] [Weekly] [Hourly] [On-Demand]
|
| 62 |
+
New Contracts Priority Historical Health User-Triggered
|
| 63 |
+
Monitor Orgs Reanalysis Check Investigations
|
| 64 |
+
│ │ │ │ │
|
| 65 |
+
└───────────┴───────────┴────────────┴───────────────┘
|
| 66 |
+
│
|
| 67 |
+
▼
|
| 68 |
+
┌───────────────────────────────┐
|
| 69 |
+
│ Auto Investigation Service │
|
| 70 |
+
│ - Fetch contracts from API │
|
| 71 |
+
│ - Pre-screen for suspicion │
|
| 72 |
+
│ - Trigger full investigation │
|
| 73 |
+
└───────────────┬───────────────┘
|
| 74 |
+
│
|
| 75 |
+
▼
|
| 76 |
+
┌───────────────────────────────┐
|
| 77 |
+
│ Zumbi (InvestigatorAgent) │
|
| 78 |
+
│ - Full anomaly detection │
|
| 79 |
+
│ - Forensic enrichment │
|
| 80 |
+
│ - Evidence collection │
|
| 81 |
+
└───────────────┬───────────────┘
|
| 82 |
+
│
|
| 83 |
+
▼
|
| 84 |
+
┌───────────────────────────────┐
|
| 85 |
+
│ Supabase (Database) │
|
| 86 |
+
│ - Investigation records │
|
| 87 |
+
│ - Forensic results │
|
| 88 |
+
│ - ML feedback data │
|
| 89 |
+
└───────────────────────────────┘
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
## 🚀 Como Ativar
|
| 93 |
+
|
| 94 |
+
### Pré-requisitos
|
| 95 |
+
|
| 96 |
+
1. **Redis** instalado e rodando:
|
| 97 |
+
```bash
|
| 98 |
+
# Ubuntu/Debian
|
| 99 |
+
sudo apt-get install redis-server
|
| 100 |
+
sudo systemctl start redis
|
| 101 |
+
|
| 102 |
+
# macOS
|
| 103 |
+
brew install redis
|
| 104 |
+
brew services start redis
|
| 105 |
+
|
| 106 |
+
# Docker
|
| 107 |
+
docker run -d -p 6379:6379 redis:7-alpine
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
2. **Variáveis de ambiente configuradas**:
|
| 111 |
+
```bash
|
| 112 |
+
# .env
|
| 113 |
+
REDIS_URL=redis://localhost:6379/0
|
| 114 |
+
TRANSPARENCY_API_KEY=sua-chave-aqui # Opcional mas recomendado
|
| 115 |
+
SUPABASE_URL=sua-url-supabase
|
| 116 |
+
SUPABASE_SERVICE_ROLE_KEY=sua-chave-supabase
|
| 117 |
+
GROQ_API_KEY=sua-chave-groq # Para LLM dos agentes
|
| 118 |
+
```
|
| 119 |
+
|
| 120 |
+
### Iniciar o Sistema
|
| 121 |
+
|
| 122 |
+
#### Opção 1: Desenvolvimento Local
|
| 123 |
+
|
| 124 |
+
```bash
|
| 125 |
+
# Terminal 1: Celery Worker
|
| 126 |
+
celery -A src.infrastructure.queue.celery_app worker \
|
| 127 |
+
--loglevel=info \
|
| 128 |
+
--queues=critical,high,default,low,background \
|
| 129 |
+
--concurrency=4
|
| 130 |
+
|
| 131 |
+
# Terminal 2: Celery Beat (Scheduler)
|
| 132 |
+
celery -A src.infrastructure.queue.celery_app beat \
|
| 133 |
+
--loglevel=info
|
| 134 |
+
```
|
| 135 |
+
|
| 136 |
+
#### Opção 2: Produção (Supervisor)
|
| 137 |
+
|
| 138 |
+
Criar `/etc/supervisor/conf.d/cidadao-ai-celery.conf`:
|
| 139 |
+
|
| 140 |
+
```ini
|
| 141 |
+
[program:cidadao-ai-worker]
|
| 142 |
+
command=/path/to/venv/bin/celery -A src.infrastructure.queue.celery_app worker --loglevel=info --queues=critical,high,default,low,background --concurrency=8
|
| 143 |
+
directory=/path/to/cidadao.ai-backend
|
| 144 |
+
user=www-data
|
| 145 |
+
autostart=true
|
| 146 |
+
autorestart=true
|
| 147 |
+
stopasgroup=true
|
| 148 |
+
killasgroup=true
|
| 149 |
+
redirect_stderr=true
|
| 150 |
+
stdout_logfile=/var/log/celery/worker.log
|
| 151 |
+
|
| 152 |
+
[program:cidadao-ai-beat]
|
| 153 |
+
command=/path/to/venv/bin/celery -A src.infrastructure.queue.celery_app beat --loglevel=info
|
| 154 |
+
directory=/path/to/cidadao.ai-backend
|
| 155 |
+
user=www-data
|
| 156 |
+
autostart=true
|
| 157 |
+
autorestart=true
|
| 158 |
+
redirect_stderr=true
|
| 159 |
+
stdout_logfile=/var/log/celery/beat.log
|
| 160 |
+
```
|
| 161 |
+
|
| 162 |
+
Aplicar configuração:
|
| 163 |
+
```bash
|
| 164 |
+
sudo supervisorctl reread
|
| 165 |
+
sudo supervisorctl update
|
| 166 |
+
sudo supervisorctl start cidadao-ai-worker
|
| 167 |
+
sudo supervisorctl start cidadao-ai-beat
|
| 168 |
+
```
|
| 169 |
+
|
| 170 |
+
#### Opção 3: Docker Compose
|
| 171 |
+
|
| 172 |
+
Adicionar ao `docker-compose.yml`:
|
| 173 |
+
|
| 174 |
+
```yaml
|
| 175 |
+
services:
|
| 176 |
+
redis:
|
| 177 |
+
image: redis:7-alpine
|
| 178 |
+
ports:
|
| 179 |
+
- "6379:6379"
|
| 180 |
+
volumes:
|
| 181 |
+
- redis_data:/data
|
| 182 |
+
|
| 183 |
+
celery-worker:
|
| 184 |
+
build: .
|
| 185 |
+
command: celery -A src.infrastructure.queue.celery_app worker --loglevel=info --queues=critical,high,default,low,background
|
| 186 |
+
depends_on:
|
| 187 |
+
- redis
|
| 188 |
+
env_file:
|
| 189 |
+
- .env
|
| 190 |
+
volumes:
|
| 191 |
+
- .:/app
|
| 192 |
+
|
| 193 |
+
celery-beat:
|
| 194 |
+
build: .
|
| 195 |
+
command: celery -A src.infrastructure.queue.celery_app beat --loglevel=info
|
| 196 |
+
depends_on:
|
| 197 |
+
- redis
|
| 198 |
+
- celery-worker
|
| 199 |
+
env_file:
|
| 200 |
+
- .env
|
| 201 |
+
volumes:
|
| 202 |
+
- .:/app
|
| 203 |
+
|
| 204 |
+
volumes:
|
| 205 |
+
redis_data:
|
| 206 |
+
```
|
| 207 |
+
|
| 208 |
+
Iniciar:
|
| 209 |
+
```bash
|
| 210 |
+
docker-compose up -d redis celery-worker celery-beat
|
| 211 |
+
```
|
| 212 |
+
|
| 213 |
+
## 📊 Monitoramento
|
| 214 |
+
|
| 215 |
+
### Ver Tarefas Agendadas
|
| 216 |
+
|
| 217 |
+
```bash
|
| 218 |
+
celery -A src.infrastructure.queue.celery_app inspect scheduled
|
| 219 |
+
```
|
| 220 |
+
|
| 221 |
+
### Ver Tarefas Ativas
|
| 222 |
+
|
| 223 |
+
```bash
|
| 224 |
+
celery -A src.infrastructure.queue.celery_app inspect active
|
| 225 |
+
```
|
| 226 |
+
|
| 227 |
+
### Ver Estatísticas
|
| 228 |
+
|
| 229 |
+
```bash
|
| 230 |
+
celery -A src.infrastructure.queue.celery_app inspect stats
|
| 231 |
+
```
|
| 232 |
+
|
| 233 |
+
### Flower (Web UI)
|
| 234 |
+
|
| 235 |
+
```bash
|
| 236 |
+
pip install flower
|
| 237 |
+
celery -A src.infrastructure.queue.celery_app flower
|
| 238 |
+
# Acesse: http://localhost:5555
|
| 239 |
+
```
|
| 240 |
+
|
| 241 |
+
## 🎛️ Configuração Avançada
|
| 242 |
+
|
| 243 |
+
### Ajustar Frequência de Monitoramento
|
| 244 |
+
|
| 245 |
+
Edite `src/infrastructure/queue/celery_app.py`:
|
| 246 |
+
|
| 247 |
+
```python
|
| 248 |
+
celery_app.conf.beat_schedule = {
|
| 249 |
+
"auto-monitor-new-contracts-6h": {
|
| 250 |
+
"schedule": timedelta(hours=3), # Mude de 6h para 3h
|
| 251 |
+
"args": (3,), # Lookback de 3h
|
| 252 |
+
},
|
| 253 |
+
}
|
| 254 |
+
```
|
| 255 |
+
|
| 256 |
+
### Adicionar Órgãos Prioritários
|
| 257 |
+
|
| 258 |
+
Edite `src/infrastructure/queue/tasks/auto_investigation_tasks.py`:
|
| 259 |
+
|
| 260 |
+
```python
|
| 261 |
+
priority_orgs = [
|
| 262 |
+
"26101", # Ministério da Saúde
|
| 263 |
+
"20101", # Ministério da Educação
|
| 264 |
+
"53000", # Prefeitura de São Paulo
|
| 265 |
+
# Adicione mais códigos aqui
|
| 266 |
+
]
|
| 267 |
+
```
|
| 268 |
+
|
| 269 |
+
### Ajustar Thresholds de Detecção
|
| 270 |
+
|
| 271 |
+
Edite `src/services/auto_investigation_service.py`:
|
| 272 |
+
|
| 273 |
+
```python
|
| 274 |
+
self.value_threshold = 50000.0 # Reduzir para R$ 50k
|
| 275 |
+
self.daily_contract_limit = 1000 # Aumentar limite diário
|
| 276 |
+
```
|
| 277 |
+
|
| 278 |
+
## 📈 Métricas e KPIs
|
| 279 |
+
|
| 280 |
+
O sistema automaticamente coleta:
|
| 281 |
+
|
| 282 |
+
- **Contratos Analisados**: Total de contratos processados
|
| 283 |
+
- **Taxa de Suspeição**: % de contratos que passam pré-triagem
|
| 284 |
+
- **Investigações Criadas**: Quantidade de investigações automáticas
|
| 285 |
+
- **Anomalias Detectadas**: Total de irregularidades encontradas
|
| 286 |
+
- **Tempo de Processamento**: Duração média das investigações
|
| 287 |
+
- **Taxa de Sucesso**: % de investigações completadas com sucesso
|
| 288 |
+
|
| 289 |
+
Acesse via Flower ou logs estruturados.
|
| 290 |
+
|
| 291 |
+
## 🛠️ Troubleshooting
|
| 292 |
+
|
| 293 |
+
### Problema: Tasks não executam
|
| 294 |
+
|
| 295 |
+
**Causa**: Redis não está rodando ou configuração incorreta
|
| 296 |
+
|
| 297 |
+
**Solução**:
|
| 298 |
+
```bash
|
| 299 |
+
# Verificar Redis
|
| 300 |
+
redis-cli ping
|
| 301 |
+
# Deve retornar: PONG
|
| 302 |
+
|
| 303 |
+
# Verificar configuração
|
| 304 |
+
echo $REDIS_URL
|
| 305 |
+
# Deve retornar: redis://localhost:6379/0
|
| 306 |
+
```
|
| 307 |
+
|
| 308 |
+
### Problema: Muitos erros de API
|
| 309 |
+
|
| 310 |
+
**Causa**: Rate limit do Portal da Transparência
|
| 311 |
+
|
| 312 |
+
**Solução**: Ajustar delays no código ou adicionar `TRANSPARENCY_API_KEY`
|
| 313 |
+
|
| 314 |
+
### Problema: Investigações não aparecem no frontend
|
| 315 |
+
|
| 316 |
+
**Causa**: Supabase não configurado ou credenciais inválidas
|
| 317 |
+
|
| 318 |
+
**Solução**:
|
| 319 |
+
```bash
|
| 320 |
+
# Verificar variáveis
|
| 321 |
+
echo $SUPABASE_URL
|
| 322 |
+
echo $SUPABASE_SERVICE_ROLE_KEY
|
| 323 |
+
|
| 324 |
+
# Testar conexão
|
| 325 |
+
python -c "from src.services.supabase_service_rest import get_supabase_service_rest; import asyncio; print(asyncio.run(get_supabase_service_rest()))"
|
| 326 |
+
```
|
| 327 |
+
|
| 328 |
+
## 🔐 Segurança
|
| 329 |
+
|
| 330 |
+
- ✅ Tasks rodando com user `system_auto_monitor`
|
| 331 |
+
- ✅ Rate limiting configurado para APIs externas
|
| 332 |
+
- ✅ Logs estruturados com rastreabilidade completa
|
| 333 |
+
- ✅ Retry automático com backoff exponencial
|
| 334 |
+
- ✅ Timeout configurado para evitar tasks travadas
|
| 335 |
+
|
| 336 |
+
## 📝 Próximos Passos
|
| 337 |
+
|
| 338 |
+
1. **Aprendizado Automático**: Treinar modelos ML com dados coletados
|
| 339 |
+
2. **Notificações**: Alertas quando anomalias críticas são encontradas
|
| 340 |
+
3. **Dashboard Analytics**: Visualização de descobertas em tempo real
|
| 341 |
+
4. **Watchlist Dinâmica**: Atualização automática de fornecedores suspeitos
|
| 342 |
+
5. **Cross-referência**: Integração com outros sistemas de fiscalização
|
| 343 |
+
|
| 344 |
+
## 📚 Referências
|
| 345 |
+
|
| 346 |
+
- [Documentação Celery](https://docs.celeryq.dev/)
|
| 347 |
+
- [Portal da Transparência API](https://api.portaldatransparencia.gov.br/swagger-ui.html)
|
| 348 |
+
- [Supabase Python Client](https://supabase.com/docs/reference/python)
|
| 349 |
+
|
| 350 |
+
---
|
| 351 |
+
|
| 352 |
+
**Status**: ✅ Sistema operacional e pronto para produção
|
| 353 |
+
**Última atualização**: 2025-10-07 18:11:37 (America/Sao_Paulo)
|
| 354 |
+
**Autor**: Anderson Henrique da Silva
|