Skip to content

fix(webhook): resolveBestJid deixa de priorizar dígitos-LID sobre telefone real - #130

Merged
adm01-debug merged 2 commits into
mainfrom
fix/resolvebestjid-lid-priority
Sep 2, 2026
Merged

fix(webhook): resolveBestJid deixa de priorizar dígitos-LID sobre telefone real#130
adm01-debug merged 2 commits into
mainfrom
fix/resolvebestjid-lid-priority

Conversation

@adm01-debug

@adm01-debug adm01-debug commented Sep 2, 2026

Copy link
Copy Markdown
Owner

Problema

Follow-up da auditoria do E35 (normalizePhone, PR #120): resolveBestJid usava a mesma regex de "10-15 dígitos" para aceitar tanto telefones E.164 quanto LIDs sem sufixo @lid (que também caem nessa faixa — 14-15 dígitos, mesma heurística já usada em normalizePhone).

Como a resolução é .find() em ordem de posição do array de candidatos (remoteJid antes de remoteJidAlt, etc.), se remoteJid trouxer o LID em dígitos nus e remoteJidAlt trouxer o telefone real, o LID vencia só por estar primeiro no array — não por ser mais confiável. Isso reabre, por uma rota diferente, o mesmo tipo de fragmentação de contato que o E35 fechou em normalizePhone.

Mudança

evolution-helpers.tsresolveBestJid ganha um tier extra: dígitos no formato LID (14-15 dígitos) são deixados para depois de @g.us, ao invés de competir na mesma prioridade que telefones reais (10-13 dígitos):

// ANTES
return valid.find((jid) => jid.includes('@s.whatsapp.net'))
  ?? valid.find((jid) => /^\+?\d{10,15}$/.test(jid))
  ?? valid.find((jid) => jid.includes('@g.us'))
  ?? valid.find((jid) => !jid.includes('@lid'))
  ?? valid[0]
  ?? null;

// DEPOIS
return valid.find((jid) => jid.includes('@s.whatsapp.net'))
  ?? valid.find((jid) => /^\+?\d{10,15}$/.test(jid) && !isLidLengthDigits(jid))
  ?? valid.find((jid) => jid.includes('@g.us'))
  ?? valid.find((jid) => /^\+?\d{10,15}$/.test(jid))
  ?? valid.find((jid) => !jid.includes('@lid'))
  ?? valid[0]
  ?? null;

Diff mínimo — só a função afetada, sem tocar normalizePhone (já corrigido em #120) nem resolveEventJid (só repassa candidatos).

Validação

  • tsc --noEmit: OK
  • node scripts/ci/lint-ratchet.mjs: 0 novas ocorrências
  • supabase/deployment-manifest.json: regenerado
  • vitest.contracts.config.ts: 167/167 passam
  • node --test scripts/ci/*.unit.mjs scripts/edge-deploy/*.unit.mjs: 38/38 passam
  • node scripts/db-audit/supabase-usage-guard.mjs: 0 violações novas

🤖 Generated with Claude Code

https://claude.ai/code/session_018N9zUcTpab3dWsuR3ZSSBj


Summary by cubic

Updates resolveBestJid to distinguish bare 14–15-digit LIDs from real phone numbers. Previously, both shared the same priority, so a LID in remoteJid could beat a real phone in remoteJidAlt based only on candidate order; now 10–13-digit phones are preferred, while LID-length digits fall back after group JIDs to reduce contact fragmentation.

Scope

  • Only resolveBestJid changes behavior; normalizePhone and resolveEventJid remain unchanged.
  • Regenerates supabase/deployment-manifest.json for the updated helper source.

Written for commit 16d3a5e. Summary will update on new commits.

Review in cubic

…efone real

Bug encontrado durante a auditoria do E35 (normalizePhone): resolveBestJid
usava a mesma regex de "10-15 digitos" para aceitar tanto telefones E.164
quanto LIDs sem sufixo @lid (que tambem caem nessa faixa, 14-15 digitos).
Como a busca e por .find() em ordem de posicao do array de candidatos, se
remoteJid trouxer o LID em digitos nus e remoteJidAlt trouxer o telefone
real, o LID vencia so por estar primeiro — nao por ser mais confiavel.

Aplica a mesma heuristica de tamanho que normalizePhone (E35, PR #120) para
excluir digitos no formato LID (14-15 digitos) do tier de prioridade alta,
com fallback para eles apenas depois de tentar @g.us e antes do fallback
generico "nao-@lid".

Validado:
- typecheck (tsc --noEmit): OK
- lint-ratchet: 0 novas ocorrencias
- manifest de deploy: regenerado (supabase/deployment-manifest.json)
- testes de contrato (vitest.contracts.config.ts): 167/167 passam
- guards CI (scripts/ci/*.unit.mjs, scripts/edge-deploy/*.unit.mjs): 38/38 passam
- supabase-usage-guard: 0 violacoes novas

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018N9zUcTpab3dWsuR3ZSSBj
Copilot AI lite review requested due to automatic review settings September 2, 2026 10:14
@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.

@vercel

vercel Bot commented Sep 2, 2026

Copy link
Copy Markdown

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

Project Deployment Actions Updated
zapp_web_v2 Ready Ready Preview Sep 2, 2026 10:18am UTC

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

adm01-debug has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@coderabbitai

coderabbitai Bot commented Sep 2, 2026

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 49 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available. Your 98 included PR review attempts over the past 7 days set your current allowance at 1 review per hour.

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Team

Run ID: 6c3faa71-a760-484a-a2ee-17f563014e9c

📥 Commits

Reviewing files that changed from the base of the PR and between b9ca894 and 16d3a5e.

📒 Files selected for processing (2)
  • supabase/deployment-manifest.json
  • supabase/functions/_shared/evolution-helpers.ts

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

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

A nova função isLidLengthDigits aceita + e pode tratar números E.164 válidos de 14–15 dígitos como “LID”, desfazendo a priorização pretendida em alguns cenários.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

Ajusta a heurística de seleção de JID em webhooks para evitar que LIDs numéricos (14–15 dígitos sem @lid) sejam escolhidos antes de telefones reais, reduzindo fragmentação de contatos no fluxo Evolution.

Changes:

  • Introduz um “tier” extra em resolveBestJid para empurrar dígitos com comprimento típico de LID para depois de @g.us.
  • Atualiza o supabase/deployment-manifest.json para refletir o novo hash/tamanho dos artefatos.
File summaries
File Description
supabase/functions/_shared/evolution-helpers.ts Ajusta a prioridade de seleção de JID para não favorecer LID numérico sobre telefone real.
supabase/deployment-manifest.json Regenera hashes/bytes do manifesto após a mudança em funções Supabase.
Review details
  • Files reviewed: 2/2 changed files
  • Comments generated: 1
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread supabase/functions/_shared/evolution-helpers.ts
Comment thread supabase/functions/_shared/evolution-helpers.ts

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

adm01-debug has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@adm01-debug
adm01-debug merged commit bcd90d5 into main Sep 2, 2026
13 checks passed
@adm01-debug
adm01-debug deleted the fix/resolvebestjid-lid-priority branch September 2, 2026 10:23
adm01-debug pushed a commit that referenced this pull request Sep 2, 2026
…alogo/manifest com main (P2)

P1 (cubic): a excecao de 20260901200001 usava kind ledger-divergence/pinned-replay,
mas o ledger_sql_sha256 e SHA256("") — o ledger historico nao tem statements
(stmts_count=NULL, confirmado ao vivo). O branch pinned-replay do guard falha
incondicionalmente quando ledgerSql e vazio ("excecao pinned-replay exige
ledgerSql canonico nao vazio"), entao essa excecao deixava o step 7 vermelho
em vez de corrigi-lo. Troca para ledger-only/name-and-file-pinned, o kind
correto para ledger sem SQL/hash algum (so pina nome+arquivo) — mesmo padrao
ja usado nas outras excecoes comment-only deste arquivo.

P2 (cubic + Copilot): dedup_baseline_20260901 estava documentada em
schema-catalog.json/schema-manifest.json/types.ts sem migration correspondente
em supabase/migrations/. A tabela ja foi dropada (0 linhas, artefato de
auditoria pontual, confirmado ao vivo). supabase/schema-catalog.json,
supabase/schema-manifest.json e src/integrations/supabase/types.ts desta PR
estavam desatualizados desde 01/09 (antes do merge de #120/#125/#130); main ja
teve esses artefatos resincronizados pelo workflow automation/types-sync hoje
(02/09). Restaura os 3 arquivos para a versao atual de main em vez de tentar
reconciliar o diff antigo — nenhuma mudanca de schema nesta PR justifica um
snapshot proprio, e main ja e a fonte de verdade mais fresca.

Validado:
- node scripts/db-audit/check-migration-drift.mjs (offline): OK, 326 arquivos validos
- node --test scripts/db-audit/*.test.mjs: 118/118 passam
- node scripts/db-audit/supabase-usage-guard.mjs: 0 violacoes novas
- Confirmado ao vivo: supabase_migrations.schema_migrations.statements = NULL
  para 20260901200001; dedup_baseline_20260901 nao existe em information_schema.tables

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018N9zUcTpab3dWsuR3ZSSBj
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.

3 participants