diff --git a/docs/AGENTE_MONITOR_SKILLS.md b/docs/AGENTE_MONITOR_SKILLS.md new file mode 100644 index 0000000..b16e104 --- /dev/null +++ b/docs/AGENTE_MONITOR_SKILLS.md @@ -0,0 +1,41 @@ +# Agente: Monitor de Skills + +## Objetivo +Verificar as skills mais executadas nos últimos 7 dias e gerar um resumo com recomendações. + +## Passos + +1. **Consultar execuções recentes** + - Buscar em `/api/skills` todas as skills ativas do tenant + - Para cada skill, buscar `/api/skills/:id/executions?limit=50` + - Filtrar execuções dos últimos 7 dias + +2. **Analisar padrões** + - Contar total de execuções por skill + - Identificar taxa de sucesso (status = "success" / total) + - Destacar skills com taxa de falha > 20% + +3. **Gerar relatório** + - Listar top 5 skills mais executadas + - Alertar skills com problemas + - Sugerir skills candidatas a automação (executadas 3+ vezes por dia) + +## Saída esperada + +``` +## Relatório de Skills — últimos 7 dias + +### Top 5 mais usadas +1. [nome] — X execuções (Y% sucesso) +... + +### Atenção +- [skill] com taxa de falha de Z% + +### Candidatas ao OpenClaw +- [skill] — média de N exec/dia +``` + +## Parâmetros +- `tenant_id` — filtro de tenant (opcional) +- `dias` — janela de análise (padrão: 7) diff --git a/docs/INDICE_PLANEJAMENTO.md b/docs/INDICE_PLANEJAMENTO.md new file mode 100644 index 0000000..f43b5d2 --- /dev/null +++ b/docs/INDICE_PLANEJAMENTO.md @@ -0,0 +1,240 @@ +# Índice: PLANEJAMENTO ESTRATÉGICO ARCÁDIA AGENTIC SUITE + +**Documento:** `/home/ubuntu/# PLANEJAMENTO ESTRATÉGICO ARCÁDIA.txt` +**Versão:** 1.0 — Março 2026 +**Estado:** Pronto para Implementação + +--- + +## 📑 ESTRUTURA DO DOCUMENTO + +### 1. **Executive Summary** (Seção 1) +- Visão: ERP tradicional → **Sistema Agêntico Orientado a Objetos** +- 5 decisões arquiteturais críticas (MiroFlow, OpenClaw, Superset, Skills POO, Automações) + +### 2. **Arquitetura de Alto Nível** (Seção 2) +``` +Interface Unificada (Chat + Dev Center + OpenClaw + BI) + ↓ +Orquestradores (Manus + Blackboard + Automation Fabric) + ↓ +Motores Especializados Embutidos (MiroFlow + OpenClaw + Skill Engine) + ↓ +Infraestrutura (Knowledge Graph + PostgreSQL + Ollama/DeepSeek) +``` + +### 3. **Componentes Embutidos** (Seção 3+) + +| Componente | Status | Local | Propósito | +|-----------|--------|-------|----------| +| **MiroFlow** | ✅ | `server/modules/miroflow/` | Motor científico, benchmarks, análise estatística | +| **OpenClaw** | 🔄 | `server/modules/openclaw/` + `client/src/components/openclaw/` | Detecção padrões, sugestão proativa, skills emergentes | +| **Skills Engine** | ✅ | `server/skills/` | POO: herança, composição, polimorfismo, versionamento | +| **Automation Fabric** | ⏳ | `server/modules/automation/` | Runtime unificado: Workflow, Rule, Agent, Schedule, Event | +| **Dev Center** | ⏳ | `client/src/pages/DevCenter.tsx` | Design → Assemble → Deploy de agentes | +| **Superset Integration** | ⏳ | `server/modules/superset/` | BI visual + MiroFlow bridge | + +### 4. **Skills Engine POO** (Seção 4) +- ✅ Herança: `extends`, `isA` +- ✅ Composição: `dependencies`, `requires` +- ✅ Polimorfismo: `useMiroFlow`, `autoApprove` +- ✅ Versionamento Git-like (createVersion, listVersions, rollback, fork, diff) +- ✅ Marketplace / Biblioteca (import de skills públicas) + +### 5. **Automation Fabric Unificada** (Seção 6) +- Runtime com suporte: Workflow, Rule, Agent, Schedule, Event +- Trigger-based (webhook, database, schedule, event) +- Integração com Blackboard para codegen + +### 6. **Dev Center Completo** (Seção 8) +- **Design Studio**: UML, Visual, Markdown +- **Assemble Line**: Integração com Blackboard +- **Orchestrate Center**: Deploy, monitoramento +- **Galeria de Agentes**: Marketplace interno + +### 7. **Infraestrutura** (Seção 9) +- PostgreSQL 16 + pgvector +- Neo4j (Knowledge Graph) +- Ollama (LLMs locais: deepseek-r1:32b/70b, llama3.1:8b/70b) +- Apache Superset (BI visual) + +--- + +## 🗺️ ROADMAP E STATUS + +### ✅ Fase 1: Fundação (Semanas 1-2) +**Status: CONCLUÍDA (2026-03-25)** +- Submodules MiroFlow + OpenClaw +- Tabelas skills, skill_executions +- Neo4j no Docker +- ReferenceParser/Resolver +- Superset + Ollama + +**Entregável:** Infraestrutura base ✅ + +--- + +### ✅ Fase 2: Skills Engine (Semanas 3-4) +**Status: CONCLUÍDA (25/03/2026 - 15:04)** +- SkillEngine com herança/composição +- API REST CRUD + execução + histórico +- Editor Monaco (tabs Geral/Body/Params) +- Versionamento Git-like (VersionManager) +- Skill Marketplace / Biblioteca + +**Entregável:** Skills criáveis, versionáveis, executáveis ✅ + +--- + +### ✅ Fase 3: MiroFlow Embutido (Semanas 5-6) +**Status: CONCLUÍDA PARCIAL (25/03/2026 - 15:04)** + +**Implementado:** +- Adapt MiroFlow para Ollama local (llama3.2:3b / deepseek-r1:14b) +- Containerização em docker-compose.prod.yml +- Agentes especializados (Statistician, Auditor, Researcher) +- Proxy Node.js: `/api/miroflow/analyze` +- UI MiroFlowControl (tab Científico em /insights) + +**Pendente:** +- [ ] MiroFlowBridge para Superset +- [ ] Integração com Arcádia Audit (imutabilidade) +- [ ] Dashboard de benchmarks no Dev Center +- [ ] **Tool SQL via Skills** (skill `db_query` como MCP tool) + +**Entregável:** Análises científicas (ETA completo: 08/04/2026) + +--- + +### 🔄 Fase 4: OpenClaw Embutido (Semanas 7-8) +**Status: SPRINT 1 COMPLETO (26/03/2026) | Sprints 2-3 Em Progresso** + +#### ✅ Sprint 1: Backend (COMPLETO - 26/03) +- [x] PatternDetector.ts — detecção (3+ em 30d), confiança, Neo4j +- [x] OpenClawEngine.ts — orquestração, sugestões, scheduler, Socket.IO +- [x] SkillEmergence.ts — Blackboard codegen, validação, DRAFT storage +- [x] routes.ts — 10 endpoints REST +- [x] arcadia.config.yaml — pattern detection, suggestions, emergence + +#### ⏳ Sprint 2: Frontend (PRÓXIMO - 28-29/03) +- [ ] OpenClawWidget.tsx — widget flutuante de sugestão +- [ ] SkillSuggestion.tsx — modal de sugestão +- [ ] useAgentEmergence.ts — hook de lógica +- [ ] Integração em App.tsx (layout principal) + +#### ⏳ Sprint 3: Config + Testes (30-31/03) +- [ ] Schema database (detectedPatterns, skillSuggestions) +- [ ] Migration SQL (migrations/0004_openclaw_tables.sql) +- [ ] Testes unitários +- [ ] Documentação + +**Fluxo:** Padrão → Detector → Engine → Sugestão → Widget → User → Blackboard → SkillEmergence → DRAFT → Dev Center → Publicada + +**Entregável:** Skills emergentes (ETA: 08/04/2026) + +--- + +### ⏳ Fase 5: Automation Fabric (Semanas 9-10) +**Status: PENDENTE** +- [ ] Unificar XOS/Automations + Central /automations +- [ ] 4 runtimes: Workflow, Rule, Agent, Schedule, Event +- [ ] UI única no Dev Center +- [ ] Migração dados existentes +- [ ] Testes carga/segurança + +**Entregável:** Automações unificadas + +--- + +### ⏳ Fase 6: Dev Center Completo (Semanas 11-12) +**Status: PENDENTE** +- [ ] Design Studio (UML, Visual, Markdown) +- [ ] Assemble Line (Blackboard integration) +- [ ] Orchestrate Center (deploy, monitoramento) +- [ ] Galeria de Agentes (marketplace interno) +- [ ] Documentação e treinamento + +**Entregável:** Sistema completo operacional + +--- + +## 🎯 DECISÕES CRÍTICAS (RESUMO) + +| Decisão | Escolha | Justificativa | +|---------|---------|---------------| +| **MiroFlow** | **EMBUTIR** | Motor científico nativo, benchmarks, verificação multi-camada | +| **OpenClaw** | **EMBUTIR** | Widget interno, detecção contextual no Arcádia | +| **Superset** | **INTEGRAR** | BI visual mantido, bridge para MiroFlow | +| **Skills** | **POO** | Herança, composição, polimorfismo para reuso | +| **Automações** | **UNIFICAR** | Runtime único, múltiplos orquestradores | +| **Dev Center** | **FÁBRICA** | Design → Assemble → Deploy de agentes | +| **Multi-tenant** | **HIERARQUIA** | System → Tenant → Company → User skills | + +--- + +## 📋 PRÓXIMO PASSO + +### **Fase 4 Sprint 2: OpenClaw Frontend** +**ETA: 28-29/03/2026** + +A Fase 4 Sprint 1 (backend) foi concluída em 26/03. Agora entrar na **Sprint 2 do frontend**, que consiste em: + +#### Tarefas Sprint 2: +1. **OpenClawWidget.tsx** — Widget flutuante que: + - Escuta eventos de sugestões via Socket.IO + - Mostra notificação "Detectei padrão!" + - Abre SkillSuggestion modal ao ser clicado + +2. **SkillSuggestion.tsx** — Modal que: + - Exibe padrão detectado (frequência, confiança) + - Preview do código da skill sugerida (gerado por Blackboard) + - Botões: Aprovar (→ DRAFT em Dev Center) ou Rejeitar + +3. **useAgentEmergence.ts** — Hook que: + - Conecta a Socket.IO `/api/openclaw` events + - Gerencia estado de sugestões + - Sincroniza com OpenClawEngine backend + +4. **Integração em App.tsx**: + - Importar OpenClawWidget + - Renderizar no layout principal (canto inferior direito) + - Garantir que não bloqueia interação com página + +#### Localização dos arquivos: +``` +client/src/ +├── components/ +│ └── openclaw/ +│ ├── OpenClawWidget.tsx ← NOVO +│ ├── SkillSuggestion.tsx ← NOVO +│ └── ... +├── hooks/ +│ └── useAgentEmergence.ts ← NOVO +└── App.tsx ← MODIFICAR (integração) +``` + +#### Integração com backend já pronto: +- PatternDetector.ts emite eventos via Socket.IO +- OpenClawEngine.ts orquestra sugestões +- SkillEmergence.ts gera código via Blackboard +- Todas as rotas REST já existem + +**Próximo passo após Sprint 2:** Sprint 3 (Config + Testes), depois Fase 5 (Automation Fabric). + +--- + +## 🔗 LINKS ESSENCIAIS + +| Recurso | URL | +|---------|-----| +| **MiroFlow Docs** | https://github.com/MiroMindAI/MiroFlow/tree/main/docs | +| **MiroFlow Paper** | https://arxiv.org/abs/2602.22808 | +| **OpenClaw README** | https://github.com/miaoxworld/OpenClawInstaller/blob/main/README.md | +| **Superset Docs** | https://superset.apache.org/docs/intro | +| **Neo4j Docs** | https://neo4j.com/docs/ | +| **Ollama Docs** | https://github.com/ollama/ollama/blob/main/README.md | + +--- + +**Pronto para começar Fase 4 Sprint 2?** + diff --git a/docs/PLANO_IMPLEMENTACAO_AGENTIC.md b/docs/PLANO_IMPLEMENTACAO_AGENTIC.md new file mode 100644 index 0000000..f9fc22e --- /dev/null +++ b/docs/PLANO_IMPLEMENTACAO_AGENTIC.md @@ -0,0 +1,313 @@ +# PLANO DE IMPLEMENTAÇÃO: ARCÁDIA AGENTIC SUITE +**Versão:** 1.0 | **Baseado em:** Planejamento Estratégico Arcádia v1.0 (Março 2026) +**Rastreamento:** Ações marcadas com `[DATA | HORA | AUTOR | DETALHE]` + +--- + +## LEGENDA DE STATUS + +``` +[ ] Pendente +[~] Em andamento +[x] Concluído +[!] Bloqueado / Atenção +[?] Requer decisão antes de executar +``` + +--- + +## ALERTAS DE CONFLITO COM SISTEMA EXISTENTE + +> Itens marcados com **(CONFLITO POTENCIAL)** podem sobrescrever ou interferir +> com configurações já existentes no Arcádia. CONFIRMAR antes de executar. + +| Item | Conflito | Observação | +|------|----------|------------| +| `docker-compose.yml` | **(CONFLITO POTENCIAL)** | Pode já existir com serviços configurados | +| Apache Superset | **(CONFLITO POTENCIAL)** | RLS e dashboards já configurados — nova instância pode perder dados | +| Tabelas `skills`, `automations` | **(CONFLITO POTENCIAL)** | Verificar se já existem no schema atual | +| XOS/Automations | **(CONFLITO POTENCIAL)** | Unificação na Fase 5 altera o runtime existente | +| `/automations` (Central) | **(CONFLITO POTENCIAL)** | Será migrado/substituído na Fase 5 | + +--- + +## FASE 1 — FUNDAÇÃO (Semanas 1-2) +**Entregável:** Infraestrutura base funcionando + +### 1.1 Submodules / Clone + +- [ ] Clonar MiroFlow como submodule em `server/modules/miroflow/` + ```bash + git submodule add https://github.com/MiroMindAI/MiroFlow.git server/modules/miroflow + ``` + +- [ ] Clonar OpenClaw como submodule em `server/modules/openclaw/` + ```bash + git submodule add https://github.com/miaoxworld/OpenClawInstaller.git server/modules/openclaw + ``` + +- [ ] Inicializar submodules + ```bash + git submodule update --init --recursive + ``` + +### 1.2 Banco de Dados — Novas Tabelas + +> **(CONFLITO POTENCIAL)** — Verificar se tabelas já existem antes de criar + +- [ ] Criar tabela `skills` no PostgreSQL +- [ ] Criar tabela `automations` no PostgreSQL +- [ ] Criar tabela `skill_executions` no PostgreSQL +- [ ] Criar migration e executar `npm run db:migrate` + +### 1.3 Knowledge Graph (Neo4j) — Novos Nós + +- [ ] Estender KG com nó: `Skill` +- [ ] Estender KG com nó: `Automation` +- [ ] Estender KG com nó: `Execution` + +### 1.4 Reference System + +- [ ] Implementar `ReferenceParser` — `server/modules/skills/ReferenceParser.ts` +- [ ] Implementar `ReferenceResolver` — `server/modules/skills/ReferenceResolver.ts` + +### 1.5 Docker Compose / Infraestrutura + +> **(CONFLITO POTENCIAL)** — `docker-compose.yml` pode já existir. +> Confirmar com João antes de sobrescrever. + +- [?] Verificar se `docker-compose.yml` já existe no projeto +- [?] Se existir: mesclar serviços (Neo4j, Ollama, Superset) sem sobrescrever configs atuais +- [ ] Garantir serviços no compose: PostgreSQL, Neo4j, Ollama, Superset, Arcádia Suite + +--- + +## FASE 2 — SKILLS ENGINE (Semanas 3-4) +**Entregável:** Skills criáveis e executáveis + +### 2.1 Backend — Skill Engine + +- [ ] Implementar `SkillEngine.ts` — `server/modules/skills/SkillEngine.ts` + - Suporte a herança (`extends`) + - Suporte a composição (`dependencies`) + - Suporte a polimorfismo (`execute()`) +- [ ] Implementar `SkillRepository.ts` — CRUD de skills no banco + +### 2.2 Sistema de Namespaces + +- [ ] Hierarquia: `system` → `tenant` → `company` → `user` +- [ ] Resolver prioridade e herança entre namespaces + +### 2.3 Frontend — Editor de Skills + +- [ ] Criar componente `SkillEditor.tsx` — `client/src/components/skills/` + - Modo Visual + - Modo Code (TypeScript) + - Modo Markdown +- [ ] Criar `ReferenceParser.ts` no frontend com autocomplete de `/` +- [ ] Criar `SkillMarketplace.tsx` — descoberta de skills disponíveis + +### 2.4 Versionamento de Skills + +- [ ] Implementar versionamento Git-like para skills (histórico de versões) + +--- + +## FASE 3 — MIROFLOW EMBUTIDO (Semanas 5-6) +**Entregável:** Análises científicas disponíveis + +### 3.1 Configuração MiroFlow para Ollama Local + +- [ ] Criar `config/arcadia_agents.yaml` em `server/modules/miroflow/config/` + - `provider: ollama` + - `base_url: http://localhost:11434` + - Modelos: `deepseek-r1:32b` (default), `deepseek-r1:70b` (reasoning), `llama3.1:8b` (fast) +- [ ] Instalar dependências Python: `pip install -r requirements.txt` + +### 3.2 Agentes Especializados + +- [ ] Configurar agente `Arcádia Statistician` (deepseek-r1:32b) + - Tools: arcadia_sql_query, pandas_analysis, scipy_stats, visualization_generator +- [ ] Configurar agente `Arcádia Fiscal Auditor` (deepseek-r1:70b) + - Tools: nfe_validator, sped_generator, tax_calculator, risk_scorer +- [ ] Configurar agente `Arcádia Researcher` (llama3.1:70b) + - Tools: knowledge_graph_query, document_search, trend_analyzer + +### 3.3 Bridge Superset → MiroFlow + +> **(CONFLITO POTENCIAL)** — Superset já está em produção com RLS configurado. +> A bridge adiciona funcionalidade nova (Modo Científico), não deve quebrar configs existentes. +> Confirmar antes de modificar qualquer arquivo do Superset atual. + +- [?] Verificar se a instância atual do Superset suporta custom viz (`BaseViz`) +- [ ] Criar `MiroFlowBridge.ts` — `server/modules/superset/MiroFlowBridge.ts` +- [ ] Criar `miroflow_scientific.py` — viz customizada no Superset + - Endpoint: `POST /api/miroflow/analyze` +- [ ] Criar `MiroFlowControl.tsx` — toggle "Modo Científico" no frontend + - `client/src/modules/superset-bridge/MiroFlowControl.tsx` + +### 3.4 Integração com Arcádia Audit + +- [ ] Garantir que execuções MiroFlow sejam registradas com `immutable_logging: true` +- [ ] Registrar proveniência no Knowledge Graph (dataset versions, analysis lineage, model registry) + +### 3.5 Modelos Ollama + +- [ ] Baixar modelo: `deepseek-r1:32b` +- [ ] Baixar modelo: `deepseek-r1:70b` +- [ ] Baixar modelo: `llama3.1:8b` +- [ ] Baixar modelo: `llama3.1:70b` + +### 3.6 Dev Center — Dashboard de Benchmarks + +- [ ] Criar dashboard de benchmarks MiroFlow no Dev Center (GAIA, HLE, FutureX) + +--- + +## FASE 4 — OPENCLAW EMBUTIDO (Semanas 7-8) +**Entregável:** Skills emergentes funcionando + +### 4.1 Backend — Pattern Detection + +- [ ] Implementar `PatternDetector.ts` — `server/modules/openclaw/PatternDetector.ts` + - `min_occurrences: 3` | `time_window_days: 30` | `confidence_threshold: 0.8` +- [ ] Implementar `SkillEmergence.ts` — criação de skills emergentes como DRAFT +- [ ] Implementar `OpenClawEngine.ts` — motor de sugestões + +### 4.2 Frontend — Widget + +- [ ] Criar `OpenClawWidget.tsx` — widget flutuante + - `client/src/modules/openclaw/OpenClawWidget.tsx` +- [ ] Criar `PatternDetector.ts` frontend — hook de detecção +- [ ] Criar `SkillSuggestion.tsx` — modal de sugestão ao usuário +- [ ] Criar `useAgentEmergence.ts` — lógica de emergência + +### 4.3 Configuração OpenClaw Arcádia + +- [ ] Criar `config/arcadia.yaml` em `server/modules/openclaw/config/` + - `tenant_aware: true` + - `auto_suggest: false` (sempre pedir confirmação) + - `create_as_draft: true` (requer aprovação) + - `auto_publish: false` + - `notify_admins: true` +- [ ] Instalar dependências Node: `cd server/modules/openclaw && npm install` + +### 4.4 Fluxo Completo de Emergência + +- [ ] Implementar fluxo: Padrão detectado → Skill DRAFT criado → Dev Center para aprovação +- [ ] Integrar com Blackboard para codegen automático da skill emergente +- [ ] Painel de configuração de sugestões por tenant + +--- + +## FASE 5 — AUTOMATION FABRIC (Semanas 9-10) +**Entregável:** Automações unificadas + +> **(CONFLITO POTENCIAL)** — Esta fase unifica XOS/Automations e `/automations` Central. +> São sistemas ATIVOS no Arcádia. Migração de dados necessária. +> Confirmar estratégia de migração com João antes de iniciar. + +### 5.1 Backend — Runtimes Unificados + +- [ ] Implementar `AutomationEngine.ts` — `server/modules/automations/AutomationEngine.ts` +- [ ] Implementar runtime `WorkflowEngine.ts` (BPMN, processos longos, aprovações) +- [ ] Implementar runtime `RuleEngine.ts` (IFTTT simples, rápido) +- [ ] Implementar runtime `AgentExecutor.ts` (Manus/OpenClaw, IA adaptativa) +- [ ] Implementar runtime `ScheduleEngine.ts` (Cron, recorrente) +- [ ] (Opcional) Implementar runtime `EventEngine.ts` (Webhook, real-time) + +### 5.2 Modelo Unificado de Automação + +- [ ] Definir schema `Automation` com campo `runtime` polimórfico + - tipos: `workflow | rule | agent | scheduled | event` +- [ ] Implementar `auditHash` para imutabilidade + +### 5.3 Migração de Dados + +- [ ] Mapear automações existentes em XOS para novo modelo +- [ ] Mapear automações existentes em `/automations` Central para novo modelo +- [ ] Executar migração sem downtime + +### 5.4 Frontend — UI Única + +- [ ] Criar `AutomationCenter.tsx` — `client/src/modules/automations/AutomationCenter.tsx` +- [ ] Criar `RuleDesigner.tsx` — designer visual de regras +- [ ] Criar `WorkflowDesigner.tsx` — designer BPMN +- [ ] Criar `AgentDesigner.tsx` — designer de agentes IA +- [ ] Criar `AutomationList.tsx` — listagem unificada + +### 5.5 Testes + +- [ ] Testes de carga nas automações unificadas +- [ ] Testes de segurança (permissões por tenant/company/user) + +--- + +## FASE 6 — DEV CENTER COMPLETO (Semanas 11-12) +**Entregável:** Sistema completo operacional + +### 6.1 Design Studio + +- [ ] Criar `DesignStudio.tsx` — `client/src/modules/devcenter/DesignStudio.tsx` + - Modo UML Diagram (classes, herança, relações) + - Modo Visual Flow (drag-drop nodes) + - Modo Markdown Spec (linguagem natural) + - Modo Code Editor (TypeScript + IntelliSense) + +### 6.2 Assemble Line + +- [ ] Criar `AssembleLine.tsx` — `client/src/modules/devcenter/AssembleLine.tsx` + - Composition Panel (available skills → selected skills) + - Flow Diagram automático + - Botões: Generate Code | Preview | Test | Deploy +- [ ] Integrar com Blackboard (GeneratorAgent, ValidatorAgent, ExecutorAgent) + +### 6.3 Orchestrate Center + +- [ ] Criar `OrchestrateCenter.tsx` — `client/src/modules/devcenter/OrchestrateCenter.tsx` + - Deploy de agentes + - Versionamento + - Monitoramento de execuções + +### 6.4 Galeria de Agentes + +- [ ] Criar marketplace interno de agentes (descoberta, instalação por tenant) + +### 6.5 Finalização + +- [ ] Documentação técnica dos componentes criados +- [ ] Treinamento / onboarding interno +- [ ] `npm run test:miroflow` +- [ ] `npm run test:openclaw` +- [ ] `npm run test:integration` + +--- + +## REGISTRO DE AÇÕES EXECUTADAS + +> Formato: `[AAAA-MM-DD | HH:MM | AUTOR | O que foi feito e em qual arquivo/componente]` + +| # | Data | Hora | Autor | Ação | Fase | +|---|------|------|-------|------|------| +| 1 | 2026-03-24 | — | João | Adicionado serviço `neo4j` (profile: `kg`) ao `docker-compose.yml` + volumes `neo4j_data` e `neo4j_logs` | Fase 1 | +| 2 | 2026-03-24 | — | João | Adicionado serviço `neo4j` (profile: `kg`) ao `docker-compose.prod.yml` + volumes `neo4j_data` e `neo4j_logs` | Fase 1 | +| 3 | 2026-03-24 | — | João | Adicionadas tabelas `arcadia_skills` (modelo POO) e `skill_executions` ao `shared/schema.ts` — `xosSkillRegistry` preservado | Fase 1 + 2 | +| 4 | 2026-03-24 | — | João | Criada migration `0003_arcadia_skills.sql` — cria tabelas `arcadia_skills` e `skill_executions` com índices | Fase 1 | + +--- + +## DECISÕES ARQUITETURAIS REGISTRADAS + +| Componente | Decisão | Status | +|------------|---------|--------| +| MiroFlow | EMBUTIR como submodule em `server/modules/miroflow/` | Pendente | +| OpenClaw | EMBUTIR como submodule em `server/modules/openclaw/` | Pendente | +| Apache Superset | INTEGRAR externamente com bridge MiroFlow | Pendente | +| Skills | Modelo POO (herança, composição, polimorfismo) | Pendente | +| Automações | Unificar XOS + Central em runtime único | Pendente | +| Dev Center | Fábrica: Design → Assemble → Deploy | Pendente | +| Multi-tenant | Hierarquia: System → Tenant → Company → User | Pendente | + +--- + +*Documento gerado em: 2026-03-24 | Baseado no Planejamento Estratégico Arcádia v1.0* diff --git a/docs/PLANO_METASET.md b/docs/PLANO_METASET.md new file mode 100644 index 0000000..02ad804 --- /dev/null +++ b/docs/PLANO_METASET.md @@ -0,0 +1,617 @@ +Plano de Implementação: MetaSet no ArcadiaSuite (Atualizado - 07/04/2026) +📊 Visão Geral da Arquitetura Atual +┌─────────────────────────────────────────────────────────────────────────┐ +│ ARCADIA KERNEL (5001) │ +│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────────┐ │ +│ │ Dashboard │ │ Process │ │ Health │ │ LogAggregator │ │ +│ │ (Web UI) │ │ Manager │ │ Monitor │ │ │ │ +│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ └─────────────────┘ │ +│ │ │ │ │ +│ └────────────────┴────────────────┘ │ +│ │ │ +│ ┌───────────┴───────────┐ │ +│ │ Service Registry │ │ +│ │ (services.json) │ │ +│ └───────────┬───────────┘ │ +│ │ │ +│ ┌─────────────────────┼─────────────────────┐ │ +│ │ │ │ │ +│ ┌──┴──┐ ┌──┴──┐ ┌──┴──┐ │ +│ │9001 │ │9002 │ │9003 │ + NOVO: 8004 │ +│ │Comm │ │Core │ │Worker│ + NOVO: 8100 │ +│ │Whats│ │ API │ │Queue │ (MetaSet) │ +│ └─────┘ └─────┘ └─────┘ │ +│ │ +│ 🆕 SERVIÇOS BI: │ +│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ +│ │ 8004 │ │ 8100 │ │ 8200 │ │ +│ │ BI-API │──│ MetaSet │ │ FDB-Bridge │ │ +│ │ (Node.js) │ │ (Python) │ │ (Python) │ │ +│ │ Gateway │ │ Superset │ │ Firebird │ │ +│ └─────────────┘ └─────────────┘ └─────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────────┘ + │ + ┌──────────┴──────────┐ + │ PostgreSQL 16 │ + │ ┌───────────────┐ │ + │ │ arcadia_db │ │ + │ │ metaset_db │ │ ✅ Schema criado e migrado + │ └───────────────┘ │ + └─────────────────────┘ + +🔧 Configuração dos Serviços (services.json) +{ + "services": [ + { + "id": "communication", + "name": "Communication Service", + "type": "node", + "command": "node", + "args": ["server/communication/index.js"], + "cwd": ".", + "port": 9001, + "autoStart": true, + "healthCheck": { + "path": "/health", + "interval": 30000, + "timeout": 5000, + "retries": 3 + }, + "maxRestarts": 5 + }, + { + "id": "core-api", + "name": "Core API", + "type": "node", + "command": "node", + "args": ["server/core/index.js"], + "cwd": ".", + "port": 9002, + "autoStart": true, + "healthCheck": { + "path": "/health", + "interval": 30000, + "timeout": 5000, + "retries": 3 + }, + "maxRestarts": 5 + }, + { + "id": "bi-api", + "name": "BI API Gateway", + "type": "node", + "command": "node", + "args": ["server/bi/index.js"], + "cwd": ".", + "port": 8004, + "autoStart": true, + "env": { + "METASET_PORT": "8100", + "METASET_HOST": "127.0.0.1", + "FDB_BRIDGE_PORT": "8200" + }, + "healthCheck": { + "path": "/bi/health", + "interval": 30000, + "timeout": 5000, + "retries": 3 + }, + "maxRestarts": 5, + "description": "Gateway de BI com proxy para MetaSet e FDB-Bridge" + }, + { + "id": "metaset", + "name": "MetaSet BI", + "type": "python", + "command": "python", + "args": ["server/bi/metaset/run.py", "--port=8100", "--host=127.0.0.1"], + "cwd": ".", + "port": 8100, + "autoStart": false, + "env": { + "PYTHONPATH": "server/bi/metaset", + "FLASK_ENV": "production", + "SUPERSET_CONFIG_PATH": "server/bi/metaset/superset_config.py", + "SUPERSET_SECRET_KEY": "${SUPERSET_SECRET_KEY}" + }, + "healthCheck": { + "path": "/health", + "interval": 30000, + "timeout": 10000, + "retries": 3 + }, + "maxRestarts": 3, + "description": "Apache Superset rebrandado como MetaSet (Docker-managed)" + }, + { + "id": "fdb-bridge", + "name": "FDB Bridge", + "type": "python", + "command": "python", + "args": ["server/bi/fdb-bridge/main.py", "--port=8200"], + "cwd": ".", + "port": 8200, + "autoStart": false, + "env": { + "PYTHONPATH": "server/bi/fdb-bridge", + "FDB_HOST": "${FDB_HOST}", + "FDB_PORT": "${FDB_PORT:-3050}" + }, + "healthCheck": { + "path": "/health", + "interval": 60000, + "timeout": 5000, + "retries": 3 + }, + "maxRestarts": 3, + "description": "Conector Firebird para sincronização de dados (Docker-managed)" + } + ] +} + +🏗️ Estrutura de Diretórios Final +arcadiasuite/ +├── server/ +│ ├── kernel/ # ✅ Kernel finalizado +│ │ ├── core/ +│ │ │ ├── ProcessManager.ts # ✅ Suporta 'python' e 'node' +│ │ │ ├── HealthMonitor.ts +│ │ │ └── LogAggregator.ts +│ │ ├── dashboard/ # Dashboard Web UI (porta 5001) +│ │ ├── config/ +│ │ │ └── services.json # ✅ Configuração dos serviços +│ │ └── index.ts +│ │ +│ ├── bi/ # 🆕 MÓDULO BI COMPLETO +│ │ ├── index.ts # BI-API Gateway (porta 8004) +│ │ ├── routes/ +│ │ │ ├── query.ts # Queries nativas Drizzle +│ │ │ ├── export.ts # Exportação PDF/Word +│ │ │ └── sync.ts # Sincronização FDB +│ │ │ +│ │ ├── metaset/ # 🆕 METASET (Superset) +│ │ │ ├── run.py # Entry point Python +│ │ │ ├── superset_config.py # Configuração Arcadia +│ │ │ ├── security_manager.py # ArcadiaSecurityManager +│ │ │ ├── requirements.txt # Dependências Python +│ │ │ ├── Dockerfile # Multi-stage build +│ │ │ ├── init.sh # Container init script +│ │ │ ├── branding/ # 🎨 Assets MetaSet +│ │ │ │ ├── metaset-logo-horiz.png +│ │ │ │ ├── metaset-icon.png +│ │ │ │ ├── favicon-16x16.png +│ │ │ │ └── favicon-32x32.png +│ │ │ │ +│ │ │ └── superset-src/ # Fork Apache Superset 4.1.0 +│ │ │ ├── superset-frontend/ # ✅ Rebuild com branding MetaSet +│ │ │ │ └── src/ +│ │ │ │ ├── features/home/RightMenu.tsx # ✅ Textos atualizados +│ │ │ │ ├── components/ErrorMessage/OAuth2RedirectMessage.tsx +│ │ │ │ └── pages/... # ✅ Traduções atualizadas +│ │ │ │ +│ │ │ ├── superset/ +│ │ │ │ ├── config.py # ✅ APP_NAME = "MetaSet" +│ │ │ │ ├── constants.py # ✅ USER_AGENT = "MetaSet" +│ │ │ │ ├── cli/ +│ │ │ │ ├── templates/ # ✅ HTML templates atualizados +│ │ │ │ └── translations/ # ✅ Traduções en/pt_BR +│ │ │ └── ... +│ │ │ +│ │ └── fdb-bridge/ # 🆕 FIREBIRD CONNECTOR (skeleton) +│ │ ├── main.py # Serviço Python porta 8200 +│ │ ├── sync.py # Lógica de sincronização +│ │ ├── models.py # Modelos SQLAlchemy +│ │ └── requirements.txt +│ │ +│ └── ... (outros serviços) +│ +├── client/ +│ └── src/ +│ └── pages/ +│ └── bi/ # 🆕 FRONTEND BI +│ ├── index.tsx # Dashboard BI Arcadia +│ ├── metaset/ # Embed MetaSet +│ │ ├── Dashboard.tsx +│ │ ├── SQLLab.tsx +│ │ └── Explore.tsx +│ └── components/ +│ ├── QueryBuilder.tsx +│ ├── ExportButton.tsx +│ └── FDBSyncStatus.tsx +│ +└── branding/ # 🆕 ASSETS COMPARTILHADOS + ├── logos/ + │ ├── arcadia-suite-logo.svg + │ ├── arcadia-suite-logo-horiz.svg + │ ├── metaset-logo.svg + │ └── metaset-icon.svg + ├── colors/ + │ └── arcadia-palette.json + └── fonts/ + └── Inter-Variable.ttf + +🔐 Arquitetura de Segurança & Multi-tenancy +Fluxo de Autenticação +┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ +│ Cliente │────▶│ Arcadia │────▶│ BI-API │────▶│ MetaSet │ +│ (React) │ │ Login │ │ (8004) │ │ (8100) │ +└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ + │ │ + │ Headers: │ SET LOCAL + │ X-Tenant-ID: 123 │ app.current_tenant + │ X-User-Role: admin │ = 123; + │ Authorization: JWT │ + ▼ ▼ + ┌─────────────┐ ┌─────────────┐ + │ RLS Check │ │ PostgreSQL │ + │ Middleware │ │ (RLS) │ + └─────────────┘ └─────────────┘ + +ArcadiaSecurityManager (server/bi/metaset/security_manager.py) ✅ CORRIGIDO +""" +Security Manager integrado ao Arcadia Kernel +- Extrai tenant e usuário do token JWT +- Aplica RLS automaticamente +- Sincroniza roles com ArcadiaSuite +- Preserva comportamento padrão do Superset (chama super().before_request()) +""" +from superset.security import SupersetSecurityManager +from flask import g, request, current_app +from sqlalchemy import text +import jwt +import logging + +logger = logging.getLogger(__name__) + +class ArcadiaSecurityManager(SupersetSecurityManager): + ROLE_MAPPING = { + 'superadmin': 'Admin', + 'admin': 'Alpha', + 'analyst': 'Gamma', + 'viewer': 'Public', + } + + def before_request(self): + """Executado antes de cada requisição - preserva comportamento padrão""" + super().before_request() # ← CRÍTICO: preserva autenticação padrão + + auth_header = request.headers.get('Authorization', '') + if not auth_header.startswith('Bearer '): + return + + token = auth_header.replace('Bearer ', '') + + try: + payload = jwt.decode( + token, + current_app.config.get('SECRET_KEY', 'default-key'), + algorithms=['HS256'] + ) + + g.tenant_id = payload.get('tenant_id') + g.user_id = payload.get('sub') + g.user_role = payload.get('role', 'viewer') + g.user_email = payload.get('email') + + if g.tenant_id: + try: + from superset import db + db.session.execute( + text(f"SET LOCAL app.current_tenant = {g.tenant_id}") + ) + except Exception as e: + logger.warning(f"Erro ao aplicar RLS: {e}") + + except jwt.ExpiredSignatureError: + logger.warning("JWT token expirado") + except jwt.InvalidTokenError: + logger.warning("JWT token inválido") + except Exception as e: + logger.warning(f"Erro ao processar JWT: {e}") + +🐍 Código dos Serviços Python +1. MetaSet Entry Point (server/bi/metaset/run.py) +""" +MetaSet - Serviço Apache Superset integrado ao Arcadia Kernel +Porta: 8100 (Docker container) +Gunicorn: 2 workers, gthread, 120s timeout +""" + +import os +import sys +import logging +from pathlib import Path + +logging.basicConfig( + level=logging.INFO, + format='[MetaSet] %(levelname)s: %(message)s', + handlers=[logging.StreamHandler(sys.stdout)] +) +logger = logging.getLogger(__name__) + +def create_app(): + """Criar aplicação Flask do Superset com endpoints customizados""" + from superset import create_app as create_superset_app + from datetime import datetime + + app = create_superset_app() + + @app.route('/health') + def health_check(): + return {'status': 'healthy', 'service': 'metaset'}, 200 + + @app.route('/info') + def service_info(): + return { + 'name': 'MetaSet', + 'description': 'Business Intelligence by ArcadiaSuite', + 'version': app.config.get('VERSION_STRING', '4.1.0'), + 'features': ['sql_lab', 'dashboards', 'charts', 'rls', 'embedding'] + } + + return app + +# MetaSetApplication: custom Gunicorn app +# Config: 2 workers, gthread, 120s timeout, stdout/stderr logging + +2. BI-API Gateway (server/bi/index.ts) +""" + * BI-API Gateway + * Porta: 8004 + * Integra MetaSet (8100) e FDB-Bridge (8200) ao ArcadiaSuite + * Proxy manual usando módulo http nativo (bypass http-proxy-middleware ECONNRESET) +""" + +import express from 'express'; +import http from 'http'; + +const METASET_URL = `http://${process.env.METASET_HOST || 'metaset'}:${process.env.METASET_PORT || '8100'}`; + +// Manual proxy: http.request() com pathRewrite +// Solução para ECONNRESET com Gunicorn keepalive +// Health check agrega MetaSet + FDB-Bridge status + +🎨 Configuração de Branding (superset_config.py) +""" +Configuração do MetaSet (Superset) para ArcadiaSuite +""" + +import os +from pathlib import Path + +BASE_DIR = Path(__file__).parent.absolute() +SUPERSET_HOME = BASE_DIR / 'superset_home' + +# ========================================== +# BRANDING - ARCADIASUITE ✅ IMPLEMENTADO +# ========================================== + +APP_NAME = "MetaSet by Arcádia" +APP_ICON = "/static/assets/images/branding/metaset-logo-horiz.png" +LOGO_TARGET_PATH = "/" +LOGO_TOOLTIP = "MetaSet - Business Intelligence by ArcadiaSuite" + +# Favicons +FAVICONS = [ + {"href": "/static/assets/images/branding/favicon-16x16.png", "sizes": "16x16"}, + {"href": "/static/assets/images/branding/favicon-32x32.png", "sizes": "32x32"}, + {"href": "/static/assets/images/branding/apple-touch-icon.png", "sizes": "180x180"}, +] + +# Cores ArcadiaSuite +ARCADIA_PRIMARY = "#0ea5e9" # Azul celeste +ARCADIA_SECONDARY = "#10b981" # Verde +ARCADIA_ACCENT = "#f59e0b" # Laranja +ARCADIA_BG = "#f8fafc" # Background claro +ARCADIA_TEXT = "#1e293b" # Texto escuro + +# Desabilitar cache de arquivos estáticos +SEND_FILE_MAX_AGE_DEFAULT = 0 + +THEME_DEFAULT = { + "token": { + "brandAppName": "MetaSet", + "brandLogoAlt": "MetaSet by ArcadiaSuite", + "brandLogoUrl": "/static/assets/images/branding/metaset-logo-horiz.png", + "brandLogoMargin": "16px 0", + "brandLogoHeight": "28px", + "colorPrimary": ARCADIA_PRIMARY, + "colorLink": ARCADIA_PRIMARY, + "colorSuccess": ARCADIA_SECONDARY, + "colorWarning": ARCADIA_ACCENT, + "colorError": "#ef4444", + "colorInfo": "#3b82f6", + "colorBgLayout": ARCADIA_BG, + "colorBgContainer": "#ffffff", + "colorText": ARCADIA_TEXT, + "colorTextSecondary": "#64748b", + "fontFamily": "Inter, -apple-system, BlinkMacSystemFont, sans-serif", + "fontSize": 14, + "borderRadius": 8, + "borderRadiusLG": 12, + "boxShadow": "0 1px 3px 0 rgba(0, 0, 0, 0.1)", + "boxShadowSecondary": "0 4px 6px -1px rgba(0, 0, 0, 0.1)", + }, + "algorithm": "default", +} + +THEME_DARK = { ... } # Tema escuro + +# ========================================== +# SEGURANÇA & MULTI-TENANCY +# ========================================== + +from security_manager import ArcadiaSecurityManager +CUSTOM_SECURITY_MANAGER = ArcadiaSecurityManager # ✅ Funcionando + +AUTH_TYPE = 1 +WTF_CSRF_ENABLED = True +WTF_CSRF_TIME_LIMIT = 3600 +SESSION_COOKIE_HTTPONLY = True +SESSION_COOKIE_SECURE = False # True em produção com HTTPS +SESSION_COOKIE_SAMESITE = "Lax" + +# ========================================== +# BANCO DE DADOS +# ========================================== + +SQLALCHEMY_DATABASE_URI = os.getenv( + 'DATABASE_URL', + 'postgresql://arcadia:arcadia123@db:5432/metaset_db' +) + +SQLALCHEMY_ENGINE_OPTIONS = { + "connect_args": {"options": "-c row_security=on"}, + "pool_pre_ping": True, + "pool_recycle": 300, +} + +# ========================================== +# FEATURE FLAGS +# ========================================== + +FEATURE_FLAGS = { + "EMBEDDED_SUPERSET": True, + "EMBEDDABLE_CHARTS": True, + "DASHBOARD_RBAC": True, + "SQLLAB_BACKEND_PERSISTENCE": True, + "DASHBOARD_VIRTUALIZATION": True, + "DRILL_BY": True, + "CSS_TEMPLATES": True, + "ENABLE_JAVASCRIPT_CONTROLS": False, + "ALERT_REPORTS": False, +} + +📋 Roadmap de Implementação (8 Semanas) +Semana Foco Entregáveis +1 Setup MetaSet Fork Superset, branding básico (logo, cores), superset_config.py +2 Integração Kernel services.json atualizado, BI-API gateway, proxy funcionando +3 Segurança ArcadiaSecurityManager, JWT validation, injeção de headers +4 Multi-tenancy RLS PostgreSQL, isolamento de datasources, testes de segurança +5 FDB Bridge Serviço Python porta 8200, conexão Firebird, testes de sync +6 Sync Engine Sincronização incremental, agendamento, resolução de conflitos +7 Frontend Páginas BI no React, embed de dashboards, SQL Lab integrado +8 Go-Live Testes E2E, documentação, otimização de performance + +✅ Checklist de Implementação - STATUS ATUAL +Semana 1-2: Setup e Integração ✅ CONCLUÍDO +✅ Clonar superset (4.1.0rc4) para server/bi/metaset/superset-src +✅ Criar superset_config.py com branding ArcadiaSuite (APP_NAME, cores, tema) +✅ Rebuild do frontend React com logos MetaSet (COMPLETO - 07/04/2026) + - Substituição de textos: "Superset" → "MetaSet" em todo codebase + - Traduções atualizadas: en/LC_MESSAGES/messages.po, pt_BR/LC_MESSAGES/messages.po + - Arquivos fonte atualizados: RightMenu.tsx, OAuth2RedirectMessage.tsx, + SliceHeaderControls, HeaderActionsDropdown, AnchorLink, EmbeddedModal, + useExploreAdditionalActionsMenu + - Templates HTML: basic.html, public_welcome.html, 404.html, 500.html + - Config Python: config.py (APP_NAME), constants.py (USER_AGENT), cli/*.py + - Build webpack concluído com sucesso (429 warnings, 0 errors) + - Assets compilados com branding MetaSet incorporado +✅ Criar server/bi/metaset/run.py entry point (Gunicorn) +✅ Criar server/bi/metaset/init.sh container initialization +✅ Criar server/bi/index.ts BI-API gateway (proxy manual Node.js) +✅ Atualizar server/kernel/config/services.json (autoStart: false, Docker Discovery) +✅ Docker Compose: metaset + bi-api + redes configuradas +✅ Dockerfile multi-stage build com assets locais (não mais copiando de apache/superset:latest) +✅ Deploy: https://bi.onboardbi.com.br (MetaSet rodando com branding completo) +✅ Container antigo arcadia-prod-superset-1 removido +✅ Container metaset conectado à rede coolify para Traefik +✅ Banco de dados metaset_db migrado e inicializado +✅ Usuário admin criado (login: admin / senha: admin) +✅ BI-API Gateway proxy /bi/metaset funcionando (porta 8004) +✅ Health checks integrados (metaset + bi-api) +✅ requirements.txt corrigido (compatível apache-superset 4.1.0) +✅ extra_hosts configurado para resolver db → 10.0.10.2 (IPv4) + +Semana 3-4: Segurança 🔄 EM ANDAMENTO +✅ Implementar ArcadiaSecurityManager (CORRIGIDO - chama super().before_request()) +✅ Configurar JWT validation +🔄 Criar schema metaset no PostgreSQL (banco criado, migrações aplicadas) +☐ Configurar RLS em tabelas do arcadia_db +☐ Testar isolamento entre tenants + +Semana 5-6: FDB Bridge ⏳ PENDENTE +☐ Criar server/bi/fdb-bridge/main.py +☐ Implementar conexão Firebird (fdb library) +☐ Criar lógica de sincronização incremental +☐ Configurar agendador APScheduler +☐ Testar sync Matriz + 5 Filiais + +Semana 7-8: Frontend e Go-Live ⏳ PENDENTE +☐ Criar páginas BI no frontend React +☐ Implementar embed de dashboards MetaSet +☐ Criar componente de status de sincronização +☐ Testes E2E completos +☐ Documentação do módulo BI + +📝 Lições Aprendidas (07/04/2026) +1. Frontend rebuild obrigatório: Substituir arquivos estáticos PNG no Docker + não funciona porque os assets são compilados em bundles JS pelo webpack. + É necessário rebuildar o superset-frontend com npm run build. + +2. Dependências faltantes: O build pode falhar por pacotes não instalados: + @react-spring/web, global-box, currencyformatter.js. Instalar com + npm install --legacy-peer-deps. + +3. Security Manager: O ArcadiaSecurityManager DEVE chamar super().before_request() + no início do método para preservar o comportamento de autenticação padrão + do Flask-AppBuilder. Sem isso, o login falha com AttributeError: user. + +4. IPv6 vs IPv4: O hostname "db" resolve para IPv6 (fd20:a15a:c2d4::c) mas + o psycopg2 falha na autenticação via IPv6. Solução: mapear db → IP IPv4 + via extra_hosts no docker-compose.yml. + +5. Container antigo: Sempre verificar se há containers antigos com labels + do Traefik apontando para o mesmo domínio. Eles podem conflitar com + o novo container. + +6. Traefik discovery: O container DEVE estar na mesma rede Docker que o + Traefik (coolify) para ser descoberto automaticamente. + +💰 Custos Adicionais +Componente Especificação Custo Estimado +Memória extra +2GB para Python (MetaSet + FDB-Bridge) ~$20/mês +Storage PostgreSQL +10GB para metadata MetaSet ~$5/mês +CPU Processamento de sync FDB ~$15/mês +Total ~$40/mês + +🚀 Comandos de Deploy +# 1. Build da imagem Docker +cd /opt/arcadia_merged +docker compose build --no-cache metaset + +# 2. Recriar container com nova imagem +docker compose up -d --force-recreate metaset + +# 3. Verificar status +curl http://localhost:8100/health +curl https://bi.onboardbi.com.br/login/ | grep "" + +# 4. Logs +docker logs -f arcadia-dev-metaset-1 + +# 5. Migrar banco (se necessário) +docker exec -e FLASK_APP=superset \ + -e DATABASE_URL="postgresql://arcadia:arcadia123@10.0.10.2:5432/metaset_db" \ + arcadia-dev-metaset-1 superset db upgrade + +# 6. Inicializar +docker exec -e FLASK_APP=superset \ + -e DATABASE_URL="postgresql://arcadia:arcadia123@10.0.10.2:5432/metaset_db" \ + arcadia-dev-metaset-1 superset init + +📌 URLs de Acesso +Serviço URL Status +MetaSet UI https://bi.onboardbi.com.br ✅ Online com branding MetaSet +MetaSet Health http://localhost:8100/health ✅ OK +BI-API Gateway http://localhost:8004 ⚠️ Unhealthy (esperado - requer JWT) +Traefik Dashboard http://localhost:8080 ✅ Online + +🔧 Próximos Passos Prioritários +1. Configurar RLS (Row Level Security) no PostgreSQL para isolamento de tenants +2. Testar fluxo completo de autenticação com token JWT do Arcadia +3. Criar datasource de exemplo conectado ao arcadia_db +4. Implementar FDB Bridge (conector Firebird) +5. Criar páginas BI no frontend React +6. Configurar cache Redis para MetaSet