@peopl-health/nexus 5.75.1 → 5.75.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -35,6 +35,14 @@ const triageRecommendationEventSchema = new mongoose.Schema({
|
|
|
35
35
|
gateLatencyMs: { type: Number, default: null },
|
|
36
36
|
planLatencyMs: { type: Number, default: null },
|
|
37
37
|
planMaxOutputTokens: { type: Number, default: null },
|
|
38
|
+
planRetryReasons: {
|
|
39
|
+
type: [new mongoose.Schema({
|
|
40
|
+
attempt: { type: Number, required: true },
|
|
41
|
+
reason: { type: String, required: true },
|
|
42
|
+
paths: { type: [String], default: undefined },
|
|
43
|
+
}, { _id: false })],
|
|
44
|
+
default: undefined,
|
|
45
|
+
},
|
|
38
46
|
totalLatencyMs: { type: Number, default: null },
|
|
39
47
|
triageStored: { type: Boolean, default: null },
|
|
40
48
|
unmappedAnswerCount: { type: Number, default: null },
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
const { getTriageRecommendationEventModel } = require('../models/triageRecommendationEventModel');
|
|
1
2
|
const { buildRetriggerPayload } = require('../helpers/triageRetriggerHelper');
|
|
2
3
|
const { Symptoms_ID } = require('../../config/airtableConfig');
|
|
3
4
|
const { logger } = require('../../utils/logger');
|
|
@@ -23,6 +24,23 @@ const RETRY_SETTLE_MS = 5 * 60 * 1000;
|
|
|
23
24
|
const retryClaims = new WriteClaimStore({ namespace: 'recom-orphan-retry', ttlMs: CLAIM_TTL_MS, maxSize: 500 });
|
|
24
25
|
const ticketClaims = new WriteClaimStore({ namespace: 'recom-orphan-ticket', ttlMs: SCAN_WINDOW_MS, maxSize: 500 });
|
|
25
26
|
|
|
27
|
+
const FAILURE_REASONS = {
|
|
28
|
+
gate_inconsistent: 'el filtro de seguridad devolvió una urgencia inconsistente',
|
|
29
|
+
gate_malformed: 'el filtro de seguridad devolvió una respuesta inválida',
|
|
30
|
+
gate_incomplete: 'el filtro de seguridad no terminó su respuesta',
|
|
31
|
+
gate_provider_failed: 'el proveedor del modelo falló en el filtro de seguridad',
|
|
32
|
+
plan_provider_failed: 'el proveedor del modelo falló al armar las recomendaciones',
|
|
33
|
+
plan_incomplete: 'el plan de recomendaciones quedó incompleto',
|
|
34
|
+
plan_invalid: 'el plan de recomendaciones no pasó la validación',
|
|
35
|
+
plan_malformed: 'el plan de recomendaciones llegó malformado',
|
|
36
|
+
plan_empty: 'el plan no trajo recomendaciones',
|
|
37
|
+
plan_all_denied: 'ninguna recomendación correspondía a los síntomas reportados',
|
|
38
|
+
mirror_failed: 'no se pudo guardar la fila de recomendaciones en Airtable',
|
|
39
|
+
profile_read_failed: 'no se pudo leer el perfil clínico',
|
|
40
|
+
no_clinical_profile: 'la paciente no tiene perfil clínico',
|
|
41
|
+
error: 'el generador falló inesperadamente',
|
|
42
|
+
};
|
|
43
|
+
|
|
26
44
|
const FIELDS = ['Created', 'triaje_symptoms_id', 'whatsapp_id', 'symptom_name_positive'];
|
|
27
45
|
|
|
28
46
|
const botIsPaused = (code) => threadIsPaused(code, { label: '[recommendationRecovery]' });
|
|
@@ -55,13 +73,36 @@ function describe(row) {
|
|
|
55
73
|
};
|
|
56
74
|
}
|
|
57
75
|
|
|
76
|
+
async function lastSettle(triageRecordId) {
|
|
77
|
+
try {
|
|
78
|
+
return await getTriageRecommendationEventModel()
|
|
79
|
+
.findOne({ triageRecordId }).sort({ createdAt: -1 }).select('status stage reason hardRejectIssues')
|
|
80
|
+
.maxTimeMS(2000)
|
|
81
|
+
.lean();
|
|
82
|
+
} catch (error) {
|
|
83
|
+
logger.warn('[recommendationRecovery] could not read the last settle event', { triageRecordId, error: error.message });
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function failureReason(settle) {
|
|
89
|
+
if (settle === undefined) return { label: 'motivo no disponible', code: 'settle_unreadable' };
|
|
90
|
+
if (!settle) return { label: 'no hay registro de ejecución del generador', code: 'no_settle_event' };
|
|
91
|
+
const code = [settle.status, settle.stage, settle.reason].filter(Boolean).join('/');
|
|
92
|
+
return { label: FAILURE_REASONS[settle.reason] || `el generador terminó con ${code}`, code, issues: settle.hardRejectIssues || [] };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const issueText = (issue) => (typeof issue === 'string' ? issue : `${issue?.path}: ${issue?.problem}`);
|
|
96
|
+
|
|
58
97
|
async function fileOpsTicket(orphan) {
|
|
59
98
|
if (!orphan.code) return false;
|
|
99
|
+
const reason = failureReason(await lastSettle(orphan.triageRecordId));
|
|
100
|
+
const issues = reason.issues?.length ? ` Problemas: ${reason.issues.map(issueText).join('; ').slice(0, 500)}.` : '';
|
|
60
101
|
return recordUnresolvedRequest({
|
|
61
102
|
code: orphan.code,
|
|
62
103
|
trace: null,
|
|
63
|
-
question:
|
|
64
|
-
details: `Triaje ${orphan.triageId ?? orphan.triageRecordId} (${orphan.createdAt}) con ${orphan.positiveSymptoms} síntomas positivos no tiene recomendaciones. Revisar si procede reenviarlas.`,
|
|
104
|
+
question: `El triaje de la paciente no generó recomendaciones: ${reason.label}.`,
|
|
105
|
+
details: `Triaje ${orphan.triageId ?? orphan.triageRecordId} (${orphan.createdAt}) con ${orphan.positiveSymptoms} síntomas positivos no tiene recomendaciones. Motivo: ${reason.code}.${issues} Revisar si procede reenviarlas.`,
|
|
65
106
|
category: 'contact_team_member',
|
|
66
107
|
urgency: 'soon',
|
|
67
108
|
});
|
|
@@ -186,6 +227,7 @@ module.exports = {
|
|
|
186
227
|
DEFAULT_SWEEP_INTERVAL_MS,
|
|
187
228
|
sweepUnrecoveredTriages,
|
|
188
229
|
orphanFormula,
|
|
230
|
+
_fileOpsTicket: fileOpsTicket,
|
|
189
231
|
_handledClaims: retryClaims,
|
|
190
232
|
_ticketClaims: ticketClaims,
|
|
191
233
|
CLAIM_TTL_MS,
|
|
@@ -610,6 +610,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
|
|
|
610
610
|
settle.planLatencyMs = Date.now() - planStart;
|
|
611
611
|
settle.attempts = planOutcome.attempts;
|
|
612
612
|
settle.planMaxOutputTokens = planOutcome.planMaxOutputTokens;
|
|
613
|
+
if (planOutcome.retryReasons.length) settle.planRetryReasons = planOutcome.retryReasons;
|
|
613
614
|
if (planOutcome.safetyUncertain) settle.supportSafetyCleared = false;
|
|
614
615
|
if (planOutcome.failure) return finish({ ...planOutcome.failure, autoRepairs: [...gateRepairs, ...(planOutcome.repairs || [])] });
|
|
615
616
|
const { plan, planRepairs, qualityWarnings } = planOutcome;
|
|
@@ -748,10 +749,19 @@ async function pendingMirrorPayload(runId) {
|
|
|
748
749
|
...(excludeRecordId ? { excludeRecordId } : {}), ...(excludeRecordIds ? { excludeRecordIds } : {}) };
|
|
749
750
|
}
|
|
750
751
|
|
|
751
|
-
function gateCorrectionNote(issues) {
|
|
752
|
+
function gateCorrectionNote(issues, repairs = []) {
|
|
753
|
+
const statusRepairs = repairs.filter((repair) => repair.includes('(aritmética de eventos)'));
|
|
752
754
|
return [
|
|
753
755
|
'Tu respuesta anterior fue rechazada por incoherencia del gate:',
|
|
754
756
|
...issues.map((issue) => `- ${issue}`),
|
|
757
|
+
...(statusRepairs.length ? [
|
|
758
|
+
'El servidor recalculó el estado de tus red flags a partir de sus eventos:',
|
|
759
|
+
...statusRepairs.map((repair) => `- ${repair}`),
|
|
760
|
+
'Un red flag solo es confirmed o partially_confirmed si events_confirmed copia textualmente al menos un '
|
|
761
|
+
+ 'clinical_event de su definition que el paciente sí reportó; con events_confirmed vacío queda inconclusive '
|
|
762
|
+
+ '(o denied si hay events_denied). Si el paciente reportó un evento que forma parte del red flag, inclúyelo '
|
|
763
|
+
+ 'en definition y cópialo igual en events_confirmed.',
|
|
764
|
+
] : []),
|
|
755
765
|
'Corrige y vuelve a emitir el gate completo. Si no puedes sostener urgent_under_24h=true '
|
|
756
766
|
+ 'con al menos un red flag confirmed o partially_confirmed, emítelo como false.',
|
|
757
767
|
].join('\n');
|
|
@@ -776,7 +786,7 @@ async function runGate({ provider, presetId, casoBase, routeFloor, rid, code, pa
|
|
|
776
786
|
attempts = attempt;
|
|
777
787
|
const last = attempt === GATE_MAX_ATTEMPTS;
|
|
778
788
|
const input = [{ role: 'user', content: casoBase }];
|
|
779
|
-
if (priorIssues) input.push({ role: 'user', content: gateCorrectionNote(priorIssues) });
|
|
789
|
+
if (priorIssues) input.push({ role: 'user', content: gateCorrectionNote(priorIssues, gateRepairs) });
|
|
780
790
|
let result;
|
|
781
791
|
try {
|
|
782
792
|
result = await callProviderWithBackoff(() => provider.runStructured({
|
|
@@ -863,12 +873,21 @@ async function runGate({ provider, presetId, casoBase, routeFloor, rid, code, pa
|
|
|
863
873
|
return { attempts, gate, gateRepairs, gateWarnings };
|
|
864
874
|
}
|
|
865
875
|
|
|
876
|
+
// Validator issue paths only (never the problem text), indices collapsed so retries aggregate.
|
|
877
|
+
function issuePaths(issues) {
|
|
878
|
+
return [...new Set(issues.map((issue) => String(issue.path || '').replace(/\[[^\]]*\]/g, '[]')).filter(Boolean))];
|
|
879
|
+
}
|
|
880
|
+
|
|
866
881
|
async function runPlan({ provider, presetId, casoBase, gate, boundary = null, rankContext = {}, rid, code, payload }) {
|
|
867
882
|
const planInput = `${casoBase}\n\n### Gate de seguridad comprometido (PASO 1)\n${JSON.stringify(buildLegacyStep1(gate))}`;
|
|
868
883
|
let lastIssues = [];
|
|
869
884
|
let safetyUncertain = false;
|
|
870
885
|
let maxOutputTokens = null;
|
|
871
|
-
const
|
|
886
|
+
const retryReasons = [];
|
|
887
|
+
const retried = (attempt, reason, issues = null) => {
|
|
888
|
+
retryReasons.push(issues ? { attempt, reason, paths: issuePaths(issues) } : { attempt, reason });
|
|
889
|
+
};
|
|
890
|
+
const outcome = (result) => ({ ...result, safetyUncertain, planMaxOutputTokens: maxOutputTokens, retryReasons });
|
|
872
891
|
const buildPlan = (takeaways, elements) => new RecommendationPlan({
|
|
873
892
|
runId: rid,
|
|
874
893
|
patientId: code,
|
|
@@ -906,13 +925,16 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
|
|
|
906
925
|
} catch {
|
|
907
926
|
lastIssues = [];
|
|
908
927
|
if (last) return outcome({ attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_provider_failed' } });
|
|
928
|
+
retried(attempt, 'plan_provider_failed');
|
|
909
929
|
continue;
|
|
910
930
|
}
|
|
911
931
|
if (result?.status && result.status !== 'completed') {
|
|
912
932
|
lastIssues = [{ path: 'plan', problem: `respuesta incompleta del proveedor (status=${result.status})` }];
|
|
913
933
|
firstEvidence = firstEvidence ?? rawEvidence(result);
|
|
914
934
|
if (last) return outcome({ attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_incomplete', hardRejectIssues: lastIssues, rawExcerpt: firstEvidence } });
|
|
915
|
-
|
|
935
|
+
const isTruncated = hitTokenLimit(result);
|
|
936
|
+
if (isTruncated) maxOutputTokens = truncationBudget(result, maxOutputTokens);
|
|
937
|
+
retried(attempt, isTruncated ? 'plan_truncated' : 'plan_incomplete');
|
|
916
938
|
continue;
|
|
917
939
|
}
|
|
918
940
|
const parsed = safeParse(readStructuredText(result), null);
|
|
@@ -920,6 +942,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
|
|
|
920
942
|
if (!isPlainObject(parsed)) {
|
|
921
943
|
lastIssues = [{ path: 'plan', problem: 'la respuesta no es un objeto JSON válido' }];
|
|
922
944
|
if (last) return outcome({ attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_malformed', rawExcerpt: firstEvidence } });
|
|
945
|
+
retried(attempt, 'plan_malformed');
|
|
923
946
|
continue;
|
|
924
947
|
}
|
|
925
948
|
const rawPlan = isPlainObject(parsed.input) ? parsed.input : parsed;
|
|
@@ -928,7 +951,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
|
|
|
928
951
|
const rawElements = arr(arrayArg(rawPlan.elements));
|
|
929
952
|
if (!takeaways || !rawElements.length) {
|
|
930
953
|
lastIssues = [{ path: 'elements', problem: 'takeaways y elements[] no vacío son obligatorios' }];
|
|
931
|
-
if (attempt < PLAN_MAX_ATTEMPTS) continue;
|
|
954
|
+
if (attempt < PLAN_MAX_ATTEMPTS) { retried(attempt, 'plan_empty'); continue; }
|
|
932
955
|
return outcome({ attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_empty', rawExcerpt: firstEvidence } });
|
|
933
956
|
}
|
|
934
957
|
|
|
@@ -940,7 +963,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
|
|
|
940
963
|
deniedTargetsStripped = stripped;
|
|
941
964
|
if (!elements.length) {
|
|
942
965
|
lastIssues = [{ path: 'elements', problem: 'ningún elemento nombra un síntoma reportado en este triaje; construye el plan sobre los síntomas que el paciente sí reportó hoy' }];
|
|
943
|
-
if (attempt < PLAN_MAX_ATTEMPTS) continue;
|
|
966
|
+
if (attempt < PLAN_MAX_ATTEMPTS) { retried(attempt, 'plan_all_denied'); continue; }
|
|
944
967
|
return outcome({ attempts: attempt, repairs, failure: { status: 'failed', stage: 'validate', reason: 'plan_all_denied', hardRejectIssues: lastIssues } });
|
|
945
968
|
}
|
|
946
969
|
rankReordered = applyRankOrder(elements, gate, repairs, rankContext);
|
|
@@ -948,7 +971,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
|
|
|
948
971
|
const blocking = blockingIssues(issues);
|
|
949
972
|
if (blocking.length) {
|
|
950
973
|
lastIssues = blocking;
|
|
951
|
-
if (attempt < PLAN_MAX_ATTEMPTS) continue;
|
|
974
|
+
if (attempt < PLAN_MAX_ATTEMPTS) { retried(attempt, 'plan_invalid', blocking); continue; }
|
|
952
975
|
return outcome({ attempts: attempt, repairs, failure: { status: 'failed', stage: 'validate', reason: 'plan_invalid', hardRejectIssues: blocking } });
|
|
953
976
|
}
|
|
954
977
|
|
|
@@ -957,7 +980,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
|
|
|
957
980
|
plan = buildPlan(takeaways, elements);
|
|
958
981
|
} catch (err) {
|
|
959
982
|
lastIssues = [{ path: 'plan', problem: err?.message || 'DTO inválido' }];
|
|
960
|
-
if (attempt < PLAN_MAX_ATTEMPTS) continue;
|
|
983
|
+
if (attempt < PLAN_MAX_ATTEMPTS) { retried(attempt, 'plan_dto_invalid'); continue; }
|
|
961
984
|
return outcome({ attempts: attempt, repairs, failure: { status: 'failed', stage: 'validate', reason: 'plan_invalid', hardRejectIssues: lastIssues } });
|
|
962
985
|
}
|
|
963
986
|
return outcome({
|