@peopl-health/nexus 5.44.1 → 5.44.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.
@@ -2,6 +2,8 @@ const { Config_ID } = require('../../config/airtableConfig');
2
2
 
3
3
  const { getRecordByFilter } = require('../../services/airtableService');
4
4
 
5
+ const { ESCALATION_ROUTES } = require('../../shared/dtos/RecommendationSafetyGate');
6
+
5
7
  const { MapCache } = require('../../utils/MapCache');
6
8
  const { safeParse, safeParseArray, isPlainObject } = require('../../utils/jsonUtils');
7
9
 
@@ -14,6 +16,70 @@ const STOCHASTIC_DEFAULTS = { enabled: false, presetId: '' };
14
16
 
15
17
  const cache = new MapCache({ maxSize: 1, ttl: CACHE_TTL });
16
18
 
19
+ function parseSafetyFlagPatterns(value) {
20
+ if (!value) return [];
21
+ const parsedPatterns = safeParseArray(value);
22
+ if (!parsedPatterns) throw new Error('divergence config SAFETY_FLAG_PATTERNS is not a JSON array');
23
+ return parsedPatterns.map((row) => {
24
+ if (!isPlainObject(row)) throw new Error('divergence config SAFETY_FLAG_PATTERNS row is not an object');
25
+ const { flag, pattern } = row;
26
+ if (!flag || !pattern) throw new Error('divergence config SAFETY_FLAG_PATTERNS row missing flag or pattern');
27
+ try {
28
+ return { flag, re: new RegExp(pattern, 'i') };
29
+ } catch (err) {
30
+ throw new Error(`divergence config SAFETY_FLAG_PATTERNS pattern for ${flag} is not a valid regex: ${err.message}`);
31
+ }
32
+ });
33
+ }
34
+
35
+ function parseRedFlagMinRoute(row) {
36
+ if (!isPlainObject(row)) throw new Error('divergence config RED_FLAG_MIN_ROUTES row is not an object');
37
+ const {
38
+ flag,
39
+ ctcae_terms: ctcaeTerms,
40
+ min_route: minRoute,
41
+ max_action_time_hours: maxActionTimeHours,
42
+ requires_risk: requiresRisk = true,
43
+ } = row;
44
+ if (typeof flag !== 'string' || !flag.trim()) throw new Error('divergence config RED_FLAG_MIN_ROUTES row missing flag');
45
+ if (!Array.isArray(ctcaeTerms) || !ctcaeTerms.length || !ctcaeTerms.every((term) => typeof term === 'string' && term.trim())) {
46
+ throw new Error(`divergence config RED_FLAG_MIN_ROUTES ctcae_terms for ${flag} is not a non-empty list of terms`);
47
+ }
48
+ if (!ESCALATION_ROUTES.includes(minRoute)) {
49
+ throw new Error(`divergence config RED_FLAG_MIN_ROUTES min_route for ${flag} is not one of ${ESCALATION_ROUTES.join(', ')}`);
50
+ }
51
+ if (!Number.isInteger(maxActionTimeHours) || maxActionTimeHours < 1 || maxActionTimeHours > 24) {
52
+ throw new Error(`divergence config RED_FLAG_MIN_ROUTES max_action_time_hours for ${flag} is not an integer from 1 to 24`);
53
+ }
54
+ if (typeof requiresRisk !== 'boolean') throw new Error(`divergence config RED_FLAG_MIN_ROUTES requires_risk for ${flag} is not a boolean`);
55
+ return {
56
+ flag, ctcaeTerms, minRoute, maxActionTimeHours, requiresRisk,
57
+ };
58
+ }
59
+
60
+ function parseRedFlagMinRoutes(value) {
61
+ const routes = { rows: [], invalidRows: [] };
62
+ if (!value) return routes;
63
+ const parsedRoutes = safeParseArray(value);
64
+ if (!parsedRoutes) throw new Error('divergence config RED_FLAG_MIN_ROUTES is not a JSON array');
65
+ for (const row of parsedRoutes) {
66
+ try {
67
+ routes.rows.push(parseRedFlagMinRoute(row));
68
+ } catch (err) {
69
+ routes.invalidRows.push(err.message);
70
+ }
71
+ }
72
+ return routes;
73
+ }
74
+
75
+ function parseIsolated(parse) {
76
+ try {
77
+ return { value: parse(), error: null };
78
+ } catch (error) {
79
+ return { value: null, error };
80
+ }
81
+ }
82
+
17
83
  async function load() {
18
84
  const cached = cache.get(CACHE_KEY);
19
85
  if (cached) return cached;
@@ -46,23 +112,13 @@ async function load() {
46
112
  const stochastic = { ...STOCHASTIC_DEFAULTS, ...(parsedStochastic || {}) };
47
113
  if (stochastic.enabled && !stochastic.presetId) throw new Error('divergence config STOCHASTIC.presetId is required when enabled');
48
114
 
49
- let safetyFlagPatterns = [];
50
- if (byKey.SAFETY_FLAG_PATTERNS) {
51
- const parsedPatterns = safeParseArray(byKey.SAFETY_FLAG_PATTERNS);
52
- if (!parsedPatterns) throw new Error('divergence config SAFETY_FLAG_PATTERNS is not a JSON array');
53
- safetyFlagPatterns = parsedPatterns.map((row) => {
54
- if (!isPlainObject(row)) throw new Error('divergence config SAFETY_FLAG_PATTERNS row is not an object');
55
- const { flag, pattern } = row;
56
- if (!flag || !pattern) throw new Error('divergence config SAFETY_FLAG_PATTERNS row missing flag or pattern');
57
- try {
58
- return { flag, re: new RegExp(pattern, 'i') };
59
- } catch (err) {
60
- throw new Error(`divergence config SAFETY_FLAG_PATTERNS pattern for ${flag} is not a valid regex: ${err.message}`);
61
- }
62
- });
63
- }
64
-
65
- const config = { FIELDS: fields, ORACLE_CONNECTION: oracleConnection, STOCHASTIC: stochastic, SAFETY_FLAG_PATTERNS: safetyFlagPatterns };
115
+ const config = {
116
+ FIELDS: fields,
117
+ ORACLE_CONNECTION: oracleConnection,
118
+ STOCHASTIC: stochastic,
119
+ SAFETY_FLAG_PATTERNS: parseIsolated(() => parseSafetyFlagPatterns(byKey.SAFETY_FLAG_PATTERNS)),
120
+ RED_FLAG_MIN_ROUTES: parseIsolated(() => parseRedFlagMinRoutes(byKey.RED_FLAG_MIN_ROUTES)),
121
+ };
66
122
  cache.set(CACHE_KEY, config);
67
123
  return config;
68
124
  }
@@ -72,9 +128,16 @@ async function get(key) {
72
128
  return config[key];
73
129
  }
74
130
 
131
+ async function getIsolated(key) {
132
+ const { value, error } = await get(key);
133
+ if (error) throw error;
134
+ return value;
135
+ }
136
+
75
137
  module.exports = {
76
138
  getFields: () => get('FIELDS'),
77
139
  getOracleConnection: () => get('ORACLE_CONNECTION'),
78
140
  getStochastic: () => get('STOCHASTIC'),
79
- getSafetyFlagPatterns: () => get('SAFETY_FLAG_PATTERNS'),
141
+ getSafetyFlagPatterns: () => getIsolated('SAFETY_FLAG_PATTERNS'),
142
+ getRedFlagMinRoutes: () => getIsolated('RED_FLAG_MIN_ROUTES'),
80
143
  };
@@ -1,8 +1,10 @@
1
1
  const { ESCALATION_ROUTES, RED_FLAG_STATUSES } = require('../../shared/dtos/RecommendationSafetyGate');
2
+ const { aliasClosure } = require('../../fhir/helpers/symptomAliasHelper');
2
3
  const { str, arr, strList } = require('../../utils/coercionUtils');
3
4
  const { foldAccents } = require('../../utils/formatUtils');
4
5
 
5
6
  const ECHO_SHARE = 0.5;
7
+ const ROUTE_FLOOR_UNVERIFIABLE_CODE = 'route_floor_unverifiable';
6
8
 
7
9
  const tokensOf = (text) => foldAccents(str(text)).toLowerCase().match(/[a-z0-9]{4,}/g) || [];
8
10
 
@@ -107,6 +109,93 @@ function normalizeGateEscalation(raw, repairs) {
107
109
  return { urgent, maxActionTimeHours, escalationRoute, reasonForEscalation };
108
110
  }
109
111
 
112
+ const routeUrgency = (route) => ESCALATION_ROUTES.indexOf(route);
113
+
114
+ const aliasKeySet = (catalog, terms) => new Set(terms.flatMap((term) => aliasClosure(catalog, term)));
115
+
116
+ function riskSymptomKeys(catalog, riskAssessment) {
117
+ return aliasKeySet(catalog, [
118
+ ...arr(riskAssessment?.predictedAes)
119
+ .filter((ae) => ae?.severityIfConfirmed === 'emergency')
120
+ .flatMap((ae) => arr(ae.relatedSymptomTerms)),
121
+ ...arr(riskAssessment?.diseaseRisks).flatMap((risk) => arr(risk?.relatedSymptomTerms)),
122
+ ]);
123
+ }
124
+
125
+ const unverifiableFloor = (subject, reason) => ({
126
+ path: 'escalation_route',
127
+ code: ROUTE_FLOOR_UNVERIFIABLE_CODE,
128
+ warning: true,
129
+ problem: `${subject}: ${reason}; el gate no se elevó`,
130
+ });
131
+
132
+ function applyRouteFloor(escalation, {
133
+ catalog,
134
+ rows = [],
135
+ invalidRows = [],
136
+ affirmedKeys = new Set(),
137
+ riskAssessment = null,
138
+ riskReadFailed = false,
139
+ freeTextPending = false,
140
+ configError = null,
141
+ } = {}, repairs = [], warnings = []) {
142
+ if (configError) {
143
+ warnings.push(unverifiableFloor('rutas mínimas no verificables', `no se pudo leer RED_FLAG_MIN_ROUTES (${configError})`));
144
+ return escalation;
145
+ }
146
+ if (invalidRows.length) {
147
+ warnings.push({
148
+ path: 'escalation_route',
149
+ code: ROUTE_FLOOR_UNVERIFIABLE_CODE,
150
+ warning: true,
151
+ problem: `rutas mínimas incompletas: se ignoraron filas inválidas de RED_FLAG_MIN_ROUTES (${invalidRows.join('; ')}); esas filas no pueden elevar el gate`,
152
+ });
153
+ }
154
+ const riskKeys = riskSymptomKeys(catalog, riskAssessment);
155
+ const fired = [];
156
+ for (const row of rows) {
157
+ const termKeys = [...aliasKeySet(catalog, row.ctcaeTerms)];
158
+ const eligibleKeys = termKeys.filter((key) => !row.requiresRisk || riskKeys.has(key));
159
+ if (eligibleKeys.some((key) => affirmedKeys.has(key))) {
160
+ fired.push(row);
161
+ } else if (row.requiresRisk && !riskAssessment && termKeys.some((key) => affirmedKeys.has(key))) {
162
+ const reason = riskReadFailed ? 'no se pudo leer el perfil de riesgo' : 'no hay perfil de riesgo';
163
+ warnings.push(unverifiableFloor(`ruta mínima ${row.minRoute} de ${row.flag} no verificable`, reason));
164
+ } else if (freeTextPending && eligibleKeys.length) {
165
+ warnings.push(unverifiableFloor(`ruta mínima ${row.minRoute} de ${row.flag} no verificable`, 'el clasificador del texto libre no ha terminado'));
166
+ }
167
+ }
168
+ if (!fired.length) return escalation;
169
+ const currentRoute = escalation.urgent ? escalation.escalationRoute : null;
170
+ const currentHours = escalation.urgent ? escalation.maxActionTimeHours : null;
171
+ const floorRoute = fired.map((row) => row.minRoute).sort((left, right) => routeUrgency(left) - routeUrgency(right))[0];
172
+ const floorHours = Math.min(...fired.map((row) => row.maxActionTimeHours));
173
+ const route = currentRoute && routeUrgency(currentRoute) <= routeUrgency(floorRoute) ? currentRoute : floorRoute;
174
+ const hours = Number.isInteger(currentHours) ? Math.min(currentHours, floorHours) : floorHours;
175
+ const routeRaised = route !== currentRoute;
176
+ const windowTightened = hours !== currentHours;
177
+ if (!routeRaised && !windowTightened) return escalation;
178
+ const flags = [...new Set(fired
179
+ .filter((row) => (routeRaised && row.minRoute === route) || (windowTightened && row.maxActionTimeHours === hours))
180
+ .map((row) => row.flag))].join(', ');
181
+ const changes = [
182
+ routeRaised ? `escalation_route ${currentRoute ? `'${currentRoute}'` : 'null'} → '${route}'` : null,
183
+ windowTightened ? `max_action_time_hours ${currentHours ?? 'null'} → ${hours}` : null,
184
+ escalation.urgent ? null : 'urgent_under_24h false → true',
185
+ ].filter(Boolean);
186
+ repairs.push(`ruta mínima por término reportado (${flags}): ${changes.join(', ')}`);
187
+ return {
188
+ ...escalation,
189
+ urgent: true,
190
+ maxActionTimeHours: hours,
191
+ escalationRoute: route,
192
+ reasonForEscalation: escalation.reasonForEscalation || `Término reportado en este triaje (${flags}): ruta mínima ${route}, máximo ${hours} h.`,
193
+ summary: [str(escalation.summary).trim(), `Ruta mínima aplicada por un término reportado en este triaje (${flags}): ${route}, máximo ${hours} h.`]
194
+ .filter(Boolean)
195
+ .join(' '),
196
+ };
197
+ }
198
+
110
199
  module.exports = {
111
200
  str,
112
201
  arr,
@@ -115,4 +204,5 @@ module.exports = {
115
204
  normalizeStatus,
116
205
  buildRedFlag,
117
206
  normalizeGateEscalation,
207
+ applyRouteFloor,
118
208
  };
@@ -4,7 +4,11 @@ const {
4
4
  } = require('../../fhir/helpers/symptomAliasHelper');
5
5
  const { str, strList } = require('../../utils/coercionUtils');
6
6
 
7
- const URGENT_CARD_NAME = 'Contacto con tu equipo médico hoy';
7
+ const URGENT_CARD_NAMES = {
8
+ equipo_tratante_hoy: 'Contacto con tu equipo médico hoy',
9
+ urgencias: 'Atención médica urgente',
10
+ emergencia: 'Atención médica inmediata',
11
+ };
8
12
  const SURFACE_MAX = 6;
9
13
 
10
14
  const itemTerm = (catalog, item) => (catalog?.item_index ? termForItem(catalog, item) : null);
@@ -120,29 +124,45 @@ function stripToReportedTargets(element, boundary) {
120
124
  return true;
121
125
  }
122
126
 
123
- function reframeOnReported(element, boundary) {
124
- const anchors = (boundary.reported || [])
125
- .filter((symptom) => survives(keyOf(symptom.ctcaeTerm), boundary))
126
- .slice(0, SURFACE_MAX);
127
- if (!anchors.length) return false;
128
- element.targetedCtcaeTerms = anchors.map((symptom) => symptom.ctcaeTerm);
129
- element.symptoms = element.symptoms.filter((symptom) => survives(keyOf(symptom.ctcaeTerm), boundary));
130
- setCardSurface(element, anchors.map((symptom) => symptom.label));
127
+ const deniedToday = (term, { deniedKeys, deniedAeKeys }) => deniedKeys.has(keyOf(term)) || deniedAeKeys.has(keyOf(term));
128
+
129
+ const ownTargetsOf = (element, boundary) => element.targetedCtcaeTerms.filter((term) => !deniedToday(term, boundary));
130
+
131
+ function keepTargets(element, targets, boundary) {
132
+ if (!targets.length) return false;
133
+ element.targetedCtcaeTerms = targets;
134
+ element.symptoms = element.symptoms.filter((symptom) => !deniedToday(symptom.ctcaeTerm, boundary));
131
135
  return true;
132
136
  }
133
137
 
138
+ const urgentCardName = (gate) => URGENT_CARD_NAMES[gate.escalationRoute] || URGENT_CARD_NAMES.urgencias;
139
+
134
140
  // El gate urgente viaja en esta tarjeta: se le cambia el rótulo, no se descarta.
135
141
  function reframeOnGate(element, boundary) {
136
142
  if (boundary.gate?.urgentUnder24h !== true || element.escalation?.urgentUnder24h !== true) return false;
137
- if (!reframeOnReported(element, boundary)) return false;
138
- element.nameShort = URGENT_CARD_NAME;
143
+ const own = ownTargetsOf(element, boundary);
144
+ const anchors = (boundary.reported || [])
145
+ .filter((symptom) => survives(keyOf(symptom.ctcaeTerm), boundary))
146
+ .slice(0, SURFACE_MAX)
147
+ .map((symptom) => symptom.ctcaeTerm);
148
+ const touchesDenial = [...element.targetedCtcaeTerms, ...element.symptoms.map((symptom) => symptom.ctcaeTerm)]
149
+ .some((term) => deniedToday(term, boundary));
150
+ const catalogLabels = own.map((term) => symptomRecord(boundary.catalog, resolveTerm(boundary.catalog, term))?.es);
151
+ const header = catalogLabels.every(Boolean) || touchesDenial
152
+ ? catalogLabels.filter(Boolean)
153
+ : strList(element.recommendation.symptomsPatientFacing);
154
+ if (!keepTargets(element, own.length ? own : anchors, boundary)) return false;
155
+ const name = urgentCardName(boundary.gate);
156
+ element.nameShort = name;
157
+ element.recommendation.symptomsPatientFacing = header.length ? [...new Set(header)].slice(0, SURFACE_MAX) : [name];
139
158
  return true;
140
159
  }
141
160
 
142
161
  function applyCardSurfaceBoundary(elements, boundary, repairs = [], { rescue = false } = {}) {
143
- if (!boundary) return { elements, dropped: 0, stripped: 0 };
162
+ if (!boundary) return { elements, dropped: 0, stripped: 0, urgentReframed: [] };
144
163
  const kept = [];
145
164
  const unanchored = [];
165
+ const urgentReframed = [];
146
166
  let dropped = 0;
147
167
  let stripped = 0;
148
168
  for (const element of elements) {
@@ -159,8 +179,9 @@ function applyCardSurfaceBoundary(elements, boundary, repairs = [], { rescue = f
159
179
  continue;
160
180
  }
161
181
  if (reframeOnGate(element, boundary)) {
162
- repairs.push(`elemento (rank ${element.rank}) reencuadrado sobre los síntomas reportados para conservar el gate urgente: ${breach.why}`);
182
+ repairs.push(`elemento (rank ${element.rank}) urgente conservado con un título genérico para mantener el gate: ${breach.why}`);
163
183
  stripped += 1;
184
+ urgentReframed.push(element);
164
185
  kept.push(element);
165
186
  continue;
166
187
  }
@@ -169,10 +190,10 @@ function applyCardSurfaceBoundary(elements, boundary, repairs = [], { rescue = f
169
190
  dropped += 1;
170
191
  }
171
192
  const rescued = rescue && !kept.length
172
- ? unanchored.sort((a, b) => a.rank - b.rank).find((element) => reframeOnReported(element, boundary))
193
+ ? unanchored.sort((a, b) => a.rank - b.rank).find((element) => keepTargets(element, ownTargetsOf(element, boundary), boundary))
173
194
  : null;
174
195
  if (rescued) {
175
- repairs.push(`elemento (rank ${rescued.rank}) reencuadrado sobre los síntomas reportados en vez de descartar el plan entero`);
196
+ repairs.push(`elemento (rank ${rescued.rank}) conservado sobre su propio objetivo en vez de descartar el plan entero`);
176
197
  kept.push(rescued);
177
198
  stripped += 1;
178
199
  dropped -= 1;
@@ -181,7 +202,9 @@ function applyCardSurfaceBoundary(elements, boundary, repairs = [], { rescue = f
181
202
  kept.sort((a, b) => a.rank - b.rank);
182
203
  kept.forEach((element, index) => { element.rank = index + 1; });
183
204
  }
184
- return { elements: kept, dropped, stripped };
205
+ return {
206
+ elements: kept, dropped, stripped, urgentReframed,
207
+ };
185
208
  }
186
209
 
187
210
  module.exports = {
@@ -7,6 +7,7 @@ const ESCALATION_ELLIPSIS = /…|\.\.\./;
7
7
  const ESCALATION_LENGTH_CODE = 'when_to_escalate_length';
8
8
  const SENTENCE_COUNT_CODE = 'main_recommendation_sentence_count';
9
9
  const ATTRIBUTION_CODE = 'unsourced_care_team_attribution';
10
+ const URGENT_WITHOUT_TODAY_EVIDENCE_CODE = 'urgent_without_today_evidence';
10
11
 
11
12
  const ATTRIBUTIONS = [
12
13
  'como lo indico tu equipo', 'tal como lo indico tu equipo', 'como te lo indico tu equipo',
@@ -138,6 +139,15 @@ function validate(elements, options = {}) {
138
139
  issues.push({ path: `${path}.recommendation`, problem: 'sin main_recommendation, sin otc_offer y sin followup=team_referral — el paciente no recibe nada' });
139
140
  }
140
141
  if (isTriagePlan) issues.push(...attributionIssues(patient, path));
142
+ if (isTriagePlan && options.urgentReframed?.includes(element)) {
143
+ issues.push({
144
+ path,
145
+ code: URGENT_WITHOUT_TODAY_EVIDENCE_CODE,
146
+ warning: true,
147
+ problem: 'la tarjeta urgente no nombra ningún síntoma reportado en este triaje; se conservó con un título '
148
+ + 'genérico para no perder el gate.',
149
+ });
150
+ }
141
151
  if (recommendation.otcOffer !== null) {
142
152
  for (const field of ['dose', 'frequency', 'duration', 'warnings']) {
143
153
  if (!recommendation.otcOffer[field]) {
@@ -1,10 +1,12 @@
1
1
  const { getTriageGate, getTriagePlan } = require('../config/subAgentsConfig');
2
- const { getSafetyFlagPatterns } = require('../config/divergenceConfig');
2
+ const { getSafetyFlagPatterns, getRedFlagMinRoutes } = require('../config/divergenceConfig');
3
3
  const { requireGatewayProvider } = require('../config/llmConfig');
4
4
  const { getTriageRecommendationEventModel } = require('../models/triageRecommendationEventModel');
5
5
  const { isShadowRun } = require('../helpers/shadowHelper');
6
6
  const { readOutputText } = require('../helpers/clinicalMentionHelper');
7
- const { str, arr, buildRedFlag, normalizeGateEscalation } = require('../helpers/recommendationGateHelper');
7
+ const {
8
+ str, arr, buildRedFlag, normalizeGateEscalation, applyRouteFloor,
9
+ } = require('../helpers/recommendationGateHelper');
8
10
  const { buildElement, nullableStr } = require('../helpers/recommendationPlanHelper');
9
11
  const { readClinicalProfile } = require('../helpers/clinicalProfileHelper');
10
12
  const {
@@ -265,7 +267,13 @@ async function generateTriageRecommendations({ payload, provider, runId = null }
265
267
  if (profile === undefined) return { ...settle, status: 'failed', stage: 'assemble', reason: 'profile_read_failed' };
266
268
  if (!profile) return { ...settle, status: 'failed', stage: 'assemble', reason: 'no_clinical_profile' };
267
269
 
268
- const [riskAssessment] = await readPatientRiskAssessments({ patientId: code, limit: 1 }).catch(() => []);
270
+ const riskRead = await readPatientRiskAssessments({ patientId: code, limit: 1 })
271
+ .then((assessments) => ({ assessments, failed: false }))
272
+ .catch((err) => {
273
+ logger.warn('[triageRecommendation] risk assessment unavailable; section degraded', { code, error: err?.message });
274
+ return { assessments: [], failed: true };
275
+ });
276
+ const [riskAssessment] = riskRead.assessments;
269
277
  // A failed read degrades the section; it must never fail the run.
270
278
  const [openCases, escalations] = await Promise.all([
271
279
  readSymptomCases({ patientId: code })
@@ -315,16 +323,40 @@ async function generateTriageRecommendations({ payload, provider, runId = null }
315
323
  ...freeTextDerivedSymptoms,
316
324
  ];
317
325
  const reportedKeys = symptomKeySet(catalog, reportedTerms);
326
+ const floorConfig = await getRedFlagMinRoutes()
327
+ .then(({ rows, invalidRows }) => ({ rows, invalidRows, configError: null }))
328
+ .catch((err) => {
329
+ logger.warn('[triageRecommendation] red-flag minimum routes unavailable; no route floor', { code, error: err?.message });
330
+ return { rows: [], invalidRows: [], configError: err?.message || 'desconocido' };
331
+ });
332
+ const routeFloor = {
333
+ catalog,
334
+ ...floorConfig,
335
+ affirmedKeys: reportedKeys,
336
+ riskAssessment,
337
+ riskReadFailed: riskRead.failed,
338
+ freeTextPending: settle.classifierPending === true && freeTextBits.length > 0,
339
+ };
318
340
 
319
341
  const gateStart = Date.now();
320
- const gateOutcome = await runGate({ provider, presetId: gatePresetId, casoBase: casoBaseFor('gate'), rid, code, payload });
342
+ const gateOutcome = await runGate({
343
+ provider, presetId: gatePresetId, casoBase: casoBaseFor('gate'), routeFloor, rid, code, payload,
344
+ });
321
345
  settle.gateLatencyMs = Date.now() - gateStart;
322
346
  settle.gateAttempts = gateOutcome.attempts;
323
- if (gateOutcome.failure) return { ...settle, ...gateOutcome.failure, autoRepairs: gateOutcome.gateRepairs || [] };
324
- const { gate, gateRepairs } = gateOutcome;
347
+ if (gateOutcome.failure) {
348
+ return {
349
+ ...settle,
350
+ ...gateOutcome.failure,
351
+ autoRepairs: gateOutcome.gateRepairs || [],
352
+ qualityWarnings: gateOutcome.gateWarnings || settle.qualityWarnings,
353
+ };
354
+ }
355
+ const { gate, gateRepairs, gateWarnings } = gateOutcome;
325
356
  settle.gateVerdict = gate.urgentUnder24h ? 'urgent' : 'clear';
326
357
  settle.urgentUnder24h = gate.urgentUnder24h;
327
358
  settle.escalationRoute = gate.escalationRoute;
359
+ settle.qualityWarnings = gateWarnings;
328
360
 
329
361
  const planStart = Date.now();
330
362
  const boundary = {
@@ -344,7 +376,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null }
344
376
  const { plan, planRepairs, qualityWarnings } = planOutcome;
345
377
  settle.elementCount = plan.elements.length;
346
378
  settle.autoRepairs = [...gateRepairs, ...planRepairs];
347
- settle.qualityWarnings = qualityWarnings;
379
+ settle.qualityWarnings = [...gateWarnings, ...qualityWarnings];
348
380
  settle.rankReordered = planOutcome.rankReordered;
349
381
  settle.deniedCardsDropped = planOutcome.deniedCardsDropped;
350
382
  settle.deniedTargetsStripped = planOutcome.deniedTargetsStripped;
@@ -404,7 +436,9 @@ function rejectedGateShape(rawGate, redFlags) {
404
436
  };
405
437
  }
406
438
 
407
- async function runGate({ provider, presetId, casoBase, rid, code, payload }) {
439
+ async function runGate({
440
+ provider, presetId, casoBase, routeFloor, rid, code, payload,
441
+ }) {
408
442
  let attempts = 0;
409
443
  let gateRepairs = [];
410
444
  let accepted = null;
@@ -468,7 +502,10 @@ async function runGate({ provider, presetId, casoBase, rid, code, payload }) {
468
502
  break;
469
503
  }
470
504
  if (!accepted) return { attempts, gateRepairs, failure: { status: 'failed', stage: 'safety_gate', reason: 'gate_malformed' } };
471
- const { summary, redFlags, urgent, maxActionTimeHours, escalationRoute, reasonForEscalation } = accepted;
505
+ const gateWarnings = [];
506
+ const {
507
+ summary, redFlags, urgent, maxActionTimeHours, escalationRoute, reasonForEscalation,
508
+ } = applyRouteFloor(accepted, routeFloor, gateRepairs, gateWarnings);
472
509
 
473
510
  let gate;
474
511
  try {
@@ -487,15 +524,21 @@ async function runGate({ provider, presetId, casoBase, rid, code, payload }) {
487
524
  });
488
525
  } catch (err) {
489
526
  logger.warn('[triageRecommendation] gate failed DTO validation', { code, runId: rid, error: err?.message });
490
- return { attempts, gateRepairs, failure: { status: 'failed', stage: 'safety_gate', reason: 'gate_malformed' } };
527
+ return {
528
+ attempts, gateRepairs, gateWarnings, failure: { status: 'failed', stage: 'safety_gate', reason: 'gate_malformed' },
529
+ };
491
530
  }
492
531
  try {
493
532
  await storeSafetyGate({ patientId: code, safetyGate: gate });
494
533
  } catch (err) {
495
534
  logger.error('[triageRecommendation] gate store failed', { code, runId: rid, error: err?.message });
496
- return { attempts, gateRepairs, failure: { status: 'failed', stage: 'fhir', reason: 'gate_store_failed' } };
535
+ return {
536
+ attempts, gateRepairs, gateWarnings, failure: { status: 'failed', stage: 'fhir', reason: 'gate_store_failed' },
537
+ };
497
538
  }
498
- return { attempts, gate, gateRepairs };
539
+ return {
540
+ attempts, gate, gateRepairs, gateWarnings,
541
+ };
499
542
  }
500
543
 
501
544
  async function runPlan({ provider, presetId, casoBase, gate, boundary = null, rid, code, payload }) {
@@ -564,7 +607,9 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ri
564
607
  repairs = [];
565
608
  const built = rawElements.map((raw) => buildElement(raw, repairs));
566
609
  stripOtcOffers(built, repairs);
567
- const { elements, dropped, stripped } = applyCardSurfaceBoundary(built, boundary, repairs, { rescue: last });
610
+ const {
611
+ elements, dropped, stripped, urgentReframed,
612
+ } = applyCardSurfaceBoundary(built, boundary, repairs, { rescue: last });
568
613
  deniedCardsDropped = dropped;
569
614
  deniedTargetsStripped = stripped;
570
615
  if (!elements.length) {
@@ -573,7 +618,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ri
573
618
  return { attempts: attempt, repairs, failure: { status: 'failed', stage: 'validate', reason: 'plan_all_denied', hardRejectIssues: lastIssues } };
574
619
  }
575
620
  rankReordered = applyRankOrder(elements, gate, repairs);
576
- const issues = validate(elements, { gate, lane: 'triage' });
621
+ const issues = validate(elements, { gate, lane: 'triage', urgentReframed });
577
622
  const blocking = blockingIssues(issues);
578
623
  if (blocking.length) {
579
624
  lastIssues = blocking;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.44.1",
3
+ "version": "5.44.3",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",