Files
SLACK_COORD_RELATORIO/logic/slack.js
T
GustavoandClaude Sonnet 5 124516e64a fix(v2): fix "Validar e executar" bug (real root cause), expand generic-phrase blacklist, add FORCE_SEND
Root cause found for why the real Slack message showed "→ Validar e
executar" for nearly every ACTIONABLE_NOW ticket: logic/message.js's
ACTION_LABELS map had a hardcoded entry for ACTIONABLE_NOW that always
won over the AI's actual next_action field in shortActionLabel(). The
AI's real, specific, already-validated-as-non-generic next_action (e.g.
"Realizar inventário das máquinas") was being silently discarded for
display purposes on every single message. Fixed by removing the
ACTIONABLE_NOW entry -- it now falls through to the existing
next_action-based fallback (already there, just unreachable for that
class before). UNASSIGNED_ACTIONABLE intentionally keeps its fixed
"Atribuir técnico" label -- that IS the correct display for that class.

logic/classification.js: expanded GENERIC_NEXT_ACTION_PHRASES with the
exact phrase that leaked through ("validar e executar") plus the
mission's additional list (validar chamado, prosseguir atendimento,
executar chamado, tratar chamado, analisar chamado). Bumped
AI_CLASSIFIER_VERSION 3->4 since this changes what next_action values
validate as non-generic -- forces reclassification of any cached
candidate that only passed under the older, narrower blacklist.

n8n/nodes/validate-ai-response.node.js: generic-next-action rejections
now get their own distinct fallback_reason ('generic_or_unsupported_
next_action') instead of being lumped into 'invalid_json', matching the
same pattern already used for the technician-vendor conflict.

logic/slack.js + logic/config.js: added FORCE_SEND (default false).
Manual-triggered runs now never send for real even with SEND_ENABLED=
true in production, unless FORCE_SEND is also explicitly set -- protects
against someone clicking "Execute Workflow" in production and
accidentally re-sending today's digest.

Added format-safety regression tests (no literal backslash-n, URL never
bleeds into the next item's id, no markdown-wrapped URLs) -- verified
these were never actually triggered in a real send (the reported
corruption was n8n's raw JSON data-inspector view, not a delivered
Slack message; both manual runs in question had shouldSend:false).

169/169 tests passing.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-24 21:49:42 -03:00

65 lines
2.6 KiB
JavaScript

const { djb2Hash } = require('./hash');
// Hash estavel do texto exato que seria enviado -- usado como parte da chave de
// idempotencia (junto com report_date/run_type). Duas mensagens com o mesmo conteudo no
// mesmo dia nunca devem gerar dois envios reais.
function computeMessageHash(text) {
return djb2Hash(String(text || ''));
}
// SEND_ENABLED e o gate principal de "isso pode realmente sair pro Slack" -- nunca depende de
// editar codigo (missao "finalizacao para producao", secao 22). Runs 'manual' tem uma segunda
// trava: mesmo com SEND_ENABLED=true (producao), clicar "Execute Workflow" NAO envia de
// verdade a menos que FORCE_SEND tambem esteja ligado -- protege contra envio acidental por
// alguem testando/depurando em producao (missao "correcao final", secao 16/17).
function shouldSendByConfig(config, runType) {
if (!config || !config.sendEnabled) return false;
if (runType === 'manual' && !config.forceSend) return false;
return true;
}
// Idempotencia: so conta como "ja enviado" um registro com status 'success' para a MESMA
// data + tipo de execucao + hash de mensagem. Um retry apos falha (status 'failed') nao
// bloqueia um novo envio -- so um sucesso anterior bloqueia.
function alreadySentSuccessfully(existingRecords, { reportDate, runType, messageHash }) {
return (existingRecords || []).some((record) => (
record
&& record.status === 'success'
&& record.report_date === reportDate
&& record.run_type === runType
&& record.message_hash === messageHash
));
}
// Decisao unica de "devo mandar pro Slack agora" -- centraliza os dois motivos possiveis de
// NAO enviar (SEND_ENABLED=false, ou ja enviado com sucesso hoje) num so lugar auditavel.
function evaluateSendGuard({ config, existingRecords, reportDate, runType, messageHash }) {
if (!shouldSendByConfig(config, runType)) {
const reason = runType === 'manual' && config && config.sendEnabled ? 'manual_run_needs_force_send' : 'send_disabled';
return { shouldSend: false, reason };
}
if (alreadySentSuccessfully(existingRecords, { reportDate, runType, messageHash })) {
return { shouldSend: false, reason: 'already_sent' };
}
return { shouldSend: true, reason: 'ok' };
}
function buildEnvioDigestRecord({ reportDate, runType, messageHash, sentAt, status, errorDetail }) {
return {
report_date: reportDate,
run_type: runType,
message_hash: messageHash,
sent_at: sentAt,
status,
error_detail: errorDetail || null,
};
}
module.exports = {
computeMessageHash,
shouldSendByConfig,
alreadySentSuccessfully,
evaluateSendGuard,
buildEnvioDigestRecord,
};