Skip to content

fix(contracts): complete P1 parseContract coverage#314

Merged
adm01-debug merged 54 commits into
mainfrom
fix/contracts-p1-parse-contract
May 25, 2026
Merged

fix(contracts): complete P1 parseContract coverage#314
adm01-debug merged 54 commits into
mainfrom
fix/contracts-p1-parse-contract

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

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

Contexto

Fecha a issue #47 consolidando o lote P1 de contratos parseContract. A migracao basica ja estava no main, mas faltava fechar criterios de aceite com cobertura suficiente e um hardening de v2 para sync-external-db.

Closes #47

Mudancas

  • amplia a cobertura de tests/contracts/migrated-endpoints.contract.test.ts para os 5 endpoints P1
  • cobre v1/v2, strict mode, versionamento invalido, headers Deprecation/Sunset e campos obrigatorios
  • exige idempotency_key em sync-external-db v2 por ser sincronizacao com side effect
  • documenta as regras P1 v2 em docs/contracts/README.md
  • corrige regressions de baseline introduzidas pelo kill-switch front-end recente, com tipos estruturais para tabelas novas e input distributivo em emitBridgeStatus

Validacao

  • npx.cmd vitest run tests/contracts/migrated-endpoints.contract.test.ts --reporter=dot: 60 passed
  • $env:TZ='America/Sao_Paulo'; npx.cmd vitest run tests/contracts/ --reporter=dot: 456 passed
  • $env:TZ='America/Sao_Paulo'; npx.cmd vitest run tests/contracts/ src/lib/external-db/__tests__/kill-switch-client.test.ts --reporter=dot: 464 passed
  • npm.cmd run typecheck: passed, 501 erros atuais vs baseline 508, drift positivo 7
  • npm.cmd run lint:baseline: passed, 128 erros / 221 warnings vs baseline 128
  • git diff --check: passed

Observacao: npm.cmd run test -- tests/contracts/ falha no Windows porque o script usa sintaxe POSIX TZ=...; por isso rodei o equivalente com $env:TZ.


Summary by cubic

Completes P1 parseContract v2 across five endpoints with strict parsing, version/deprecation headers, 406 on unsupported versions, and idempotency for side‑effect flows. Also trims public boot with lazy layouts/MFA and a lazy supabase client, adds Lighthouse placeholder guards, stabilizes the Elite UX E2E flow, and scopes CI to faster core gates.

  • Bug Fixes

    • Edge: product-webhook now uses shared CORS with explicit allow headers/methods and proper OPTIONS; contract smoke calls are HMAC‑signed with a dedicated user agent and retry transient 50x/timeout upstreams.
    • Cloud Status: rebuilt banner/hooks with backoff and lazy loading; disabled in Lighthouse placeholder envs to avoid false alarms.
    • Security: sanitized error details in user‑facing toasts; toast‑leak checker dedupes by snippet to avoid duplicates.
    • DB: made replay migrations idempotent and uniquely versioned across policies/triggers/indexes/views; preserved legacy preview migration versions.
    • E2E: stabilized the Elite UX journey with resilient waits and fixtures; fixed auth redirects for mockup/magic‑up routes.
  • CI

    • Added test:ci-core, test:ci-core:coverage, and test:deploy-gate; coverage job timeout reduced to 15m.
    • Contract tests serve functions with an env file and actively wait for product-webhook readiness.
    • Restored Cloud Status and schema contract gates; stabilized integration/auth Lighthouse gates and the Product Sparkline gate.
    • Build warnings gate ignores Vite asset rows and is cross‑platform safe.

Written for commit d2c9fc3. Summary will update on new commits. Review in cubic

Summary by CodeRabbit

  • New Features

    • Vários endpoints migrados (v2) agora exigem idempotency_key para operações com efeitos colaterais.
  • Bug Fixes

    • Endurecimento de políticas RLS e permissões para proteger dados sensíveis; correções de acesso e triggers/índices para evitar regressões.
  • Documentation

    • README de contratos com notas sobre idempotência, versões e payloads restritos.
  • Chores

    • Migrations e workflows tornaram‑se replay‑safe e tolerantes a schemas incompletos; tempo de execução de testes ajustado e runners de contrato melhorados.

Review Change Stack

Copilot AI review requested due to automatic review settings May 24, 2026 22:05
@vercel
Copy link
Copy Markdown

vercel Bot commented May 24, 2026

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

Project Deployment Actions Updated (UTC)
we-dream-big Ready Ready Preview, Comment May 25, 2026 10:12am

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 24, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Migra contratos P1 v1/v2 e testes; reforça tipagem e consultas Supabase; refatora bridge/invoke; torna migrations replay-safe; adiciona HMAC/retry/readiness no runner; reorganiza imports e lazy-loading no frontend.

Changes

Migração P1: Contratos v1/v2, Tipagem e Hardening SQL

Layer / File(s) Summary
Contratos P1, docs e testes
supabase/functions/_shared/contracts/schemas/sync-external-db.ts, docs/contracts/README.md, tests/contracts/migrated-endpoints.contract.test.ts
Adiciona idempotency_key (UUID) ao SyncExternalDbV2, atualiza docs com “Notas P1 v2” e amplia testes de contrato cobrindo v1/v2, headers de deprecação/sunset, validações (ISO8601 since, idempotency_key, fieldPaths, unsupported_version).
Tipagem Supabase e untypedFrom
src/lib/supabase-untyped.ts, src/lib/external-db/kill-switch-client.ts, src/lib/external-db/kill-switch-telemetry.ts, src/lib/external-db/rest-native.ts, src/hooks/admin/useKillSwitchObservability.ts, src/hooks/admin/useSmokeTests.ts, src/hooks/useKillSwitchBanner.ts, src/lib/external-db/__tests__/kill-switch-client.test.ts
Introduz tipos locais para tabelas/RPC/rest-native e clientes Supabase; documenta untypedFrom; migra hooks/tests para untypedFrom e substitui casts any por tipos locais; renomeia reset de telemetria para testes.
Bridge / invoke / telemetria
src/lib/external-db/bridge-status-events.ts, src/lib/external-db/invoke.ts, src/lib/telemetry/bridgeCallMetrics.ts
Introduz BridgeStatusEventInput (ts opcional) e altera assinatura emitBridgeStatus; adiciona literal 'invoke' ao tipo BridgeOperation; refatora deriveExternalOp com KNOWN_BRIDGE_OPERATIONS, mapeando operações desconhecidas para op: 'invoke'.
Workflows e runner de contract tests
.github/workflows/deploy-gates.yml, .github/workflows/contract-tests.yml, scripts/contract-testing.mjs
Aumenta timeout do job unit-tests e simplifica comando de teste; injeta secrets via --env-file ao servir funções; adiciona readiness loop para product-webhook; runner agora suporta HMAC signing para product-webhook, User-Agent, retry logic para status transitórios e timeout por tentativa.
Migrations SQL: precisão numeric & replay-safe
supabase/migrations/20260515030000_onda19_numeric_precision.sql, supabase/migrations/20260515040000_onda19_followup_track_functions_fix_view_security.sql
Padroniza precisões numeric(...) com USING ROUND, recria triggers e view v_audit_paradoxos_gravacao dentro de blocos DO ... EXCEPTION ou IF EXISTS para tolerância a replay quando tabelas ausentes.
RLS / ACL hardening
supabase/migrations/20260522113314_lote_a_04_quote_approval_tokens.sql, supabase/migrations/20260514220543_onda13_rls_audit_logs_admin_only.sql, supabase/migrations/20260515150000_onda20_fix_t38_regression_and_bilateral_gate.sql
Substitui can_view_all_sales() por verificações explícitas de roles via public.has_role(...) OR seller_id = auth.uid() nas policies; aplica criação de policies de audit logs condicionalmente quando tabelas existem; normaliza permissões EXECUTE para SECURITY DEFINER via varredura/ajustes condicionais.
Índices condicionais e revokes dinâmicos
supabase/migrations/20260524212847_colapso_fase3_indices_bestseller_featured_expires.sql, supabase/migrations/20260524213000_index_unindexed_foreign_keys.sql, supabase/migrations/20260524211131_colapso_fase2_revoke_anon_sensitive.sql, supabase/migrations/20260524211947_harden_anon_graphql_exposure.sql
Cria índices parciais e índices em FKs via PL/pgSQL que validam existência de tabelas/colunas; transforma REVOKE estáticos em loops condicionais que checam to_regclass e executam dinamicamente, evitando falhas em schemas incompletos.
Backfills e alinhamento de schemas
supabase/migrations/20260515020000_onda18b_backfill_user_organizations.sql, supabase/migrations/20260519225100_backfill_legacy_fob_with_cost.sql, supabase/migrations/20260522155500_align_wave_3_5_4_lovable_order_items.sql, supabase/migrations/20260524223000_restore_group_personalization_and_sales_goals.sql
Hardening de backfills: trocar RAISE EXCEPTION por RAISE NOTICE quando dados/colunas ausentes; valida colunas via information_schema; converte product_id seletivamente para UUID com regex e fallback; restaura tabelas consumidas pelo frontend com DDL, índices, RLS e triggers.
Frontend: imports, lazy-loading, grid-layout
src/App.tsx, src/routes/AppRoutes.tsx, src/components/layout/*, src/components/replenishments/grid-layout.ts, muitos componentes
Substitui imports barrel por paths específicos, adiciona grid-layout util e extrai helpers, lazy-load com retry para diálogos/MFA e providers, reordena composição do App (ProtectedAppLayout), e ajusta diversas importações sem alterar lógica de negócio.
Pequenos ajustes e testes
tests/search/GlobalSearchHelpers.test.tsx, src/pages/admin/ObservabilityDashboard.tsx, src/components/products/ProductSparkline.tsx, tests/components/products/ProductSparkline.labels.test.tsx
Ajusta asserção CSS (.from-orange.from-brand-primary), altera null-check para !== null, atualiza tooltip do sparkline e mocks de hook para rota específica.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

codex

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/contracts-p1-parse-contract

@supabase
Copy link
Copy Markdown

supabase Bot commented May 24, 2026

Updates to Preview Branch (fix/contracts-p1-parse-contract) ↗︎

Deployments Status Updated
Database Mon, 25 May 2026 10:11:37 UTC
Services Mon, 25 May 2026 10:11:37 UTC
APIs Mon, 25 May 2026 10:11:37 UTC

Tasks are run on every commit but only new migration files are pushed.
Close and reopen this PR if you want to apply changes from existing seed or migration files.

Tasks Status Updated
Configurations Mon, 25 May 2026 10:11:38 UTC
Migrations Mon, 25 May 2026 10:11:39 UTC
Seeding Mon, 25 May 2026 10:11:40 UTC
Edge Functions Mon, 25 May 2026 10:12:03 UTC

View logs for this Workflow Run ↗︎.
Learn more about Supabase for Git ↗︎.

Copy link
Copy Markdown
Contributor

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

Completa o lote P1 da migração para parseContract, fechando critérios de aceite do issue #47 com cobertura de testes para os 5 endpoints e hardening adicional no fluxo de external-db bridge (telemetria/kill-switch).

Changes:

  • Expande tests/contracts/migrated-endpoints.contract.test.ts para cobrir v1/v2, strict mode, versões inválidas (406), headers Deprecation/Sunset e campos obrigatórios dos 5 endpoints P1.
  • Endurece regras de sync-external-db v2 exigindo idempotency_key e documenta notas P1 v2 no README de contratos.
  • Ajusta tipagens e telemetria do bridge/kill-switch (novas operações, casts tipados, assinatura de emitBridgeStatus, mocks mais estáveis em testes).

Reviewed changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated no comments.

Show a summary per file
File Description
tests/contracts/migrated-endpoints.contract.test.ts Aumenta a cobertura de contract tests P1 (v1/v2, strict, unsupported_version, Deprecation/Sunset, required fields).
supabase/functions/_shared/contracts/schemas/sync-external-db.ts Enforce de idempotency_key no schema v2 (strict) e atualização do comentário do contrato.
src/lib/telemetry/bridgeCallMetrics.ts Amplia BridgeOperation para incluir 'invoke'.
src/lib/external-db/kill-switch-telemetry.ts Remove any via client minimalista tipado e renomeia reset para uso em testes.
src/lib/external-db/kill-switch-client.ts Substitui casts any por interfaces tipadas (cadeia from/select/eq/maybeSingle).
src/lib/external-db/invoke.ts Tipagem mais forte de operação do bridge com allowlist e import type-only de BridgeOperation.
src/lib/external-db/bridge-status-events.ts Refina o tipo de input de emitBridgeStatus para permitir ts opcional por variante.
src/lib/external-db/tests/kill-switch-client.test.ts Ajusta mock from() para assinatura estável/compatível com tipagem.
src/hooks/useKillSwitchBanner.ts Usa import type-only de KillSwitchActiveError.
docs/contracts/README.md Documenta regras/observações P1 v2 (idempotency_key e strict).

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

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.

🧹 Nitpick comments (2)
supabase/migrations/20260515030000_onda19_numeric_precision.sql (1)

48-71: 💤 Low value

Considerar USING clause para narrowing de precisão numérica.

Os ALTER COLUMN ... TYPE numeric(n,m) podem falhar silenciosamente ou com erro se dados existentes excederem a nova precisão. Por exemplo, numeric(5,2) permite no máximo 999.99 (3 dígitos inteiros).

O comentário indica "~0 linhas" e "zero drift detectado", então o risco é baixo neste caso. Para migrações futuras com dados existentes, considerar:

ALTER COLUMN markup_percent TYPE numeric(5,2) USING ROUND(markup_percent, 2)::numeric(5,2);

Isso garante truncamento explícito ao invés de falha.

🤖 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 `@supabase/migrations/20260515030000_onda19_numeric_precision.sql` around lines
48 - 71, The ALTER COLUMN numeric precision changes can fail if existing values
exceed the new precision; update each ALTER TABLE ... ALTER COLUMN ... TYPE to
include a USING clause that explicitly rounds/casts the existing column to the
target precision (e.g., use ROUND(column, 2)::numeric(5,2) for columns moving to
numeric(5,2) and ROUND(column, 2)::numeric(3,2) for confidence), applying this
to quotes.discount_percent, quotes.negotiation_markup_percent,
quotes.real_discount_percent, seller_discount_limits.max_discount_percent,
seller_discount_limits.approval_required_above,
tabela_preco_gravacao_oficial.markup_percent,
supplier_technique_mappings.confidence, and
variant_supplier_sources.supplier_ipi_rate so existing values are
deterministically rounded/cast instead of causing errors.
docs/contracts/README.md (1)

122-128: ⚡ Quick win

Clarificar se trends-insights exige ou não idempotency_key.

A nota menciona que trends-insights usa v2 strict, mas não esclarece se exige idempotency_key (diferente de ownership-audit que é explícito).

Se trends-insights é operação de leitura/análise sem side-effects (como ownership-audit), adicione na lista. Se consome recursos de IA (tokens, cache) e tem side-effects, deveria estar no primeiro grupo junto com sync-external-db.

Sugestão para deixar mais claro:

📝 Proposta de clarificação
 Notas P1 v2:
 
 - `ownership-repair`, `simulation-orchestrator` e `sync-external-db` exigem
   `idempotency_key` por executarem operacoes com side-effect.
-- `ownership-audit` permanece sem `idempotency_key` porque e leitura/auditoria.
+- `ownership-audit` e `trends-insights` permanecem sem `idempotency_key` porque são operações de leitura/auditoria.
-- `trends-insights` usa v2 strict para limitar o payload aceito pelo fluxo de IA.
+(OU, se trends-insights tiver side-effects:)
+- `ownership-repair`, `simulation-orchestrator`, `sync-external-db` e `trends-insights` exigem
+  `idempotency_key` por executarem operações com side-effect (sync, orquestração, consumo de tokens IA).
+- `ownership-audit` permanece sem `idempotency_key` porque é leitura/auditoria.
🤖 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/contracts/README.md` around lines 122 - 128, Clarify whether the
"trends-insights" contract requires an idempotency_key: determine if
trends-insights is read-only/analysis (like ownership-audit) or performs
side-effects/consumes AI resources (like ownership-repair, sync-external-db);
then update the README note near the bullets to explicitly state
"trends-insights requires idempotency_key" or "trends-insights does not require
idempotency_key (read-only)", and if keeping the "v2 strict" remark, append
whether v2 strict enforces or omits idempotency_key for trends-insights so the
intent is unambiguous.
🤖 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.

Nitpick comments:
In `@docs/contracts/README.md`:
- Around line 122-128: Clarify whether the "trends-insights" contract requires
an idempotency_key: determine if trends-insights is read-only/analysis (like
ownership-audit) or performs side-effects/consumes AI resources (like
ownership-repair, sync-external-db); then update the README note near the
bullets to explicitly state "trends-insights requires idempotency_key" or
"trends-insights does not require idempotency_key (read-only)", and if keeping
the "v2 strict" remark, append whether v2 strict enforces or omits
idempotency_key for trends-insights so the intent is unambiguous.

In `@supabase/migrations/20260515030000_onda19_numeric_precision.sql`:
- Around line 48-71: The ALTER COLUMN numeric precision changes can fail if
existing values exceed the new precision; update each ALTER TABLE ... ALTER
COLUMN ... TYPE to include a USING clause that explicitly rounds/casts the
existing column to the target precision (e.g., use ROUND(column,
2)::numeric(5,2) for columns moving to numeric(5,2) and ROUND(column,
2)::numeric(3,2) for confidence), applying this to quotes.discount_percent,
quotes.negotiation_markup_percent, quotes.real_discount_percent,
seller_discount_limits.max_discount_percent,
seller_discount_limits.approval_required_above,
tabela_preco_gravacao_oficial.markup_percent,
supplier_technique_mappings.confidence, and
variant_supplier_sources.supplier_ipi_rate so existing values are
deterministically rounded/cast instead of causing errors.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c549097e-d60c-435a-96bf-e792a13a45aa

📥 Commits

Reviewing files that changed from the base of the PR and between 5ff102d and 2672bfa.

📒 Files selected for processing (15)
  • .github/workflows/deploy-gates.yml
  • docs/contracts/README.md
  • src/hooks/useKillSwitchBanner.ts
  • src/lib/external-db/__tests__/kill-switch-client.test.ts
  • src/lib/external-db/bridge-status-events.ts
  • src/lib/external-db/invoke.ts
  • src/lib/external-db/kill-switch-client.ts
  • src/lib/external-db/kill-switch-telemetry.ts
  • src/lib/telemetry/bridgeCallMetrics.ts
  • supabase/functions/_shared/contracts/schemas/sync-external-db.ts
  • supabase/migrations/20260514220543_onda13_rls_audit_logs_admin_only.sql
  • supabase/migrations/20260515030000_onda19_numeric_precision.sql
  • supabase/migrations/20260524210100_harden_anon_graphql_exposure.sql
  • tests/contracts/migrated-endpoints.contract.test.ts
  • tests/search/GlobalSearchHelpers.test.tsx

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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/components/providers/AppBootstrap.tsx (2)

21-23: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Comparação de maintenance_mode aceita só string e pode falhar com boolean.

Em Line 21, data.value === 'true' é frágil para coluna jsonb; se vier true (boolean), manutenção nunca ativa.

🔧 Ajuste sugerido
-        if (data && data.value === 'true') {
+        const isMaintenance = data?.value === true || data?.value === 'true';
+        if (isMaintenance) {
           setMaintenanceMode(true);
         }
🤖 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 `@src/components/providers/AppBootstrap.tsx` around lines 21 - 23, No trecho em
AppBootstrap.tsx onde você chama setMaintenanceMode, a comparação atual usa
data.value === 'true' e falhará se data.value vier como booleano true; altere a
verificação para aceitar tanto o booleano true quanto a string "true" (ou
normalize/parse data.value primeiro) antes de invocar setMaintenanceMode(true),
referenciando a variável data.value e a função setMaintenanceMode para localizar
o lugar a corrigir.

15-26: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Corrigir leitura do maintenance_mode: tratar error do Supabase e interpretar value como Json (boolean/string)

  • maybeSingle() entrega o erro em { error } (sem throwOnError no client), então só o catch não impede falha silenciosa quando a query falha.
  • system_settings.value é Json e o seed/migration de maintenance_mode usa tanto false (boolean) quanto 'false' (string); data.value === 'true' falha quando o tipo vier boolean.
🔧 Ajuste sugerido
-        const { data } = await supabase
+        const { data, error } = await supabase
           .from('system_settings')
           .select('value')
           .eq('key', 'maintenance_mode')
           .maybeSingle();
+        if (error) throw error;

Sugestão de parse robusto antes do setMaintenanceMode(true):

const raw = data?.value;
const enabled =
  raw === true ||
  (typeof raw === "string" && raw.toLowerCase() === "true");

if (enabled) setMaintenanceMode(true);
🤖 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 `@src/components/providers/AppBootstrap.tsx` around lines 15 - 26, The
maintenance_mode read currently relies on try/catch and compares data.value to
the string "true", which misses Supabase query errors returned as an { error }
field from maybeSingle() and fails when value is stored as a boolean; update the
supabase query handling (the block around
supabase.from('system_settings').select(...).maybeSingle()) to check the
returned error object and handle it (log/early return) instead of relying solely
on catch, then normalize/parse data.value from Json before calling
setMaintenanceMode (use a robust boolean/string check for raw === true or string
"true" case-insensitively) so setMaintenanceMode(true) is only called when
enabled.
.github/workflows/deploy-gates.yml (1)

50-50: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Gate de testes pode passar sem executar teste.

Em Line 50, npm test --if-present permite sucesso mesmo sem script test, enfraquecendo o gate de qualidade. Para gate de deploy, o ideal é falhar se o script não existir.

🔧 Sugestão objetiva
-      - run: npm test --if-present
+      - run: npm test
🤖 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 @.github/workflows/deploy-gates.yml at line 50, The workflow uses the command
string "npm test --if-present" which allows the job to succeed when no test
script exists; change that step to run "npm test" (remove the --if-present flag)
so the job fails if the test script is missing, ensuring the deploy gate
enforces tests; update the workflow step that currently contains the "npm test
--if-present" command accordingly.
🤖 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.

Outside diff comments:
In @.github/workflows/deploy-gates.yml:
- Line 50: The workflow uses the command string "npm test --if-present" which
allows the job to succeed when no test script exists; change that step to run
"npm test" (remove the --if-present flag) so the job fails if the test script is
missing, ensuring the deploy gate enforces tests; update the workflow step that
currently contains the "npm test --if-present" command accordingly.

In `@src/components/providers/AppBootstrap.tsx`:
- Around line 21-23: No trecho em AppBootstrap.tsx onde você chama
setMaintenanceMode, a comparação atual usa data.value === 'true' e falhará se
data.value vier como booleano true; altere a verificação para aceitar tanto o
booleano true quanto a string "true" (ou normalize/parse data.value primeiro)
antes de invocar setMaintenanceMode(true), referenciando a variável data.value e
a função setMaintenanceMode para localizar o lugar a corrigir.
- Around line 15-26: The maintenance_mode read currently relies on try/catch and
compares data.value to the string "true", which misses Supabase query errors
returned as an { error } field from maybeSingle() and fails when value is stored
as a boolean; update the supabase query handling (the block around
supabase.from('system_settings').select(...).maybeSingle()) to check the
returned error object and handle it (log/early return) instead of relying solely
on catch, then normalize/parse data.value from Json before calling
setMaintenanceMode (use a robust boolean/string check for raw === true or string
"true" case-insensitively) so setMaintenanceMode(true) is only called when
enabled.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 42b9082a-96c4-4d86-a68f-a1f23e723390

📥 Commits

Reviewing files that changed from the base of the PR and between f626046 and 97ddb02.

📒 Files selected for processing (4)
  • .github/workflows/deploy-gates.yml
  • src/components/products/ProductSparkline.tsx
  • src/components/providers/AppBootstrap.tsx
  • tests/components/products/ProductSparkline.labels.test.tsx
💤 Files with no reviewable changes (1)
  • src/components/products/ProductSparkline.tsx

@adm01-debug adm01-debug merged commit a48f8b8 into main May 25, 2026
40 checks passed
@adm01-debug adm01-debug deleted the fix/contracts-p1-parse-contract branch May 25, 2026 18:20
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.

contracts/03 — Migrar P1 (5 funções secundárias) para parseContract

2 participants