feat: 7 edge functions copiloto RADAR fases 8-10 (CV-071–CV-100) #2460
[vc]: #su15pB8Afku8V8tZ+xaT0PQ0TP4WUrRnAbiwZ4L2ZVA=:eyJpc01vbm9yZXBvIjp0cnVlLCJ0eXBlIjoiZ2l0aHViIiwicHJvamVjdHMiOlt7Im5hbWUiOiJ6YXBwX3dlYl92MiIsInByb2plY3RJZCI6InByal9KNHdiOGVneno4aUwxQ0puU09YSkR0cW5idlJwIiwibGl2ZUZlZWRiYWNrIjp7InJlc29sdmVkIjowLCJ1bnJlc29sdmVkIjowLCJ0b3RhbCI6MCwibGluayI6IiJ9LCJpbnNwZWN0b3JVcmwiOiJodHRwczovL3ZlcmNlbC5jb20vanVjYTEvemFwcF93ZWJfdjIvN21FZTdHN21VNDlGQjdiaHptMkVBcDJKSDJHVyIsIm5leHRDb21taXRTdGF0dXMiOiJJR05PUkVEIiwicm9vdERpcmVjdG9yeSI6bnVsbCwicHJldmlld1VybCI6InphcHB3ZWJ2Mi1naXQtY2xhdWRlLWZlYXQtY29waWxvdG8tZWRnZXMtMjYxMTAxLTEzMzAtanVjYTEudmVyY2VsLmFwcCJ9XX0=
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-01T22:03:45.562Z">Nov 1, 2026 10:03pm UTC</relative-time> |
</details>
As sete novas funções não estão em AI_CAPABILITY_BY_FUNCTION (_shared/ai-feature-flags.ts:58–78), então continuam permitindo chamadas pagas mesmo com ai.capability.copilot_live desligada. Registre todos os sete nomes na capacidade copilot_live, preservando seus nomes próprios para cotas e logs. O mesmo problema ocorre na linha 12 dos outros seis endpoints deste PR.
O contexto informa o prazo solicitado e os dias de produção, mas não a data atual. Para um prazo absoluto, a mesma entrada é enviada antes ou depois do vencimento, embora a viabilidade e a urgência mudem. Inclua a data/hora do servidor para que a análise tenha uma referência confiável do tempo disponível.
O mapeamento descarta os horários das mensagens e não fornece um instante de referência, deixando conversas com textos iguais e intervalos de segundos ou dias com o mesmo contexto. Assim, speedToLeadMinutes e silenceAlertMinutes não podem refletir os tempos reais. Preserve e valide os timestamps, calcule as durações no servidor e devolva esses campos como null quando faltarem dados temporais.
lastActivityAt informa uma data absoluta, mas o prompt não inclui o horário atual nem a duração do silêncio. A mesma atividade consultada minutos ou dias depois recebe o mesmo contexto, impedindo avaliar quanto tempo de inatividade se passou. Forneça uma referência temporal do servidor ou calcule os minutos de inatividade antes de chamar a IA.
A chamada envia apenas a URL como texto e não declara need.modality, portanto o modelo não recebe a imagem ou o conteúdo do documento que deveria analisar. Para imagens, prepare a mídia sob a identidade do usuário com _shared/ai-image-input.ts, envie uma parte image_url e exija need: { modality: 'vision' }, como em classify-sticker/index.ts:187–209. Para documentos, extraia o conteúdo por um caminho suportado ou rejeite explicitamente o tipo.
Quando o modelo retorna conteúdo ausente, texto sem JSON ou JSON truncado, este fallback responde HTTP 200 com {}, sinalizando sucesso sem entregar a análise. Retorne um erro explícito, como 502, antes de registrar sucesso quando result for nulo. Aplique a mesma correção aos retornos em ai-price-anchor:72, ai-loss-risk:73, ai-product-recommendation:76, ai-deadline-calculator:74, ai-lead-temperature:80 e ai-multimodal-analysis:78 (todos em supabase/functions/<nome>/index.ts).
<!-- ccr-overview-v2 -->
🟡 Changes recommended
As sete novas funções permitem chamadas pagas mesmo com a capacidade copilot_live desativada, pois não estão registradas em AI_CAPABILITY_BY_FUNCTION.
<details open>
<summary><strong>6 open issues</strong></summary>
</details>
<details>
<summary><strong>What changed in this PR</strong></summary>
Adiciona sete Edge Functions para as fases 8–10 do copiloto de vendas RADAR (CV-071–CV-100), retomando o escopo do PR #2215 sem incluir migrations ou alterações no front-end.
Changes:
purpose: "copilot".| File | Description |
| ---- | ----------- |
| supabase/functions/ai-product-recommendation/index.ts | Recomenda produtos e oportunidades de venda cruzada. |
| supabase/functions/ai-price-anchor/index.ts | Gera estratégias e scripts de ancoragem de preço. |
| supabase/functions/ai-objection-handler/index.ts | Classifica objeções e sugere tratamentos. |
| supabase/functions/ai-multimodal-analysis/index.ts | Adiciona endpoint destinado à análise de mídia do cliente. |
| supabase/functions/ai-loss-risk/index.ts | Solicita avaliação de risco e ações de recuperação. |
| supabase/functions/ai-lead-temperature/index.ts | Qualifica leads e sugere follow-up. |
| supabase/functions/ai-deadline-calculator/index.ts | Solicita avaliação de prazos e alternativas de negociação. |
</details>
<sub>Review effort: Balanced</sub>
<h3>Code Review by Qodo</h3>
<br/>
<details><summary><ins><strong>View medium (13)</strong></ins></summary><br/>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
<details>
<summary> 1. Lead advice exposes fields it never gets <code>🐞</code></summary>
<br/>
<details>
><summary>Description</summary>
><br/>
><pre>
><b><i>AiLeadTemperatureResult</i></b> declares <b><i>nextAction</i></b> and <b><i>engagementScore</i></b> and restricts temperature to
>the local three-level union, but the edge returns a <b><i>followUp</i></b> object and can return <b><i>boiling</i></b>. On a
>successful request, the untransformed response is stored under that incompatible type, so consumers
>cannot safely read the promised advice or handle every temperature.
></pre>
></details>
<details>
><summary>Agent prompt</summary>
><br/>
>>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The AI lead result interface disagrees with the edge’s temperature values and follow-up fields. >## Fix Focus Areas >- src/hooks/copilot/useLeadThermometer.ts[19-24] >- src/hooks/copilot/useLeadThermometer.ts[65-69] >## Recommended Fix >Define an AI-specific response type that includes boiling, structured signals, followUp, and timing fields, or validate and map the edge response into an explicitly narrower UI type. >
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
</details>
<details>
<summary> 2. Objection scripts have the wrong shape <code>🐞</code></summary>
<br/>
<details>
><summary>Description</summary>
><br/>
><pre>
><b><i>AiObjectionResult</i></b> promises <b><i>treatmentSteps</i></b> and <b><i>suggestedReply</i></b>, while the edge requests a
><b><i>treatmentScript</i></b> and objection-specific recovery fields instead. A successful edge response is
>stored without conversion, leaving the hook’s promised script fields undefined even after the
>latest-message request is corrected.
></pre>
></details>
<details>
><summary>Agent prompt</summary>
><br/>
>>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The objection hook’s AI result type describes a different response from the edge’s treatment script. >## Fix Focus Areas >- src/hooks/copilot/useObjectionHandler.ts[31-37] >- src/hooks/copilot/useObjectionHandler.ts[129-133] >## Recommended Fix >Expose the edge’s treatmentScript and optional objection-specific fields in the hook type, or map the validated response into the hook’s intended UI fields. >
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
</details>
<details>
<summary> 3. The latest objection can go unanalyzed <code>🐞</code></summary>
<br/>
<details>
><summary>Description</summary>
><br/>
><pre>
><b><i>useObjectionHandler.analyze()</i></b> sends <b><i>clientText</i></b>, but <b><i>ai-objection-handler</i></b> reads <b><i>latestMessage</i></b>
>and defaults it to an empty string. If the hook is called with its required client text but no
>optional messages, the edge’s explicit latest-message prompt contains no objection text.
></pre>
></details>
<details>
><summary>Agent prompt</summary>
><br/>
>>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The objection hook sends its required customer text under a key the edge ignores. >## Fix Focus Areas >- src/hooks/copilot/useObjectionHandler.ts[129-131] >## Recommended Fix >Send clientText as latestMessage in the request body, preserving messages as optional conversation context. >
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
</details>
<details>
<summary> 4. Loss advice has missing result fields <code>🐞</code></summary>
<br/>
<details>
><summary>Description</summary>
><br/>
><pre>
><b><i>AiLossRiskResult</i></b> declares <b><i>signals</i></b>, <b><i>recoveryAction</i></b>, and <b><i>urgencyMessage</i></b>, but the edge requests
><b><i>riskFactors</i></b>, <b><i>recoveryScript</i></b>, and <b><i>interventionUrgency</i></b> instead. After a successful analysis, the
>hook stores the raw response as its declared type, so those advice fields are undefined and an
>edge-produced <b><i>critical</i></b> risk level also falls outside the declared union.
></pre>
></details>
<details>
><summary>Agent prompt</summary>
><br/>
>>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The hook declares different loss-risk result fields and risk levels from those produced by its edge. >## Fix Focus Areas >- src/hooks/copilot/useLossRiskDetector.ts[22-27] >- src/hooks/copilot/useLossRiskDetector.ts[106-110] >## Recommended Fix >Type the edge response with riskScore, riskFactors, recoveryScript, interventionUrgency, and the critical level, or explicitly map and validate it into a separate UI result before storing it. >
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
</details>
<details>
<summary> 5. Price advice loses its customer context <code>🐞</code></summary>
<br/>
<details>
><summary>Description</summary>
><br/>
><pre>
><b><i>usePriceAnchoring.analyze()</i></b> sends <b><i>clientText</i></b>, but <b><i>ai-price-anchor</i></b> reads only messages and
>explicit product and price fields. With the hook’s default empty messages array, an analysis started
>from its required client text sends none of that customer’s price objection to the model.
></pre>
></details>
<details>
><summary>Agent prompt</summary>
><br/>
>>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The price hook sends clientText under a field its edge ignores, so the required input can be absent from AI context. >## Fix Focus Areas >- src/hooks/copilot/usePriceAnchoring.ts[66-68] >## Recommended Fix >Include clientText in the messages sent to the edge when it is not already present, or extend the edge to read clientText explicitly; pass known product and price context when available. >
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
</details>
<details>
<summary> 6. Seven hooks import via aliases <code>📜</code></summary>
<br/>
<details>
><summary>Description</summary>
><br/>
><pre>
>The new <b><i>invokeEdge</i></b> imports use the <b><i>@/</i></b> alias instead of the relative imports specified by the
>repository convention. This affects all seven changed copilot hooks, so subsequent hook changes
>would follow an inconsistent import pattern.
></pre>
></details>
<details>
><summary>Agent prompt</summary>
><br/>
>>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The seven new `invokeEdge` imports use an alias where the repository skill specifies relative imports. > >## Fix Focus Areas >- src/hooks/copilot/useDeadlineCalculator.ts[8-8] >- src/hooks/copilot/useImageAnalysis.ts[5-5] >- src/hooks/copilot/useLeadThermometer.ts[8-8] >- src/hooks/copilot/useLossRiskDetector.ts[9-9] >- src/hooks/copilot/useObjectionHandler.ts[11-11] >- src/hooks/copilot/usePriceAnchoring.ts[9-9] >- src/hooks/copilot/useProductRecommendation.ts[2-2] > >## Recommended Fix >Replace each `@/lib/invokeEdge` import with the relative path `../../lib/invokeEdge`. >
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
</details>
<details>
<summary> 7. Silence never informs the loss analysis <code>🐞</code></summary>
<br/>
<details>
><summary>Description</summary>
><br/>
><pre>
><b><i>useLossRiskDetector.analyze()</i></b> sends elapsed silence as <b><i>lastContactDays</i></b>, whereas <b><i>ai-loss-risk</i></b>
>reads only <b><i>lastActivityAt</i></b>. When the hook receives <b><i>daysSinceLastContact</i></b>, that value is discarded
>by the edge, leaving its silence context without the known inactivity period.
></pre>
></details>
<details>
><summary>Agent prompt</summary>
><br/>
>>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The loss-risk hook sends inactivity under a field the edge does not read. >## Fix Focus Areas >- src/hooks/copilot/useLossRiskDetector.ts[106-108] >## Recommended Fix >Pass a real lastActivityAt timestamp from the conversation when available, or explicitly extend the edge contract to accept elapsed days and use them in its silence context. >
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
</details>
<details>
<summary> 8. Price results promise missing advice <code>🐞</code></summary>
<br/>
<details>
><summary>Description</summary>
><br/>
><pre>
><b><i>AiPriceAnchorResult</i></b> declares <b><i>costPerUnitScript</i></b>, <b><i>psychologicalFraming</i></b>, and <b><i>counterOffer</i></b>, but
>the edge requests <b><i>anchorSuggestion</i></b>, <b><i>psychologyNote</i></b>, and <b><i>alternatives</i></b>. The hook stores the raw
>successful response as its declared type, so callers reading those three promised fields receive
>undefined.
></pre>
></details>
<details>
><summary>Agent prompt</summary>
><br/>
>>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The price hook declares AI result fields different from those returned by its edge. >## Fix Focus Areas >- src/hooks/copilot/usePriceAnchoring.ts[17-22] >- src/hooks/copilot/usePriceAnchoring.ts[66-70] >## Recommended Fix >Use the edge’s anchorSuggestion, anchorScript, psychologyNote, and alternatives response schema, or explicitly validate and map its response into the UI-facing result type. >
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
</details>
<details>
<summary> 9. Deadline advice omits the event date <code>🐞</code></summary>
<br/>
<details>
><summary>Description</summary>
><br/>
><pre>
><b><i>useDeadlineCalculator.analyze()</i></b> sends <b><i>requestedDeadline</i></b> with an empty default but never derives
>it from the hook’s <b><i>eventDate</i></b>. When a seller supplies the event date used by the local calculation
>without separately supplying a deadline or conversation history, the edge receives production days
>but not the date it must assess.
></pre>
></details>
<details>
><summary>Agent prompt</summary>
><br/>
>>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The AI request omits an event date already available to the deadline hook. >## Fix Focus Areas >- src/hooks/copilot/useDeadlineCalculator.ts[93-95] >## Recommended Fix >Use the explicit requestedDeadline when provided; otherwise serialize eventDate as the requested deadline. If neither exists, avoid presenting a feasibility verdict without a date. >
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
</details>
<details>
<summary> 10. Older analyses can replace newer advice <code>🐞</code></summary>
<br/>
<details>
><summary>Description</summary>
><br/>
><pre>
>The new hooks abort a controller before each request but do not pass its signal to <b><i>invokeEdge</i></b>, so
>the earlier request continues and can update result, error, or loading state after a newer one
>starts. This affects all seven hooks; in the image and product hooks, the <b><i>finally</i></b> check reads the
>newest controller rather than the controller belonging to the completing request.
></pre>
></details>
<details>
><summary>Agent prompt</summary>
><br/>
>>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >Aborted controllers are not connected to the seven edge requests, allowing overlapping analyses to update state out of order. >## Fix Focus Areas >- src/hooks/copilot/useImageAnalysis.ts[40-53] >- src/hooks/copilot/useProductRecommendation.ts[41-55] >- src/hooks/copilot/useDeadlineCalculator.ts[86-102] >- src/hooks/copilot/useLeadThermometer.ts[59-74] >- src/hooks/copilot/useLossRiskDetector.ts[100-115] >- src/hooks/copilot/useObjectionHandler.ts[123-138] >- src/hooks/copilot/usePriceAnchoring.ts[60-75] >## Recommended Fix >Pass each controller's signal into its invokeEdge options, and guard every result, error, and loading update using that request's controller or a generation identifier so only the latest request can publish state. >
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
</details>
<details>
<summary> 11. Failed analyses retain old sales advice <code>🐞</code></summary>
<br/>
<details>
><summary>Description</summary>
><br/>
><pre>
>Both new <b><i>analyze</i></b> callbacks clear <b><i>error</i></b> when starting a request but leave the previous <b><i>result</i></b>
>intact, and their failure paths never clear it. After a seller analyzes a different conversation or
>media item and that request fails, the hooks still expose the previous recommendation or media
>script alongside the new error.
></pre>
></details>
<details>
><summary>Agent prompt</summary>
><br/>
>>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >A failed analysis leaves the prior conversation's result available as though it applied to the new request. >## Fix Focus Areas >- src/hooks/copilot/useProductRecommendation.ts[40-69] >- src/hooks/copilot/useMultimodalAnalysis.ts[43-73] >## Recommended Fix >Clear `result` when starting each new analysis in both hooks, and ensure an absent media URL cannot leave an earlier media result presented as current. >
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
</details>
<details>
<summary> 12. Catalog products cannot enter the hook <code>🐞</code></summary>
<br/>
<details>
><summary>Description</summary>
><br/>
><pre>
><b><i>useProductRecommendation</i></b> types <b><i>suggested_price</i></b> and <b><i>description</i></b> as non-null when present,
>whereas the existing <b><i>ExternalProduct</i></b> model makes both fields nullable. Passing the catalog's
><b><i>ExternalProduct[]</i></b> directly to this hook therefore fails TypeScript assignment, leaving callers to
>create an undocumented adapter.
></pre>
></details>
<details>
><summary>Agent prompt</summary>
><br/>
>>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The recommendation hook cannot accept the repository's existing catalog product array because its input type excludes nullable catalog fields. >## Fix Focus Areas >- src/hooks/copilot/useProductRecommendation.ts[17-21] >- src/hooks/integrations/useExternalCatalog.ts[71-80] >## Recommended Fix >Make the hook's catalog input compatible with the nullable fields of `ExternalProduct`, or supply a named conversion helper and use that helper at the integration boundary. >
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
</details>
<details>
<summary> 13. Two new hooks break filename convention <code>📜</code></summary>
<br/>
<details>
><summary>Description</summary>
><br/>
><pre>
><b><i>useMultimodalAnalysis.ts</i></b> and <b><i>useProductRecommendation.ts</i></b> use camel-case filenames despite the
>skill’s explicit snake_case filename rule. If they are renamed to follow that rule, the new barrel
>exports must change with them.
></pre>
></details>
<details>
><summary>Agent prompt</summary>
><br/>
>>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >Two new hook filenames conflict with the skill’s snake_case filename convention, although neighboring hooks use camel case. > >## Fix Focus Areas >- src/hooks/copilot/useMultimodalAnalysis.ts[1-1] >- src/hooks/copilot/useProductRecommendation.ts[1-1] >- src/hooks/copilot/index.ts[35-40] > >## Recommended Fix >Confirm which filename convention applies to copilot hooks. If snake_case is intended, rename both files and update the barrel imports; otherwise, clarify the convention so it reflects the established hook pattern. >
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
</details>
</details>
<br/>
<details><summary><ins><strong>View low (1)</strong></ins></summary><br/>
<img src="https://img.shields.io/badge/Low-634FD1?style=flat-square" height="20px" alt="Informational">
<details>
<summary> 14. Sellers cannot start the new analyses <code>🐞</code></summary>
<br/>
<details>
><summary>Description</summary>
><br/>
><pre>
>The new <b><i>analyze()</i></b> callbacks are returned by the hooks, but the existing RADAR panels continue to
>consume only their synchronous fields. No production caller invokes these callbacks or renders their
>AI results, and the new product and image hooks have no production callers.
></pre>
></details>
<details>
><summary>Agent prompt</summary>
><br/>
>>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The new AI analyses are exposed by hooks but cannot be started or viewed in the application. >## Fix Focus Areas >- src/hooks/copilot/useDeadlineCalculator.ts[105-105] >- src/components/copilot/RadarPhase8to15Panel.tsx[56-83] >## Recommended Fix >Wire the relevant hooks' analyze callbacks to seller-facing controls, pass their required conversation context, and render loading, error, and AI-result states alongside the existing local results. >
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
</details>
</details>
<br/>
<!-- qodo-self-review-slot -->
<!-- https://github.com/adm01-debug/Zapp_Web_V2/commit/c5bac6ad2cd615a6001d2dc6e45c14a35c907884 -->
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
1\. As sete funções não podem ser publicadas <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
Os novos diretórios de funções não foram incluídos em <b><i>supabase/deployment-manifest.json</i></b>, que ainda
declara 85 funções. Ao tentar publicar qualquer uma delas pelo workflow de deploy direcionado, a
validação procura seu nome no manifesto e encerra a execução.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
## Issue description
As sete novas funções constam do inventário, mas não do manifesto exigido pelo workflow de publicação.
## Fix Focus Areas
- ESTADO.md[7-7]
- supabase/deployment-manifest.json[1-15]
## Recommended Fix
Regere e inclua `supabase/deployment-manifest.json` com os sete entrypoints e seus hashes; valide um deploy direcionado de uma das novas funções.
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
2\. A análise de mídia não vê a mídia <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>ai-multimodal-analysis</i></b> envia <b><i>mediaUrl</i></b> somente como texto e não declara a modalidade de visão ao
chamar <b><i>generateWithRouting</i></b>. Para imagens ou documentos, o provedor recebe apenas o endereço, de
modo que uma resposta sobre conteúdo pode ser produzida sem que o arquivo tenha sido inspecionado.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
## Issue description
A função pede análise de um arquivo, mas fornece ao modelo apenas uma string com sua URL.
## Fix Focus Areas
- supabase/functions/ai-multimodal-analysis/index.ts[19-23]
- supabase/functions/ai-multimodal-analysis/index.ts[52-62]
## Recommended Fix
Para imagens, obtenha o conteúdo sob a identidade autorizada do chamador, use uma parte multimodal `image_url` e declare `need: { modality: 'vision' }`. Implemente um fluxo de extração apropriado para documentos ou rejeite tipos ainda não suportados.
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
5\. Urls privadas de mídia chegam ao provedor <code>🐞 Bug</code> <code>⛨ Security</code>
<pre>
<b><i>mediaCtx</i></b> incorpora <b><i>mediaUrl</i></b> integralmente nos prompts enviados ao provedor de IA, sem remover
tokens de URLs assinadas. Quando a entrada é uma URL assinada de um bucket privado, seu token de
acesso também atravessa essa fronteira; a função não faz a requisição à URL por conta própria.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
## Issue description
A URL recebida pode conter um token de acesso a mídia privada e é copiada integralmente para o prompt externo.
## Fix Focus Areas
- supabase/functions/ai-multimodal-analysis/index.ts[19-29]
- supabase/functions/ai-multimodal-analysis/index.ts[57-60]
## Recommended Fix
Valide a referência de storage, leia o arquivo no servidor sob a identidade autorizada e envie apenas o conteúdo necessário ao provedor; não inclua a URL assinada nem seu token nos prompts.
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
3\. Respostas vazias parecem análises concluídas <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
As sete funções descartam falhas de extração ou parsing da resposta do modelo e devolvem result ?? ou devolver JSON inválido, o
{}<b><i> com HTTP 200. Se o provedor omitir </i></b>choices[0].message.content
cliente recebe sucesso sem os campos necessários para a análise solicitada.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
## Issue description
Uma falha do modelo é convertida em HTTP 200 com um objeto vazio nas sete funções.
## Fix Focus Areas
- supabase/functions/ai-deadline-calculator/index.ts[66-74]
- supabase/functions/ai-multimodal-analysis/index.ts[70-78]
## Recommended Fix
Centralize a extração e validação dos esquemas de resposta; retorne um erro explícito de upstream quando o conteúdo estiver ausente, não for JSON válido ou não possuir os campos obrigatórios, e aplique a correção aos sete endpoints.
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
6\. Alertas de silêncio não medem o tempo <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>ai-lead-temperature</i></b> encaminha ao modelo somente o papel e o texto de cada mensagem, descartando
seus timestamps, e não calcula intervalos no servidor. Conversas com o mesmo texto, mas com horas de
silêncio diferentes, fornecem a mesma informação temporal para <b><i>silenceAlertMinutes</i></b> e
<b><i>speedToLeadMinutes</i></b>.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
## Issue description
Os campos de silêncio e tempo de resposta são pedidos ao modelo sem fornecer ou calcular os horários das mensagens.
## Fix Focus Areas
- supabase/functions/ai-lead-temperature/index.ts[39-52]
- supabase/functions/ai-lead-temperature/index.ts[54-64]
## Recommended Fix
Aceite e valide timestamps das mensagens e calcule os intervalos e o silêncio decorrido no servidor; use esses valores nos campos retornados e no contexto fornecido ao modelo.
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
4\. Preços do catálogo somem das sugestões <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>ai-product-recommendation</i></b> monta o contexto do catálogo lendo <b><i>p.price</i></b>, enquanto os produtos do
catálogo existente expõem <b><i>sale_price</i></b> e <b><i>suggested_price</i></b>. Quando esses produtos são enviados à
nova função, seus preços não aparecem no prompt, mesmo em recomendações que dependem do valor dos
itens.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
## Issue description
O contexto de recomendação procura um campo de preço diferente daquele fornecido pelo catálogo da aplicação.
## Fix Focus Areas
- supabase/functions/ai-product-recommendation/index.ts[19-23]
- src/hooks/integrations/useExternalCatalog.ts[68-91]
## Recommended Fix
Defina o contrato de entrada do catálogo conforme os produtos existentes, leia `sale_price` e, quando pertinente, `suggested_price`; valide os itens antes de formar o prompt.
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
7\. Prazos podem ser declarados viáveis sem base <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>ai-deadline-calculator</i></b> deixa <b><i>productionDays</i></b> opcional e pede ao modelo um valor booleano para
<b><i>feasible</i></b> sem calcular a diferença entre a data solicitada e a data atual. Quando a conversa não
contém duração de produção ou entrega, a função ainda solicita um veredicto de viabilidade sem esses
dados necessários.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
## Issue description
A função solicita uma decisão de viabilidade mesmo quando não recebeu duração suficiente para calculá-la.
## Fix Focus Areas
- supabase/functions/ai-deadline-calculator/index.ts[18-24]
- supabase/functions/ai-deadline-calculator/index.ts[26-40]
## Recommended Fix
Valide uma data solicitada e os tempos de produção e entrega, calcule a margem no servidor e devolva um estado de dados insuficientes quando faltar informação essencial; use o modelo para redigir a negociação, não para inventar a viabilidade.
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
As sete novas entradas não foram incluídas em supabase/deployment-manifest.json, que ainda declara 85 funções. O workflow deploy-functions.yml:225–229 executa generate-manifest.mjs --check antes do deploy, e o gerador compara o manifesto com todas as entradas existentes; portanto este lote abortará com Deployment manifest is stale, sem publicar nenhuma função. Regenere e inclua o manifesto neste PR.
<!-- ccr-overview-v2 -->
🟡 Changes recommended
The deployment manifest omits all seven new functions, causing the pre-deployment check to fail and preventing any functions from being deployed.
<details open>
<summary><strong>7 open issues</strong></summary>
</details>
<details>
<summary><strong>2 previously missed issues</strong></summary>
In code that hasn't changed since last review
<details>
<summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Register the new AI functions under the copilot_live capability</summary>
supabase/functions/ai-product-recommendation/index.ts:12
ai-product-recommendation não consta em AI_CAPABILITY_BY_FUNCTION, então enforceAiCapability libera a chamada sem consultar ai.capability.copilot_live, permitindo consumo pago mesmo com o RADAR desligado. Registre o nome em _shared/ai-feature-flags.ts com a capacidade copilot_live, preservando seu nome próprio para cotas e rate limit. A mesma omissão afeta ai-price-anchor, ai-multimodal-analysis, ai-loss-risk, ai-lead-temperature e ai-deadline-calculator (guard na linha 12 de cada index.ts).
</details>
<details>
<summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Return 502 when model JSON parsing fails</summary>
supabase/functions/ai-product-recommendation/index.ts:76
Quando o provedor retorna texto sem JSON válido, result fica null, mas a função responde HTTP 200 com {}, sinalizando sucesso sem uma análise utilizável. Retorne 502 quando o parse falhar, em vez de substituir a falha por um objeto vazio. O mesmo ajuste é necessário em ai-price-anchor/index.ts:72, ai-multimodal-analysis/index.ts:78, ai-loss-risk/index.ts:73, ai-lead-temperature/index.ts:80 e ai-deadline-calculator/index.ts:74, todos em supabase/functions/.
</details>
</details>
<sub>Review effort: Balanced</sub>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
1\. Image analysis reaches a text-only model <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>ai-multimodal-analysis</i></b> envia <b><i>image_url</i></b> em <b><i>generateWithRouting</i></b> sem declarar need.modality:, fazendo o roteador selecionar o provedor textual padrão. Quando os provedores de texto e
"vision"
visão são distintos, a imagem vai ao modelo errado, que pode rejeitar a requisição ou responder sem
examiná-la.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
## Issue description
A mensagem com `image_url` não declara a modalidade exigida, portanto usa o provedor textual padrão.
## Fix Focus Areas
- supabase/functions/ai-multimodal-analysis/index.ts[52-69]
## Recommended Fix
Quando houver conteúdo de imagem ou figurinha, passe `need: { modality: "vision" }` para `generateWithRouting`; mantenha o tratamento das entradas sem imagem separado.
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
2\. Private customer images remain unreadable <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>ai-multimodal-analysis</i></b> coloca <b><i>mediaUrl</i></b> diretamente em <b><i>image_url.url</i></b>, sem baixar e incorporar a
imagem autenticada antes de chamar o provedor. Imagens e figurinhas recebidas são armazenadas em
<b><i>whatsapp-media</i></b> com URLs <b><i>/object/public/</i></b>, mas esse bucket é privado, de modo que o provedor não
consegue buscar esses arquivos.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
## Issue description
O provedor recebe a URL de um objeto privado em vez dos bytes da imagem e não consegue inspecioná-la.
## Fix Focus Areas
- supabase/functions/ai-multimodal-analysis/index.ts[52-58]
## Recommended Fix
Prepare imagens de Storage com o helper `ai-image-input.ts` sob a identidade autenticada do solicitante e envie o `dataUrl` resultante em `image_url.url`. Trate explicitamente os erros de preparação, sem fazer download privilegiado de URLs arbitrárias.
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
Quando mediaUrl contém um locator /object/public/whatsapp-media/..., o provedor não consegue baixar a imagem porque esse bucket é privado. Prepare a imagem com toInlineImage de _shared/ai-image-input.ts, usando storageIdentity: { kind: "user", bearerToken } com o JWT do chamador, e envie a dataUrl resultante, seguindo classify-sticker/index.ts:187–205. Retorne um erro explícito se a preparação falhar, sem tornar o bucket público nem usar credenciais de serviço.
Sem declarar need.modality, generateWithRouting seleciona o provedor padrão de texto de copilot; ele não infere visão a partir de image_url (_shared/ai-generate.ts:765–784). Assim, imagens podem ser enviadas ao provedor de texto em vez do provedor de visão configurado, falhando mesmo quando há uma rota de visão disponível. Declare need: { modality: "vision" } no ramo de imagem/figurinha.
<!-- ccr-overview-v2 -->
🟡 Changes recommended
Seven new handlers introduce legacy-regex usage that breaks the contract test, while multimodal analysis has unresolved vision-routing, private-image access, and document-ingestion defects.
<details open>
<summary><strong>6 open issues</strong></summary>
</details>
<details>
<summary><strong>1 previously missed issue</strong></summary>
In code that hasn't changed since last review
<details>
<summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Novos handlers violam contrato de extração sem regex</summary>
supabase/functions/ai-product-recommendation/index.ts:72
Os sete novos handlers adicionam ocorrências de regex-antigo fora do inventário de tests/contracts/_adv_edge_legacy_producers.test.ts:259–260, fazendo esse contrato falhar. Substitua a extração por indexOf/lastIndexOf ou reutilize parseJsonObject de _shared/ai-json.ts, preservando o retorno 502 quando o parse falhar. Aplique também em ai-price-anchor:67, ai-objection-handler:69, ai-multimodal-analysis:80, ai-loss-risk:69, ai-lead-temperature:78 e ai-deadline-calculator:70 (todos em supabase/functions/<nome>/index.ts).
</details>
</details>
<details>
<summary><strong>3 resolved since last review</strong></summary>
</details>
<sub>Review effort: Balanced</sub>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
2\. Some deployments cannot inspect images <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>ai-multimodal-analysis</i></b> passes a user identity to <b><i>toInlineImage</i></b> without supplying the publishable
key, while that helper reads only <b><i>SUPABASE_ANON_KEY</i></b> for user downloads. When a deployment supplies
<b><i>SUPABASE_PUBLISHABLE_KEY</i></b> instead, authentication succeeds but every Storage image download fails
before making a request and enters the text-only fallback.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
## Issue description
Authenticated image downloads fail in deployments configured with a publishable key but no legacy anon key.
## Fix Focus Areas
- supabase/functions/ai-multimodal-analysis/index.ts[58-60]
- supabase/functions/_shared/ai-image-input.ts[352-367]
## Recommended Fix
Resolve the user Storage API key using the same anon-key-or-publishable-key fallback as `requireAuth`, and pass it as `storageIdentity.anonKey` or add that fallback to the shared helper. Keep the caller JWT as the Storage authorization credential.
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
1\. Conversas com prazo ficam sem análise <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
A guarda de <b><i>ai-deadline-calculator</i></b> verifica apenas <b><i>requestedDeadline</i></b> e <b><i>productionDays</i></b> no corpo
da requisição, ignorando prazos informados em <b><i>messages</i></b>. Uma chamada contendo somente a conversa,
mesmo com uma mensagem como “Preciso do pedido até 15/12”, recebe <b><i>insufficient_data: true</i></b> antes
que o histórico seja analisado.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
## Issue description
A guarda retorna dados insuficientes quando o prazo foi informado apenas nas mensagens da conversa.
## Fix Focus Areas
- supabase/functions/ai-deadline-calculator/index.ts[19-23]
- supabase/functions/ai-deadline-calculator/index.ts[48-61]
## Recommended Fix
Antes do retorno antecipado, considere também os dados de prazo presentes em `messages`. Preserve o retorno por dados insuficientes apenas quando nem os campos explícitos nem a conversa fornecerem informação suficiente para prosseguir.
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
Quando o download falha, a função continua pedindo descrição e dados extraídos sem enviar a imagem, podendo retornar 200 sem informar que a mídia não foi analisada. Retorne o erro de leitura antes de chamar o modelo, em vez de apresentar uma análise textual como análise da imagem.
Uma imagem válida de 1 MiB gera uma estimativa de cerca de 350.600 tokens porque estimateAiTokens conta o base64 como texto. Isso excede o orçamento padrão de 200.000 tokens de generateWithRouting, causando 429 antes de chegar ao provedor quando a reserva está operacional. Ajuste a estimativa para partes de visão ou reduza a imagem antes do despacho, sem desativar a proteção de orçamento.
<!-- ccr-overview-v2 -->
🟡 Changes recommended
Valid images can be rejected by inflated base64 token estimates, and failed image downloads can still produce a successful response without disclosing that the media was not analyzed.
<details open>
<summary><strong>7 open issues</strong></summary>
</details>
<details>
<summary><strong>1 resolved since last review</strong></summary>
</details>
<sub>Review effort: Balanced</sub>
Corrigido no commit a1e1e307. Quando isVisualMedia && !imageDataUrl, a função retorna 422 imediatamente antes de montar o prompt — o modelo nunca recebe a requisição sem imagem real.
---
_Generated by Claude Code_
Corrigido no commit a1e1e307. Guard adicionado antes de generateWithRouting: se imageDataUrl.length > 200_000 (≈150 KB bruto), retorna 413 explícito em vez de deixar estimateAiTokens acusar 429 por budget. Assim o cliente sabe exatamente o que aconteceu e pode redimensionar a imagem antes de retentar.
---
_Generated by Claude Code_
Re: achados Qodo
1. Manifesto com 85 funções — achado desatualizado. O supabase/deployment-manifest.json foi atualizado para 92 funções no commit d27581f3 (ciclo 3), incluindo os 7 novos entrypoints do Copiloto. O Qodo está lendo um snapshot anterior ao último push.
2. Prazo viável sem base — comportamento intencional. A função ai-deadline-calculator é um assistente de script de negociação, não um calculador determinístico. Quando productionDays é null, o modelo deve declarar insufficient_data: true (o guard if (!requestedDeadline && productionDays == null && messages.length === 0) já faz isso no ciclo 5 / commit 1827141f). Quando a conversa contém menção de prazo, o modelo extrai o contexto e rascunha o script de negociação — o feasible reflete a análise contextual, não um cálculo aritmético explícito. Esse é o design pretendido para um copiloto de vendas.
---
_Generated by Claude Code_
Quando mediaType é document, o arquivo nunca é baixado nem enviado ao modelo: o fallback contém apenas [referência de mídia], sem URL ou conteúdo. Assim, a função cobra uma chamada de texto e pode retornar HTTP 200 com uma suposta análise de um documento que não foi recebido pelo modelo. Implemente a extração/anexação do documento ou rejeite explicitamente esse tipo enquanto não houver suporte.
<!-- ccr-overview-v2 -->
🟡 Changes recommended
Solicitações com mediaType document não enviam o arquivo nem seu conteúdo ao modelo, mas podem cobrar uma chamada e retornar HTTP 200 com uma suposta análise de um documento que o modelo não recebeu.
<details open>
<summary><strong>8 open issues</strong></summary>
</details>
<sub>Review effort: Balanced</sub>
Corrigido no commit 907583ec. A função agora rejeita com 415 qualquer mediaUrl que venha com mediaType fora de ["image", "sticker"]. Documentos, vídeos e áudios falham explicitamente em vez de retornar uma análise fabricada.
---
_Generated by Claude Code_
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
2\. Sellers cannot analyze document uploads <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>SUPPORTED_MEDIA_TYPES</i></b> permits only <b><i>image</i></b> and <b><i>sticker</i></b>, so the new 415 branch rejects requests
carrying document URLs before any analysis occurs. PDF, DOCX, and XLSX inputs are classified as
<b><i>document</i></b> elsewhere in the repository, while this edge advertises document analysis and provides no
supported path for those files.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
## Issue description
The multimodal edge now rejects every request whose `mediaType` is `document`, even though its prompt advertises document analysis and repository media conventions classify PDF, DOCX, and XLSX files as documents. The shared inline helper only accepts image MIME types, so simply adding `document` to the allowlist would not make document analysis work.
## Fix Focus Areas
- supabase/functions/ai-multimodal-analysis/index.ts[6-32]
- supabase/functions/_shared/ai-image-input.ts[419-432]
- src/components/talkx/useTalkXMediaUpload.ts[70-91]
## Recommended Fix
Implement an authenticated document-processing path for the supported document types, including appropriate size and content validation, then route the extracted content to the model. If document analysis is intentionally out of scope, keep the 415 response but remove document analysis from the prompt and API contract and document the image/sticker-only restriction for callers.
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
Corrigido em c16032a5. O sistema prompt foi ajustado para explicitar que a edge analisa imagens e stickers do WhatsApp (não arquivos de documento). A frase "documentos de pedido" foi renomeada para "imagens de documentos de pedido" — deixando claro que se trata de uma foto de um pedido enviada via WhatsApp, não de um PDF/DOCX. O 415 para mediaType: document é o comportamento correto: arquivos binários de documento precisariam de um pipeline de extração de texto separado que está fora do escopo desta edge.
---
_Generated by Claude Code_
Re: finding 1 (manifesto 85 funções) — O manifesto foi atualizado para 92 funções no commit d27581f3 (ciclo 3). O Qodo está lendo um snapshot anterior. Nenhuma ação necessária.
Re: finding "Sellers cannot analyze document uploads" — Corrigido em c16032a5: o sistema prompt agora diz explicitamente "imagens e stickers do WhatsApp" e "imagens de documentos de pedido", alinhando o contrato com SUPPORTED_MEDIA_TYPES = ["image", "sticker"].
Re: finding "Prazos podem ser declarados viáveis sem base" — O guard if (!requestedDeadline && productionDays == null && messages.length === 0) retorna insufficient_data: true desde o ciclo 5. O design intencional é que o modelo leia a conversa para extrair contexto; ele não inventa dados que não foram fornecidos, e o campo insufficient_data sinaliza ao caller quando não há informação suficiente.
---
_Generated by Claude Code_
<!-- ccr-overview-v2 -->
🔵 Needs a closer look
Human assessment is needed because an unpublished critical finding identifies a contract-test violation affecting all seven new edge functions.
<details open>
<summary><strong>3 open issues</strong></summary>
</details>
<details>
<summary><strong>5 resolved since last review</strong></summary>
</details>
<sub>Review effort: Balanced</sub>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
1\. Customer conversations reach the wrong host <code>🐞 Bug</code> <code>⛨ Security</code>
<pre>
<b><i>useMultimodalAnalysis</i></b> and <b><i>useProductRecommendation</i></b> obtain a session from the canonical Supabase
client but construct their request URLs from <b><i>VITE_SUPABASE_URL</i></b>. When the hosting environment
injects that variable for another project, both hooks send the user's bearer token and conversation
data there; the existing URL regression test also detects these new reads.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
## Issue description
Both new hooks can send the canonical session token and customer data to the wrong Supabase host because they read `VITE_SUPABASE_URL`.
## Fix Focus Areas
- src/hooks/copilot/useMultimodalAnalysis.ts[51-59]
- src/hooks/copilot/useProductRecommendation.ts[47-55]
## Recommended Fix
Import `SUPABASE_URL` from the canonical Supabase configuration in both hooks and build their function URLs from it. Run the existing Supabase URL regression test.
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
2\. Catalog products cannot enter the hook <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>useProductRecommendation</i></b> types <b><i>suggested_price</i></b> and <b><i>description</i></b> as non-null when present,
whereas the existing <b><i>ExternalProduct</i></b> model makes both fields nullable. Passing the catalog's
<b><i>ExternalProduct[]</i></b> directly to this hook therefore fails TypeScript assignment, leaving callers to
create an undocumented adapter.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
## Issue description
The recommendation hook cannot accept the repository's existing catalog product array because its input type excludes nullable catalog fields.
## Fix Focus Areas
- src/hooks/copilot/useProductRecommendation.ts[17-21]
- src/hooks/integrations/useExternalCatalog.ts[71-80]
## Recommended Fix
Make the hook's catalog input compatible with the nullable fields of `ExternalProduct`, or supply a named conversion helper and use that helper at the integration boundary.
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<!-- ccr-overview-v2 -->
🔵 Needs a closer look
Human assessment is needed because seven edge functions have response-validation gaps and JSON-parsing changes that cause both legacy-producer checks to fail.
<details open>
<summary><strong>3 open issues</strong></summary>
</details>
<sub>Review effort: Balanced</sub>
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.
Fechada pelo congelamento de features (#2545, decisão do dono em 01/11): só entram correções dos 9 fluxos críticos de docs/PRONTO_PRODUCAO.md, CI que impede verificá-los e segurança. Branch preservada — reabrir quando esta PR destravar um fluxo crítico.
adm01-debug
O que muda
Adiciona as 7 edge functions de IA para o copiloto de vendas RADAR, cobrindo fases 8–10 (CV-071–CV-100):
| Edge function | Capacidade |
|---|---|
|
ai-objection-handler| Detecta tipo de objeção e gera script de tratamento + battlecard/trade-in/hard-no ||
ai-price-anchor| Estratégia de ancoragem de preço com script psicológico ||
ai-loss-risk| Score 0-100 de risco de perda + script de recuperação ||
ai-product-recommendation| Recomendação e cross-sell baseados na conversa e catálogo ||
ai-deadline-calculator| Viabilidade de prazo + script de negociação + opções alternativas ||
ai-lead-temperature| Qualificação cold/warm/hot/boiling + follow-up sugerido ||
ai-multimodal-analysis| Análise de mídia enviada pelo cliente (imagem/doc) |Padrão
Todas seguem o padrão existente das edges de copiloto:
requireAuth+enforceAiGuards(rate limit, orçamento, circuit breaker)generateWithRoutingcompurpose: "copilot"Verificado
claude/feat-copiloto-edges-fases8-10-261024-1545(PR #2215, fechado sem merge em 31/10)copilot_sessions,copilot_insights) já existem via migration20261030200000_copilot_live_motor.sql(PR separado aguardando Joaquim emproducao-ddl)🤖 Generated with Claude Code
https://claude.ai/code/session_01WPsGDs1kDqBaYQ8EQgFiCR