← Back to Pull requests

feat: inventário gerado do estado real — scripts refazem banco, edges, rotas e tabelas #3039

Merged
adm01-debug merged 11 files (22317 lines) on Nov 02, 2026 20:59 UTC
View on GitHub
adm01-debug adm01-debug commented on Nov 02, 2026 13:48 UTC
Author

📋 Descrição

Causa: o mapa do projeto estava espalhado em dezenas de auditorias escritas à mão, que ficam velhas em semanas. Esta PR cria inventario/estado/ com dados gerados por script, a fonte que os agentes devem consultar. É o mesmo formato do Zapp_Web_V2: inventario/estado/ mais scripts/inventario/.

Scripts:

  • scripts/inventario/gerar-banco.mjs (novo) → grava banco.json. Lê o banco oficial doufsxqlfjyuvxuezpln em somente leitura, pela Management API /database/query/read-only e /functions, com o SUPABASE_ACCESS_TOKEN. Conteúdo:

  • - tabelas com linhas, RLS, policies, triggers e tamanho;
    - views, mviews e funções SQL (security definer marcado);
    - cron jobs com execuções e falhas de 48 h e o último erro;
    - edge functions publicadas versus repo;
    - candidatas a órfãs.
    - Para sem gravar nada se faltar o token ou se a saída tiver algo com cara de credencial.
  • scripts/inventario/gerar-repo.mjs → grava edges.json, rotas.json e tabelas-uso.json.

  • - edges.json: edge functions, segredos lidos e quem chama cada uma. _shared/ e README não contam como chamadores.
    - rotas.json: rota → tela (arquivo) → hooks → dados (tabelas, buckets de storage, RPCs e edges alcançáveis por imports locais até 4 níveis), mais as guardas, inclusive as herdadas do AppRoutes.tsx (ProtectedRoute) e wrappers como MagazineRoute.
    - tabelas-uso.json: .from() por tabela em src/ e nas edges, e a lista final de órfãs.
  • Para refazer tudo: SUPABASE_ACCESS_TOKEN=... node scripts/inventario/gerar-banco.mjs && node scripts/inventario/gerar-repo.mjs.

  • Atualização semanal automática: #3042, que fica aberta para o dono aprovar porque mexe em workflow.
  • Achados da geração de hoje (detalhes no inventario/estado/README.md):

  • RLS: todas as tabelas de public têm RLS e nenhuma está com 0 policies. Há 24 tabelas sem RLS fora de public.

  • Tabelas: 23 órfãs e 14 de backup/arquivo em public.

  • Cron: 144 jobs; 7 inativos; 679 falhas em 48 h, quase todas job startup timeout.

  • Edge functions: 110 no repo e 110 publicadas, com os mesmos nomes; 36 estão com verify_jwt=false; 26 sem chamador no repo.

  • Rotas: 135; 124 com tela resolvida (as outras 11 são <Navigate>); 98 alcançam dados; 28 públicas.
  • 🎯 Tipo de mudança

  • 🚀 feat — nova funcionalidade
  • 🌐 Sistemas afetados

  • Outro: só arquivos novos em inventario/estado/ e scripts/inventario/
  • 🧭 Contratos, impacto e autorizações

  • Não altera banco, dados, design, infraestrutura, integração externa ou deploy. O banco foi só lido.
  • ✅ Verificado

  • Consulta exata do gerar-banco.mjs executada no banco real via MCP execute_sql: retornou 297 KB, com 428 tabelas, 209 views, 1.351 funções, 144 cron e 50 candidatas a órfãs.

  • Script completo rodado com essa resposta real, mais a lista real de edge functions (INVENTARIO_OFFLINE_DIR):

  • - saída banco: 428 tabelas | 209 views | 1351 funcoes | 144 cron (679 falhas/48h) | 110 edges publicadas;
    - em seguida o gerar-repo.mjs: edges: 110 | rotas: 135 | tela resolvida: 124 | sem tela resolvida: 0 | tabelas: 382 | órfãs: 23.
  • Sem token: gerar-banco.mjs sai com exit 1 e defina SUPABASE_ACCESS_TOKEN…, sem gravar nada.

  • Amostras conferidas à mão:

  • - /admin/usuarios → AdminUsuariosPage.tsx, guardas ProtectedRoute+AdminRoute, bucket avatars;
    - /magazine/:id → MagazineEditorPage.tsx, guarda MagazineRoute;
    - /login → 3 tabelas (password_reset_requests, profiles, user_roles).
  • npx eslint scripts/inventario/*.mjs → exit 0.

  • Segredos: varredura por Bearer <token>, JWT, sb_secret_ e service_role no JSON → 0. Os comandos de cron usam get_edge_function_secret(), não valores.

  • guard-canonical-project: nada novo. A acusação que sobra, em analise-branches/..., é herdada do main.

  • NÃO VERIFICADO: chamada real à Management API com token. Nesta sessão não há SUPABASE_ACCESS_TOKEN; o mesmo SQL e o mesmo helper (scripts/supabase-read-only-query.mjs) já são usados por gates do CI.
  • 🤖 Generated with Claude Code

    https://claude.ai/code/session_01N1ArYQYUMHo9B9k67vpvBo

    Diff: 22317 lines (+22317 / -0) across 11 files Reviewer: adm01-debug Review duration: 431m
    All Vouch review confidence checks passed
    Residual risk 0.19 = Change Risk (0.77) × (1 − Review Confidence (0.76)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.77 · 22317 lines diff across 11 files
    0.77
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.85 · 5 substantive comment(s)
    0.85
    Model 3 · Review Timing & Attention
    Session adequacy: 77% · Reviewer familiarity: 50%
    75%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    5 comments
    scripts/inventario/gerar-repo.mjs
    "**<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Include inherited route guards in the inventory** For routes protected by parent `<Route>` elements, this extraction discards the pathless parent at `if (!path) continue` and searches only the child's attributes for guards. Consequently, every generated `guardas` array is empty, including `/admin/usuarios` and `/admin/seguranca`, which are wrapped by `AdminRoute` and `DevRoute` respectively in `src/routes/admin-routes.tsx`, and by `ProtectedRoute` in `src/routes/AppRoutes.tsx`. Track ancestor wrappers, including the composed route groups, so the advertised guard inventory distinguishes protected routes from public ones. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->"
    nit_style weight: 0.15
    inventario/estado/banco-2026-11-02.json
    "**<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Exclude tables accessed through wrappers from the orphan list** These three tables are actively queried and mutated through `untypedFrom` in `src/components/admin/hooks/useGroupPersonalization.ts`, including reads at lines 79, 101 and 137. That helper delegates directly to `supabase.from(table)` in `src/lib/supabase-untyped.ts`, so searching only literal `.from('table')` calls misses their consumers. Account for the repository's table-access wrappers before classifying tables as orphaned, and regenerate the list; the current snapshot incorrectly presents tables used by the admin personalization flow as unused. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->"
    nit_style weight: 0.15
    scripts/inventario/gerar-repo.mjs
    "**<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Preserve table usage output when stdin contains no table names** Running the README's documented command for refreshing edges and routes, `node scripts/inventario/gerar-repo.mjs < /dev/null`, enters this branch because stdin is not a TTY. The empty input then overwrites the committed 398-table `tabelas-uso.json` with an empty inventory. Check that table names were actually supplied before writing this optional output, so an edges/routes-only refresh does not erase the existing table-usage data. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->"
    logic_concern weight: 0.8
    scripts/inventario/gerar-repo.mjs
    "<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 1\. Refreshes erase the table-use snapshot <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>gerar-repo.mjs</i></b> treats any non-interactive stdin as a table list and writes <b><i>tabelas-uso.json</i></b> even when that list is empty. Running the documented <b><i>&lt; /dev/null</i></b> command therefore replaces the committed 398-table inventory with an empty one, as does a run with closed stdin in automation. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description A repo-only refresh with empty stdin overwrites the existing table-use snapshot with an empty inventory. ## Fix Focus Areas - scripts/inventario/gerar-repo.mjs[75-87] - inventario/estado/README.md[9-15] ## Recommended Fix Read and parse stdin before deciding to generate the table inventory; write `tabelas-uso.json` only when at least one valid table name was supplied. Keep the documented repo-only command safe. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details> [Dismiss ↗](https://app.qodo.ai/findings/eb0e96b8-11fb-4987-a8e6-695cbc76efc7?action=dismiss&origin=git) | [View ↗](https://app.qodo.ai/findings/eb0e96b8-11fb-4987-a8e6-695cbc76efc7)"
    logic_concern weight: 0.8
    scripts/inventario/gerar-repo.mjs
    "<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> 2\. Admin routes appear unprotected <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> The route extractor calculates <b><i>guardas</i></b> only from the current <b><i>&lt;Route&gt;</i></b> tag and does not carry guards from enclosing route groups. <b><i>/admin/usuarios</i></b> is nested under both <b><i>AdminRoute</i></b> and <b><i>ProtectedRoute</i></b>, while <b><i>/simulacao</i></b> is nested under <b><i>DevRoute</i></b>, yet their generated entries show empty guard lists. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description The generated guard field omits enclosing authentication and role gates, misleading readers of the route map. ## Fix Focus Areas - scripts/inventario/gerar-repo.mjs[58-72] ## Recommended Fix Build the route tree and propagate ancestor guard elements through the route groups mounted in AppRoutes; emit inherited guards alongside guards on each route itself. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details> [Dismiss ↗](https://app.qodo.ai/findings/e4e9b47d-8051-40f2-bfe1-f81d28540320?action=dismiss&origin=git) | [View ↗](https://app.qodo.ai/findings/e4e9b47d-8051-40f2-bfe1-f81d28540320)"
    logic_concern weight: 0.8
    Reviewers
    Assignees
    adm01-debug adm01-debug
    Labels
    risk: low confidence: 75.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 76.6% (HIGH) · Higher = larger blast radius
    76.6%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 75.8% · Lower = rushed or shallow review
    75.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 18.6% · Safe to merge
    18.6%