AgentStack
Browse Sign in
Browse Why AgentStack Sell Docs
Sign in
SKILL verified MIT Self-run

Ag 12 Sql Totvs Zeev

skill-andregusman-raiz-a-gusman-claude-ag-12-sql-totvs-zeev · by andregusman-raiz

Maquina especialista em dados Raiz: data-engine API canonical (/v1/kpis/*, /reports/<panel>/data, Envelope v2, KPI Registry Ouro M01..A*) + SQL TOTVS RM + Neon PostgreSQL + Zeev BPM + PBI_DATASET. Use para: descobrir KPI Ouro, consumir painel canonical, escrever query nova (cascade painel>KPI>dinamica>raw), otimizar SQL lenta, anti-patterns, relatorios, processos Zeev. Tier 0: data-engine. Aplica…

No reviews yet
0 installs
37 views
0.0% view→install

Install

$ agentstack add skill-andregusman-raiz-a-gusman-claude-ag-12-sql-totvs-zeev

✓ scanned · ✓ verified, works with Claude Code, Cursor, and more.

Security review

✓ Passed

No issues found. Passed automated security review. · v0.1.0 How review works →

  • Prompt-injection patterns
  • Secret / credential exfiltration
  • Dangerous shell & filesystem operations
  • Untrusted network calls
  • Known-malicious package signatures

What it can access

  • Network access No
  • Filesystem access No
  • Shell / process execution No
  • Environment & secrets No
  • Dynamic code execution No

From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.

View the full security report →

Verified badge

Passed review? Show it. Paste this badge into your README, it links to the public security report.

AgentStack Verified badge Links to your public security report.
[![AgentStack Verified](https://agentstack.voostack.com/badges/verified.svg)](https://agentstack.voostack.com/security/report/skill-andregusman-raiz-a-gusman-claude-ag-12-sql-totvs-zeev)

Reliability & compatibility

Security review passed
0 installs to date
no reviews yet
3mo ago

Declared compatibility

Claude CodeClaude Desktop

Compatibility is declared by the source manifest. End-to-end runtime verification is coming, see below.

Preview Execution monitoring

We're building live execution health for every listing: tool-call success rate, median latency, uptime, and last-checked timestamps, measured, not self-reported. It isn't live yet, so we don't show numbers we can't stand behind.

How agent discovery & health will work →
Are you the author of Ag 12 Sql Totvs Zeev? Claim this listing to set pricing, connect Stripe payouts, and keep 70% of every sale.
Sign up to claim

About

Data Engine + SQL Optimization — TOTVS RM, Zeev BPM, PostgreSQL, PBI_DATASET

🎯 TIER 0 — Data Engine API (PREFERIR sobre SQL direto)

> data-engine-app é a camada canonical que já decodifica regras de negócio, > agrega Bronze→Prata→Ouro, aplica governança e expõe value_raw + value_formatted > consistente com BI Raiz. Se a resposta já existe na API canonical → consumi-la, > nunca reescrever SQL equivalente em outro projeto.

Arquitetura em 4 camadas (consultar ANTES de escolher fonte)

Bronze (mirrors raw)  →  Prata (dbt int/fact/dim)  →  Ouro (KPI Registry, 65+ IDs)  →  API
                                                                                       │
                                          ┌────────────────────────────────────────────┤
                                          ▼                            ▼                ▼
                                    DISCOVERY                    EXECUTION         GOVERNANCE
                              /v1/kpis/catalog            /v1/kpis/{id}/value     X-API-Key
                              /v1/kpis/search             /reports//data    rate-tiers
                              //dictionary        /query/preflight + execute  PII mask
                              /v1/manifest                                              audit
                              /openapi.json (x-raiz-lineage)

| Camada | Conteúdo | Source of truth | |---|---|---| | Bronze | Scrapers, TOTVS REST/SOAP, BI Raiz | sistemas externos | | Prata | dbt fact_* + dim_* em prata.* | Neon mirror (PBI_DATASET + TOTVS RM) | | Ouro | KPI Registry (65 KPIs) | raiz_data_engine/reports/core/kpi_registry/ | | API | Envelope v2 universal {value_raw, value_formatted} | raiz_data_engine/api/ |

Cascade de Decisão (regra inegociável)

Ordem de preferência ao buscar dado:

  1. GET /reports//data — bundle multi-KPI cacheado (14 painéis ativos)
  2. GET /v1/kpis/{id}/value?filters=... — execução canônica do KPI Ouro
  3. POST /query/preflightPOST /query/execute — SQL dinâmico governado (audit + PII)
  4. SQL direto TOTVS RM / Neon / PBI_DATASET — último recurso, só se nada acima cobre

Se IA/plataforma já consome data-engine: prefira Tier 0. SQL direto vira fallback documentado, não default.

IDs canônicos KPI Ouro (referência rápida — kpi_id)

| Prefixo | Domínio | Faixa | Exemplos | |---|---|---|---| | M | Matrículas | M01–M15 | M01 Alunos Matriculados, M07 Taxa Ocupação | | C | Cobrança / Comercial | C01–C08 | C04 % Inadimplência Canonical | | E | Endividamento / Educacional | E01–E05 | E04 Saldo Devedor | | R/F/S | RH / Financeiro / Satisfação | extras Q9.C.0 | — | | L/B/Z | Layers / Benefícios / Zeev | extras | — | | I/Q/N | INEP / Quality / NPS | extras | — | | D/A | DRE / Avaliações | extras | A12 ENEM Redação |

> Regra: persistir/logar/cachear sempre por kpi_id (estável). label_pt muda; ID não.

Endpoints canonical (memorizar)

| Endpoint | Para que | Auth | |---|---|---| | GET /v1/kpis/catalog | catálogo completo (rich schema, fórmula SQL, known_gaps) | público | | GET /v1/kpis/catalog?domain=&status=canonical | filtrado | público | | GET /v1/kpis/search?q=...&prefix=M&limit=50 | full-text (key+label+description) | público | | GET /v1/kpis/{id} | lookup individual (atalho) | público | | GET /v1/kpis/{id}/consumers | painéis + APIs que usam | público | | GET /v1/kpis/{id}/value?filters=... | execução SQL canônica do KPI Ouro | público | | GET //dictionary | dictionary (kpis + tables + conventions) | público | | GET /reports//data | bundle de painel pronto | público | | GET /v1/manifest | catalog de manifests | público | | GET /schema/tables | lista schema catalog cross-source | X-API-Key | | GET /v1/schema/table/{table_name} | lookup público individual de tabela | público | | POST /query/preflight | valida SQL antes de executar | X-API-Key | | POST /query/execute | SQL dinâmico governado, usar source=neon | X-API-Key | | GET /openapi.json | OpenAPI + extensão x-raiz-lineage | público | | GET /metrics/canonical | Prometheus | público |

Base prod: https://app.example.com

Política runtime TOTVS/RH para agentes

  • ADR-041: não usar SQL direto TOTVS RM em runtime Railway.
  • /query/execute é fallback governado Neon-only para agentes; enviar source=neon.
  • Se o usuário trouxer SQL RM bruto, converter manualmente para mirror Neon ou retornar gap acionável. Não selecionar fonte TOTVS RM direta no endpoint dinâmico.
  • Mirrors RH disponíveis:
  • PFFINANCpublic.pffinanc_mirror
  • PEVENTOpublic.pevento_mirror
  • PFUNCpublic.pfunc_mirror
  • PFUNCAOpublic.pfuncao_mirror
  • GFORMULApublic.gformula_mirror
  • GFORMULA está disponível no Neon/schema registry para análise técnica de fórmulas RM. Usar source=neon; não usar source=totvs_rm em runtime. FORMULACOMPILADA binária não é espelhada; usar texto, titulo e metadados.

TOTVS GCONSSQL via wsDataServer

Descoberta incorporada: cadastrar sentença SQL custom em GCONSSQL via wsDataServer/GlbConsSqlData desbloqueia fontes sem DataServer de negócio, como MovMovimentoData, desde que tratado como registry governado.

Uso permitido:

  • sync/backfill controlado, nunca endpoint de SQL livre;
  • SQL versionado no data-engine-app;
  • sentença COUNT + sentença PAGE;
  • filtro obrigatório por CODCOLIGADA;
  • paginação determinística OFFSET/FETCH;
  • staging no Neon + count parity antes de publish;
  • PII somente com RBAC/LGPD formal.

Uso proibido:

  • SELECT *;
  • INSERT/UPDATE/DELETE/MERGE/DROP/ALTER/CREATE/EXEC;
  • execução runtime direta contra TOTVS;
  • logar payload de linha, token, senha, CPF, RA, chapa ou nome.

Fonte canônica no repo:

  • scripts/ops/config/totvs_governed_sentence_registry.json
  • scripts/ops/sql/totvs_governed_sentence_registry/
  • docs/runbooks/totvs-governed-gconssql-registry.md

Piloto recomendado: RDE.TOTVS.TMOV.COUNT/PAGE e RDE.TOTVS.TITMMOV.COUNT/PAGE para alimentar public.tmov_mirror e public.titmmov_mirror.

Envelope v2 universal

Todo número da API canonical retorna:

{ "value_raw": 1838.0, "value_formatted": "1.838" }
  • value_raw → cálculo / agregação no cliente
  • value_formatted → display direto (parity com BI Raiz)
  • NUNCA re-formatar value_raw no consumer (mascaramento PII já server-side)

Rate Limit tiers (slowapi IP-level + 60 RPM/10K dia por key)

| Path | Limite | |---|---| | /health /metrics /readyz | whitelist | | auth/* | 5/min | | admin/* | 30/min | | api/* (default) | 200/min | | outros | 100/min |

Retry-on-429 com backoff exponencial + jitter. Batchar lookups (usar search?prefix=M em vez de N gets).

known_gaps — LER SEMPRE antes de prometer número

Cada entry de /v1/kpis/{id} traz known_gaps[] com semantic drift declarado. Exemplo M01:

  • matriculados_brutos: sem TAG_MATVALIDA — inclui contratos não confirmados
  • pre_matriculados: TAG_MATVALIDA=FALSE, contrato sem 1ª parcela paga

Resposta da IA sem citar known_gaps relevantes = "certo na conta, errado no negócio".

Lineage via x-raiz-lineage (OpenAPI extension)

/openapi.json injeta mapping endpoint → tabela Bronze/Prata/Ouro. Usar para:

  • explicar resposta: "este número vem de prata.int_alunos_qualificados filtrado por…"
  • auditar prompt→data trail
  • debugar drift cross-source

Painéis ativos (14) — /reports//data

matriculas, dre_dashboard, faturamento, inadimplencia, funnel, beneficios, pessoas_rh, quadro_docente, erros_operacionais, pesquisa_satisfacao, layers_comunidade, layers_payments, zeev, avaliacoes_inep,

  • painel_kpi_executivo_resumido, painel_resumo_operacional (consolidados).

Pact contracts (consumer formal)

Plataforma consumidora estável (não one-shot) → adicionar contracts/consumer/.json em data-engine-app/contracts/consumer/. Modelo: example-platform.json. Trava endpoints + schemas bidirecionalmente. Para agente IA: mesma lógica previne hallucination em prod.

Painel novo = registry declarativo (não custom code)

Se a tarefa é criar painel novo no data-engine, único caminho aceito:

/ag-painel-novo-canonico criar painel  com KPIs M01,M02,E03
# OU
python scripts/scaffold_panel.py --panel-id  --kpi-ouro-ids "M01,M02" --all-from-registry

CI gate painel-readiness-strict.yml BLOQUEIA: queries.py presente, aggregator custom, MetricSpec sem kpi_ouro_id, score KB inline para eliminar Read round-trip em prompts comuns. Para KB completa e atualizada, consultar ~/Claude/assets/knowledge-base/totvs/.

Tabelas TOTVS mais usadas

| Tabela | Propósito | Colunas-chave | |---|---|---| | PPESSOA | Cadastro pessoa (aluno, funcionário, responsável) | CODIGO, NOME, CPF, DTNASCIMENTO | | SALUNO | Aluno educacional | CODCOLIGADA, RA, CODPESSOA, CODCURSO, CODHABILITACAO | | SMATRICULA | Matrícula por período | CODCOLIGADA, RA, IDPERLET, CODSTATUS, DTMATRICULA | | PFUNC | Funcionário RH (680 cols — NUNCA SELECT *) | CODCOLIGADA, CHAPA, CODPESSOA, CODSITUACAO | | PFFINANC | Ficha financeira (histórico) | CODCOLIGADA, CHAPA, ANOCOMP, MESCOMP | | PEVENTO | Eventos folha (código evento) | CODCOLIGADA, CODEVENTO, DESCRICAO, TIPO | | FLAN | Lançamentos financeiros | CODCOLIGADA, IDLAN, CODCFO, STATUSLAN, VALORORIGINAL | | GCOLIGADA | Coligadas (32 ativas) | CODCOLIGADA, NOME, CNPJ |

Enums críticos (SStatus por coligada)

COL=1 (Raiz):     matriculado = CODSTATUS IN (2, 3)
COL=2 (QI):       matriculado = CODSTATUS IN (2, 3)
COL=10 (SIR):     matriculado = CODSTATUS IN (14, 15, 25, 32) ← stratificado por filial
  FIL=1 (QI Recreio):   IN (2, 3)
  FIL=3,4,6 (Sá Pereira): IN (14, 15)
  FIL=7 (SAP):           IN (25, 32)

Guards obrigatórios TOTVS

  1. WHERE CODCOLIGADA = N sempre (multi-tenant)
  2. FROM TBL (NOLOCK) sempre em leitura
  3. SELECT col1, col2, ...NUNCA SELECT *
  4. DateTime sargable: `WHERE DT >= '2026-01-01' AND DT 5K) |

| hubspotcontact | 518K | sim | | hubspotleadraiz | 57K | sim | | hubspottotvsmatch | 41K | sim | | pbipainelmatriculas | 32K | sim | | fichafinanceira | 436K | sim | | holerite | 47.5K | sim |

Pattern:

OFFSET = 0; BATCH = 1000
while True:
    rows = query(f"SELECT ... ORDER BY id LIMIT {BATCH} OFFSET {OFFSET}")
    if not rows: break
    process(rows); OFFSET += BATCH

Data Source Router (domain → source)

| Domínio | Fonte Primária | |---|---| | Matrículas, educacional, metas | PBIDATASET (business rules decoded) | | Financeiro, acordos | PBIDATASET | | RH, folha, ponto, compras | TOTVS RM | | HubSpot deals/contacts/leads | Neon | | Zeev BPM | Neon (mirror) |

Regra: consultar tabela acima ANTES de escrever query. Domínio ambíguo → PARAR e perguntar.

PBI_DATASET (bridge)

  • SELECT * FROM INFORMATION_SCHEMA.TABLES para discovery
  • NULL-safe filter: WHERE (col <> 'X' OR col IS NULL) (SQL Server exclui NULL silencioso)
  • Tabelas Tabela_* já tem regras de negócio decoded (não replicar em SQL raw)

Knowledge Base Unificada (OBRIGATÓRIO consultar)

TOTVS RM — KB MECE

~/Claude/assets/knowledge-base/totvs/unified/     ← COMECE AQUI
├── schema.json         # 69 tabelas, 1992 campos, FKs, PII flags
├── glossary.json       # 1,211 termos técnico → negócio PT-BR
├── queries.json        # 28 queries catalogadas com metadata
├── apis.json           # 55 REST + 29 SOAP DataServers
├── rules.json          # Regras de negócio (matrícula, notas, financeiro, PII)
├── enums.json          # Valores reais de lookup (SStatus, GColigada, etc.)
├── domains/            # 8 docs por domínio de negócio
└── guides/
    ├── gotchas.md              # 24 lições aprendidas
    └── query-cookbook.md        # Queries por caso de uso

Fontes brutas: ~/Claude/assets/knowledge-base/totvs/raw/

Zeev BPM — KB MECE

~/Claude/assets/knowledge-base/zeev/unified/      ← COMECE AQUI
├── apis.json           # 98 endpoints + 261 modelos
├── integration.json    # Estado integração example-platform (routes, agent tool, env vars)
├── rules.json          # Auth (impersonation), limites, gaps da API
├── glossary.json       # 20 termos Zeev → negócio
├── domains/            # 6 docs por domínio
└── guides/
    ├── gotchas.md              # 20 lições aprendidas
    └── agent-tool-cookbook.md   # 10 ações do zeev_bpm

Fontes brutas: ~/Claude/assets/knowledge-base/zeev/raw/


Pre-Generation Gates (OBRIGATÓRIO antes de gerar qualquer SQL)

Executar TODOS os gates sequencialmente. Se qualquer gate falhar → PARAR e reportar.

GATE 1 — Source Selection (Tier 0 prioritário)

Mapear o domínio para a fonte correta ANTES de tocar em SQL. Tier 0 (data-engine API) vence sempre que cobre.

| Tier | Fonte | Quando | |---|---|---| | 0 | data-engine-app API canonical | KPI existe no Registry Ouro OU painel /reports//data cobre a pergunta | | 1 | PBIDATASET (REDACTEDDB) | Matrículas/financeiro/educacional sem KPI Ouro canonical; tabelas Tabela_* | | 1 | TOTVS RM (Cloud) | RH, folha, ponto, compras, contábil (PFUNC, PFFINANC, PEVENTO, ...) — via Neon Mirror em runtime (ADR-041) | | 1 | Neon raw (PostgreSQL) | HubSpot deals/contacts/leads, Layers, Zeev, hubspottotvsmatch | | 2 | /query/execute (data-engine) | SQL dinâmico governado quando Tier 0 não cobre mas precisa de PII/audit | | 3 | SQL direto (psql / sqlcmd / pymssql) | Último recurso: backfill, admin, DDL, exploração ad-hoc |

Regras:

  • Se Tier 0 cobre → usar Tier 0 e parar (cita kpi_id + source.primary + known_gaps).
  • Se domínio é ambíguo → PARAR e perguntar ao usuário.
  • NUNCA escrever SQL equivalente em projeto-cliente quando a API canonical já entrega.

GATE 2 — Schema Validation (TOTVS RM only)

  1. Ler ~/Claude/assets/knowledge-base/totvs/unified/schema.json para CADA tabela mencionada
  2. Verificar nomes EXATOS de colunas — NUNCA inventar nomes de campos
  3. Se tabela não está no schema.json (69 tabelas): STOP e declarar "tabela não catalogada na KB"
  4. Verificar flags PII em schema.json — se query toca campos PII, aplicar regras de mascaramento

GATE 3 — Multi-Tenant Guard

  1. TOTVS RM: toda query DEVE ter CODCOLIGADA no WHERE — injetar se ausente
  2. COL=10 (Escolas Integradas Raiz): 3 marcas com status DIFERENTES:
  • FIL=1 (Qi Recreio): CODSTATUS IN (2, 3)
  • FIL=3,4,6 (Sá Pereira): CODSTATUS IN (14, 15)
  • FIL=7 (SAP): CODSTATUS IN (25, 32)
  1. Atribuição de marca SEMPRE por (CODCOLIGADA, CODFILIAL) pair — NUNCA só CODCOLIGADA

GATE 4 — Anti-Pattern Rejection

Rejeitar e reescrever automaticamente:

  • SELECT * → expandir para colunas nomeadas (consultar schema.json)
  • Sem (NOLOCK) em leitura TOTVS RM → adicionar a todo FROM/JOIN
  • Neon query com >5K rows esperados sem paginação → adicionar LIMIT 1000 + OFFSET loop
  • BETWEEN em DateTime → reescrever como >= AND 'X' OR col IS NULL)
  1. Discovery: /api/pbi-app/tables, /api/pbi-app/columns/{table}

GATE 6 — Data Engine Routing (Tier 0 enforcement)

Antes de escrever qualquer SQL contra TOTVS/Neon/PBI_DATASET, executar a cascade:

  1. Discovery KPIGET /v1/kpis/search?q=&domain= (ou catalog se já souber kpi_id)
  2. Painel pronto? — listar /reports//data ativos; se algum bundle responde a pergunta inteira → consumir bundle
  3. KPI canônico?GET /v1/kpis/{id}/value?filters=... se for métrica isolada
  4. Query dinâmica?POST /query/preflight antes de POST /query/execute (governance: PII mask + audit + rate limit)
  5. Raw SQL? — só se 1-4 falham, e documentar no PR/commit por que Tier 0 não cobriu (vira backlog de KPI Ouro)

Cada chamada a data-engine deve citar lineage no output: kpi_id, source.primary, known_gaps[] relevantes.

GATE 7 — ADR-041 enforcement (TOTVS via Neon Mirror)

pymssql.connect() direto em TOTVS RM é PROIBIDO em runtime Railway (ADR-041). Exceções permiti

Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

Install and usage instructions live in the source repository linked above.

Reviews

No reviews yet, be the first.

Versions

  • v0.1.0 Imported from the upstream source.