@peopl-health/nexus 5.45.0-dev.7119 → 5.45.0-dev.7121

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.
@@ -205,16 +205,21 @@ function buildSymptomsMetadata({
205
205
  return parts.join('\n');
206
206
  }
207
207
 
208
- const OPEN_CASE_RULE = 'Son contexto de razonamiento, NO material de tarjeta: úsalos para entender la '
209
- + 'evolución, agrupar, afinar el diferencial y decidir qué caracterizar. Un caso abierto que el '
210
- + 'paciente NO reportó en este triaje nunca puede aparecer en name_short, en '
211
- + 'recommendation.symptoms_patient_facing, en symptoms ni en targeted_ctcae_terms: nombrarle un '
212
- + 'síntoma que hoy no reportó le hace pensar que nos equivocamos de paciente.';
208
+ const OPEN_CASE_RULE = 'Son contexto de razonamiento, NO evidencia de hoy ni material de tarjeta. Úsalos '
209
+ + 'para ver la evolución, agrupar y afinar el diferencial. Un caso no reportado hoy no va en '
210
+ + 'events_confirmed, no abre ni sostiene un red flag y nunca aparece en name_short, '
211
+ + 'recommendation.symptoms_patient_facing, symptoms ni targeted_ctcae_terms. \'improving\' o días sin '
212
+ + 'evidencia no significan resuelto: si ya se escaló y no hay cierre documentado, anótalo como '
213
+ + 'pendiente del equipo en el resumen interno (summary en el gate, summary_internal en el plan), nunca '
214
+ + 'como tarjeta ni urgencia.';
213
215
 
214
- const ESCALATION_RULE = 'Registran sólo lo que se ENVIÓ al equipo, nunca si el equipo respondió, qué '
215
- + 'indicó, ni si el problema se resolvió. Un motivo sin cambio desde una escalación de hace un día '
216
- + 'rara vez necesita un segundo envío; uno que sigue sin control días después de su escalación '
217
- + 'necesita uno de urgencia MAYOR, y reason_for_escalation debe decir cuál de los dos es.';
216
+ const ESCALATION_RULE = 'Registran sólo lo que se ENVIÓ al equipo: nunca si respondió, qué indicó ni si se '
217
+ + 'resolvió. Son contexto, no evidencia: una escalación pasada nunca crea, sostiene ni sube una urgencia '
218
+ + 'por sí sola. Si el mismo motivo se escaló en los últimos 14 días, no lo reenvíes si hoy mejoró, se negó '
219
+ + 'o no se reportó. Reenvíalo sólo con evidencia de hoy: si subió de grado o hay un signo de alarma nuevo, '
220
+ + 'decide la ruta por sus méritos; si sigue igual, aplica la política de reenvío de tus instrucciones. El '
221
+ + 'tiempo transcurrido nunca justifica por sí solo una ruta mayor. En '
222
+ + 'reason_for_escalation cita la evidencia de hoy y di si es nuevo, empeoramiento o persistencia.';
218
223
 
219
224
  function buildOpenCaseBlock(openCases = []) {
220
225
  if (!openCases.length) return 'Sin casos clínicos abiertos.';
@@ -3,6 +3,13 @@ const { termKey } = require('../../fhir/utils/normalizeUtils');
3
3
  const { matchTerm, entriesOfKeys } = require('../../fhir/helpers/termMatchHelper');
4
4
  const { getCtcaeCatalog } = require('../stores/CtcaeCatalog');
5
5
 
6
+ const CRITICAL_FIELD_GAPS = {
7
+ functional_impact: 'la interferencia del PRO-CTCAE es una escala de 5 puntos, no la limitación de '
8
+ + 'actividades instrumentales/autocuidado que exige la cláusula',
9
+ intensity_nrs: 'la intensidad del PRO-CTCAE es verbal, no una escala 0–10',
10
+ };
11
+ const QUESTIONNAIRE_GAP = 'el cuestionario no pregunta este dato';
12
+
6
13
  function candidateKeys(catalog, term) {
7
14
  const keys = [termKey(term)];
8
15
  const ctcaeV5 = getSymptom(catalog, term)?.ctcae_v5;
@@ -48,8 +55,9 @@ function renderLadder(ladder, grade, { indent = ' ' } = {}) {
48
55
  if (ladder.criticalField) {
49
56
  lines.push(
50
57
  `${indent}Dato que decide el grado de ${ladder.ctcaeTerm} (critical_field): ${ladder.criticalField}. `
51
- + 'Si no está entre las respuestas de arriba, el grado NO está establecido por el cuestionario: '
52
- + 'pide caracterización en vez de asumirlo.',
58
+ + `No capturado por el cuestionario (${CRITICAL_FIELD_GAPS[ladder.criticalField] || QUESTIONNAIRE_GAP}): `
59
+ + 'pide caracterización en vez de asumirlo; el grado es una aproximación del cuestionario; no lo '
60
+ + 'presentes como grado CTCAE ni lo uses para confirmar un umbral.',
53
61
  );
54
62
  }
55
63
  return lines;
@@ -6,7 +6,6 @@ const { isAllowedUrl, redactDirectIdentifiers } = require('../utils/sanitizerUti
6
6
  const { getPatientInformation, updatePatientInformation, logPatientChange } = require('../services/patientService');
7
7
  const { getTriageHistory } = require('../services/triageHistoryService');
8
8
  const { getCarePlanHistory } = require('../services/carePlanHistoryService');
9
- const { getEscalationContext } = require('../services/escalationContextService');
10
9
  const { getPatientTasks, updatePatientTask } = require('../services/patientTaskService');
11
10
  const {
12
11
  getRecommendationCarousels,
@@ -242,25 +241,10 @@ const logPatientChangeController = async (req, res) => {
242
241
  }
243
242
  };
244
243
 
245
- const getPatientEscalationContextController = async (req, res) => {
246
- try {
247
- const context = await getEscalationContext({ code: req.params.code });
248
- res.status(200).json({ success: true, context });
249
- } catch (error) {
250
- logger.error('Error fetching patient escalation context:', {
251
- error: redactDirectIdentifiers(String(error.message || '')),
252
- stack: redactDirectIdentifiers(String(error.stack || '')),
253
- code: redactDirectIdentifiers(String(req.params?.code || '')),
254
- });
255
- res.status(error.statusCode || 500).json({ success: false, error: error.message });
256
- }
257
- };
258
-
259
244
  module.exports = {
260
245
  getPatientInfoController,
261
246
  getPatientTriageInfoController,
262
247
  getPatientCarePlanController,
263
- getPatientEscalationContextController,
264
248
  getPatientTasksController,
265
249
  getPatientRecommendationCarouselsController,
266
250
  getPatientRecommendationCarouselImageController,
@@ -70,7 +70,6 @@ const patientRouteDefinitions = {
70
70
  'GET /:code': 'getPatientInfoController',
71
71
  'GET /triage/:code': 'getPatientTriageInfoController',
72
72
  'GET /careplan/:code': 'getPatientCarePlanController',
73
- 'GET /escalation-context/:code': 'getPatientEscalationContextController',
74
73
  'GET /tasks/:code': 'getPatientTasksController',
75
74
  'PATCH /:code': 'updatePatientController',
76
75
  'PATCH /tasks/:code/:kind/:recordId': 'updatePatientTaskController',
@@ -215,7 +214,6 @@ const builtInControllers = {
215
214
  getPatientInfoController: patientController.getPatientInfoController,
216
215
  getPatientTriageInfoController: patientController.getPatientTriageInfoController,
217
216
  getPatientCarePlanController: patientController.getPatientCarePlanController,
218
- getPatientEscalationContextController: patientController.getPatientEscalationContextController,
219
217
  getPatientTasksController: patientController.getPatientTasksController,
220
218
  getPatientRecommendationCarouselsController: patientController.getPatientRecommendationCarouselsController,
221
219
  getPatientRecommendationCarouselImageController: patientController.getPatientRecommendationCarouselImageController,
@@ -149,7 +149,6 @@ function redactDirectIdentifiers(value) {
149
149
  }
150
150
 
151
151
  module.exports = {
152
- PATIENT_CODE,
153
152
  decodeUnicodeEscapes,
154
153
  decodeUnicodeEscapesDeep,
155
154
  collectStringsDeep,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.45.0-dev.7119",
3
+ "version": "5.45.0-dev.7121",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -1,81 +0,0 @@
1
- const { isoDay } = require('../utils/dateUtils');
2
- const { logger } = require('../utils/logger');
3
- const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
4
- const { withTimeout } = require('../utils/timeoutUtils');
5
- const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
6
- const { assembleHistory } = require('../clinical/services/patientHistoryService');
7
- const { DefaultMemoryManager } = require('../clinical/memory/DefaultMemoryManager');
8
-
9
- const { getCarePlanHistory } = require('./carePlanHistoryService');
10
- const { getPatientInformation } = require('./patientService');
11
- const { getTriageHistory } = require('./triageHistoryService');
12
-
13
- const SECTION_TIMEOUT_MS = 10000;
14
- const TRIAGE_WINDOW_DAYS = 30;
15
- const CARE_PLAN_LIMIT = 5;
16
- const HISTORY_SCOPE = ['closed_cases_90d', 'recurrence_patterns', 'recent_medications', 'patient_reported_procedures'];
17
-
18
- const httpError = (statusCode, message) => Object.assign(new Error(message), { statusCode });
19
-
20
- function sectionReaders(code, now) {
21
- const memoryManager = new DefaultMemoryManager();
22
- const triageStart = isoDay(new Date(now - TRIAGE_WINDOW_DAYS * 86400000).toISOString());
23
- return {
24
- agentContext: () => memoryManager.getClinicalData(code),
25
- conversation: () => memoryManager.buildContext({ thread: { code } }),
26
- triages: () => getTriageHistory({ code, startDate: triageStart }),
27
- carePlan: () => getCarePlanHistory({ code, limit: CARE_PLAN_LIMIT }),
28
- history: () => assembleHistory(code, { scope: HISTORY_SCOPE }),
29
- };
30
- }
31
-
32
- async function getEscalationContext({ code, now = Date.now(), timeoutMs = SECTION_TIMEOUT_MS } = {}) {
33
- const patientCode = ensureWhatsAppFormat(String(code ?? '').trim());
34
- if (!PATIENT_CODE.test(patientCode)) throw httpError(400, 'A valid WhatsApp ID is required');
35
-
36
- const patient = await withTimeout(getPatientInformation(patientCode), timeoutMs, 'patient lookup');
37
- if (!patient) throw httpError(404, 'Patient not found');
38
-
39
- const readers = sectionReaders(patientCode, now);
40
- const names = Object.keys(readers);
41
- const outcomes = await Promise.allSettled(names.map((name) => withTimeout(readers[name](), timeoutMs, name)));
42
-
43
- const context = { patientCode, asOf: new Date(now).toISOString(), degradedSections: [] };
44
- outcomes.forEach((outcome, index) => {
45
- const name = names[index];
46
- if (outcome.status === 'fulfilled' && outcome.value != null) {
47
- context[name] = outcome.value;
48
- return;
49
- }
50
- context[name] = null;
51
- context.degradedSections.push(name);
52
- if (outcome.status === 'rejected') {
53
- logger.error('[escalationContextService] Section reader failed', {
54
- code: patientCode,
55
- section: name,
56
- error: redactDirectIdentifiers(String(outcome.reason?.message ?? outcome.reason)),
57
- stack: redactDirectIdentifiers(String(outcome.reason?.stack ?? '')),
58
- });
59
- }
60
- });
61
-
62
- if (context.conversation) {
63
- context.conversation = context.conversation
64
- .filter((item) => item.type === 'message')
65
- .map(({ role, content }) => ({ role, content }));
66
- }
67
- if (context.triages) {
68
- if (context.triages.pagination?.hasNext) context.degradedSections.push('triages');
69
- context.triages = context.triages.records;
70
- }
71
- if (context.carePlan) {
72
- const { records, pagination = null, currentState = null } = context.carePlan;
73
- const { degradedSections: carePlanDegraded = [], ...state } = currentState || {};
74
- context.carePlan = { records, pagination, currentState: currentState ? state : null };
75
- for (const section of carePlanDegraded) context.degradedSections.push(`carePlan.${section}`);
76
- }
77
-
78
- return context;
79
- }
80
-
81
- module.exports = { getEscalationContext };