Skip to content

docs(session-2026-05-12): audit types drift + backup procedures + DBA session report#130

Merged
adm01-debug merged 5 commits into
mainfrom
feat/audit-types-drift-2026-05
May 20, 2026
Merged

docs(session-2026-05-12): audit types drift + backup procedures + DBA session report#130
adm01-debug merged 5 commits into
mainfrom
feat/audit-types-drift-2026-05

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

@adm01-debug adm01-debug commented May 12, 2026

📋 Resumo

Documenta a sessão de BPM/DBA de 2026-05-12. Esta sessão fez majoritariamente mudanças no BD self-hosted (state changes), não em código. Este PR commita apenas os artefatos documentais e scripts operacionais que fazem sentido versionar.

🎯 O que está neste PR

Auditoria types.ts vs BD self-hosted (read-only)

  • docs/types-drift-2026-05/AUDIT_REPORT.md (124 linhas, markdown legível)
  • docs/types-drift-2026-05/missing-tables-from-types.txt (301 entries)

Descobertas: 187 tables missing no types.ts + 241 obsoletas. 3 opções de regeneração documentadas.

Scripts de backup e disaster recovery

  • docs/backups/restore-test.sh — Script automatizado de teste de restore (validado em prod: 121s, 600 tables, 17.340 contacts match)
  • docs/backups/install-restore-test-cron.sh — Helper para instalar cron mensal no HOST
  • docs/backups/README.md — Procedure de DR validado com métricas reais

Relatório consolidado da sessão

  • docs/session-2026-05-12/SESSION_REPORT.md — Transparência total sobre o que foi feito e o que ficou pendente

✅ O que JÁ ESTÁ EM PRODUÇÃO (não vai pro repo, é state do BD)

  • 18+ tables com RLS lockdown aplicado
  • 17 functions Lovable reinstaladas + smoke test 17/17 passou
  • 23 ALTER COLUMN aplicados
  • 6 credentials harmonizadas (api_keys, bling_token, credential_vault, workspace_secrets, passkey_credentials, whatsapp_official_credentials)
  • 7 backups vazios deletados + 5 FATOR X arquivados
  • Validação smoke test em prod: {\"ok\": 24, \"fail\": 0, \"defer\": 7, \"status\": \"healthy\"}

❌ Pendências (precisam ação do Joaquim)

Tarefa Bloqueio
Off-site R2 backup Worker retorna 401 — secret correto está no CF Dashboard
Upgrade studio+analytics+meta+functions Docker Swarm — precisa janela noturna
Upgrade storage-api (HIGH RISK) Mesma razão
Upgrade kong (MAJOR) Vai quebrar auth — precisa migrar kong.yml manual

🐛 Bug fix incluído

Commit anterior do AUDIT_REPORT.md tinha conteúdo base64 cru (não decodificado). Este PR corrige.

✅ Validação

[2026-05-12T19:54:02+00:00] Restore test resultado:
  - tables públicas: 600
  - evolution_contacts: 17.340 (match com produção)
  - evolution_messages: 1.838.351
  - tamanho restaurado: 1921 MB
✅ RESTORE TEST PASSOU (121 segundos)

🚀 Deploy do restore-test após merge

docker cp docs/backups/restore-test.sh \
  $(docker ps -qf name=supabase-backup_backup):/backups/restore-test.sh
bash docs/backups/install-restore-test-cron.sh

Ref: documento docs/session-2026-05-12/SESSION_REPORT.md para detalhes completos da sessão.

Summary by CodeRabbit

  • Documentação

    • Guia completo de backup e restauração com procedimento validado, histórico, checklist, problemas conhecidos e relatório operacional.
    • Relatório de sessão (hardening, validações e próximos passos).
    • Auditoria de deriva de tipos com métricas, impactos, recomendações e arquivo com a lista completa de tabelas faltantes.
  • Novos Recursos

    • Script de teste de restauração automatizado com validações, thresholds e sinalização de falhas.
    • Instalador idempotente para cron mensal (04:00 UTC dia 1) para agendar testes de restauração.

Review Change Stack

Copilot AI review requested due to automatic review settings May 12, 2026 20:16
@vercel
Copy link
Copy Markdown

vercel Bot commented May 12, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
zapp-web Ready Ready Preview, Comment May 20, 2026 10:54am

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 12, 2026

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 928bf0f9-b0fd-4360-9906-295525954b29

📥 Commits

Reviewing files that changed from the base of the PR and between a887ff9 and 3b0bb1f.

📒 Files selected for processing (6)
  • docs/backups/README.md
  • docs/backups/install-restore-test-cron.sh
  • docs/backups/restore-test.sh
  • docs/session-2026-05-12/SESSION_REPORT.md
  • docs/types-drift-2026-05/AUDIT_REPORT.md
  • docs/types-drift-2026-05/missing-tables-from-types.txt

Walkthrough

PR adiciona automação de validação periódica para backups Postgres self-hosted Supabase: script restore-test.sh executa restore em DB temporária com filtragem pg_cron e validação heurística; script install-restore-test-cron.sh instala cron mensal via docker exec; documentação procedimento disaster recovery; e relatórios de session & auditoria de drift types.ts.

Changes

Backup & Restore Automation

Layer / File(s) Summary
Script de Validação de Restore
docs/backups/restore-test.sh
Automatiza validação periódica: localiza dump recente, verifica SHA256 opcional, cria DB temporária, filtra pg_cron do TOC, executa pg_restore com timeout, valida counts heurísticos (>=400 tabelas, >=10k contacts), e marca failures com file marker.
Instalação Cron Job Mensal
docs/backups/install-restore-test-cron.sh
Script idempotente que valida container supabase-backup_backup e instala cron na linha 0 4 1 * * para executar via docker exec, escrevendo logs em host /var/log/restore-test-cron.log.
Documentação Procedimento Disaster Recovery
docs/backups/README.md
Estrutura diretório backups, configuração automação (host/user/target DB/retention/threshold/format/compress/freq), fluxo validação com filtragem pg_cron, queries pós-restore esperadas, tabela benchmarks dry-run, inventory scripts, e histórico datado com milestones validados.
Relatório Sessão & Auditoria Drift
docs/session-2026-05-12/SESSION_REPORT.md, docs/types-drift-2026-05/AUDIT_REPORT.md, docs/types-drift-2026-05/missing-tables-from-types.txt
SESSION_REPORT: ações de hardening e validações; AUDIT_REPORT: 187 missing + 241 extra entries e recomendações para regenerar types.ts; missing-tables: lista de 301 tabelas.
sequenceDiagram
  participant Operator as Operador
  participant Cron as Cron Host
  participant BackupContainer as supabase-backup_backup
  participant RestoreScript as restore-test.sh
  participant Postgres as PostgreSQL
  participant FS as Filesystem/Logs

  Operator->>Cron: instalar cron via `install-restore-test-cron.sh`
  Cron->>BackupContainer: docker exec /backups/restore-test.sh (agendado)
  BackupContainer->>RestoreScript: executar script de restore
  RestoreScript->>FS: localizar dump + validar .sha256
  RestoreScript->>Postgres: criar DB temporária
  RestoreScript->>FS: gerar e filtrar TOC (remover pg_cron)
  RestoreScript->>Postgres: executar pg_restore (timeout 10m)
  Postgres-->>RestoreScript: resultado restore
  RestoreScript->>Postgres: consultas de validação (counts, tamanho)
  RestoreScript->>FS: escrever logs e marker PASS/FAIL
Loading

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possivelmente relacionado:

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed O título descreve com precisão o conteúdo principal do PR: audit de tipos drift, procedimentos de backup e relatório de sessão DBA.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4ca2f68f4a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread docs/backups/restore-test.sh Outdated
Comment on lines +66 to +68
timeout 600 pg_restore -d $DBNAME --no-owner --no-acl \
--use-list=/tmp/toc-${DBNAME}.filtered --jobs=4 \
"$LATEST" >> $LOG 2>&1 || true
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Do not ignore pg_restore failures

In the monthly restore-test path, any nonzero pg_restore exit (timeout, corrupted dump section, missing extension/object errors) is swallowed by || true, so the script can still report RESTORE TEST PASSOU if the few count queries exceed the thresholds after a partial restore. Since this script is meant to validate disaster recovery, please fail the test and create the failure marker when pg_restore returns nonzero instead of relying only on row-count heuristics.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/backups/restore-test.sh`:
- Around line 66-68: O comando de restauração usa "|| true", o que oculta falhas
de pg_restore/timeout; remova "|| true", capture o código de saída imediatamente
após o comando (ex.: rc=$?) e passe esse rc como primeira condição no check de
sucesso usado depois (referencie o comando timeout 600 pg_restore -d $DBNAME ...
"$LATEST" >> $LOG 2>&1 e a checagem de sucesso existente), de forma que qualquer
rc != 0 (incluindo timeouts) faça o script marcar FAILED.
- Around line 39-47: The checksum flow can be interrupted by set -e if cd fails;
wrap the cd and sha256sum in a subshell used directly by the if so the exit
status is captured without aborting the script. Replace the current separate
cd/sha256sum + subsequent if [ $? -eq 0 ] check with an if that runs (cd
/backups && sha256sum -c "$(basename ${LATEST}).sha256" >/dev/null 2>&1); then
call log "OK: SHA256 válido" else call log "ERRO: SHA256 FALHOU - backup
corrompido!", create the RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S) marker and
exit 2, keeping references to LATEST, the log function, and the
RESTORE_TEST_FAILED marker.

In `@docs/session-2026-05-12/SESSION_REPORT.md`:
- Around line 105-107: Update the session report line that currently reads
"**STATUS: ⚠️ AINDA NÃO ABERTO**" to reflect that the PR is open by changing the
status text to something like "**STATUS: ✅ ABERTO — PR `#130` (2026-05-12)**", and
ensure the PR number "#130" and date "2026-05-12" are included next to the
status; modify the string in SESSION_REPORT.md where that exact status line
appears so the handoff reflects the current PR state.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: af3abd6e-1557-4ebd-bf72-f750719bcfc7

📥 Commits

Reviewing files that changed from the base of the PR and between 8555b50 and 4ca2f68.

📒 Files selected for processing (6)
  • docs/backups/README.md
  • docs/backups/install-restore-test-cron.sh
  • docs/backups/restore-test.sh
  • docs/session-2026-05-12/SESSION_REPORT.md
  • docs/types-drift-2026-05/AUDIT_REPORT.md
  • docs/types-drift-2026-05/missing-tables-from-types.txt

Comment thread docs/backups/restore-test.sh
Comment thread docs/backups/restore-test.sh Outdated
Comment thread docs/session-2026-05-12/SESSION_REPORT.md Outdated
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Documentation + operational artifacts from the 2026-05-12 BPM/DBA session, including a recorded schema/types drift audit and a scripted monthly restore test procedure for the self-hosted Supabase backups.

Changes:

  • Adds a drift audit report comparing src/integrations/supabase/types.ts vs the self-hosted production DB, plus the full list of missing tables.
  • Adds backup/DR documentation and two operational scripts: an automated restore-test and a cron installer for monthly execution.
  • Adds a consolidated session report capturing what was changed in production (state changes) vs what is versioned in this repo.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 8 comments.

Show a summary per file
File Description
docs/types-drift-2026-05/missing-tables-from-types.txt Full list of tables present in DB but missing from types.ts.
docs/types-drift-2026-05/AUDIT_REPORT.md Human-readable drift summary + regeneration options.
docs/session-2026-05-12/SESSION_REPORT.md Session log of production actions + repo artifacts.
docs/backups/restore-test.sh Automated restore validation script intended to run monthly.
docs/backups/README.md DR/restore procedure and deployment notes for the backup container.
docs/backups/install-restore-test-cron.sh Host-side helper to install a monthly cron job running the restore test.
Comments suppressed due to low confidence (3)

docs/backups/restore-test.sh:47

  • Because set -e is enabled, a failing sha256sum -c will terminate the script immediately, so the subsequent $? check and failure logging won't run. Wrap the checksum validation directly in the if ...; then condition (or otherwise capture the exit code without triggering set -e) so failures are logged and handled consistently.
if [ -f "${LATEST}.sha256" ]; then
  cd /backups && sha256sum -c "$(basename ${LATEST}).sha256" >/dev/null 2>&1
  if [ $? -eq 0 ]; then
    log "OK: SHA256 válido"
  else
    log "ERRO: SHA256 FALHOU - backup corrompido!"
    touch /backups/RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S)
    exit 2
  fi

docs/backups/restore-test.sh:61

  • The grep pattern uses \| alternation without -E. This is not portable across grep implementations and can silently fail, causing pg_cron objects to be restored when they shouldn't. Prefer grep -E (or egrep) with pg_cron|cron\. for predictable behavior.
pg_restore -l "$LATEST" > /tmp/toc-${DBNAME}.list 2>/dev/null
grep -v 'pg_cron\|cron\.' /tmp/toc-${DBNAME}.list > /tmp/toc-${DBNAME}.filtered

docs/backups/restore-test.sh:69

  • pg_restore errors are currently ignored (... || true). This can produce a misleading PASS if enough rows restore to satisfy the thresholds while critical objects failed to restore. Capture the pg_restore exit status and treat non-zero as failure (while still collecting counts/logs), or at least include the exit status in the pass/fail decision.
log "Iniciando pg_restore (timeout 10min)..."

timeout 600 pg_restore -d $DBNAME --no-owner --no-acl \
  --use-list=/tmp/toc-${DBNAME}.filtered --jobs=4 \
  "$LATEST" >> $LOG 2>&1 || true


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +16 to +34
set -e

LOG=/backups/restore-test.log
DATE=$(date -Iseconds)

log() {
echo "[$DATE] $*" | tee -a "$LOG"
}

log "==================== RESTORE TEST INICIADO ===================="

# 1. Identificar backup mais recente
LATEST=$(ls -t /backups/supabase_selfhosted_*.dump 2>/dev/null | head -1)

if [ -z "$LATEST" ]; then
log "ERRO: nenhum backup encontrado em /backups/supabase_selfhosted_*.dump"
touch /backups/RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S)
exit 1
fi
Comment on lines +53 to +57
DBNAME="restore_test_$(date +%Y%m%d_%H%M%S)"
log "Criando BD temporário: $DBNAME"
psql -c "DROP DATABASE IF EXISTS $DBNAME;" >/dev/null 2>&1
psql -c "CREATE DATABASE $DBNAME;" >/dev/null 2>&1

Comment thread docs/backups/restore-test.sh Outdated
Comment on lines +19 to +22
DATE=$(date -Iseconds)

log() {
echo "[$DATE] $*" | tee -a "$LOG"
Comment on lines +8 to +12
BACKUP_CONTAINER="supabase-backup_backup"

# Comando a executar: roda o script dentro do container
CRON_LINE="0 4 1 * * /usr/bin/docker exec \$(docker ps -qf name=${BACKUP_CONTAINER}) /backups/restore-test.sh >> /var/log/restore-test-cron.log 2>&1"

Comment thread docs/backups/README.md Outdated

# 4. Gerar TOC e filtrar pg_cron
pg_restore -l /backups/supabase_selfhosted_YYYYMMDD_HHMMSS.dump > /tmp/toc.list
grep -v 'pg_cron\|cron\.' /tmp/toc.list > /tmp/toc.filtered
Comment on lines +74 to +81
git checkout feat/audit-types-drift-2026-05
cd src/integrations/supabase

# Conectar à instância self-hosted
export SUPABASE_DB_URL="postgresql://supabase_admin:[PASSWORD]@supabase.atomicabr.com.br:5432/postgres"

# Gerar tipos
npx supabase gen types typescript --db-url $SUPABASE_DB_URL --schema public > types.new.ts
Comment thread docs/backups/restore-test.sh Outdated
Comment on lines +55 to +56
psql -c "DROP DATABASE IF EXISTS $DBNAME;" >/dev/null 2>&1
psql -c "CREATE DATABASE $DBNAME;" >/dev/null 2>&1
Comment on lines +105 to +112
- **STATUS: ⚠️ AINDA NÃO ABERTO** — branch existe com 4 commits + este, mas precisa
de aprovação do operador antes de eu abrir o PR.

---

## 🎯 Próximos passos sugeridos para o operador (Joaquim)

1. **Revisar este PR** quando for aberto e mergear para `main`.
Copy link
Copy Markdown
Owner Author

@coderabbitai review

Solicitando review fresh com a config completa do .coderabbit.yaml.


Generated by Claude Code

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 13, 2026

@adm01-debug, entendido! Disparando um review completo do PR #130 com a configuração atual do .coderabbit.yaml. 🐇

✅ Actions performed

Full review triggered.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (3)
docs/session-2026-05-12/SESSION_REPORT.md (1)

105-107: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Status do PR está desatualizado no relatório da sessão.

O texto diz "AINDA NÃO ABERTO", mas este PR já está aberto (#130, 2026-05-12). Vale corrigir para evitar ruído operacional no handoff.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/session-2026-05-12/SESSION_REPORT.md` around lines 105 - 107, Summary:
The session report's PR status line still reads "STATUS: ⚠️ AINDA NÃO ABERTO"
but the PR (`#130`, 2026-05-12) is already open. Fix: edit the STATUS line in
SESSION_REPORT.md to reflect the PR is open (e.g., "STATUS: ✅ ABERTO — PR `#130`
(2026-05-12)"), remove the note about needing operator approval, and ensure the
branch/commit context remains if needed; update the text that referenced
operator approval so it no longer contradicts the open PR status.
docs/backups/restore-test.sh (2)

39-47: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Fluxo de checksum quebrado com set -e — script pode sair antes de logar/marcar falha.

Se cd /backups falhar na linha 40, set -e mata o script imediatamente, nunca atingindo o if [ $? -eq 0 ] (linha 41). O log de erro, marker file e exit 2 nunca executam. Use subshell com if para capturar o exit code sem ser interrompido por set -e.

Diff sugerido
 if [ -f "${LATEST}.sha256" ]; then
-  cd /backups && sha256sum -c "$(basename ${LATEST}).sha256" >/dev/null 2>&1
-  if [ $? -eq 0 ]; then
+  if (cd /backups && sha256sum -c "$(basename "$LATEST").sha256" >/dev/null 2>&1); then
     log "OK: SHA256 válido"
   else
     log "ERRO: SHA256 FALHOU - backup corrompido!"
-    touch /backups/RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S)
+    touch "/backups/RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S)"
     exit 2
   fi
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/backups/restore-test.sh` around lines 39 - 47, The current two-step
change-directory plus `sha256sum` call can be interrupted by `set -e` if `cd
/backups` fails, so replace the `cd /backups && sha256sum -c "$(basename
${LATEST}).sha256" >/dev/null 2>&1` plus the separate `if [ $? -eq 0 ]` check
with a single guarded if using a subshell, e.g. `if (cd /backups && sha256sum -c
"$(basename ${LATEST}).sha256") >/dev/null 2>&1; then` to ensure the exit status
of the combined operation is tested atomically; keep the existing `log "OK:
SHA256 válido"` on success and in the else branch run `log "ERRO: SHA256 FALHOU
- backup corrompido!"`, `touch /backups/RESTORE_TEST_FAILED_$(date
+%Y%m%d_%H%M%S)` and `exit 2` so failures are always logged/marked even when
`set -e` is enabled.

66-68: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Capturar falha de pg_restore e forçar FAILED.

O || true na linha 68 mascara falhas de pg_restore ou timeout. Mesmo que a operação falhe (exit code != 0 ou timeout), o script segue adiante. Se o restore falha parcialmente mas deixa o banco com algumas tabelas/registros, o teste pode passar incorretamente baseado nas contagens de threshold.

Solução: Capture o exit code real de pg_restore e inclua-o como primeira condição no check de sucesso (linha 89). Assim, falha crítica no restore sempre resulta em FAILED.

Diff sugerido
-timeout 600 pg_restore -d $DBNAME --no-owner --no-acl \
+if timeout 600 pg_restore -d "$DBNAME" --no-owner --no-acl \
   --use-list=/tmp/toc-${DBNAME}.filtered --jobs=4 \
-  "$LATEST" >> $LOG 2>&1 || true
+  "$LATEST" >> "$LOG" 2>&1; then
+  RESTORE_OK=1
+else
+  RESTORE_OK=0
+fi
@@
-if [ "$TABLE_COUNT" -ge 400 ] && [ "$CONTACTS" -ge 10000 ]; then
+if [ "$RESTORE_OK" -eq 1 ] && [ "$TABLE_COUNT" -ge 400 ] && [ "$CONTACTS" -ge 10000 ]; then
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/backups/restore-test.sh` around lines 66 - 68, Remove the unconditional
"|| true" that masks pg_restore failures, capture its real exit code right after
the timeout pg_restore invocation (use a variable like RESTORE_EXIT=$?), and
then make the later success check include RESTORE_EXIT == 0 as the first
required condition so any non-zero exit (including timeout) forces the script to
mark FAILED; reference the timeout pg_restore invocation that uses "$LATEST",
$DBNAME, $LOG and the later success/threshold check to add the RESTORE_EXIT
check.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In `@docs/backups/restore-test.sh`:
- Around line 39-47: The current two-step change-directory plus `sha256sum` call
can be interrupted by `set -e` if `cd /backups` fails, so replace the `cd
/backups && sha256sum -c "$(basename ${LATEST}).sha256" >/dev/null 2>&1` plus
the separate `if [ $? -eq 0 ]` check with a single guarded if using a subshell,
e.g. `if (cd /backups && sha256sum -c "$(basename ${LATEST}).sha256") >/dev/null
2>&1; then` to ensure the exit status of the combined operation is tested
atomically; keep the existing `log "OK: SHA256 válido"` on success and in the
else branch run `log "ERRO: SHA256 FALHOU - backup corrompido!"`, `touch
/backups/RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S)` and `exit 2` so failures
are always logged/marked even when `set -e` is enabled.
- Around line 66-68: Remove the unconditional "|| true" that masks pg_restore
failures, capture its real exit code right after the timeout pg_restore
invocation (use a variable like RESTORE_EXIT=$?), and then make the later
success check include RESTORE_EXIT == 0 as the first required condition so any
non-zero exit (including timeout) forces the script to mark FAILED; reference
the timeout pg_restore invocation that uses "$LATEST", $DBNAME, $LOG and the
later success/threshold check to add the RESTORE_EXIT check.

In `@docs/session-2026-05-12/SESSION_REPORT.md`:
- Around line 105-107: Summary: The session report's PR status line still reads
"STATUS: ⚠️ AINDA NÃO ABERTO" but the PR (`#130`, 2026-05-12) is already open.
Fix: edit the STATUS line in SESSION_REPORT.md to reflect the PR is open (e.g.,
"STATUS: ✅ ABERTO — PR `#130` (2026-05-12)"), remove the note about needing
operator approval, and ensure the branch/commit context remains if needed;
update the text that referenced operator approval so it no longer contradicts
the open PR status.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1d210281-a90f-48d9-bd0d-48f16197af85

📥 Commits

Reviewing files that changed from the base of the PR and between 8555b50 and 4ca2f68.

📒 Files selected for processing (6)
  • docs/backups/README.md
  • docs/backups/install-restore-test-cron.sh
  • docs/backups/restore-test.sh
  • docs/session-2026-05-12/SESSION_REPORT.md
  • docs/types-drift-2026-05/AUDIT_REPORT.md
  • docs/types-drift-2026-05/missing-tables-from-types.txt

adm01-debug added a commit that referenced this pull request May 13, 2026
restore-test.sh (5 fixes em 1):
- pg_restore: captura exit code real e usa como 1ª condição obrigatória
  no check de sucesso (antes `|| true` mascarava timeouts/falhas).
- SHA256: subshell + if direto para não ser interrompido por `set -e`
  se `cd` falhar antes do bloco de erro.
- `ls` com fallback `|| true` para permitir o check `[ -z $LATEST ]`.
- DBNAME quoted em SQL + DROP DATABASE WITH (FORCE) para evitar
  conexões pendentes no BD temporário derrubarem o cron.
- log() agora avalia `date -Iseconds` por linha (era fixo no startup).
- grep -Ev '(pg_cron|cron\\.)' portável (sem alternação não-POSIX).

install-restore-test-cron.sh:
- pré-flight valida que o container está rodando e é único antes de
  instalar; cron line usa o NOME do container (não `$(docker ps -qf ...)`)
  para sobreviver a restarts que mudam o ID.

docs/backups/README.md:
- grep -Ev '(pg_cron|cron\\.)' no procedure de DR para alinhar com
  o script automatizado.

docs/types-drift-2026-05/AUDIT_REPORT.md:
- senha de DB lê de SUPABASE_DB_PASSWORD via vault (pass/op/.env
  gitignored), com `unset` após uso para não vazar em history/process list.

docs/session-2026-05-12/SESSION_REPORT.md:
- status do PR atualizado: 'AINDA NÃO ABERTO' -> 'ABERTO PR #130'.

https://claude.ai/code/session_016crk2XNP846FHdJo6cPEVR
@chatgpt-codex-connector
Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

Copy link
Copy Markdown
Owner Author

@coderabbitai review

Push de 9 fixes em #130 endereçando todos os achados críticos/majors anteriores:

docs/backups/restore-test.sh (refatorado):

  • pg_restore agora captura exit code real (RESTORE_OK), usado como 1ª condição obrigatória no check de sucesso (antes || true mascarava timeouts/falhas).
  • SHA256: subshell + if direto para não ser interrompido por set -e se cd falhar.
  • ls -t … || true para permitir o check [ -z "$LATEST" ].
  • DBNAME quoted em SQL + DROP DATABASE WITH (FORCE) (fallback pg_terminate_backend em PG<13).
  • log() avalia date -Iseconds por linha (era fixo no startup).
  • grep -Ev '(pg_cron|cron\.)' portável.

docs/backups/install-restore-test-cron.sh:

  • Pré-flight valida que o container está rodando e é único antes de instalar.
  • Cron line usa nome do container (não $(docker ps -qf ...)), sobrevivendo a restarts.

docs/backups/README.md:

  • grep -Ev '(pg_cron|cron\.)' no procedure de DR.

docs/types-drift-2026-05/AUDIT_REPORT.md:

  • Senha de DB lê de SUPABASE_DB_PASSWORD via vault (pass/op/.env gitignored), com unset após uso.

docs/session-2026-05-12/SESSION_REPORT.md:

Por favor, confirmar que os achados anteriores estão endereçados.


Generated by Claude Code

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 13, 2026

@adm01-debug, entendido! Disparando review completo para validar os 9 fixes — vou verificar especialmente:

  • RESTORE_OK como condição obrigatória e o tratamento do set -e com subshells
  • Preflight do container no cron installer
  • Remoção de senha hardcoded no AUDIT_REPORT.md via vault
  • Portabilidade do grep -Ev

Aguarde o resultado. 🐇

✅ Actions performed

Full review triggered.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/backups/install-restore-test-cron.sh`:
- Around line 30-35: The current cron presence check uses a too-broad grep for
'restore-test.sh' (if crontab -l 2>/dev/null | grep -qF 'restore-test.sh') which
can produce false positives; update the check to match the full expected cron
line exactly (e.g., use grep -Fx or compare against the complete cron entry
string) so the if block that echoes and exits only runs when the exact cron
entry exists; adjust the subsequent crontab display (crontab -l | grep
restore-test) to show the exact matched line as well.

In `@docs/backups/README.md`:
- Around line 38-39: Os comandos que usam docker ps -qf
name=supabase-backup_backup podem devolver múltiplos containers e quebrar docker
exec/cp; altere cada ocorrência (por exemplo onde aparece docker exec -it
$(docker ps -qf name=supabase-backup_backup) sh e comandos semelhantes) para
selecionar um único container de forma determinística: use um filtro ancorado
com regex (--filter "name=^supabase-backup_backup$") ou use --format '{{.ID}}'
piped a head -n1 (e.g. CONTAINER=$(docker ps -qf "name=^supabase-backup_backup$"
--format '{{.ID}}' | head -n1) && docker exec -it $CONTAINER sh) para garantir
que docker exec/cp opere no container correto.

In `@docs/backups/restore-test.sh`:
- Around line 106-116: The current success condition only checks RESTORE_OK,
TABLE_COUNT and CONTACTS which allows partial restores to pass; update the
conditional that sets STATUS (and the log messages) to also require measured
MESSAGES and PROFILES thresholds (e.g. ensure MESSAGES and PROFILES are >= their
expected minimums) alongside RESTORE_OK, TABLE_COUNT and CONTACTS, and keep the
existing failed branch behavior (log, set STATUS="FAILED", touch failure marker)
so partial restores no longer report as PASSED.

In `@docs/session-2026-05-12/SESSION_REPORT.md`:
- Line 112: The sentence "Revisar este PR quando for aberto e mergear para
`main`." contradicts the documented status "ABERTO" at Line 105; replace that
phrase so it aligns with the current status—e.g., update the sentence to
"Revisar este PR enquanto estiver ABERTO e mergear para `main`." to remove the
temporal mismatch and avoid handoff noise.
- Around line 122-124: O trecho usa o filtro ambíguo `docker ps -qf
name=supabase-backup_backup` que pode retornar múltiplos containers; substitua
esse filtro por um filtro ancorado igual ao usado no installer (ex.: name
anchored with start/end anchors) para garantir correspondência exata do
container supabase-backup_backup antes de executar o docker cp e a chamada a
install-restore-test-cron.sh.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a39b2f4a-7ec7-4992-b6fd-ceb6b5f8564b

📥 Commits

Reviewing files that changed from the base of the PR and between 4ca2f68 and a887ff9.

📒 Files selected for processing (5)
  • docs/backups/README.md
  • docs/backups/install-restore-test-cron.sh
  • docs/backups/restore-test.sh
  • docs/session-2026-05-12/SESSION_REPORT.md
  • docs/types-drift-2026-05/AUDIT_REPORT.md
✅ Files skipped from review due to trivial changes (1)
  • docs/types-drift-2026-05/AUDIT_REPORT.md

Comment on lines +30 to +35
# Verifica se já existe
if crontab -l 2>/dev/null | grep -qF 'restore-test.sh'; then
echo "✅ Cron já instalado:"
crontab -l | grep restore-test
exit 0
fi
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Validação de cron está ampla demais.

No Line [31], buscar só por restore-test.sh pode detectar entrada errada e abortar instalação válida. Compare com a linha completa esperada.

Diff sugerido
-if crontab -l 2>/dev/null | grep -qF 'restore-test.sh'; then
+if crontab -l 2>/dev/null | grep -qF "$CRON_LINE"; then
   echo "✅ Cron já instalado:"
-  crontab -l | grep restore-test
+  crontab -l | grep -F "$CRON_LINE"
   exit 0
 fi
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/backups/install-restore-test-cron.sh` around lines 30 - 35, The current
cron presence check uses a too-broad grep for 'restore-test.sh' (if crontab -l
2>/dev/null | grep -qF 'restore-test.sh') which can produce false positives;
update the check to match the full expected cron line exactly (e.g., use grep
-Fx or compare against the complete cron entry string) so the if block that
echoes and exits only runs when the exact cron entry exists; adjust the
subsequent crontab display (crontab -l | grep restore-test) to show the exact
matched line as well.

Comment thread docs/backups/README.md
Comment on lines +38 to +39
docker exec -it $(docker ps -qf name=supabase-backup_backup) sh

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Comandos de docker ps podem selecionar container errado.

Nos Lines [38], [87] e [89], o filtro sem âncora pode retornar múltiplos IDs e quebrar docker exec/cp no procedimento de DR/deploy.

Diff sugerido
-docker exec -it $(docker ps -qf name=supabase-backup_backup) sh
+docker exec -it $(docker ps -q --filter "name=^/supabase-backup_backup$") sh
@@
-docker cp docs/backups/restore-test.sh \
-  $(docker ps -qf name=supabase-backup_backup):/backups/restore-test.sh
+docker cp docs/backups/restore-test.sh \
+  $(docker ps -q --filter "name=^/supabase-backup_backup$"):/backups/restore-test.sh
@@
-docker exec $(docker ps -qf name=supabase-backup_backup) \
+docker exec $(docker ps -q --filter "name=^/supabase-backup_backup$") \
   chmod +x /backups/restore-test.sh

Also applies to: 86-90

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/backups/README.md` around lines 38 - 39, Os comandos que usam docker ps
-qf name=supabase-backup_backup podem devolver múltiplos containers e quebrar
docker exec/cp; altere cada ocorrência (por exemplo onde aparece docker exec -it
$(docker ps -qf name=supabase-backup_backup) sh e comandos semelhantes) para
selecionar um único container de forma determinística: use um filtro ancorado
com regex (--filter "name=^supabase-backup_backup$") ou use --format '{{.ID}}'
piped a head -n1 (e.g. CONTAINER=$(docker ps -qf "name=^supabase-backup_backup$"
--format '{{.ID}}' | head -n1) && docker exec -it $CONTAINER sh) para garantir
que docker exec/cp opere no container correto.

Comment on lines +106 to +116
# 7. Avaliar sucesso. RESTORE_OK == 1 é condição obrigatória primeiro;
# thresholds são guard adicional contra restore parcial que sobe alguma
# coisa mas não o suficiente para considerar válido.
if [ "$RESTORE_OK" -eq 1 ] && [ "$TABLE_COUNT" -ge 400 ] && [ "$CONTACTS" -ge 10000 ]; then
log "✅ RESTORE TEST PASSOU"
STATUS="PASSED"
else
log "❌ RESTORE TEST FALHOU - exit do pg_restore != 0 ou threshold não atingido"
STATUS="FAILED"
touch "/backups/RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S)"
fi
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Evite PASS em restore parcial.

No Line [109], o sucesso exige só TABLE_COUNT e CONTACTS, apesar de MESSAGES e PROFILES já serem medidos. Isso pode aprovar restore incompleto.

Diff sugerido
-if [ "$RESTORE_OK" -eq 1 ] && [ "$TABLE_COUNT" -ge 400 ] && [ "$CONTACTS" -ge 10000 ]; then
+if [ "$RESTORE_OK" -eq 1 ] \
+  && [ "$TABLE_COUNT" -ge 400 ] \
+  && [ "$CONTACTS" -ge 10000 ] \
+  && [ "$MESSAGES" -ge 1000000 ] \
+  && [ "$PROFILES" -ge 1 ]; then
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# 7. Avaliar sucesso. RESTORE_OK == 1 é condição obrigatória primeiro;
# thresholds são guard adicional contra restore parcial que sobe alguma
# coisa mas não o suficiente para considerar válido.
if [ "$RESTORE_OK" -eq 1 ] && [ "$TABLE_COUNT" -ge 400 ] && [ "$CONTACTS" -ge 10000 ]; then
log "✅ RESTORE TEST PASSOU"
STATUS="PASSED"
else
log "❌ RESTORE TEST FALHOU - exit do pg_restore != 0 ou threshold não atingido"
STATUS="FAILED"
touch "/backups/RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S)"
fi
# 7. Avaliar sucesso. RESTORE_OK == 1 é condição obrigatória primeiro;
# thresholds são guard adicional contra restore parcial que sobe alguma
# coisa mas não o suficiente para considerar válido.
if [ "$RESTORE_OK" -eq 1 ] \
&& [ "$TABLE_COUNT" -ge 400 ] \
&& [ "$CONTACTS" -ge 10000 ] \
&& [ "$MESSAGES" -ge 1000000 ] \
&& [ "$PROFILES" -ge 1 ]; then
log "✅ RESTORE TEST PASSOU"
STATUS="PASSED"
else
log "❌ RESTORE TEST FALHOU - exit do pg_restore != 0 ou threshold não atingido"
STATUS="FAILED"
touch "/backups/RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S)"
fi
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/backups/restore-test.sh` around lines 106 - 116, The current success
condition only checks RESTORE_OK, TABLE_COUNT and CONTACTS which allows partial
restores to pass; update the conditional that sets STATUS (and the log messages)
to also require measured MESSAGES and PROFILES thresholds (e.g. ensure MESSAGES
and PROFILES are >= their expected minimums) alongside RESTORE_OK, TABLE_COUNT
and CONTACTS, and keep the existing failed branch behavior (log, set
STATUS="FAILED", touch failure marker) so partial restores no longer report as
PASSED.


## 🎯 Próximos passos sugeridos para o operador (Joaquim)

1. **Revisar este PR** quando for aberto e mergear para `main`.
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Texto operacional contradiz o status atual do PR.

No Line [112], “quando for aberto” conflita com o status “ABERTO” já documentado no Line [105]. Ajuste para evitar ruído no handoff.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/session-2026-05-12/SESSION_REPORT.md` at line 112, The sentence "Revisar
este PR quando for aberto e mergear para `main`." contradicts the documented
status "ABERTO" at Line 105; replace that phrase so it aligns with the current
status—e.g., update the sentence to "Revisar este PR enquanto estiver ABERTO e
mergear para `main`." to remove the temporal mismatch and avoid handoff noise.

Comment thread docs/session-2026-05-12/SESSION_REPORT.md
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/backups/README.md`:
- Around line 7-16: The fenced code block showing the /backups/ directory
structure is missing a language tag which triggers MD040; update the opening
fence from ``` to ```text in the README's directory tree block so the linter
recognizes it as plain text (the block containing the lines starting with
"/backups/" and entries like "restore-test.sh", "restore-test.log",
"last_error.log").

In `@docs/backups/restore-test.sh`:
- Around line 55-73: The script currently creates a temporary DB (DBNAME) and
TOC files but can leave them orphaned if the script exits early under set -e;
add a trap on EXIT that runs a cleanup function which drops the temporary
database (using the same DBNAME logic: DROP DATABASE IF EXISTS "$DBNAME" with
the FORCE fallback logic already present) and removes the
"/tmp/toc-${DBNAME}.list" and "/tmp/toc-${DBNAME}.filtered" files; ensure the
cleanup function is defined before DB creation and the trap 'trap cleanup EXIT'
is registered immediately after DBNAME is set so it always runs even on early
failures.

In `@docs/session-2026-05-12/SESSION_REPORT.md`:
- Around line 53-61: The fenced code block that begins with "```" and the line
"[2026-05-12T19:54:02+00:00] Resultado:" in SESSION_REPORT.md lacks a language
tag which triggers MD040; update that fence to use a language (e.g., "text") so
it reads "```text" to satisfy the markdown linter and leave the block contents
unchanged.

In `@docs/types-drift-2026-05/AUDIT_REPORT.md`:
- Around line 88-93: Update the comment around SUPABASE_DB_URL / the npx
supabase gen types command to remove the false claim that passing the DB URL via
--db-url prevents the password from appearing in ps; explain that supplying
credentials on the command line (even via an interpolated env var like
SUPABASE_DB_PASSWORD used in SUPABASE_DB_URL) still exposes them in the process
argv, and instead recommend using the supported secure flows such as
--project-id or --local (or other Supabase-authenticated methods) when running
npx supabase gen types typescript so no credentials appear in the command
invocation.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 25a7c594-f56b-416b-94f7-4391735cf63f

📥 Commits

Reviewing files that changed from the base of the PR and between 8555b50 and a887ff9.

📒 Files selected for processing (6)
  • docs/backups/README.md
  • docs/backups/install-restore-test-cron.sh
  • docs/backups/restore-test.sh
  • docs/session-2026-05-12/SESSION_REPORT.md
  • docs/types-drift-2026-05/AUDIT_REPORT.md
  • docs/types-drift-2026-05/missing-tables-from-types.txt

Comment thread docs/backups/README.md
Comment on lines +7 to +16
```
/backups/
├── supabase_selfhosted_YYYYMMDD_HHMMSS.dump # backup oficial automático
├── supabase_selfhosted_YYYYMMDD_HHMMSS.dump.sha256
├── archive/ # históricos pré-migração (não tocar)
├── manual/ # snapshots manuais pré-mudança
├── restore-test.sh # ← este script (deploy de docs/backups/)
├── restore-test.log
└── last_error.log
```
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Bloco de estrutura sem linguagem no fence (MD040).

Adicionar linguagem evita warning de lint.

Diff sugerido
-```
+```text
 /backups/
 ├── supabase_selfhosted_YYYYMMDD_HHMMSS.dump       # backup oficial automático
 ├── supabase_selfhosted_YYYYMMDD_HHMMSS.dump.sha256
 ├── archive/                                        # históricos pré-migração (não tocar)
 ├── manual/                                         # snapshots manuais pré-mudança
 ├── restore-test.sh                                 # ← este script (deploy de docs/backups/)
 ├── restore-test.log
 └── last_error.log
</details>

<!-- suggestion_start -->

<details>
<summary>📝 Committable suggestion</summary>

> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

```suggestion

🧰 Tools
🪛 markdownlint-cli2 (0.22.1)

[warning] 7-7: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/backups/README.md` around lines 7 - 16, The fenced code block showing
the /backups/ directory structure is missing a language tag which triggers
MD040; update the opening fence from ``` to ```text in the README's directory
tree block so the linter recognizes it as plain text (the block containing the
lines starting with "/backups/" and entries like "restore-test.sh",
"restore-test.log", "last_error.log").

Comment on lines +55 to +73
# 3. Criar BD temporário (identificador é seguro: composto só por timestamp).
DBNAME="restore_test_$(date +%Y%m%d_%H%M%S)"
log "Criando BD temporário: $DBNAME"

# DROP com FORCE (PG13+) termina conexões pendentes em vez de falhar.
# Fallback para variante sem FORCE em PG<13: termina backends manualmente.
psql -c "DROP DATABASE IF EXISTS \"$DBNAME\" WITH (FORCE);" >/dev/null 2>&1 \
|| {
psql -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '$DBNAME' AND pid <> pg_backend_pid();" >/dev/null 2>&1 || true
psql -c "DROP DATABASE IF EXISTS \"$DBNAME\";" >/dev/null 2>&1 || true
}
psql -c "CREATE DATABASE \"$DBNAME\";" >/dev/null 2>&1

# 4. Gerar TOC filtrada (sem pg_cron que requer BD chamado postgres).
# `grep -E` com alternação `|` é portável; o antigo `grep -v 'pg_cron\|cron\.'`
# depende de extensão GNU e silenciosamente passa pg_cron em outros greps.
pg_restore -l "$LATEST" > "/tmp/toc-${DBNAME}.list" 2>/dev/null
grep -Ev '(pg_cron|cron\.)' "/tmp/toc-${DBNAME}.list" > "/tmp/toc-${DBNAME}.filtered"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Falta cleanup garantido em falhas intermediárias com set -e.

Se falhar antes da etapa final, o banco temporário e TOCs podem ficar órfãos. Coloque cleanup em trap EXIT para garantir idempotência.

Diff sugerido
 set -e
 
 LOG=/backups/restore-test.log
+DBNAME=""
+TOC_LIST=""
+TOC_FILTERED=""
+
+cleanup() {
+  if [ -n "$DBNAME" ]; then
+    psql -c "DROP DATABASE IF EXISTS \"$DBNAME\" WITH (FORCE);" >/dev/null 2>&1 \
+      || psql -c "DROP DATABASE IF EXISTS \"$DBNAME\";" >/dev/null 2>&1 \
+      || true
+  fi
+  [ -n "$TOC_LIST" ] && rm -f "$TOC_LIST" "$TOC_FILTERED"
+}
+trap cleanup EXIT
@@
 DBNAME="restore_test_$(date +%Y%m%d_%H%M%S)"
@@
-pg_restore -l "$LATEST" > "/tmp/toc-${DBNAME}.list" 2>/dev/null
-grep -Ev '(pg_cron|cron\.)' "/tmp/toc-${DBNAME}.list" > "/tmp/toc-${DBNAME}.filtered"
+TOC_LIST="/tmp/toc-${DBNAME}.list"
+TOC_FILTERED="/tmp/toc-${DBNAME}.filtered"
+pg_restore -l "$LATEST" > "$TOC_LIST" 2>/dev/null
+grep -Ev '(pg_cron|cron\.)' "$TOC_LIST" > "$TOC_FILTERED"
@@
-# 8. Cleanup (idempotente — DROP IF EXISTS WITH FORCE limpa mesmo se algo
-# ficar pendente no BD temporário).
-log "Dropping BD temporário"
-psql -c "DROP DATABASE IF EXISTS \"$DBNAME\" WITH (FORCE);" >/dev/null 2>&1 \
-  || psql -c "DROP DATABASE IF EXISTS \"$DBNAME\";" >/dev/null 2>&1 \
-  || true
-rm -f "/tmp/toc-${DBNAME}.list" "/tmp/toc-${DBNAME}.filtered"
+# 8. Cleanup automático via trap EXIT.
+log "Cleanup automático finalizado"

Also applies to: 118-124

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/backups/restore-test.sh` around lines 55 - 73, The script currently
creates a temporary DB (DBNAME) and TOC files but can leave them orphaned if the
script exits early under set -e; add a trap on EXIT that runs a cleanup function
which drops the temporary database (using the same DBNAME logic: DROP DATABASE
IF EXISTS "$DBNAME" with the FORCE fallback logic already present) and removes
the "/tmp/toc-${DBNAME}.list" and "/tmp/toc-${DBNAME}.filtered" files; ensure
the cleanup function is defined before DB creation and the trap 'trap cleanup
EXIT' is registered immediately after DBNAME is set so it always runs even on
early failures.

Comment on lines +53 to +61
```
[2026-05-12T19:54:02+00:00] Resultado:
- tables públicas: 600
- evolution_contacts: 17.340 (match com produção)
- evolution_messages: 1.838.351
- profiles: 6
- tamanho restaurado: 1921 MB
✅ RESTORE TEST PASSOU (121 segundos)
```
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Bloco de código sem linguagem quebra lint de Markdown (MD040).

Adicione linguagem no fence para manter o lint limpo.

Diff sugerido
-```
+```text
 [2026-05-12T19:54:02+00:00] Resultado:
   - tables públicas: 600
   - evolution_contacts: 17.340 (match com produção)
   - evolution_messages: 1.838.351
   - profiles: 6
   - tamanho restaurado: 1921 MB
 ✅ RESTORE TEST PASSOU (121 segundos)
</details>

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 markdownlint-cli2 (0.22.1)</summary>

[warning] 53-53: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

</details>

</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @docs/session-2026-05-12/SESSION_REPORT.md around lines 53 - 61, The fenced
code block that begins with "" and the line "[2026-05-12T19:54:02+00:00] Resultado:" in SESSION_REPORT.md lacks a language tag which triggers MD040; update that fence to use a language (e.g., "text") so it reads "text" to
satisfy the markdown linter and leave the block contents unchanged.


</details>

<!-- fingerprinting:phantom:poseidon:hawk -->

<!-- This is an auto-generated comment by CodeRabbit -->

Comment on lines +88 to +93
# Monta a URL sem expor a senha em ps/history (interpolação é local ao processo).
SUPABASE_DB_URL="postgresql://supabase_admin:${SUPABASE_DB_PASSWORD}@supabase.atomicabr.com.br:5432/postgres"

# Gerar tipos (passar via --db-url evita que a senha apareça em `ps`).
npx supabase gen types typescript --db-url "$SUPABASE_DB_URL" --schema public > types.new.ts

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

No Supabase CLI, supabase gen types typescript --db-url ...evita mesmo exposição da senha emps? Qual é o método oficial recomendado para gerar types sem secret no argv?

💡 Result:

Sim — passar --db-url postgres://...:[POSTGRES_PASSWORD]@... na linha de comando pode expor a senha em ps (porque o valor completo do argumento costuma ser visível para outros processos/usuários no mesmo host). O método oficial recomendado para gerar types sem colocar secret no argv é não usar --db-url e, em vez disso, gerar via projeto (linked) ou via variáveis/segredos suportados pela CLI/CI: 1) Gerar a partir do projeto Supabase (sem --db-url) - Use --project-id "$PROJECT_REF" (ex.: em CI). A documentação mostra o comando: npx supabase gen types typescript --project-id "$PROJECT_REF" --schema public > database.types.ts [1] - A referência do CLI para supabase gen types lista --project-id como alternativa ao --db-url (ou seja, você não precisa embutir a URL do banco com senha para esse modo) [2]. 2) Se você estiver usando a instância local - Use --local (também sem --db-url com senha): npx supabase gen types typescript --local > database.types.ts [1]. 3) Para evitar senha em argv em CI (quando algum comando precisar de password) - A documentação de CLI indica que, em ambientes como CI, você pode fornecer a senha via variável de ambiente SUPABASE_DB_PASSWORD em vez de prompt/entrada interativa [3]. (Isso evita colocar a senha como argumento de linha de comando.) Portanto: a escolha “oficial” para o seu objetivo (typescript types sem secret no argv) é usar --project-id ou --local, e não --db-url; e, quando for necessário informar senha, use SUPABASE_DB_PASSWORD (variável de ambiente), não --db-url com password na URL [1][2][3].

Citations:


A orientação sobre --db-url é enganosa: a senha continua visível em ps.

A senha passada via --db-url fica exposta no argv do processo e pode ser vista por outros usuários/processos no mesmo host — independente de estar em uma variável. O modo oficial recomendado é usar --project-id (sem credenciais no comando) ou --local, conforme a documentação do Supabase. Corrija o comentário para remover a afirmação falsa sobre proteção em ps e indique o fluxo seguro.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/types-drift-2026-05/AUDIT_REPORT.md` around lines 88 - 93, Update the
comment around SUPABASE_DB_URL / the npx supabase gen types command to remove
the false claim that passing the DB URL via --db-url prevents the password from
appearing in ps; explain that supplying credentials on the command line (even
via an interpolated env var like SUPABASE_DB_PASSWORD used in SUPABASE_DB_URL)
still exposes them in the process argv, and instead recommend using the
supported secure flows such as --project-id or --local (or other
Supabase-authenticated methods) when running npx supabase gen types typescript
so no credentials appear in the command invocation.

- 187 tables existem no BD mas missing no types.ts
- 241 tables no types.ts são obsoletas (não existem mais no BD)
- Análise agrupada por categoria (evolution, bpm, gmail, agent, etc)
- 3 opções de regeneração documentadas com risco/segurança
…ssion report

- fix: AUDIT_REPORT.md estava com conteúdo base64 cru (bug do commit anterior)
- add: docs/backups/restore-test.sh (validado em prod: 121s, 600 tables, 17.340 contacts)
- add: docs/backups/install-restore-test-cron.sh (helper de cron mensal)
- add: docs/backups/README.md (procedure de DR validado)
- add: docs/session-2026-05-12/SESSION_REPORT.md (relatório consolidado da sessão)
restore-test.sh (5 fixes em 1):
- pg_restore: captura exit code real e usa como 1ª condição obrigatória
  no check de sucesso (antes `|| true` mascarava timeouts/falhas).
- SHA256: subshell + if direto para não ser interrompido por `set -e`
  se `cd` falhar antes do bloco de erro.
- `ls` com fallback `|| true` para permitir o check `[ -z $LATEST ]`.
- DBNAME quoted em SQL + DROP DATABASE WITH (FORCE) para evitar
  conexões pendentes no BD temporário derrubarem o cron.
- log() agora avalia `date -Iseconds` por linha (era fixo no startup).
- grep -Ev '(pg_cron|cron\\.)' portável (sem alternação não-POSIX).

install-restore-test-cron.sh:
- pré-flight valida que o container está rodando e é único antes de
  instalar; cron line usa o NOME do container (não `$(docker ps -qf ...)`)
  para sobreviver a restarts que mudam o ID.

docs/backups/README.md:
- grep -Ev '(pg_cron|cron\\.)' no procedure de DR para alinhar com
  o script automatizado.

docs/types-drift-2026-05/AUDIT_REPORT.md:
- senha de DB lê de SUPABASE_DB_PASSWORD via vault (pass/op/.env
  gitignored), com `unset` após uso para não vazar em history/process list.

docs/session-2026-05-12/SESSION_REPORT.md:
- status do PR atualizado: 'AINDA NÃO ABERTO' -> 'ABERTO PR #130'.

https://claude.ai/code/session_016crk2XNP846FHdJo6cPEVR
@adm01-debug adm01-debug force-pushed the feat/audit-types-drift-2026-05 branch from a887ff9 to 3b0bb1f Compare May 20, 2026 10:53
@adm01-debug adm01-debug merged commit 91f0db9 into main May 20, 2026
4 of 10 checks passed
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3b0bb1f623

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +113 to +115
log "❌ RESTORE TEST FALHOU - exit do pg_restore != 0 ou threshold não atingido"
STATUS="FAILED"
touch "/backups/RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S)"
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Return non-zero when restore test is marked failed

When validation fails, this branch only logs and creates RESTORE_TEST_FAILED_*, then the script continues to normal cleanup and exits successfully. That makes callers see a success status even when pg_restore failed or thresholds were not met, so automated schedulers/monitors that rely on process exit code will miss a failed DR test unless they parse marker files manually.

Useful? React with 👍 / 👎.

Comment on lines +71 to +72
pg_restore -l "$LATEST" > "/tmp/toc-${DBNAME}.list" 2>/dev/null
grep -Ev '(pg_cron|cron\.)' "/tmp/toc-${DBNAME}.list" > "/tmp/toc-${DBNAME}.filtered"
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle TOC generation failures before exiting with set -e

After creating the temporary database, pg_restore -l and the TOC filter run without error handling under set -e; if either command fails (e.g., damaged dump or parse error), the script exits immediately before creating a failure marker and before dropping the temp database. This leaves orphan restore_test_* databases and loses the script’s intended failure signaling path for this error class.

Useful? React with 👍 / 👎.

Comment on lines +122 to +124
docker cp docs/backups/restore-test.sh \
$(docker ps -qf name=supabase-backup_backup):/backups/restore-test.sh
bash docs/backups/install-restore-test-cron.sh
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Add executable-step to deployment snippet

This deployment snippet copies restore-test.sh into the container and immediately schedules it, but it omits making the script executable. Since the committed file mode is non-executable and docker cp preserves source permissions, hosts that follow this runbook alone will install a cron job that runs docker exec ... /backups/restore-test.sh and fails with permission errors instead of executing the restore test.

Useful? React with 👍 / 👎.

fi

# Adiciona ao crontab
(crontab -l 2>/dev/null; echo "$CRON_LINE") | crontab -
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Append cron line even when no crontab exists

With set -e enabled, the append command fails on first-time installs: when the user has no crontab yet, crontab -l returns non-zero and the subshell exits before echo "$CRON_LINE" runs, so nothing is piped into crontab -. The script can then report success while leaving the restore job unscheduled.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants