← Back to Pull requests

chore(pacote): integra 20 PRs aprovadas num único merge #3035

Merged
adm01-debug merged 164 files (19554 lines) on Nov 13, 2026 16:27 UTC
View on GitHub
adm01-debug adm01-debug commented on Nov 13, 2026 13:43 UTC
Author

Por quê


Com strict=true cada merge deixava as outras ~20 PRs BEHIND e o CI rodava de novo em todas (fila de horas). O dono aprovou juntar as PRs prontas num pacote único: um CI, um merge, um deploy.

PRs incluídas (merge na ordem, sem squash, histórico preservado)


#3030 · #3011 · #3009 · #3012 · #3025 · #3026 · #3022 · #3031 · #2992 · #2994 · #2995 · #2997 · #2818 · #3019 · #3021 · #2932 · #2998 · #2970 · #2553 · #2556

Também cobertas (conteúdo já dentro da #3030/#3031): #3008, #3020, #2999, #3024, #2993.

Ficaram FORA de propósito: #2996, #3013, #3014 (têm migration — vão sozinhas e são aplicadas depois pelo fluxo de banco.md); #2555 (regressão do "Retomar"); #2894, #2838, #2943, #2971, #2981.

Conflitos resolvidos à mão


  • src/components/catalog/WhatsAppTemplatesManager.tsx (#3011 × #3030): união — ficam os botões "Templates na Meta" (MetaTemplatesDialog) e "Enviar template aprovado" (SendTemplateDialog), com os estados metaAberto e templateParaEnviar.

  • src/hooks/connections/useConnectionOptions.ts (#3011 × #3030): versão da #3011, useConnectionOptions(enabled = true, { onlyConnected = false } = {}); sem a opção o comportamento é o da main. queryKey separa connected/all.

  • src/components/calls/NewCallPanel.tsx (#2994 × #3030): união — useCallChannels() (ligar pelo WhatsApp) + reconectarLinha de useCallSession().

  • supabase/deployment-manifest.json: regenerado com node scripts/edge-deploy/generate-manifest.mjs; --check OK.
  • Workflow tocado


    .github/workflows/ci.yml: +1 linha (#2932) que registra scripts/eslint/no-secret-compare.unit.mjs no job de testes Node — só acrescenta teste. .env.ci.local.example novo (#2970), sem valores.

    Verificado localmente no HEAD adf218cf7 (main atual é ancestral)


    | Passo | Resultado |
    |---|---|
    | tsc -p tsconfig.app.json / e2e | exit 0 / exit 0 |
    | typecheck-ratchet / lint-ratchet | exit 0 / exit 0 |
    | manifest --check / test-inventory / contracts | exit 0 |
    | node --test scripts/ci/*.unit.mjs | 7187 testes, 7185 pass, 0 fail |
    | vitest completo | 1890 arquivos, 16095 passed, 0 failed |
    | deno check + deno test das edges | exit 0 · 2413 passed, 0 failed |
    | vite build | exit 0 |

    Nenhum arquivo de teste removido nem .skip/.only novo; nenhum arquivo de teste com menos asserções que na main. Os 6 títulos de teste que mudaram são reescritas de comportamento (relatório da campanha concluída, X163) ou trocas de lista colada por leitura do fonte (useEvolutionMessaging.test.ts: a lista colada de 108 ações não existia — o roteador da main tem 58; agora o teste lê o fonte real, 74 ações no pacote).

    🤖 Generated with Claude Code

    https://claude.ai/code/session_01RfQzo5V5pKsBWff8aWzH4j

    Diff: 19554 lines (+15077 / -4477) across 164 files Reviewer: adm01-debug Review duration: 163m
    All Vouch review confidence checks passed
    Residual risk 0.48 = Change Risk (0.91) × (1 − Review Confidence (0.47)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.91 · 19554 lines diff across 164 files
    0.91
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.52 · 5 substantive comment(s)
    0.52
    Model 3 · Review Timing & Attention
    Session adequacy: 33% · Reviewer familiarity: 50%
    47%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Mass File Touch mass_file_touch
    0.080
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    11 items
    vercel[bot] vercel[bot] commented on Nov 13, 2026 13:43 UTC
    Bot

    [vc]: #CJz9cx+O1pOne7of1meJZT01KxiSAb1KN4R8/r/KH20=:eyJpc01vbm9yZXBvIjp0cnVlLCJ0eXBlIjoiZ2l0aHViIiwicHJvamVjdHMiOlt7Im5hbWUiOiJ6YXBwX3dlYl92MiIsInByb2plY3RJZCI6InByal9KNHdiOGVneno4aUwxQ0puU09YSkR0cW5idlJwIiwibGl2ZUZlZWRiYWNrIjp7InJlc29sdmVkIjowLCJ1bnJlc29sdmVkIjowLCJ0b3RhbCI6MCwibGluayI6IiJ9LCJpbnNwZWN0b3JVcmwiOiJodHRwczovL3ZlcmNlbC5jb20vanVjYTEvemFwcF93ZWJfdjIvRm5pVU44eHBKQkRITXB0RkhwdHExU3NTYUpZVCIsInByZXZpZXdVcmwiOiJ6YXBwd2VidjItZ2l0LWNsYXVkZS1jaG9yZS1wYWNvdGUtbWVyZ2UtMjYxMTEzLTEzMDItanVjYTEudmVyY2VsLmFwcCIsIm5leHRDb21taXRTdGF0dXMiOiJJR05PUkVEIiwicm9vdERpcmVjdG9yeSI6bnVsbH1dfQ==
    The latest updates on your projects. Learn more about Vercel for GitHub.

    <details><summary>1 Skipped Deployment</summary>

    | Project | Deployment | Actions | Updated |
    | :--- | :----- | :------ | :------ |
    | <a href="https://vercel.com/juca1/zapp_web_v2"><sup><img src="https://vercel.com/api/www/avatar?projectId=prj_J4wb8egzz8iL1CJnSOXJDtqnbvRp&teamId=team_QyN41X0q8hrqhW80AwokbFLv&s=32" width="16" height="16" align="middle" alt="" /></sup></a> zapp_web_v2 | !Ignored Ignored | Preview | <relative-time datetime="2026-11-13T15:16:45.897Z">Nov 13, 2026 3:16pm UTC</relative-time> |
    </details>

    qodo-code-review[bot] qodo-code-review[bot] commented on Nov 13, 2026 13:43 UTC
    Bot

    <!-- qodo:billing-blocked -->

    ⓘ Qodo reviews are paused because your trial has ended. Ask your workspace admin to add credits to resume reviews. Manage billing

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 13, 2026 13:43 UTC
    Bot

    <!-- codex-pull-request-review-summary -->
    <!-- codex-review-state:v1 {"code_review":{"commit_sha":"adf218cf7fc6346fc13a59fcff50419393818c26","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} -->

    <details>
    <summary><strong>Codex Review Summary</strong>: ✅ Completed</summary>

    This comment shows the latest Codex review activity on this pull request.

    | Review | Status | Commit | Review trigger |
    | --- | --- | --- | --- |
    | 📝 Code Review | ✅ Completed <relative-time datetime="2026-11-13T13:48:30.288543Z">2026-11-13T13:48:30.288543Z</relative-time> | adf218c | PR opened |

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    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" or "@codex security review".
  • Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

    </details>

    </details>

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 13, 2026 13:48 UTC
    Reviewer

    <!-- codex-review-receipt:v1 -->

    💡 Codex Review

    Here are some automated review suggestions for this pull request.

    Reviewed commit: adf218cf7f

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    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".

    </details>

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Nov 13, 2026 13:48 UTC
    Code Review
    src/components/team-chat/TeamChatView.tsx:1
    @@ -10,11 +10,93 @@ import { useActiveTeamChatConversation } from '@/hooks/chat/useTeamChatNotificat
     import { Button } from '@/components/ui/button';
     import { ConversationEmptyState } from '@/components/shared/ConversationEmptyState';
     
    +/** Lê ?cid=<id> da URL (deep-link da notificação do chat da equipe). */
    +function readCidParam(): string | null {
    +  return new URLSearchParams(window.location.search).get('cid');
    +}
    +
    +/** Remove ?cid= da entrada atual sem empilhar histórico (mesmo padrão do ?emailContact). */
    +function stripCidParam(): void {
    +  const url = new URL(window.location.href);
    +  if (!url.searchParams.has('cid')) return;
    +  url.searchParams.delete('cid');
    +  const base = window.history.state && typeof window.history.state === 'object' ? window.history.state : {};
    +  window.history.replaceState(base, '', url.href);
    +}
    +
     export function TeamChatView() {
    -  const { data: conversations = [], isLoading: conversationsLoading } = useTeamConversations();
    -  const [selectedId, setSelectedId] = useState<string | null>(null);
    +  const {
    +    data: conversations = [],
    +    isLoading: conversationsLoading,
    +    refetch: refetchConversations,
    +  } = useTeamConversations();
    +  // Conversa aberta (escolha do usuário ou deep-link já resolvido). Um deep-link
    +  // pendente não a apaga: só a substitui quando a conversa dele existir.
    +  const [pickedId, setPickedId] = useState<string | null>(null);
    +  const [deepLinkCid, setDeepLinkCid] = useState<string | null>(() => readCidParam());
       const [showNewDialog, setShowNewDialog] = useState(false);
       const [showDetails, setShowDetails] = useState(false);
    +  // Recarga da lista pedida pelo deep-link (ver abaixo): cid e se já terminou.
    +  const [recarga, setRecarga] = useState<{ cid: string; feita: boolean } | null>(null);
    +
    +  // Deep-link: ?cid=<uuid> (vindo da notificação) é lido ao abrir a tela e a cada
    +  // `zapp:navigate` (nova notificação com a tela aberta) e sai da URL na hora —
    +  // recargas da lista (realtime) não desfazem a conversa escolhida depois.
    +  useEffect(() => {
    +    const onNavigate = () => {
    +      const cid = readCidParam();
    +      if (!cid) return;
    +      // Sai da URL aqui mesmo, sem depender de mudança de estado: com o mesmo cid duas
    +      // vezes seguidas o estado não muda, e o ?cid= ficaria pendurado na URL (reabrindo a
    +      // conversa ao voltar para a tela ou recarregar).
    +      stripCidParam();
    +      // A seleção atual NÃO muda aqui: só troca quando o cid resolver para uma conversa
    +      // existente (abaixo). Se ele for descartado, o usuário continua na conversa que
    +      // tinha aberta. E cada notificação é um pedido novo: zera a recarga, para que o
    +      // mesmo cid descartado antes volte a recarregar a lista (a conversa pode ter
    +      // passado a existir desde então).
    +      setDeepLinkCid(cid);
    +      setRecarga(null);
    +    };
    +    window.addEventListener('zapp:navigate', onNavigate);
    +    return () => window.removeEventListener('zapp:navigate', onNavigate);
    +  }, []);
    +  // O ?cid= da abertura já foi lido no estado inicial: sai da URL na montagem, mesmo
    +  // quando a conversa não existe para o usuário (o pedido é descartado logo abaixo).
    +  useEffect(() => {
    +    stripCidParam();
    +  }, []);
    +  // Lista carregada sem a conversa do deep-link: antes de desistir, recarrega a lista
    +  // UMA vez — a notificação de uma conversa recém-criada costuma chegar antes do
    +  // realtime atualizar a lista. Se depois da recarga ela continuar ausente (sem acesso,
    +  // apagada), o pedido é descartado e não abre sozinho quando surgir mais tarde.
    +  // Ajuste de estado no render (padrão do React para estado derivado de props).
    +  const deepLinkAusente =
    +    !conversationsLoading && !!deepLinkCid && !conversations.some(c => c.id === deepLinkCid);
    +  if (deepLinkAusente && recarga?.cid !== deepLinkCid) setRecarga({ cid: deepLinkCid as string, feita: false });

    <sub><sub>!P2 Badge</sub></sub> Aguarde o perfil antes de descartar o deep-link

    Ao abrir ?view=team-chat&cid=... com o perfil ainda carregando, useTeamConversations fica desabilitado por enabled: !!profile, mas isLoading é falso. Esta condição interpreta a lista como carregada e dispara refetchConversations(), cuja função retorna [] enquanto não há perfil; logo depois, o pedido é descartado definitivamente. Esse cenário é possível porque src/hooks/auth/useAuth.tsx inicia fetchProfile sem aguardá-lo, e as permissões da rota carregam separadamente. Mesmo quando o perfil e a conversa chegam, o chat solicitado não abre. Aguarde a identidade e uma consulta efetiva antes de concluir que a conversa está ausente.

    Useful? React with 👍 / 👎.

    <!-- codex-code-review-finding:v1 -->

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Nov 13, 2026 13:48 UTC
    Code Review
    scripts/ci/ci-local.mjs:1
    @@ -0,0 +1,1470 @@
    +#!/usr/bin/env node
    +// CI local: roda na máquina os MESMOS passos dos workflows do GitHub, lendo os
    +// próprios .github/workflows/*.yml (nada de cópia de comandos que envelhece).
    +//
    +// Uso:
    +//   npm run ci:local                          # ci.yml + db-guard.yml completos
    +//   npm run ci:local -- --rapido              # unit-tests só dos arquivos mudados nos commits
    +//   npm run ci:local -- --job typecheck,build # só esses jobs
    +//   npm run ci:local -- --workflow ci         # só ci.yml (aceita: ci, db-guard, e2e-talkx ...)
    +//   npm run ci:local -- --listar              # mostra workflows/jobs/passos sem rodar
    +//   npm run ci:local -- --incluir-nao-commitado  # testa também o que não foi commitado
    +//   npm run ci:local -- --evento workflow_dispatch [--input chave=valor]
    +//   npm run ci:local -- --base origin/main    # base de comparação (padrão)
    +//   npm run ci:local -- --com-credenciais     # copia o login do gh (hosts.yml) e do docker para o HOME do job
    +//   npm run ci:local -- --permitir-workflow-sem-pr  # roda workflow sem gatilho pull_request
    +//
    +// Cada execução roda num CLONE DESCARTÁVEL do HEAD commitado (nada escreve no
    +// .git real) e cada job tem HOME, TMPDIR e RUNNER_TEMP próprios. Os passos não
    +// herdam o ambiente de quem chamou (lista permitida) e sudo/apt/dpkg/su/doas/pkexec
    +// caem em shims que falham. Ctrl-C encerra com SIGINT → SIGTERM → SIGKILL e
    +// limpa containers, processos e temporários. Detalhes: docs/ci/CI_LOCAL.md.
    +//
    +// Saída: 0 = tudo o que rodou passou; 1 = algum job falharia no GitHub;
    +//        2 = uso inválido ou ambiente sem base; 3 = nenhum job rodou.
    +
    +import { spawn, spawnSync } from 'node:child_process';
    +import {
    +  existsSync,
    +  mkdirSync,
    +  readFileSync,
    +  readdirSync,
    +  writeFileSync,
    +  chmodSync,
    +  statSync,
    +  accessSync,
    +  constants as fsConstants,
    +  appendFileSync,
    +  mkdtempSync,
    +  rmSync,
    +  cpSync,
    +  copyFileSync,
    +  symlinkSync,
    +} from 'node:fs';
    +import { tmpdir, constants as osConstants } from 'node:os';
    +import { join, resolve, dirname, isAbsolute } from 'node:path';
    +import { parse as parseYaml } from 'yaml';
    +import {
    +  avaliarCondicao,
    +  avaliarBooleano,
    +  avaliarMinutos,
    +  avaliarValor,
    +  interpolar,
    +  expandirMatriz,
    +  ordenarJobs,
    +  lerArquivoEnv,
    +  comandoShell,
    +  extensaoShell,
    +  separarOpcoesDocker,
    +  portaLocal,
    +  arquivosDoDiffZ,
    +  arquivosParaVitestRelated,
    +  comandosComSudo,
    +  mascarar,
    +  ExpressaoNaoSuportada,
    +  planoHomeIsolado,
    +  paraTexto,
    +  shimsDeRoot,
    +  ambientePermitido,
    +  configDockerSemCredenciais,
    +  GITCONFIG_SEM_CREDENCIAL,
    +  temGatilhoPullRequest,
    +  gatilhosDoWorkflow,
    +  semTestesRelacionados,
    +  encerrarEscalonado,
    +  inicioDoProcesso,
    +  donoVivo,
    +  lerListaContainers,
    +  shimDocker,
    +  containersOrfaos,
    +} from './ci-local-lib.mjs';
    +
    +class ErroUso extends Error {}
    +
    +// Nenhum `git status`/`git diff` do CI local reescreve o índice do checkout real
    +// (o refresh do índice disputaria o index.lock com o editor/IDE do usuário).
    +process.env.GIT_OPTIONAL_LOCKS = '0';
    +
    +const ORIGEM = resolve(
    +  spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8' }).stdout.trim() || '.'
    +);
    +const PADRAO_WORKFLOWS = ['ci', 'db-guard'];
    +const EVENTOS = ['pull_request', 'push', 'workflow_dispatch'];
    +const TIMEOUT_JOB_PADRAO_MIN = 360; // padrão do GitHub
    +
    +// ------------------------------------------------------------- limpeza global
    +// Tudo o que a execução cria fica registrado aqui; SIGINT/SIGTERM e o fim do main
    +// encerram os grupos de processos (SIGINT → SIGTERM → SIGKILL), removem os
    +// containers COM O RÓTULO desta execução e apagam os temporários.
    +const limpeza = {
    +  grupos: new Set(),
    +  containers: new Set(),
    +  dirs: new Set(),
    +  marca: null,
    +  forcar: false,
    +};
    +const GRACA_MS = /^\d+$/.test(process.env.CI_LOCAL_GRACA_MS ?? '')
    +  ? Number(process.env.CI_LOCAL_GRACA_MS)
    +  : 5000;
    +
    +function grupoVivo(pid) {
    +  try {
    +    process.kill(-pid, 0);
    +    return true;
    +  } catch {
    +    return false;
    +  }
    +}
    +
    +/** Encerra o grupo de processos com escalada (o timeout e o Ctrl-C chegam aqui). */
    +function encerrarGrupo(pid) {
    +  if (!pid) return Promise.resolve(null);
    +  return encerrarEscalonado({
    +    sinalizar: (sinal) => {
    +      try {
    +        process.kill(-pid, sinal);
    +      } catch {
    +        /* grupo já terminou */
    +      }
    +    },
    +    vivo: () => grupoVivo(pid),
    +    esperaMs: GRACA_MS,
    +    apressar: () => limpeza.forcar,
    +  });
    +}
    +
    +/** PIDs (exceto o próprio) que herdaram a marca `chave=valor` no ambiente. */
    +function pidsMarcados(chave, valor) {
    +  const marca = `${chave}=${valor}`;
    +  let pids = [];
    +  try {
    +    pids = readdirSync('/proc').filter((d) => /^\d+$/.test(d));
    +  } catch {
    +    return [];
    +  }
    +  const out = [];
    +  for (const pid of pids) {
    +    if (Number(pid) === process.pid) continue;
    +    let environ;
    +    try {
    +      environ = readFileSync(`/proc/${pid}/environ`, 'latin1');
    +    } catch {
    +      continue;
    +    }
    +    if (environ.split('\0').includes(marca)) out.push(Number(pid));
    +  }
    +  return out;
    +}
    +
    +/**
    + * Encerra (com escalada) todo processo que herdou a marca `chave=valor` no
    + * ambiente (órfãos em segundo plano, inclusive os que mudaram de grupo). Usa a
    + * marca, e não o PGID, para nunca acertar um processo alheio que reaproveitou o número.
    + */
    +function encerrarMarcados(chave, valor) {
    +  return encerrarEscalonado({
    +    sinalizar: (sinal) => {
    +      for (const pid of pidsMarcados(chave, valor)) {
    +        try {
    +          process.kill(pid, sinal);
    +        } catch {
    +          /* já saiu */
    +        }
    +      }
    +    },
    +    vivo: () => pidsMarcados(chave, valor).length > 0,
    +    esperaMs: GRACA_MS,
    +    apressar: () => limpeza.forcar,
    +  });
    +}
    +
    +function docker(args, opcoes = {}) {
    +  return spawnSync('docker', args, { encoding: 'utf8', timeout: 60_000, ...opcoes });
    +}
    +
    +/** Para (SIGTERM do docker, com prazo) e remove containers pelo id/nome. */
    +function removerContainers(ids) {
    +  if (!ids.length) return;
    +  docker(['stop', '--time', String(Math.ceil(GRACA_MS / 1000)), ...ids], { stdio: 'ignore' });
    +  docker(['rm', '-f', ...ids], { stdio: 'ignore' });
    +}
    +
    +function derrubarContainer(nome) {
    +  removerContainers([nome]);
    +  limpeza.containers.delete(nome);
    +}
    +
    +const FORMATO_PS = '{{.ID}}\t{{.Label "ci-local.run"}}\t{{.Names}}\t{{.Image}}';
    +
    +/**
    + * Remove os containers com o rótulo `chave=valor` (ci-local.run desta execução ou
    + * ci-local.job de um job). Rótulo vem do `docker run` dos services e do shim
    + * `docker` dos passos. Container SEM esse rótulo nunca é tocado.
    + */
    +function removerRotulados(chave, valor) {
    +  const r = docker([
    +    'ps',
    +    '-a',
    +    '--no-trunc',
    +    '--filter',
    +    `label=${chave}=${valor}`,
    +    '--format',
    +    FORMATO_PS,
    +  ]);
    +  if (r.error || r.status !== 0) return [];
    +  const alvos = lerListaContainers(r.stdout);
    +  removerContainers(alvos.map((c) => c.id));
    +  return alvos;
    +}
    +
    +function removerContainersDaExecucao() {
    +  for (const c of [...limpeza.containers]) derrubarContainer(c);
    +  return limpeza.marca ? removerRotulados('ci-local.run', limpeza.marca) : [];
    +}
    +
    +let limpando = null;
    +function limparTudo() {
    +  limpando ??= (async () => {
    +    await Promise.all([...limpeza.grupos].map((g) => encerrarGrupo(g)));
    +    limpeza.grupos.clear();
    +    if (limpeza.marca) await encerrarMarcados('CI_LOCAL_RUN', limpeza.marca);
    +    const removidos = removerContainersDaExecucao();
    +    for (const d of limpeza.dirs) rmSync(d, { recursive: true, force: true });
    +    limpeza.dirs.clear();
    +    return removidos;
    +  })();
    +  return limpando;
    +}
    +
    +let interrompido = false;
    +for (const [sinal, codigo] of [
    +  ['SIGINT', 130],
    +  ['SIGTERM', 143],
    +  ['SIGHUP', 129],
    +]) {
    +  process.on(sinal, () => {
    +    if (interrompido) {
    +      // Segundo sinal: sem esperas, direto para o SIGKILL.
    +      limpeza.forcar = true;
    +      return;
    +    }
    +    interrompido = true;
    +    console.error(
    +      `\n${sinal}: interrompido — encerrando passos (SIGINT → SIGTERM → SIGKILL), ` +
    +        'containers e temporários... (de novo para forçar)'
    +    );
    +    limparTudo().finally(() => process.exit(codigo));
    +  });
    +}
    +
    +// ------------------------------------------------------- restos de execuções
    +const DONO = 'dono.json';
    +
    +/**
    + * Varre restos de execuções que morreram sem limpar (SIGKILL, queda do WSL):
    + * diretórios /tmp/ci-local-XXXXXX cujo dono.json aponta para processo morto
    + * (e os processos que herdaram a marca deles) e containers com rótulo ci-local
    + * cujo pid dono morreu. Sem dono.json o diretório não é tocado.
    + */
    +async function varrerRestos(log) {
    +  const base = tmpdir();
    +  let nomes = [];
    +  try {
    +    nomes = readdirSync(base).filter((n) => /^ci-local-[A-Za-z0-9]{6}$/.test(n));
    +  } catch {
    +    /* tmp ilegível */
    +  }
    +  for (const nome of nomes) {
    +    const dir = join(base, nome);
    +    let dono;
    +    try {
    +      dono = JSON.parse(readFileSync(join(dir, DONO), 'utf8'));
    +    } catch {
    +      continue; // sem dono conhecido: não é nosso para apagar
    +    }
    +    if (donoVivo(dono)) continue;
    +    await encerrarMarcados('CI_LOCAL_RUN', dir);
    +    rmSync(dir, { recursive: true, force: true });
    +    log(`🧹 resto de execução morta (pid ${dono.pid}) removido: ${dir}`);
    +  }
    +  const r = docker([
    +    'ps',
    +    '-a',
    +    '--no-trunc',
    +    '--filter',
    +    'label=ci-local=1',
    +    '--format',
    +    '{{.ID}}\t{{.Label "ci-local.pid"}}\t{{.Label "ci-local.inicio"}}\t{{.Names}}',
    +  ]);
    +  if (r.error || r.status !== 0) return;
    +  const orfaos = containersOrfaos(r.stdout);
    +  if (orfaos.length) {
    +    removerContainers(orfaos.map((c) => c.id));
    +    for (const c of orfaos)
    +      log(`🧹 container de execução morta (pid ${c.dono.pid}) removido: ${c.nomes || c.id}`);
    +  }
    +}
    +
    +// ---------------------------------------------------------------- argumentos
    +function lerArgs(argv) {
    +  const a = {
    +    workflows: null,
    +    jobs: null,
    +    rapido: false,
    +    listar: false,
    +    incluirNaoCommitado: false,
    +    base: 'origin/main',
    +    evento: 'pull_request',
    +    inputs: {},
    +    comCredenciais: false,
    +    permitirSemPr: false,
    +  };
    +  const valor = (i, nome) => {
    +    const v = argv[i];
    +    if (v === undefined || v === '' || v.startsWith('--'))
    +      throw new ErroUso(`${nome} precisa de um valor`);
    +    return v;
    +  };
    +  const lista = (s, nome) => {
    +    const l = s
    +      .split(',')
    +      .map((x) => x.trim())
    +      .filter(Boolean);
    +    if (!l.length) throw new ErroUso(`${nome} precisa de um valor`);
    +    return l;
    +  };
    +  for (let i = 0; i < argv.length; i++) {
    +    const x = argv[i];
    +    if (x === '--rapido') a.rapido = true;
    +    else if (x === '--listar') a.listar = true;
    +    else if (x === '--incluir-nao-commitado') a.incluirNaoCommitado = true;
    +    else if (x === '--com-credenciais') a.comCredenciais = true;
    +    else if (x === '--permitir-workflow-sem-pr') a.permitirSemPr = true;
    +    else if (x === '--workflow') a.workflows = lista(valor(++i, x), x);
    +    else if (x === '--job') a.jobs = lista(valor(++i, x), x);
    +    else if (x === '--base') a.base = valor(++i, x);
    +    else if (x === '--evento') {
    +      a.evento = valor(++i, x);
    +      if (!EVENTOS.includes(a.evento))
    +        throw new ErroUso(`--evento aceita: ${EVENTOS.join(', ')} (recebi "${a.evento}")`);
    +    } else if (x === '--input') {
    +      const kv = valor(++i, x);
    +      const eq = kv.indexOf('=');
    +      if (eq <= 0) throw new ErroUso(`--input espera chave=valor (recebi "${kv}")`);
    +      a.inputs[kv.slice(0, eq)] = kv.slice(eq + 1);
    +    } else if (x === '-h' || x === '--help') {
    +      const linhas = readFileSync(new URL(import.meta.url), 'utf8').split('\n');
    +      const fim = linhas.findIndex((l, k) => k > 0 && !l.startsWith('//'));
    +      console.log(
    +        linhas
    +          .slice(1, fim)
    +          .map((l) => l.replace(/^\/\/ ?/, ''))
    +          .join('\n')
    +      );
    +      process.exit(0);
    +    } else throw new ErroUso(`argumento desconhecido: ${x} (use --help)`);
    +  }
    +  return a;
    +}
    +
    +// ------------------------------------------------------------------- contexto
    +function git(...args) {
    +  const r = spawnSync('git', args, { cwd: ORIGEM, encoding: 'utf8' });
    +  return { ok: r.status === 0, out: (r.stdout ?? '').trim(), err: (r.stderr ?? '').trim() };
    +}
    +
    +function executar(cmd, args, opcoes = {}) {
    +  const r = spawnSync(cmd, args, { encoding: 'utf8', maxBuffer: 1 << 30, ...opcoes });
    +  if (r.status !== 0) {
    +    const msg = (r.stderr || r.error?.message || '').toString().trim().split('\n').slice(-3);
    +    throw new Error(`${cmd} ${args.slice(0, 3).join(' ')} falhou: ${msg.join(' | ')}`);
    +  }
    +  return r.stdout;
    +}
    +
    +/**
    + * `secrets.*` vêm SÓ de .env.ci.local (nunca do ambiente de quem chamou: um
    + * `secrets.GITHUB_TOKEN` não pode pegar o GITHUB_TOKEN/GH_TOKEN do terminal).
    + */
    +function carregarSegredos() {
    +  const arq = join(ORIGEM, '.env.ci.local');
    +  let doArquivo = {};
    +  if (existsSync(arq)) {
    +    try {
    +      doArquivo = lerArquivoEnv(readFileSync(arq, 'utf8').replace(/^\s*#.*$/gm, ''));
    +    } catch (e) {
    +      throw new ErroUso(`.env.ci.local inválido: ${e.message}`);
    +    }
    +  }
    +  const usados = new Set(Object.values(doArquivo).filter(Boolean));
    +  const proxy = new Proxy(
    +    {},
    +    {
    +      get: (_, k) => {
    +        if (typeof k !== 'string') return undefined;
    +        const v = doArquivo[k];
    +        if (v) usados.add(v);
    +        return v;
    +      },
    +    }
    +  );
    +  return { proxy, valores: () => [...usados] };
    +}
    +
    +function contextoGithub(args, ws) {
    +  const head = git('rev-parse', 'HEAD').out;
    +  const ramo = git('rev-parse', '--abbrev-ref', 'HEAD').out;
    +  const branch = ramo && ramo !== 'HEAD' ? ramo : '';
    +  const mb = git('merge-base', args.base, 'HEAD');
    +  if (!mb.ok || !mb.out) {
    +    if (!args.listar)
    +      throw new ErroUso(
    +        `sem merge-base entre ${args.base} e HEAD (base inexistente ou repositório raso?). ` +
    +          'Rode `git fetch origin` (ou `git fetch --unshallow origin`) e tente de novo.'
    +      );
    +  }
    +  const baseSha = mb.out;
    +  const evento =
    +    args.evento === 'pull_request'
    +      ? {
    +          pull_request: {
    +            draft: false,
    +            base: { sha: baseSha, ref: 'main' },
    +            head: { sha: head, ref: branch },
    +          },
    +        }
    +      : { inputs: args.inputs };
    +  return {
    +    event_name: args.evento,
    +    sha: head,
    +    ref: `refs/heads/${branch || 'HEAD'}`,
    +    head_ref: args.evento === 'pull_request' ? branch : '',
    +    base_ref: args.evento === 'pull_request' ? 'main' : '',
    +    workspace: ws,
    +    repository: 'adm01-debug/Zapp_Web_V2',
    +    repository_owner: 'adm01-debug',
    +    token: '',
    +    run_id: 'local',
    +    run_attempt: '1',
    +    event: evento,
    +  };
    +}
    +
    +/** Clone descartável do HEAD: os passos (git fetch --depth, git config...) não tocam o .git real. */
    +function prepararWorkspace(runRoot, gh, args, avisos, log) {
    +  const ws = join(runRoot, 'workspace');
    +  const comum = resolve(ORIGEM, git('rev-parse', '--git-common-dir').out);
    +  executar('git', ['clone', '--quiet', '--shared', '--no-checkout', comum, ws]);
    +  executar('git', [
    +    '-C',
    +    ws,
    +    'fetch',
    +    '--quiet',
    +    '--no-tags',
    +    comum,
    +    '+refs/remotes/origin/*:refs/remotes/origin/*',
    +  ]);
    +  executar('git', ['-C', ws, 'checkout', '--quiet', '--detach', gh.sha]);
    +  const url = git('config', '--get', 'remote.origin.url');
    +  if (url.ok && url.out) executar('git', ['-C', ws, 'remote', 'set-url', 'origin', url.out]);
    +
    +  // .ci-local/ (logs desta execução) nunca conta como mudança do working tree.
    +  const sujo = git('status', '--porcelain', '--untracked-files=all', '--', '.', ':!.ci-local').out;
    +  if (sujo) {
    +    const n = sujo.split('\n').length;
    +    if (args.incluirNaoCommitado) {
    +      const diff = spawnSync('git', ['-C', ORIGEM, 'diff', '--binary', 'HEAD'], {
    +        maxBuffer: 1 << 30,
    +      });
    +      if (diff.status !== 0) throw new Error('git diff do working tree falhou');
    +      if (diff.stdout.length)
    +        executar('git', ['-C', ws, 'apply', '--binary', '--whitespace=nowarn'], {
    +          input: diff.stdout,
    +          encoding: undefined,
    +        });
    +      const novos = arquivosDoDiffZ(
    +        executar('git', [
    +          '-C',
    +          ORIGEM,
    +          'ls-files',
    +          '-z',
    +          '--others',
    +          '--exclude-standard',
    +          '--',
    +          '.',
    +          ':!.ci-local',
    +        ])
    +      );
    +      for (const f of novos) {
    +        mkdirSync(dirname(join(ws, f)), { recursive: true });
    +        copyFileSync(join(ORIGEM, f), join(ws, f));
    +      }
    +      avisos.add(`--incluir-nao-commitado: ${n} arquivo(s) do working tree entraram no teste`);
    +    } else {
    +      avisos.add(
    +        `testado o HEAD commitado (${gh.sha.slice(0, 9)}); ${n} arquivo(s) modificado(s)/novo(s) ` +
    +          'NÃO entraram — use --incluir-nao-commitado para incluí-los'
    +      );
    +    }
    +  }
    +  if (existsSync(join(ws, 'bun.lock')) || existsSync(join(ws, 'bun.lockb'))) {
    +    log('📦 bun install --frozen-lockfile no clone descartável...');
    +    executar('bun', ['install', '--frozen-lockfile', '--ignore-scripts', '--silent'], { cwd: ws });
    +  }
    +  return ws;
    +}
    +
    +function sitePackagesDoUsuario() {
    +  const r = spawnSync('python3', ['-c', 'import site; print(site.getusersitepackages())'], {
    +    encoding: 'utf8',
    +  });
    +  return r.status === 0 ? r.stdout.trim() : undefined;
    +}
    +
    +function prepararHome(homeJob, plano) {
    +  mkdirSync(join(homeJob, '.local', 'bin'), { recursive: true });
    +  for (const c of plano.copias) {
    +    mkdirSync(dirname(c.destino), { recursive: true });
    +    const ligar = new Set(c.ligar ?? []);
    +    const excluir = new Set(c.excluir ?? []);
    +    cpSync(c.origem, c.destino, {
    +      recursive: true,
    +      dereference: false,
    +      filter: (src) => {
    +        const topo = src.slice(c.origem.length + 1).split('/')[0];
    +        return !ligar.has(topo) && !excluir.has(topo);
    +      },
    +    });
    +    for (const nome of ligar) {
    +      const alvo = join(c.origem, nome);
    +      if (existsSync(alvo)) symlinkSync(alvo, join(c.destino, nome));
    +    }
    +    if (c.semCredencialGit) appendFileSync(c.destino, GITCONFIG_SEM_CREDENCIAL);
    +    const cfgDocker = join(c.destino, 'config.json');
    +    if (c.semCredencialDocker && existsSync(cfgDocker))
    +      writeFileSync(cfgDocker, configDockerSemCredenciais(readFileSync(cfgDocker, 'utf8')));
    +  }
    +}
    +
    +/**
    + * Diretório que vai na frente do PATH de todo passo: shims de sudo/apt/apt-get/
    + * dpkg/su/doas/pkexec que falham e o shim `docker` que rotula os containers.
    + */
    +function prepararShims(runRoot) {
    +  const dir = join(runRoot, 'bin-sem-root');
    +  mkdirSync(dir, { recursive: true });
    +  for (const [nome, conteudo] of Object.entries({ ...shimsDeRoot(), docker: shimDocker(dir) })) {
    +    writeFileSync(join(dir, nome), conteudo);
    +    chmodSync(join(dir, nome), 0o755);
    +  }
    +  return dir;
    +}
    +
    +/** Caminho absoluto do docker real no PATH de quem chamou (resolvido uma vez, no início). */
    +function dockerReal() {
    +  for (const d of (process.env.PATH ?? '').split(':')) {
    +    if (!d) continue;
    +    const p = resolve(d, 'docker');
    +    try {
    +      if (statSync(p).isFile()) {
    +        accessSync(p, fsConstants.X_OK);
    +        return p;
    +      }
    +    } catch {
    +      /* próximo */
    +    }
    +  }
    +  return '';
    +}
    +
    +// --------------------------------------------------- equivalentes de `uses:`
    +// Steps `uses:` que fazem VERIFICAÇÃO ganham equivalente local; os de
    +// infraestrutura (checkout, setup-*, cache, upload) não se aplicam à máquina.
    +function equivalenteLocal(uses, step, gh) {
    +  const acao = uses.split('@')[0];
    +  const base = gh.event.pull_request?.base?.sha;
    +  if (acao === 'gitleaks/gitleaks-action' && base) {
    +    return {
    +      desc: 'gitleaks (equivalente local)',
    +      cmd: `gitleaks git --no-banner --log-opts="${base}..HEAD"`,
    +    };
    +  }
    +  if (
    +    acao === 'actions/github-script' &&
    +    /Rejeitar edicao de migration/i.test(step.name ?? '') &&
    +    base
    +  ) {
    +    // Mesmo critério do workflow: só 'modified' em supabase/migrations/*.sql.
    +    return {
    +      desc: 'migration existente editada? (equivalente local)',
    +      cmd:
    +        `m=$(git diff --diff-filter=M --name-only "${base}"...HEAD -- 'supabase/migrations/*.sql'); ` +
    +        `if [ -n "$m" ]; then echo "::error::migration já existente editada:"; echo "$m"; exit 1; fi; echo "nenhuma migration existente editada"`,
    +    };
    +  }
    +  return null;
    +}
    +
    +// ------------------------------------------------------------------- docker
    +async function subirServicos(job, jobId, ctx, log, res, containersJob) {
    +  for (const [svc, def] of Object.entries(job.services ?? {})) {
    +    const nome = `ci-local-${jobId}-${svc}-${process.pid}`;
    +    const env = [];
    +    for (const [k, v] of Object.entries(def.env ?? {})) {
    +      const r = interpolar(v, ctx);
    +      if (r.erros.length) throw new Error(`env ${k} do serviço ${svc}: ${r.erros.join('; ')}`);
    +      env.push('-e', `${k}=${r.texto}`);
    +    }
    +    const portas = (def.ports ?? []).flatMap((p) => {
    +      const local = portaLocal(interpolar(p, ctx).texto);
    +      res.avisos.add(`serviço ${svc}: porta publicada no host (${local})`);
    +      return ['-p', local];
    +    });
    +    const opcoes = separarOpcoesDocker(interpolar(def.options ?? '', ctx).texto);
    +    const imagem = interpolar(def.image, ctx).texto;
    +    const r = spawnSync(
    +      'docker',
    +      [
    +        'run',
    +        '-d',
    +        '--rm',
    +        '--name',
    +        nome,
    +        '--label',
    +        'ci-local=1',
    +        '--label',
    +        `ci-local.run=${limpeza.marca}`,
    +        '--label',
    +        `ci-local.pid=${process.pid}`,
    +        '--label',
    +        `ci-local.inicio=${inicioDoProcesso(process.pid) ?? ''}`,
    +        ...env,
    +        ...portas,
    +        ...opcoes,
    +        imagem,
    +      ],
    +      { encoding: 'utf8' }
    +    );
    +    if (r.status !== 0) {
    +      spawnSync('docker', ['rm', '-f', nome], { stdio: 'ignore' });
    +      const msg = (r.stderr || r.error?.message || '').trim().split('\n').filter(Boolean);
    +      throw new Error(`docker run do serviço ${svc} falhou: ${msg.slice(-3).join(' | ')}`);
    +    }
    +    containersJob.add(nome);
    +    limpeza.containers.add(nome);
    +    log(`   🐳 serviço ${svc} (${imagem.split('@')[0]}) subindo...`);
    +    let estado = '';
    +    for (let t = 0; t < 60; t++) {
    +      estado = spawnSync(
    +        'docker',
    +        [
    +          'inspect',
    +          '--format',
    +          '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}',
    +          nome,
    +        ],
    +        { encoding: 'utf8' }
    +      ).stdout.trim();
    +      if (estado === 'healthy' || estado === 'running') break;
    +      if (estado === 'unhealthy' || estado === 'exited' || estado === 'dead' || estado === '')
    +        throw new Error(`serviço ${svc} não ficou de pé (estado: ${estado || 'removido'})`);
    +      await new Promise((ok) => setTimeout(ok, 2000));
    +    }
    +    if (estado !== 'healthy' && estado !== 'running')
    +      throw new Error(`serviço ${svc} não ficou pronto em 120 s (estado: ${estado})`);
    +  }
    +}
    +
    +// ------------------------------------------------------------------- passos
    +function escritorMascarado(arquivoLog, segredos) {
    +  const buf = { out: '', err: '' };
    +  const gravar = (texto) => appendFileSync(arquivoLog, mascarar(texto, segredos()));
    +  const receber = (canal) => (d) => {
    +    buf[canal] += d.toString();
    +    const k = buf[canal].lastIndexOf('\n');
    +    if (k >= 0) {
    +      gravar(buf[canal].slice(0, k + 1));
    +      buf[canal] = buf[canal].slice(k + 1);
    +    }
    +  };
    +  return {
    +    out: receber('out'),
    +    err: receber('err'),
    +    linha: (l) => gravar(`${l}\n`),
    +    fechar: () => {
    +      for (const c of ['out', 'err']) if (buf[c]) gravar(`${buf[c]}\n`);
    +      buf.out = buf.err = '';
    +    },
    +  };
    +}
    +
    +/**
    + * Roda um processo num grupo próprio (detached): o timeout e o Ctrl-C matam o
    + * grupo inteiro (netos inclusive). Não espera processo em segundo plano que
    + * herdou o pipe — como o runner, que só recolhe órfãos no fim do job.
    + */
    +function rodarProcesso({ bin, args, cwd, env, timeoutMs, arquivoLog, segredos }) {
    +  return new Promise((ok) => {
    +    const inicio = Date.now();
    +    const escrita = escritorMascarado(arquivoLog, segredos);
    +    writeFileSync(arquivoLog, '', { flag: 'a' });
    +    let terminou = false;
    +    let estourou = false;
    +    let timer = null;
    +    let saida = null;
    +    const fim = (r) => {
    +      if (terminou) return;
    +      terminou = true;
    +      if (timer) clearTimeout(timer);
    +      escrita.fechar();
    +      ok({ ...r, segundos: Math.round((Date.now() - inicio) / 1000) });
    +    };
    +    let filho;
    +    try {
    +      filho = spawn(bin, args, { cwd, env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
    +    } catch (e) {
    +      escrita.linha(`[ci-local] não consegui iniciar "${bin}": ${e.message}`);
    +      fim({ code: 127, erro: `não consegui iniciar "${bin}" (${e.message})` });
    +      return;
    +    }
    +    filho.on('error', (e) => {
    +      escrita.linha(`[ci-local] não consegui iniciar "${bin}": ${e.code ?? e.message}`);
    +      fim({
    +        code: 127,
    +        erro: `"${bin}" não encontrado ou não executável (${e.code ?? e.message})`,
    +      });
    +    });
    +    if (filho.pid) limpeza.grupos.add(filho.pid);
    +    if (Number.isFinite(timeoutMs))
    +      timer = setTimeout(
    +        () => {
    +          estourou = true;
    +          encerrarGrupo(filho.pid);
    +        },
    +        Math.max(1, Math.min(timeoutMs, 2 ** 31 - 1))
    +      );
    +    filho.stdout.on('data', escrita.out);
    +    filho.stderr.on('data', escrita.err);
    +    let fechou = false;
    +    filho.on('exit', (code, sinal) => {
    +      limpeza.grupos.delete(filho.pid); // líder saiu: o PGID pode ser reaproveitado
    +      saida = estourou
    +        ? { code: 124, timeout: true }
    +        : { code: code ?? 128 + (osConstants.signals[sinal] ?? 0) };
    +      if (fechou) fim(saida);
    +      else setTimeout(() => fim(saida), 1000);
    +    });
    +    filho.on('close', () => {
    +      fechou = true;
    +      if (saida) fim(saida);
    +    });
    +  });
    +}
    +
    +function rodarScript({ script, shell, dirPassos, n, ...resto }) {
    +  const arq = join(dirPassos, `step-${n}${extensaoShell(shell)}`);
    +  writeFileSync(arq, script);
    +  const [bin, args] = comandoShell(shell);
    +  return rodarProcesso({ bin, args: args.map((a) => a.replace('{0}', arq)), ...resto });
    +}
    +
    +function ultimasLinhas(arquivo, n = 15) {
    +  if (!existsSync(arquivo)) return '';
    +  const texto = readFileSync(arquivo, 'utf8').trimEnd();
    +  if (!texto) return '      │ (passo sem saída)';
    +  return texto
    +    .split('\n')
    +    .slice(-n)
    +    .map((l) => `      │ ${l}`)
    +    .join('\n');
    +}
    +
    +// ------------------------------------------------------------------ workflows
    +function carregarWorkflows(nomes) {
    +  const dir = join(ORIGEM, '.github/workflows');

    <sub><sub>!P2 Badge</sub></sub> Carregue os workflows da revisão efetivamente testada

    No modo padrão, uma alteração não commitada em .github/workflows/ci.yml que remova ou desative um teste já altera os passos executados: carregarWorkflows() lê o checkout original antes de criar o clone descartável de HEAD. Assim, o código vem de HEAD, mas os checks vêm do working tree, apesar do aviso em prepararWorkspace() afirmar que alterações não commitadas não entraram. Isso pode apresentar HEAD como validado sem executar seus testes commitados. Leia os workflows do workspace preparado, respeitando também --incluir-nao-commitado.

    Useful? React with 👍 / 👎.

    <!-- codex-code-review-finding:v1 -->

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Nov 13, 2026 13:48 UTC
    Code Review
    scripts/ci/ci-local.mjs:1
    @@ -0,0 +1,1470 @@
    +#!/usr/bin/env node
    +// CI local: roda na máquina os MESMOS passos dos workflows do GitHub, lendo os
    +// próprios .github/workflows/*.yml (nada de cópia de comandos que envelhece).
    +//
    +// Uso:
    +//   npm run ci:local                          # ci.yml + db-guard.yml completos
    +//   npm run ci:local -- --rapido              # unit-tests só dos arquivos mudados nos commits
    +//   npm run ci:local -- --job typecheck,build # só esses jobs
    +//   npm run ci:local -- --workflow ci         # só ci.yml (aceita: ci, db-guard, e2e-talkx ...)
    +//   npm run ci:local -- --listar              # mostra workflows/jobs/passos sem rodar
    +//   npm run ci:local -- --incluir-nao-commitado  # testa também o que não foi commitado
    +//   npm run ci:local -- --evento workflow_dispatch [--input chave=valor]
    +//   npm run ci:local -- --base origin/main    # base de comparação (padrão)
    +//   npm run ci:local -- --com-credenciais     # copia o login do gh (hosts.yml) e do docker para o HOME do job
    +//   npm run ci:local -- --permitir-workflow-sem-pr  # roda workflow sem gatilho pull_request
    +//
    +// Cada execução roda num CLONE DESCARTÁVEL do HEAD commitado (nada escreve no
    +// .git real) e cada job tem HOME, TMPDIR e RUNNER_TEMP próprios. Os passos não
    +// herdam o ambiente de quem chamou (lista permitida) e sudo/apt/dpkg/su/doas/pkexec
    +// caem em shims que falham. Ctrl-C encerra com SIGINT → SIGTERM → SIGKILL e
    +// limpa containers, processos e temporários. Detalhes: docs/ci/CI_LOCAL.md.
    +//
    +// Saída: 0 = tudo o que rodou passou; 1 = algum job falharia no GitHub;
    +//        2 = uso inválido ou ambiente sem base; 3 = nenhum job rodou.
    +
    +import { spawn, spawnSync } from 'node:child_process';
    +import {
    +  existsSync,
    +  mkdirSync,
    +  readFileSync,
    +  readdirSync,
    +  writeFileSync,
    +  chmodSync,
    +  statSync,
    +  accessSync,
    +  constants as fsConstants,
    +  appendFileSync,
    +  mkdtempSync,
    +  rmSync,
    +  cpSync,
    +  copyFileSync,
    +  symlinkSync,
    +} from 'node:fs';
    +import { tmpdir, constants as osConstants } from 'node:os';
    +import { join, resolve, dirname, isAbsolute } from 'node:path';
    +import { parse as parseYaml } from 'yaml';
    +import {
    +  avaliarCondicao,
    +  avaliarBooleano,
    +  avaliarMinutos,
    +  avaliarValor,
    +  interpolar,
    +  expandirMatriz,
    +  ordenarJobs,
    +  lerArquivoEnv,
    +  comandoShell,
    +  extensaoShell,
    +  separarOpcoesDocker,
    +  portaLocal,
    +  arquivosDoDiffZ,
    +  arquivosParaVitestRelated,
    +  comandosComSudo,
    +  mascarar,
    +  ExpressaoNaoSuportada,
    +  planoHomeIsolado,
    +  paraTexto,
    +  shimsDeRoot,
    +  ambientePermitido,
    +  configDockerSemCredenciais,
    +  GITCONFIG_SEM_CREDENCIAL,
    +  temGatilhoPullRequest,
    +  gatilhosDoWorkflow,
    +  semTestesRelacionados,
    +  encerrarEscalonado,
    +  inicioDoProcesso,
    +  donoVivo,
    +  lerListaContainers,
    +  shimDocker,
    +  containersOrfaos,
    +} from './ci-local-lib.mjs';
    +
    +class ErroUso extends Error {}
    +
    +// Nenhum `git status`/`git diff` do CI local reescreve o índice do checkout real
    +// (o refresh do índice disputaria o index.lock com o editor/IDE do usuário).
    +process.env.GIT_OPTIONAL_LOCKS = '0';
    +
    +const ORIGEM = resolve(
    +  spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8' }).stdout.trim() || '.'
    +);
    +const PADRAO_WORKFLOWS = ['ci', 'db-guard'];
    +const EVENTOS = ['pull_request', 'push', 'workflow_dispatch'];
    +const TIMEOUT_JOB_PADRAO_MIN = 360; // padrão do GitHub
    +
    +// ------------------------------------------------------------- limpeza global
    +// Tudo o que a execução cria fica registrado aqui; SIGINT/SIGTERM e o fim do main
    +// encerram os grupos de processos (SIGINT → SIGTERM → SIGKILL), removem os
    +// containers COM O RÓTULO desta execução e apagam os temporários.
    +const limpeza = {
    +  grupos: new Set(),
    +  containers: new Set(),
    +  dirs: new Set(),
    +  marca: null,
    +  forcar: false,
    +};
    +const GRACA_MS = /^\d+$/.test(process.env.CI_LOCAL_GRACA_MS ?? '')
    +  ? Number(process.env.CI_LOCAL_GRACA_MS)
    +  : 5000;
    +
    +function grupoVivo(pid) {
    +  try {
    +    process.kill(-pid, 0);
    +    return true;
    +  } catch {
    +    return false;
    +  }
    +}
    +
    +/** Encerra o grupo de processos com escalada (o timeout e o Ctrl-C chegam aqui). */
    +function encerrarGrupo(pid) {
    +  if (!pid) return Promise.resolve(null);
    +  return encerrarEscalonado({
    +    sinalizar: (sinal) => {
    +      try {
    +        process.kill(-pid, sinal);
    +      } catch {
    +        /* grupo já terminou */
    +      }
    +    },
    +    vivo: () => grupoVivo(pid),
    +    esperaMs: GRACA_MS,
    +    apressar: () => limpeza.forcar,
    +  });
    +}
    +
    +/** PIDs (exceto o próprio) que herdaram a marca `chave=valor` no ambiente. */
    +function pidsMarcados(chave, valor) {
    +  const marca = `${chave}=${valor}`;
    +  let pids = [];
    +  try {
    +    pids = readdirSync('/proc').filter((d) => /^\d+$/.test(d));
    +  } catch {
    +    return [];
    +  }
    +  const out = [];
    +  for (const pid of pids) {
    +    if (Number(pid) === process.pid) continue;
    +    let environ;
    +    try {
    +      environ = readFileSync(`/proc/${pid}/environ`, 'latin1');
    +    } catch {
    +      continue;
    +    }
    +    if (environ.split('\0').includes(marca)) out.push(Number(pid));
    +  }
    +  return out;
    +}
    +
    +/**
    + * Encerra (com escalada) todo processo que herdou a marca `chave=valor` no
    + * ambiente (órfãos em segundo plano, inclusive os que mudaram de grupo). Usa a
    + * marca, e não o PGID, para nunca acertar um processo alheio que reaproveitou o número.
    + */
    +function encerrarMarcados(chave, valor) {
    +  return encerrarEscalonado({
    +    sinalizar: (sinal) => {
    +      for (const pid of pidsMarcados(chave, valor)) {
    +        try {
    +          process.kill(pid, sinal);
    +        } catch {
    +          /* já saiu */
    +        }
    +      }
    +    },
    +    vivo: () => pidsMarcados(chave, valor).length > 0,
    +    esperaMs: GRACA_MS,
    +    apressar: () => limpeza.forcar,
    +  });
    +}
    +
    +function docker(args, opcoes = {}) {
    +  return spawnSync('docker', args, { encoding: 'utf8', timeout: 60_000, ...opcoes });
    +}
    +
    +/** Para (SIGTERM do docker, com prazo) e remove containers pelo id/nome. */
    +function removerContainers(ids) {
    +  if (!ids.length) return;
    +  docker(['stop', '--time', String(Math.ceil(GRACA_MS / 1000)), ...ids], { stdio: 'ignore' });
    +  docker(['rm', '-f', ...ids], { stdio: 'ignore' });
    +}
    +
    +function derrubarContainer(nome) {
    +  removerContainers([nome]);
    +  limpeza.containers.delete(nome);
    +}
    +
    +const FORMATO_PS = '{{.ID}}\t{{.Label "ci-local.run"}}\t{{.Names}}\t{{.Image}}';
    +
    +/**
    + * Remove os containers com o rótulo `chave=valor` (ci-local.run desta execução ou
    + * ci-local.job de um job). Rótulo vem do `docker run` dos services e do shim
    + * `docker` dos passos. Container SEM esse rótulo nunca é tocado.
    + */
    +function removerRotulados(chave, valor) {
    +  const r = docker([
    +    'ps',
    +    '-a',
    +    '--no-trunc',
    +    '--filter',
    +    `label=${chave}=${valor}`,
    +    '--format',
    +    FORMATO_PS,
    +  ]);
    +  if (r.error || r.status !== 0) return [];
    +  const alvos = lerListaContainers(r.stdout);
    +  removerContainers(alvos.map((c) => c.id));
    +  return alvos;
    +}
    +
    +function removerContainersDaExecucao() {
    +  for (const c of [...limpeza.containers]) derrubarContainer(c);
    +  return limpeza.marca ? removerRotulados('ci-local.run', limpeza.marca) : [];
    +}
    +
    +let limpando = null;
    +function limparTudo() {
    +  limpando ??= (async () => {
    +    await Promise.all([...limpeza.grupos].map((g) => encerrarGrupo(g)));
    +    limpeza.grupos.clear();
    +    if (limpeza.marca) await encerrarMarcados('CI_LOCAL_RUN', limpeza.marca);
    +    const removidos = removerContainersDaExecucao();
    +    for (const d of limpeza.dirs) rmSync(d, { recursive: true, force: true });
    +    limpeza.dirs.clear();
    +    return removidos;
    +  })();
    +  return limpando;
    +}
    +
    +let interrompido = false;
    +for (const [sinal, codigo] of [
    +  ['SIGINT', 130],
    +  ['SIGTERM', 143],
    +  ['SIGHUP', 129],
    +]) {
    +  process.on(sinal, () => {
    +    if (interrompido) {
    +      // Segundo sinal: sem esperas, direto para o SIGKILL.
    +      limpeza.forcar = true;
    +      return;
    +    }
    +    interrompido = true;
    +    console.error(
    +      `\n${sinal}: interrompido — encerrando passos (SIGINT → SIGTERM → SIGKILL), ` +
    +        'containers e temporários... (de novo para forçar)'
    +    );
    +    limparTudo().finally(() => process.exit(codigo));
    +  });
    +}
    +
    +// ------------------------------------------------------- restos de execuções
    +const DONO = 'dono.json';
    +
    +/**
    + * Varre restos de execuções que morreram sem limpar (SIGKILL, queda do WSL):
    + * diretórios /tmp/ci-local-XXXXXX cujo dono.json aponta para processo morto
    + * (e os processos que herdaram a marca deles) e containers com rótulo ci-local
    + * cujo pid dono morreu. Sem dono.json o diretório não é tocado.
    + */
    +async function varrerRestos(log) {
    +  const base = tmpdir();
    +  let nomes = [];
    +  try {
    +    nomes = readdirSync(base).filter((n) => /^ci-local-[A-Za-z0-9]{6}$/.test(n));
    +  } catch {
    +    /* tmp ilegível */
    +  }
    +  for (const nome of nomes) {
    +    const dir = join(base, nome);
    +    let dono;
    +    try {
    +      dono = JSON.parse(readFileSync(join(dir, DONO), 'utf8'));
    +    } catch {
    +      continue; // sem dono conhecido: não é nosso para apagar
    +    }
    +    if (donoVivo(dono)) continue;
    +    await encerrarMarcados('CI_LOCAL_RUN', dir);
    +    rmSync(dir, { recursive: true, force: true });
    +    log(`🧹 resto de execução morta (pid ${dono.pid}) removido: ${dir}`);
    +  }
    +  const r = docker([
    +    'ps',
    +    '-a',
    +    '--no-trunc',
    +    '--filter',
    +    'label=ci-local=1',
    +    '--format',
    +    '{{.ID}}\t{{.Label "ci-local.pid"}}\t{{.Label "ci-local.inicio"}}\t{{.Names}}',
    +  ]);
    +  if (r.error || r.status !== 0) return;
    +  const orfaos = containersOrfaos(r.stdout);
    +  if (orfaos.length) {
    +    removerContainers(orfaos.map((c) => c.id));
    +    for (const c of orfaos)
    +      log(`🧹 container de execução morta (pid ${c.dono.pid}) removido: ${c.nomes || c.id}`);
    +  }
    +}
    +
    +// ---------------------------------------------------------------- argumentos
    +function lerArgs(argv) {
    +  const a = {
    +    workflows: null,
    +    jobs: null,
    +    rapido: false,
    +    listar: false,
    +    incluirNaoCommitado: false,
    +    base: 'origin/main',
    +    evento: 'pull_request',
    +    inputs: {},
    +    comCredenciais: false,
    +    permitirSemPr: false,
    +  };
    +  const valor = (i, nome) => {
    +    const v = argv[i];
    +    if (v === undefined || v === '' || v.startsWith('--'))
    +      throw new ErroUso(`${nome} precisa de um valor`);
    +    return v;
    +  };
    +  const lista = (s, nome) => {
    +    const l = s
    +      .split(',')
    +      .map((x) => x.trim())
    +      .filter(Boolean);
    +    if (!l.length) throw new ErroUso(`${nome} precisa de um valor`);
    +    return l;
    +  };
    +  for (let i = 0; i < argv.length; i++) {
    +    const x = argv[i];
    +    if (x === '--rapido') a.rapido = true;
    +    else if (x === '--listar') a.listar = true;
    +    else if (x === '--incluir-nao-commitado') a.incluirNaoCommitado = true;
    +    else if (x === '--com-credenciais') a.comCredenciais = true;
    +    else if (x === '--permitir-workflow-sem-pr') a.permitirSemPr = true;
    +    else if (x === '--workflow') a.workflows = lista(valor(++i, x), x);
    +    else if (x === '--job') a.jobs = lista(valor(++i, x), x);
    +    else if (x === '--base') a.base = valor(++i, x);
    +    else if (x === '--evento') {
    +      a.evento = valor(++i, x);
    +      if (!EVENTOS.includes(a.evento))
    +        throw new ErroUso(`--evento aceita: ${EVENTOS.join(', ')} (recebi "${a.evento}")`);
    +    } else if (x === '--input') {
    +      const kv = valor(++i, x);
    +      const eq = kv.indexOf('=');
    +      if (eq <= 0) throw new ErroUso(`--input espera chave=valor (recebi "${kv}")`);
    +      a.inputs[kv.slice(0, eq)] = kv.slice(eq + 1);
    +    } else if (x === '-h' || x === '--help') {
    +      const linhas = readFileSync(new URL(import.meta.url), 'utf8').split('\n');
    +      const fim = linhas.findIndex((l, k) => k > 0 && !l.startsWith('//'));
    +      console.log(
    +        linhas
    +          .slice(1, fim)
    +          .map((l) => l.replace(/^\/\/ ?/, ''))
    +          .join('\n')
    +      );
    +      process.exit(0);
    +    } else throw new ErroUso(`argumento desconhecido: ${x} (use --help)`);
    +  }
    +  return a;
    +}
    +
    +// ------------------------------------------------------------------- contexto
    +function git(...args) {
    +  const r = spawnSync('git', args, { cwd: ORIGEM, encoding: 'utf8' });
    +  return { ok: r.status === 0, out: (r.stdout ?? '').trim(), err: (r.stderr ?? '').trim() };
    +}
    +
    +function executar(cmd, args, opcoes = {}) {
    +  const r = spawnSync(cmd, args, { encoding: 'utf8', maxBuffer: 1 << 30, ...opcoes });
    +  if (r.status !== 0) {
    +    const msg = (r.stderr || r.error?.message || '').toString().trim().split('\n').slice(-3);
    +    throw new Error(`${cmd} ${args.slice(0, 3).join(' ')} falhou: ${msg.join(' | ')}`);
    +  }
    +  return r.stdout;
    +}
    +
    +/**
    + * `secrets.*` vêm SÓ de .env.ci.local (nunca do ambiente de quem chamou: um
    + * `secrets.GITHUB_TOKEN` não pode pegar o GITHUB_TOKEN/GH_TOKEN do terminal).
    + */
    +function carregarSegredos() {
    +  const arq = join(ORIGEM, '.env.ci.local');
    +  let doArquivo = {};
    +  if (existsSync(arq)) {
    +    try {
    +      doArquivo = lerArquivoEnv(readFileSync(arq, 'utf8').replace(/^\s*#.*$/gm, ''));
    +    } catch (e) {
    +      throw new ErroUso(`.env.ci.local inválido: ${e.message}`);
    +    }
    +  }
    +  const usados = new Set(Object.values(doArquivo).filter(Boolean));
    +  const proxy = new Proxy(
    +    {},
    +    {
    +      get: (_, k) => {
    +        if (typeof k !== 'string') return undefined;
    +        const v = doArquivo[k];
    +        if (v) usados.add(v);
    +        return v;
    +      },
    +    }
    +  );
    +  return { proxy, valores: () => [...usados] };
    +}
    +
    +function contextoGithub(args, ws) {
    +  const head = git('rev-parse', 'HEAD').out;
    +  const ramo = git('rev-parse', '--abbrev-ref', 'HEAD').out;
    +  const branch = ramo && ramo !== 'HEAD' ? ramo : '';
    +  const mb = git('merge-base', args.base, 'HEAD');
    +  if (!mb.ok || !mb.out) {
    +    if (!args.listar)
    +      throw new ErroUso(
    +        `sem merge-base entre ${args.base} e HEAD (base inexistente ou repositório raso?). ` +
    +          'Rode `git fetch origin` (ou `git fetch --unshallow origin`) e tente de novo.'
    +      );
    +  }
    +  const baseSha = mb.out;
    +  const evento =
    +    args.evento === 'pull_request'
    +      ? {
    +          pull_request: {
    +            draft: false,
    +            base: { sha: baseSha, ref: 'main' },
    +            head: { sha: head, ref: branch },
    +          },
    +        }
    +      : { inputs: args.inputs };
    +  return {
    +    event_name: args.evento,
    +    sha: head,
    +    ref: `refs/heads/${branch || 'HEAD'}`,
    +    head_ref: args.evento === 'pull_request' ? branch : '',
    +    base_ref: args.evento === 'pull_request' ? 'main' : '',
    +    workspace: ws,
    +    repository: 'adm01-debug/Zapp_Web_V2',
    +    repository_owner: 'adm01-debug',
    +    token: '',
    +    run_id: 'local',
    +    run_attempt: '1',
    +    event: evento,
    +  };
    +}
    +
    +/** Clone descartável do HEAD: os passos (git fetch --depth, git config...) não tocam o .git real. */
    +function prepararWorkspace(runRoot, gh, args, avisos, log) {
    +  const ws = join(runRoot, 'workspace');
    +  const comum = resolve(ORIGEM, git('rev-parse', '--git-common-dir').out);
    +  executar('git', ['clone', '--quiet', '--shared', '--no-checkout', comum, ws]);
    +  executar('git', [
    +    '-C',
    +    ws,
    +    'fetch',
    +    '--quiet',
    +    '--no-tags',
    +    comum,
    +    '+refs/remotes/origin/*:refs/remotes/origin/*',
    +  ]);
    +  executar('git', ['-C', ws, 'checkout', '--quiet', '--detach', gh.sha]);
    +  const url = git('config', '--get', 'remote.origin.url');
    +  if (url.ok && url.out) executar('git', ['-C', ws, 'remote', 'set-url', 'origin', url.out]);
    +
    +  // .ci-local/ (logs desta execução) nunca conta como mudança do working tree.
    +  const sujo = git('status', '--porcelain', '--untracked-files=all', '--', '.', ':!.ci-local').out;
    +  if (sujo) {
    +    const n = sujo.split('\n').length;
    +    if (args.incluirNaoCommitado) {
    +      const diff = spawnSync('git', ['-C', ORIGEM, 'diff', '--binary', 'HEAD'], {
    +        maxBuffer: 1 << 30,
    +      });
    +      if (diff.status !== 0) throw new Error('git diff do working tree falhou');
    +      if (diff.stdout.length)
    +        executar('git', ['-C', ws, 'apply', '--binary', '--whitespace=nowarn'], {
    +          input: diff.stdout,
    +          encoding: undefined,
    +        });
    +      const novos = arquivosDoDiffZ(
    +        executar('git', [
    +          '-C',
    +          ORIGEM,
    +          'ls-files',
    +          '-z',
    +          '--others',
    +          '--exclude-standard',
    +          '--',
    +          '.',
    +          ':!.ci-local',
    +        ])
    +      );
    +      for (const f of novos) {
    +        mkdirSync(dirname(join(ws, f)), { recursive: true });
    +        copyFileSync(join(ORIGEM, f), join(ws, f));
    +      }
    +      avisos.add(`--incluir-nao-commitado: ${n} arquivo(s) do working tree entraram no teste`);
    +    } else {
    +      avisos.add(
    +        `testado o HEAD commitado (${gh.sha.slice(0, 9)}); ${n} arquivo(s) modificado(s)/novo(s) ` +
    +          'NÃO entraram — use --incluir-nao-commitado para incluí-los'
    +      );
    +    }
    +  }
    +  if (existsSync(join(ws, 'bun.lock')) || existsSync(join(ws, 'bun.lockb'))) {
    +    log('📦 bun install --frozen-lockfile no clone descartável...');
    +    executar('bun', ['install', '--frozen-lockfile', '--ignore-scripts', '--silent'], { cwd: ws });
    +  }
    +  return ws;
    +}
    +
    +function sitePackagesDoUsuario() {
    +  const r = spawnSync('python3', ['-c', 'import site; print(site.getusersitepackages())'], {
    +    encoding: 'utf8',
    +  });
    +  return r.status === 0 ? r.stdout.trim() : undefined;
    +}
    +
    +function prepararHome(homeJob, plano) {
    +  mkdirSync(join(homeJob, '.local', 'bin'), { recursive: true });
    +  for (const c of plano.copias) {
    +    mkdirSync(dirname(c.destino), { recursive: true });
    +    const ligar = new Set(c.ligar ?? []);
    +    const excluir = new Set(c.excluir ?? []);
    +    cpSync(c.origem, c.destino, {
    +      recursive: true,
    +      dereference: false,
    +      filter: (src) => {
    +        const topo = src.slice(c.origem.length + 1).split('/')[0];
    +        return !ligar.has(topo) && !excluir.has(topo);
    +      },
    +    });
    +    for (const nome of ligar) {
    +      const alvo = join(c.origem, nome);
    +      if (existsSync(alvo)) symlinkSync(alvo, join(c.destino, nome));
    +    }
    +    if (c.semCredencialGit) appendFileSync(c.destino, GITCONFIG_SEM_CREDENCIAL);
    +    const cfgDocker = join(c.destino, 'config.json');
    +    if (c.semCredencialDocker && existsSync(cfgDocker))
    +      writeFileSync(cfgDocker, configDockerSemCredenciais(readFileSync(cfgDocker, 'utf8')));
    +  }
    +}
    +
    +/**
    + * Diretório que vai na frente do PATH de todo passo: shims de sudo/apt/apt-get/
    + * dpkg/su/doas/pkexec que falham e o shim `docker` que rotula os containers.
    + */
    +function prepararShims(runRoot) {
    +  const dir = join(runRoot, 'bin-sem-root');
    +  mkdirSync(dir, { recursive: true });
    +  for (const [nome, conteudo] of Object.entries({ ...shimsDeRoot(), docker: shimDocker(dir) })) {
    +    writeFileSync(join(dir, nome), conteudo);
    +    chmodSync(join(dir, nome), 0o755);
    +  }
    +  return dir;
    +}
    +
    +/** Caminho absoluto do docker real no PATH de quem chamou (resolvido uma vez, no início). */
    +function dockerReal() {
    +  for (const d of (process.env.PATH ?? '').split(':')) {
    +    if (!d) continue;
    +    const p = resolve(d, 'docker');
    +    try {
    +      if (statSync(p).isFile()) {
    +        accessSync(p, fsConstants.X_OK);
    +        return p;
    +      }
    +    } catch {
    +      /* próximo */
    +    }
    +  }
    +  return '';
    +}
    +
    +// --------------------------------------------------- equivalentes de `uses:`
    +// Steps `uses:` que fazem VERIFICAÇÃO ganham equivalente local; os de
    +// infraestrutura (checkout, setup-*, cache, upload) não se aplicam à máquina.
    +function equivalenteLocal(uses, step, gh) {
    +  const acao = uses.split('@')[0];
    +  const base = gh.event.pull_request?.base?.sha;
    +  if (acao === 'gitleaks/gitleaks-action' && base) {
    +    return {
    +      desc: 'gitleaks (equivalente local)',
    +      cmd: `gitleaks git --no-banner --log-opts="${base}..HEAD"`,
    +    };
    +  }
    +  if (
    +    acao === 'actions/github-script' &&
    +    /Rejeitar edicao de migration/i.test(step.name ?? '') &&
    +    base
    +  ) {
    +    // Mesmo critério do workflow: só 'modified' em supabase/migrations/*.sql.
    +    return {
    +      desc: 'migration existente editada? (equivalente local)',
    +      cmd:
    +        `m=$(git diff --diff-filter=M --name-only "${base}"...HEAD -- 'supabase/migrations/*.sql'); ` +
    +        `if [ -n "$m" ]; then echo "::error::migration já existente editada:"; echo "$m"; exit 1; fi; echo "nenhuma migration existente editada"`,

    <sub><sub>!P2 Badge</sub></sub> Preserve os critérios do guard de migrations no equivalente local

    Quando uma migration é renomeada e seu conteúdo também muda, este equivalente passa, enquanto .github/workflows/db-guard.yml:115-120 rejeita explicitamente essa alteração. A ajuda local de Git documenta --diff-filter como “select files by diff type”; selecionar somente M exclui os renames R. A reprodução com rename e acréscimo de SQL produziu R093, mas o comando deste trecho retornou vazio. O equivalente também rejeita as exceções legítimas previstas no workflow para stubs e arquivos registrados no evidence. Reutilize os mesmos critérios do guard real para evitar resultados locais divergentes do GitHub.

    Useful? React with 👍 / 👎.

    <!-- codex-code-review-finding:v1 -->

    adm01-debug adm01-debug commented on code on Nov 13, 2026 13:56 UTC
    Code Review
    src/components/team-chat/TeamChatView.tsx:1
    @@ -10,11 +10,93 @@ import { useActiveTeamChatConversation } from '@/hooks/chat/useTeamChatNotificat
     import { Button } from '@/components/ui/button';
     import { ConversationEmptyState } from '@/components/shared/ConversationEmptyState';
     
    +/** Lê ?cid=<id> da URL (deep-link da notificação do chat da equipe). */
    +function readCidParam(): string | null {
    +  return new URLSearchParams(window.location.search).get('cid');
    +}
    +
    +/** Remove ?cid= da entrada atual sem empilhar histórico (mesmo padrão do ?emailContact). */
    +function stripCidParam(): void {
    +  const url = new URL(window.location.href);
    +  if (!url.searchParams.has('cid')) return;
    +  url.searchParams.delete('cid');
    +  const base = window.history.state && typeof window.history.state === 'object' ? window.history.state : {};
    +  window.history.replaceState(base, '', url.href);
    +}
    +
     export function TeamChatView() {
    -  const { data: conversations = [], isLoading: conversationsLoading } = useTeamConversations();
    -  const [selectedId, setSelectedId] = useState<string | null>(null);
    +  const {
    +    data: conversations = [],
    +    isLoading: conversationsLoading,
    +    refetch: refetchConversations,
    +  } = useTeamConversations();
    +  // Conversa aberta (escolha do usuário ou deep-link já resolvido). Um deep-link
    +  // pendente não a apaga: só a substitui quando a conversa dele existir.
    +  const [pickedId, setPickedId] = useState<string | null>(null);
    +  const [deepLinkCid, setDeepLinkCid] = useState<string | null>(() => readCidParam());
       const [showNewDialog, setShowNewDialog] = useState(false);
       const [showDetails, setShowDetails] = useState(false);
    +  // Recarga da lista pedida pelo deep-link (ver abaixo): cid e se já terminou.
    +  const [recarga, setRecarga] = useState<{ cid: string; feita: boolean } | null>(null);
    +
    +  // Deep-link: ?cid=<uuid> (vindo da notificação) é lido ao abrir a tela e a cada
    +  // `zapp:navigate` (nova notificação com a tela aberta) e sai da URL na hora —
    +  // recargas da lista (realtime) não desfazem a conversa escolhida depois.
    +  useEffect(() => {
    +    const onNavigate = () => {
    +      const cid = readCidParam();
    +      if (!cid) return;
    +      // Sai da URL aqui mesmo, sem depender de mudança de estado: com o mesmo cid duas
    +      // vezes seguidas o estado não muda, e o ?cid= ficaria pendurado na URL (reabrindo a
    +      // conversa ao voltar para a tela ou recarregar).
    +      stripCidParam();
    +      // A seleção atual NÃO muda aqui: só troca quando o cid resolver para uma conversa
    +      // existente (abaixo). Se ele for descartado, o usuário continua na conversa que
    +      // tinha aberta. E cada notificação é um pedido novo: zera a recarga, para que o
    +      // mesmo cid descartado antes volte a recarregar a lista (a conversa pode ter
    +      // passado a existir desde então).
    +      setDeepLinkCid(cid);
    +      setRecarga(null);
    +    };
    +    window.addEventListener('zapp:navigate', onNavigate);
    +    return () => window.removeEventListener('zapp:navigate', onNavigate);
    +  }, []);
    +  // O ?cid= da abertura já foi lido no estado inicial: sai da URL na montagem, mesmo
    +  // quando a conversa não existe para o usuário (o pedido é descartado logo abaixo).
    +  useEffect(() => {
    +    stripCidParam();
    +  }, []);
    +  // Lista carregada sem a conversa do deep-link: antes de desistir, recarrega a lista
    +  // UMA vez — a notificação de uma conversa recém-criada costuma chegar antes do
    +  // realtime atualizar a lista. Se depois da recarga ela continuar ausente (sem acesso,
    +  // apagada), o pedido é descartado e não abre sozinho quando surgir mais tarde.
    +  // Ajuste de estado no render (padrão do React para estado derivado de props).
    +  const deepLinkAusente =
    +    !conversationsLoading && !!deepLinkCid && !conversations.some(c => c.id === deepLinkCid);
    +  if (deepLinkAusente && recarga?.cid !== deepLinkCid) setRecarga({ cid: deepLinkCid as string, feita: false });

    Confirmado no código: useTeamConversations usa enabled: !!profile (src/hooks/team-chat/useTeamConversations.ts:105) e o queryFn devolve [] sem perfil (:18); no React Query v5 isLoading fica false com a query desabilitada, então o gate de TeamChatView.tsx:75 pode descartar o ?cid= aberto por URL direta antes do perfil carregar. Não é regressão (a main não tem deep-link de team chat); corrijo em PR própria logo após este pacote, aguardando a primeira busca real (isPending) antes de concluir que a conversa está ausente, com teste do cenário.

    ---
    _Generated by Claude Code_

    adm01-debug adm01-debug commented on code on Nov 13, 2026 13:56 UTC
    Code Review
    scripts/ci/ci-local.mjs:1
    @@ -0,0 +1,1470 @@
    +#!/usr/bin/env node
    +// CI local: roda na máquina os MESMOS passos dos workflows do GitHub, lendo os
    +// próprios .github/workflows/*.yml (nada de cópia de comandos que envelhece).
    +//
    +// Uso:
    +//   npm run ci:local                          # ci.yml + db-guard.yml completos
    +//   npm run ci:local -- --rapido              # unit-tests só dos arquivos mudados nos commits
    +//   npm run ci:local -- --job typecheck,build # só esses jobs
    +//   npm run ci:local -- --workflow ci         # só ci.yml (aceita: ci, db-guard, e2e-talkx ...)
    +//   npm run ci:local -- --listar              # mostra workflows/jobs/passos sem rodar
    +//   npm run ci:local -- --incluir-nao-commitado  # testa também o que não foi commitado
    +//   npm run ci:local -- --evento workflow_dispatch [--input chave=valor]
    +//   npm run ci:local -- --base origin/main    # base de comparação (padrão)
    +//   npm run ci:local -- --com-credenciais     # copia o login do gh (hosts.yml) e do docker para o HOME do job
    +//   npm run ci:local -- --permitir-workflow-sem-pr  # roda workflow sem gatilho pull_request
    +//
    +// Cada execução roda num CLONE DESCARTÁVEL do HEAD commitado (nada escreve no
    +// .git real) e cada job tem HOME, TMPDIR e RUNNER_TEMP próprios. Os passos não
    +// herdam o ambiente de quem chamou (lista permitida) e sudo/apt/dpkg/su/doas/pkexec
    +// caem em shims que falham. Ctrl-C encerra com SIGINT → SIGTERM → SIGKILL e
    +// limpa containers, processos e temporários. Detalhes: docs/ci/CI_LOCAL.md.
    +//
    +// Saída: 0 = tudo o que rodou passou; 1 = algum job falharia no GitHub;
    +//        2 = uso inválido ou ambiente sem base; 3 = nenhum job rodou.
    +
    +import { spawn, spawnSync } from 'node:child_process';
    +import {
    +  existsSync,
    +  mkdirSync,
    +  readFileSync,
    +  readdirSync,
    +  writeFileSync,
    +  chmodSync,
    +  statSync,
    +  accessSync,
    +  constants as fsConstants,
    +  appendFileSync,
    +  mkdtempSync,
    +  rmSync,
    +  cpSync,
    +  copyFileSync,
    +  symlinkSync,
    +} from 'node:fs';
    +import { tmpdir, constants as osConstants } from 'node:os';
    +import { join, resolve, dirname, isAbsolute } from 'node:path';
    +import { parse as parseYaml } from 'yaml';
    +import {
    +  avaliarCondicao,
    +  avaliarBooleano,
    +  avaliarMinutos,
    +  avaliarValor,
    +  interpolar,
    +  expandirMatriz,
    +  ordenarJobs,
    +  lerArquivoEnv,
    +  comandoShell,
    +  extensaoShell,
    +  separarOpcoesDocker,
    +  portaLocal,
    +  arquivosDoDiffZ,
    +  arquivosParaVitestRelated,
    +  comandosComSudo,
    +  mascarar,
    +  ExpressaoNaoSuportada,
    +  planoHomeIsolado,
    +  paraTexto,
    +  shimsDeRoot,
    +  ambientePermitido,
    +  configDockerSemCredenciais,
    +  GITCONFIG_SEM_CREDENCIAL,
    +  temGatilhoPullRequest,
    +  gatilhosDoWorkflow,
    +  semTestesRelacionados,
    +  encerrarEscalonado,
    +  inicioDoProcesso,
    +  donoVivo,
    +  lerListaContainers,
    +  shimDocker,
    +  containersOrfaos,
    +} from './ci-local-lib.mjs';
    +
    +class ErroUso extends Error {}
    +
    +// Nenhum `git status`/`git diff` do CI local reescreve o índice do checkout real
    +// (o refresh do índice disputaria o index.lock com o editor/IDE do usuário).
    +process.env.GIT_OPTIONAL_LOCKS = '0';
    +
    +const ORIGEM = resolve(
    +  spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8' }).stdout.trim() || '.'
    +);
    +const PADRAO_WORKFLOWS = ['ci', 'db-guard'];
    +const EVENTOS = ['pull_request', 'push', 'workflow_dispatch'];
    +const TIMEOUT_JOB_PADRAO_MIN = 360; // padrão do GitHub
    +
    +// ------------------------------------------------------------- limpeza global
    +// Tudo o que a execução cria fica registrado aqui; SIGINT/SIGTERM e o fim do main
    +// encerram os grupos de processos (SIGINT → SIGTERM → SIGKILL), removem os
    +// containers COM O RÓTULO desta execução e apagam os temporários.
    +const limpeza = {
    +  grupos: new Set(),
    +  containers: new Set(),
    +  dirs: new Set(),
    +  marca: null,
    +  forcar: false,
    +};
    +const GRACA_MS = /^\d+$/.test(process.env.CI_LOCAL_GRACA_MS ?? '')
    +  ? Number(process.env.CI_LOCAL_GRACA_MS)
    +  : 5000;
    +
    +function grupoVivo(pid) {
    +  try {
    +    process.kill(-pid, 0);
    +    return true;
    +  } catch {
    +    return false;
    +  }
    +}
    +
    +/** Encerra o grupo de processos com escalada (o timeout e o Ctrl-C chegam aqui). */
    +function encerrarGrupo(pid) {
    +  if (!pid) return Promise.resolve(null);
    +  return encerrarEscalonado({
    +    sinalizar: (sinal) => {
    +      try {
    +        process.kill(-pid, sinal);
    +      } catch {
    +        /* grupo já terminou */
    +      }
    +    },
    +    vivo: () => grupoVivo(pid),
    +    esperaMs: GRACA_MS,
    +    apressar: () => limpeza.forcar,
    +  });
    +}
    +
    +/** PIDs (exceto o próprio) que herdaram a marca `chave=valor` no ambiente. */
    +function pidsMarcados(chave, valor) {
    +  const marca = `${chave}=${valor}`;
    +  let pids = [];
    +  try {
    +    pids = readdirSync('/proc').filter((d) => /^\d+$/.test(d));
    +  } catch {
    +    return [];
    +  }
    +  const out = [];
    +  for (const pid of pids) {
    +    if (Number(pid) === process.pid) continue;
    +    let environ;
    +    try {
    +      environ = readFileSync(`/proc/${pid}/environ`, 'latin1');
    +    } catch {
    +      continue;
    +    }
    +    if (environ.split('\0').includes(marca)) out.push(Number(pid));
    +  }
    +  return out;
    +}
    +
    +/**
    + * Encerra (com escalada) todo processo que herdou a marca `chave=valor` no
    + * ambiente (órfãos em segundo plano, inclusive os que mudaram de grupo). Usa a
    + * marca, e não o PGID, para nunca acertar um processo alheio que reaproveitou o número.
    + */
    +function encerrarMarcados(chave, valor) {
    +  return encerrarEscalonado({
    +    sinalizar: (sinal) => {
    +      for (const pid of pidsMarcados(chave, valor)) {
    +        try {
    +          process.kill(pid, sinal);
    +        } catch {
    +          /* já saiu */
    +        }
    +      }
    +    },
    +    vivo: () => pidsMarcados(chave, valor).length > 0,
    +    esperaMs: GRACA_MS,
    +    apressar: () => limpeza.forcar,
    +  });
    +}
    +
    +function docker(args, opcoes = {}) {
    +  return spawnSync('docker', args, { encoding: 'utf8', timeout: 60_000, ...opcoes });
    +}
    +
    +/** Para (SIGTERM do docker, com prazo) e remove containers pelo id/nome. */
    +function removerContainers(ids) {
    +  if (!ids.length) return;
    +  docker(['stop', '--time', String(Math.ceil(GRACA_MS / 1000)), ...ids], { stdio: 'ignore' });
    +  docker(['rm', '-f', ...ids], { stdio: 'ignore' });
    +}
    +
    +function derrubarContainer(nome) {
    +  removerContainers([nome]);
    +  limpeza.containers.delete(nome);
    +}
    +
    +const FORMATO_PS = '{{.ID}}\t{{.Label "ci-local.run"}}\t{{.Names}}\t{{.Image}}';
    +
    +/**
    + * Remove os containers com o rótulo `chave=valor` (ci-local.run desta execução ou
    + * ci-local.job de um job). Rótulo vem do `docker run` dos services e do shim
    + * `docker` dos passos. Container SEM esse rótulo nunca é tocado.
    + */
    +function removerRotulados(chave, valor) {
    +  const r = docker([
    +    'ps',
    +    '-a',
    +    '--no-trunc',
    +    '--filter',
    +    `label=${chave}=${valor}`,
    +    '--format',
    +    FORMATO_PS,
    +  ]);
    +  if (r.error || r.status !== 0) return [];
    +  const alvos = lerListaContainers(r.stdout);
    +  removerContainers(alvos.map((c) => c.id));
    +  return alvos;
    +}
    +
    +function removerContainersDaExecucao() {
    +  for (const c of [...limpeza.containers]) derrubarContainer(c);
    +  return limpeza.marca ? removerRotulados('ci-local.run', limpeza.marca) : [];
    +}
    +
    +let limpando = null;
    +function limparTudo() {
    +  limpando ??= (async () => {
    +    await Promise.all([...limpeza.grupos].map((g) => encerrarGrupo(g)));
    +    limpeza.grupos.clear();
    +    if (limpeza.marca) await encerrarMarcados('CI_LOCAL_RUN', limpeza.marca);
    +    const removidos = removerContainersDaExecucao();
    +    for (const d of limpeza.dirs) rmSync(d, { recursive: true, force: true });
    +    limpeza.dirs.clear();
    +    return removidos;
    +  })();
    +  return limpando;
    +}
    +
    +let interrompido = false;
    +for (const [sinal, codigo] of [
    +  ['SIGINT', 130],
    +  ['SIGTERM', 143],
    +  ['SIGHUP', 129],
    +]) {
    +  process.on(sinal, () => {
    +    if (interrompido) {
    +      // Segundo sinal: sem esperas, direto para o SIGKILL.
    +      limpeza.forcar = true;
    +      return;
    +    }
    +    interrompido = true;
    +    console.error(
    +      `\n${sinal}: interrompido — encerrando passos (SIGINT → SIGTERM → SIGKILL), ` +
    +        'containers e temporários... (de novo para forçar)'
    +    );
    +    limparTudo().finally(() => process.exit(codigo));
    +  });
    +}
    +
    +// ------------------------------------------------------- restos de execuções
    +const DONO = 'dono.json';
    +
    +/**
    + * Varre restos de execuções que morreram sem limpar (SIGKILL, queda do WSL):
    + * diretórios /tmp/ci-local-XXXXXX cujo dono.json aponta para processo morto
    + * (e os processos que herdaram a marca deles) e containers com rótulo ci-local
    + * cujo pid dono morreu. Sem dono.json o diretório não é tocado.
    + */
    +async function varrerRestos(log) {
    +  const base = tmpdir();
    +  let nomes = [];
    +  try {
    +    nomes = readdirSync(base).filter((n) => /^ci-local-[A-Za-z0-9]{6}$/.test(n));
    +  } catch {
    +    /* tmp ilegível */
    +  }
    +  for (const nome of nomes) {
    +    const dir = join(base, nome);
    +    let dono;
    +    try {
    +      dono = JSON.parse(readFileSync(join(dir, DONO), 'utf8'));
    +    } catch {
    +      continue; // sem dono conhecido: não é nosso para apagar
    +    }
    +    if (donoVivo(dono)) continue;
    +    await encerrarMarcados('CI_LOCAL_RUN', dir);
    +    rmSync(dir, { recursive: true, force: true });
    +    log(`🧹 resto de execução morta (pid ${dono.pid}) removido: ${dir}`);
    +  }
    +  const r = docker([
    +    'ps',
    +    '-a',
    +    '--no-trunc',
    +    '--filter',
    +    'label=ci-local=1',
    +    '--format',
    +    '{{.ID}}\t{{.Label "ci-local.pid"}}\t{{.Label "ci-local.inicio"}}\t{{.Names}}',
    +  ]);
    +  if (r.error || r.status !== 0) return;
    +  const orfaos = containersOrfaos(r.stdout);
    +  if (orfaos.length) {
    +    removerContainers(orfaos.map((c) => c.id));
    +    for (const c of orfaos)
    +      log(`🧹 container de execução morta (pid ${c.dono.pid}) removido: ${c.nomes || c.id}`);
    +  }
    +}
    +
    +// ---------------------------------------------------------------- argumentos
    +function lerArgs(argv) {
    +  const a = {
    +    workflows: null,
    +    jobs: null,
    +    rapido: false,
    +    listar: false,
    +    incluirNaoCommitado: false,
    +    base: 'origin/main',
    +    evento: 'pull_request',
    +    inputs: {},
    +    comCredenciais: false,
    +    permitirSemPr: false,
    +  };
    +  const valor = (i, nome) => {
    +    const v = argv[i];
    +    if (v === undefined || v === '' || v.startsWith('--'))
    +      throw new ErroUso(`${nome} precisa de um valor`);
    +    return v;
    +  };
    +  const lista = (s, nome) => {
    +    const l = s
    +      .split(',')
    +      .map((x) => x.trim())
    +      .filter(Boolean);
    +    if (!l.length) throw new ErroUso(`${nome} precisa de um valor`);
    +    return l;
    +  };
    +  for (let i = 0; i < argv.length; i++) {
    +    const x = argv[i];
    +    if (x === '--rapido') a.rapido = true;
    +    else if (x === '--listar') a.listar = true;
    +    else if (x === '--incluir-nao-commitado') a.incluirNaoCommitado = true;
    +    else if (x === '--com-credenciais') a.comCredenciais = true;
    +    else if (x === '--permitir-workflow-sem-pr') a.permitirSemPr = true;
    +    else if (x === '--workflow') a.workflows = lista(valor(++i, x), x);
    +    else if (x === '--job') a.jobs = lista(valor(++i, x), x);
    +    else if (x === '--base') a.base = valor(++i, x);
    +    else if (x === '--evento') {
    +      a.evento = valor(++i, x);
    +      if (!EVENTOS.includes(a.evento))
    +        throw new ErroUso(`--evento aceita: ${EVENTOS.join(', ')} (recebi "${a.evento}")`);
    +    } else if (x === '--input') {
    +      const kv = valor(++i, x);
    +      const eq = kv.indexOf('=');
    +      if (eq <= 0) throw new ErroUso(`--input espera chave=valor (recebi "${kv}")`);
    +      a.inputs[kv.slice(0, eq)] = kv.slice(eq + 1);
    +    } else if (x === '-h' || x === '--help') {
    +      const linhas = readFileSync(new URL(import.meta.url), 'utf8').split('\n');
    +      const fim = linhas.findIndex((l, k) => k > 0 && !l.startsWith('//'));
    +      console.log(
    +        linhas
    +          .slice(1, fim)
    +          .map((l) => l.replace(/^\/\/ ?/, ''))
    +          .join('\n')
    +      );
    +      process.exit(0);
    +    } else throw new ErroUso(`argumento desconhecido: ${x} (use --help)`);
    +  }
    +  return a;
    +}
    +
    +// ------------------------------------------------------------------- contexto
    +function git(...args) {
    +  const r = spawnSync('git', args, { cwd: ORIGEM, encoding: 'utf8' });
    +  return { ok: r.status === 0, out: (r.stdout ?? '').trim(), err: (r.stderr ?? '').trim() };
    +}
    +
    +function executar(cmd, args, opcoes = {}) {
    +  const r = spawnSync(cmd, args, { encoding: 'utf8', maxBuffer: 1 << 30, ...opcoes });
    +  if (r.status !== 0) {
    +    const msg = (r.stderr || r.error?.message || '').toString().trim().split('\n').slice(-3);
    +    throw new Error(`${cmd} ${args.slice(0, 3).join(' ')} falhou: ${msg.join(' | ')}`);
    +  }
    +  return r.stdout;
    +}
    +
    +/**
    + * `secrets.*` vêm SÓ de .env.ci.local (nunca do ambiente de quem chamou: um
    + * `secrets.GITHUB_TOKEN` não pode pegar o GITHUB_TOKEN/GH_TOKEN do terminal).
    + */
    +function carregarSegredos() {
    +  const arq = join(ORIGEM, '.env.ci.local');
    +  let doArquivo = {};
    +  if (existsSync(arq)) {
    +    try {
    +      doArquivo = lerArquivoEnv(readFileSync(arq, 'utf8').replace(/^\s*#.*$/gm, ''));
    +    } catch (e) {
    +      throw new ErroUso(`.env.ci.local inválido: ${e.message}`);
    +    }
    +  }
    +  const usados = new Set(Object.values(doArquivo).filter(Boolean));
    +  const proxy = new Proxy(
    +    {},
    +    {
    +      get: (_, k) => {
    +        if (typeof k !== 'string') return undefined;
    +        const v = doArquivo[k];
    +        if (v) usados.add(v);
    +        return v;
    +      },
    +    }
    +  );
    +  return { proxy, valores: () => [...usados] };
    +}
    +
    +function contextoGithub(args, ws) {
    +  const head = git('rev-parse', 'HEAD').out;
    +  const ramo = git('rev-parse', '--abbrev-ref', 'HEAD').out;
    +  const branch = ramo && ramo !== 'HEAD' ? ramo : '';
    +  const mb = git('merge-base', args.base, 'HEAD');
    +  if (!mb.ok || !mb.out) {
    +    if (!args.listar)
    +      throw new ErroUso(
    +        `sem merge-base entre ${args.base} e HEAD (base inexistente ou repositório raso?). ` +
    +          'Rode `git fetch origin` (ou `git fetch --unshallow origin`) e tente de novo.'
    +      );
    +  }
    +  const baseSha = mb.out;
    +  const evento =
    +    args.evento === 'pull_request'
    +      ? {
    +          pull_request: {
    +            draft: false,
    +            base: { sha: baseSha, ref: 'main' },
    +            head: { sha: head, ref: branch },
    +          },
    +        }
    +      : { inputs: args.inputs };
    +  return {
    +    event_name: args.evento,
    +    sha: head,
    +    ref: `refs/heads/${branch || 'HEAD'}`,
    +    head_ref: args.evento === 'pull_request' ? branch : '',
    +    base_ref: args.evento === 'pull_request' ? 'main' : '',
    +    workspace: ws,
    +    repository: 'adm01-debug/Zapp_Web_V2',
    +    repository_owner: 'adm01-debug',
    +    token: '',
    +    run_id: 'local',
    +    run_attempt: '1',
    +    event: evento,
    +  };
    +}
    +
    +/** Clone descartável do HEAD: os passos (git fetch --depth, git config...) não tocam o .git real. */
    +function prepararWorkspace(runRoot, gh, args, avisos, log) {
    +  const ws = join(runRoot, 'workspace');
    +  const comum = resolve(ORIGEM, git('rev-parse', '--git-common-dir').out);
    +  executar('git', ['clone', '--quiet', '--shared', '--no-checkout', comum, ws]);
    +  executar('git', [
    +    '-C',
    +    ws,
    +    'fetch',
    +    '--quiet',
    +    '--no-tags',
    +    comum,
    +    '+refs/remotes/origin/*:refs/remotes/origin/*',
    +  ]);
    +  executar('git', ['-C', ws, 'checkout', '--quiet', '--detach', gh.sha]);
    +  const url = git('config', '--get', 'remote.origin.url');
    +  if (url.ok && url.out) executar('git', ['-C', ws, 'remote', 'set-url', 'origin', url.out]);
    +
    +  // .ci-local/ (logs desta execução) nunca conta como mudança do working tree.
    +  const sujo = git('status', '--porcelain', '--untracked-files=all', '--', '.', ':!.ci-local').out;
    +  if (sujo) {
    +    const n = sujo.split('\n').length;
    +    if (args.incluirNaoCommitado) {
    +      const diff = spawnSync('git', ['-C', ORIGEM, 'diff', '--binary', 'HEAD'], {
    +        maxBuffer: 1 << 30,
    +      });
    +      if (diff.status !== 0) throw new Error('git diff do working tree falhou');
    +      if (diff.stdout.length)
    +        executar('git', ['-C', ws, 'apply', '--binary', '--whitespace=nowarn'], {
    +          input: diff.stdout,
    +          encoding: undefined,
    +        });
    +      const novos = arquivosDoDiffZ(
    +        executar('git', [
    +          '-C',
    +          ORIGEM,
    +          'ls-files',
    +          '-z',
    +          '--others',
    +          '--exclude-standard',
    +          '--',
    +          '.',
    +          ':!.ci-local',
    +        ])
    +      );
    +      for (const f of novos) {
    +        mkdirSync(dirname(join(ws, f)), { recursive: true });
    +        copyFileSync(join(ORIGEM, f), join(ws, f));
    +      }
    +      avisos.add(`--incluir-nao-commitado: ${n} arquivo(s) do working tree entraram no teste`);
    +    } else {
    +      avisos.add(
    +        `testado o HEAD commitado (${gh.sha.slice(0, 9)}); ${n} arquivo(s) modificado(s)/novo(s) ` +
    +          'NÃO entraram — use --incluir-nao-commitado para incluí-los'
    +      );
    +    }
    +  }
    +  if (existsSync(join(ws, 'bun.lock')) || existsSync(join(ws, 'bun.lockb'))) {
    +    log('📦 bun install --frozen-lockfile no clone descartável...');
    +    executar('bun', ['install', '--frozen-lockfile', '--ignore-scripts', '--silent'], { cwd: ws });
    +  }
    +  return ws;
    +}
    +
    +function sitePackagesDoUsuario() {
    +  const r = spawnSync('python3', ['-c', 'import site; print(site.getusersitepackages())'], {
    +    encoding: 'utf8',
    +  });
    +  return r.status === 0 ? r.stdout.trim() : undefined;
    +}
    +
    +function prepararHome(homeJob, plano) {
    +  mkdirSync(join(homeJob, '.local', 'bin'), { recursive: true });
    +  for (const c of plano.copias) {
    +    mkdirSync(dirname(c.destino), { recursive: true });
    +    const ligar = new Set(c.ligar ?? []);
    +    const excluir = new Set(c.excluir ?? []);
    +    cpSync(c.origem, c.destino, {
    +      recursive: true,
    +      dereference: false,
    +      filter: (src) => {
    +        const topo = src.slice(c.origem.length + 1).split('/')[0];
    +        return !ligar.has(topo) && !excluir.has(topo);
    +      },
    +    });
    +    for (const nome of ligar) {
    +      const alvo = join(c.origem, nome);
    +      if (existsSync(alvo)) symlinkSync(alvo, join(c.destino, nome));
    +    }
    +    if (c.semCredencialGit) appendFileSync(c.destino, GITCONFIG_SEM_CREDENCIAL);
    +    const cfgDocker = join(c.destino, 'config.json');
    +    if (c.semCredencialDocker && existsSync(cfgDocker))
    +      writeFileSync(cfgDocker, configDockerSemCredenciais(readFileSync(cfgDocker, 'utf8')));
    +  }
    +}
    +
    +/**
    + * Diretório que vai na frente do PATH de todo passo: shims de sudo/apt/apt-get/
    + * dpkg/su/doas/pkexec que falham e o shim `docker` que rotula os containers.
    + */
    +function prepararShims(runRoot) {
    +  const dir = join(runRoot, 'bin-sem-root');
    +  mkdirSync(dir, { recursive: true });
    +  for (const [nome, conteudo] of Object.entries({ ...shimsDeRoot(), docker: shimDocker(dir) })) {
    +    writeFileSync(join(dir, nome), conteudo);
    +    chmodSync(join(dir, nome), 0o755);
    +  }
    +  return dir;
    +}
    +
    +/** Caminho absoluto do docker real no PATH de quem chamou (resolvido uma vez, no início). */
    +function dockerReal() {
    +  for (const d of (process.env.PATH ?? '').split(':')) {
    +    if (!d) continue;
    +    const p = resolve(d, 'docker');
    +    try {
    +      if (statSync(p).isFile()) {
    +        accessSync(p, fsConstants.X_OK);
    +        return p;
    +      }
    +    } catch {
    +      /* próximo */
    +    }
    +  }
    +  return '';
    +}
    +
    +// --------------------------------------------------- equivalentes de `uses:`
    +// Steps `uses:` que fazem VERIFICAÇÃO ganham equivalente local; os de
    +// infraestrutura (checkout, setup-*, cache, upload) não se aplicam à máquina.
    +function equivalenteLocal(uses, step, gh) {
    +  const acao = uses.split('@')[0];
    +  const base = gh.event.pull_request?.base?.sha;
    +  if (acao === 'gitleaks/gitleaks-action' && base) {
    +    return {
    +      desc: 'gitleaks (equivalente local)',
    +      cmd: `gitleaks git --no-banner --log-opts="${base}..HEAD"`,
    +    };
    +  }
    +  if (
    +    acao === 'actions/github-script' &&
    +    /Rejeitar edicao de migration/i.test(step.name ?? '') &&
    +    base
    +  ) {
    +    // Mesmo critério do workflow: só 'modified' em supabase/migrations/*.sql.
    +    return {
    +      desc: 'migration existente editada? (equivalente local)',
    +      cmd:
    +        `m=$(git diff --diff-filter=M --name-only "${base}"...HEAD -- 'supabase/migrations/*.sql'); ` +
    +        `if [ -n "$m" ]; then echo "::error::migration já existente editada:"; echo "$m"; exit 1; fi; echo "nenhuma migration existente editada"`,
    +    };
    +  }
    +  return null;
    +}
    +
    +// ------------------------------------------------------------------- docker
    +async function subirServicos(job, jobId, ctx, log, res, containersJob) {
    +  for (const [svc, def] of Object.entries(job.services ?? {})) {
    +    const nome = `ci-local-${jobId}-${svc}-${process.pid}`;
    +    const env = [];
    +    for (const [k, v] of Object.entries(def.env ?? {})) {
    +      const r = interpolar(v, ctx);
    +      if (r.erros.length) throw new Error(`env ${k} do serviço ${svc}: ${r.erros.join('; ')}`);
    +      env.push('-e', `${k}=${r.texto}`);
    +    }
    +    const portas = (def.ports ?? []).flatMap((p) => {
    +      const local = portaLocal(interpolar(p, ctx).texto);
    +      res.avisos.add(`serviço ${svc}: porta publicada no host (${local})`);
    +      return ['-p', local];
    +    });
    +    const opcoes = separarOpcoesDocker(interpolar(def.options ?? '', ctx).texto);
    +    const imagem = interpolar(def.image, ctx).texto;
    +    const r = spawnSync(
    +      'docker',
    +      [
    +        'run',
    +        '-d',
    +        '--rm',
    +        '--name',
    +        nome,
    +        '--label',
    +        'ci-local=1',
    +        '--label',
    +        `ci-local.run=${limpeza.marca}`,
    +        '--label',
    +        `ci-local.pid=${process.pid}`,
    +        '--label',
    +        `ci-local.inicio=${inicioDoProcesso(process.pid) ?? ''}`,
    +        ...env,
    +        ...portas,
    +        ...opcoes,
    +        imagem,
    +      ],
    +      { encoding: 'utf8' }
    +    );
    +    if (r.status !== 0) {
    +      spawnSync('docker', ['rm', '-f', nome], { stdio: 'ignore' });
    +      const msg = (r.stderr || r.error?.message || '').trim().split('\n').filter(Boolean);
    +      throw new Error(`docker run do serviço ${svc} falhou: ${msg.slice(-3).join(' | ')}`);
    +    }
    +    containersJob.add(nome);
    +    limpeza.containers.add(nome);
    +    log(`   🐳 serviço ${svc} (${imagem.split('@')[0]}) subindo...`);
    +    let estado = '';
    +    for (let t = 0; t < 60; t++) {
    +      estado = spawnSync(
    +        'docker',
    +        [
    +          'inspect',
    +          '--format',
    +          '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}',
    +          nome,
    +        ],
    +        { encoding: 'utf8' }
    +      ).stdout.trim();
    +      if (estado === 'healthy' || estado === 'running') break;
    +      if (estado === 'unhealthy' || estado === 'exited' || estado === 'dead' || estado === '')
    +        throw new Error(`serviço ${svc} não ficou de pé (estado: ${estado || 'removido'})`);
    +      await new Promise((ok) => setTimeout(ok, 2000));
    +    }
    +    if (estado !== 'healthy' && estado !== 'running')
    +      throw new Error(`serviço ${svc} não ficou pronto em 120 s (estado: ${estado})`);
    +  }
    +}
    +
    +// ------------------------------------------------------------------- passos
    +function escritorMascarado(arquivoLog, segredos) {
    +  const buf = { out: '', err: '' };
    +  const gravar = (texto) => appendFileSync(arquivoLog, mascarar(texto, segredos()));
    +  const receber = (canal) => (d) => {
    +    buf[canal] += d.toString();
    +    const k = buf[canal].lastIndexOf('\n');
    +    if (k >= 0) {
    +      gravar(buf[canal].slice(0, k + 1));
    +      buf[canal] = buf[canal].slice(k + 1);
    +    }
    +  };
    +  return {
    +    out: receber('out'),
    +    err: receber('err'),
    +    linha: (l) => gravar(`${l}\n`),
    +    fechar: () => {
    +      for (const c of ['out', 'err']) if (buf[c]) gravar(`${buf[c]}\n`);
    +      buf.out = buf.err = '';
    +    },
    +  };
    +}
    +
    +/**
    + * Roda um processo num grupo próprio (detached): o timeout e o Ctrl-C matam o
    + * grupo inteiro (netos inclusive). Não espera processo em segundo plano que
    + * herdou o pipe — como o runner, que só recolhe órfãos no fim do job.
    + */
    +function rodarProcesso({ bin, args, cwd, env, timeoutMs, arquivoLog, segredos }) {
    +  return new Promise((ok) => {
    +    const inicio = Date.now();
    +    const escrita = escritorMascarado(arquivoLog, segredos);
    +    writeFileSync(arquivoLog, '', { flag: 'a' });
    +    let terminou = false;
    +    let estourou = false;
    +    let timer = null;
    +    let saida = null;
    +    const fim = (r) => {
    +      if (terminou) return;
    +      terminou = true;
    +      if (timer) clearTimeout(timer);
    +      escrita.fechar();
    +      ok({ ...r, segundos: Math.round((Date.now() - inicio) / 1000) });
    +    };
    +    let filho;
    +    try {
    +      filho = spawn(bin, args, { cwd, env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
    +    } catch (e) {
    +      escrita.linha(`[ci-local] não consegui iniciar "${bin}": ${e.message}`);
    +      fim({ code: 127, erro: `não consegui iniciar "${bin}" (${e.message})` });
    +      return;
    +    }
    +    filho.on('error', (e) => {
    +      escrita.linha(`[ci-local] não consegui iniciar "${bin}": ${e.code ?? e.message}`);
    +      fim({
    +        code: 127,
    +        erro: `"${bin}" não encontrado ou não executável (${e.code ?? e.message})`,
    +      });
    +    });
    +    if (filho.pid) limpeza.grupos.add(filho.pid);
    +    if (Number.isFinite(timeoutMs))
    +      timer = setTimeout(
    +        () => {
    +          estourou = true;
    +          encerrarGrupo(filho.pid);
    +        },
    +        Math.max(1, Math.min(timeoutMs, 2 ** 31 - 1))
    +      );
    +    filho.stdout.on('data', escrita.out);
    +    filho.stderr.on('data', escrita.err);
    +    let fechou = false;
    +    filho.on('exit', (code, sinal) => {
    +      limpeza.grupos.delete(filho.pid); // líder saiu: o PGID pode ser reaproveitado
    +      saida = estourou
    +        ? { code: 124, timeout: true }
    +        : { code: code ?? 128 + (osConstants.signals[sinal] ?? 0) };
    +      if (fechou) fim(saida);
    +      else setTimeout(() => fim(saida), 1000);
    +    });
    +    filho.on('close', () => {
    +      fechou = true;
    +      if (saida) fim(saida);
    +    });
    +  });
    +}
    +
    +function rodarScript({ script, shell, dirPassos, n, ...resto }) {
    +  const arq = join(dirPassos, `step-${n}${extensaoShell(shell)}`);
    +  writeFileSync(arq, script);
    +  const [bin, args] = comandoShell(shell);
    +  return rodarProcesso({ bin, args: args.map((a) => a.replace('{0}', arq)), ...resto });
    +}
    +
    +function ultimasLinhas(arquivo, n = 15) {
    +  if (!existsSync(arquivo)) return '';
    +  const texto = readFileSync(arquivo, 'utf8').trimEnd();
    +  if (!texto) return '      │ (passo sem saída)';
    +  return texto
    +    .split('\n')
    +    .slice(-n)
    +    .map((l) => `      │ ${l}`)
    +    .join('\n');
    +}
    +
    +// ------------------------------------------------------------------ workflows
    +function carregarWorkflows(nomes) {
    +  const dir = join(ORIGEM, '.github/workflows');

    Procede: scripts/ci/ci-local.mjs (ferramenta local da #2970, fora do CI do GitHub e da produção) lê os workflows do checkout original e não do clone de HEAD. Corrijo em PR própria após este pacote, lendo os workflows do workspace preparado e respeitando --incluir-nao-commitado.

    ---
    _Generated by Claude Code_

    adm01-debug adm01-debug commented on code on Nov 13, 2026 13:56 UTC
    Code Review
    scripts/ci/ci-local.mjs:1
    @@ -0,0 +1,1470 @@
    +#!/usr/bin/env node
    +// CI local: roda na máquina os MESMOS passos dos workflows do GitHub, lendo os
    +// próprios .github/workflows/*.yml (nada de cópia de comandos que envelhece).
    +//
    +// Uso:
    +//   npm run ci:local                          # ci.yml + db-guard.yml completos
    +//   npm run ci:local -- --rapido              # unit-tests só dos arquivos mudados nos commits
    +//   npm run ci:local -- --job typecheck,build # só esses jobs
    +//   npm run ci:local -- --workflow ci         # só ci.yml (aceita: ci, db-guard, e2e-talkx ...)
    +//   npm run ci:local -- --listar              # mostra workflows/jobs/passos sem rodar
    +//   npm run ci:local -- --incluir-nao-commitado  # testa também o que não foi commitado
    +//   npm run ci:local -- --evento workflow_dispatch [--input chave=valor]
    +//   npm run ci:local -- --base origin/main    # base de comparação (padrão)
    +//   npm run ci:local -- --com-credenciais     # copia o login do gh (hosts.yml) e do docker para o HOME do job
    +//   npm run ci:local -- --permitir-workflow-sem-pr  # roda workflow sem gatilho pull_request
    +//
    +// Cada execução roda num CLONE DESCARTÁVEL do HEAD commitado (nada escreve no
    +// .git real) e cada job tem HOME, TMPDIR e RUNNER_TEMP próprios. Os passos não
    +// herdam o ambiente de quem chamou (lista permitida) e sudo/apt/dpkg/su/doas/pkexec
    +// caem em shims que falham. Ctrl-C encerra com SIGINT → SIGTERM → SIGKILL e
    +// limpa containers, processos e temporários. Detalhes: docs/ci/CI_LOCAL.md.
    +//
    +// Saída: 0 = tudo o que rodou passou; 1 = algum job falharia no GitHub;
    +//        2 = uso inválido ou ambiente sem base; 3 = nenhum job rodou.
    +
    +import { spawn, spawnSync } from 'node:child_process';
    +import {
    +  existsSync,
    +  mkdirSync,
    +  readFileSync,
    +  readdirSync,
    +  writeFileSync,
    +  chmodSync,
    +  statSync,
    +  accessSync,
    +  constants as fsConstants,
    +  appendFileSync,
    +  mkdtempSync,
    +  rmSync,
    +  cpSync,
    +  copyFileSync,
    +  symlinkSync,
    +} from 'node:fs';
    +import { tmpdir, constants as osConstants } from 'node:os';
    +import { join, resolve, dirname, isAbsolute } from 'node:path';
    +import { parse as parseYaml } from 'yaml';
    +import {
    +  avaliarCondicao,
    +  avaliarBooleano,
    +  avaliarMinutos,
    +  avaliarValor,
    +  interpolar,
    +  expandirMatriz,
    +  ordenarJobs,
    +  lerArquivoEnv,
    +  comandoShell,
    +  extensaoShell,
    +  separarOpcoesDocker,
    +  portaLocal,
    +  arquivosDoDiffZ,
    +  arquivosParaVitestRelated,
    +  comandosComSudo,
    +  mascarar,
    +  ExpressaoNaoSuportada,
    +  planoHomeIsolado,
    +  paraTexto,
    +  shimsDeRoot,
    +  ambientePermitido,
    +  configDockerSemCredenciais,
    +  GITCONFIG_SEM_CREDENCIAL,
    +  temGatilhoPullRequest,
    +  gatilhosDoWorkflow,
    +  semTestesRelacionados,
    +  encerrarEscalonado,
    +  inicioDoProcesso,
    +  donoVivo,
    +  lerListaContainers,
    +  shimDocker,
    +  containersOrfaos,
    +} from './ci-local-lib.mjs';
    +
    +class ErroUso extends Error {}
    +
    +// Nenhum `git status`/`git diff` do CI local reescreve o índice do checkout real
    +// (o refresh do índice disputaria o index.lock com o editor/IDE do usuário).
    +process.env.GIT_OPTIONAL_LOCKS = '0';
    +
    +const ORIGEM = resolve(
    +  spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8' }).stdout.trim() || '.'
    +);
    +const PADRAO_WORKFLOWS = ['ci', 'db-guard'];
    +const EVENTOS = ['pull_request', 'push', 'workflow_dispatch'];
    +const TIMEOUT_JOB_PADRAO_MIN = 360; // padrão do GitHub
    +
    +// ------------------------------------------------------------- limpeza global
    +// Tudo o que a execução cria fica registrado aqui; SIGINT/SIGTERM e o fim do main
    +// encerram os grupos de processos (SIGINT → SIGTERM → SIGKILL), removem os
    +// containers COM O RÓTULO desta execução e apagam os temporários.
    +const limpeza = {
    +  grupos: new Set(),
    +  containers: new Set(),
    +  dirs: new Set(),
    +  marca: null,
    +  forcar: false,
    +};
    +const GRACA_MS = /^\d+$/.test(process.env.CI_LOCAL_GRACA_MS ?? '')
    +  ? Number(process.env.CI_LOCAL_GRACA_MS)
    +  : 5000;
    +
    +function grupoVivo(pid) {
    +  try {
    +    process.kill(-pid, 0);
    +    return true;
    +  } catch {
    +    return false;
    +  }
    +}
    +
    +/** Encerra o grupo de processos com escalada (o timeout e o Ctrl-C chegam aqui). */
    +function encerrarGrupo(pid) {
    +  if (!pid) return Promise.resolve(null);
    +  return encerrarEscalonado({
    +    sinalizar: (sinal) => {
    +      try {
    +        process.kill(-pid, sinal);
    +      } catch {
    +        /* grupo já terminou */
    +      }
    +    },
    +    vivo: () => grupoVivo(pid),
    +    esperaMs: GRACA_MS,
    +    apressar: () => limpeza.forcar,
    +  });
    +}
    +
    +/** PIDs (exceto o próprio) que herdaram a marca `chave=valor` no ambiente. */
    +function pidsMarcados(chave, valor) {
    +  const marca = `${chave}=${valor}`;
    +  let pids = [];
    +  try {
    +    pids = readdirSync('/proc').filter((d) => /^\d+$/.test(d));
    +  } catch {
    +    return [];
    +  }
    +  const out = [];
    +  for (const pid of pids) {
    +    if (Number(pid) === process.pid) continue;
    +    let environ;
    +    try {
    +      environ = readFileSync(`/proc/${pid}/environ`, 'latin1');
    +    } catch {
    +      continue;
    +    }
    +    if (environ.split('\0').includes(marca)) out.push(Number(pid));
    +  }
    +  return out;
    +}
    +
    +/**
    + * Encerra (com escalada) todo processo que herdou a marca `chave=valor` no
    + * ambiente (órfãos em segundo plano, inclusive os que mudaram de grupo). Usa a
    + * marca, e não o PGID, para nunca acertar um processo alheio que reaproveitou o número.
    + */
    +function encerrarMarcados(chave, valor) {
    +  return encerrarEscalonado({
    +    sinalizar: (sinal) => {
    +      for (const pid of pidsMarcados(chave, valor)) {
    +        try {
    +          process.kill(pid, sinal);
    +        } catch {
    +          /* já saiu */
    +        }
    +      }
    +    },
    +    vivo: () => pidsMarcados(chave, valor).length > 0,
    +    esperaMs: GRACA_MS,
    +    apressar: () => limpeza.forcar,
    +  });
    +}
    +
    +function docker(args, opcoes = {}) {
    +  return spawnSync('docker', args, { encoding: 'utf8', timeout: 60_000, ...opcoes });
    +}
    +
    +/** Para (SIGTERM do docker, com prazo) e remove containers pelo id/nome. */
    +function removerContainers(ids) {
    +  if (!ids.length) return;
    +  docker(['stop', '--time', String(Math.ceil(GRACA_MS / 1000)), ...ids], { stdio: 'ignore' });
    +  docker(['rm', '-f', ...ids], { stdio: 'ignore' });
    +}
    +
    +function derrubarContainer(nome) {
    +  removerContainers([nome]);
    +  limpeza.containers.delete(nome);
    +}
    +
    +const FORMATO_PS = '{{.ID}}\t{{.Label "ci-local.run"}}\t{{.Names}}\t{{.Image}}';
    +
    +/**
    + * Remove os containers com o rótulo `chave=valor` (ci-local.run desta execução ou
    + * ci-local.job de um job). Rótulo vem do `docker run` dos services e do shim
    + * `docker` dos passos. Container SEM esse rótulo nunca é tocado.
    + */
    +function removerRotulados(chave, valor) {
    +  const r = docker([
    +    'ps',
    +    '-a',
    +    '--no-trunc',
    +    '--filter',
    +    `label=${chave}=${valor}`,
    +    '--format',
    +    FORMATO_PS,
    +  ]);
    +  if (r.error || r.status !== 0) return [];
    +  const alvos = lerListaContainers(r.stdout);
    +  removerContainers(alvos.map((c) => c.id));
    +  return alvos;
    +}
    +
    +function removerContainersDaExecucao() {
    +  for (const c of [...limpeza.containers]) derrubarContainer(c);
    +  return limpeza.marca ? removerRotulados('ci-local.run', limpeza.marca) : [];
    +}
    +
    +let limpando = null;
    +function limparTudo() {
    +  limpando ??= (async () => {
    +    await Promise.all([...limpeza.grupos].map((g) => encerrarGrupo(g)));
    +    limpeza.grupos.clear();
    +    if (limpeza.marca) await encerrarMarcados('CI_LOCAL_RUN', limpeza.marca);
    +    const removidos = removerContainersDaExecucao();
    +    for (const d of limpeza.dirs) rmSync(d, { recursive: true, force: true });
    +    limpeza.dirs.clear();
    +    return removidos;
    +  })();
    +  return limpando;
    +}
    +
    +let interrompido = false;
    +for (const [sinal, codigo] of [
    +  ['SIGINT', 130],
    +  ['SIGTERM', 143],
    +  ['SIGHUP', 129],
    +]) {
    +  process.on(sinal, () => {
    +    if (interrompido) {
    +      // Segundo sinal: sem esperas, direto para o SIGKILL.
    +      limpeza.forcar = true;
    +      return;
    +    }
    +    interrompido = true;
    +    console.error(
    +      `\n${sinal}: interrompido — encerrando passos (SIGINT → SIGTERM → SIGKILL), ` +
    +        'containers e temporários... (de novo para forçar)'
    +    );
    +    limparTudo().finally(() => process.exit(codigo));
    +  });
    +}
    +
    +// ------------------------------------------------------- restos de execuções
    +const DONO = 'dono.json';
    +
    +/**
    + * Varre restos de execuções que morreram sem limpar (SIGKILL, queda do WSL):
    + * diretórios /tmp/ci-local-XXXXXX cujo dono.json aponta para processo morto
    + * (e os processos que herdaram a marca deles) e containers com rótulo ci-local
    + * cujo pid dono morreu. Sem dono.json o diretório não é tocado.
    + */
    +async function varrerRestos(log) {
    +  const base = tmpdir();
    +  let nomes = [];
    +  try {
    +    nomes = readdirSync(base).filter((n) => /^ci-local-[A-Za-z0-9]{6}$/.test(n));
    +  } catch {
    +    /* tmp ilegível */
    +  }
    +  for (const nome of nomes) {
    +    const dir = join(base, nome);
    +    let dono;
    +    try {
    +      dono = JSON.parse(readFileSync(join(dir, DONO), 'utf8'));
    +    } catch {
    +      continue; // sem dono conhecido: não é nosso para apagar
    +    }
    +    if (donoVivo(dono)) continue;
    +    await encerrarMarcados('CI_LOCAL_RUN', dir);
    +    rmSync(dir, { recursive: true, force: true });
    +    log(`🧹 resto de execução morta (pid ${dono.pid}) removido: ${dir}`);
    +  }
    +  const r = docker([
    +    'ps',
    +    '-a',
    +    '--no-trunc',
    +    '--filter',
    +    'label=ci-local=1',
    +    '--format',
    +    '{{.ID}}\t{{.Label "ci-local.pid"}}\t{{.Label "ci-local.inicio"}}\t{{.Names}}',
    +  ]);
    +  if (r.error || r.status !== 0) return;
    +  const orfaos = containersOrfaos(r.stdout);
    +  if (orfaos.length) {
    +    removerContainers(orfaos.map((c) => c.id));
    +    for (const c of orfaos)
    +      log(`🧹 container de execução morta (pid ${c.dono.pid}) removido: ${c.nomes || c.id}`);
    +  }
    +}
    +
    +// ---------------------------------------------------------------- argumentos
    +function lerArgs(argv) {
    +  const a = {
    +    workflows: null,
    +    jobs: null,
    +    rapido: false,
    +    listar: false,
    +    incluirNaoCommitado: false,
    +    base: 'origin/main',
    +    evento: 'pull_request',
    +    inputs: {},
    +    comCredenciais: false,
    +    permitirSemPr: false,
    +  };
    +  const valor = (i, nome) => {
    +    const v = argv[i];
    +    if (v === undefined || v === '' || v.startsWith('--'))
    +      throw new ErroUso(`${nome} precisa de um valor`);
    +    return v;
    +  };
    +  const lista = (s, nome) => {
    +    const l = s
    +      .split(',')
    +      .map((x) => x.trim())
    +      .filter(Boolean);
    +    if (!l.length) throw new ErroUso(`${nome} precisa de um valor`);
    +    return l;
    +  };
    +  for (let i = 0; i < argv.length; i++) {
    +    const x = argv[i];
    +    if (x === '--rapido') a.rapido = true;
    +    else if (x === '--listar') a.listar = true;
    +    else if (x === '--incluir-nao-commitado') a.incluirNaoCommitado = true;
    +    else if (x === '--com-credenciais') a.comCredenciais = true;
    +    else if (x === '--permitir-workflow-sem-pr') a.permitirSemPr = true;
    +    else if (x === '--workflow') a.workflows = lista(valor(++i, x), x);
    +    else if (x === '--job') a.jobs = lista(valor(++i, x), x);
    +    else if (x === '--base') a.base = valor(++i, x);
    +    else if (x === '--evento') {
    +      a.evento = valor(++i, x);
    +      if (!EVENTOS.includes(a.evento))
    +        throw new ErroUso(`--evento aceita: ${EVENTOS.join(', ')} (recebi "${a.evento}")`);
    +    } else if (x === '--input') {
    +      const kv = valor(++i, x);
    +      const eq = kv.indexOf('=');
    +      if (eq <= 0) throw new ErroUso(`--input espera chave=valor (recebi "${kv}")`);
    +      a.inputs[kv.slice(0, eq)] = kv.slice(eq + 1);
    +    } else if (x === '-h' || x === '--help') {
    +      const linhas = readFileSync(new URL(import.meta.url), 'utf8').split('\n');
    +      const fim = linhas.findIndex((l, k) => k > 0 && !l.startsWith('//'));
    +      console.log(
    +        linhas
    +          .slice(1, fim)
    +          .map((l) => l.replace(/^\/\/ ?/, ''))
    +          .join('\n')
    +      );
    +      process.exit(0);
    +    } else throw new ErroUso(`argumento desconhecido: ${x} (use --help)`);
    +  }
    +  return a;
    +}
    +
    +// ------------------------------------------------------------------- contexto
    +function git(...args) {
    +  const r = spawnSync('git', args, { cwd: ORIGEM, encoding: 'utf8' });
    +  return { ok: r.status === 0, out: (r.stdout ?? '').trim(), err: (r.stderr ?? '').trim() };
    +}
    +
    +function executar(cmd, args, opcoes = {}) {
    +  const r = spawnSync(cmd, args, { encoding: 'utf8', maxBuffer: 1 << 30, ...opcoes });
    +  if (r.status !== 0) {
    +    const msg = (r.stderr || r.error?.message || '').toString().trim().split('\n').slice(-3);
    +    throw new Error(`${cmd} ${args.slice(0, 3).join(' ')} falhou: ${msg.join(' | ')}`);
    +  }
    +  return r.stdout;
    +}
    +
    +/**
    + * `secrets.*` vêm SÓ de .env.ci.local (nunca do ambiente de quem chamou: um
    + * `secrets.GITHUB_TOKEN` não pode pegar o GITHUB_TOKEN/GH_TOKEN do terminal).
    + */
    +function carregarSegredos() {
    +  const arq = join(ORIGEM, '.env.ci.local');
    +  let doArquivo = {};
    +  if (existsSync(arq)) {
    +    try {
    +      doArquivo = lerArquivoEnv(readFileSync(arq, 'utf8').replace(/^\s*#.*$/gm, ''));
    +    } catch (e) {
    +      throw new ErroUso(`.env.ci.local inválido: ${e.message}`);
    +    }
    +  }
    +  const usados = new Set(Object.values(doArquivo).filter(Boolean));
    +  const proxy = new Proxy(
    +    {},
    +    {
    +      get: (_, k) => {
    +        if (typeof k !== 'string') return undefined;
    +        const v = doArquivo[k];
    +        if (v) usados.add(v);
    +        return v;
    +      },
    +    }
    +  );
    +  return { proxy, valores: () => [...usados] };
    +}
    +
    +function contextoGithub(args, ws) {
    +  const head = git('rev-parse', 'HEAD').out;
    +  const ramo = git('rev-parse', '--abbrev-ref', 'HEAD').out;
    +  const branch = ramo && ramo !== 'HEAD' ? ramo : '';
    +  const mb = git('merge-base', args.base, 'HEAD');
    +  if (!mb.ok || !mb.out) {
    +    if (!args.listar)
    +      throw new ErroUso(
    +        `sem merge-base entre ${args.base} e HEAD (base inexistente ou repositório raso?). ` +
    +          'Rode `git fetch origin` (ou `git fetch --unshallow origin`) e tente de novo.'
    +      );
    +  }
    +  const baseSha = mb.out;
    +  const evento =
    +    args.evento === 'pull_request'
    +      ? {
    +          pull_request: {
    +            draft: false,
    +            base: { sha: baseSha, ref: 'main' },
    +            head: { sha: head, ref: branch },
    +          },
    +        }
    +      : { inputs: args.inputs };
    +  return {
    +    event_name: args.evento,
    +    sha: head,
    +    ref: `refs/heads/${branch || 'HEAD'}`,
    +    head_ref: args.evento === 'pull_request' ? branch : '',
    +    base_ref: args.evento === 'pull_request' ? 'main' : '',
    +    workspace: ws,
    +    repository: 'adm01-debug/Zapp_Web_V2',
    +    repository_owner: 'adm01-debug',
    +    token: '',
    +    run_id: 'local',
    +    run_attempt: '1',
    +    event: evento,
    +  };
    +}
    +
    +/** Clone descartável do HEAD: os passos (git fetch --depth, git config...) não tocam o .git real. */
    +function prepararWorkspace(runRoot, gh, args, avisos, log) {
    +  const ws = join(runRoot, 'workspace');
    +  const comum = resolve(ORIGEM, git('rev-parse', '--git-common-dir').out);
    +  executar('git', ['clone', '--quiet', '--shared', '--no-checkout', comum, ws]);
    +  executar('git', [
    +    '-C',
    +    ws,
    +    'fetch',
    +    '--quiet',
    +    '--no-tags',
    +    comum,
    +    '+refs/remotes/origin/*:refs/remotes/origin/*',
    +  ]);
    +  executar('git', ['-C', ws, 'checkout', '--quiet', '--detach', gh.sha]);
    +  const url = git('config', '--get', 'remote.origin.url');
    +  if (url.ok && url.out) executar('git', ['-C', ws, 'remote', 'set-url', 'origin', url.out]);
    +
    +  // .ci-local/ (logs desta execução) nunca conta como mudança do working tree.
    +  const sujo = git('status', '--porcelain', '--untracked-files=all', '--', '.', ':!.ci-local').out;
    +  if (sujo) {
    +    const n = sujo.split('\n').length;
    +    if (args.incluirNaoCommitado) {
    +      const diff = spawnSync('git', ['-C', ORIGEM, 'diff', '--binary', 'HEAD'], {
    +        maxBuffer: 1 << 30,
    +      });
    +      if (diff.status !== 0) throw new Error('git diff do working tree falhou');
    +      if (diff.stdout.length)
    +        executar('git', ['-C', ws, 'apply', '--binary', '--whitespace=nowarn'], {
    +          input: diff.stdout,
    +          encoding: undefined,
    +        });
    +      const novos = arquivosDoDiffZ(
    +        executar('git', [
    +          '-C',
    +          ORIGEM,
    +          'ls-files',
    +          '-z',
    +          '--others',
    +          '--exclude-standard',
    +          '--',
    +          '.',
    +          ':!.ci-local',
    +        ])
    +      );
    +      for (const f of novos) {
    +        mkdirSync(dirname(join(ws, f)), { recursive: true });
    +        copyFileSync(join(ORIGEM, f), join(ws, f));
    +      }
    +      avisos.add(`--incluir-nao-commitado: ${n} arquivo(s) do working tree entraram no teste`);
    +    } else {
    +      avisos.add(
    +        `testado o HEAD commitado (${gh.sha.slice(0, 9)}); ${n} arquivo(s) modificado(s)/novo(s) ` +
    +          'NÃO entraram — use --incluir-nao-commitado para incluí-los'
    +      );
    +    }
    +  }
    +  if (existsSync(join(ws, 'bun.lock')) || existsSync(join(ws, 'bun.lockb'))) {
    +    log('📦 bun install --frozen-lockfile no clone descartável...');
    +    executar('bun', ['install', '--frozen-lockfile', '--ignore-scripts', '--silent'], { cwd: ws });
    +  }
    +  return ws;
    +}
    +
    +function sitePackagesDoUsuario() {
    +  const r = spawnSync('python3', ['-c', 'import site; print(site.getusersitepackages())'], {
    +    encoding: 'utf8',
    +  });
    +  return r.status === 0 ? r.stdout.trim() : undefined;
    +}
    +
    +function prepararHome(homeJob, plano) {
    +  mkdirSync(join(homeJob, '.local', 'bin'), { recursive: true });
    +  for (const c of plano.copias) {
    +    mkdirSync(dirname(c.destino), { recursive: true });
    +    const ligar = new Set(c.ligar ?? []);
    +    const excluir = new Set(c.excluir ?? []);
    +    cpSync(c.origem, c.destino, {
    +      recursive: true,
    +      dereference: false,
    +      filter: (src) => {
    +        const topo = src.slice(c.origem.length + 1).split('/')[0];
    +        return !ligar.has(topo) && !excluir.has(topo);
    +      },
    +    });
    +    for (const nome of ligar) {
    +      const alvo = join(c.origem, nome);
    +      if (existsSync(alvo)) symlinkSync(alvo, join(c.destino, nome));
    +    }
    +    if (c.semCredencialGit) appendFileSync(c.destino, GITCONFIG_SEM_CREDENCIAL);
    +    const cfgDocker = join(c.destino, 'config.json');
    +    if (c.semCredencialDocker && existsSync(cfgDocker))
    +      writeFileSync(cfgDocker, configDockerSemCredenciais(readFileSync(cfgDocker, 'utf8')));
    +  }
    +}
    +
    +/**
    + * Diretório que vai na frente do PATH de todo passo: shims de sudo/apt/apt-get/
    + * dpkg/su/doas/pkexec que falham e o shim `docker` que rotula os containers.
    + */
    +function prepararShims(runRoot) {
    +  const dir = join(runRoot, 'bin-sem-root');
    +  mkdirSync(dir, { recursive: true });
    +  for (const [nome, conteudo] of Object.entries({ ...shimsDeRoot(), docker: shimDocker(dir) })) {
    +    writeFileSync(join(dir, nome), conteudo);
    +    chmodSync(join(dir, nome), 0o755);
    +  }
    +  return dir;
    +}
    +
    +/** Caminho absoluto do docker real no PATH de quem chamou (resolvido uma vez, no início). */
    +function dockerReal() {
    +  for (const d of (process.env.PATH ?? '').split(':')) {
    +    if (!d) continue;
    +    const p = resolve(d, 'docker');
    +    try {
    +      if (statSync(p).isFile()) {
    +        accessSync(p, fsConstants.X_OK);
    +        return p;
    +      }
    +    } catch {
    +      /* próximo */
    +    }
    +  }
    +  return '';
    +}
    +
    +// --------------------------------------------------- equivalentes de `uses:`
    +// Steps `uses:` que fazem VERIFICAÇÃO ganham equivalente local; os de
    +// infraestrutura (checkout, setup-*, cache, upload) não se aplicam à máquina.
    +function equivalenteLocal(uses, step, gh) {
    +  const acao = uses.split('@')[0];
    +  const base = gh.event.pull_request?.base?.sha;
    +  if (acao === 'gitleaks/gitleaks-action' && base) {
    +    return {
    +      desc: 'gitleaks (equivalente local)',
    +      cmd: `gitleaks git --no-banner --log-opts="${base}..HEAD"`,
    +    };
    +  }
    +  if (
    +    acao === 'actions/github-script' &&
    +    /Rejeitar edicao de migration/i.test(step.name ?? '') &&
    +    base
    +  ) {
    +    // Mesmo critério do workflow: só 'modified' em supabase/migrations/*.sql.
    +    return {
    +      desc: 'migration existente editada? (equivalente local)',
    +      cmd:
    +        `m=$(git diff --diff-filter=M --name-only "${base}"...HEAD -- 'supabase/migrations/*.sql'); ` +
    +        `if [ -n "$m" ]; then echo "::error::migration já existente editada:"; echo "$m"; exit 1; fi; echo "nenhuma migration existente editada"`,

    Procede: o equivalente local do guard de migrations em scripts/ci/ci-local.mjs filtra só M e diverge de .github/workflows/db-guard.yml (renames R e exceções de stub/evidence). Afeta só a ferramenta local da #2970, não o guard real do GitHub. Corrijo em PR própria após este pacote, reaproveitando os critérios do workflow.

    ---
    _Generated by Claude Code_

    Reviewers
    Assignees
    adm01-debug adm01-debug
    Labels
    risk: medium confidence: 47.1% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 90.5% (HIGH) · Higher = larger blast radius
    90.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 47.1% · Lower = rushed or shallow review
    47.1%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 47.9% · Moderate risk
    47.9%