Files
SLACK_COORD_RELATORIO/n8n/nodes/decide-needs-ai.node.js
T
GustavoandClaude Sonnet 5 482b7ef48e fix(v2): redefine AI actionability semantics + version the classifier (AI_CLASSIFIER_VERSION)
Production-readiness cycle. Classifier was excessively conservative (real
Run A: ACTIONABLE_NOW/UNASSIGNED_ACTIONABLE both 0) and made concrete
semantic mistakes on real tickets:
- #34419: technician "Rafael Brito" (internal) classified as WAITING_VENDOR
  waiting_for -- an internal technician is not a vendor.
- #37389: ticket had concrete open tasks ("Realizar um inventário das
  máquinas", "Alinhar o dia...") but was classified INSUFFICIENT_CONTEXT.
- Generic next_action ("Revisar chamado") repeated across unrelated
  tickets, proving nothing about real actionability.

Rewrote the system prompt (n8n/nodes/prepare-ai-prompt.node.js) with:
practical actionability definition ("suporte consegue fazer algo util
agora", explicit inclusion list); contatar-vs-aguardar distinction with
examples; WAITING_* requires positive evidence (action already taken AND
external dependency still open); technician-vs-vendor distinction citing
the TECNICO context field; STATUS Planejado alone != blocked/scheduled;
SCHEDULED requires an explicit date/window; mandatory chronological
interpretation (most recent apontamento wins over a superseded old
blocker); next_action must be concrete, with explicit accepted/rejected
examples; INSUFFICIENT_CONTEXT bar raised (ask "is there a diagnostic
step available even without full info" first).
n8n/nodes/prepare-ai-prompt.node.test.js: 10 new tests asserting each
rule's text is still present in the prompt (deterministic proxy --
behavioral proof comes from the real DEV run, inspected manually).

logic/classification.js: added AI_CLASSIFIER_VERSION=3 (stamped on every
valid classification); added a deterministic safety net (not just a
prompt hope) -- isWaitingForInternalTechnician() rejects WAITING_VENDOR
when waiting_for matches the ticket's own TECNICO field, routing to a new
fallback_reason 'ai_semantic_conflict' instead of accepting a known-wrong
semantic classification; added next_action genericness rejection
(isGenericNextAction) for ACTIONABLE_NOW/UNASSIGNED_ACTIONABLE only.
n8n/nodes/validate-ai-response.node.js: now passes the ticket into
validateAiClassification() so the technician guard has the facts it needs.

logic/cache.js: added buildCacheKey(contextHash, classifierVersion) ->
"<hash>:v<version>", stored in the same last_context_hash column (no
schema migration) -- bumping AI_CLASSIFIER_VERSION now forces a cache
miss on every ticket without manually clearing the Data Table.
n8n/nodes/decide-needs-ai.node.js / prepare-memoria-analise-record.node.js
updated to compute/persist the composite key.

logic/config.js: AI_MAX_CANDIDATES default raised 30->60 (now equals
CANDIDATE_POOL_SIZE) -- no candidate should go unanalyzed by an
artificial cap now that Run B already proved the cache makes repeat runs
cheap; AI_FALLBACK stays reserved for real provider failures. Also added
SEND_ENABLED (default false) and ENVIRONMENT config fields for the real
Slack send gate (used by logic/slack.js, next commit).

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

54 lines
2.2 KiB
JavaScript

// @requires config.js cache.js classification.js
// Instancia bloqueia $env em Code nodes -- config vem do node "Config - Coordenador GLPI v2".
const config = parseConfig($('Config - Coordenador GLPI v2').first().json);
const now = Date.now();
// $input vem do Merge - Aguardar Memoria (so existe para GARANTIR que os candidatos e a
// memoria ja foram buscados antes deste node rodar); os dados de verdade sao lidos por nome.
const items = $('Code - Mesclar Contexto e Calcular Hash').all().map((item) => item.json); // { ticket, contextHash }
const memoryRows = $('Data Table - Buscar Memoria').all().map((item) => item.json);
const memoryByTicket = {};
for (const row of memoryRows) memoryByTicket[String(row.ticket_id)] = row;
const withDecision = items.map((item) => {
const memory = memoryByTicket[String(item.ticket.id)] || null;
// Chave de cache = conteudo do chamado + versao do classificador (logic/cache.js). Bump de
// AI_CLASSIFIER_VERSION forca cache miss em TODO chamado, mesmo sem nenhuma mudanca real no
// GLPI -- sem precisar apagar a Data Table na mao (missao "finalizacao para producao", secao 12).
const cacheKey = buildCacheKey(item.contextHash, AI_CLASSIFIER_VERSION);
const analysis = needsReanalysis({ memory, currentHash: cacheKey, now });
return {
ticket: item.ticket, contextHash: item.contextHash, cacheKey, memory, needsAiReason: analysis.reason, needsAiRaw: analysis.needsAi,
};
});
const needingAi = withDecision
.filter((item) => item.needsAiRaw)
.sort((a, b) => (Number(b.ticket.score_criticidade) || 0) - (Number(a.ticket.score_criticidade) || 0));
const allowedIds = new Set(needingAi.slice(0, config.aiMaxCandidates).map((item) => item.ticket.id));
return withDecision.map((item) => {
let resolucao;
if (!item.needsAiRaw) {
resolucao = 'cache';
} else if (allowedIds.has(item.ticket.id)) {
resolucao = 'ia';
} else {
resolucao = 'fallback_cap';
}
return {
json: {
ticket: item.ticket,
contextHash: item.contextHash,
cacheKey: item.cacheKey,
memory: item.memory,
needsAiReason: item.needsAiReason,
resolucao,
precisa_ia: resolucao === 'ia',
config,
now,
},
};
});